Go Down

Topic: help with pressure sensor controlling color fade (Read 1 time) previous topic - next topic


I am building a pressure sensor that controls RGB lED's. I want to be able to get a smooth transition from blue (light pressure) to green (medium pressure) up to red (highest pressure) and am having trouble with the code.

//main sketch for pressure sensor(POT1) controlling brightness of LED's

#define GREENLED 9  //
#define BLUELED 10  //
#define REDLED 11  //
#define POT1 A0

int brt = 0;  //pot value
int redval= 0;
int blueval = 0;
int greenval = 0;

void setup()
  pinMode(REDLED, OUTPUT);   //tell Arduino LED is an output
  pinMode(BLUELED, OUTPUT);  //tell Arduino LED is an output
  pinMode(GREENLED, OUTPUT); //tell Arudino LED is an output
  pinMode(POT1, INPUT);      //tell Arduino LED is an output


void loop(){
  brt = analogRead(POT1);
  Serial.print (blueval);

  //blue def
  //green def
  //red def

  analogWrite(BLUELED, blueval);
  analogWrite(GREENLED, greenval);
  analogWrite(REDLED, redval);

Anyone out there who can help with this?


First the obvious part (assuming that the input goes from 0-1023 and the output too):

0: Blue 1023 - green 0 - red 0
between 0 and 512: reduce blue, increase green, red is off
512: blue 0 - green 1023 - red 0
between 512 and 1023: reduce green, increase red, blue is off
1023: blue 0 - green 0 - red 1023

If you take a simple linear approach, the code would look something like:
Code: [Select]
void loop(){
 brt = analogRead(POT1);

 if (brt < 512) {
   // blue + green
   greenval = brt * 2;
   blueval = 1023 - greenval;
   redval = 0;
 else {
   // green + red
   redval = (brt-512) * 2;
   greenval = 1023 - redval;
   blueval = 0;

 analogWrite(BLUELED, blueval);
 analogWrite(GREENLED, greenval);
 analogWrite(REDLED, redval);

Now with this method, the colours might not be of constant brightness or the gradient of change isn't pleasing. In this case you'll have to adapt the mixing formula, which can become complex if you need to take into account unequal brightness for the 3 colours. But for starters, this should do.


Go Up