The numbers of temperature which is displayed on LCD run randomly

Hi there, i have a trouble while measuring the temperature of air and the moisture of earth. I had tested these by using 2 separated programs (1 for temperature, 1 for moisture), before merging it into one program and it worked when separated. However, after merging, the temperature keeps changing randomly. And I don’t know where I did wrong. Can someone find out where i did wrong? Here my program

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
int pin1 = A0;    //for temperature
int pin2 = A1;   //for moisture
void setup()
{
  Serial.begin(9600);
  lcd.begin(16, 2); 
}
void loop() 
{
  int reading = analogRead(pin1);            // these are used to change the analog voltage to temperature
  float voltage = reading*5.0/1024.0;      //
  float temp = voltage*100.0;                 //
  lcd.setCursor(0, 0);
  lcd.print("TEMPER:"); 
  lcd.setCursor(10, 0);
  lcd.print(temp,1);
  lcd.write(223);
  lcd.print("C");
  lcd.setCursor(0,1);
  lcd.print("MOIS:");
  lcd.setCursor(10,1);
  int value = analogRead(pin2);
  int percent = map(value, 0, 1023, 0, 70);      //use map to change the voltage value of the moisture 
  int mois = 70-percent;                                 //sensor to percentage
  lcd.print(mois,1);
  lcd.print('%');
  delay (1000);
}

CP.ino (704 Bytes)

Try adding some serial.prints to see what readings you’re getting from the ADC.

One possibility is that since the ADC is shared, the temperature reading is being impacted by the previous read for moisture. A common solution is to read the ADC twice for each reading and throw away the first one.

i have set up the adc and what can i get from it?
Edited: when i changed the rhostat until i got value 0 on serial monitor, sometimes it changed to 1 or 2. Is that a problem?

You're getting a reading from the ADC:

  int reading = analogRead(pin1);

I'm suggesting that you should use serial to tell you what value "reading" has, and the one for moisture. If reading is varying wildly, either you have the problem I suggested above or something is wrong with your wiring/hardware.

You’re right. reading change widly and i dont think that the wire/ hardware is wrong because it’s still good when i separate it. And can you help me to read ‘reading’ twice before use it?

  int reading = analogRead(pin1);            // these are used to change the analog voltage to temperature
  int reading = analogRead(pin1);            // these are used to change the analog voltage to temperature
  float voltage = reading*5.0/1024.0;      //

ohh...wow! that's so easy. why i couldn't think about it. Thank you very much! :slight_smile: