CanSat Tutorials

Tutorial 5 of 9 · Making the board decide

Decisions, loops and your own functions

Making the board choose, making it repeat, and splitting a sketch into named pieces you can test one at a time.

Tutorials 1 2 3 4 5 6 7 8 9

Three ideas here, and between them they cover most of what flight software actually does: choosing, repeating, and splitting a job into named pieces.

Choosing

if, else if and else

So far every sketch has done the same thing every time round. Real flight software has to choose: is the sensor responding, are we still on the launch pad, has a second passed, is this reading believable. All of that is built from if.

if, else if, else
// A chain of decisions. The board tries them in order and takes
// the first one that is true, then skips the rest.

int count = 0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  count++;

  if (count % 10 == 0) {               // remainder is zero: exactly divisible
    Serial.print(count);
    Serial.println("   every tenth");
  } else if (count % 2 == 0) {
    Serial.print(count);
    Serial.println("   even");
  } else {
    Serial.print(count);
    Serial.println("   odd");
  }

  delay(300);
}

Line by line

if (something) { ... }
Run the block in the brackets only when the test in the round brackets is true. If it is false, skip the whole block.
else if (...) { ... }
Only tried when the earlier tests were all false. You can chain as many as you like.
else { ... }
Run this when none of the tests above were true. Optional, but usually useful, so you notice the cases you did not expect.
count % 10 == 0
% gives the remainder. count % 10 is zero only when count divides exactly by ten, which is a neat way to do something every tenth pass.
TestTrue when
a == ba is equal to b. Two equals signs.
a != ba is not equal to b
a > b, a < bGreater than, less than
a >= b, a <= bGreater than or equal to, less than or equal to
a && bBoth a and b are true
a || bEither a or b is true, or both
!aa is false
One equals sign versus two

= puts a value into a box. == asks whether two things are the same. So if (count = 10) does not test anything: it sets count to 10 and then treats 10 as true, so the block always runs. It compiles cleanly, which is what makes it nasty. If your condition is always true, check this first.

Repeating

for and while loops

loop() repeats forever. Sometimes you want to repeat a known number of times and then move on: flash a status light five times, read a sensor sixteen times and average the results, step through a list of readings.

A for loop
// Do something a known number of times.

const int ledPin = 8;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);

  for (int i = 1; i <= 5; i++) {
    Serial.print("flash ");
    Serial.println(i);

    digitalWrite(ledPin, HIGH);
    delay(100);
    digitalWrite(ledPin, LOW);
    delay(200);
  }

  Serial.println("done");
}

void loop() {
}

Line by line

for (int i = 1; i <= 5; i++)
Three parts separated by semicolons. Start with i as 1. Keep going while i is 5 or less. After each pass, add one to i.
i
Just a variable name, traditionally i for index. It exists only inside the loop. Programmers usually count from 0, as in for (int i = 0; i < 5; i++), which also runs five times.
while (test) { ... }
Not in this sketch. Repeats as long as the test stays true, with no counter. Use it when you do not know how many times, for example while (!bmp.begin()). Be careful: if the test never becomes false the sketch hangs there.
break;
Jump straight out of the loop you are in. continue; skips the rest of this pass and starts the next one.

Your own commands

Writing and using functions

setup() and loop() are functions the Arduino library calls for you. Nothing stops you writing your own, and you should. A function lets you name an idea, test it on its own, and use it from several places without copying the code.

Three functions of your own
// Writing your own commands.

const int ledPin = 8;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);

  flash(ledPin, 3, 100);     // three quick flashes means "starting up"
  flash(ledPin, 1, 800);     // one long flash means "ready"

  Serial.println(packetsInDescent(30, 1));
  Serial.println(packetsInDescent(40, 2));
  Serial.println(toVolts(512), 3);
}

void loop() {
  flash(ledPin, 2, 60);      // a heartbeat, twice a second
  delay(2000);
}

// Hands nothing back. Three values go in.
void flash(int pin, int times, int ms) {
  for (int i = 0; i < times; i++) {
    digitalWrite(pin, HIGH);
    delay(ms);
    digitalWrite(pin, LOW);
    delay(ms);
  }
}

// Hands back a whole number.
int packetsInDescent(int seconds, int perSecond) {
  return seconds * perSecond;
}

// Hands back a decimal.
float toVolts(int reading) {
  return reading * 5.0 / 1023.0;
}

Line by line

void flash(int pin, int times, int ms)
The line that declares a function. void is what it hands back, here nothing. flash is the name you choose. The three things in brackets are parameters: names for the values you pass in when you call it.
flash(ledPin, 3, 100);
Calling it. The values line up with the parameters in order: pin becomes 8, times becomes 3, ms becomes 100.
int packetsInDescent(...)
Starts with int, not void, so it hands an int back to whoever called it.
return seconds * perSecond;
Works out the answer, hands it back, and leaves the function immediately. Anything after a return never runs.
Order in the file
The Arduino IDE quietly sorts this out for you, so a function can be used above where it is written. In plain C++ you would have to declare it first. Useful to know if you ever move the code into another tool.
This is what the PDR means by modules

The report asks you to name your software modules: sensing, telemetry, data storage, and so on. Functions are how those boxes on your block diagram become real. If your diagram has a box called read sensors, your sketch should have a function called something like readSensors(), and the person who drew the diagram can check it exists.

It also makes testing honest. A function with a clear input and output can be tested on the bench on its own, which gives you a pass criterion to write down.

Now change it

Change one thing at a time, upload, and watch what the board does.

  1. Change the chain so it prints every third as well. Where in the chain does that test have to go, and why does the order matter?
  2. Swap count % 10 == 0 for count % 10 = 0 and read the error message carefully. Now try if (count = 10) instead, which compiles. What happens?
  3. Rewrite the five flashes using a while loop instead of a for loop. Which reads better to you?
  4. Write a function bool isBelievable(float pressurePa) that hands back true only when the pressure is somewhere between 30,000 and 110,000 pascals. Why might a CanSat want that?
  5. Write float descentRate(float startAltitude, float endAltitude, float seconds). Test it with numbers where you already know the answer.
  6. Add a function void heartbeat() with no parameters that flashes the LED once, and call it from loop().
  7. Make flash refuse to do anything if times is zero or negative. Should it print a complaint, or stay silent? Which is better in flight?