Python (pySerial) + Arduino + DC Motor

by thesharanmohan in Circuits > Arduino

12143 Views, 7 Favorites, 0 Comments

Python (pySerial) + Arduino + DC Motor

INSTRUCTABLES - COVER PHOTO_1.png

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.

Hardware

HARDWARE_1_31.jpeg

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

Hardware Setup

HARDWARE_2_31.jpg

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

Software - Arduino IDE, PyCharm IDE

SOFTWARE_31.png

Arduino IDE

ARDUINO_IDE_UPLOAD.png

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.

Arduino IDE - Code Part 1

ARDUINO_31_CODE_P1.PNG

Arduino IDE - Code Part 2

ARDUINO_31_CODE_P2.PNG

Open PyCharm IDE and Click on File -> Settings.

PYCHARM_IDE_SETTINGS.png

Under Project, Select Project Interpreter and Click on the ā€œ+ā€ Icon.

PYCHARM_PROJECT_INTERPRETER.png

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

PYCHARM_PYSERIAL_INSTALL_PAGE.PNG

The Python Code Below Is Run on PyCharm IDE.

PYCHARM_IDE_RUN.PNG

Python Code - Part 1

PYTHON_31_CODE_P1.PNG

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

References:
pySerial: https://pyserial.readthedocs.io/en/latest/shortintro.html
Tkinter: https://docs.python.org/3/library/tkinter.html#tkinter-modules


Python Code - Part 2

PYTHON_31_CODE_P2.PNG

Final

PYCHARM_31_GUI.PNG

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.

Video

PYTHON (pySerial) + ARDUINO + DC MOTOR