COMPUTER SCIENCE CAFÉ
  • WORKBOOKS
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • BLOCKY GAMES
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
  • WORKBOOKS
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • BLOCKY GAMES
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
Picture
PI & ARDUINO | DC MOTOR CONTROL
Here we cover build a project to control a DC motor with variable speed control. We are building a three part communication chain. Each part has a specific job to do to ensure the motor spins exactly how we want it to:
  • The Brain (Raspberry Pi/PC): You will write a Python script to create a Graphical User Interface (GUI). This is where you give the commands, such as "Start," "Stop," or "Set Speed to 75%."
  • The Translator (Arduino): The Arduino acts as the middleman. It listens to the USB port, translates the Python "text" into electrical signals, and manages the timing of the motor pulses.
  • The Muscle (L298N & Battery): Since motors require more "juice" than a computer can safely provide, the L298N Motor Driver uses an external battery to do the heavy lifting, while following the instructions sent by the Arduino.

By the end of this guide, you will be able to:
  • Build a GUI: Create a custom window with a slider to control hardware.
  • Master PWM (Pulse Width Modulation): Control motor speed by pulsing electricity hundreds of times per second.
  • Debug Serial Data: Use the terminal to "listen" to the conversation happening between your Python code and your Arduino hardware.
  • Wire a Bridge: Correctlly connect a multi-component circuit using a Common Ground.​
SECTION 1 | MATERIAL NEEDED
  • Raspberry Pi : This runs your Python script and the Graphical User Interface (GUI).
  • ​Arduino Uno: This acts as the dedicated motor controller. It handles the high-speed timing that the Pi can't do as precisely.
  • USB-A to USB-B Cable: This is the "Data Highway" that connects your Pi to your Arduino.
  • L298N Motor Driver Module: This is a heavy-duty "H-Bridge" that allows the Arduino to control the speed and direction of the motor without drawing too much current from the Arduino itself.
  • DC Motor: A standard 3V–12V brushed DC motor.
  • External Power Supply: A battery pack (e.g., 4x AA batteries or a 9V battery). Note: Do not try to power the motor directly from the Arduino 5V pin; it doesn't provide enough current!
  • Jumper Wires (Male-to-Male & Male-to-Female): You will need about 10–12 wires to make all the connections.
  • Small Screwdriver: Most L298N modules use screw terminals to secure the power and motor wires.
SECTION 2| THE PRINCIPLES
The core principle of this project is Distributed Processing. While the Raspberry Pi is an incredibly powerful computer capable of running complex Python scripts and high-resolution graphics, its "brain" is designed for multitasking. Because the Pi is busy managing an Operating System, it can sometimes struggle with the micro-second precision required to maintain a perfectly steady motor speed. By offloading the motor control to an Arduino, we allow the Pi to focus on the User Interface while the Arduino handles the "Real-Time" electrical pulses.

We achieve this connection through Serial Communication. Using the pyserial library, the Raspberry Pi sends data packets over a USB cable. The Arduino acts as a dedicated "Output Slave," listening for these packets and translating them into Pulse Width Modulation (PWM). This hybrid setup is the industry standard for robotics; it combines the easy-to-use programming of Python with the rugged, precise hardware timing of the Arduino.

Why not use the Pi's GPIO pins directly?
You might wonder why we don't just plug the motor driver into the Raspberry Pi's own pins. There are two major reasons:
  • Safety: Motors generate "electrical noise" and back-voltage that can easily destroy the sensitive 3.3V circuitry of a Raspberry Pi. The Arduino acts as a sacrificial "buffer" that is much more resilient to these electrical spikes.
  • Hardware PWM: Arduino boards have dedicated hardware timers specifically built for variable speed control. By using the Arduino's analogWrite function, we get a much smoother and more reliable motor spin than we could achieve using the Pi's software-driven digital outputs.
SECTION 3| THE CONNECTIONS
Wiring is the most critical part of this project. If one wire is in the wrong place, the motor won't spin, or worse, you could send too much voltage into the wrong component.

Step-by-step:  Control Logic, Motor Power, and the Common Ground.

1. The Control Logic (Arduino to L298N)
These wires carry the "instructions" from the Arduino to the motor driver.
  • Pin 9 (Arduino) → ENA (L298N): This is the speed signal (PWM). Note: You must remove the black plastic jumper cap from the ENA pins to plug your wire in here.
  • Pin 8 (Arduino) → IN1 (L298N): Controls the first direction.
  • Pin 7 (Arduino) → IN2 (L298N): Controls the second direction.

2. The Muscle (L298N to Motor & Battery)
This is where the high-current electricity flows. Use your screwdriver to secure these in the screw terminals.
  • Motor Terminals (OUT1 & OUT2): Connect the two wires from your DC motor here. (If the motor spins the wrong way later, just swap these two wires).
  • 12V Terminal (L298N): Connect the Positive (+) wire from your battery pack here.
  • GND Terminal (L298N): Connect the Negative (-) wire from your battery pack here.

3. The "Common Ground" (CRITICAL STEP)
This is the #1 reason projects fail. For the Arduino to talk to the L298N, they must share a "reference point" for their electricity.
  • Arduino GND → L298N GND Terminal: Take a jumper wire and connect any GND pin on the Arduino to the middle screw terminal (GND) on the L298N.
Now, the L298N GND terminal should have TWO wires in it: one from the battery and one from the Arduino.
Component Pin / Terminal Connects To Purpose
Arduino Pin 9 L298N ENA Speed Control (PWM)
Arduino Pin 8 L298N IN1 Direction Control A
Arduino Pin 7 L298N IN2 Direction Control B
Arduino GND L298N GND Terminal Common Ground Signal
Battery Positive (+) L298N 12V Terminal Motor Power Source
Battery Negative (-) L298N GND Terminal Power Return Path
SECTION 4| THE ARDUINO
Now that the hardware is ready, we need to give the Arduino its instructions. In this project, the Arduino acts as a Serial Listener. It doesn't do anything on its own; it waits for a specific number to arrive through the USB cable and then translates that number into a motor speed.

To program your hardware, you will need to use the Arduino IDE (Integrated Development Environment). This is the software where you will write, check, and send code to your Arduino.

Follow these steps before moving to the next section:
  • Download the Software: If you do not have the IDE installed on your Raspberry Pi or laptop, go to the Official Arduino Website to download and install the latest version.
  • Select Your Board: Once the IDE is open, go to Tools > Board and ensure you have selected Arduino Uno (or the specific board you are using).
  • Identify the Port: Go to Tools > Port and select the active USB port connected to your Arduino. On a Raspberry Pi, this usually looks like /dev/ttyACM0.
  • Ready to Upload: You must perform these steps every time you plug in a new board, otherwise, the "Upload" button will not work!
Code for Arduino

    
Understanding the Key Commands
  • Serial.parseInt(): This is a smart function. It ignores letters and looks only for numbers in the incoming data stream.
  • analogWrite(enA, speedInput): This is how we control speed. Even though the Arduino is a digital device, it uses PWM (Pulse Width Modulation) to "fake" a lower voltage by turning the pin on and off very fast.
  • The Buffer Clear: The while(Serial.available() > 0) line is our "clean-up" crew. It ensures that if the Python script sends data too fast, the Arduino doesn't get confused by old messages.

Testing Without Python (The Hardware Check)
  • Before moving to the Python section, you can test if your wiring is correct right now:
  • Open the Serial Monitor in the Arduino IDE (Tools > Serial Monitor).
  • Set the baud rate to 9600 and select Newline.
  • Type 200 and press Enter.

Result: Your motor should start spinning! If it does, your hardware and Arduino code are 100% correct.
SECTION 5| THE RASPBERRY PI
​Now for the final piece of the puzzle! We will use Python to create a Graphical User Interface (GUI). This allows students to interact with the motor using a visual slider rather than typing raw numbers into a terminal. Copy this code into a new file in your Python editor (like Thonny or VS Code).

Important: Make sure your Arduino is plugged in and the Arduino Serial Monitor is CLOSED before running this script.
Python Code

    
How the Code Works
  • ser.write(command.encode()): Python stores text as "strings," but the USB cable sends "bytes." The .encode() command translates our number into a format the Arduino hardware can understand.
  • The command=update_motor Parameter: This is a powerful feature of the Tkinter Slider. Instead of checking the speed 100 times a second, Python stays "asleep" until the student moves the slider, making the program very efficient.
  • time.sleep(2): When Python first connects to an Arduino, the Arduino actually reboots itself. We wait 2 seconds to let it "wake up" before we start shouting commands at it.

NOTE: For this script to work, you must have the PySerial library installed. If you get a "ModuleNotFoundError," open your Terminal and type: ​pip install pyserial
SECTION 6| TROUBLESHOOTING
In engineering, things rarely work perfectly on the first try. If your motor isn't spinning, don't worry! Most issues are caused by one of these common "bottlenecks." Use this guide to diagnose and fix the problem.

1. The "Logic vs. Power" Check
If your Python code is running and the Arduino lights are blinking, but the motor isn't moving:
  • The Battery: Is your battery pack plugged in? The USB cable cannot provide enough power to turn a DC motor.
  • The ENA Jumper: Did you remove the black plastic cap from the ENA pin on the L298N? If the wire from Pin 9 is loose or plugged into the wrong pin, the motor won't get the "Go" signal.
  • Common Ground: Check the GND terminal on the L298N. It should have two wires: one going to the Battery (-) and one going to the Arduino GND.
Click to set custom HTML
The Error Message The Cause How to Fix It
ser_open(): can't open device
Found in Arduino IDE during upload
Arduino is disconnected or the wrong Port is selected. Action
  • Go to Tools > Port and select the active USB port.
  • Check your USB cable connection.
Access Denied / Permission Denied
Found in Python or Arduino IDE
The Serial Port is being "hugged" by another program. Action
  • Close the Arduino Serial Monitor before running Python.
  • Stop any other Python scripts that might be using the motor.
ModuleNotFoundError: No module named 'serial'
Found in Python Terminal
The PySerial library is not installed on your computer. Action
  • Open your Terminal/Command Prompt and type:
    pip install pyserial
Motor Hums / High-Pitched Whine
Physical symptom (No code error)
Not enough power to overcome the motor's friction. Action
  • Increase the slider to 255.
  • Check that your Battery Pack is switched ON and charged.
3. Hardware Diagnostic Checklist
If you are still stuck, try this "Back-to-Basics" sequence:
  • The "L" LED Test: Look at the tiny LED labeled L on your Arduino. If you move the slider in Python, does that LED flicker or change brightness? If yes, Python and Arduino are communicating—the problem is in your L298N or Motor wiring.
  • The Direct Power Test: Briefly touch your motor wires directly to your battery terminals. Does the motor spin? If no, your motor or battery is dead.
  • The Screw Terminals: Tug gently on the wires in the L298N screw terminals. If they slide out, they weren't making a good electrical connection. Tighten the screws!
​​
Picture
SUGGESTIONS
We would love to hear from you
SUBSCRIBE 
To enjoy more benefits
We hope you find this site useful. If you notice any errors or would like to contribute material then please contact us.