Unit A · From blocks to text
What we are making: the button-and-LED circuit from Level 1, written so that changing a pin means changing one word, not six.
You used variables last year — the orange blocks, the score in your game. A variable is a box with a name that holds a value.
In C++ there is one extra step: you have to say what kind of thing the box holds
before you use it. That is what int means — a whole number.
| In blocks | In C++ | Worth knowing |
|---|---|---|
| set x to 5, first time | int x = 5; | int means it holds a whole number |
| set x to 5, after that | x = 5; | no int — the box already exists |
| change x by 1 | x = x + 1; | read it, add one, put it back |
| a box for decimals | float t = 21.5; | float holds numbers with a point in them |
| a yes/no box | bool ready = true; | bool holds only true or false |
int ledPin = 9; the first time, and just ledPin = 9; after that. Saying int twice is like telling somebody your name twice in one sentence — the compiler will object.Look at this program. The number 9 appears three times.
Now move the LED to pin 6. You must find and change all three, and if you miss one the program still compiles perfectly and simply does not work. That bug is genuinely hard to find because nothing is wrong with the code — it is just about a different pin.
ledPin is good. x is bad. You will read this code again in March and x will mean nothing to you.digitalRead asks the pin what it is seeing and puts the answer in the box.== compares. = assigns. This catches everybody, including professionals.= means 'put this in the box'. == means 'is this the same as that?' Writing if (x = 5) puts 5 in x and then always runs the if. It compiles without a single warning and behaves very strangely.int count = 0; at the top and make it count presses. Print the count with Serial.println(count);.In this session