- 打卡等级:初来乍到
- 打卡总天数:3
- 最近打卡:2025-07-17 07:52:50
已绑定手机
新手上路
- 积分
- 29
|
根据AI8G1K08A-8pin的数据手册,可以通过15通道先读取供电电压,然后使用计算公式计算外部电压值。
在实际使用时,获取供电电压5v,并进行串口输出。但在测取外部电压时,出现了问题。
代码如下:
#include "stc8.h"
#include "intrins.h"
#include "delay.h"
#include "stdio.h"
#include "string.h"
#define FOSC 11059200UL
#define BRT (65536 - FOSC / 115200 / 4)
//sbit KEY1 = P3^2;
bit busy; //等待上一个数据发送完
char wptr;
char rptr;
char buffer[16];
int *BGV;
void UartIsr() interrupt 4
{
if (TI) //发送完之后响应
{
TI = 0;
busy = 0;
}
if (RI) //接受完之后响应
{
RI = 0;
buffer[wptr++] = SBUF;
wptr &= 0x0f;
}
}
//stc8-8pin 只有串口1
//stc8-20pin 有2个串口
//stc8-48pin 有2~4个串口 芯片型号s2 s4
// from datasheet
// 14.7.2 串口 1 使用定时器 1(模式 0)做波特率发生器
void UartInit()
{
SCON = 0x50;
TMOD = 0x00;
TL1 = BRT;
TH1 = BRT >> 8;
TR1 = 1;
AUXR = 0x40;//0x41为使用定时器2(使用哪个定时器都不影响正常工作)
wptr = 0x00;
rptr = 0x00;
busy = 0;
}
void UartSend(char dat)
{
while (busy); //等待上一个数据发送完
busy = 1;
SBUF = dat;
}
void UartSendStr(char *p)
{
while (*p)
{
UartSend(*p++);
}
}
void msg_send(char msg[])
{//发送字符串函数
int i=0;
while(msg)
{
SBUF=msg;
while(!TI);
TI=0;
i++;
}
}
void ADCInit()
{
P_SW2 |= 0x80;//访问特殊功能寄存器
ADCTIM = 0x3f;//设置ADC内部时序
P_SW2 &= 0x7f;//关闭
ADCCFG = 0x2f;//数据右对齐,设置工作频率
ADC_CONTR = 0x83; //P3^3
//开启,设置P1^0为通道,0x01为P1^1,同理到P1^7//0x8f为内部参考电压
}
//测取内部电压1.19V,基准电压
void ADCInitInside()
{
P_SW2 |= 0x80;//访问特殊功能寄存器
ADCTIM = 0x3f;//设置ADC内部时序
P_SW2 &= 0x7f;//关闭
ADCCFG = 0x2f;//数据右对齐,设置工作频率
ADC_CONTR = 0x8f;//开启,设置P1^0为通道0x01为P1^1,同理到P1^7//0x8f为内部参考电压
}
int ADCRead()
{
int res;
ADC_CONTR |= 0x40;//启动AD转换
_nop_();
_nop_();
while (!(ADC_CONTR & 0x20)); //检测到转换结束
ADC_CONTR &= ~0x20;//清标志位
res = (ADC_RES << 8) | ADC_RESL; //送数据
return res;
}
//Vx = BGV/resbg*resx;
void main()
{
int Vref_res=0; //供电电压ad值
int res=0; //外部电压ad值
int i=0;
int vcc=0; //参考电压值
char disp[15];
int V; //外部电压值
P3M0 = 0x00;
P3M1 = 0x00;
P5M0 = 0x00;
P5M1 = 0x00;
BGV = (int idata *)0xef ;
UartInit();
ADCInitInside();
ES = 1;
EA = 1;
while (1)
{
// ADCInitInside(); //供电电压 测取
ADC_CONTR = 0x8f;
Vref_res = 0;
for (i = 0; i < 8; i++) // 平均
{
Vref_res += ADCRead();
}
Vref_res >>= 3; // 除以8
vcc = (int)(1024L * *BGV / Vref_res);
sprintf(disp,"vcc:%d mv\r\n",vcc);//以10进制转化为字符串
msg_send(disp);
delay_ms(500);
ADC_CONTR = 0x82; //p55
// ADCInit(); //测取外部电压
res = 0;
for (i = 0; i < 8; i++) // 平均
{
res += ADCRead();
}
res >>= 3; // 除以8
V = vcc/Vref_res*res;
sprintf(disp,"外部电压:%d mv\r\n",V);//以10进制转化为字符串
msg_send(disp);
delay_ms(500);
}
}
|
-
串口打印图
|