5 min read
On this page

Sensor and Actuator Systems

Sensor Types

Temperature Sensors

Sensor Type Range Accuracy Interface
DS18B20 Digital (1-Wire) -55 to +125C +/-0.5C 1-Wire
LM35 Analog (voltage) -55 to +150C +/-0.5C Analog
BME280 Digital (I2C/SPI) -40 to +85C +/-1C I2C/SPI
Thermistor (NTC) Analog (resistance) -40 to +300C 1-5% Analog + divider
Thermocouple (K) Analog (voltage) -200 to +1350C +/-2C Analog + amplifier

Thermistors follow the Steinhart-Hart equation: 1/T = A + B*ln(R) + C*(ln(R))^3

Inertial Measurement Unit (IMU)

An IMU combines multiple motion sensors:

Accelerometer -- measures linear acceleration (including gravity)

  • Principle: MEMS proof mass displacement
  • Output: 3-axis acceleration in g (1g = 9.81 m/s^2)
  • Used for: tilt detection, step counting, vibration monitoring

Gyroscope -- measures angular velocity

  • Principle: Coriolis effect on vibrating MEMS structure
  • Output: 3-axis rotation rate in degrees/second
  • Used for: rotation tracking, stabilization, navigation
  • Suffers from drift over time

Magnetometer -- measures magnetic field

  • Principle: Hall effect or magnetoresistive
  • Output: 3-axis magnetic field in microtesla
  • Used for: compass heading, position sensing
  • Affected by hard/soft iron distortion from nearby metals

Common IMU chips: MPU-6050 (6-axis), MPU-9250 (9-axis), BNO055 (9-axis with onboard fusion), LSM6DSO (6-axis).

Proximity and Distance Sensors

Sensor Technology Range Resolution
HC-SR04 Ultrasonic 2cm - 4m ~3mm
VL53L0X Time-of-Flight laser 3cm - 2m 1mm
Sharp GP2Y0A21 Infrared triangulation 10cm - 80cm Variable
LiDAR (TFMini) Time-of-Flight laser 0.3 - 12m 1cm

Gas Sensors

Sensor Detected Gas Principle
MQ-2 LPG, methane, smoke Metal oxide semiconductor
MQ-135 Air quality (NH3, NOx, CO2) Metal oxide semiconductor
SGP30 TVOC, eCO2 MOX with I2C digital output
SCD40 CO2 (true) Photoacoustic NDIR
BME680 VOC, temp, humidity, pressure MOX + environmental combo

MQ-series sensors require a burn-in period and calibration. Digital sensors like SGP30 and SCD40 provide factory-calibrated output.

Reading a Sensor in Embedded Rust

BME280_ADDR ← 0x76

STRUCTURE Bme280Reading
    temperature: real   // Celsius
    pressure: real      // hPa
    humidity: real      // %RH

PROCEDURE READ_BME280(i2c) → Bme280Reading or error
    raw ← array of 8 bytes
    I2C_WRITE_READ(i2c, BME280_ADDR, [0xF7], raw)

    // Apply compensation formulas from datasheet
    // (simplified here -- real code uses calibration data)
    adc_t ← (raw[3] << 12) OR (raw[4] << 4) OR (raw[5] >> 4)
    temperature ← COMPENSATE_TEMPERATURE(adc_t)

    RETURN Bme280Reading(temperature, pressure ← 1013.25, humidity ← 50.0)

Sensor Fusion

Raw sensor data is noisy and incomplete. Sensor fusion combines multiple sensors to produce a more accurate estimate than any single sensor alone.

Complementary Filter

Combines high-frequency data (gyroscope) with low-frequency data (accelerometer) using a simple weighted blend:

angle = alpha * (angle + gyro_rate * dt) + (1 - alpha) * accel_angle

Where alpha is typically 0.95-0.98. The gyroscope provides short-term accuracy (no vibration noise) while the accelerometer prevents long-term drift.

STRUCTURE ComplementaryFilter
    angle: real
    alpha: real

PROCEDURE NEW_FILTER(alpha) → ComplementaryFilter
    RETURN ComplementaryFilter(angle ← 0.0, alpha ← alpha)

PROCEDURE UPDATE(filter, gyro_rate, accel_angle, dt) → real
    filter.angle ← filter.alpha * (filter.angle + gyro_rate * dt)
                  + (1.0 - filter.alpha) * accel_angle
    RETURN filter.angle

Kalman Filter

Optimal recursive estimator that predicts state, then corrects using measurements. Handles noise statistically.

Predict step:

x_pred = A * x + B * u         (state prediction)
P_pred = A * P * A^T + Q       (covariance prediction)

Update step:

K = P_pred * H^T * (H * P_pred * H^T + R)^-1   (Kalman gain)
x = x_pred + K * (z - H * x_pred)                (state update)
P = (I - K * H) * P_pred                         (covariance update)

Where:

  • x = state vector, P = state covariance
  • A = state transition, B = control input, H = observation model
  • Q = process noise, R = measurement noise, K = Kalman gain

The Kalman filter is computationally expensive for embedded (matrix operations). For simple 1D cases, a scalar Kalman filter is practical on an MCU.

Madgwick Filter

An efficient orientation filter specifically designed for IMUs. Computes quaternion orientation using gradient descent optimization.

Advantages over Kalman:

  • No matrix operations -- uses quaternion math
  • Single tuning parameter (beta)
  • Very efficient on Cortex-M (runs in ~300 us at 48 MHz)
  • Handles magnetic distortion gracefully

Used in drones, robotics, motion capture, and VR controllers.

Actuators

Motor Types

Motor Control Characteristics Applications
DC Brushed PWM voltage Simple, bidirectional, moderate speed Wheels, fans, pumps
Stepper Step/direction pulses Precise positioning, no feedback needed 3D printers, CNC
Servo (RC) PWM position signal Built-in feedback, limited rotation Robotics joints
BLDC Electronic commutation High efficiency, long life, complex control Drones, EV, hard drives

H-Bridge Motor Driver

An H-bridge controls DC motor direction using four switches:

    VCC                     VCC
     |                       |
   [S1]---+---Motor---+---[S3]
          |           |
   [S2]---+           +---[S4]
     |                       |
    GND                     GND

Forward:  S1=ON, S4=ON, S2=OFF, S3=OFF
Reverse:  S2=ON, S3=ON, S1=OFF, S4=OFF
Brake:    S1=ON, S2=ON (or S3+S4)
Coast:    All OFF

Common H-bridge ICs: L298N, DRV8833, TB6612FNG. Never turn on S1+S2 or S3+S4 simultaneously (shoot-through destroys the bridge).

Stepper Motor Control

// Simple stepper driver using step/direction interface (e.g., A4988, DRV8825)
STRUCTURE StepperDriver
    step_pin: output pin
    dir_pin: output pin

ASYNC PROCEDURE STEP(driver, direction, steps, delay_us)
    IF direction THEN
        SET_HIGH(driver.dir_pin)
    ELSE
        SET_LOW(driver.dir_pin)

    FOR i ← 1 TO steps DO
        SET_HIGH(driver.step_pin)
        AWAIT DELAY(delay_us microseconds)
        SET_LOW(driver.step_pin)
        AWAIT DELAY(delay_us microseconds)

Servo Motor Control

Standard RC servos accept a 50 Hz PWM signal:

  • 1.0 ms pulse = 0 degrees
  • 1.5 ms pulse = 90 degrees (center)
  • 2.0 ms pulse = 180 degrees
PROCEDURE SET_SERVO_ANGLE(pwm, angle_deg)
    // Map 0-180 degrees to 1.0-2.0 ms pulse at 50 Hz (20 ms period)
    pulse_us ← 1000.0 + (angle_deg / 180.0) * 1000.0
    duty ← (pulse_us / 20000.0) * GET_MAX_DUTY(pwm)
    SET_DUTY(pwm, duty)

Motor Control Algorithms

PID Controller

Proportional-Integral-Derivative control is the workhorse of motor control:

output = Kp * error + Ki * integral(error) + Kd * derivative(error)
STRUCTURE PidController
    kp, ki, kd: real
    integral: real
    prev_error: real
    output_min, output_max: real

PROCEDURE UPDATE(pid, setpoint, measurement, dt) → real
    error ← setpoint - measurement

    // Proportional
    p ← pid.kp * error

    // Integral with anti-windup clamping
    pid.integral ← pid.integral + error * dt
    pid.integral ← CLAMP(pid.integral, pid.output_min / pid.ki,
                                        pid.output_max / pid.ki)
    i ← pid.ki * pid.integral

    // Derivative (on measurement to avoid derivative kick)
    d ← pid.kd * (error - pid.prev_error) / dt
    pid.prev_error ← error

    RETURN CLAMP(p + i + d, pid.output_min, pid.output_max)

Tuning Methods

Method Approach
Ziegler-Nichols Increase Kp until oscillation, derive Ki/Kd from period
Manual tuning Set Ki=Kd=0, increase Kp, then add Ki, then Kd
Cohen-Coon Based on step response characterization
Auto-tune Relay oscillation method (automated)

Field-Oriented Control (FOC)

Advanced BLDC/PMSM control that transforms 3-phase currents into a rotating reference frame (d-q transform), enabling independent control of torque and flux:

3-phase currents --> Clarke transform --> alpha-beta --> Park transform --> d-q
     (ia, ib, ic)                        (stationary)                    (rotating)

FOC requires:

  • Current sensing (shunt resistors + ADC)
  • Rotor position (encoder or sensorless estimation)
  • Fast control loop (10-20 kHz)
  • Space Vector Modulation (SVM) for inverter switching

FOC delivers smooth, efficient motor operation and is standard in drones, EVs, and industrial drives.

Key Takeaways

  • Sensor selection depends on the measurand, accuracy, interface, and power requirements.
  • Complementary filters are simple and effective for combining gyro and accelerometer data.
  • Kalman filters are optimal but computationally heavy; Madgwick is a practical alternative for orientation.
  • H-bridges enable bidirectional DC motor control; stepper drivers provide open-loop precision.
  • PID control with anti-windup is sufficient for most motor control; FOC is needed for BLDC efficiency.