我在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