Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //*********************************************
- //* Arduino Toggle Switch *
- //* learnelectronics 28 June 2020 *
- //* *
- //* www.youtube.com/learnelectronics *
- //* email: arduino0169@gmail.com *
- //* *
- //*********************************************
- int switchPin = 2; // Button Pin2 one side 5V, opposite to GND through 10K resistor
- int led1Pin = 8; // 1st LED on pin8
- int led2pin = 9; // 2nd LED on pin9
- int val; // Read instantanious pin value
- int val2; // Read delayed value
- int buttonState; // Hold the button Value
- int Mode = 0; // keep track of which LED is on
- void setup() {
- pinMode(switchPin, INPUT); // Set the switch pin as input
- pinMode(led1Pin, OUTPUT); // Set LED1 as output
- pinMode(led2pin, OUTPUT); // Set LED2 as output
- buttonState = digitalRead(switchPin); // read the initial state
- }
- void loop(){
- val = digitalRead(switchPin); // read button value and store it in val
- delay(10); // wait 10mS and see if button is still on
- val2 = digitalRead(switchPin); // read the input again to check for bounces
- if (val == val2) { // make sure we got 2 consistant readings!
- if (val != buttonState) { // the button state has changed!
- if (val == LOW) { // check if the button is pressed
- if (Mode == 0) {
- Mode = 1;
- } else {
- if (Mode == 1) {
- Mode = 0;
- }
- }
- }
- }
- buttonState = val; // save the new state in our variable
- }
- // Switch LED according to mode
- if (Mode == 0) {
- digitalWrite(led1Pin, HIGH); //LED1 On
- digitalWrite(led2pin, LOW); //LED2 Off
- }
- if (Mode == 1) {
- digitalWrite(led1Pin, LOW); //LED1 Off
- digitalWrite(led2pin, HIGH); //LED2 On
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement