Arduino toggle push power on off switch

Toggle switches are a type of switches which alternates its output between the two output states, on the same input action. That is each time when you press the button, the output turns on and off alternately.

 In this project, the Arduino toggles the output, for each positive edge triggering at the input pin. A transition of state from LOW to HIGH is called as a Positive edge. That is if the first push ON’s the circuit, then the next push OFF’s the circuit.

The push switch is just giving the trigger pulse to the Arduino, for every pulse the circuit will toggle the state and hold it till the next pulse receives.

arduino toggle switch circuit

Here given a sample code to ON and OFF LED with push button. The input pulse is given to the digital pin 2. To avoid false triggering, a pull-down resistor is connected to the digital pin 2 and the Ground.

The circuit can be modified to operate high power loads with the same toggle switch. For that, instead of an LED, Connect a relay with the Arduino output. Then 230V/110V AC loads or similar loads can be controlled by the circuit.

Arduino toggle switch code

Code 1

const int Switch = 2, LED = 3;
int state = 0, LEDstate=0;

void setup()
{
  pinMode(Switch, INPUT);
  pinMode(LED, OUTPUT);
  Serial.begin(9600);
}
void loop()
{
  if (state == 0 && digitalRead(Switch) == HIGH) {
    state = 1;
    LEDstate=!LEDstate;
  }
  if (state == 1 && digitalRead(Switch) == LOW) {   
    state = 0;
  }
   digitalWrite(LED, LEDstate);
}

 For to run additional codes or to operate devices or module with the toggle switch, use the below code. Place the required code in the code block space shown in the code. The ”Else” state is already true, thus the code placed inside it runs first. The ”if” condition becomes true only on the first pulse. Then the execution of code blocks toggles for the next successive actions.

code 2

const int Switch = 2;
int state = 0, Loadstate=0;

void setup()
{
  pinMode(Switch, INPUT);
}
void loop()
{
  if (state == 0 && digitalRead(Switch) == HIGH) {
    state = 1;
    Loadstate=!Loadstate;
  }
  if (state == 1 && digitalRead(Switch) == LOW) {   
    state = 0;
  }
   if (Loadstate==HIGH){
    // Add Code block
   }
   else{
    //Add Code block
   }
}
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...

Leave a Reply

Your email address will not be published. Required fields are marked *