#include "STC8xxxx.H" //头文件
#include "intrins.h"
#define FOSC 11059200UL
#define BRT (65536 - FOSC / 115200 / 4)
#define ADCTIM (*(unsigned char volatile xdata *)0xfea8)
sbit led = P5^5;
int *BGV; //内部1.19V参考信号源值存放在idata中
//idata的EFH地址存放高字节
//idata的F0H地址存放低字节
//电压单位为毫伏(mV)
bit busy;
void UartIsr() interrupt 4
{
if (TI)
{
TI = 0;
busy = 0;
}
if (RI)
{
RI = 0;
}
}
void UartInit()
{
SCON = 0x50;
TMOD = 0x00;
TL1 = BRT;
TH1 = BRT >> 8;
TR1 = 1;
AUXR = 0x40;
busy = 0;
}
void UartSend(char dat)
{
while (busy);
busy = 1;
SBUF = dat;
}
void ADCInit()
{
P_SW2 |= 0x80;
ADCTIM = 0x3f; //设置ADC内部时序
P_SW2 &= 0x7f;
ADCCFG = 0x2f; //设置ADC时钟为系统时钟/2/16/16
ADC_CONTR = 0x8f; //使能ADC模块,并选择第15通道
}
int ADCRead()
{
int res;
ADC_CONTR |= 0x40; //启动AD转换
_nop_();
_nop_();
while (!(ADC_CONTR & 0x20)); //查询ADC完成标志
ADC_CONTR &= ~0x20; //清完成标志
res = (ADC_RES << 8) | ADC_RESL; //读取ADC结果
return res;
}
void main()
{
int res;
int vcc;
int i;
P5M0 = 0x00;
P5M1 = 0x00;
BGV = (int idata *)0xef;
ADCInit(); //ADC初始化
UartInit(); //串口初始化
ES = 1;
EA = 1;
// ADCRead();
// ADCRead(); //前两个数据建议丢弃
res = 0;
for (i=0; i<8; i++)
{
res += ADCRead(); //读取8次数据
}
res >>= 3; //取平均值
vcc = (int)(1024L * *BGV / res); //(10位ADC算法)计算VREF管脚电压,即电池电压
//printf(vcc);
// vcc = (int)(4096L * *BGV / res); //(12位ADC算法)计算VREF管脚电压,即电池电压
//注意,此电压的单位为毫伏(mV)
UartSend(vcc >> 8); //输出电压值到串口,显示为“0D”
UartSend(vcc); //输出电压值到串口,显示为显示为“14”
//将16进制“0D 14”转换成10进制是“3348”,请问如何在C语言程序中,将“vcc >> 8”和“vcc”相加等于“3348”?谢谢!
//我想要实现如下的效果,当电压高于3200毫伏时亮灯
if (vcc > 3200){
led = 0; //LED灯亮起,电量提醒
}
while (1);
}
|