|
#include<reg51.h>
#include<intrins.h>
#define uchar unsigned char
sbit RS = P1^0;
sbit RW = P1^1;
sbit E = P1^5;
sbit DQ = P3^2;
uchar ds18b20_romA[8];
/******************延時程序**********************/
void delay(unsigned int N)
{
unsigned int i;
for(i=0;i<N;i++);
}
/******************1602忙測**********************/
void check_busy(void)
{
while(1)
{
P0 = 0xFF;
E = 0;
_nop_();
RS = 0;
_nop_();
_nop_();
RW = 1;
_nop_();
_nop_();
E = 1;
_nop_();
_nop_();
_nop_();
_nop_();
if((P0 & 0x80)==0)
{
break;
}
E = 0;
}
}
/******************1602寫命令**********************/
void write_command(uchar tempdata)
{
E = 0;
_nop_();
_nop_();
RS = 0;
_nop_();
_nop_();
RW = 0;
P0 = tempdata;
_nop_();
_nop_();
E = 1;
_nop_();
_nop_();
E = 0;
_nop_();
check_busy();
}
/******************1602寫數據**********************/
void write_data(uchar tempdata)
{
E = 0;
_nop_();
_nop_();
RS = 1;
_nop_();
_nop_();
RW = 0;
P0 = tempdata;
_nop_();
_nop_();
E = 1;
_nop_();
_nop_();
E = 0;
_nop_();
check_busy();
}
/******************1602初始化**********************/
void init_lcd1602()
{
write_command(0x01);
write_command(0x38);
write_command(0x0C);
write_command(0x06);
}
/******************1820初始化**********************/
bit resetpulse(void)
{
DQ = 0;
delay(40); //500us
DQ = 1;
delay(4); //60us
return(DQ);
}
void ds18b20_init(void)
{
while(1)
{
if(!resetpulse())
{
DQ = 1;
delay(40);
break;
}
else
resetpulse();
}
}
/******************讀1820一位**********************/
uchar read_bit(void)
{
DQ = 0;
_nop_();
_nop_();
DQ = 1;
delay(2);
return(DQ);
}
/******************讀1820一個字節**********************/
uchar read_byte(void)
{
uchar i,m,receive_data;
m = 1;
receive_data = 0;
for(i=0;i<8;i++)
{
if(read_bit())
{
receive_data = receive_data + (m<<i);
}
delay(7);
}
return(receive_data);
}
/******************向1820寫一位**********************/
void write_bit(uchar bitval)
{
DQ = 0;
if(bitval == 1)
DQ = 1;
delay(5);
DQ = 1;
}
/******************向1820寫一字節命令**********************/
void write_byte(uchar val)
{
uchar i,temp;
for(i=0;i<8;i++)
{
temp = val>>i;
temp = temp & 0x01;
write_bit(temp);
delay(5);
}
}
uchar *read_rom(void)
{
uchar rom[8],i;
ds18b20_init();
write_byte(0x33);
for(i=8;i>0;i--)
{
rom[i-1] = read_byte();
}
return &rom[0];
}
/******************將64位序列號在lcd顯示出來**********************/
void print_char(uchar a)
{
if(a>=0&&a<=9)
write_data(a + 0x30);
else if(a>=0x0A&&a<=0x0F)
write_data(a + 0x37);
}
void main(void)
{
uchar *ds18b20_rom;
init_lcd1602();
while(1)
{
uchar i;
ds18b20_rom = read_rom(); //讀序列號
write_command(0x80);
for(i=0;i<8;i++)
{
ds18b20_romA[i] = *ds18b20_rom;
ds18b20_rom++;
}
write_command(0x80);
for(i=0;i<8;i++) //顯示序列號
{
print_char(ds18b20_romA[i]/16);
print_char(ds18b20_romA[i]%16);
}
}
}
|
|