示例代码(以Arduino为例)
以下是一个使用Arduino的示例代码,演示如何通过I2C读取DHT12传感器的数据:
cpp
#include <Wire.h>
#define DHT12_ADDRESS 0x5C
void setup() {
Serial.begin(9600);
Wire.begin();
}
void loop() {
uint8_t data[5];
// Start I2C transmission
Wire.beginTransmission(DHT12_ADDRESS);
Wire.write(0x00); // Send the command to read from register 0x00
Wire.endTransmission();
// Request 5 bytes of data from DHT12
Wire.requestFrom(DHT12_ADDRESS, 5);
if (Wire.available() == 5) {
for (int i = 0; i < 5; i++) {
data[i] = Wire.read();
}
// Check the checksum
if (data[4] == (data[0] + data[1] + data[2] + data[3])) {
float humidity = data[0] + data[1] * 0.1;
float temperature = data[2] + (data[3] & 0x7F) * 0.1;
if (data[3] & 0x80) temperature = -temperature;
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" *C");
} else {
Serial.println("Checksum error");
}
} else {
Serial.println("Failed to read from DHT12");
}
delay(2000); // Wait for 2 seconds before the next read
}
|