#include <reg51.h>
#define uchar unsigned char
#define uint unsigned int
sbit rw = P3^6;
sbit RS = P3^5;
sbit ds = P2^2;
sbit LCDEN = P3^4;
sbit beep=P2^3;
uchar table1[10];
uchar code table[] = " test temp:";
int i,tmp;
float value,tempss;
void delayMs(uint a) //延时
{
uint i, j;
for(i = a; i > 0; i--)
for(j = 100; j > 0; j--);
}
void writeComm(uchar comm)
{
RS = 0;
P0 = comm;
delayMs(5);
LCDEN = 1;
delayMs(5);
LCDEN = 0;
}
void writeData(uchar dat)
{
RS = 1;
P0 = dat;
delayMs(1);
LCDEN = 1;
delayMs(1);
LCDEN = 0;
}
void init()
{
rw = 0;
writeComm(0x38);
writeComm(0x0c);
writeComm(0x06);
writeComm(0x01);
}
void writeString(uchar * str, uchar length)
{
uchar i;
for(i = 0; i < length; i++)
{
writeData(str[i]);
}
}
void inits()
{
TMOD=0X20;//T1工作在方式2及自动重装
TH1=0XFD;//波特率9600
TL1=0XFD;
TR1=1;
SM0=0;
SM1=1;
REN=1;
ES=1; //启动串口中断
EA=1;
}
void displays()
{
tempss=(table1[0]-48)*1000+(table1[1]-48)*100;
writeComm(0x80);
writeString(table,11);
writeComm(0x80+12);
for(i=0;i<2;i++)
{
writeData(table1[i]);
delayMs(100);
}
}
//ds18b20
void dsInit()
{
unsigned int i;
ds = 0;
i = 100;
while(i>0)
i--;
ds = 1;
i = 4;
while(i>0)
i--;
}
bit readBit()
{
unsigned int i;
bit b;
ds = 0;
i++;
ds = 1;
i++;
i++;
b = ds;
i = 8;
while(i>0)
i--;
return b;
}
unsigned char readByte()
{
unsigned int i;
unsigned char j, dat;
dat = 0;
for(i=0; i<8; i++)
{
j = readBit();
dat = (j << 7) | (dat >> 1);
}
return dat;
}
void writeByte(unsigned char dat)
{
int i,j;
for(j=0;j<8;j++)
{
ds=0;
i++;
ds=dat&0x01;
i=6;
while(i--);
ds=1;
dat>>=1;
}
}
void sendChangeCmd()//温度转化命令
{
dsInit();
delayMs(1);
writeByte(0xcc);
writeByte(0x44);
}
void sendReadCmd() //读取温度
{
dsInit();
delayMs(1);
writeByte(0xcc);
writeByte(0xbe);
}
int getTmpValue()
{
unsigned int tmpvalue;
float t;
unsigned char low, high;
sendReadCmd();
low = readByte();
high = readByte();
tmpvalue = high;
tmpvalue <<= 8;
tmpvalue |= low;
value = tmpvalue;
t = value * 0.0625;
value = t * 100 + (value > 0 ? 0.5 : -0.5); //大于0加0.5, 小于0减0.5
return value;
}
void display()
{
unsigned char count;
unsigned char datas[] = {0, 0, 0, 0, 0};
tmp =getTmpValue();
datas[0] = tmp / 10000;
datas[1] = tmp % 10000 / 1000;
datas[2] = tmp % 1000 / 100;
datas[3] = tmp % 100 / 10;
datas[4] = tmp % 10;
writeComm(0xc0+3);
if(tmp< 0)
{
writeString("- ", 1);
}
else
{
writeString("+ ", 1);
}
for(count = 1; count < 5; count++)
{
writeData('0'+datas[count]);
if(count == 2)
{
writeData('.');
}
}
}
void main()
{
init();
while(1)
{
inits();
displays();
sendChangeCmd();//发送温度转化命令
delayMs(750); //温度转换时间需要750ms以上
writeComm(0xc0);
display();
if(tempss>tmp)
{
beep=0;
P1=0X00;
}
else
{
beep=1;
P1=0Xff;
}
}
}
void uate() interrupt 4
{
ES=0; //先关闭串口中断防止出错
for(i=0;i<2;i++)
{
while(!RI);
RI=0; //发送标志位清零
table1[i]=SBUF;
}
ES=1;//启动串口中断,继续发送
}
|