Keep going¶
Functions¶
Let’s refresh your mind regarding the declaration and use of functions in C/C++.
Create a new project on the mbed development site. Select the same template (“Blinky LED test for the ST Nucleo boards”), but give it a new project name. If you were to select a blank template, you would miss the mbed.h header file that contains many important elements for your code.
Replace the demo code with the code below. What does the select_led function do? If you are intrigued by the expression “t%3”, look for its definition; it is the remainder after division of t by 3, also called modulo.
#include "mbed.h"
// Green LED
DigitalOut led1(LED1);
// Blue LED
DigitalOut led2(LED2);
// Red LED
DigitalOut led3(LED3);
void select_led(int l)
{
if (l==1) {
led1 = true;
led2 = false;
led3 = false;
}
else if (l==2) {
led1 = false;
led2 = true;
led3 = false;
}
else if (l==3) {
led1 = false;
led2 = false;
led3 = true;
}
}
int main() {
int t=0;
while(true) {
select_led(t);
wait(0.5);
t=(t%3)+1;
}
}
Task
Modify the program so that select_led(0) turns all the LEDs off, and select_led(-1) turns them all on.
Change the sequence such that the pattern is {all off, led 1, led 2, led 3, all on, all off, etc.}.
For a more immersive experience, try your code while visiting this page .
Task (optional)
Program a LED sequence inspired by this video clip.