Counters

How to Make Counters?

We can use counters to break our code into steps inside of void loop. This way we can have our code broken up in to simple steps. To do this we will have a variable to keep track of our current step. Then we will use a series of if statements to have each of our steps. Then at the end of each step we will have it change the counter to move on to the next step.

```int counter = 0;

void setup()
{

}

void loop()
{
if (counter == 0)
{
// code for step 1
counter = 1;
}
else if (counter == 1)
{
// code for step 2
counter = 2;
}
else if (counter == 2)
{
// code for step 3
counter = 3;
}
}```

Each time through the loop this code will do the next step in the process. If you would like it to not always move on to the next step you can have the changing of the counter value inside of another if statement so that it will not change to the next step until the condition is met.

```int counter = 0;

void setup()
{

}

void loop()
{
if (counter == 0)
{
// code for step 1

if (condition1)
{
counter = 1;
}
}
else if (counter == 1)
{
// code for step 2

if (condition2)
{
counter = 2;
}
}
else if (counter == 2)
{
// code for step 3

if (condition3)
{
counter = 3;
}
}
}```

This way it will not move on to the next step until the condition for that step is met.

Here is an example code for using counters to move through a three step program.

```int counter = 0;

void setup()
{
Serial.begin(9600);
}

void loop()
{
if (counter == 0)
{
Serial.println("first step");
counter = 1;
}
else if (counter == 1)
{
Serial.println("second step");
counter = 2;
}
else if (counter == 2)
{
Serial.println("third step");
counter = 3;
}
}```

This will have it print out this:

first step

second step

third step

Then it will not keep repeating, since there is no step for when counter is equal to 3.