#include <reg52.h>
#include <intrins.h>
#define uint unsigned int
#define uchar unsigned char
#define delay4us() {_nop_();_nop_();_nop_();_nop_();}
#define NOP _nop_()
sbit AD_CS =P1^0;
sbit SCK=P1^1;
sbit DO =P1^2;
sbit DI =P1^2;
sbit RS = P2^0;
sbit RW = P2^1;
sbit E = P2^2;
unsigned char adval;
uchar Display_Buffer[] = "0.00V";
uchar code Line1[] = "Current Voltage:";
uchar adc0832(uchar channel) //读ADC0832函数,采集并返回
{
uchar i=0;
uchar j;
uint dat2=0;
uchar ndat=0;
if(channel==0)channel=2;
if(channel==1)channel=3;
AD_CS=0;NOP; NOP; //拉低CS端,AD片选
DI=1;NOP; NOP; //在第一个脉冲下降之前 DI 必须是高电平,表示启始信号
SCK=1;NOP; NOP;
SCK=0;NOP; NOP;
SCK=1;
DI=channel&0x1;NOP;NOP;//在第二和第三个脉冲下降之前 DI 输入两位表示通道
SCK=0;NOP; NOP;
SCK=1;
DI=(channel>>1)&0x1;NOP; NOP;
SCK=0; //写命令完成,DI失去输入作用
DI=1;NOP;NOP;
dat2=0;
for(i=0;i<8;i++) //读出8字节数据
{
dat2|=DO;
SCK=1;NOP; NOP;
SCK=0;NOP; NOP;
dat2<<=1;
if(i==7)dat2|=DO;
}
for(i=0;i<8;i++)
{
j=0;
j=j|DO;
SCK=1;NOP; NOP;
SCK=0;NOP; NOP;
j=j<<7;
ndat=ndat|j;
if(i<7)ndat>>=1;
}
AD_CS=1;
SCK=0;
DO=1;
dat2<<=8;
dat2|=ndat;
return(dat2); //返回数据
}
void DelayMS(uint ms)
{
uchar i;
while(ms--)
{
for(i=0;i<120;i++);
}
}
uchar Read_LCD_State()
{
uchar state;
RS=0;RW=1;E=1;DelayMS(1);
state=P0;
E= 0;DelayMS(1);
return state;
}
void LCD_Busy_Wait()
{
while((Read_LCD_State()&0x80)==0x80);
DelayMS(5);
}
void LCD_Write_Command(uchar cmd)
{
LCD_Busy_Wait();
RS = 0;
RW = 0;
E = 0;
_nop_();
_nop_();
P0 = cmd;
delay4us();
E = 1;
delay4us();
E = 0;
}
void Set_LCD_Pos(uchar pos)
{
LCD_Write_Command(pos | 0x80);
}
void LCD_Write_Data(uchar dat)
{
LCD_Busy_Wait();
RS = 1;
RW = 0;
E = 0;
P0 = dat;
delay4us();
E = 1;
delay4us();
E = 0;
}
void LCD_Initialise()
{
LCD_Write_Command(0x38); DelayMS(1);
LCD_Write_Command(0x0c); DelayMS(1);
LCD_Write_Command(0x06); DelayMS(1);
LCD_Write_Command(0x01); DelayMS(1);
}
void Display_LCD_String(uchar p,uchar *s)
{
uchar i;
Set_LCD_Pos(p);
for(i=0;i<16;i++)
{
LCD_Write_Data(s[i]);
DelayMS(1);
}
}
void write_sfm(uchar add,uchar num)//分秒函数
{
LCD_Write_Command(0x80+0x40+add); //第行数据指针位置调整
LCD_Write_Data(0x30+num);
}
void main()
{
uchar c;
uint bai,sh,ge, d;
LCD_Initialise();
DelayMS(10);
Display_LCD_String(0x00,Line1);
Display_LCD_String(0x46,Display_Buffer);
while(1)
{
c=adc0832(0);
d=c*1.0*500/255 ;
bai=d/100 ; //分离出百位
sh=d/10; //分离出十位
ge=d; //分离出个位
write_sfm(6,bai);
write_sfm(8,sh);
write_sfm(9,ge);
}
}
|