Pages: [1]   Go Down
Author Topic: Are these 2 code identical in function ?  (Read 933 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 2
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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:
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);
}
« Last Edit: November 11, 2012, 06:23:45 am by stinkyled » Logged

Massachusetts, USA
Offline Offline
Tesla Member
***
Karma: 208
Posts: 8821
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

Global Moderator
Netherlands
Offline Offline
Shannon Member
*****
Karma: 216
Posts: 13663
In theory there is no difference between theory and practice, however in practice there are many...
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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...
Logged

Rob Tillaart

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

Offline Offline
Newbie
*
Karma: 0
Posts: 2
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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 smiley
Logged

Pages: [1]   Go Up
Jump to: