I am trying to use a single button/switch to turn an LED ON/OFF (like a light switch at home ) , but i am having trouble finding code that would execute that. Does anyone know how it could possibly work?
Here is the exactly what you want. Arduino - Button control LED
The code in that tutorial work not only for button but switch
you want the LED to toggle with each button press, right?
// recognize multiple button presses; tgl LED when pressed
byte butPin = A1;
byte ledPin = 10;
byte butLst;
// -----------------------------------------------------------------------------
void setup (void)
{
digitalWrite (ledPin, HIGH);
pinMode (ledPin, OUTPUT);
pinMode (butPin, INPUT_PULLUP);
butLst = digitalRead (butPin);
}
// -----------------------------------------------------------------------------
void loop (void)
{
byte but = digitalRead (butPin);
if (butLst != but) {
butLst = but;
if (LOW == but) // button pressed
digitalWrite (ledPin, ! digitalRead (ledPin));
}
delay (10); // debounce
}
gcjr:
you want the LED to toggle with each button press, right?// recognize multiple button presses; tgl LED when pressed
byte butPin = A1;
byte ledPin = 10;
byte butLst;
// -----------------------------------------------------------------------------
void setup (void)
{
digitalWrite (ledPin, HIGH);
pinMode (ledPin, OUTPUT);
pinMode (butPin, INPUT_PULLUP);
butLst = digitalRead (butPin);
}
// -----------------------------------------------------------------------------
void loop (void)
{
byte but = digitalRead (butPin);
if (butLst != but) {
butLst = but;
if (LOW == but) // button pressed
digitalWrite (ledPin, ! digitalRead (ledPin));
}
delay (10); // debounce
}
thanks gcjr that totally worked !
the code you posted worked as I needed ! but would you mind explaining the code or providing some pseudocode to help me understand what is going on ? Im trying to learn Arduino so it would be of much help .
Anyone else is welcome to help explain btw !