error in temperature misuration (LM35 sensor)

MY temperature sensor is giving problems; it keeps finding temperature and then going back to 0. Serial plotter in attachment…

Then you probably have a bug in the code that you have not posted!

const int pin = A0; // analog pin
float celsius = 0, farhenheit =0; // temperature variables
float millivolts;
int sensor;
int redLed = 5;
int yellowLed = 9;
int greenLed = 10;
int errorLed = 11;

void setup()
{
Serial.begin(9600); // inizializza la comunicazione seriale
// LED
pinMode(errorLed, OUTPUT);
pinMode(redLed, OUTPUT);
pinMode(yellowLed, OUTPUT);
pinMode(greenLed, OUTPUT);
}

void loop() {
int aRead = 0;
aRead = analogRead(pin);

Serial.print("Analog = ");
Serial.print(aRead);

float tempC = aRead * 0.48875;

Serial.print(" Temp = ");
Serial.println(tempC);
// accendi il led
if (analogRead(pin) < 39) { // 41 corrisponde a 20°C
analogWrite(errorLed, 255);
analogWrite(greenLed, 0);
analogWrite(yellowLed, 0);
analogWrite(redLed, 0); }
else if (analogRead(pin)<41) {
analogWrite(errorLed, 0);
analogWrite(greenLed, 255);
analogWrite(yellowLed, 0);
analogWrite(redLed, 0);
}
else if (analogRead(pin)<61) {
analogWrite(errorLed, 0);
analogWrite(greenLed, 0);
analogWrite(yellowLed, 255);
analogWrite(redLed, 0);
}
else if (analogRead(pin)<100) {
analogWrite(errorLed, 0);
analogWrite(greenLed, 0);
analogWrite(yellowLed, 0);
analogWrite(redLed, 255);
}
delay(1000);
}

I used another code from a tutorial, but the error persisted.

Please post the serial output values that are used to generate the Serial plot.

Er... I'm sorry, I don't know of what are you speaking...

The values you are plotting are available on the serial output. Post these as well as the plot.

I recreated the circuit and it works, for stretches of time, well.

Hi,
This section of your code.

void loop() {
int aRead = 0;
aRead = analogRead(pin);

Serial.print("Analog = ");
Serial.print(aRead);

float tempC = aRead * 0.48875;

Serial.print(" Temp = ");
Serial.println(tempC);
// accendi il led
if (analogRead(pin) < 39) { // 41 corrisponde a 20°C

You read the temp value as aRead, then convert it to degC, but then use analogRead(pin) as the value to compare for your LEDS.

Why not

if ( tempC < 39) { // 41 corrisponde a 20°C

Tom… :slight_smile: