I think I am making a simple mistake but just can't see it !! Any idea why my float to string conversion is always reporting "2.0" instead of the value output from a SHT21 temp/rh sensor?
My code is:
/*
* Read the Relative Humidity and Temperature values from SHT21 sensor
* Clock is Analog pin 5
* Data is Analog pin 4
*
*/
#include <Wire.h>
#include <SHT21.h>
#include<stdlib.h>
char temp_str[10];
char rh_str[10];
float temp;
float rh;
void setup()
{
Serial.begin(9600);
Wire.begin();
}
void loop()
{
SHT21.readSensor();
temp=(SHT21.temp, 2);
rh=(SHT21.humi, 2);
dtostrf(temp,6,2,temp_str);
dtostrf(rh,6,2,rh_str);
Serial.println("Humidity(%RH): ");
Serial.println(rh_str); //prints "2.0"
Serial.println(SHT21.humi, 2); //works
Serial.println("Temperature(C): ");
Serial.println(temp_str); //prints "2.0"
Serial.println(SHT21.temp, 2); //works
delay(5000);
}
temp = (SHT21.temp,2); does not copy with 2 decimals - you copy/pasted a pattern from Serial print where the 2 is a parameter (#decimals) of the print function for floats.
The statement (SHT21.temp,2) is a compound statement existing of 2 statements executed from left to right. The return value of the last statement is 2 (as odd as it may sounds) and this value is assigned to temp.
For humidity the error is the same
Check this variation:
/*
* Read the Relative Humidity and Temperature values from SHT21 sensor
* Clock is Analog pin 5
* Data is Analog pin 4
*
*/
#include <Wire.h>
#include <SHT21.h>
#include<stdlib.h>
char temp_str[10];
char rh_str[10];
float temp;
float rh;
void setup()
{
Serial.begin(9600);
Wire.begin();
}
void loop()
{
SHT21.readSensor();
temp = SHT21.temp;
rh = SHT21.humi;
dtostrf(temp, 6, 2, temp_str);
dtostrf(rh, 6, 2, rh_str);
Serial.println("Humidity(%RH): ");
Serial.println(rh_str);
Serial.println(SHT21.humi, 2); //works
Serial.println("Temperature(C): ");
Serial.println(temp_str);
Serial.println(SHT21.temp, 2); //works
delay(5000);
}