Python (pySerial) + Arduino + DC Motor
by thesharanmohan in Circuits > Arduino
12143 Views, 7 Favorites, 0 Comments
Python (pySerial) + Arduino + DC Motor
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
Adafruit motor shield, Arduino board (Mega), DC motor, 1k ohm resistors (2), LEDs (2), hook-up wires and breadboard.
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
Software - Arduino IDE, PyCharm IDE
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.
Arduino IDE - Code Part 1
Arduino IDE - Code Part 2
Open PyCharm IDE and Click on File -> Settings.
Under Project, Select Project Interpreter and Click on the ā+ā Icon.
In the Search Bar, Type Pyserial and Click on Install Package.
The Python Code Below Is Run on PyCharm IDE.
Python Code - Part 1
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
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.