How do I make the LEDs stay and continue in a loop after I press the switch once, and turn off when the switch is pressed again? This is the code I have so far but it only allows the LEDs to light up when I hold onto pressing the switch and turn back off immediately after I release it. If anybody knows how to help going from here that would be great, thank you ^-^
int button1 = 2; //tact switch connected to digital pin 2
int LED = 4; //blue LED
int button2 = 7; //tact switch connected to digital pin 7
int LED2 = 9; //yellow LED
void setup() {
pinMode(2, INPUT);
pinMode(4, OUTPUT);
pinMode(7, INPUT);
pinMode(9, OUTPUT);
}
void loop() {
if (digitalRead (button1)==HIGH) {
digitalWrite (LED, HIGH);
}
else {
digitalWrite (LED, LOW);
}
{
if (digitalRead (button2)==HIGH) {
digitalWrite (LED2, HIGH);
}
else {
digitalWrite (LED2, LOW);
}
}
}
// This a simple OOP example to toggle LEDs, keep in mind to connection of the hardware
// The sketch is tested using my test enviromnet and the initialization may has to be changed
// declare an object
struct LEDBUTTON {
byte switchPin; // [port pin] ----- [switch] ------ [gnd]
byte ledPin; // [port pin] ----- [led] ------ [gnd]
byte counter; // counter to toggle led
int statusQuo; // old switch state
};
// initialize an array using the object declaration
LEDBUTTON ledButtons[] { // add switch and led combinatios as you like simply
{A0, 3, 0,false},
{A1, 5, 0,false},
{A2, 6, 0,false},
{A3, 7, 0,false},
};
void setup() {
// the "range based for loop" will save typing work :)
for (auto &ledButton : ledButtons) {
pinMode (ledButton.switchPin, INPUT_PULLUP);
pinMode (ledButton.ledPin, OUTPUT);
}
}
void loop() {
delay (20); // dirty debouncing
// the "range based for loop" will save typing work :)
for (auto &ledButton : ledButtons) {
// read button state
int stateNew = !digitalRead(ledButton.switchPin);
// any changes ?
if (ledButton.statusQuo != stateNew) {
// save state
ledButton.statusQuo = stateNew;
// if button is pressed, than toogle led on/off vs off/on
if (stateNew) digitalWrite(ledButton.ledPin, ++ledButton.counter & 1);
}
}
}