DS18B20溫度感測器利用LCD顯示室內溫度
阿新 • • 發佈:2019-02-12
#include <reg52.h> #include "./delay/delay.h" #include "./lcd/lcd.h" #include "intrins.h" #include "stdio.h" sbit DS = P3^2; sbit led = P3^3; bit ack; void ds18b20_init() { DS = 0; delay_us(200); delay_us(200); DS = 1; delay_us(30); if(DS == 0) { ack = 1; led = 0; } else ack = 0; delay_us(200); } void ds18b20_send_byte(unsigned char byte) { unsigned char i; for(i=0;i<8;i++) { DS = 1; DS = 0; _nop_(); _nop_(); DS = byte && 0x01; byte = byte >> 1; delay_us(30); } delay_us(30); } void ds18b20_write_byte(unsigned char byte) { unsigned char i; for(i=0;i<8;i++) { DS = 1; DS = 0; _nop_(); _nop_(); DS = byte & 0x01; byte = byte >> 1; delay_us(30); } delay_us(30); DS = 1; } bit ds18b20_read_bit() { bit tmp; DS = 1; DS = 0; _nop_(); _nop_(); DS = 1; tmp = DS; delay_us(30); return tmp; } unsigned char ds18b20_read_byte() { unsigned char i,j,k=0; for(i=0;i<8;i++) { j = ds18b20_read_bit(); j = j << 7; k = k >> 1; k = j + k; } return k; } void main() { float temp_f; unsigned char a; unsigned int temp,b; unsigned char disbuf[16]; LCD_Init(); LCD_Clear(); //ds18b20_init(); //ds18b20_send_byte(0x55); while(1) { ds18b20_init(); ds18b20_write_byte(0xcc); ds18b20_write_byte(0x44); delay_ms(20); ds18b20_init(); ds18b20_write_byte(0xcc); ds18b20_write_byte(0xbe); a = ds18b20_read_byte(); b = ds18b20_read_byte(); temp = (b << 8) + a; temp_f = (float)temp * 0.0625; sprintf(disbuf,"temp is %7.3f",temp_f); LCD_Write_String(0,0,disbuf); } }