Temperature Controlled RGB LED

Hello to all Arduinians,

I am having some trouble modifying some code for the captioned project.

How can I modify the following code to make it so that the LED turns from Blue>Green>Red as temperature increases? At the moment, it just goes from Blue>Red:

#define TEMP_PIN A0
#define RED_PIN 9
#define GREEN_PIN 10
#define BLUE_PIN 11

int adc = 0;
int blue = 0, red = 0, green = 0;

double ReadThermistor(int adc) {

  double resistance = ((1024.0/adc) - 1);    //calculate from voltage divider, for 10k resistor
  double Temp = log(resistance);

  // calculate the temperature, in K, using 4 thermistor model/material specific parameters A, B, C, D
  // here we use the values for the Sparkfun/Hactronics version of the Vishay 10k NTC thermistor
  Temp = 1 / (0.003354016 + 0.0002569850 * Temp + 0.000002620131 * Temp * Temp + 0.00000006383091 * Temp * Temp * Temp);
  Temp = Temp - 273.15;            // Convert Kelvin to Celsius
  return Temp;
}

void setLED(int blue, int red, int green){
  analogWrite(BLUE_PIN, blue);
  analogWrite(RED_PIN, red);
  analogWrite(GREEN_PIN, green);
}

void setup(){
  Serial.begin(14400);
  pinMode(BLUE_PIN, OUTPUT); 
  pinMode(RED_PIN, OUTPUT); 
  pinMode(GREEN_PIN, OUTPUT);  
  pinMode(TEMP_PIN, INPUT);
}

void loop(){
  adc = analogRead(TEMP_PIN);
  int temp = ReadThermistor(adc);
  Serial.println(temp);
  
  red = map(temp, 0, 20, 0, 255);
  blue = 255 - red;
  setLED(blue, red, green);
}

Thank you for your helps! :slight_smile:

Take that code and make two ranges, one from red to green and the other from green to red.

Then decide what threshold temperature you need to use to make the switch between one range and the next. Then use an if statement to switch the mapping from one range to the other.

How do I go about making the ranges?

Use two map functions and let the if statement choose which one is executed.