You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.5 KiB
C

2 years ago
#include "dht20.h"
#define DHT20_ADDRESS 0x70
// 初始化DHT20
void DHT20_Init(void) {
uint8_t read_buf = 0;
HAL_Delay(500); //等待DHT20上电稳定
HAL_I2C_Master_Receive(&hi2c1, DHT20_ADDRESS, &read_buf, 1, 10);
if ((read_buf & 0x18) != 0x18) {
DHT20_Reset_REG(0x1B);
DHT20_Reset_REG(0x1C);
DHT20_Reset_REG(0x1E);
}
}
// DHT20初始化寄存器
void DHT20_Reset_REG(uint8_t addr) {
uint8_t send_buf[3] = { 0x00 };
send_buf[0] = addr;
HAL_I2C_Master_Transmit(&hi2c1, DHT20_ADDRESS, send_buf, 3, 10);
HAL_Delay(5);
HAL_I2C_Master_Receive(&hi2c1, DHT20_ADDRESS, send_buf, 3, 10);
HAL_Delay(10);
send_buf[0] = 0xB0 | addr;
HAL_I2C_Master_Transmit(&hi2c1, DHT20_ADDRESS, send_buf, 3, 10);
}
// DHT20读温湿度
void DHT20_Get_T_H(float *Temperature, float *Humidity) {
uint8_t cmd_ac[3] = { 0xAC, 0x33, 0x00 };
uint8_t read_buf[6] = { 0 };
int32_t data = 0;
int16_t hum = 0, tmp = 0;
HAL_I2C_Master_Transmit(&hi2c1, DHT20_ADDRESS, cmd_ac, 3, 10);
HAL_Delay(200);
HAL_I2C_Master_Receive(&hi2c1, DHT20_ADDRESS, read_buf, 6, 10);
if ((read_buf[0] & 0x80) != 0x80) {
data = (data | read_buf[1]) << 8;
data = (data | read_buf[2]) << 8;
data = (data | read_buf[3]);
data = data >> 4;
hum = data * 100 * 10 / 1024 / 1024;
data = 0;
data = (data | read_buf[3]) << 8;
data = (data | read_buf[4]) << 8;
data = (data | read_buf[5]);
data = data & 0xFFFFF;
tmp = data * 200 * 10 / 1024 / 1024 - 500;
*Temperature = ((float) tmp) / 10.0f;
*Humidity = ((float) hum) / 10.0f;
}
}