005 - ESP32 MicroPython: Pulse Width Modulation

Introduction

In this tutorial, we will learn to use the PWM of ESP32 in MicroPython. PWM stands for Pulse Width Modulation.

Circuit Diagram

Video Demonstration

Call To Action

If you find this tutorial helpful, please consider Subscribing to my Youtube channel by clicking this link to SUBSCRIBE to TechToTinker Youtube channel.

Thank you.

Source Code

 1# DC motor speed control using PWM in MicroPython
 2# Author: George Bantique, TechToTinker
 3# Date: September 13, 2020
 4
 5# Load the machine module which also
 6# includes the pwm class
 7import machine
 8
 9# Create the drives object for the direction
10# of rotation of the DC motor
11dr1 = machine.Pin(21, machine.Pin.OUT)
12dr2 = machine.Pin(19, machine.Pin.OUT)
13
14# Create the en1 object as normal GPIO
15en1 = machine.Pin(18, machine.Pin.OUT)
16
17# Create a pwm object and attach it to
18# pwm drivers
19pwm = machine.PWM(en1)
20
21# Rotates the DC motor clockwise
22def cw():
23    dr1.value(1)
24    dr2.value(0)
25    
26# Rotates the DC motor counter-clockwise    
27def ccw():
28    dr1.value(0)
29    dr2.value(1)
30
31# Starts the pwm with a definite value
32# and start the motor rotating according 
33# to the input argument
34def start(rotation):
35    pwm.init(freq=1, duty=512)
36    if (rotation=='cw'):
37        cw()
38    elif (rotation=='ccw'):
39        ccw()
40
41# Stops the pwm using pwm.deinit() function
42# which dettach the pwm driver to the en1 object
43# We also provide the drives pin a logic low value
44def stop():
45    pwm.deinit()
46    dr1.value(0)
47    dr2.value(0)
48    


Posts in this series



No comments yet!

GitHub-flavored Markdown & a sane subset of HTML is supported.