EAZYLife STEM LAB · MODULE 16

Digital Sensors and Communication Interfaces

Understand how sensors report digital states and measurements, how microcontrollers exchange data, and how to wire and troubleshoot I²C, SPI and UART interfaces.

Free open lesson Three communication buses Arduino practicals
SENSE · TRANSMIT · INTERPRET
01 · DIGITAL SENSOR OUTPUTS

Digital does not always mean a simple ON/OFF switch

A digital sensor may report a binary state, send a pulse whose timing carries information, or transmit a multi-bit measurement over a communication bus. Before wiring a module, identify its output type and the electrical requirements of the exact part.

Four common output styles

Digital switching output

HIGHLOW

Examples: limit switches, digital Hall modules and threshold outputs. The logic state represents an event or condition.

Pulse / timing output

PeriodHIGH

Examples: ultrasonic echo pulse, encoder output and frequency-output sensors. Timing or pulse count carries the measurement.

Serial digital data

1010010

Examples: I²C, SPI and UART. The receiver interprets bits according to the bus rules and device protocol.

Logic HIGH and LOW are voltage ranges

Digital logic is not necessarily 0 V and 5 V. A device specifies input thresholds and output levels. A 3.3 V controller and a 5 V sensor may not be directly compatible in both directions.

  • Check the datasheet's VIH, VIL, VOH and VOL values.
  • Check absolute maximum ratings, not just normal operating voltage.
  • Never assume a pin is 5 V tolerant because the board is powered from USB.
  • Use a suitable level shifter when required.

Push-pull and open-drain outputs

A push-pull output actively drives both HIGH and LOW. An open-drain/open-collector output actively pulls LOW but needs a pull-up resistor or another specified pull-up source to create HIGH.

Multiple open-drain devices can share a bus safely when designed correctly. Do not connect ordinary push-pull outputs together.

02 · PULL-UPS AND LOGIC CONNECTIONS

Why some digital pins need a pull-up resistor

An open input can float: its voltage may wander and produce unpredictable readings. A pull-up provides a defined idle HIGH state. A pull-down can provide a defined LOW state when the circuit and device support that arrangement.

Button input with a pull-up

+5 V (if board and input are 5 V)10 kΩpull-upGNDMicrocontrollerDigital input D2Input nodeButton pulls node LOWReleased = HIGH · Pressed = LOW

The 10 kΩ value is a teaching example, not a universal rule. The correct value depends on leakage, noise, speed, bus capacitance and device recommendations. A microcontroller's internal pull-up may be suitable for a simple button, but it is often too weak or poorly specified for a faster shared bus.

Internal pull-up example

const byte buttonPin = 2;

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

void loop() {
  bool pressed = (digitalRead(buttonPin) == LOW);
  Serial.println(pressed ? "PRESSED" : "RELEASED");
  delay(50);
}

With INPUT_PULLUP, the pin reads HIGH when the switch is open and LOW when the switch connects it to ground. Software debouncing may still be needed.

Level shifting is not optional when required

For a 3.3 V-only input, a 5 V HIGH may exceed the permitted pin voltage. Use a level shifter designed for the signal type. A resistor divider can sometimes reduce a one-way slow signal, but it is not a universal replacement for a proper bidirectional I²C level shifter.

Also check whether breakout boards already include pull-ups and which rail those resistors connect to.

03 · I²C TWO-WIRE BUS

Many devices, two signal lines

I²C uses a clock line (SCL) and a data line (SDA). A controller initiates transfers, sends an address and controls the clock. Devices respond at their configured address. Both lines are typically open-drain/open-collector and require pull-ups to a suitable logic rail.

One controller and several I²C devices

ControllerSDA · SCLGNDSDA shared dataSCL shared clockSensor ASDA/SCLSensor BSDA/SCLDisplaySDA/SCLAll grounds share a suitable common referenceR pull-upR pull-upPull-ups to compatible logic rail

Conceptual shared-bus topology. The drawing groups each device's SDA and SCL connections; it is not a pin-by-pin breakout-board layout. Pull-ups may already be fitted to modules. Too many parallel pull-ups can make the effective resistance too low.

What happens during a transfer?

  1. Bus is idle with SDA and SCL HIGH.
  2. Controller creates a START condition.
  3. Controller sends a 7-bit address and read/write bit.
  4. Addressed device acknowledges (ACK) or no device responds (NACK).
  5. Data bytes are exchanged, each followed by ACK/NACK.
  6. Controller ends with a STOP condition, or uses a repeated START.

Address conflicts and bus limits

  • Two devices with the same fixed address may conflict unless one supports an address-select pin or a multiplexer is used.
  • Some devices support 10-bit addressing, but many beginner libraries use 7-bit addresses.
  • Bus speed, cable length and capacitance affect reliability.
  • Check voltage compatibility and the module's pull-up rail.
  • Do not assume every device accepts the same clock speed.
04 · SPI AND UART

Choose the interface that fits the job

SPI · Separate data paths and a clock

ControllerSCLK MOSI MISODevice 1CS1Device 2CS2Shared SCLK, MOSI, MISOSeparate chip-select per peripheral

SPI commonly uses SCLK, MOSI, MISO and a chip-select (CS/SS) line for each peripheral. It is often fast and full-duplex, but uses more wires and has device-specific mode, timing and selection rules.

  • MOSI: controller to peripheral.
  • MISO: peripheral to controller.
  • SCLK: clock generated by controller.
  • CS: selects the target device, often active LOW.

UART · Asynchronous serial

Controller ATX · RX · GNDDevice BRX · TX · GNDTX → RXRX ← TXCommon ground · compatible logic levels

UART sends framed serial data without a shared clock. Both ends must agree on baud rate, data bits, parity and stop bits. TX connects to the other device's RX, and vice versa.

UART logic voltage is not automatically the same as RS-232 voltage. Do not connect a true RS-232 port directly to a microcontroller UART pin; use the appropriate transceiver.

At a glance

InterfaceSignal wiresClockTypical strengthsWatch for
I²CSDA, SCLShared clockMultiple addressed devices, low pin countPull-ups, address conflicts, capacitance
SPISCLK, MOSI, MISO, CSShared clockHigh throughput, full-duplexMore pins, CS and mode requirements
UARTTX, RX, GNDNo shared clockSimple point-to-point links, debuggingMatching format/baud and logic levels
05 · PRACTICAL 1 · I²C SCANNER

Discover the addresses on an I²C bus

An I²C scanner asks the bus whether a device acknowledges each candidate address. It is a useful first diagnostic, but it does not identify a sensor model or prove that every register and measurement function works.

Example Arduino Uno wiring

Arduino UnoA4 / SDAA5 / SCL5VGNDI²C breakoutSDASCLVCC*GNDSDASCLSupply*Only use a supply voltage accepted by this exact breakout

For a classic Arduino Uno R3, SDA is A4 and SCL is A5. Some newer boards expose dedicated SDA/SCL pins as well. Confirm the pinout of your board revision. Never assume a breakout's VCC pin accepts 5 V.

Scanner sketch

#include <Wire.h>

void setup() {
  Serial.begin(9600);
  Wire.begin(); // Uno R3: SDA=A4, SCL=A5
  Serial.println("I2C scanner");
}

void loop() {
  byte found = 0;

  for (byte address = 1; address < 127; address++) {
    Wire.beginTransmission(address);
    byte error = Wire.endTransmission();

    if (error == 0) {
      Serial.print("Found device at 0x");
      if (address < 16) Serial.print("0");
      Serial.println(address, HEX);
      found++;
    }
  }

  Serial.print("Devices found: ");
  Serial.println(found);
  delay(3000);
}

Upload, open Serial Monitor at 9600 baud and note the addresses. The scan may miss devices that are unpowered, held in reset, using a different bus or not responding in the expected way.

Before connecting: check the breakout pin labels, supply range, logic voltage, pull-up arrangement and exact sensor datasheet. If the breakout pulls SDA/SCL up to 5 V, do not connect it to a 3.3 V-only controller unless the board is explicitly designed for that arrangement.

06 · PRACTICAL 2 · READ A DIGITAL SENSOR

Read an I²C sensor using its library

Many digital temperature, humidity and inertial sensors return calibrated digital measurements over I²C or SPI. The example below uses an Adafruit-compatible BME280 breakout and library. It is an example implementation, not a claim that every BME280 board has identical pin labels, voltage regulation or pull-ups.

Example BME280 connections to Uno R3

  • Breakout SDA → Uno A4 / SDA.
  • Breakout SCL → Uno A5 / SCL.
  • Breakout GND → Uno GND.
  • Breakout VIN/VCC → only the voltage supported by that breakout. Many boards accept 3.3–5 V input through onboard regulation; bare sensors do not.

Install the sensor library and its required bus/sensor dependency using the Arduino Library Manager. Confirm the I²C address from the board documentation or scanner. Common BME280 addresses are 0x76 or 0x77, depending on the SDO/address configuration.

Example sketch

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

Adafruit_BME280 bme;

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

  if (!bme.begin(0x76)) {
    Serial.println("BME280 not found. Check wiring/address.");
    while (true) { delay(100); }
  }
}

void loop() {
  Serial.print("Temperature: ");
  Serial.print(bme.readTemperature());
  Serial.println(" C");

  Serial.print("Pressure: ");
  Serial.print(bme.readPressure() / 100.0F);
  Serial.println(" hPa");

  Serial.print("Humidity: ");
  Serial.print(bme.readHumidity());
  Serial.println(" %");

  delay(1000);
}

If the scanner reports 0x77, change the begin address. Use the exact library version and board configuration in your build record.

UART serial debugging between two microcontrollers

For a simple hardware-UART link, connect controller A TX to controller B RX, controller A RX to controller B TX, and GND to GND. Use compatible logic levels and choose a baud rate both sketches support. On an Uno, pins 0 and 1 are also used by the USB serial interface, so a separate UART arrangement or a board with an additional hardware UART may make debugging easier.

// Controller A: transmit a short message
void setup() {
  Serial.begin(9600);
}
void loop() {
  Serial.println("SENSOR NODE READY");
  delay(1000);
}

// Controller B: receive and display
void setup() {
  Serial.begin(9600);
}
void loop() {
  if (Serial.available()) {
    String message = Serial.readStringUntil('\n');
    Serial.print("Received: ");
    Serial.println(message);
  }
}

These two sketches use the USB-connected hardware serial port on an Uno for illustration. When two Unos are connected together, use SoftwareSerial on suitable pins or a different hardware UART for the inter-board link, and keep USB serial available for the Serial Monitor. Avoid connecting two TX outputs together.

07 · PRACTICAL 3 · IDENTIFY THE BUS

Inspect a sensor module before writing code

Common modules and interfaces

  • Ultrasonic range modules: may use trigger/echo pulses, UART or I²C depending on model.
  • IMUs: commonly use I²C or SPI; check address, range, data rate and interrupt pin.
  • IR receiver modules: often produce timed digital pulses decoded by a protocol/library.
  • Digital temperature/humidity modules: may use a proprietary single-wire timing protocol or I²C.
  • Magnetic encoders: may provide quadrature pulses, I²C, SPI or PWM.

The product family name is not enough to select wiring or code. Read the exact module marking and datasheet.

Bench investigation

  1. Photograph or sketch the module and record its exact marking.
  2. Find its supply range, logic levels, pinout and interface in the datasheet.
  3. Identify whether pull-ups, regulators or level shifting are already fitted.
  4. Wire only power and ground first; check current draw and supply polarity.
  5. Add signal wires with power removed and inspect for shorts.
  6. Run the simplest suitable test: input-state read, pulse timing, I²C scan, SPI example or UART echo.
  7. Record the observed address, pulse timing or data format.
08 · INTERFACE CALCULATOR

Estimate UART transmission time

UART sends each character as a framed group of bits. For a common 8-N-1 format, each byte uses one start bit, eight data bits and one stop bit: ten bits per character, excluding any pauses between characters.

UART frame-time estimator

Estimated wire time20.83 msIdeal maximum throughput960 bytes/s

Estimate excludes software delays, inter-message gaps and processing time.

Understand the result

At 9600 baud with 8-N-1, one character occupies approximately 10/9600 seconds, or 1.04 ms. Twenty continuous characters take about 20.8 ms.

Baud rate is the signalling rate in symbols per second. In ordinary binary UART, each symbol carries one bit, so the bit rate and baud rate are numerically equal. This is not always true for more advanced modulation systems.

09 · TROUBLESHOOTING

Diagnose the connection layer by layer

I²C scanner finds no devices

Check supply and ground, SDA/SCL pin mapping, swapped wires, reset state, pull-ups, logic compatibility and whether the selected bus pins match the board. Confirm the sensor is actually an I²C device.

Device appears at an unexpected address

Check the address-select pin, breakout revision and datasheet. Some libraries expect a 7-bit address, while documentation may show an address byte including the read/write bit.

I²C works on short wires but fails remotely

Bus capacitance, cable length, pull-up value, clock speed, noise and grounding can affect signal edges. Reduce speed and wiring length, then inspect the waveform if possible.

UART displays unreadable characters

Check baud rate, data bits, parity, stop bits, crossed TX/RX wiring, common ground and voltage levels. Ensure both ends use the same serial format.

SPI device does not respond

Check chip-select polarity, SPI mode (CPOL/CPHA), clock limit, bit order, MOSI/MISO direction and the device's power-up timing.

Input changes randomly

Check for a floating input, missing pull-up/down, poor ground, switch bounce, long noisy wires or an output that is open-drain but not pulled up.

Good debugging sequence: verify power, ground and pinout first; confirm electrical compatibility second; verify the physical bus signals third; only then investigate library calls, addresses and application logic.

10 · SAFETY AND KNOWLEDGE CHECK

Build reliable interfaces, not damaged pins

Practical safety

  • Power down before changing wiring; check supply polarity before energising.
  • Never exceed a pin's input voltage or absolute maximum ratings.
  • Use level shifting where voltage compatibility is not guaranteed.
  • Do not connect RS-232 voltage levels directly to logic UART pins.
  • Check current limits and avoid shorting supply rails.
  • Use ESD precautions for sensitive sensor and microcontroller devices.
  • Keep beginner activities at extra-low voltage; no mains-connected experiments.

What to document

Record the board revision, sensor part number, supply voltage, logic levels, pin mapping, bus speed, device address, library version and measured behaviour. A wiring diagram without the module identity can be misleading.

1. Which lines form a basic I²C bus?

2. How should two UART devices be connected?

3. What does an open-drain output need to create a HIGH state?

4. Why must a 3.3 V-only input not receive an unchecked 5 V signal?

KEEP LEARNING · GO FURTHER

Free to learn. More support when you need it.

Explore these open lessons at your own pace. For personalised explanations, project-specific troubleshooting, guided practical training or masterclasses, EazyLife offers paid support tailored to your learning goals.

Free or sponsored lesson referrals may be available through active programmes; they are not guaranteed.

Enquire about guidance