Turning on the lamp

In this project, we’ll turn a lamp on through the Mosfet Nanoshield and introduce a programming structure called for.

!Important Information

For this project we are going to learn how to use the for command. This is a peculiar repetition structure, made of four basic elements: initialiser, validator, consequence and incrementer.

To explain each one of them, the easiest way is through an example:

You have to make a cake and you need 10 eggs – this is you stop condition (up to where you want to go). However, you have only 2 eggs – this is your initialiser (what you already have). You then go to the farm and start to collect eggs – this is your consequence, or what you are going to do to reach the goal. For each egg collected, you check if you already have 10 eggs total – this is the validator, that checks if you have reached your stop condition. After collecting each egg, you increment the egg counting - this is the incrementer.

We also need to understand the lamp connection. It is connected through the Mosfet Nanoshield, which makes it possible to use the pin D3, D5, D6 or D9 to turn it on. To select the desired pin, you just have to change the jumper position! Check it out on the image below:

Mosfet Jumper

For this experiment, we will use the pin D3, which is the way the Mosfet Nanoshield comes configured. That is, you don’t need to change the jumper.

!Identifying the Components

Jumper Position

!Code Components

The command for has the following anatomy:

for(initialiser; validator; incrementer) 
{
  Lines of code that refer to the consequence
}

The validator is any declaration that can be evaluated as true or false.

!Running on Arduino

The code below will make the lamp blink 10 times with a certain time interval, and then 10 times with another time interval.

int lamp = 3;

int button = A0; 


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


void loop() 
{ 
for (int i = 0; i < 10; i++)
    {
      digitalWrite(lamp, HIGH);
      delay(200);
      digitalWrite(lamp, LOW);
      delay(100);
    }
    
delay(1000);

for (int k = 0; k < 10; k++)
    {
      digitalWrite(lamp, HIGH);
      delay(600);
      digitalWrite(lamp, LOW);
      delay(600);
    }

delay(1000);

}

!Your Turn!

Try modifying the code above using for so that 3 different musical notes are played, 10 times each.

Answer

int buzzer = 5;

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


void loop() 
{ 
for (int i = 0; i < 10; i++)
    {
            tone(buzzer,261);            
            delay(200);
            noTone(buzzer); 
    }
    
delay(1000);

for (int k = 0; k < 10; k++)
    {
            tone(buzzer,329);            
            delay(200);
            noTone(buzzer); 
    }

delay(1000);

for (int m = 0; m < 10; m++)
    {
            tone(buzzer,392);            
            delay(200);
            noTone(buzzer); 
    }

delay(1000);

}