CHƯƠNG 4: THIẾT KẾ PHẦN MỀM 4.1 Code LCD1602 giao tiếp với AT89S
4.2. Code giao tiếp cảm biến DHT22 với AT89S52 hiển thị trên LCD
#include <REGX51.H> #include <stdio.h>
#include "..\lib\LCD1602.h" // Thu vien LCD1602
#define DHT22 P3_0 // Chan Data cua DHT22 //Khai bao bien:
int I_RH,D_RH,I_Temp,D_Temp,CheckSum;
void delay20ms() /* Ham tre 20ms su dung Timer0, thach anh 11.0592MHz */
{
TMOD = 0x01; /* Timer0 che do 1 */
TH0 = 0xB8; /* Gia tri TH0 */
TL0 = 0x0C; /* Gia tri TL0 */
TR0 = 1; /* Bat dau timer0 */
TF0 = 0; /* Dat lai co tran TF0=0 */
}
void delay30us() /* Ham tre 30us su dung Timer0, thach anh 11.0592MHz */
{
TMOD = 0x01; /* Timer0 che do 1 */
TH0 = 0xFF; /* Gia tri TH0 */
TL0 = 0xF1; /* Gia tri TL0 */
TR0 = 1; /* Bat dau timer0 */
while(TF0 == 0); /* Doi den khi TF0=1*/
TR0 = 0; /* Dung timer0 */
TF0 = 0; /* Dat lai co tran TF0=0 */
}
void Request() /* VDK gui lenh bat dau */
{
DHT22 = 0; delay20ms(); DHT22 = 1; }
void Response() /* Tin hieu phan hoi tu DHT22 */
{
while(DHT22==1); while(DHT22==0); while(DHT22==1); }
int Receive_data() /* Nhan du lieu la gia tri Do Am - Nhiet Do */
int i,dat=0;
for (i=0; i<8; i++) {
while(DHT22==0); /* Doi den khi DHT22 len muc 1 */
delay30us(); /* Sau 30us, neu DHT22 o muc 1 thi do la bit 1, neu o muc 0 thi do la bit 0 */
if(DHT22 == 1) // Doc duoc bit 1
dat = (dat<<1)|(0x01);
else // Doc duoc bit 0
dat = (dat<<1);
while(DHT22==1); /* Doi den khi DHT22 xuong muc 0 */
}
return dat; }
void main() // Chuong trinh chinh
{
unsigned char str[20];
LCD_Init(); /* Goi ham khoi tao LCD */
LCD_SetCursor(0,2); /* Dua con tro den hang 1 cot 3 */
LCD_Print("Nhom 2 do an 1");
LCD_SetCursor(1,3); /* Dua con tro den hang 2 cot 4 */
lCD_Print("Test DHT22"); delay_ms(3000);
LCD_Clear();
while(1) {
Request(); /* Goi ham VDK gui lenh bat dau*/
Response(); /* Goi ham DHT22 phan hoi */
I_RH = Receive_data(); /* 8 bit dau tien I_RH */
D_RH = Receive_data(); /* 8 bit tiep theo D_RH */
I_Temp = Receive_data(); /* 8 bit tiep theo I_Temp */
D_Temp = Receive_data(); /* 8 bit tiep theo D_Temp */
CheckSum = Receive_data(); /* 8 bit tiep theo CheckSum */
if ((I_RH + D_RH + I_Temp + D_Temp) != CheckSum) // kiem tra tong CheckSum
{
LCD_SetCursor(0,0); /* Dua con tro den hang 1 cot 1*/
LCD_Print("Error"); }
else {
sprint (str,"Hum = %d.%d",(I_RH*256+D_RH)/10,(I_RH*256+D_RH)%10);
// Chuyen gia tri sang xau ki tu str
LCD_SetCursor(0,0); // Con tro o hang 1, cot 1
//Nếu muốn in ra nhiệt độ và checksum /sprintf(str,"Tem = %d.%d",(I_Temp*256+D_Temp)/10,(I_Temp*256+D_Temp) %10); /LCD_SetCursor(1,0); /LCD_Print(str); /sprintf(str,"%d ",CheckSum); /LCD_SetCursor(1,13); /LCD_Print(str); }
delay20ms(); // dung lai trong 20ms
} }