I used to program in college but that was 20 years ago now and I am back to basics. I am trying to figure out how to add a button to this code to control it. Once pressed I want it to only run once, and then stop. I have looked at other examples but I am either not integrating it right or I'm botching it on the breadboard. Any assistance would be appreciated.
CODE
/*
Fade
This example shows how to fade an LED on pin 9
using the analogWrite() function.
This example code is in the public domain.
*/
int led = 9; // the pin that the LED is attached to
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() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// check to see if we are ready for flash
if (brightness > 150) {
// flash the led
analogWrite(led, 255);
delay(50);
// start the dimming effect
fadeAmount = -fadeAmount ;
Serial.println(brightness);
}
if (brightness <= 0) {
fadeAmount = -fadeAmount;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
jamstraz:
Goodbye. Deleted profile. Sorry to have bothered anyone.
I don't know if the deletion is automatic or it needs intervention/approval of the Moderator. In the past, I tried to delete my profile; but, it was never deleted. I think that you are still alive in the Forum and just continue.
Here, how you can go connecting a button with your sketch, which when pressed will cause your sketch to run only once.
1. Connect K1 with DPin-2 (with internal pull-up enabled) as per Fig-1.
Figure-1:
2. Upload the following sketch (tested).
int led = 9; // the pin that the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
int counter = 0;
// the setup routine runs once when you press reset:
void setup()
{
// declare pin 9 to be an output:
// pinMode(led, OUTPUT);
pinMode(2, INPUT_PULLUP); //internal pull-up resistor is connected
Serial.begin(9600);
}
void loop()
{
while (digitalRead(2) != LOW) //check if the button is pressed; if not wait until closed
;
counter = 0;
do
{
// set the brightness of pin 9:
analogWrite(led, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// check to see if we are ready for flash
if (brightness > 150)
{
// flash the led
analogWrite(led, 255);
delay(50);
// start the dimming effect
fadeAmount = -fadeAmount ;
Serial.println(brightness);
}
if (brightness <= 0)
{
fadeAmount = -fadeAmount;
counter++;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
while (counter != 1);
}
3. Just press K1 and check the fading effect on the LED for one cycle.