Build a mini robotBeginnerLesson 2699 min read

Wiring motors and sensors safely

Connect the motor driver, motors and ultrasonic sensor to an Arduino, upload a first test sketch, and test with the wheels off the ground. Safety first, every step.

Lesson in motion

In 60 seconds

Wiring motors and sensors safely

Connect the motor driver, motors and ultrasonic sensor to an Arduino, upload a first test sketch, and test with the wheels off the ground. Safety first, every step.

1/5
In simple words
Wiring a robot is like connecting pipes in a house. Water must come from the tank, go through the tap, reach the bucket and drain back. If one pipe is missing, nothing flows. If you connect the wrong pipes, you get a flood. Electricity needs a full path too, and a wrong wire can make things hot.
This lesson wires the robot you planned: an Arduino Uno, an L298N-type motor driver, two TT motors, an HC-SR04 sensor and two IR sensors. If you use other parts, the idea is the same, but the pins will differ. Check your board's pin labels and datasheet before every connection.

Safety rules before you start

  1. Power off while wiring. Take the batteries out, or switch off, and unplug USB before you change any wire.
  2. Check polarity. Red is usually + and black is usually −, but check the markings on the battery holder and the board. A reversed battery can destroy parts.
  3. Wheels off the ground for the first tests. Rest the robot on a box or a stack of books so the wheels spin in the air.
  4. Watch for heat and smell. If anything gets hot, smokes or smells of burning, disconnect the battery at once and check the wiring.
  5. Supervision. Younger learners should build with an adult, especially when soldering or using lithium cells.
Danger
Soldering irons are very hot (hundreds of degrees Celsius) and can burn skin instantly. Always put the iron back in its stand, never touch the metal tip, work in a ventilated space away from the fumes, wear eye protection, and wash your hands after handling solder. Unplug the iron when you finish, and let it cool before putting it away.
Danger
Battery safety. Batteries store a lot of energy. Never connect the two ends of a battery with a wire, a coin or a tool (a short circuit): wires can get very hot and cells can leak or catch fire. Lithium cells (for example 18650 cells and flat LiPo packs) need extra care: use only a proper holder and the right charger, never charge them unattended, and never use a cell that is swollen, dented or hot. Beginners should start with ordinary AA cells. Younger learners should work with an adult.

The connections

FromToWhy
Battery + (through a switch)Driver motor power input (often labelled 12V or VS)Power for the motors
Battery −Driver GNDReturn path
Driver GNDArduino GNDCommon ground: board and driver must share it or signals will not work
Arduino pins 5, 7, 8Driver ENA, IN1, IN2Speed and direction of the left motor
Arduino pins 6, 9, 10Driver ENB, IN3, IN4Speed and direction of the right motor
Driver motor A / motor B outputsLeft and right motor wiresIf a wheel spins backwards, swap that motor's two wires
HC-SR04 VCC, GNDArduino 5V, GNDPower for the sensor
HC-SR04 TRIG, ECHOArduino pins 2, 3Send a sound burst, measure the echo
IR sensors VCC, GND, OUTArduino 5V, GND, pins 11 and 12Line sensors for later
Note
On many L298N-type boards, the ENA and ENB pins have small jumper caps. With the caps on, the motor always runs at full speed. Remove them and connect ENA/ENB to PWM pins (on the Uno, pins marked with ~ such as 5 and 6) to control speed. For the Arduino itself, power it by USB while testing. Check your driver's datasheet before using any 5 V output it has to power the board.

A first test sketch

This sketch is for the real Arduino board, written in Arduino C++ and uploaded with the Arduino IDE. It waits 3 seconds, then drives forward slowly and stops when something is closer than 20 cm. It prints the distance so you can watch it in the Serial Monitor.
Arduino C++ (for the real board): first drive-and-stop testcpp
// First test for an Arduino Uno + L298N-type driver + HC-SR04.
// Check your board's pin labels and datasheet: your pins may differ.
// First run: wheels OFF the ground.
const int ENA = 5, IN1 = 7, IN2 = 8;     // left motor
const int ENB = 6, IN3 = 9, IN4 = 10;    // right motor
const int TRIG = 2, ECHO = 3;            // ultrasonic sensor
const int IR_LEFT = 11, IR_RIGHT = 12;   // line sensors (used later)

void setMotor(int en, int a, int b, int speed) {   // speed from -255 to 255
  digitalWrite(a, speed > 0 ? HIGH : LOW);
  digitalWrite(b, speed < 0 ? HIGH : LOW);
  analogWrite(en, constrain(abs(speed), 0, 255));
}

void drive(int left, int right) {
  setMotor(ENA, IN1, IN2, left);
  setMotor(ENB, IN3, IN4, right);
}

long distanceCm() {
  digitalWrite(TRIG, LOW);  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH); delayMicroseconds(10);
  digitalWrite(TRIG, LOW);
  long us = pulseIn(ECHO, HIGH, 30000);  // wait at most 30 ms for the echo
  if (us == 0) return -1;                // no echo: we do not know
  return us * 0.0343 / 2;                // there and back, so divide by 2
}

void setup() {
  int outputs[] = {ENA, IN1, IN2, ENB, IN3, IN4, TRIG};
  for (int p : outputs) pinMode(p, OUTPUT);
  pinMode(ECHO, INPUT);
  pinMode(IR_LEFT, INPUT);
  pinMode(IR_RIGHT, INPUT);
  Serial.begin(9600);
  drive(0, 0);
  delay(3000);                           // time to put the robot down and step back
}

void loop() {
  long d = distanceCm();
  Serial.println(d);
  if (d < 0 || d < 20) drive(0, 0);      // unsure or too close: stop
  else drive(150, 150);                  // gentle forward speed
  delay(50);
}
  1. 1

    Upload with the robot on a box

    Wheels in the air. Batteries in, switch on after uploading.
  2. 2

    Watch the Serial Monitor

    Move your hand in front of the sensor. Does the distance change?
  3. 3

    Check wheel directions

    Both wheels should spin forward. If one spins backward, power off and swap that motor's two wires.
  4. 4

    Check the stop

    Hold your hand 10 cm in front. Both wheels should stop.
  5. 5

    Floor test, slowly

    Only now put it on the floor, in a clear area, with a hand ready on the switch.
Notice how this sketch matches your virtual labs: distanceCm() is s["distance"], and drive(left, right) is what your decide function returned. The code you wrote in the browser carries straight over to the real robot, only in a different language.
Watch out
If the robot does something unexpected, switch it off first, then think. Do not try to catch a moving robot by its wheels.
Try this. Before wiring, draw every wire on paper with its colour, and tick each one as you connect it. Ask someone else to check your drawing against the real board.

Watch and read more

Lab

A wired, tested robot that drives forward slowly and stops before an obstacle, with a signed safety checklist.

~60 min

The problem

This lab is done with your real board. If you do not have parts yet, do steps 1 and 2 on paper.

  1. Draw a wiring diagram on paper for your parts. Label every pin from your board's pin labels and datasheet.
  2. Write a safety checklist: power off while wiring, polarity checked, grounds connected, wheels off the ground, hair and fingers clear, adult present (if needed).
  3. Wire the robot, one part at a time. Upload the test sketch from the lesson (change pin numbers if yours differ).
  4. Test on a box: check the Serial Monitor distances, both wheel directions, and the stop at 20 cm.
  5. Then test on the floor at low speed. Record: did it stop in time? How far from the obstacle did it end up?
Starter codecpp
// For the REAL board (Arduino IDE), not the browser.
// Fill in YOUR pin numbers from your board's pin labels and datasheet.
const int ENA = 5, IN1 = 7, IN2 = 8;   // left motor
const int ENB = 6, IN3 = 9, IN4 = 10;  // right motor
const int TRIG = 2, ECHO = 3;          // ultrasonic sensor

// Safety checklist (tick before powering on):
// [ ] batteries out while wiring      [ ] polarity checked
// [ ] all grounds connected           [ ] wheels off the ground
// [ ] hands, hair, sleeves clear      [ ] adult present if needed

// Paste the setMotor, drive, distanceCm, setup and loop functions from the lesson here.

You are done when

Hard questions

Try to answer before you reveal. If you can answer these, you understood the lesson.

Q1The robot stops in time on the box test, but on the floor it rolls into the obstacle. Why, and how would you fix it?Reveal

On the box the wheels spin freely and stop almost at once. On the floor the robot has weight and keeps rolling after the motors stop, more on smooth floors. The sensor also reads only every 50 ms or so. Fix it by increasing the stop distance, slowing down as the distance gets smaller (like the virtual lab in lesson 2), and briefly driving the motors backward to brake if needed.

Q2Why does the sketch treat "no echo" (-1) as a reason to stop instead of "the path is clear"?Reveal

No echo can mean nothing is in range, but it can also mean the sensor is unplugged, the object is soft or angled, or the wiring is wrong. When the robot cannot tell which, the safe choice is to stop. A robot should fail safe: when unsure, do the harmless thing.

Please sign in to continue.

Questions people ask

Why must the grounds be connected together?

A signal is a voltage measured against ground. If the Arduino and the driver have separate grounds, the driver cannot "see" the Arduino's HIGH and LOW properly, and the motors behave strangely or not at all. Connect all grounds together.

My motor only runs in one direction. What is wrong?

Check that both direction pins (for example IN1 and IN2) are wired and set as outputs in setup(). Also check the code: one should be HIGH and the other LOW for each direction.

The distance always prints -1. What should I check?

Check that VCC and GND are connected, TRIG and ECHO are on the right pins (and not swapped), and that something is in front of the sensor within its range. With a 3.3 V board, check the voltage level on the echo pin.

Can I use MicroPython on a Pico instead of Arduino C++?

Yes. The ideas are the same: set pins as outputs, send PWM to the driver, time the echo. Follow the Pico documentation for pin numbers and the functions it provides, and check your board's pin labels and datasheet.

Lesson test

5 questions. Get 3 right (60%) to pass and complete this lesson.

Sign in to take the test and save your progress