I`m new to the Arduino and just started practicing simple use of PWM and pin input/output.
I got a really strange behavior with the led fading program that I`m runing when a pin is LOW.
When I disconnect the pin from GROUND when the led is fading dow and I put it back to GROUND the led is flashing really fast like in a loop . To get out of this loop I have to disconect the pin for a couple of seconds .
here is my code
int led = 5; // the PWM pin the LED is attached to
int test ;
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
// the setup routine runs once when you press reset:
void setup() {
pinMode(led, OUTPUT);
pinMode(6,INPUT);
pinMode(9,OUTPUT);
digitalWrite(6, HIGH);
}
// the loop routine runs over and over again forever:
void loop() {
// read input pin 6
test = digitalRead(6);
if (test == LOW ) {
analogWrite(led, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
if (test != LOW ){
brightness=0;
analogWrite(led, 0);
delay(2);
}
}
Also note that when the int -5 (0xFFFB) is used as a PWM value it gets truncated to a byte (0xFB) and treated as unsigned so the value is 251. You're toggling between a very low brightness (5) and a very high brightness (251).