BME280函数没有库,但得到负数
BME280 function without library, but getting negative numbers
所以我正在使用 bme280 并尝试制作一个无需使用库即可读取温度的函数。但出于某种原因,它给了我 - 数字。有人知道为什么会这样吗?
long BME280_ReadTemperature()
{
long temperature = 0;
Wire.beginTransmission(BME280_ADDR);
Wire.write(BME280_TEMP_REG);
Wire.endTransmission();
//request 3 bits so that it can read 3 registers
Wire.requestFrom(BME280_ADDR, 3);
//These three are being read as shown in the powerpoint slides
uint8_t reading1 = Wire.read();
uint8_t reading2 = Wire.read();
int reading3 = Wire.read();
temperature |= (reading1 << 8);
temperature |= (reading2 << 4);
temperature |= reading3;
return temperature;
}
取而代之的是 int
in Arduino environment is 16-bit long. It is used for calculations of values with the size of int
or below, but it is not sufficient to deal with 20-bit temperature value of BME280. You should use long
,它是 32 位长。
而且移动量看起来不对。根据BME280数据表的5.4.8,位[3:0]
存储在0xFC的高半部分,位[11:4]
存储在0xFB,位[19:12]
存储在 0xFA。偏移量应与这些匹配。
总之,行
temperature |= (reading1 << 8);
temperature |= (reading2 << 4);
temperature |= reading3;
应该是:
temperature |= ((long)reading1 << 12);
temperature |= (reading2 << 4);
temperature |= (reading3 >> 4);
所以我正在使用 bme280 并尝试制作一个无需使用库即可读取温度的函数。但出于某种原因,它给了我 - 数字。有人知道为什么会这样吗?
long BME280_ReadTemperature()
{
long temperature = 0;
Wire.beginTransmission(BME280_ADDR);
Wire.write(BME280_TEMP_REG);
Wire.endTransmission();
//request 3 bits so that it can read 3 registers
Wire.requestFrom(BME280_ADDR, 3);
//These three are being read as shown in the powerpoint slides
uint8_t reading1 = Wire.read();
uint8_t reading2 = Wire.read();
int reading3 = Wire.read();
temperature |= (reading1 << 8);
temperature |= (reading2 << 4);
temperature |= reading3;
return temperature;
}
取而代之的是 int
in Arduino environment is 16-bit long. It is used for calculations of values with the size of int
or below, but it is not sufficient to deal with 20-bit temperature value of BME280. You should use long
,它是 32 位长。
而且移动量看起来不对。根据BME280数据表的5.4.8,位[3:0]
存储在0xFC的高半部分,位[11:4]
存储在0xFB,位[19:12]
存储在 0xFA。偏移量应与这些匹配。
总之,行
temperature |= (reading1 << 8);
temperature |= (reading2 << 4);
temperature |= reading3;
应该是:
temperature |= ((long)reading1 << 12);
temperature |= (reading2 << 4);
temperature |= (reading3 >> 4);