我在我的 PCB 板上同时使用 Si7021 硅实验室的温度和湿度传感器和 APD300 光传感器,我还使用 STM32F103 Arduino 兼容微控制器,它通过 I2C 协议与传感器通信,我之前已经测试过,传感器正在读取正确的传感器Arduino 串行监视器中的数据,但现在我的湿度和温度传感器读取的值太多,例如“219982828282 C”,即使我使用了正确的上拉电阻,我想知道我的代码是否有问题使用(从互联网上找到)。我附上了我使用的源代码和传感器的串行监视器输出。
#include <Wire.h>
// SI7021 I2C address is 0x40(64)
#define Addr 0x40
void setup()
{
// Initialise I2C communication as MASTER
Wire.begin();
// Initialise serial communication, set baud rate = 9600
Serial.begin(9600);
// Start I2C transmission
Wire.beginTransmission(Addr);
// Stop I2C transmission
Wire.endTransmission();
delay(300);
}
void loop()
{
unsigned int data[2];
// Start I2C transmission
Wire.beginTransmission(Addr);
// Send humidity measurement command, NO HOLD MASTER
Wire.write(0xF5);
// Stop I2C transmission
Wire.endTransmission();
delay(500);
// Request 2 bytes of data
Wire.requestFrom(Addr, 2);
// Read 2 bytes of data
// humidity msb, humidity lsb
if(Wire.available() == 2)
{
data[0] = Wire.read();
data[1] = Wire.read();
}
// Convert the data
float humidity = ((data[0] * 256.0) + data[1]);
humidity = ((125 * humidity) / 65536.0) - 6;
// Start I2C transmission
Wire.beginTransmission(Addr);
// Send temperature measurement command, NO HOLD MASTER
Wire.write(0xF3);
// Stop I2C transmission
Wire.endTransmission();
delay(500);
// Request 2 bytes of data
Wire.requestFrom(Addr, 2);
// Read 2 bytes of data
// temp msb, temp lsb
if(Wire.available() == 2)
{
data[0] = Wire.read();
data[1] = Wire.read();
}
// Convert the data
float temp = ((data[0] * 256.0) + data[1]);
float cTemp = ((175.72 * temp) / 65536.0) - 46.85;
float fTemp = cTemp * 1.8 + 32;
// Output data to serial monitor
Serial.print("Relative humidity : ");
Serial.print(humidity);
Serial.println(" % RH");
Serial.print("Temperature in Celsius : ");
Serial.print(cTemp);
Serial.println(" C");
Serial.print("Temperature in Fahrenheit : ");
Serial.print(fTemp);
Serial.println(" F");
delay(500);
}
Arduino 串行监视器输出:
照度:101 相对湿度:65802760.00 % RH 摄氏温度:92502848.00 C 华氏温度:166505152.00 F