I was hoping to get some help on the fading led which I am working on.
For my project I need to have a led, which when it is placed next to a magnet, continuously shines, but as soon as it is taken away it has to fade out in a certain amount of time. So far I managed to write the code which detects when the light is taken away from the magnet and fades out, but when the magnet is nearby again, the led lights up and keeps shining, no matter if I take it away from the magnet or not. So how I could solve this? I tried to exit the loop function, but then this process happens only once, which is not what I want. I am also using reed switch to detect the magnet, but if you have other sensor suggestions, let me know. I'm including the code down here.
Thank you for your help in advance:)
int ledPin = 9;
int brightness = 255;
int fadeAmount = 5;
const int reedPin = 2;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(reedPin, INPUT_PULLUP);
}
void loop() {
int proximity = digitalRead(reedPin);
if (proximity == HIGH) {
Serial.println("Switch opened");
while (brightness >= 0) {
analogWrite(ledPin, brightness);
brightness = brightness - fadeAmount;
delay(30);
Serial.println(brightness);
}
}
else {
Serial.println("Switch closed");
analogWrite(ledPin, brightness);
Serial.println(brightness);
}
}
{}
button in the question editor