Unit A · From blocks to text
What we are making: a traffic light, written so that the main program reads like a description of a traffic light rather than a wall of pin numbers.
Last year, when a stack of blocks got long, you could wrap it up and give it a name with define. Then you used the name instead of the whole stack.
That is a function, and it was a function all along. In C++ you write it out yourself, and it is one of the most useful things in the entire language.
void means “this function does not hand a value back”. Most of yours will be void.flashRed, stopMotors, readSensor.Here is a traffic light without functions.
And here is the same traffic light with them.
Look at loop() in the second one. Four lines, and it reads like the sequence of
a real traffic light. That is the point of functions: the main program says what
happens, and the fiddly details live somewhere else.
void set(int r, int a, int g) takes three pieces of information, called parameters. They are the white ovals of a block — the numbers you dropped in. You do not have to use parameters this session, but you will want them by March.pedestrian() function that flashes green three times, and call it after green.| What you see | Why | What to do |
|---|---|---|
| 'flashRed' was not declared in this scope | The function is written below where you use it. | Move it above loop(). |
| expected initializer before ... | A missing bracket in the function's first line. | It is void name() { — all four parts. |
| It compiles but nothing happens | You wrote the function but never called it. | Defining it is not using it. Add flashRed(); inside loop(). |
| It runs once and stops | Your code is in setup() rather than loop(). | setup runs once. loop repeats. |
In this session