i am relatively new to arduino and I have been putting together a i2c lcd "thermostat" as a start to a bigger project i have in mind.
I have recently add smoothing to the TMP36 part of the code but for some reason the first 5 or what ever you put as the numReadings are incorrect data starting off as minus and then slowly working they way up to the correct figure which messes up how it is displayed on the lcd.
I am also looking to round the tmp36 data to 1 decimal place i have tried
"tempC = round(tempC*10)/10;
but just results in rounding to e.g 22.00 for 21.87 . I was wondering whether anyone could point me in the right direction to solving these problems, also if anyone could point out how my code could be tidy up/made better that would be much appreciated.
thanks
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3f,20,4); // set the LCD address
#define aref_voltage 3.3 // 3.3v analog reference
//TMP36 Pin Variables
int tempPin = 1; //Tmp 36 data pin
//the resolution is 10 mV / degree centigrade with a
//500 mV offset to allow for negative temperatures
const int numReadings = 5;
int readings[numReadings]; // the readings from the analog input
int readIndex = 0; // the index of the current reading
int total = 0; // the running total
int average = 0; // the average
void setup() {
Serial.begin(9600); // serial setup
lcd.init(); // initialize the lcd
lcd.backlight(); // Backlight on
lcd.setCursor(0,0); // set Cursor to the Top left
lcd.print("Temperature: C"); // print temperature with space for data
lcd.setCursor(18,0);
lcd.print((char)223); // print degree symbol
lcd.setCursor(3,1);
lcd.print("Set Temp: C"); // print Set temp: with space for data
lcd.setCursor(18,1);
lcd.print((char)223); // print degree symbol
analogReference(EXTERNAL); // If you want to set the aref to something other than 5v
for (int thisReading = 0; thisReading < numReadings; thisReading++)
{
readings[thisReading] = 0;
}
}
void loop() {
total = total - readings[readIndex]; // subtract last reading
readings[readIndex] = analogRead(tempPin); //read the tmp36 data pin
total = total + readings[readIndex]; // add reading to the total
readIndex = readIndex + 1; // advance to the next postion in the array
if (readIndex >= numReadings) // if we are at the end of the array
{
readIndex = 0 ; // go back to the beginning
}
average = total / numReadings;
float voltage = average * aref_voltage; // convert the reading in to mV
voltage /= 1024.0;
float TempC = (voltage - 0.5) * 100; // convert from 10mV per c with 500mV offset
if (TempC < 10)
{
lcd.setCursor(13,0);
lcd.print(" ");
lcd.print(TempC);
}
else
{
lcd.setCursor(13,0);
lcd.print(TempC);
}
Serial.println(TempC);
delay(1000);
}