Skip to content

Instantly share code, notes, and snippets.

@eddy85br
Created January 24, 2021 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eddy85br/ec026c9e8d6f0b0bcef098f10330e915 to your computer and use it in GitHub Desktop.
Save eddy85br/ec026c9e8d6f0b0bcef098f10330e915 to your computer and use it in GitHub Desktop.
Arduino Toggle LED with a push button
/*
Fade
This example shows how to fade an LED on pin 9
using the analogWrite() function.
The analogWrite() function uses PWM, so if you
want to change the pin you're using, be sure to
use another PWM capable pin. On most Arduino,
the PWM pins are identified with a "~" sign,
like ~3, ~5, ~6, ~9, ~10 and ~11.
*/
#include <Arduino.h>
#include <OneButton.h> // Library: https://github.com/mathertel/OneButton
#define BUTTON_PIN A1
#define LED_PIN 3
typedef enum {
OFF, // set LED "OFF".
ON // set LED "ON"
} states;
OneButton button = OneButton(
BUTTON_PIN, // Input pin for the button
true, // Button is active LOW
true // Enable internal pull-up resistor
);
// old version:
//OneButton button(BUTTON_PIN, true);
states state = OFF;
int brightness = 0;
int inc = 5;
void setup() {
pinMode(LED_PIN, OUTPUT);
button.attachClick(handleClick);
// set 80 msec. debouncing time. Default is 50 msec.
//button.setDebounceTicks(80); // no need..
Serial.begin(9600);
}
void loop() {
button.tick(); // check if button was pushed
if (state == ON) {
for (brightness = 0; brightness <= 255; brightness += inc) {
analogWrite(LED_PIN, brightness);
delay(30); // Wait for 30 millisecond(s)
button.tick(); // check if button was pushed
}
for (brightness = 255; brightness >= 0; brightness -= inc) {
analogWrite(LED_PIN, brightness);
delay(30); // Wait for 30 millisecond(s)
button.tick(); // check if button was pushed
}
}
}
// Handler function for a single click:
static void handleClick() {
Serial.println("Clicked!");
if (state == OFF) {
Serial.println("ON!");
state = ON;
} else {
Serial.println("OFF!");
state = OFF;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment