#include <STC8h.H>
#include <stdio.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit RS = P2^4; //定义LCD1602端口
sbit RW = P2^5;
sbit EN = P2^6;
#define DataPort P0
#define RS_CLR RS=0
#define RS_SET RS=1
#define RW_CLR RW=0
#define RW_SET RW=1
#define EN_CLR EN=0
#define EN_SET EN=1
void delay(unsigned int ms) //@11.0592MHz
{
unsigned char i, j;
while(ms--)
{
i = 15;
j = 90;
do
{
while (--j);
} while (--i);
}}
bit LCD_Check_Busy(void)
{
DataPort= 0xFF;
RS_CLR;
RW_SET;
EN_CLR;
delay(1);
EN_SET;
delay(1);
return (bit)(DataPort & 0x80);
}
void LCD_Write_Com(unsigned char com)
{
while(LCD_Check_Busy()); //忙则等待
RS_CLR;
RW_CLR;
EN_SET;
DataPort= com;
delay(1);
EN_CLR;
delay(1);
}
void LCD_Write_Data(unsigned char Data)
{
while(LCD_Check_Busy()); //忙则等待
RS_SET;
RW_CLR;
EN_SET;
DataPort= Data;
delay(1);
EN_CLR;
delay(1);
}
void LCD_Clear(void)
{
LCD_Write_Com(0x01);
delay(5);
}
void LCD_Write_String(unsigned char x,unsigned char y,unsigned char *s)
{
if (y == 0)
{
LCD_Write_Com(0x80 + x); //表示第一行
}
else
{
LCD_Write_Com(0xC0 + x); //表示第二行
}
while ((*s)!='\0')
{
LCD_Write_Data( *s);
s ++;
}
}
void LCD_Init(void)
{
LCD_Write_Com(0x38); /*显示模式设置*/
delay(5);
LCD_Write_Com(0x38);
delay(5);
LCD_Write_Com(0x38);
delay(5);
LCD_Write_Com(0x38);
LCD_Write_Com(0x08); /*显示关闭*/
LCD_Write_Com(0x01); /*显示清屏*/
LCD_Write_Com(0x06); /*显示光标移动设置*/
delay(5);
LCD_Write_Com(0x0C); /*显示开及光标设置*/
}
void DisplayVoltage(float voltage)
{
unsigned char str[16];
sprintf(str,"Voltage: %.2fV",voltage);
LCD_Write_Com(0x80);
LCD_Write_String(0,0,str);
}
void ADC_Init(void)
{
ADC_CONTR |= 0x80; //AD上电
ADCTIM = 0x3f; //设置ADC内部时序
ADC_CONTR &= 0x7f; //AD断电
ADCCFG = 0x2f; //设置ADC时钟为系统时钟/2/16,12位结果右对齐
ADC_CONTR = 0x80; //使能ADC模块上电
delay(4);
ADC_CONTR |= 0x01; //选P01作为AD输入
}
uint ADC_Read()
{
ADC_CONTR |= 0x40; //启动AD转换
delay(2);
while ((ADC_CONTR & 0x20)==0); //查询ADC完成标志
ADC_CONTR &= ~0x20; //清完成标志
return ADC_RES << 8 | ADC_RESL; //返回12位ADC结果
}
void main(void)
{
P0M0=0;
P0M1=0;
P2M0=0;
P2M1=0;
LCD_Init();
LCD_Clear();//清屏
ADC_Init();
delay(3);
while (1)
{
unsigned int rawVoltage = ADC_Read();
float voltage = (rawVoltage * 5.0) / 4095; // 假设参考电压是5V
DisplayVoltage(voltage);
delay(900);
}
}
在测量时有点电压(不管是0.5v还是3.3v)就直接显示5V,不进行测量时读数在0~5v之间一直变化。程序有什么错误?指教指教!
|