Skip to content
Academia.
ELEmbedded LinuxT550077101 · Fall 2026
CourseFall 2026

Friday · 12:00–16:00 · Odense U174

Sensors, Actuators, GPIO, and Serial Interfaces

Lecture 04: This lecture introduces the measurement chain and the practical integration of sensors, actuators, GPIO, and serial communication interfaces in embedded and robotic systems. It covers sensor specifications, calibration and uncertainty, dynamic response, sampling and filtering, representative sensors, industrial and PLC-oriented interfaces, communication interfaces, GPIO safety, smart sensors, robotics, GNSS and multi-sensor systems, actuator control, validation, and a guided sensor-to-actuator laboratory.

Learning objectives

✓By the end of this module, students should be able to:
✓describe the complete measurement chain from physical phenomenon to timestamped engineering data;
✓interpret range, sensitivity, resolution, accuracy, precision, repeatability, reproducibility, linearity, hysteresis, dead band, drift, noise, cross-sensitivity, response time, bandwidth, saturation, and uncertainty;
✓apply basic static calibration, uncertainty analysis, and traceability concepts;
✓explain dynamic sensor behavior, response time, saturation, sampling, aliasing, and filtering;
✓select appropriate sensors and interfaces for embedded, industrial, robotic, and precision-farming applications;
✓distinguish common industrial and PLC-oriented interfaces such as PNP/NPN, 0–10 V, and 4–20 mA;
✓compare UART, I²C, SPI, 1-Wire, USB, RS-485, CAN, Ethernet, wireless, and related interfaces;
✓apply GPIO electrical-boundary and protection concepts;
✓explain smart-sensor processing, onboard diagnostics, sensor integration, and GNSS/multi-sensor systems;
✓design safe actuator command, feedback, fault, timeout, and recovery behavior;
✓develop a sensor-to-actuator validation and testing procedure.
Block 112:00–12:50content

Block 1 · 12:00–12:50 · Measurement Chain and Sensor Fundamentals

CHAPTER 4

Sensors, Actuators, GPIO, and Serial Interfaces

Learning objectives
By the end of this module, students should be able to:
  • describe the complete measurement chain from physical phenomenon to timestamped engineering data;
  • interpret range, sensitivity, resolution, accuracy, precision, uncertainty, drift, hysteresis, bandwidth, response time, and saturation;
  • select sensors used in embedded systems, robotics, mechatronics, precision farming, and industrial automation;
  • compare analog, GPIO, pulse, UART, I²C, SPI, USB, CAN, RS-485/Modbus, IO-Link, 0–10 V, and 4–20 mA interfaces;
  • distinguish a sensing element from signal conditioning, conversion, calibration, onboard processing, and sensor fusion;
  • connect low-voltage and industrial sensors through safe electrical interfaces;
  • acquire, validate, timestamp, filter, and report measurements without concealing faults;
  • design actuator drivers, feedback, interlocks, command timeouts, and safe states; and
  • diagnose realistic sensor, wiring, bus, timing, environmental, and integration failures.
A measurement is more than a number
A value such as 23.4 is incomplete. A defensible measurement states what was measured, in which unit, by which device and channel, at what observation time, over what range, under which calibration and environmental conditions, and with what quality or uncertainty. Embedded software should preserve this context instead of turning every sensor response into an unquestioned floating-point value.

4.1  The Measurement Chain

A sensor system converts a physical, chemical, or biological phenomenon into usable information. The chain may contain a sensing element, excitation, analog front end, filtering, amplification, analog-to-digital conversion, compensation, digital processing, calibration coefficients, communication, timestamping, and application interpretation.

An analog-output sensor leaves conversion and much validation to the host system. A digital sensor may return compensated engineering units. A smart sensor may estimate orientation, recognize objects, reject invalid echoes, or report diagnostics. More onboard processing reduces host workload but can hide assumptions and failure modes inside undocumented firmware.

Embedded Linux — Fall 202639
EMBEDDED LINUXFall 2026
Physical
quantity
Sensing
element
Conditioning
and ADC
Timestamped data
and decision
Digital / industrial
interface
Compensation,
filtering, calibration
A sensor package may include several stages; validate the complete chain.
A sensor package may include several stages; validate the complete chain.

Figure 4.1. A practical measurement chain. The sensor package may contain only the sensing element or nearly the entire chain.

4.2  Reading Sensor Specifications Correctly

Sensor selection begins with the measurand and operating conditions, not the connector or available library. The following terms answer different questions.

PropertyMeaning and practical consequence
RangeInterval over which performance is specified. A device may output values beyond it without those values being trustworthy.
SpanDifference between upper and lower range limits.
SensitivityChange in output per change in input, such as mV/kPa. High sensitivity does not automatically mean high accuracy.
ResolutionSmallest distinguishable or represented change. Digital bit depth gives quantization resolution, not complete system resolution.
AccuracyCloseness to an accepted reference under stated conditions. Specifications may combine offset, gain, nonlinearity, and temperature effects.
PrecisionCloseness among repeated results. A precise sensor can be consistently wrong.
RepeatabilityAgreement when the same method and conditions are repeated over a short interval.
ReproducibilityAgreement when conditions, operators, instruments, or times change according to a defined procedure.
LinearityDeviation from a chosen straight-line relationship. A nonlinear sensor can still be accurate after valid compensation.
HysteresisDifferent output for the same input depending on whether the input approached from above or below.
Dead bandInput interval that produces no observable output change. Common in mechanical systems and valves.
40Embedded Linux — Fall 2026
EMBEDDED LINUXFall 2026
PropertyMeaning and practical consequence
Offset and gain errorConstant output shift and scale error, respectively. They require different calibration models.
DriftOutput change over time at constant input, caused by aging, contamination, stress, or environment.
NoiseRandom variation from the sensor, electronics, environment, power, electromagnetic coupling, or quantization.
Cross-sensitivityResponse to a quantity other than the intended measurand, such as humidity influence on a gas sensor.
Response timeTime required to approach a defined fraction of the final response after an input change. Always check the criterion.
BandwidthFrequency interval over which dynamic response meets a defined limit.
SaturationRegion where increasing input no longer produces a meaningful corresponding output. Saturated data are not simply “large values.”
UncertaintyQuantified doubt associated with the measurement, based on identified contributions and stated coverage.

Accuracy and resolution are frequently confused. A 16-bit ADC across 3.3 V has a nominal code width near 50 μV, but reference error, front-end noise, sensor tolerance, layout, and calibration may make the usable accuracy far worse. Displaying many decimal places does not create information.

4.3  Static Calibration, Uncertainty, and Traceability

Calibration compares indications with a reference under defined conditions and estimates a relationship. For a linear model,

y=ax+b,

where x is raw indication and y is the estimated measurand. Calibration does not repair poor placement, hysteresis, saturation, insufficient response time, contamination, or use outside the calibrated range.

For n ≥ 2 repeated observations x₁, …, xₙ, the sample mean and standard deviation are

x¯ = 1n ∑i=1n xi , s = 1 n−1 ∑i=1n ( xi − x¯ ) 2 .

The mean summarizes the observed level, and the standard deviation describes sample dispersion; neither alone establishes closeness to the reference value. For independent observations from a stationary process, the standard uncertainty of the mean due to repeatability is estimated by s/√n. Correlated samples need a different treatment. Averaging a biased sensor produces a more stable biased result.

An uncertainty budget may include reference uncertainty, repeatability, resolution, calibration fit, temperature, supply variation, mounting, spatial variability, and drift. For a measurement model y = f(x₁, …, xₘ), independent input standard uncertainties are propagated to first order as

uc(y) = ∑i=1m ( ci u(xi) ) 2 , ci = ∂f ∂xi | input estimates .
Embedded Linux — Fall 202641
EMBEDDED LINUXFall 2026

Here cᵢ converts the uncertainty of input xᵢ into output units. A direct root-sum-square is appropriate only when the contributions are already expressed as output standard uncertainties. Correlated inputs require covariance terms; strongly nonlinear models may require propagation of full probability distributions. State assumptions, units, and any coverage factor rather than presenting an unjustified percentage [86].

Traceability means that a result can be related to a reference through a documented, unbroken calibration chain with stated uncertainties. A comparison against an uncharacterized second low-cost sensor is a functional check, not necessarily traceable calibration.

4.4  Dynamic Behavior, Response Time, and Saturation

Many sensors behave approximately as a first-order system:

τ dy(t) dt + y(t) = Kx(t) ,

where τ is the time constant and K the steady-state sensitivity. After a step, an ideal first-order response reaches about 63.2% of its final change after one τ, 95% after roughly 3τ, and 99% after roughly 4.6τ.

Response depends on packaging and installation. A protected temperature sensor inside a massive enclosure may be electrically fast but thermally slow. A gas sensor behind a membrane has transport delay. A soil probe may be dominated by contact and spatial heterogeneity. Sampling faster than the physical response does not make the phenomenon respond faster.

Saturation can occur in the sensing element, amplifier, ADC, or onboard algorithm. A rail value may mean true full scale, overrange, power failure, broken wiring, or a numerical limit. Detect repeated exact extrema, quality flags, impossible derivatives, and inconsistency with redundant information. Recovery from chemical, optical, or magnetic saturation may take time even after the stimulus returns to range.

Engineering caution
Never use an out-of-range value as ordinary control feedback. Mark it invalid or degraded, apply a defined safe strategy, and preserve evidence. Clamping a value to the allowed range can make a failed sensor look plausible and can drive an actuator continuously in the wrong direction.

4.5  Sampling, Aliasing, Timing, and Filtering

For ideal reconstruction of a baseband signal band-limited to fmax, sample uniformly at fs > 2fmax. Real systems require an analog anti-alias filter and margin because useful signals and interference are not perfectly band-limited. Once an aliased frequency enters sampled data, a digital filter cannot reconstruct the missing information uniquely.

Sampling rate should follow the physical dynamics and decision requirement. A slowly changing air-temperature sensor may need seconds between useful samples; an IMU used for stabilization may require hundreds of samples per second. Timestamp near acquisition. Record sequence, observation time, receive time, and dropped-sample status where latency matters.

A moving average

yk = 1N Σi=0N−1 xk−i
42Embedded Linux — Fall 2026
EMBEDDED LINUXFall 2026

reduces some high-frequency variation but adds delay and can smear abrupt events. A first-order exponential filter

yk = αxk + (1−α) yk−1 , 0<α≤1 ,

is computationally simple but also trades noise reduction for lag. Median filtering can reject isolated spikes but alters signal shape. Filtering must be justified by the noise and application, not used to make an unattractive plot look smooth.

4.6  Representative Sensors for Embedded and Robotic Systems

Table 4.2 is a selection guide, not an endorsement. Exact voltage, address, rate, accuracy, and protocol depend on the breakout board and product revision. A module may add regulators, level shifters, or protocol conversion not present in the sensing IC.

Table 4.2. Examples of sensors commonly encountered with Arduino, Raspberry Pi, ESP32, robotics, and mechatronics.

Device/typeMeasuresInterfaceReality, strengths, and limitations
BME280Temperature, relative humidity, pressureI²C or SPICompact environmental sensor with factory coefficients; host software converts raw readings into compensated units. Placement, board heating, enclosure, condensation, and airflow often dominate results.
BMP280/BMP390Pressure and temperatureI²C or SPIUseful for pressure and relative altitude trends. Weather and reference pressure limit absolute altitude; it does not measure humidity.
SHT3x/SHT4xTemperature and humidityI²CGood digital integration. Condensation, contamination, self-heating, and slow enclosure exchange remain important.
DS18B20Temperature1-WireUnique address and several devices on one bus. Cabling, pull-up, conversion time, counterfeit devices, and waterproof-probe construction require attention.
DHT11/DHT22Temperature and humidityProprietary pulse timingInexpensive and simple but relatively slow, limited, and timing-sensitive; not a reference instrument.
Thermocouple + interfaceTemperature differenceMicrovolt analog; interface IC via SPIWide temperature capability. Needs cold-junction compensation, suitable wire, noise control, and open-circuit detection.
PT100/PT1000 RTDTemperatureResistance through precision front endStable industrial measurement. Lead resistance, excitation self-heating, wiring configuration, and analog design matter.
PhotoresistorLight-dependent resistanceAnalog dividerCheap qualitative sensing; nonlinear, variable, temperature-sensitive, and unsuitable for calibrated illuminance without characterization.
TSL2591/BH1750Light/illuminance-related responseI²CDigital range control and easier integration. Spectral response and geometry differ from human vision and plant response.
Embedded Linux — Fall 202643
EMBEDDED LINUXFall 2026
Device/typeMeasuresInterfaceReality, strengths, and limitations
VL53L0X/VL53L1XOptical time-of-flight distanceI²CCompact ranging with onboard timing/processing. Target reflectivity, ambient light, field of view, cover glass, and multipath affect results.
TFmini/TF-Luna familySingle-point LiDAR distance and signal strengthUART; some variants I²COnboard emitter timing, echo detection, and range estimation reduce host work. Sunlight, dark/angled targets, minimum range, beam divergence, multipath, and update-mode configuration matter.
HC-SR04-type ultrasonicDistanceTrigger/echo pulseLow cost. Often uses 5 V logic; affected by surface angle, soft targets, temperature, crosstalk, blind zone, and specular echoes.
MPU-60503-axis accelerometer + gyroscopeI²CCommon teaching IMU. Bias, temperature drift, vibration, limited calibration, and module quality limit navigation.
ICM-20948/BMI270Accelerometer and gyroscope; ICM-20948 also includes a magnetometerI²C or SPIHigher-rate inertial sensing. Orientation still requires calibration and fusion; magnetic disturbance is a major practical issue.
BNO055/BNO085 classIMU with onboard fusionI²C, UART, or SPI depending on productOutputs orientation estimates and calibration status. Convenient, but internal algorithm assumptions, latency, frame conventions, and magnetic environment must be understood.
GNSS module (u-blox class)Position, velocity, and timeUART, USB, I²C, or SPI depending on moduleOnboard radio correlation and navigation solution. Accuracy depends on sky view, antenna, multipath, corrections, constellation, dynamics, and solution status.
Quadrature encoderShaft/wheel position and speedA/B digital pulses; optional indexExcellent relative motion feedback. Missed edges, electrical noise, direction convention, mounting, wheel slip, and integer rollover matter.
Hall-effect sensorMagnetic field, speed, proximity, or currentDigital or analogContactless and robust; sensitive to magnet geometry, air gap, temperature, and external fields.
Load cell + HX711Force/weightMillivolt bridge; module digital clock/dataHigh sensitivity at low cost. Mechanical mounting, creep, temperature, vibration, excitation, and calibration dominate performance.
INA219/INA226 classBus voltage and inferred current/powerI²CUseful power monitoring with programmable conversion. Shunt selection, common-mode range, heating, calibration, and transient bandwidth matter.
PIR moduleChange in infrared sceneDigitalLow-power motion indication, not object ranging. Detects changes, with dead time and sensitivity to temperature, optics, and placement.
44Embedded Linux — Fall 2026
EMBEDDED LINUXFall 2026
Device/typeMeasuresInterfaceReality, strengths, and limitations
Capacitive soil-moisture probePermittivity-related soil responseAnalog, frequency, SDI-12, or digital by modelCorrelates with water content only after soil-specific consideration. Salinity, density, temperature, installation, air gaps, and corrosion matter.
NDIR CO₂ moduleCO₂ concentrationUART, I²C, analog, or ModbusOnboard optical processing and compensation. Warm-up, pressure, humidity, contamination, drift, and automatic baseline assumptions can bias field data.
Electrochemical gas sensorGas concentrationNanoamp/microamp analog via potentiostatSelective only to a degree; cross-sensitivity, temperature/humidity, aging, zero drift, warm-up, and calibration gas are critical.
CameraImages, indirectly many scene propertiesCSI, USB, EthernetVery information-rich. Illumination, exposure, optics, calibration, motion blur, bandwidth, privacy, and inference errors dominate.
2D/3D LiDARRange scan or point cloudUART, USB, Ethernet, CAN by productDirect geometric data with onboard timing. Weather, dust, reflective materials, blind zones, multipath, scan timing, and moving-platform distortion matter.
RadarRange, velocity, angle depending on productSPI, CAN, UART, or EthernetOperates in difficult light and some weather. Interpretation, multipath, interference, resolution, antenna placement, and regulatory constraints matter.
Embedded Linux — Fall 202645
Block 213:00–13:50content

Block 2 · 13:00–13:50 · Sensor Behavior, Interfaces, and Industrial Systems

Embedded Linux — Chapter 4 Part 2

4.7  Industrial and PLC-Oriented Sensors

Industrial automation frequently uses standardized electrical signaling and robust connectors rather than board-level buses. A PLC digital input may expect 24 V logic. Three-wire proximity sensors commonly use PNP or NPN transistor outputs. Whether current is sourced or sunk must match the input module and wiring convention.

Signal/
interface
StrengthsLimitationsTypical use
24 V discrete
PNP/NPN
Robust switching and
easy PLC integration
Wiring polarity,
leakage, input type,
and isolation must
match
Proximity, limit,
pressure, and
photoelectric switches
0–10 VSimple continuous
signal and common
industrial support
Voltage drop, ground
difference, EMI, and
broken-wire ambiguity
Position, pressure,
speed reference,
environmental
transmitters
4–20 mANoise-resistant over
distance; live zero can
indicate some faults
Requires loop supply
and receiver;
saturation/fault-
current conventions
vary
Pressure, flow, level,
temperature, gas
transmitters
Pulse/frequencyGood noise immunity
and direct rate/count
information
Counter bandwidth,
pulse shape, bounce,
and missed events
Flow meters, speed
pickups, encoders
RS-485/Modbus
RTU
Long multidrop
differential link;
registers and
diagnostics
Addressing,
termination, bias,
timing, register maps,
and endianness
Drives, energy meters,
environmental stations
CAN/CANopen/
J1939
Arbitration, error
detection, robust
multidrop operation
Requires termination,
identifiers, and
application-profile
knowledge
Vehicles, mobile
machinery, drives,
distributed I/O
IO-LinkPoint-to-point digital
sensor data,
parameters, and
diagnostics
Requires IO-Link
master and
device-description
integration
Smart industrial sensors
and actuators
SSI/industrial
encoder
Deterministic absolute
position transfer
Specialized
electrical/timing
interface and cable
requirements
Absolute encoders and
precision motion
Industrial
Ethernet
High data rate and
system integration
Complexity,
switch/configuration
needs, and real-time
profile differences
Vision, drives, remote
I/O, controllers
Embedded Linux — Fall 202645

For a 4–20 mA loop measured through resistance R, the nominal voltage is V = IR. With R = 250 Ω, the ideal signal is 1–5 V, which is too high for some 3.3 V ADCs. Select the receiver and protection around the complete input range, fault currents, tolerance, power dissipation, common-mode voltage, and isolation need. Do not connect an industrial loop directly to a GPIO. PLC integration also involves channel configuration, process image update, input filtering, scaling, fault codes, grounding, shielding, safety category, and deterministic scan behavior. Reading a register successfully does not prove that it represents the intended physical channel or unit.

For a 4–20 mA loop measured through resistance R, the nominal voltage is V = IR. With R = 250 Ω, the ideal signal is 1–5 V, which is too high for some 3.3 V ADCs. Select the receiver and protection around the complete input range, fault currents, tolerance, power dissipation, common-mode voltage, and isolation need. Do not connect an industrial loop directly to a GPIO. PLC integration also involves channel configuration, process image update, input filtering, scaling, fault codes, grounding, shielding, safety category, and deterministic scan behavior. Reading a register successfully does not prove that it represents the intended physical channel or unit.

4.8  Communication Interfaces: Selection and Failure Modes

Table 4.4.   Common sensor interfaces, advantages, and realistic failure modes.
InterfaceAdvantagesLimitationsCommon failures and checks
Analog voltageSimple, low latency,
widely available
ADC/reference/noise/
ground errors; limited
cable distance
Overvoltage, rail saturation,
broken wire, wrong attenuation,
shared-ground noise
GPIO discreteSimple state/event
input
No rich data; contact
bounce and threshold
ambiguity
Floating input, wrong logic level,
missing pull resistor, EMI,
active-low confusion
Pulse/PWMEncodes frequency,
duty, or duration
Requires timing capture
and electrical
compatibility
Missed edges, jitter, counter
overflow, blocking software, 5 V
output
UARTSimple, observable,
full duplex,
moderate distance
with proper
transceiver
Normally point-to-point;
no common clock; framing must
match
TX/RX reversed, no common
reference, baud/parity mismatch,
logic versus RS-232 level
I²CTwo signal wires
addressed devices
Board-level distance,
pull-ups, address
conflicts, shared-bus
blocking
Wrong address, missing/strong
pull-ups, level mismatch, stuck
SDA, capacitance, clock stretching
SPIHigh rate, full
duplex, simple
framing
More wires and chip
selects; no standard
message format
Wrong mode, clock too fast, select
timing, MISO contention,
long-wire ringing
1-WireUnique identities
and few wires
Timing/cabling/power
constraints
Weak pull-up, parasite-power
failure, reflections, counterfeit or
duplicated IDs
USBPower plus high-level
enumeration and
bandwidth
Connector, host, driver,
and hotplug complexity
Cable/power quality, renamed
device node, permissions, suspend,
re-enumeration
Embedded Linux — Fall 202646
InterfaceAdvantagesLimitationsCommon failures and checks
RS-485Differential, long
distance, multidrop
Needs transceiver and
application protocol
Missing/excess termination, absent
bias, swapped pair, ground
potential, driver-enable timing
CANRobust arbitration
and fault detection
Frame payload/profiles
require design
Wrong bitrate, missing
termination, bus-off, identifier
collision, wiring topology
EthernetLong reach, isolation,
high bandwidth,
standard tools
Network stack,
addressing, switches,
security
Duplicate address, route, cable,
PoE mismatch, firewall, time
synchronization
WirelessMobility and no
signal cable
Variable latency, loss,
interference, energy and
security constraints
Weak coverage, coexistence,
antenna placement, credential
expiry, congestion

For a conventional two-wire RS-485 bus, termination belongs at the two physical ends, not at every node; match the transceiver, cable, grounding, and bias design to the installation [28]. Bus speed is not application sample rate. A sensor may need conversion time after a command, may internally average several readings, or may repeat its previous register value. Read status bits and rate-ready signals when available. Polling faster can increase self-heating and bus load without producing new information.

4.9  GPIO and Electrical Boundaries

GPIO pins operate within strict absolute maximum voltage and current limits. Absolute maximum ratings are damage limits, not recommended operating points. Floating inputs require pull-up or pull-down resistors. Mechanical switches bounce and require hardware or software debouncing. Long cables act as antennas and require appropriate interfaces and protection.

Level translation must be chosen for direction, voltage, speed, open-drain behavior, and power-off state. A simple resistor divider may be adequate for a slow unidirectional signal but is not a universal bidirectional level shifter. Isolation is useful where ground potentials differ, noise is severe, or hazardous energy must not cross the boundary.

Embedded Linux — Fall 202647
Figure 4.2
Figure 4.2. A computing pin should reach field wiring and loads only through an interface designed for voltage, current, transients, grounding, and safe failure.
Engineering caution
Software cannot repair unsafe electrical design. Verify nominal and worst-case voltage, source and sink current, polarity, connector pinout, power sequencing, inductive energy, transient protection, grounding, shielding, isolation, and load supply before enabling an output. A risk-relevant emergency stop must not depend only on ordinary application software.

4.10  Smart Sensors and Onboard Processing

A smart sensor combines sensing with some computation, storage, calibration, diagnostics, or communication. The division of work varies significantly.

The BME280 stores factory calibration coefficients and returns raw pressure, temperature, and humidity data. Host software reads those coefficients and applies the manufacturer’s compensation formulas; the sensor itself provides conversion, oversampling, and configurable filtering. The host also manages operating mode, placement, and operating limits [31]. A TFmini-family ranging sensor contains an optical emitter and receiver, high-speed timing and signal processing, and firmware that outputs an estimated distance and signal-strength information. It does not provide the host with raw photons; sunlight, reflectivity, angle, multipath, and internal validity rules still determine performance.

GNSS receivers perform enormous onboard processing: radio-frequency sampling, correlation with satellite codes, tracking, navigation-message decoding, clock estimation, and po-sition/velocity/time solution. An NMEA position string is therefore the output of a complex estimator, not a direct physical measurement. Status, fix type, dilution of precision, satellite geometry, correction age, antenna quality, and covariance are essential.

Smart IMUs may include a digital motion processor or fusion firmware that estimates orientation. Cameras may perform auto-exposure, image-signal processing, feature extraction, or neural inference. Industrial IO-Link sensors may expose process data, device parameters, event diagnostics, operating hours, and quality flags.

Advantages include reduced host workload, standardized output, compensation, self-test, and higher-level information. Limitations include hidden algorithms, firmware changes, internal latency, undocumented filtering, vendor-specific failure behavior, and inability to access raw data. Validate the complete device rather than assuming that digital output is automatically correct.

Embedded Linux — Fall 202648

4.11  Sensor Research Versus Sensor Integration

Connecting a BME280 to an Arduino, ESP32, or Raspberry Pi is valuable sensor integration: selecting an interface, acquiring data, validating it, and using it in a system. It is not, by itself, sensor development research. When a researcher says their field is sensor development, this normally means creating new sensing capability or substantially advancing performance, selectivity, fabrication, packaging, calibration, or inference.

Examples of genuine sensor-development research include:

  • developing a new functional material whose electrical response is selective to ammonia;
  • designing a micromechanical structure and readout circuit for force or inertial sensing;
  • creating a new optical geometry and spectral method for non-destructive crop-stress detection;
  • building a low-noise analog front end for an electrochemical biosensor;
  • developing a soil nutrient sensor with new ion-selective chemistry and field compensation;
  • designing radar or ultrasonic transducers and new signal-processing algorithms;
  • inventing self-calibration, drift compensation, or multi-sensor inference validated against traceable references; and
  • solving packaging, contamination, lifetime, manufacturability, and field-calibration limitations that prevent laboratory principles from becoming usable instruments.

Integration can still be publishable research when it makes a new, rigorously validated contribution: a fusion method, uncertainty model, self-diagnostic architecture, or deployment study that produces generalizable knowledge. Novelty is not created by changing the microcontroller or displaying an existing sensor’s values on a dashboard.

4.12  Sensors in Robotics and Mechatronics

Robots estimate internal state and external environment from imperfect sensors. Common roles include:

  • encoders and current sensors for actuator state and load;
  • IMUs for angular rate, acceleration, attitude support, and vibration;
  • GNSS, UWB, visual odometry, and wheel odometry for localization;
  • LiDAR, radar, ultrasonic, and cameras for geometry and obstacle perception;
  • force/torque, tactile, pressure, and proximity sensing for interaction; and
  • limit switches and independent safety devices for bounded motion.
Embedded Linux — Fall 202649

No sensor supplies “the robot position” without assumptions. Wheel odometry drifts and fails under slip. An IMU measures specific force and angular rate; integrating bias creates growing error. Magnetometers are disturbed by motors and steel. GNSS suffers from blockage and multipath. Cameras depend on texture and illumination. LiDAR has material, weather, and geometry limitations. Sensor fusion combines complementary information but cannot rescue multiple sensors sharing the same unmodeled bias.

Frames and time are fundamental. State which coordinate frame a vector uses, how the sensor is mounted, when the observation occurred, and how clocks are synchronized. A correct value in the wrong frame or at the wrong time is wrong for control.

Embedded Linux — Fall 202650
Block 314:00–14:50content

Block 3 · 14:00–14:50 · GPIO, Smart Sensors, Robotics, and Linux Acquisition

Embedded Linux — Chapter 4 Part 3


4.13  GNSS and Multi-Sensor Systems in Precision Farming

GNSS supports field mapping, guidance, georeferencing, fleet tracking, and repeatable operations. Standalone consumer positioning may be adequate for monitoring a vehicle’s general location but not for centimeter-level row following. Differential corrections and real-time kinematic (RTK) techniques can substantially improve relative positioning when correction data, carrier-phase ambiguity resolution, antenna installation, and sky visibility are suitable.

Precision-farming failure sources include canopy blockage, trees and buildings, reflected signals near machinery, antenna motion, electromagnetic interference, base-to-rover distance, correction-link interruption, wrong coordinate reference system, and confusing fix status with guaranteed accuracy.

Complementary sensing on an agricultural robot

Figure 4.3. Complementary sensing on an agricultural robot, with a body frame and a local east–north–up (ENU) reference frame. Sensor and antenna positions are illustrative. Soil probes require soil contact; emergency stopping requires a separately engineered and validated stop function.


A practical localization architecture may fuse GNSS position and velocity with IMU angular rate and acceleration, wheel or steering odometry, and camera or LiDAR motion. The estimator should consume measurement covariance and reject or down-weight invalid data. Record raw data and quality indicators so incorrect estimates can be reconstructed.

Environmental monitoring requires representative placement. Air sensors close to electronics may measure enclosure heating. Soil measurements vary within centimeters. Crop reflectance changes with sun angle, leaf geometry, wind, and camera exposure. A beautiful spatial map can therefore be precisely georeferenced but scientifically misleading.

50Embedded Linux — Fall 2026


4.14  Linux Device Access and Robust Acquisition

Linux drivers expose devices through subsystem APIs, device nodes, sysfs attributes, input interfaces, networking, and maintained libraries. Device filenames such as /dev/ttyUSB0 can change after reconnection. Prefer stable discovery through device attributes, serial numbers, or managed symbolic links.

Access is controlled by ownership, groups, and policy. Do not make a device world-writable. Serial acquisition must define framing, byte order, checksum, timeout, maximum frame length, reconnect behavior, and how corrupted or partial messages are discarded.

Listing 4.1. Validated parsing without pretending validation is calibration

1import json
2import math
3import time
4
5def parse_measurement(line: str) -> dict:
6    if len(line.encode("utf-8")) > 2048:
7        raise ValueError("frame too long")
8    data = json.loads(line)
9    if not isinstance(data, dict):
10         raise ValueError("frame must contain a JSON object")
11    if type(data.get("schema")) is not int or data["schema"] != 1:
12         raise ValueError("unsupported schema")
13
14     value = data.get("temperature_C")
15     if type(value) not in (int, float):
16         raise ValueError("temperature must be a JSON number")
17     if not -50 <= value <= 100 or not math.isfinite(value):
18         raise ValueError("measurement outside accepted range")
19     sequence = data.get("sequence")
20     if type(sequence) is not int or not 0 <= sequence < 2**32:
21         raise ValueError("sequence must be an unsigned 32-bit integer")
22     status = data.get("status", "unknown")
23    if not isinstance(status, str) or status not in {
24         "valid", "warming_up", "fault", "unknown"
25     }:
26         raise ValueError("unsupported sensor status")
27
28     return {
29         "temperature_C": float(value),
30         "unit": "degC",
31         "sequence": sequence,
32         "sensor_status": status,
33         "usable": status == "valid",
34         "received_monotonic": time.monotonic(),
35         "received_unix": time.time(),
36 }

This parser assumes a UTF-8 JSON line whose temperature unit is Celsius and whose sequence counter is unsigned 32-bit. Missing status is explicitly unknown, so a plausible value alone does not become usable control feedback. Catch ValueError (including JSON decoding errors) in the acquisition loop and record a rejected frame. Enforce a byte limit and timeout while reading the serial port, before accumulating a complete line; a parser limit alone does not bound receive-buffer growth. The recorded times are host receipt times, not sensor observation times. Add the device identity, observation timestamp, and boot/session identifier at the acquisition boundary when available [41].

Software range checks detect only some failures. A disconnected input can remain in range; a stuck sensor can be stable; a delayed frame can be valid but stale. Combine protocol checks, device status, freshness, rate-of-change, cross-sensor comparison, startup self-test, and physical reference tests.

51Embedded Linux — Fall 2026


4.15  Actuators, Drivers, Feedback, and Safe States

An actuator converts electrical command into physical action. GPIO cannot directly drive most motors, valves, relays, heaters, pumps, or solenoids. Drivers provide current and voltage capability; inductive loads require energy handling; moving systems require mechanical and electrical protection.

Open-loop actuation assumes the command produced the result. Closed-loop control measures output and corrects error. Feedback can fail, so define plausibility relationships: a commanded pump should produce flow or pressure within a time; an encoder should change consistently with motor command; a valve limit switch should agree with the requested state.

Define behavior for boot, shutdown, process crash, communication loss, stale command, sensor invalidity, driver fault, power recovery, and emergency stop. “Off” is not always the safest state: freezing protection may require limited heat, and a ventilation system may need a mechanical fail-open position. Safe state follows risk analysis.

ChatGPT Image Sep 20, 2026, 12_38_35 AMFigure 4.4. Actuator states with explicit authorization, timeout, fault, and reset transitions.

Command messages should contain identity, desired state or setpoint, unit, validity interval, sequence or operation ID, and authority. A receiver should reject stale, duplicated, out-of-range, unauthorized, or conflicting commands. A software watchdog is useful, but an independent hardware path may be required for risk reduction.

52Embedded Linux — Fall 2026
Block 415:00–15:50content

Block 4 · 15:00–15:50 · Actuators, Validation, and Sensor-to-Actuator Laboratory

Embedded Linux — Chapter 4 Part 4

4.16   A Reality-Based Sensor Validation Plan

Validation should reproduce expected use and expected abuse. A useful plan includes:

  1. verify identity, revision, interface, supply, logic level, and configuration;
  2. compare against a suitable reference across the intended range;
  3. test increasing and decreasing inputs for hysteresis;
  4. measure step response and effective delay;
  5. test noise and repeatability at constant input;
  6. vary temperature, humidity, supply, mounting, and orientation where relevant;
  7. expose saturation, recovery, disconnection, short circuit where safe, and invalid frames;
  8. test interference, cable length, bus load, and simultaneous devices;
  9. power-cycle and reconnect repeatedly;
  10. evaluate long-duration drift, contamination, condensation, and enclosure effects; and
  11. confirm that application quality flags and safe states match observed failures.

Keep raw observations. A plot of processed values alone cannot reveal whether filtering, clipping, or interpolation concealed the fault.

4.17   Guided Laboratory: Sensor-to-Actuator System

Laboratory objective
Integrate one digital or serial sensor and one low-risk indicator or properly driven actuator. Produce a timestamped measurement contract, characterize real dynamic and failure behavior, and demonstrate that invalid or stale data cannot command unsafe output.
Part A—selection and specification. Identify measurand, required range, target uncertainty, response time, sample rate, interface, supply, logic level, environment, placement, and expected life. Extract manufacturer specifications and distinguish typical from guaranteed values.
Part B—electrical interface. Draw power, reference, pull resistors, conversion or transceiver, driver, load supply, protection, and connector pins. Measure supply at the device under load before connecting signal pins.
Part C—acquisition contract. Record device ID, sequence, observation time, receive time, value, unit, raw value when accessible, status, and quality. Enforce bounded read time and maximum frame length.
Part D—characterization. Compare at three or more reference points where feasible. Perform a step test to estimate response time. Record constant-input noise and investigate self-heating or enclosure influence. State what your test cannot prove.
Part E—actuator state machine. Define SAFE, READY, ACTIVE, and FAULT states with guarded transitions. Implement command timeout, valid-range check, feedback or low-risk indication, and startup default.
Part F—fault injection. Test sensor disconnect, stuck or repeated data, saturation or simulated out-of-range input, bus error, delayed sample, application restart, and command timeout. Verify that every failure is visible and that physical output reaches the predefined safe condition.
54 Embedded Linux — Fall 2026
Portfolio evidence
Include requirements, selected sensor and alternatives, datasheet-derived limit table, complete wiring diagram, interface rationale, acquisition and validation code, calibration/reference procedure, raw and processed plots, response-time estimate, uncertainty discussion, state machine, fault-test matrix, and evidence of safe behavior. Clearly separate manufacturer claims, your measurements, and assumptions.

4.18   Self-Assessment and Job-Interview Preparation

These questions support Module 4 and future interviews in embedded systems, robotics, mechatronics, industrial automation, instrumentation, and precision agriculture. Strong answers connect specifications to physical mechanisms and failure behavior. Attempt every question before reading the answers.

Questions

Q1. Distinguish accuracy, precision, resolution, sensitivity, and uncertainty.

Q2. Why does a 16-bit ADC not guarantee 16-bit measurement accuracy?

Q3. A temperature reading is stable to 0.01 °C but differs from a traceable reference by 2 °C. What does this show?

Q4. Explain sensor saturation and give three ways software could detect it.

Q5. What is response time, and why can a protective enclosure change it?

Q6. Why can sampling too slowly create a false low-frequency signal? Can digital filtering after sampling always correct it?

Q7. Compare UART, I²C, SPI, RS-485, and CAN for sensor integration.

Q8. Why might an I²C bus work on a bench but fail with longer field wiring?

Q9. Explain the practical difference between a 0–10 V signal and a 4–20 mA loop.

Q10. What do PNP and NPN outputs mean in PLC-oriented sensors, and why must the PLC input type match?

Q11. Which processing occurs in a BME280, TFmini-type LiDAR, smart IMU, and GNSS receiver, and which work remains with the host?

Q12. Why does a digital sensor output not guarantee a correct measurement?

Q13. Explain why connecting a BME280 to an Arduino is integration rather than sensor-development research.

Q14. A wheel encoder reports movement, but the robot has not changed position. Give plausible explanations.

Q15. Why does IMU position drift rapidly when acceleration is integrated twice?

Q16. List major GNSS failure sources in agricultural fields and explain what RTK improves.

Q17. Why can a smooth precision-farming map still be scientifically wrong?

Q18. A sensor value remains within range but is stuck. How can the system detect the problem?

Q19. Why is a relay or motor unsafe to drive directly from GPIO?

Q20. Define a safe actuator response to sensor loss, network loss, stale command, and application restart.

Q21. Design a validation experiment that separates repeatability, hysteresis, response time, and drift.

Q22. A new sensor works once in a Python script but fails as a systemd service. What should be investigated?

55 Embedded Linux — Fall 2026
Answers and discussion

A1. Accuracy concerns closeness to a reference; precision concerns repeated agreement; resolution is the smallest represented change; sensitivity is output change per input change; uncertainty quantifies doubt under stated conditions. None is interchangeable with another.

A2. ADC reference tolerance, noise, nonlinearity, front-end gain and offset, sensor error, grounding, layout, source impedance, and calibration reduce effective accuracy. Sixteen bits describe code capacity, not trustworthy physical information.

A3. It shows good short-term precision or displayed resolution with substantial bias. Averaging may reduce random variation but will not remove the 2 °C systematic error.

A4. Saturation occurs when the chain no longer represents further input change. Detect exact repeated rail codes, device overrange/status flags, implausibly zero response to changing context, and disagreement with a redundant sensor or physical model.

A5. Response time specifies approach to a defined fraction of final output after change. An enclosure adds thermal mass, restricts airflow or diffusion, and may delay the physical stimulus reaching the sensing element.

A6. Frequencies above half the sampling rate can fold into lower apparent frequencies. Once aliased, samples do not uniquely retain the original frequency; an analog anti-alias filter and adequate sampling must act beforehand.

A7. UART is simple point-to-point asynchronous communication; I²C connects several addressed board-level devices with pull-ups; SPI offers high rate but more wires and chip selects; RS-485 provides differential long-distance physical signaling and needs a protocol; CAN adds arbitration and strong error handling for robust multidrop systems.

A8. Cable capacitance slows open-drain edges; ground noise, EMI, reflections, weak or excessive pull-ups, level mismatch, and a stuck device can violate timing. I²C was primarily designed for short board-level connections.

A9. 0–10 V is referenced voltage and is sensitive to voltage drop and ground difference. 4–20 mA represents information as loop current, tolerates cable voltage drop within compliance limits, and uses a live zero that can distinguish some wiring faults. Both need correctly designed receivers.

A10. A PNP sensor generally sources current to the input; an NPN sensor generally sinks it. The PLC input and common wiring must provide the complementary current path and correct polarity, or the signal will not be interpreted safely.

A11. BME280 performs conversion and configurable filtering and exposes factory coefficients; its host driver applies compensation to the raw channels; TFmini performs optical timing and echo processing to estimate range; a smart IMU may calibrate/filter and fuse inertial channels into orientation; GNSS correlates radio signals, estimates timing, and solves navigation state. Each output embeds assumptions and latency.

A12. The sensing element can drift, saturate, be badly placed, or experience cross-sensitivity. Firmware can apply undocumented filtering or compensation. Digital communication protects representation from some noise but does not prove physical validity.

A13. It applies an existing transducer, calibration, interface, and library. Sensor development creates or materially advances the transduction principle, material, structure, electronics, packaging, calibration, or inference and validates the contribution against alternatives.

A14. Wheels can slip or spin, the robot can be lifted, encoder coupling can be loose, counts can be assigned to the wrong wheel, electrical noise can create edges, direction can be reversed, or the kinematic model can be incorrect. Encoder motion is shaft motion, not guaranteed global displacement.

A15. Small accelerometer bias and orientation error create velocity error through integration and position error through a second integration. Gravity projection error is especially damaging. External references and a valid estimator are required to bound drift.

56 Embedded Linux — Fall 2026

A16. Blockage, multipath, antenna placement, canopy, nearby structures, interference, poor satellite geometry, correction loss, wrong coordinate frame, and incorrect fix interpretation are common. RTK uses carrier-phase corrections to support centimeter-level relative positioning under suitable conditions; it does not remove blockage or bad installation.

A17. Interpolation and filtering can create smooth surfaces from biased, badly placed, stale, sparse, or environmentally confounded measurements. Georeferencing precision does not establish agronomic validity.

A18. Track freshness, sequence progression, variance over a physically meaningful window, response to known excitation or self-test, rate consistency, status flags, and comparison with related variables. Do not declare failure merely because a genuinely constant process is stable.

A19. GPIO lacks load current and voltage capability and is vulnerable to inductive voltage. Use a transistor or driver, gate/base network, flyback or appropriate energy suppression, separate rated supply, protection, and possibly isolation.

A20. Define a risk-based local state: reject invalid sensing, stop or limit actuation, expire remote authority after a timeout, initialize outputs safely before application startup, require checks before READY, and make reset deliberate. The safest physical state depends on the hazard analysis.

A21. Repeat constant reference points for short-term variation; approach the same points from increasing and decreasing directions for hysteresis; apply a controlled step and measure defined settling criteria; repeat calibrated points over days or environmental cycles for drift. Preserve raw data and reference uncertainty.

A22. Compare service identity, groups, device ownership, working directory, environment variables, paths, permissions, startup ordering, timeout, and logs. An interactive shell may provide groups, current directory, environment, and terminal behavior absent from the service.

Chapter summary
Sensors do not deliver truth automatically. They deliver observations shaped by transduction, electronics, calibration, dynamics, placement, environment, onboard and host algorithms, interfaces, and software. Professional systems preserve units, identity, timing, status, uncertainty, and raw evidence; recognize saturation, drift, delay, cross-sensitivity, and disconnection; and select electrical interfaces appropriate to the environment. Robotics and precision agriculture depend on complementary sensing and explicit frames, time, and quality. Actuation adds physical consequence, so drivers, feedback, interlocks, timeouts, and independently justified safe states are essential.
57 Embedded Linux — Fall 2026

Summary

This chapter presents a practical framework for integrating sensors, actuators, GPIO, and communication interfaces in embedded systems. It begins with the measurement chain and sensor specifications, then introduces calibration, uncertainty, traceability, dynamic response, sampling, aliasing, and filtering. The chapter reviews representative sensors for embedded and robotic systems and industrial/PLC-oriented interfaces, followed by common communication interfaces and GPIO electrical safety. It also discusses smart sensors, sensor integration in robotics and mechatronics, GNSS and multi-sensor systems for precision farming, Linux device access, actuator state management, sensor validation, and a guided sensor-to-actuator laboratory.

Course outline

What we will learn

From Linux foundations to physical interfaces, networking, security and a complete embedded system.

Linux foundationsKernel, users, processes and file systems
Command lineShells, scripting and automation
Embedded hardwareBoot, storage and device drivers
Physical I/OGPIO, sensors and actuators
Device busesUART, I²C and SPI
NetworkingTCP/IP, SSH and remote management
Distributed systemsMessage passing and cooperating nodes
Engineering practiceGit, testing, logging and deployment
SecurityLeast privilege, updates and secrets

Teaching method

Short introductions are followed by laboratory activities. Work is normally completed in teams of three. Each team develops an embedded Linux system; the examination portfolio is individual.

Project ideas

Applications you could build

Each project should begin with one reliable end-to-end function.

Automatic Raspberry Pi-based GPS trackerSample examination report available in PDF format
Environmental monitoring stationValidated sensing, local storage and dashboard
Energy monitoring systemMeasure, log and visualize equipment power use
Greenhouse automationClimate sensing, actuation and remote supervision
Field-robot telemetryLocation, operating state, measurements and faults
LoRaWAN sensor networkField nodes, TTN integration and private cloud
Intelligent irrigationSensing, decisions, valves and safe failure handling
Multi-node IoT gatewayProtocol translation, buffering and secure forwarding
ROS 2 communication systemDistributed nodes, QoS and service integration
Edge-AI monitoring systemLocal inference, measured performance and safe fallback

A complete project should demonstrate

NeedA clear user and purpose
Physical interfaceA sensor, actuator or device
Linux integrationPrograms, scripts or services
CommunicationA justified data-exchange method
ReliabilityLogging and failure handling
EvidenceTests, results and reflection

Contractor and client roles

Project groups

Each group develops a project for one client group and evaluates the project received from another contractor group.

Contractor

Heros

ProjectProject 01
Delivers to
Client not assigned
Receives from
Contractor not assigned

Fridays · four 50-minute slots · Odense

Fall 2026 lecture plan

The SDU timetable remains authoritative for dates, times and rooms.

Project progression

Project ideas and proposals begin in Module 1 and evolve throughout the course. Module 10 is the formal integration, architecture and verification review; Modules 11–12 complete implementation, demonstration and individual portfolio evidence.

Lecture 04 · participation

Student questions

Questions remain hidden until the student is called. Model answers are revealed separately.

Instructor classroom view

The roster, answers, attendance and participation records are available only to the authorized primary owner after sign-in.

Instructor sign in

Definitions

Essential course vocabulary

Plain-language definitions for the technical terms used throughout the course.

TermDefinitionExample
ActuatorA device that produces a physical action.Motor, valve, relay or fan
BootThe sequence that starts the hardware, kernel, services and applications.Starting an embedded computer
CLIA text interface that accepts commands.Windows Terminal or a Linux terminal
CommandAn instruction interpreted by a shell.pwd, ls or Get-Location
Device driverSoftware through which the operating system communicates with hardware.GPIO or camera driver
DirectoryA named container for files and other directories./home/student/eml
DistributionA complete operating system built around the Linux kernel.Ubuntu or Debian
Embedded systemA computer integrated into a larger product for a defined purpose.Greenhouse controller
File systemThe structure used to name, store and retrieve files.ext4
GPIOA configurable digital input or output pin.Reading a switch
I²CA two-signal serial bus for peripherals.Environmental sensor
KernelThe privileged core managing memory, processors, devices and processes.Linux kernel
MQTTA lightweight publish/subscribe messaging protocol.Sending sensor data
ProcessA running instance of a program.A data logger
PWMRapid switching used to control average power or a signal duty cycle.Motor speed
RootThe privileged Linux user or the top directory, depending on context.Administrative access
ScriptA file containing commands that automate work.A backup script
SensorA device that converts a physical quantity into data.Temperature sensor
ServiceA background program providing an ongoing function.SSH server
ShellA program that interprets commands and starts programs.Bash or PowerShell
SPIA synchronous bus commonly used for fast peripherals.Display or converter
SSHEncrypted remote command-line access.Managing a Raspberry Pi
TCP/IPThe principal protocol family used across computer networks.Device-to-server communication
UARTAn asynchronous serial interface.Debug console
User spaceThe environment where ordinary programs run outside the kernel.Application software
Version controlA system that records and manages file changes.Git

Official examination information · EKA T550077102

Individual portfolio examination

Form

Portfolio

Individual presentation portfolio submitted at semester end.

Grade

7-point scale

No second examiner.

Weighting

No split published

No separate written-exam or coursework percentages are stated.

Re-examination

Same form

Same form as the ordinary examination.

Team project and individual assessment

The team project creates practical evidence, but each student is assessed individually through the presentation portfolio. Classroom participation points support engagement and do not form part of the official grade.

Document from the beginning

  • Your own decisions and identifiable contribution
  • Commands, code, configuration and version history
  • Tests, results, failures and improvements
  • Reflection on trade-offs and learning

People and course systems

Contacts and official links