Are these 2 code identical in function ?

Hi everyone , I am so new to arduino that I could not tell what is the difference between these 2 codes , code 2 is written by me but it doesn't have the solid feel as code 1.
Can you please take a look ?

Code 1

const int LED = 13; // the pin for the LED
const int BUTTON = 7; // the input pin where the
// pushbutton is connected
int val = 0; // val will be used to store the state
// of the input pin
int old_val = 0; // this variable stores the previous
// value of "val"
int state = 0; // 0 = LED off and 1 = LED on
void setup() {
pinMode(LED, OUTPUT); // tell Arduino LED is an output
pinMode(BUTTON, INPUT); // and BUTTON is an input
}
void loop(){
val = digitalRead(BUTTON); // read input value and store it
// yum, fresh
// check if there was a transition
if ((val == HIGH) && (old_val == LOW)){
state = 1 - state;
delay(10);
}
old_val = val; // val is now old, let's store it
if (state == 1) {
digitalWrite(LED, HIGH); // turn LED ON
} else {
digitalWrite(LED, LOW);
}
}

Code 2

const int led =13;
const int button =7;
int state = 0;

void setup()
{
   pinMode(led,OUTPUT);
   pinMode(button,INPUT); 
}

void loop()
{
   if(digitalRead(button))
     {
       delay(10);
       state = 1-state;
     }

     if(!state)
     digitalWrite(led,LOW);
     else
      digitalWrite(led,HIGH);
}

Not quite. Code 1 will toggle the LED once, each time the button is pushed. Code 2 will toggle the LED at about 100 times per second as long as the button remains pressed.

When comparing code you must be the compiler

  • strip of the comments
  • variable names only need to be distinct
  • fill in the #defines/macros
  • then start comparing...

johnwasser:
Not quite. Code 1 will toggle the LED once, each time the button is pushed. Code 2 will toggle the LED at about 100 times per second as long as the button remains pressed.

Awesome !! thank you for pointing that out :slight_smile: