Blink does not remember anything. Everything useful does: a packet count, the last reading, the time the last transmission went out. This tutorial is about where a sketch keeps numbers, what it can do with them, and how to make something happen once a second without freezing the board.
Variables
Boxes with labels, and why the kind matters
A variable is a labelled box in the board's memory. You say what kind of thing goes in it, you give it a name, and from then on the name stands for whatever is inside.
You have to say what kind, because an Uno has only 2 KB of memory and it needs to know how much room to set aside. A whole number takes two bytes, a decimal takes four, a true or false takes one. On a board that small, those bytes count. Picking the wrong type is one of the most common reasons a sketch stops working halfway through a flight.
// Four kinds of box, and what goes in each.
int packetCount = 0; // whole numbers
float temperature = 21.5; // numbers with a decimal point
bool sensorReady = false; // true or false, nothing else
unsigned long upTime = 0; // big whole numbers, never negative
void setup() {
Serial.begin(9600);
packetCount = packetCount + 1;
temperature = temperature + 0.5;
sensorReady = true;
upTime = millis();
Serial.print("packet ");
Serial.println(packetCount);
Serial.print("temperature ");
Serial.println(temperature);
Serial.print("ready ");
Serial.println(sensorReady);
Serial.print("up for ");
Serial.print(upTime);
Serial.println(" ms");
}
void loop() {
}
| Type | Holds | Range on an Uno | Use it for |
|---|---|---|---|
bool | true or false | 2 values, 1 byte | Flags: has the sensor started, is the LED on |
byte | Small whole number | 0 to 255 | Packing data tightly for a radio |
char | One character | -128 to 127 | A single letter or a command code |
int | Whole number | -32,768 to 32,767 | Counters, pin numbers, analogRead results |
unsigned int | Whole number, never negative | 0 to 65,535 | When you need a bit more headroom |
long | Big whole number | about ±2.1 billion | Pressure in pascals, large counts |
unsigned long | Big, never negative | 0 to about 4.29 billion | Anything from millis(). Always. |
float | Decimal number | about 7 digits of precision | Temperature, volts, altitude |
String | Text | As much as you have spare | Messages. Use sparingly, see the warning below. |
On an Uno an int stops at 32,767. Air pressure in pascals is around 101,325, so int pressure = 101325; silently produces nonsense. Use long or float. On a Pico or an ESP32 an int is twice as wide, so the same line works there. Differences like that are why code can behave differently when you change boards.
String is easy and expensive. Every time you join Strings together the board carves up its tiny memory a little more, and after a few thousand packets it can run out and freeze. In flight software, print the pieces separately or use a fixed char array.
Arithmetic
Doing sums, and the one that always goes wrong
| Operator | Means | Example |
|---|---|---|
+ - * / | Add, subtract, multiply, divide | total = a + b; |
% | Remainder after dividing | 7 % 3 is 1. Useful for "every nth time". |
= | Put the value on the right into the box on the left | count = 0; |
++ | Add one | count++; is shorthand for count = count + 1; |
+= | Add to what is already there | total += reading; |
! | Not. Flips true and false | ledOn = !ledOn; |
The one that catches people is division. If both numbers are whole numbers, the board does whole number division and throws the remainder away without mentioning it.
// The trap that catches everyone at least once.
void setup() {
Serial.begin(9600);
int a = 5;
int b = 2;
Serial.println(a / b); // 2 whole number division
Serial.println(5.0 / 2); // 2.50 one decimal is enough
Serial.println((float)a / b); // 2.50 force a to be decimal
int reading = 512;
Serial.println(reading * 5 / 1023); // 2
Serial.println(reading * 5.0 / 1023.0); // 2.50
}
void loop() {
}
So 5 / 2 is 2, not 2.5. To get a decimal answer, at least one side has to be a decimal. Writing 5.0 instead of 5 is enough. (float)a is called a cast and means "treat a as a decimal just for this sum".
This matters the moment you turn a sensor reading into a real world value. Converting an analogRead result into volts, or pascals into an altitude, both mean division. A flight log full of 2 where you expected 2.5 is the kind of mistake you only catch by printing the number and looking at it.
If a number should never change while the sketch runs, say so: const int ledPin = 8;. The compiler then stops you writing to it by accident and does not set aside memory for it. Use it for pin numbers, calibration values and limits.
Timing
millis(), and getting rid of delay()
delay(1000) is a dead stop. For one second the board does nothing but count. The alternative is to stop stopping, and instead keep asking "has it been a second yet?" while getting on with other things.
millis() hands back the number of milliseconds since the board powered up. It just keeps climbing. You cannot set it, and you do not need to. You store the time you last did something, then compare.
// Two jobs at two different speeds, and neither one blocks the other.
// Flash an LED every 250 ms. Report uptime every 1000 ms.
int ledPin = 8;
unsigned long lastFlash = 0; // when the LED last changed
unsigned long lastReport = 0; // when we last printed
bool ledOn = false;
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
unsigned long now = millis(); // how long since power up
if (now - lastFlash >= 250) { // 250 ms gone?
lastFlash = now; // remember when
ledOn = !ledOn; // flip true to false, or back
digitalWrite(ledPin, ledOn);
}
if (now - lastReport >= 1000) { // a whole second gone?
lastReport = now;
Serial.print("up for ");
Serial.print(now / 1000);
Serial.println(" s");
}
}
Line by line
unsigned long now = millis();- Read the clock once, at the top, and use the same value for every check below. Calling
millis()several times in one pass means slightly different answers each time. now - lastFlash >= 250- "Has at least 250 milliseconds passed since the last flash?" Note it is
>=and not==: the board may be busy and come back late, and==would miss the exact moment and then wait forever. lastFlash = now;- Reset the stopwatch. Forget this line and the condition stays true forever, so it runs every pass.
ledOn = !ledOn;- Flip a true to a false or a false to a true. Two lines of state instead of two
digitalWritecalls and two delays. unsigned long, notintmillis()passes 32,767 after 33 seconds. Store it in aninton an Uno and your timer breaks half a minute into the flight.
The primary mission is to measure temperature and pressure during the descent and send them once per second. The descent lasts roughly 20 to 40 seconds, so you get 20 to 40 packets and no second chances. Meanwhile you may also want to log to a card, flash a beacon, watch for a command and read a second sensor. Built out of delay() calls, those jobs block each other. Built out of millis() checks, they take turns, and none of them has to wait.
millis() wraps round to zero after about 49.7 days. No flight lasts that long. Subtracting two unsigned long values stays correct across the wrap anyway, which is one more reason to use the right type.
Now change it
Change one thing at a time, upload, and watch what the board does.
- Change the flash interval to 60 ms and the report interval to 2000 ms. Did either change affect the other?
- Add a third job: print the word
tickevery 5 seconds. How many lines did it take? - Keep a running total of how many times the LED has flashed, and print it with the uptime.
- Store
millis()in anintinstead of anunsigned longand leave it running for a minute. Write down what happens and why. - Work out the average of the last ten numbers you print. You will need somewhere to keep ten numbers.
- Track the highest and lowest value of something that changes. Which variables do you need, and what should they start at?
- Print a temperature of
21.456789to 1, 3 and 5 decimal places. How many of those digits do you think a real sensor can justify?