Go Down

Topic: Are these 2 code identical in function ? (Read 1 time) previous topic - next topic

Nov 11, 2012, 12:06 pm Last Edit: Nov 11, 2012, 12:23 pm by stinkyled Reason: 1
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
Code: [Select]
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
Code: [Select]
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);
}

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.
Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

robtillaart

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...
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)


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 :)

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy