Introduction: Python (pySerial) + Arduino + DC Motor

About: Electronics Engineer | Always in the phase of continuous learning

This quick tutorial shows the simple operation of a DC motor using a Python GUI. To make Python to communicate with an Arduino board we will be using the pySerial package. pySerial is a Python library which provides support for serial connections over a variety of different devices.

Step 1: Hardware

Adafruit motor shield, Arduino board (Mega), DC motor, 1k ohm resistors (2), LEDs (2), hook-up wires and breadboard.

Step 2: Hardware Setup

In this setup,
green LED -> Pin 30 of Arduino board
red LED -> Pin 32 of Arduino board
DC Motor -> Channel 3 (M3) of motor shield

Step 3: Software - Arduino IDE, PyCharm IDE

Step 4: Arduino IDE

Connect the desired Arduino board to PC (in this case I’m using an Arduino Mega). Open Arduino IDE and select the appropriate COM port and board. The code below is uploaded to the Arduino board by clicking on the Upload button.

Step 5: Arduino IDE - Code Part 1

Step 6: Arduino IDE - Code Part 2

Step 7: Open PyCharm IDE and Click on File -> Settings.

Step 8: Under Project, Select Project Interpreter and Click on the “+” Icon.

Step 9: In the Search Bar, Type Pyserial and Click on Install Package.

Step 10: The Python Code Below Is Run on PyCharm IDE.

Step 11: Python Code - Part 1

NOTE: Make sure the same COM port number is used in the Python code.


Step 12: Python Code - Part 2

Step 13: Final

A simple GUI opens with 3 buttons – FORWARD, REVERSE and EXIT.

Depending on the motor connection wiring, the motor runs in the desired direction with the click of the FORWARD or REVERSE button. The EXIT button closes the serial port and ends the program execution.

Step 14: Video