Fading RGB light from yellow to red using reed switch

95 views Asked by At

I am still quite new to arduino coding, so I would very much appreciate your help!

I have recently made a circuit using reed switch and a simple LED light, which makes a light slowly fade out once it is taken away from a magnetic field and light up again once it is close to the magnet. For my project, I need the LED to produce constant yellow light when it is close to the magnetic field, but as soon as it is taken away, the light has to fade to the red light and fade out in general at the same time.

So simply put:

  • reed switch "closed" = constant yellow light
  • reed switch "open" = fading to the red light and fading out at the same time

Bellow is the code that I already have for simple LED and reed switch.

`

int ledPin = 9;
int reedPin = 2;

int brightness = 0;
int fadeAmount = 5;
unsigned long timestamp = 0;

void setup(){
    pinMode(ledPin, OUTPUT);
    pinMode(reedPin, INPUT_PULLUP);
}

void loop(){
    if(millis()-timestamp > 30){
        brightness = brightness - fadeAmount;
        if(brightness < 0) brightness = 0;
        timestamp = millis();
    }

    if(!digitalRead(reedPin)){
        brightness = 255;
    }

    analogWrite(ledPin, brightness);
}

//different code begins here

int rVal = 254;
int gVal = 1;
int bVal = 127;

int rDir = -1;
int gDir = 1;
int bDir = -1;

const int rPin = 11;
const int gPin = 10;
const int bPin = 9;

void setup() {
  pinMode(rPin, OUTPUT);
  pinMode(gPin, OUTPUT);
  pinMode(bPin, OUTPUT);
}

void loop() {

  analogWrite(rPin, rVal);
  analogWrite(gPin, gVal);
  analogWrite(bPin, bVal);

  // change the values of the LEDs
  rVal = rVal + rDir;
  gVal = gVal + gDir;
  bVal = bVal + bDir;

  if (rVal >= 255 || rVal <= 0) {
    rDir = rDir * -1;
  }

  if (gVal >= 255 || gVal <= 0) {
    gDir = gDir * -1;
  }

  if (bVal >= 255 || bVal <= 0) {
    bDir = bDir * -1;
  }

  delay(33);
}
}

`

Bottom one is the code that makes RGB led crossfade different colours, but I need it to go from yellow to red. How could I do that? And how can I incorporate the RGB light code into reed switch code?

1

There are 1 answers

1
Piglet On

You achieve yellow with the green and red emitter at the same level.

In order to fade to red you need to decrease the green emitter to 0. This of course will also decrease the overall brightness.

Once you faded out green you can fade red to 0.

Of course you can also fade out both leds at the same time. Fading the green component faster will also move the colour towards red.

That's personal preference