Understanding Sensors and Actuators in Robotics

Coordinated robot movement depends on the seamless integration of sensors and actuators. Sensors gather data about the environment—distance to obstacles, orientation, temperature, or light levels—while actuators convert commands into physical actions such as rotation, linear motion, or gripping. When these components work together under a central control system, a robot can navigate, manipulate objects, and adapt to changing conditions. This article explains how to select, connect, and program sensors and actuators for reliable, coordinated motion. We cover everything from fundamental principles to advanced topics like sensor fusion and the Robot Operating System (ROS), providing practical code and wiring examples you can apply immediately.

Fundamentals: Sensors and Actuators in the Control Loop

A sensor is a transducer that converts a physical quantity into an electrical signal. For example, an ultrasonic sensor emits sound waves and measures the time it takes for the echo to return, producing a voltage or digital value proportional to distance. An actuator, on the other hand, receives an electrical signal and produces mechanical motion. Common actuators include DC motors for continuous rotation, servo motors for precise angular positioning, and linear actuators for push‑pull movements.

The key to coordination lies in the control loop: sensors provide feedback, a microcontroller processes that feedback, and commands are sent to actuators to adjust the robot’s state. This cycle repeats many times per second, enabling real‑time responsiveness. The speed and reliability of this loop depend on the selection of components and the efficiency of your code.

In modern robotics, you often see a hierarchical control architecture. Low-level loops run at high frequencies (hundreds to thousands of Hertz) for motor current control, while mid-level loops operate at tens of Hertz for position or velocity. High-level planners may run at a few Hertz. Understanding these layers helps you design systems that are both responsive and stable.

Selecting the Right Sensors

Types of Sensors for Robot Movement

  • Distance sensors: Ultrasonic (HC‑SR04), infrared (Sharp GP2Y0A21), and LiDAR (TF‑Luna) provide range measurements. Each has trade‑offs in accuracy, cost, and environmental sensitivity. Ultrasonic works well in low light but can be affected by soft surfaces; infrared is fast but limited in bright sunlight; LiDAR offers high accuracy at a higher cost.
  • Inertial measurement units (IMUs): Gyroscopes and accelerometers (MPU‑6050, ICM-20948) measure angular velocity and acceleration, essential for balancing, dead‑reckoning, and orientation estimation. Modern IMUs often include a magnetometer for heading reference.
  • Encoders: Optical or magnetic encoders on motors track wheel rotation, enabling odometry and speed control. Incremental encoders give relative position; absolute encoders give position at power‑up. Quadrature encoders allow direction detection.
  • Contact sensors: Limit switches and bump sensors detect physical collisions, often used as emergency stops or tactile feedback for grippers.
  • Vision sensors: Cameras (OV7670, Raspberry Pi Camera, Intel RealSense) enable visual servoing, object tracking, simultaneous localization and mapping (SLAM), and pick‑and‑place operations.

Key Selection Criteria

When choosing a sensor, consider resolution (smallest detectable change), accuracy (closeness to true value), update rate (how often new data is available), and interface (analog, digital, I²C, SPI, UART). For example, a line‑following robot requires fast, binary‑output infrared sensors with a response time under 1 ms, while a balancing robot needs a high‑update‑rate IMU (at least 100 Hz) with low latency. Always check the datasheet for operating voltage and current—mismatches can damage your microcontroller.

Another often‑overlooked criterion is sensor fusion compatibility. If you plan to combine data from multiple sensors (e.g., IMU + encoder), choose sensors with synchronized timestamps or the ability to be polled at deterministic intervals.

Selecting the Right Actuators

Types of Actuators

  • DC motors: Simple, cheap, and high‑speed. Use with motor drivers (L298N, TB6612, DRV8833) and often require gearboxes for torque. They are the workhorses of mobile robots.
  • Servo motors: Integrated gearbox, feedback potentiometer, and control electronics. Accept PWM signals for precise angular positioning (0–180°). Ideal for grippers, pan‑tilt mechanisms, and legged robots.
  • Stepper motors: Move in discrete steps, offering excellent position control without feedback (open‑loop). Good for 3D printers, CNC machines, and precise linear motion.
  • Linear actuators: Convert rotary motion to linear motion via lead screw or rack‑and‑pinion. Used for lifting, pressing, or adjusting height. Some include position feedback.
  • Brushless DC motors (BLDC): Higher efficiency and longer life than brushed motors, but require electronic speed controllers (ESC). Used in drones and high‑performance robots.

Key Selection Criteria

Evaluate torque (or force), speed, power consumption, and control signal type. For a mobile robot, DC motors with encoders allow closed‑loop speed control via PID. For a robotic arm, servo motors simplify position control but may have limited payload. Always match actuator voltage and current to your microcontroller’s output capabilities—use dedicated motor drivers and power transistors when necessary. Also consider mechanical coupling: gears, belts, or direct drive each affect backlash, efficiency, and maintenance.

For high‑torque applications, consider using a motor with a hall‑effect sensor for commutation (BLDC) or a worm gearbox for self‑locking. For precision, stepper motors with microstepping can achieve very fine resolution.

Hardware Integration

Wiring and Power Management

Proper wiring ensures reliability and prevents damage. Connect sensor outputs to microcontroller input pins (analog or digital). Actuator control lines (e.g., PWM pins) connect to motor drivers. Separate power supplies for logic (5 V) and motors (6–12 V) reduce noise. Use capacitors near motor drivers to smooth current spikes. Always include a common ground between all components—failure to do so can cause erratic behavior or damage.

For high‑current actuators, use a dedicated battery and a power distribution board. Avoid running high‑current wires near sensor signal lines to prevent electromagnetic interference (EMI). Twisted‑pair cables for I²C and SPI lines can reduce noise.

A typical robot architecture includes a microcontroller (Arduino Uno, ESP32, STM32) or a single‑board computer (Raspberry Pi) as the brain. The microcontroller reads sensor data and computes actuator commands. For heavy processing (image processing), offload tasks to a companion computer and use serial communication between them. A real‑time operating system (RTOS) like FreeRTOS on the microcontroller can help manage timing constraints.

Communication Protocols

  • PWM (Pulse Width Modulation): Used to control servo angle and motor speed. Most microcontrollers have dedicated PWM pins. Frequency and resolution matter—50 Hz for servos, higher for LEDs.
  • I²C (Inter‑Integrated Circuit): Two‑wire bus for connecting multiple sensors (IMU, distance sensors, displays). Address conflicts must be managed—many sensors have configurable addresses. Pull‑up resistors (4.7 kΩ) are required.
  • SPI (Serial Peripheral Interface): Faster than I²C, four wires, ideal for high‑speed data (encoders, cameras, ADCs). Requires more pins but offers full‑duplex communication.
  • UART (Universal Asynchronous Receiver‑Transmitter): Point‑to‑point serial communication (GPS, LiDAR, serial monitors). Use for debug output or connecting to a separate computer.
  • CAN bus: Used in automotive and industrial robotics for robust, real‑time communication over longer distances. Requires a CAN transceiver.

Choose protocols based on data rate requirements and microcontroller capabilities. Many sensors now use I²C, which simplifies wiring but may introduce latency if many devices share the bus. For high‑speed control loops, use SPI or parallel interfaces.

Programming for Coordinated Movement

Software architecture is critical. A typical robot program follows an event‑driven or real‑time loop:

  1. Initialize all sensors and actuators in setup().
  2. Read sensor data (e.g., distance, IMU angles) at the start of each loop iteration.
  3. Process the data using conditionals, state machines, or control algorithms (PID).
  4. Command actuators based on the processed result (e.g., set motor speed, servo angle).
  5. Wait a fixed small interval (e.g., 20 ms) to maintain a constant loop rate.

Use millis() for non‑blocking timing instead of delay() to keep the loop responsive. An RTOS can manage multiple tasks at different rates—for example, one task reads IMU data at 200 Hz, another runs a PID controller at 100 Hz, and a third handles serial communication.

State Machines for Coordination

For complex behaviors like obstacle‑avoidance, a state machine organizes actions. States include: Forward, Turn Left, Turn Right, Reverse. Sensor conditions trigger transitions. For example, if front distance < 30 cm, transition from Forward to Turn Left. This structure avoids tangled if‑else chains and makes debugging easier. Implement state machines using switch statements or a dedicated state machine library.

Closed‑Loop Control: PID

Open‑loop control (just sending a fixed PWM) is insufficient for precise movement. A PID controller (Proportional‑Integral‑Derivative) uses sensor feedback to correct errors. For a line follower, the error is the difference between the line position and the sensor center. PID outputs adjust motor speeds to keep the robot on track. Implement PID with a known sampling time and tune the gains (Kp, Ki, Kd) manually or via auto‑tuning. The Ziegler‑Nichols method is a common starting point.

Example libraries: Arduino PID Library and MATLAB PID Control. For advanced applications, consider cascaded PID (velocity and position loops) and feed‑forward terms to reduce lag.

Example: Building an Obstacle‑Avoiding Robot

This step‑by‑step example integrates an ultrasonic sensor, two DC motors with an L298N driver, and an Arduino Uno. We'll expand it to include behaviors and PID wall‑following.

Components

  • Arduino Uno
  • HC‑SR04 ultrasonic sensor
  • 2× DC motors with wheels
  • L298N motor driver
  • Battery pack (7.2 V – 12 V)
  • Jumper wires, breadboard, chassis

Wiring

  • HC‑SR04 VCC → 5 V, GND → GND, Trig → pin 9, Echo → pin 10.
  • L298N: IN1→pin 4, IN2→pin 5 (left motor), IN3→pin 6, IN4→pin 7 (right motor), ENA→pin 3 (PWM), ENB→pin 11 (PWM). Connect motor power to battery (12 V recommended).
  • Connect L298N GND to Arduino GND.

Code Sketch (Expanded with PID Wall‑Following)


#include <PID_v1.h>

const int trigPin = 9;
const int echoPin = 10;
const int motorLeftSpeed = 3;
const int motorLeftDir1 = 4;
const int motorLeftDir2 = 5;
const int motorRightSpeed = 11;
const int motorRightDir1 = 6;
const int motorRightDir2 = 7;

double setpoint = 20.0; // desired distance from left wall (cm)
double measuredDistance;
double output;
PID myPID(&measuredDistance, &output, &setpoint, 2,5,1, DIRECT);

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(motorLeftSpeed, OUTPUT);
  // ... all motor pins as outputs
  myPID.SetMode(AUTOMATIC);
  myPID.SetOutputLimits(-255, 255);
  Serial.begin(9600);
}

long getDistance() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  long duration = pulseIn(echoPin, HIGH);
  return duration * 0.034 / 2;
}

void setMotors(int leftSpeed, int rightSpeed) {
  // Clamp speeds between -255 and 255
  // Direction control omitted for brevity
}

void loop() {
  measuredDistance = getDistance();
  myPID.Compute();
  int baseSpeed = 150;
  int leftMotor = baseSpeed + output;
  int rightMotor = baseSpeed - output;
  setMotors(leftMotor, rightMotor);
  delay(20);
}

For obstacle avoidance, add a front‑facing ultrasonic sensor and a simple state machine that overrides PID when an obstacle is too close. This gives you both wall‑following and collision avoidance.

Advanced Integration: Sensor Fusion and ROS

Complex robots combine data from multiple sensors (sensor fusion) to improve accuracy. For example, an IMU plus wheel encoders can correct drift using a Kalman filter. The Robot Operating System (ROS) provides tools for message passing, coordinate transforms, and reusable sensor/actuator drivers. With ROS, you can build a distributed system: a Raspberry Pi runs ROS nodes that interface with an Arduino over serial. This approach scales to multi‑sensor, multi‑actuator systems like autonomous vehicles.

Sensor fusion libraries like robot_localization in ROS can fuse IMU, GPS, and encoder data using an Extended Kalman Filter (EKF). For visual‑inertial odometry, consider using Zivid or ORB‑SLAM3.

When moving to ROS, use rosserial for Arduino to publish sensor topics and subscribe to motor command topics. This allows you to leverage ROS’s built‑in PID controllers and visualization tools like RViz.

Testing, Debugging, and Calibration

Always test each sensor and actuator individually before integration. Use serial monitor output to verify sensor readings under different conditions. For actuators, check that they respond correctly to manual commands. Calibration steps:

  • For ultrasonic sensors, measure known distances and adjust the speed‑of‑sound constant for temperature and humidity.
  • For servos, find the pulse widths that correspond to 0° and 180° using servo.writeMicroseconds().
  • For motor encoders, count pulses per revolution and adjust the wheel diameter for accurate odometry. Perform a straight‑line distance test and correct constants.
  • For IMU, run a calibration script to remove bias and scale errors. Many libraries include a calibration routine.

Use a logic analyzer or oscilloscope to debug digital signals (PWM frequency, I²C timing, SPI clock). Tools like Python with pyserial can log data for offline analysis. Plotting data with matplotlib helps visualize sensor noise and PID response.

Another invaluable technique is to log timestamped data and replay it in simulation. Tools like ROS 2 bag record sensor and actuator data for offline debugging.

Safety and Reliability Considerations

Coordinated movement introduces safety risks. Always include an emergency stop—either a physical button or a software timeout that disables actuators if the control loop stops responding. Use current‑limiting resistors and fuses on motor power lines. For collaborative robots, ensure force/torque limits are enforced in software.

Watchdog timers on microcontrollers can reset the system if the program hangs. For battery‑powered robots, implement low‑battery detection and graceful shutdown. Finally, test extensively in a controlled environment before deploying in real‑world applications.

Conclusion

Integrating sensors and actuators for coordinated robot movement is a multi‑step process requiring careful component selection, robust wiring, and intelligent programming. By understanding sensor characteristics, actuator types, control loops, and communication protocols, you can build robots that respond fluidly to their environment. Start with a simple obstacle‑avoiding robot, then add closed‑loop PID control, sensor fusion, and eventually ROS for complex autonomy. Each project deepens your intuition for how hardware and software combine to create coordinated motion. The key is to iterate: build, test, log data, tune, and improve. With the right tools and knowledge, you can create reliable, high‑performance robotic systems.