Sensors, Actuators and Hardware InterfacingIntroductionEmbedded systems interact with the physical world through sensors and actuators. A sensor converts a physical variable—such as temperature, pressure, light, acceleration, or position—into an electrical signal. An actuator converts an electrical command into physical action, such as motion, illumination, heating, switching, or fluid control. The interface between these devices and a microcontroller is not merely a matter of connecting wires. It involves signal conditioning, electrical compatibility, timing, power integrity, grounding, isolation, protection, and software coordination. At postgraduate level, interface design must be treated as a system-engineering problem. A successful design satisfies functional requirements while also managing uncertainty, noise, safety, electromagnetic compatibility, lifetime, manufacturability, and cost. This chapter develops the principles required to design interfaces for GPIO, timers, PWM, ADC/DAC systems, displays, motors, and common sensors. Learning ObjectivesAfter completing this chapter, the reader should be able to: 1. Distinguish the electrical and functional roles of GPIO, timers, PWM, ADCs, DACs, and communication interfaces. 2. Design basic signal-conditioning and protection circuits for sensors. 3. Select suitable interfaces for displays, relays, solenoids, DC motors, stepper motors, and servomotors. 4. Analyse resolution, sampling, timing, loading, noise, grounding, and isolation requirements. 5. Evaluate electrical compatibility between sensors, actuators, and embedded processors. 6. Apply a structured method to develop and validate a reliable embedded hardware interface. 1. Interface Architecture and Electrical CompatibilityA typical measurement or control chain is: physical variable → sensing element → signal conditioning → conversion or communication → processor → driver → actuator → physical system Each stage has a distinct responsibility. The sensing element provides transduction; conditioning may amplify, filter, linearize, or isolate the signal; the processor performs estimation and decision-making; and the driver supplies the voltage and current required by the actuator. Important electrical compatibility parameters include: - Voltage levels: A 5 V sensor output must not be connected directly to a 3.3 V-only input unless the input is 5 V tolerant or a level translator is used.
- Current capability: A GPIO pin is generally intended for logic-level loads, not motors, relays, lamps, or solenoids.
- Input and output impedance: Loading can alter an analogue signal. A high-impedance sensor may require a buffer.
- Logic thresholds: A valid high and low are defined by the receiving device, not only by nominal supply voltage.
- Rise and fall times: Capacitance, pull-up resistance, and driver strength affect timing.
- Reference compatibility: Analogue measurements depend on the ADC reference and the sensor ground.
- Protection: Transient voltage suppressors, series resistors, current limiting, filtering, and reverse-polarity protection may be necessary.
A data sheet should be treated as a design document rather than a catalogue. Absolute maximum ratings describe survival limits, not recommended operating conditions. Recommended operating conditions, input leakage, output drive, conversion timing, and thermal limits must also be checked. 2. GPIO and Digital InterfacingA general-purpose input/output (GPIO) pin can usually be configured as a digital input, push-pull output, open-drain or open-collector output, and sometimes an alternate-function pin for a timer or serial peripheral. A push-pull output actively drives both logic states. It is suitable for a single digital input but should not be connected directly to another actively driven output. An open-drain output actively pulls the line low and relies on an external or internal pull-up for the high state. It permits wired signalling and level translation, provided that the devices share compatible voltage and the total bus capacitance is acceptable. For a pull-up resistor connected to a supply voltage VDD, the approximate low-state current when the output transistor pulls the line low is I = VDD / R_P, where R_P is the pull-up resistance. The resistor must be low enough to provide an acceptable rise time and high enough to limit sinking current. For an RC-dominated rising edge, the voltage reaches approximately 63.2% of its final value after one time constant τ = R_P C_B, where C_B is the total bus capacitance. A smaller resistor improves speed but increases static current and may exceed the sink-current rating. Mechanical switches require debouncing because contact bounce can produce several transitions within milliseconds. Hardware debouncing may use an RC network and a Schmitt-trigger input. Software debouncing may sample the input periodically and accept a new state only after it remains stable for a specified interval. Interrupts are useful for genuinely asynchronous events, but an interrupt should not be interpreted as proof that a switch changed only once. GPIO design should also address unused pins, boot-strap pins, alternate-function conflicts, reset states, and fail-safe behaviour. Inputs should not be left floating unless the device explicitly supports that condition. Pull resistors establish a defined state during reset and power sequencing. 3. Timers, Capture, Compare and PWMMicrocontroller timers count clock ticks and support event generation, input capture, output compare, pulse measurement, periodic interrupts, and pulse-width modulation (PWM). If a timer clock has frequency f_CLK and a prescaler divides it by N, the timer tick period is T_tick = N / f_CLK. For an up-counting timer with period register value ARR, the PWM frequency is commonly f_PWM = f_CLK / [N(ARR + 1)], assuming the timer counts from zero through ARR and no additional centre-aligned factor applies. The exact expression must be verified against the particular microcontroller's timer mode. For edge-aligned PWM, if the compare value is CCR and the timer period is ARR + 1 counts, the ideal duty ratio is approximately D = CCR / (ARR + 1), with implementation details depending on whether CCR = 0 and the timer's compare semantics are special cases. Duty ratio is often expressed as a percentage: D_percent = 100D. PWM controls average power when the load responds slowly relative to the switching period. For an ideal resistive load driven between 0 and V_H, the average voltage is approximately D V_H, while average power is D V_H²/R only when the load and switching conditions justify that interpretation. Motors are not simple resistors: inductance, back electromotive force, commutation, speed, and controller topology determine the actual current and torque. Timer capture measures the time between input events. It is useful for frequency, pulse width, encoder period, and ultrasonic time-of-flight measurement. Measurement resolution is limited by timer clock frequency, prescaling, interrupt latency, input synchronisation, and jitter. At high event rates, hardware capture is preferable to software polling. 4. Analogue Sensors, ADCs and Signal ConditioningAn analogue-to-digital converter (ADC) maps an input voltage to a code. For an ideal n-bit ADC with input range 0 to V_REF, the nominal code width is q = V_REF / 2^n. The ideal quantisation uncertainty is commonly represented as approximately ±q/2, although real accuracy is affected by offset, gain error, integral nonlinearity, differential nonlinearity, reference error, noise, and sampling effects. The conversion code should not be described as having unlimited accuracy merely because its nominal resolution is high. The ADC input must remain within its specified range. A voltage divider can scale a signal: V_OUT = V_IN R_2/(R_1 + R_2), where R_1 is connected from the input to the output node and R_2 from the output node to ground. The divider draws current and its Thevenin resistance is R_TH = R_1 || R_2. If the ADC sample-and-hold capacitor requires a low source impedance, a buffer amplifier or longer acquisition time may be necessary. Signal conditioning commonly includes: - amplification for low-level signals;
- attenuation for over-range signals;
- low-pass filtering for anti-aliasing and noise reduction;
- level shifting for bipolar signals entering a unipolar ADC;
- bridge completion for strain gauges and load cells;
- linearization for thermistors and other nonlinear sensors;
- galvanic isolation where safety or ground potential differences exist.
For a first-order RC low-pass filter, the cutoff frequency is f_c = 1/(2πRC), where R and C are the resistance and capacitance. This formula assumes an ideal source and negligible loading. The filter attenuates frequencies above the cutoff at approximately 20 dB per decade in the asymptotic region. Anti-alias filtering must be designed in relation to the sampling frequency, not selected solely because it smooths the waveform. Sampling must satisfy the Nyquist condition for band-limited signals: the sampling frequency must exceed twice the highest frequency component to be reconstructed. In practice, transition bands, interference, and nonideal filters require margin. Oversampling can reduce in-band quantisation noise under suitable assumptions, but it does not correct aliasing that has already occurred. Ratiometric measurement is valuable when the sensor output and ADC reference depend on the same supply. Supply variation then tends to cancel in the ratio. However, this does not remove errors caused by sensor nonlinearity, reference noise, layout coupling, or temperature drift. A differential instrumentation amplifier is appropriate for small differential signals in the presence of common-mode voltage. Its common-mode rejection ratio (CMRR) is important, but practical CMRR decreases with frequency and resistor mismatch. The amplifier's input common-mode range, output swing, input bias current, noise density, offset, bandwidth, and power-supply requirements must all be verified. 5. DACs and Waveform GenerationA digital-to-analogue converter (DAC) produces an analogue output from a digital code. DAC architectures include resistor-string, R-2R, current-steering, and sigma-delta types. Important specifications are resolution, settling time, monotonicity, integral and differential nonlinearity, output range, reference dependence, glitch impulse, and load-driving capability. When a microcontroller lacks a DAC, filtered PWM can generate a slowly varying voltage. The load must be high impedance or buffered, and the filter must balance ripple against response time. This method is unsuitable for signals requiring precise instantaneous voltage unless its dynamic limitations are acceptable. 6. Sensors and Communication InterfacesDigital sensors may communicate through I2C, SPI, UART, 1-Wire, CAN, USB, or specialised interfaces. Communication reduces analogue-layout sensitivity but does not eliminate system-level concerns. Digital sensors still require appropriate supply decoupling, bus pull-ups, address management, timing margins, electromagnetic compatibility, and error handling. I2C uses open-drain signalling and therefore requires pull-up resistors. Its rising edge is determined by pull-up resistance and bus capacitance. SPI generally offers higher throughput and simpler timing but requires chip-select management and often uses one select line per peripheral. UART provides asynchronous point-to-point communication and requires agreement on baud rate, framing, and logic levels. CAN uses differential signalling, arbitration, termination, and robust error detection, making it suitable for electrically noisy distributed systems. Sensor software should validate plausibility, detect missing or stale data, distinguish a real zero from a communication failure, and record diagnostic status. Calibration data should be versioned and protected against accidental modification. 7. Actuator Interfaces7.1 Low-side and high-side switchingA transistor or MOSFET driver is normally required between a processor and a high-current load. In a low-side N-channel MOSFET circuit, the load connects to the positive supply and the MOSFET switches its return path. The gate must receive sufficient voltage for the required current; a device with a low threshold voltage is not necessarily fully enhanced at the chosen gate voltage. A flyback diode is required across inductive loads such as relays, solenoids, and many DC motors when the switching device cannot tolerate the inductive voltage transient. The diode's current, reverse-voltage rating, recovery behaviour, and placement must be appropriate. A diode slows current decay; a TVS, zener clamp, or active clamp may be selected when faster release is required. High-side switching may be implemented with P-channel MOSFETs, PNP transistors, or dedicated high-side drivers. It preserves the load's ground reference but may require gate-level translation and charge-pump circuitry. 7.2 DC motorsA DC motor requires a driver capable of handling starting current, stall current, switching losses, and regenerative energy. An H-bridge permits forward and reverse operation. PWM controls average voltage and therefore, indirectly, speed, while current determines torque over the motor's operating region. Current sensing supports protection, torque control, stall detection, and closed-loop regulation. Dead time is required in complementary bridge switching to prevent shoot-through. Excessive dead time increases distortion and losses; insufficient dead time risks catastrophic cross-conduction. Gate-driver propagation delays and Miller effects must be included in the timing analysis. 7.3 Stepper and servo motorsA stepper motor is controlled by phase currents and step sequence. Microstepping improves smoothness but does not guarantee proportional mechanical accuracy under load. A current-regulated driver is generally preferred because winding resistance and back EMF vary during operation. A hobby servomotor commonly interprets a periodic pulse whose width represents a position command, but the exact pulse range and update requirements are device-specific. Industrial servomotors normally use a closed-loop drive with encoder feedback. The terminology must therefore be interpreted in context. 7.4 Relays and solenoidsRelays provide galvanic separation between contacts and coils but have finite switching speed, contact wear, arcing, and electromagnetic emissions. A transistor driver, coil suppression, and appropriate contact rating are required. Safety-critical switching should not rely on a microcontroller GPIO state alone; a defined hardware-safe state is necessary during reset and software failure. 8. Displays and Human InterfacesLED indicators require current limiting. For a simple resistive LED circuit, an approximate resistor value is R = (V_S - V_F)/I_F, where V_S is the supply voltage, V_F is the LED forward voltage at the intended current, and I_F is the desired forward current. The resistor power is approximately P_R = I_F²R. Tolerances, temperature, multiplexing duty cycle, and processor sink/source limits must be considered. Seven-segment and matrix displays are often multiplexed. Each digit or row is enabled for a short interval, and persistence of vision creates the appearance of continuous illumination. The refresh rate must avoid visible flicker, while peak current must remain within display and driver ratings. Multiplexing reduces average brightness and can increase electromagnetic interference. Character and graphical displays may use parallel, SPI, I2C, or dedicated controllers. Designers should account for initialization timing, busy states, reset behaviour, contrast generation, backlight current, and data integrity. A display interface can become a significant real-time load if large graphical updates are performed synchronously. 9. Noise, Grounding, Isolation and EMCNoise has conducted and radiated components. Common sources include switching converters, PWM edges, motor commutation, clock harmonics, relay contacts, and shared return impedance. A practical design separates noisy power paths from sensitive analogue paths and joins grounds according to a controlled current-return strategy rather than an arbitrary physical drawing. Decoupling capacitors should be placed close to device supply pins with short, low-inductance connections. Bulk capacitance supports lower-frequency load changes, while small ceramic capacitors reduce high-frequency supply impedance. A ground plane can reduce loop area, but gaps and high-current returns must be planned carefully. Shielding, twisted pairs, differential signalling, common-mode chokes, ferrites, filtering, slew-rate control, and enclosure design may be used to improve EMC. Filters must be assessed for their effect on signal integrity and stability. Galvanic isolation is appropriate when grounds may differ substantially, when a hazardous voltage is present, or when a ground loop would compromise measurement. Options include optocouplers, isolated digital interfaces, transformers, isolated amplifiers, and isolated DC-DC converters. Isolation requires attention to creepage, clearance, insulation rating, common-mode transient immunity, and safe fault behaviour. An optocoupler alone does not guarantee a safe system if the PCB layout violates creepage requirements. 10. Timing, Reliability and VerificationHardware and software must be co-designed. A sensor's conversion time, bus transaction duration, filtering delay, control-loop period, actuator response, and watchdog timeout form a timing budget. Excessive filtering improves noise performance but introduces delay and phase shift, potentially destabilising a control loop. Reliability practices include derating components, protecting against reverse polarity and transients, using thermal analysis, checking startup and brownout states, and testing worst-case tolerances. Design verification should include: 1. schematic and pin-multiplexing review; 2. electrical rule and power-budget checks; 3. simulation or calculation of analogue and switching networks; 4. oscilloscope measurements of rise time, ringing, PWM dead time, and supply transients; 5. calibration and accuracy testing across temperature and supply limits; 6. fault injection, such as unplugged sensors, short circuits, stuck buses, and stalled motors; 7. EMC pre-compliance testing and documented corrective actions. A robust interface defines what happens when a sensor is disconnected, a bus is stuck low, a motor stalls, a watchdog resets the processor, or a power rail collapses. Fail-safe design is a functional requirement, not an optional refinement. Worked Example: ADC Interface for a ThermistorConsider a 10-bit ADC with V_REF = 3.3 V. A sensor signal ranges from 0.20 V to 2.80 V. The ideal code width is q = 3.3/1024 = 3.2227 mV. The sensor fits within the ADC range, so no attenuator is required. If the sensor output has significant high-frequency noise, an RC filter may be placed at the ADC input. Suppose R = 1 kΩ and C = 100 nF. Then f_c = 1/(2π × 1000 × 100 × 10^-9) ≈ 1.59 kHz. This filter attenuates interference well above 1.59 kHz, but its suitability depends on the sensor bandwidth and ADC sampling rate. If the sensor is sampled at 10 kS/s, the filter alone may not provide sufficient attenuation near the Nyquist frequency of 5 kHz. A higher-order anti-alias filter or a lower cutoff may be necessary, provided the resulting settling time remains acceptable. The example illustrates that component selection must be based on both noise and dynamic requirements. Applied Case: Isolated Motorised Valve ControllerBackgroundThe following is an illustrative case. A process controller must measure a 4–20 mA pressure transmitter and drive a 24 V motorised valve. The controller uses a 3.3 V microcontroller and shares a cabinet with a variable-speed drive. ProblemThe pressure signal is small and may be exposed to common-mode interference. The valve has a high startup current and generates inductive transients. A software reset must not leave the valve energised indefinitely. AnalysisThe current-loop input is converted to a voltage using a precision shunt resistor and differential amplifier. The maximum signal is checked against the ADC range, including tolerance and fault overvoltage. The motor driver is rated for stall current, not merely nominal running current. The variable-speed drive creates a high-noise environment, so cable routing, shield termination, filtering, and isolation are considered. Approach and SolutionThe analogue front end uses a protected shunt, a low-noise differential amplifier, an RC anti-alias filter, and an ADC input whose source impedance meets the acquisition requirement. The valve is driven by an isolated H-bridge with current sensing, hardware overcurrent protection, and a defined disabled state. A watchdog and independent timeout de-energise the actuator if valid control commands are not refreshed. Galvanic isolation separates the field wiring from the processor domain. The firmware checks loop plausibility, detects open-circuit and over-range conditions, and logs faults. OutcomeThe resulting design separates measurement and power returns, limits motor transients, prevents unsafe indefinite actuation, and provides diagnostic information. Verification includes injected sensor faults, stalled-valve tests, power interruption, EMC testing, and temperature cycling. Learning PointsThe case demonstrates that interface design is multidisciplinary. Correct ADC resolution alone does not ensure measurement quality, and a correctly rated motor driver does not ensure safety. Signal integrity, energy flow, fault response, timing, and maintainability must be considered together. Challenges, Limitations and Contemporary DevelopmentsInterface designs face trade-offs between bandwidth, noise, power, size, cost, and safety. Integrated sensor modules simplify hardware but can obscure calibration assumptions and create software dependencies. Highly integrated motor drivers reduce component count but may complicate thermal analysis and fault diagnosis. Modern systems increasingly use time-synchronised networks, smart sensors, edge processing, and machine-learning-based anomaly detection. AI can assist in detecting sensor drift, bearing faults, or abnormal actuator current, but it does not replace electrical protection or deterministic safety mechanisms. Training data may be biased toward normal operating conditions, and false alarms must be managed. Cybersecurity is also relevant to networked sensors and actuators. Authentication, secure firmware updates, least-privilege access, audit logging, and protection against replay or spoofing should be considered where a compromised interface could cause physical harm. Safety, EMC, and functional requirements should be mapped to applicable institutional, industrial, and regulatory standards; exact compliance depends on the application domain and jurisdiction. Best-Practice Design Workflow1. Specify the physical variable, required accuracy, bandwidth, latency, operating environment, and fault response. 2. Identify sensor and actuator electrical limits, including startup, transient, and worst-case values. 3. Select analogue, digital, isolated, or differential signalling as appropriate. 4. Calculate scaling, loading, ADC resolution, filter response, timer settings, and power dissipation. 5. Define protection, grounding, return-current paths, and safe reset states. 6. Check component tolerances, temperature range, ageing, and derating. 7. Prototype with measurement equipment and verify actual waveforms rather than relying only on nominal calculations. 8. Test normal operation, boundary conditions, faults, EMC, and recovery from reset or power interruption. 9. Document calibration, assumptions, test evidence, and revision history. Chapter SummarySensors and actuators form the physical boundary of an embedded system. Reliable interfacing requires more than matching signal names: voltage, current, impedance, timing, grounding, noise, protection, isolation, and fault behaviour must be analysed together. GPIOs require defined logic states and suitable loading; timers support precise event measurement and PWM; ADCs require correct reference, scaling, acquisition, filtering, and error analysis; DACs and filtered PWM provide controlled analogue outputs. Inductive actuators require appropriate switching devices, clamps, and often current regulation. Displays require current limiting, multiplexing analysis, and timing control. Grounding, decoupling, EMC practices, and galvanic isolation determine whether a theoretically correct circuit operates reliably in the field. Verification must include worst-case conditions and deliberate fault testing. Key TermsGPIO: Configurable digital input/output pin. Push-pull output: Output that actively drives both logic high and logic low. Open-drain output: Output that actively pulls low and requires a pull-up for high logic. Debouncing: Suppression of unwanted transitions caused by mechanical contact bounce. PWM: Pulse-width modulation used to control average power or encode a command. Input capture: Timer function that records timer values at external events. ADC: Converter that maps an analogue input to a digital code. DAC: Converter that produces an analogue output from a digital code. Quantisation: Discretisation of a continuous amplitude into finite digital codes. Anti-alias filter: Filter that limits signal bandwidth before sampling. CMRR: Ability of a differential amplifier to reject common-mode signals. Ratiometric measurement: Measurement in which signal and reference share a varying supply relationship. Flyback diode: Suppression diode used across an inductive load. H-bridge: Switching topology allowing bidirectional motor drive. Shoot-through: Undesired simultaneous conduction of complementary bridge switches. Galvanic isolation: Transfer of power or information without a direct conductive connection. Creepage: Surface distance between conductive parts across an insulating material. Clearance: Shortest distance through air between conductive parts. Decoupling: Local supply bypassing that reduces voltage disturbance and noise. Fail-safe state: Defined condition that limits hazard after a fault or loss of control. Review QuestionsShort Answer Questions1. Why is a GPIO pin unsuitable for directly driving a motor? 2. What is the function of a flyback diode? 3. Define ADC quantisation width for an ideal n-bit converter. 4. Why are pull-up resistors required for open-drain buses? 5. Distinguish creepage from clearance. Long Answer Questions1. Explain the design and verification of an analogue sensor interface, including scaling, buffering, filtering, ADC acquisition, and error sources. 2. Describe PWM generation using a hardware timer and discuss frequency, duty ratio, resolution, and timing limitations. 3. Compare low-side and high-side switching for inductive actuators. 4. Explain grounding, decoupling, shielding, and galvanic isolation in a noisy embedded system. 5. Develop a complete interface architecture for a microcontroller-controlled DC motor, including protection and fault handling. Analytical / Application Questions1. A 3.3 V, 12-bit ADC measures a 0–10 V sensor. Design a resistor divider with a nominal output of 3.0 V at 10 V input, and discuss loading, tolerance, and overvoltage protection. 2. A PWM timer runs at 48 MHz with a prescaler of 47 and ARR of 999. Calculate the PWM frequency and explain how changing ARR affects frequency and duty-cycle resolution. 3. Design a fault strategy for a motorised valve that must move to a safe state after sensor disconnection, processor reset, communication loss, or motor stall. Multiple Choice Questions with AnswersQuestion 1For an ideal 10-bit ADC with a 3.3 V reference, what is the nominal code width? A. 0.323 mV B. 3.22 mV C. 32.2 mV D. 330 mV Correct Answer: B. 3.22 mV Question 2What is the principal purpose of a flyback diode across a relay coil? A. To increase coil current during steady state B. To reduce the inductive voltage transient when switching off C. To convert DC into AC D. To provide galvanic isolation from the processor Correct Answer: B. To reduce the inductive voltage transient when switching off Question 3An open-drain digital bus normally requires a pull-up resistor because the output device A. can actively drive only the low state B. can actively drive only the high state C. cannot sink any current D. must operate without a supply voltage Correct Answer: A. can actively drive only the low state Question 4For an RC low-pass filter, increasing R while keeping C constant causes the cutoff frequency to A. increase B. decrease C. remain unchanged D. become equal to the sampling frequency Correct Answer: B. decrease Question 5Which interface is most directly associated with bidirectional motor control? A. Voltage divider B. H-bridge C. Pull-up network D. Instrumentation amplifier Correct Answer: B. H-bridge Question 6What is the main danger of insufficient dead time in a complementary motor bridge? A. ADC quantisation B. Visible display flicker C. Shoot-through current D. Reduced sensor bandwidth Correct Answer: C. Shoot-through current Question 7A 1 kΩ resistor and a 100 nF capacitor form a first-order RC filter. Its approximate cutoff frequency is A. 15.9 Hz B. 159 Hz C. 1.59 kHz D. 15.9 kHz Correct Answer: C. 1.59 kHz Question 8Which measurement is especially suited to timer input capture? A. Motor shaft frequency from encoder pulses B. LED forward voltage without a reference C. PCB creepage distance D. MOSFET package temperature without a sensor Correct Answer: A. Motor shaft frequency from encoder pulses Question 9What does galvanic isolation prevent? A. All electromagnetic radiation B. Any need for signal conditioning C. Direct conductive current between two circuit domains D. All timing jitter Correct Answer: C. Direct conductive current between two circuit domains Question 10For a 48 MHz timer clock, prescaler 47, and ARR 999, the PWM frequency in edge-aligned up-counting mode is A. 100 Hz B. 1 kHz C. 10 kHz D. 48 kHz Correct Answer: B. 1 kHz
|