单片机小white。..
求。路。大 STC8H单片机打印ADC采集电压输出为0
#include "reg51.h"
#include "intrins.h"
#include
#define FOSC 11059200UL
#define BRT (65536 - FOSC / 115200 / 4)
sfr AUXR = 0x8e;
sfr ADC_CONTR = 0xbc;
sfr ADC_RES = 0xbd;
sfr ADC_RESL = 0xbe;
sfr ADCCFG = 0xde;
sfr P_SW2 = 0xba;
#define ADCTIM (*(unsigned char volatile xdata *)0xfea8)
sfr P0M1 = 0x93;
sfr P0M0 = 0x94;
sfr P1M1 = 0x91;
sfr P1M0 = 0x92;
sfr P2M1 = 0x95;
sfr P2M0 = 0x96;
sfr P3M1 = 0xb1;
sfr P3M0 = 0xb2;
sfr P4M1 = 0xb3;
sfr P4M0 = 0xb4;
sfr P5M1 = 0xc9;
sfr P5M0 = 0xca;
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;
ADCTIM = 0X2a;
ADCCFG = 0x00; //设置ADC时钟为系统时钟/2/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 ADC()
{
int res;
int vcc;
int i;
P0M0 = 0x00;
P0M1 = 0x00;
P1M0 = 0x00;
P1M1 = 0x00;
P2M0 = 0x00;
P2M1 = 0x00;
P3M0 = 0x00;
P3M1 = 0x00;
P4M0 = 0x00;
P4M1 = 0x00;
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管脚电压,即电池电压
vcc = (int)(4096L * *BGV / res); //(12位ADC算法)计算VREF管脚电压,即电池电压
//注意,此电压的单位为毫伏(mV)
UartSend(vcc >> 8); //输出电压值到串口
UartSend(vcc);
}
}
#include "reg51.h"
#include "intrins.h"
#include
#include
void main(){
UartInit();
ADC();
while(1)
{
printf("%d\r\n",res);
}
}
#ifndef __ADC8H_H__
#define __ADC8H_H__
UartInit();
ADC();
int res;
全局变量定义的res,实际上从来没被赋值过,当然是0.
adc函数里也有res,和全局的res同名,但函数里重新定义了res,所以这res和全局的res不是一个。
这个代码整体很乱,感觉像是几个例程拼成的,没有组合好。
其它就不说了,建议改一下main函数
void main(){
int adcvalue;
UartInit();
ADC();
while(1)
{
adcvalue = ADCRead();
printf("%d\r\n",adcvalue);
}
}