Go Down

Topic: SHT21 float values & dtostrf string? (Read 2884 times) previous topic - next topic

point5

Hi,

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:

Code: [Select]
/*
*  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);
}


.... and the output is:

Code: [Select]
Humidity(%RH):
  2.00
57.50
Temperature(C):
  2.00
25.74
Humidity(%RH):
  2.00
56.42
Temperature(C):
  2.00
25.74

robtillaart

#1
Sep 11, 2011, 10:44 am Last Edit: Sep 11, 2011, 11:02 am by robtillaart Reason: 1
Very wrong code

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:
Code: [Select]

/*
*  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);
}
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

point5

Wonderful, thanks for both the explaination and fix - works great and I can now print to LCD :-)

Cheers.

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy