Robotics · Step 3 of 8 · 6 min
Sensors, motors and servos
You can choose a sensor and a motor for a job, and wire them the right way.
Sensors measure one thing
Each sensor answers a narrow question. An ultrasonic sensor such as the HC-SR04 times an echo to measure distance. An infrared sensor sees a black line on a white floor. An IMU reports tilt and turning. An encoder counts how far a wheel has turned.
Every sensor is noisy and has limits. Ultrasonic sensors miss soft or angled surfaces. Infrared struggles in sunlight. Plan for bad readings from day one.
Three kinds of motor
DC motors spin fast and are cheap. You control speed with PWM and direction with a motor driver. Most small wheeled robots use geared DC motors.
Servos turn to an angle you command, usually 0 to 180 degrees, using a pulse sent about every 20 ms. They suit arms, grippers and steering. Stepper motors move in exact small steps, which suits 3D printers and precise positioning.
Drivers and shared ground
A motor driver is a switch the microcontroller can control, sitting between the battery and the motor. Common boards include the TB6612FNG and the older, less efficient L298N.
Connect the grounds of the battery, driver and microcontroller. Without a shared ground, signals have no reference and the robot behaves strangely.
Moving parts bite
Motors can pinch fingers, pull hair and strip gears. Lift a wheeled robot off the table the first time you run new code. Keep a switch where you can reach it to cut motor power at once.
Try it
Make a servo follow a distance sensor
- 1.In Wokwi, add an Arduino Uno, an HC-SR04 ultrasonic sensor and a servo.
- 2.Ask a chatbot for a sketch that reads the distance and maps 5 to 50 cm onto 0 to 180 degrees.
- 3.Run it, then drag the simulated obstacle and watch the servo move.
- 4.Read every line of the code and ask about any line you cannot explain.
Write an Arduino sketch for Wokwi: an HC-SR04 on pins 9 (trig) and 10 (echo) and a servo on pin 6. Map 5–50 cm to 0–180 degrees. Ignore readings outside that range. Comment each line for a beginner.