Bug in course lesson 'Serial Communications with I2C'?
I've noticed a problem with the sample code for the TMP102 temperature sensor which shows up in my dev environment (mbed-classic, nRF51-DK). The sensor returns temperatures as the first 12 bits of the two byte read, in twos compliment format.
Given:
float temp;
char temp_read[2];
tempsensor.read(addr, temp_read, 2); //read the two-byte temp data
temp = 0.0625 * (((temp_read[0] << 8) + temp_read[1]) >> 4); //convert data
The 'convert data' code doesn't properly handle negative temperature values. Looks like the compiler needs a hand with type inference, as this fixes it:
temp = 0.0625 * ((int16_t)((temp_read[0] << 8) + temp_read[1]) >> 4);
For example if I test with:
temp_read[0] = 0xE7;
temp_read[1] = 0x00;
int16_t sum = (((int16_t)(temp_read[0] << 8) + (int16_t)temp_read[1]) >> 4);
int16_t sum1 = (((temp_read[0] << 8) + (int16_t)temp_read[1]) >> 4);
pc.printf("sum: %i sum1: %i\r\n", sum, sum1);
I get:
sum: -400 sum1: 3696
Bug in course lesson 'Serial Communications with I2C'?
I've noticed a problem with the sample code for the TMP102 temperature sensor which shows up in my dev environment (mbed-classic, nRF51-DK). The sensor returns temperatures as the first 12 bits of the two byte read, in twos compliment format.
Given:
The 'convert data' code doesn't properly handle negative temperature values. Looks like the compiler needs a hand with type inference, as this fixes it:
For example if I test with:
I get: sum: -400 sum1: 3696