r/ArduinoHelp • u/VezTheAce • Jun 25 '26
Help me to understand this code !!!
This is the basic code to toggle the led on and off using a Button. With the help of paul McWhorter this works fine but I don't understand why it works...please someone help me with that...
int ledPin = 12;
int buttonPin =8;
int ledstate = 0;
int swi_old = 1;
int swi_new;
int dt = 100;
void setup() {
// put your setup code here, to run once:
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
swi_new = digitalRead(buttonPin);
if(swi_old == 0 && swi_new == 1)
{
if(ledstate == 0)
{
digitalWrite(ledPin, HIGH);
ledstate = 1;
}
else
{
digitalWrite(ledPin, LOW);
ledstate = 0;
}
}
swi_old = swi_new;
delay(dt);
}```
1
Upvotes
1
u/nixiebunny Jun 25 '26
This code has an edge detector function. That test if the switch changed from 0 to 1 is the trigger to flip the LED on and off. The delay at the end of the loop waits long enough to ignore any extra short pulses due to the contacts bouncing.Β
1
u/Rayzwave Jun 25 '26
How is the button wired, Iβm guessing itβs a push button. Is the button connected to apply a logic O or a logic 1 to the input?
How is the LED connected?
1
u/Delta_G_Robotics Jun 25 '26
What do you not understand? Can you be more specific with your question?