My ?: Why does the FOR behave this way, or am I incorrect in my conclusion?
Specifically: Ending the for loop with a "<" as opposed to an "="
This is my first Arduino Program, so pardon my ignorance. I am simply toying around with the first project in Massimo Banzi's "Getting Started with Arduino", (i.e., push a button and an LED lights up and then turns off), very simple. I decided to have some fun with the code and make the LED blink according to the Fibonacci sequence (i.e., 1 1 2 3 5 8 ...) and here's what tripped me up:
Normally a "For" statement works according to lets say for example n=1 to n=100, but I found that if you want to loop 100 times in this language you would use n=0 to n<100. In my code below, if you track to the For loop, you will see the version that works. The one where I ended the loop when the counter is less than the current Fib number, also starting the count at zero. Starting it at one and ending when it equaled the current Fib resulted in an endless loop of blinking LED. I don't comprehend how that woulkd be possible.
//example 2Mod: turn on led while the button is pressed and LED will successively blink out the Fibonnaci Serquence
const int LED = 13; // LED connected to
const int BUTTON = 7;
int val = 0;
int fib2 = 0;
int fib1 = 1;
int fib = 1;
void setup() {
pinMode(LED,OUTPUT);
pinMode(BUTTON,INPUT);
}
void loop() {
val = digitalRead(BUTTON);
if(val==HIGH){
if(fib==1){digitalWrite(LED,HIGH);
delay(100);
digitalWrite(LED,LOW);
delay(100);}
else{for(int n = 0; n < fib; n=n+1){
digitalWrite(LED,HIGH);
delay(100);
digitalWrite(LED,LOW);
delay(100);}}
fib = fib1 + fib2;
fib2 = fib1;
fib1 = fib;}
else{digitalWrite(LED,LOW);}
}