Skip to content

Week 09: Input Devices

Assignment:

  • Group: probe an input device's analog levels and digital signals.
  • Individual: measure something: add a sensor to a microcontroller board that you have designed and read it.

Group assignment

Our group work for this week is documented on the RIIDL Fab Lab group page: Week 9: Input Devices.

What I learned: we tested the signals of two distance sensors that talk to the microcontroller in different ways. The HC-SR04 ultrasonic sensor uses plain digital signals: a short trigger pulse goes in, and the sensor answers with an echo pulse whose length depends on the distance. The VL53L0X time-of-flight sensor instead communicates over I²C, so the distance arrives as data on the SDA/SCL lines rather than as a pulse to time. Seeing both showed me that "reading a sensor" can mean timing a pulse or talking to it over a bus, and that this choice affects the wiring, the code and the libraries needed.

Individual assignment: HC-SR04 on my own board

For the individual assignment I connected an HC-SR04 ultrasonic sensor to the XIAO RP2040 board I designed and milled (Week 6, Week 8) and read the distance over USB serial. This is the same sensor my final project uses to detect a hand bringing an object to the gripper.

HC-SR04 on the breadboard, wired to my milled XIAO RP2040 board, with my hand in front of the sensor

Wiring

HC-SR04 XIAO RP2040
VCC 5V
GND GND
TRIG D4
ECHO D6, through a voltage divider

Voltage divider: HC-SR04 ECHO → 1 kΩ → D6, and D6 → 2 kΩ → GND.

The HC-SR04 runs on 5 V, and its ECHO pin outputs a 5 V pulse. The RP2040's pins are 3.3 V only and can be damaged by 5 V, so the divider scales the pulse down: 5 V × 2 kΩ / (1 kΩ + 2 kΩ) ≈ 3.3 V. TRIG doesn't need a divider, because the 3.3 V pulse from the XIAO is high enough for the sensor to read.

Close-up of my board wired to the sensor and the divider on the breadboard

How the sensor is read

  1. The XIAO sends a short 10 µs pulse on TRIG.
  2. The sensor sends out a burst of ultrasound and holds ECHO high until the echo comes back.
  3. The XIAO measures how long ECHO stays high and converts that time into distance: distance (cm) = time (µs) × 0.0343 / 2. 0.0343 cm/µs is the speed of sound, and the result is halved because the sound travels to the object and back.

If no echo comes back in time, nothing is in range, and the serial output says so instead of printing a wrong distance.

Code

pulseIn() waits for ECHO to go high and returns how long it stayed high, in microseconds. The 30 ms timeout (about 5 m of travel) stops the loop from hanging when there is no echo; in that case it returns 0 and the sketch prints "Out of range / No echo". A new reading is taken every 200 ms.

Code: hcsr04_distance.ino

#define TRIG_PIN D4
#define ECHO_PIN D6

void setup() {
  Serial.begin(115200);

  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);

  digitalWrite(TRIG_PIN, LOW);
  delay(500);
}

void loop() {
  // Send ultrasonic trigger pulse
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);

  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // Read echo duration (timeout: 30 ms)
  unsigned long duration = pulseIn(ECHO_PIN, HIGH, 30000);

  if (duration == 0) {
    Serial.println("Out of range / No echo");
  } else {
    // Convert echo duration into distance
    float distance = duration * 0.0343 / 2;

    Serial.print(distance, 1);
    Serial.println(" cm");
  }

  delay(200);
}

Result

Serial Monitor showing distance readings between 9.1 and 12.2 cm

Parameter Observation
Sensor HC-SR04 ultrasonic sensor
Microcontroller My custom XIAO RP2040 board
Serial output Distance in centimetres
Observed range 9.1–12.2 cm, with my hand held in front of the sensor
Status Continuous readings received

The readings vary by a centimetre or two while my hand is held in front of the sensor, because a hand is not a flat, still target and the sensor's beam spreads out in a cone. When nothing is in front of the sensor, the output shows "Out of range / No echo". This variation is something I need to allow for in the gripper, by choosing a trigger distance with some margin rather than an exact value.

Accuracy check with a ruler

To check how accurate the readings are, I laid a steel ruler against the front of the sensor and held a flat object (my phone) upright at 10, 20 and 30 cm, recording the Serial Monitor at each distance.

Phone held at 10 cm on the ruler in front of the HC-SR04

Ruler distance Sensor readings Most common reading Error
10 cm 9.0–10.0 cm 10.0 cm 0 to −1.0 cm
20 cm 18.7–20.4 cm 19.2 cm about −0.8 cm
30 cm 29.6–31.7 cm about 30 cm −0.4 to +1.7 cm

Serial Monitor readings with the object at 20 cm

Object at 30 cm on the ruler

The sensor stays within about ±1–2 cm of the ruler, and the spread grows slightly with distance. Likely causes:

  • Holding the object by hand: a small tilt or movement changes the reflected echo.
  • Speed of sound: the code uses 343 m/s, which is only exact at about 20 °C.
  • Beam spread: the sensor's beam is a cone, so it can pick up echoes from things beside the object at longer distances.
  • Ruler zero: the exact point inside the sensor where the distance is measured from is not the front edge of the metal cylinders.

For the gripper this is accurate enough: it only needs to decide whether a hand is closer than a set distance, and a margin of a couple of centimetres covers this error.

Earlier experiment: measuring distance with a VL53L0X time-of-flight sensor

alt text alt text

The VL53L0X is a time-of-flight distance sensor: it fires an infrared laser pulse and measures how long the light takes to bounce back. It communicates over I²C, so it only needs four wires: VIN, GND, SCL and SDA.

alt text

Code

I used the Adafruit VL53L0X library. The sketch starts the sensor over I²C, then prints the distance in millimetres every 200 ms, or "Out of range" when there is no valid reading.

alt text

#include <Wire.h>
#include <Adafruit_VL53L0X.h>

Adafruit_VL53L0X lox = Adafruit_VL53L0X();

void setup() {
  Serial.begin(115200);
  Wire.begin(21, 22); // SDA, SCL

  Serial.println("VL53L0X Test");

  if (!lox.begin()) {
    Serial.println("Failed to find VL53L0X sensor");
    while (1);
  }

  Serial.println("Sensor initialized!");
}

void loop() {
  VL53L0X_RangingMeasurementData_t measure;

  lox.rangingTest(&measure, false); // pass true to debug

  if (measure.RangeStatus != 4) {  // valid reading
    Serial.print("Distance (mm): ");
    Serial.println(measure.RangeMilliMeter);
  } else {
    Serial.println("Out of range");
  }

  delay(200);
}

Result

alt text

The serial monitor shows live readings of roughly 1,190–1,280 mm, with occasional "Out of range" results when nothing valid is in front of the sensor.

Exploring the input devices in the lab

alt text A push button is a momentary input device that only completes the circuit when pressed. It has internal metal contacts that touch when force is applied and disconnect when released. This produces a digital signal (HIGH/LOW) for microcontrollers. It is commonly used for triggering events like turning LEDs on/off or resetting systems. Debouncing is often required because mechanical contacts can create noise. It is one of the simplest and most reliable human input interfaces.

alt text A toggle switch is a latching mechanical switch that stays in its position after being flipped. Unlike push buttons, it does not require continuous force to maintain state. It is typically used for ON/OFF control of circuits. Internally, it connects or disconnects terminals based on lever position. It outputs a stable digital HIGH or LOW signal. Used in power control, mode selection, and hardware toggling.

alt text A slide switch changes state by sliding a small actuator horizontally. It is a latching switch, meaning it stays in position until moved again. It typically has 2 or 3 terminals depending on configuration (SPST/SPDT). Used for mode selection or power switching in compact devices. Provides a clean digital output without bouncing issues as severe as push buttons. Common in portable electronics and embedded systems

alt text A rocker switch operates by pressing one side down to toggle states. It is a latching switch commonly used for power control. Many versions include internal illumination to indicate ON state. It provides a stable HIGH/LOW output depending on position. Mechanically robust, suitable for higher current applications. Widely used in appliances and power distribution systems.

alt text This is a household AC switch used for controlling mains power. It works by physically connecting or disconnecting live wires. Unlike microcontroller switches, it handles high voltage (220–240V AC). Internally, it uses spring-loaded contacts for quick switching. Not directly interfaced with microcontrollers without relays or isolation. Represents real-world large-scale switching systems.

alt text This is a compact version of a slide switch designed for PCBs. Used in space-constrained electronic designs. Operates the same as a regular slide switch but in smaller form factor. Typically used for configuration settings or power toggling. Provides reliable digital switching with minimal footprint. Common in wearable devices and compact circuits.

alt text A flex sensor measures bending by changing its resistance. When straight, resistance is low; when bent, resistance increases. It provides an analog output proportional to curvature. Used in gesture detection, robotics, and wearable tech. Requires a voltage divider to read values using a microcontroller. Useful for capturing physical motion as electrical data

alt text An FSR detects pressure or force applied to its surface. Resistance decreases as more force is applied. It outputs an analog signal based on applied pressure. Used in touch sensing, weight detection, and interactive surfaces. Not highly precise but good for relative force measurement. Requires calibration for consistent readings.

alt text A rotary encoder detects rotation and direction instead of absolute position. It outputs digital pulses (CLK and DT) when rotated. Unlike potentiometers, it has no fixed start or end. Often includes a push button for additional input. Used in menus, volume control, and navigation systems. Requires decoding logic in software

alt text A joystick module provides two-axis analog input (X and Y) along with a push button. It uses two potentiometers internally to detect direction and position. The output is analog voltage for movement and digital for the button press. It is widely used for navigation, robotics control, and gaming interfaces.

alt text A PIR sensor detects motion using infrared radiation changes. It senses heat differences from moving objects (like humans). Outputs a digital HIGH signal when motion is detected. Does not emit energy, only detects passive IR radiation. Used in security systems and automatic lighting. Has adjustable sensitivity and delay.

alt text A gas sensor is an input device used to detect the presence and concentration of gases in the environment. It works by sensing changes in electrical properties (like resistance or voltage) when gas molecules interact with the sensor material. Common types such as MQ-series sensors can detect gases like LPG, methane, carbon monoxide, and smoke. The sensor outputs an analog or digital signal that can be read by a microcontroller (like Arduino or ESP32) for further processing. These sensors are widely used in safety systems, air quality monitoring, and smart alert devices to prevent hazards.

alt text This is an advanced LDR module with built-in signal conditioning. It includes a potentiometer to adjust sensitivity threshold. Provides a clean digital output using comparator (LM393). Also supports analog output for raw light values. Useful when precise triggering is needed based on light level. Common in automation and smart lighting systems.

alt text

The MQ series sensors are gas detection modules that work on changes in resistance when exposed to different gases. Each variant is tuned for specific gases like LPG, methane, alcohol, carbon monoxide, hydrogen, or air quality compounds. They contain a heated sensing element (SnO₂) which reacts with gases and alters conductivity. Output can be both analog (concentration level) and digital (threshold detection). They require a warm-up time (typically 20–60 seconds or more) for stable readings. These sensors are widely used in safety systems, air quality monitoring, and leak detection.