Temperature sensor reading changes when a relay is turned on ?

Hi all,

I’ve designed a temperature indicator that is supposed to turn on a red LED when temperature is above a certain level. Otherwise, the yellow LED is on. I use a TMP36 temperature sensor (26f, 27f, 28f on the breadboard as shown in the photo) and a relay to control the LEDs. I’ve noticed that immediately when the relay is turned on, the voltage reading from the temperature sensor will go up as well. And it always goes up by a certain amount. The device is powered by USB from my laptop. To make it work properly, I had to program different threshold values for when relay is on and off.

The code is as follows :

const int temperaturePin = 0;
const int relayPin = 2;    // use this pin to drive the transistor
boolean relayon = false;

void setup()
{
  pinMode(relayPin, OUTPUT); 
  Serial.begin(9600);
}

void loop()                    
{
  float voltage;
  delay(1000);
  voltage = getVoltage(temperaturePin);
  Serial.print("voltage: ");
  Serial.println(voltage);
  if ( (relayon == false && voltage > 0.86) || (relayon == true && voltage > 0.93) )
  {
    digitalWrite(relayPin, HIGH);  
    delay(1000);
    voltage = getVoltage(temperaturePin);
    Serial.print("On. voltage: ");
    Serial.println(voltage);
    relayon = true;
  }
  else
  {
    digitalWrite(relayPin, LOW);   // turn the relay off
    delay(1000);
    voltage = getVoltage(temperaturePin);
    Serial.print("Off. voltage: ");
    Serial.println(voltage);
    relayon = false;
  }    
  delay(1000);
} 

float getVoltage(int pin)
{
  return (analogRead(pin) * 0.004882814);
  // This equation converts the 0 to 1023 value that analogRead()
  // returns, into a 0.0 to 5.0 value that is the true voltage
}

I know this is a stupid solution… I’m wondering what I should do to keep the voltage reading from the temperature sensor at the same value for the same temperature ?

IMAG0423_1.zip (736 KB)

Give the relay a separate power supply.