One Circuit, A Thousand Behaviours
The great advantage of digital, programmable electronics over classic electronics now becomes evident: I will show you how to implement many different "behaviours" using the same electronic circuit as in the previous section, just by changing the software.
As I've mentioned before, it's not very practical to have to hold your finger on the button to have the light on. We therefore must implement some form of "memory", in the form of a software mechanism that will remember when we have pressed the button and will keep the light on even after we have released it.
To do this, we're going to use what is called a variable. (We have used one already, but I haven't explained it.) A variable is a place in the Arduino memory where you can store data. Think of it like one of those sticky notes you use to remind yourself about something, such as a phone number: you take one, you write "Luisa 02 555 1212" on it, and you stick it to your computer monitor or your fridge. In the Arduino language, it's equally simple: you just decide what type of data you want to store (a number or some text, for example), give it a name, and when you want to, you can store the data or retrieve it. For example:
int val = 0;
int means that your variable will store an integer number, val is the name of the variable, and = 0 assigns it an initial value of zero.
A variable, as the name intimates, can be modified anywhere in your code, so that later on in your program, you could write: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access