51驱动DHT12
时间: 2023-07-22 10:13:05 浏览: 90
以下是一个使用51单片机驱动DHT12的简单示例代码:
```
#include <reg52.h>
#include <intrins.h>
#include <stdio.h>
#include <stdlib.h>
#define DHT12_I2C_ADDRESS 0x5C
typedef unsigned char uint8_t;
typedef unsigned int uint16_t;
sbit SDA=P1^1;
sbit SCL=P1^0;
void delay_us(unsigned int us)
{
while(us--)
{
_nop_();
}
}
void I2C_start()
{
SDA = 1;
SCL = 1;
delay_us(5);
SDA = 0;
delay_us(5);
SCL = 0;
}
void I2C_stop()
{
SDA = 0;
SCL = 1;
delay_us(5);
SDA = 1;
delay_us(5);
}
uint8_t I2C_write_byte(uint8_t dat)
{
uint8_t i, ack;
for(i=0; i<8; i++)
{
SDA = (dat & 0x80) ? 1 : 0;
dat <<= 1;
delay_us(5);
SCL = 1;
delay_us(5);
SCL = 0;
}
SDA = 1;
delay_us(5);
SCL = 1;
ack = SDA;
delay_us(5);
SCL = 0;
return ack;
}
uint8_t I2C_read_byte()
{
uint8_t i, dat = 0;
SDA = 1;
for(i=0; i<8; i++)
{
delay_us(5);
SCL = 1;
dat <<= 1;
dat |= SDA;
delay_us(5);
SCL = 0;
}
return dat;
}
void DHT12_read_data(uint8_t *data)
{
uint8_t i;
I2C_start();
I2C_write_byte(DHT12_I2C_ADDRESS << 1);
I2C_write_byte(0x00);
I2C_start();
I2C_write_byte((DHT12_I2C_ADDRESS << 1) + 1);
for(i=0; i<5; i++)
{
data[i] = I2C_read_byte();
}
I2C_stop();
}
void main()
{
uint8_t data[5];
uint16_t temperature, humidity;
while(1)
{
DHT12_read_data(data);
temperature = (data[2] << 8) | data[3];
temperature /= 10;
humidity = (data[0] << 8) | data[1];
humidity /= 10;
printf("Temperature: %dC, Humidity: %d%%\n", temperature, humidity);
delay_ms(2000);
}
}
```
这个示例代码使用了51单片机的GPIO来模拟I2C总线,读取DHT12传感器的温度和湿度值,并通过串口输出。请将DHT12连接到51单片机的SDA和SCL引脚上,然后下载代码到单片机上进行测试。
阅读全文