I'm new to the game, just going through the sparkfun inventor's kit, with a few additions here and there for fun. This is an easy situation. I have a working temperature sensor; I wanted to have two LEDs (one red, one yellow) show if the temperature is going up or down.
The goal was to have the Red LED come on when the temperature was going up, and the Yellow LED to come on when the temperature is going down.
So I put this little bit in the loop:
void setup()
{
float lastvoltage = 0;
pinMode(YellowLED, OUTPUT);
pinMode(RedLED, OUTPUT);
digitalWrite(YellowLED, LOW);
digitalWrite(RedLED, LOW);
}
void loop()
{
float voltage, degreesC, degreesF;
voltage = getVoltage(temperaturePin);
//A function that reads the sensor and returns a Float to "voltage"
if(voltage < lastvoltage)
{
digitalWrite(YellowLED, HIGH);
digitalWrite(RedLED, LOW);
}
if(voltage > lastvoltage) {
digitalWrite(RedLED, HIGH);
digitalWrite(YellowLED, LOW);
}
lastvoltage = voltage;
delay(1000);
}
float getVoltage(int pin)
{
return (analogRead(pin) * 0.004882814);
}
The strange thing to me is that the opposite of what I expected happened- when the console was reading temperatures going up, the YELLOW LED was coming on, instead of the red one, and vice versa.
Obviously when I reverse the "<" and ">" it works, but I wanted to know why it was backwards.
As temperature goes up, the variable "voltage" goes up, so if "lastvoltage" was saving the last reading before the sensor returns again and the next reading is higher, then voltage should be > lastvoltage and the RED LED should turn on.
It has confounded me so much that I had to post it here. I'm sure it's a simple reason, my simple brain just can't figure it out.
Thanks!