Often in programming it is useful to make something happen a certain number of times, rather than just go round forever. To do this we use a variable to count how many times something has happened, and a special command called for(){}.
Load Ex1_1_Blink you will edit it to create the program Ex3_1_Blink5Times.
Add the definition for a constant at the beginning (above the setup(){}) of the program to set the ledPin to be 5.
Update the pinMode() and digitalWrite() commands so that they use the constant integer.
Currently, LED 5 will flash on forever until you unplug power, but you will make it flash only 5 times and then stop.
To do this you first need to move the code for flashing the LED from the loop() procedure (where it would happen over and over again), and into the setup() procedure, just after the pinMode() definition (where it will only happen once when we first switch it on or press the reset button), so do this now.
Try uploading the program on your tutorial board and check that the LED only flashes once and then turns off.
You now want to put the digitalWrite() commands inside a for(){} loop so that it runs a certain number of times.
In the setup() function, i.e. after the { and before the }, add the following line of code just after the pinMode() commands and before the first digitalWrite() command:
for(int i=1; i<=5; i++){
After the last delay() add a } to match the { of the for loop and thus close it. You should now have two } at the end of your setup code, one for closing the for(){} loop and one for closing the setup(){} procedure. Your loop(){} procedure will be empty.
Let's look at what this does in stages:
The first statement in the brackets defines a new variable of the integer type called i, and gives it a starting value of 1.
The second statement tells the program to stop this loop when i is no longer less than or equal to 5 (i.e. once it reaches 6).
The third statement is what we call an increment, and this adds 1 to the value in i at the end of each time round the loop. You could also write this as i = i + 1.
So, the first time we get to the for() statement we put 1 into this new variable i, and then we run the code up until the } which flashes the LED once. When we get to the }, we add 1 to the number in i (so it becomes 2) and then we go back and run the code in between the { }s again. When we reach the end we add one and repeat, and so on UNTIL the number in i reaches 6 (no longer <=5) at which point we exit the for() loop (i.e. we move to the next line after the }). In this case, that brings us to the end of the setup() procedure, and since the loop() is now empty, nothing further happens. In essence, i acts as a counting variable.
Upload the program to the tutorial board and see what happens. If you missed it, press stop and then simulate to run the code again.
Don't forget to copy and paste your code into your Lesson #3 programs doc under Ex3_1_Blink5Times: before moving on.
Ex3_2_FadeVariable: Now see if you can figure out how to use it to improve upon one of your other programs. Starting with Ex2_2_CrudeFade modify it to use the counting variable in the for loop to control the brightness. Also, declare a constant before the setup to control the pin on which you are varying the brightness.
Q3.1 Why use a constant and not just a pin number?
To get the effect of CrudeFade, but smoother, replace the code in the loop() procedure with two for() loops. The first should count from 0 to 255 and should simply contain an analogWrite() command followed by a short delay() (say 10ms), where the value used to set the brightness should be the value of your counting variable (probably "i").
The second loop is slightly more complicated as it should count from 255 down to 0 which will require you to make use of i-- instead of i++, but you should be able to figure out how to do that. The contents of that loop will be exactly the same: an analogWrite() followed by a delay.
If you have done it right, when you download it you should find that it does broadly the same as the original, but is much smoother than it was last week, and with far fewer lines of code. Save the new program under Ex3_2_FadeVariable in the Lesson #3 doc.
Now we have seen how a variable can be used to choose which output to control, to select how to control it (e.g. brightness), and also to control the length of a delay. There are many other things variables can do, and many other types as well as just integers. We shall encounter some more as the course progresses.
Ex3_3_ProgressBarVariable: To see just how useful a variable can be, rewrite a couple of the programs you did last week.
First, load up Ex1_2_ProgressBar
Next we're going to replace the code in the setup(){} procedure which defines our OUTPUTs with the following:
for(int i=1; i<=8; i++){
pinMode(i, OUTPUT);
}
Then we're going to replace the code in the loop() procedure with the following two for() loops:
for(int i=1; i<=8; i++){
digitalWrite(i, HIGH);
delay(100);
}
for(int i=1; i<=8; i++){
digitalWrite(i, LOW);
}
Q3.2 Why is there no delay in the second for loop?
Simulate it and make sure it still does what it did before. You have managed to dramatically reduce the number of lines of code required to control all 8 LEDs in turn, simply by using the for() loop! Save the new program under Ex3_3_ProgressBarVariable in the Lesson #3 doc.
Ex3_4_HelloWorld: Sometimes it is useful to get more feedback on what our system is doing than just flashing an LED. The cable that connects our PC to the Arduino can be used to transfer information back to the computer, and display it on our screens. We do this using Serial communication. This means all the data is sent over one wire, one bit at a time.
In order to use Serial, we first have to "initialise" it. We do this in the setup(){} procedure like we did with the outputs.
Start with the blank program
Add the following code in the setup() procedure:
Serial.begin(9600);
delay(500);
This intialises the Serial communication and sets the "baud rate", which is the maximum number of signal changes per second that our system can send. In this application, it is also equal to the "bit rate" which is the actual number of binary digits we send per second. It is important to make sure that the sender and receiver are using the same baud rate, otherwise the message will not be received properly.
Note we have added a delay to give the system time to get the Serial link up and running before sending any data down it.
We are going to check the Serial connection has worked, so we will send the traditional message "Hello World!". Add the following code into the loop() procedure:
Serial.print("Hello World!");
Click the Serial Monitor tab at the bottom of the TinkerCad code window. In the real world this would open up a Serial Monitor program for you to observe the messages that are sent back from the Arduino to the PC. If you Simulate the program you should see your message appear.
You will notice that LED 1 is always on when Serial communication is active. This is because it is actually the pin down which data travels to the PC, and the line is held high when no data is being sent. You might even see it flashing when the message gets sent.
There are two commands for sending data to the PC, Serial.print() and Serial.println(). The only difference is that Serial.println() adds a new line character at the end of the message.
See what happens when you run your code. Now change the Serial.print() to Serial.println(), clear the Serial Monitor and run it again to see the difference. We will make use of both of these commands to make more complex messages.
Save the new program under Ex3_4_HelloWorld in the Lesson #3 doc.
Ex3_5_Blink5TimesSerial: This ability to send messages to the computer screen can be really useful when you are trying to work out what a program is doing, and especially why it isn't working. Adding statements like Serial.println("You got to ... stage") can be key to identifying where exactly in your code things are going awry.
We're going to try this by adding a message to one of our previous programs to let us know how it's getting on.
Load up Ex3_1_Blink5Times.
Add the Serial.begin(9600) statement at the start of the setup() procedure, and a delay() of 500ms.
Now add the following lines towards the end of the for() loop (i.e. within the curly brackets), and just before the last delay(1000):
Serial.print("I have flashed the bulb ");
Serial.print(i);
Serial.println(" times.");
Notice how we are building up a message in three parts, and ending the whole thing with a new line.
We are also using the Serial.print() command to display the value of a variable, using the Serial.print(i) line.
Upload the program and open up the Serial Monitor. You might want to clear the Serial Monitor at this point.
Finally, save the new program under Ex3_5_Blink5TimesSerial in the Lesson #3 doc.
Now move on to lesson 4: analogue inputs.