basic help on timing a blinking led

Hi folks, I’ve a basic question.
before writing this post I browse the forum but I didn’t find something similar to my question.
I hope not to bore you with my basic problem.
I’m using the Arduino IDE for the first time but I can’t understand clearly the behavior of the micro-controller.
I wrote the classical code for blinking a led :

//THIS CODE WORKS !!
void setup() {
pinMode(5,OUTPUT); }

void loop() {
digitalWrite(5,HIGH);
delay(1000);
digitalWrite(5,LOW);
delay(1000);
}

Then I decided to make the led flashing just five times - in the previous example the led flash forever.
Here how I modified the code:

//THIS CODE DOES NOT WORK !!
int counter = 0;

void setup() {
pinMode(5,OUTPUT); }

void loop() {
if(counter < 5)
{
digitalWrite(5,HIGH);
delay(1000);
digitalWrite(5,LOW);
delay(1000);
}
counter = counter +1;
}

PROBLEM : The led flash forever instead of flashing just five times, WHY ???

I made some experiments, I found a workaround but I do not understand the behavior of the Arduino environment. I print out on the serial port the value of the var counter, and actually i saw counter running but the led didn’t stop after 5 counts.

here the workaround i tried:

//THIS CODE, with the workaround, WORKS !! - but… WHY ???
int counter = 0;

void setup() {
pinMode(5,OUTPUT); }

void loop() {
if(counter < 5)
{
digitalWrite(5,HIGH);
delay(1000);
digitalWrite(5,LOW);
delay(1000);
}
counter = counter +1;
delay(15);
}

WHY adding delay(15) the code works ??
Thanks a lot for some explanation about the functioning of the Arduino code.

It also doesn't work, it just doesn't work a bit more slowly.

Get a pencil and paper and work it through.

Always show us your ‘current’ compete sketch. Use CTRL T to format the sketch. Please use code tags. Use the </> icon in the posting menu.

[code]Paste sketch here. [/code]

Try this:

int counter = 0;

void setup()  
{
  pinMode(5,OUTPUT);  
}

void loop()  
{   
if(counter < 5) 
  {
    digitalWrite(5,HIGH);    
    delay(1000);                
    digitalWrite(5,LOW);   
    delay(1000);    
    counter = counter +1;      
   }
         
}

What range of numbers can be represented by 'type' int

larryd:
What range of numbers can be represented by 'type' int

And, what happens when you try to store a value outside that range?

These are things you absolutely MUST know.

Think about how you might do something 5 times only. What would your process look like? Specifically, what would you count? What are you counting now? Are they the same thing?

Here's a hint. What you are counting and what you should be counting are NOT the same thing.