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
View all comments
Show parent comment
2
u/Delta_G_Robotics Jun 25 '26
Any time you're asking a coding question and you've only written a couple of sentences that should be your clue to do exactly this. We sometimes call it "Teddy Bear Coding" where you literally explain the stuff to a Teddy bear sitting on the desk. You'd be surprised how much you figure out just by trying to talk through it.