hi guys i am new to arduino community i am working on a simple project
-One button
-One LED
When button is pressed and held down led starts fading in to its max brightness and stays max while button is press
when button is released led starts fading out from maximum brightness to zero
Now i have looked everywhere for example of the code but can't find anything what would work
or give me any clue how to make it work
Please help
here is what i have written but there is a bug and i it fades up but not down
int button = 2;
int led = 3;
int fadeAmount = 5;
int brightness = 0;
void setup()
{
pinMode(led, OUTPUT);
pinMode(button, INPUT);
Serial.begin(9600);
}
void loop()
{
Serial.println(brightness);
if (brightness <= 255 && digitalRead(button) == HIGH)
{
analogWrite(led, brightness);
brightness = brightness + fadeAmount;
delay(10);
}
if (brightness == 255 && digitalRead(button) == LOW)
{
analogWrite(led, brightness);
brightness = brightness - fadeAmount;
delay(10);
}
delay(50);
}
I think the main task is this: check button; increase or decrease the brightness.
To apply the limits of 0 and 255 is something extra on top of that.
The program flow would be : the button is the input data, the code is the processing part and the led is the output.
Put that into a sketch.
//
// Sketch for kwiattek:
// http://forum.arduino.cc/index.php?topic=372413.0
// Using Arduino 1.6.7 and Arduino Uno
const int buttonPin = 2; // button to GND at pin 2
const int ledPin = 3; // led at pin 3
int fadeAmount = 5;
int brightness = 0;
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600);
Serial.println("Started");
}
void loop()
{
// --------------------------
// The input part.
// --------------------------
// Only a single button is the input.
int btn = digitalRead(buttonPin);
// --------------------------
// The processing part.
// --------------------------
if( btn == HIGH)
{
brightness += fadeAmount;
if( brightness > 255)
brightness = 255;
}
else
{
brightness -= fadeAmount;
if( brightness < 0)
brightness = 0;
}
// --------------------------
// The output part.
// --------------------------
analogWrite(ledPin, brightness);
Serial.println(brightness);
// Delay 50 ms, to run this 20 times a second.
delay(50);
}
(while I was writing this sketch, Wusaweki also wrote a sketch. I'm glad to see that Wusaweki has also a good code flow by using seperate parts for input, processing and output.)
If your button switches 5V to the input pin, have you got a 10K resistor between the input pin and gnd to make sure the input goes to gnd when you release the button?