CanSat Tutorials

Tutorial 6 of 9 · Getting data in

Reading inputs: a button and an analogue sensor

Digital in, analogue in, and the difference between a pin that is either on or off and a pin that can read a voltage.

Tutorials 1 2 3 4 5 6 7 8 9

Everything so far has been the board talking. Now it listens. There are two kinds of input pin and the difference between them matters, because it decides which sensors you can use and how.

Digital in

A button, and the pull-up resistor you cannot see

A digital input asks one question: is this pin near 5 volts or near 0 volts. The answer comes back as HIGH or LOW. That is enough for a button, a switch, a tilt sensor or a reed switch, and it is how a master switch tells your CanSat it has been armed.

FromToNotes
One leg of the buttonUno pin 2Any pin from 2 to 13 will do. Not 0 or 1.
The other legUno GNDNo resistor needed, because of INPUT_PULLUP
Why pressed reads LOW

An input pin with nothing connected is floating: it picks up stray electrical noise and reads randomly. INPUT_PULLUP switches on a resistor inside the chip that gently ties the pin up to 5 volts, so an unpressed button reads HIGH. Pressing the button connects the pin straight to ground. Ground pulls far harder than that small internal resistor, so the pin drops to LOW.

It feels backwards, and it is the convention to get used to, because most sensor breakout boards with a digital output work the same way. The alternative is INPUT plus your own 10k resistor to ground, which is more wires for the same result.

Reading a button
// A push button. Pin 2 reads it, pin 8 shows the result.

const int buttonPin = 2;
const int ledPin = 8;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);   // see the explanation below
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int state = digitalRead(buttonPin);

  if (state == LOW) {                 // LOW means pressed, not released
    digitalWrite(ledPin, HIGH);
    Serial.println("pressed");
  } else {
    digitalWrite(ledPin, LOW);
  }

  delay(50);
}

That sketch reports pressed over and over while you hold the button down. Usually you want the moment it was pressed, which means remembering what it was last time round and looking for the change.

Detecting the press itself
// Act on the moment of the press, not on the whole time it is held down.

const int buttonPin = 2;
const int ledPin = 8;

int lastState = HIGH;        // the button starts released
bool ledOn = false;

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

void loop() {
  int state = digitalRead(buttonPin);

  // true only on the pass where it changed from released to pressed
  if (state == LOW && lastState == HIGH) {
    ledOn = !ledOn;
    digitalWrite(ledPin, ledOn);

    if (ledOn) {
      Serial.println("on");
    } else {
      Serial.println("off");
    }

    delay(30);               // crude way to ignore contact bounce
  }

  lastState = state;         // remember for next time round
}
Contact bounce

Metal contacts do not close cleanly. For a few milliseconds a button flickers between open and closed, and a board checking thousands of times a second sees several presses. The delay(30) above hides it crudely, and it also freezes the board for 30 milliseconds, which you now know is a problem. Doing it properly uses millis() and is a good exercise.

Analogue in

Reading a voltage

Six of the Uno's pins, A0 to A5, can measure a voltage rather than just detect one. analogRead() hands back a whole number from 0 to 1023, where 0 means 0 volts and 1023 means 5 volts. That is a 10 bit reading, so each step is about 4.9 millivolts.

FromToWhat it does
Potentiometer outer leg 1Uno 5VTop of the range
Potentiometer outer leg 2Uno GNDBottom of the range
Potentiometer middle legUno A0The wiper: somewhere between the two

No potentiometer? A light dependent resistor works too: LDR from 5V to A0, and a 10k resistor from A0 to GND. That is a voltage divider, and it is how almost every resistive sensor gets read.

Reading a voltage
// Reading a voltage instead of an on or off.

const int sensorPin = A0;

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

void loop() {
  int reading = analogRead(sensorPin);          // 0 to 1023
  float volts = reading * 5.0 / 1023.0;         // turn it into volts
  int percent = map(reading, 0, 1023, 0, 100);  // and into a percentage

  Serial.print(reading);
  Serial.print("\t");
  Serial.print(volts, 3);
  Serial.print(" V\t");
  Serial.print(percent);
  Serial.println(" %");

  delay(200);
}

Line by line

analogRead(sensorPin)
Takes about 100 microseconds and hands back 0 to 1023. No pinMode needed for analogue reads.
reading * 5.0 / 1023.0
Turns the number back into volts. Note 5.0 and not 5, for the reason in tutorial 4. The 5.0 assumes the board really is on 5 volts, which over USB it roughly is and on a battery it may not be.
map(reading, 0, 1023, 0, 100)
Rescales a number from one range to another: 0 to 1023 becomes 0 to 100. Whole numbers only, so it rounds. Useful for turning raw readings into something a human can read.
constrain(x, 0, 100)
Not in the sketch. Clamps a value so it can never leave the range you give. Wrap it round anything you are about to put in a packet.
\t
A tab character, inside the quotes. Lines the output up into columns in the Serial Monitor.
analogWrite(pin, 0..255)
The output version, on the pins marked with a ~. It does not really make 2.5 volts, it switches between 0 and 5 volts very fast, which is enough to dim an LED or drive a motor.

Reference

Which Uno pins are already busy

Not every pin on an Uno is free to use. Some are already busy.

PinsWhat they areCan you use them?
0, 1The USB serial link (RX, TX)No. Wiring anything here breaks uploads and the Serial Monitor.
2 to 13Digital in or outYes. Pin 13 also drives the on-board LED.
3 5 6 9 10 11Marked ~: capable of analogWriteYes, and these are the only ones that can dim or vary.
10 to 13SPI busYes, until you add an SD card or an SPI radio, which need them.
A0 to A5Analogue inputsYes, and they work as ordinary digital pins too.
A4, A5Also the I2C bus (SDA, SCL)Shared. The BMP280 in the next tutorial uses these two.
5V, 3V3, GNDPower outYes. 3V3 on an Uno can only supply about 50 mA.
VIN, RESETPower in, reset lineLeave alone until you know you need them.
5 volts and 3.3 volt parts

The Uno runs its pins at 5 volts. Plenty of modern sensors run at 3.3 volts, including most BMP280 breakouts and every Raspberry Pi Pico. Five volts can damage them. So check the voltage of every part before you wire it in. Most teams who kill a sensor kill it this way, and it is one good reason to pick a 3.3 volt board such as a Pico for the CanSat itself.

Now change it

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

  1. Replace the delay(30) debounce with a millis() based one, so the board never stops. Test it by pressing the button quickly.
  2. Count how many times the button has been pressed and print the running total.
  3. Hold the button down for two seconds to mean something different from a quick tap. What do you need to remember to do that?
  4. Print the raw analogRead value and nothing else, then open the Serial Plotter and move the potentiometer. Save a screenshot: that is evidence of a test.
  5. Cover the LDR with your hand and write down the reading. Shine a phone torch on it and write that down too. Those two numbers are your sensor's useful range.
  6. Work out the smallest change in volts your Uno can actually see. Then look up the accuracy of the sensor you plan to fly. Which one limits you?
  7. Use map() to turn the LDR reading into a number from 0 to 9, and flash the LED that many times. What happens at the ends of the range, and does constrain() help?