Sketch 1
int led = 4; void setup() { pinMode (led,OUTPUT); } void loop() { digitalWrite (led, HIGH); delay(500); digitalWrite (led, LOW); delay(500); digitalWrite (led, HIGH); delay(500); digitalWrite (led, LOW); delay(500); digitalWrite (led, HIGH); delay(500); digitalWrite (led, LOW); delay(500); digitalWrite (led, HIGH); delay(500); digitalWrite (led, LOW); delay(500); digitalWrite (led, HIGH); delay(500); digitalWrite (led, LOW); delay(500); delay(3000); } |
The above sketch seems too long and you might think it probably does a very complicated task. Well, it although it seems like that but it only turns a led on and off 5 times then wait for 3 seconds and it starts the task all over again. You can do the same task with less code by using a "for" statement.
Sketch 2
int led = 4; int i; void setup() { pinMode (led,OUTPUT); } void loop() { for (i=0; i<5; i++){ digitalWrite (led, HIGH); delay(500); digitalWrite (led, LOW); delay(500); } delay(3000); } |
Now you can see that sketch 2 looks very nice and tidy and does exact same task as sketch 1, this is the miracle of the for statement. Let me explain about it a bit.
for (i=0; i<5; i++){
digitalWrite (led, HIGH);
delay(500);
digitalWrite (led, LOW);
delay(500);
}
Three thing are going on in the brackets after the for ().
i=0; "i" is a reference point of something that you want it to start from. For example: If you write i=3 that means you want the code between the two yellow curly brackets to run from number three. So if your code is (i=3; i<10; i++) so it will run 7 times only and not 10 times.
Note:
Remember after reaching the maximum number it will only ignore that particular for statement and it will continue to run other codes.
One last sketch I want to finish this post with.
Sketch 3
int led = 4; int i; void setup() { pinMode (led,OUTPUT); for (i=0; i<10; i++){ digitalWrite (led, HIGH); delay(500); digitalWrite (led, LOW); delay(500); } } void loop() { } |
The sketch 3 is very helpful when you trying to run a code for certain amount of times then turn it off until you click the reset button and turn it on again.
That's all for this post I hope you've fund it helpful. :)
No comments:
Post a Comment