#include <REG51.H>
#include <intrins.h>
#define uint unsigned int
#define uchar unsigned char
uint num;
sbit lcd_rs=P3^5;
sbit lcd_rw=P3^6;
sbit lcd_en=P3^7; //液晶控制端
uchar temp;
float result;
sbit out=P3^4;
sbit DS=P3^0;
uchar code name[]="WangYeSheng-VOLT";
void delay(unsigned int m)
//延時函數
{
while(m--);
}
void read1602()
//忙檢測
{
uchar i;
i=254;
P1=0xff;
lcd_rs=0;
lcd_rw=1;
lcd_en=1;
while((i--)&&(P2&0x80));//若一段時間以后仍低,不忙
lcd_en=0;
}
void write1602(uchar wdata,bit rw)//向LCD1602寫數據(rw=1)或者命令(rw=0)
{
read1602();
P1=wdata;
lcd_rs=rw;
lcd_rw=0;
lcd_en=1;
delay(1);
lcd_en=0;
}
void lcd_init()
//LCD1602液晶的初始化
{
delay(1500);
write1602(0x38,0);
delay(500);
write1602(0x38,0);
delay(500);
write1602(0x38,0);
write1602(0x38,0);
write1602(0x0c,0);
write1602(0x06,0);
write1602(0x01,0);
//清屏
}
void lcd_printf(uchar *str)//顯示字符串
{
while(*str!='\0')
{
write1602(*str,1);
//寫入數據
str++;
}
}
void lcd_moveto(uchar x,uchar y)//指定顯示的行列坐標
{
if(x==0)
write1602(0x80|y,0);
if(x==1)
write1602(0xc0|y,0);
}
/*************DS18B20溫度讀取模塊*************/
void tmpDelay(int num)//延時函數
{
while(num--) ;
}
void Init_DS18B20()//初始化ds1820
{
unsigned char x=0;
DS = 1; //DS復位
tmpDelay(8); //稍做延時
DS = 0; //單片機將DS拉低
tmpDelay(80); //精確延時 大于 480us
DS = 1; //拉高總線
tmpDelay(14);
x=DS; //稍做延時后 如果x=0則初始化成功 x=1則初始化失敗
tmpDelay(20);
}
unsigned char ReadOneChar()//讀一個字節(jié)
{
unsigned char i=0;
unsigned char dat = 0;
for (i=8;i>0;i--)
{
DS = 0; // 給脈沖信號
dat>>=1;
DS = 1; // 給脈沖信號
if(DS)
dat|=0x80;
tmpDelay(4);
}
return(dat);
}
void WriteOneChar(unsigned char dat)//寫一個字節(jié)
{
unsigned char i=0;
for (i=8; i>0; i--)
{
DS = 0;
DS = dat&0x01;
tmpDelay(5);
DS = 1;
dat>>=1;
}
}
unsigned int Readtemp()//讀取溫度
{
unsigned char a=0;
unsigned char b=0;
unsigned int t=0;
float tt=0;
Init_DS18B20();
WriteOneChar(0xCC); // 跳過讀序號列號的操作
WriteOneChar(0x44); // 啟動溫度轉換
Init_DS18B20();
WriteOneChar(0xCC); //跳過讀序號列號的操作
WriteOneChar(0xBE); //讀取溫度寄存器
a=ReadOneChar(); //連續(xù)讀兩個字節(jié)數據 //讀低8位
b=ReadOneChar(); //讀高8位
t=b;
t<<=8;
t=t|a; //兩字節(jié)合成一個整型變量。
tt=t*0.0625; //得到真實十進制溫度值,因為DS18B20可以精確到0.0625度,所以讀回數據的最低位代表的是0.0625度
t= tt*10+0.5; //放大十倍,這樣做的目的將小數點后第一位也轉換為可顯示數字,同時進行一個四舍五入操作。
return(t);
}
void display1()
{
//定義的時候用uchar宏定義就會出錯
uint shi,ge,xiaoshu; //這里的num,shi,ge,xiaoshu 必須用uint無符號整數來表示,用uchar字符型則顯示錯誤
num=Readtemp();
shi=num/100;
ge=num/10%10;
xiaoshu=num%10;
lcd_moveto(1,4);
temp=(uchar)(shi);//取得電壓值的整數部分
write1602(temp+48,1);//顯示電壓值的整數部分
temp=(uchar)(ge);//取得電壓值的整數部分
write1602(temp+48,1);//顯示電壓值的整數部分
write1602('.',1);//顯示小數點
temp=(uchar)(xiaoshu);//取得電壓值的整數部分
write1602(temp+48,1);//顯示電壓值的整數部分
}
void main()//測試用MAIN函數
{
lcd_init();
delay(50000);
while(1)
{
display1();
if(num<500){out=1;}
else if (num>500){out=0;}
}
}
|