Python Tutorials
Python Tutorials
com
1. Thonny Installation.........................................................2
2. Projects........................................................................ 10
www.keyestudio.com
www.keyestudio.com
Project 7: Fan...............................................................35
3. Resources.....................................................................55
www.keyestudio.com
www.keyestudio.com
1. Thonny Installation
www.keyestudio.com
www.keyestudio.com
www.keyestudio.com
www.keyestudio.com
Download link:https://micropython.org/download/esp32/
shown below.
www.keyestudio.com
www.keyestudio.com
Select Port
firmware
www.keyestudio.com
www.keyestudio.com
Click install
www.keyestudio.com
www.keyestudio.com
CH340(COM)
www.keyestudio.com
www.keyestudio.com
Thonny interface
www.keyestudio.com
www.keyestudio.com
2. Projects
1. Working Principle
2. Parameters
www.keyestudio.com
www.keyestudio.com
Power 0.1W
3. Control Pin
Yellow LED 12
1. Description
We can make the LED pin output high level and low level
2. Test Code
from machine import Pin
import time
led = Pin(12, Pin.OUT)# Build an LED object, connect the external LED light to pin 0,
and set pin 0 to output mode
while True:
led.value(1)# turn on led
time.sleep(1)# delay 1s
led.value(0)# turn off led
time.sleep(1)# delay 1s
www.keyestudio.com
www.keyestudio.com
www.keyestudio.com
www.keyestudio.com
1. Description
number of high level and low level in unit time, the more
time the high level occupies, the larger the PWM value,
www.keyestudio.com
www.keyestudio.com
2. Test Code
import time
from machine import Pin,PWM
#The way that the ESP32 PWM pins output is different from traditionally controllers.
#It can change frequency and duty cycle by configuring PWM’s parameters at the
initialization stage.
#Define GPIO 0’s output frequency as 10000Hz and its duty cycle as 0, and assign
them to PWM.
pwm =PWM(Pin(12,Pin.OUT),10000,0)
try:
while True:
#The range of duty cycle is 0-1023, so we use the first for loop to control PWM to
change the duty
#cycle value,making PWM output 0% -100%; Use the second for loop to make PWM
output 100%-0%.
for i in range(0,1023):
pwm.duty(i)
www.keyestudio.com
www.keyestudio.com
time.sleep_ms(1)
for i in range(0,1023):
pwm.duty(1023-i)
time.sleep_ms(1)
except:
#Each time PWM is used, the hardware Timer will be turned ON to cooperate it.
Therefore, after each use of PWM,
#deinit() needs to be called to turned OFF the timer. Otherwise, the PWM may fail to
work next time.
pwm.deinit()
3. Test Result
www.keyestudio.com
www.keyestudio.com
1. Description
which can control the light on and off pressing the button.
2. Button Principle
Button 1 16
Button 2 27
www.keyestudio.com
www.keyestudio.com
1. Description
2. Test Code
button1 = Pin(16, Pin.IN, Pin.PULL_UP)
button2 = Pin(27, Pin.IN, Pin.PULL_UP)
while True:
btnVal1 = button1.value() # Reads the value of button 1
btnVal2 = button2.value()
print("button1 =",btnVal1) #Print it out in the shell
print("button2 =",btnVal2)
time.sleep(0.1) #delay 0.1s
3. Test Result
Click the run button, then you can see the status values of
the smart home, and you can see the change of the status
values.
www.keyestudio.com
www.keyestudio.com
1. Description
2. Test Code
www.keyestudio.com
www.keyestudio.com
import time
while True:
btnVal1 = button1.value() # Reads the value of button 1
#print("button1 =",btnVal1) #Print it out in the shell
if(btnVal1 == 0):
time.sleep(0.01)
while(btnVal1 == 0):
btnVal1 = button1.value()
if(btnVal1 == 1):
count = count + 1
print(count)
val = count % 2
if(val == 1):
led.value(1)
else:
led.value(0)
time.sleep(0.1) #delay 0.1s
3. Test Result
The shell will print out the clicked button times, then click
the button once, the LED will be on, click it again, it will be
off.
www.keyestudio.com
www.keyestudio.com
1. Description
www.keyestudio.com
www.keyestudio.com
moving.
2. Control Pin
PIR motion 14
sensor
1. Test Code
from machine import Pin
import time
www.keyestudio.com
www.keyestudio.com
if value == 1:
print("Some body is in this area!")
else:
print("No one!")
time.sleep(0.1)
2. Test Result
www.keyestudio.com
www.keyestudio.com
up.
1. Test Code
from machine import Pin
import time
while True:
value = PIR.value()
print(value)
if value == 1:
led.value(1)# turn on led
else:
led.value(0)
time.sleep(0.1)
2. Test Result
Move your hand in front of the sensor, the LED will turn
on. After a few seconds of immobility, the LED will turn off.
www.keyestudio.com
www.keyestudio.com
1. Description
using it.
2. Component Knowledge
www.keyestudio.com
www.keyestudio.com
3. Control Pin
Passive Buzzer 25
1. Test Code
from machine import Pin, PWM
from time import sleep
buzzer = PWM(Pin(25))
buzzer.duty(1000)
# Happy birthday
buzzer.freq(294)
sleep(0.25)
buzzer.freq(440)
sleep(0.25)
buzzer.freq(392)
sleep(0.25)
buzzer.freq(532)
sleep(0.25)
buzzer.freq(494)
sleep(0.25)
buzzer.freq(392)
sleep(0.25)
buzzer.freq(440)
sleep(0.25)
www.keyestudio.com
www.keyestudio.com
buzzer.freq(392)
sleep(0.25)
buzzer.freq(587)
sleep(0.25)
buzzer.freq(532)
sleep(0.25)
buzzer.freq(392)
sleep(0.25)
buzzer.freq(784)
sleep(0.25)
buzzer.freq(659)
sleep(0.25)
buzzer.freq(532)
sleep(0.25)
buzzer.freq(494)
sleep(0.25)
buzzer.freq(440)
sleep(0.25)
buzzer.freq(698)
sleep(0.25)
buzzer.freq(659)
sleep(0.25)
buzzer.freq(532)
sleep(0.25)
buzzer.freq(587)
sleep(0.25)
buzzer.freq(532)
sleep(0.5)
buzzer.duty(0)
2. Test Result
www.keyestudio.com
www.keyestudio.com
1. Description
2. Component Knowledge
position detector.
www.keyestudio.com
www.keyestudio.com
is 0° --180 °.
www.keyestudio.com
www.keyestudio.com
3. Pin
www.keyestudio.com
www.keyestudio.com
1. Test Code
from machine import Pin, PWM
import time
pwm = PWM(Pin(13))
pwm.freq(50)
'''
Duty cycle corresponding to the Angle
0°----2.5%----25
45°----5%----51.2
90°----7.5%----77
135°----10%----102.4
180°----12.5%----128
'''
angle_0 = 25
angle_90 = 77
angle_180 = 128
while True:
pwm.duty(angle_0)
time.sleep(1)
pwm.duty(angle_90)
time.sleep(1)
pwm.duty(angle_180)
time.sleep(1)
2. Test Result
The servo of the door turns with the door, back and forth
www.keyestudio.com
www.keyestudio.com
1. Description
2. Component Knowledge
3. Test Code
# Import Pin, ADC and DAC modules.
from machine import ADC,Pin,DAC,PWM
import time
pwm = PWM(Pin(5))
pwm.freq(50)
# Read ADC value once every 0.1seconds, convert ADC value to DAC value and output it,
# and print these data to “Shell”.
try:
while True:
adcVal=adc.read()
dacVal=adcVal//16
www.keyestudio.com
www.keyestudio.com
voltage = adcVal / 4095.0 * 3.3
print("ADC Val:",adcVal,"DACVal:",dacVal,"Voltage:",voltage,"V")
if(voltage > 0.6):
pwm.duty(46)
else:
pwm.duty(100)
time.sleep(0.1)
except:
pass
4. Test Result
1. Description
which can adjust the color to bring out the lamp effect of
www.keyestudio.com
www.keyestudio.com
other scenes.
2. Component Knowledge
how many they are, we can use a pin to control a RGB LED
highly consistent.
www.keyestudio.com
www.keyestudio.com
3. Pin
SK6812 26
1. Test Code
#Import Pin, neopiexl and time modules.
from machine import Pin
import neopixel
import time
#brightness :0-255
brightness=100
www.keyestudio.com
www.keyestudio.com
colors=[[brightness,0,0], #red
[0,brightness,0], #green
[0,0,brightness], #blue
[brightness,brightness,brightness], #white
[0,0,0]] #close
#Nest two for loops to make the module repeatedly display five states of red, green, blue, white
and OFF.
while True:
for i in range(0,5):
for j in range(0,4):
np[j]=colors[i]
np.write()
time.sleep_ms(50)
time.sleep_ms(500)
time.sleep_ms(500)
2. Test Result
1. Description
atmosphere lamp.
2. Test Code
#Import Pin, neopiexl and time modules.
from machine import Pin
www.keyestudio.com
www.keyestudio.com
import neopixel
import time
#brightness :0-255
brightness=100
colors=[[0,0,0],
[brightness,0,0], #red
[0,brightness,0], #green
[0,0,brightness], #blue
[brightness,brightness,brightness] #white
] #close
def func_color(val):
for j in range(0,4):
np[j]=colors[val]
np.write()
time.sleep_ms(50)
#Nest two for loops to make the module repeatedly display five states of red, green, blue, white
and OFF.
while True:
btnVal1 = button1.value() # Reads the value of button 1
#print("button1 =",btnVal1) #Print it out in the shell
if(btnVal1 == 0):
time.sleep(0.01)
while(btnVal1 == 0):
btnVal1 = button1.value()
if(btnVal1 == 1):
count = count - 1
print(count)
if(count <= 0):
count = 0
btnVal2 = button2.value()
if(btnVal2 == 0):
www.keyestudio.com
www.keyestudio.com
time.sleep(0.01)
while(btnVal2 == 0):
btnVal2 = button2.value()
if(btnVal2 == 1):
count = count + 1
print(count)
if(count >= 4):
count = 4
if(count == 0):
func_color(0)
elif(count == 1):
func_color(1)
elif(count == 2):
func_color(2)
elif(count == 3):
func_color(3)
elif(count == 4):
func_color(4)
3. Test Result
Project 7: Fan
1. Description
www.keyestudio.com
www.keyestudio.com
2. Component Knowledge
blades. You can use PWM output to control the fan speed.
3. Control Method
Two pins are required to control the motor of the fan, one
for INA and two for INB. The PWM value range is 0~255.
When the PWM output of the two pins is different, the fan
can rotate.
4. Control Pins
INA 19
INB 18
www.keyestudio.com
www.keyestudio.com
1. Test Code
from machine import Pin,PWM
import time
#Two pins of the motor
INA =PWM(Pin(19,Pin.OUT),10000,0)#INA corresponds to IN+
INB =PWM(Pin(18,Pin.OUT),10000,2)#INB corresponds to IN-
try:
while True:
#Counterclockwise 2s
INA.duty(0) #The range of duty cycle is 0-1023
INB.duty(700)
time.sleep(2)
#stop 1s
INA.duty(0)
INB.duty(0)
time.sleep(1)
#Turn clockwise for 2s
INA.duty(600)
INB.duty(0)
time.sleep(2)
#stop 1s
INA.duty(0)
INB.duty(0)
time.sleep(1)
except:
INA.duty(0)
INB.duty(0)
www.keyestudio.com
www.keyestudio.com
INA.deinit()
INB.deinit()
2. Test Result
speeds.
1. Test Code
from machine import Pin,PWM
import time
#Two pins of the motor
INA =PWM(Pin(19,Pin.OUT),10000,0)#INA corresponds to IN+
INB =PWM(Pin(18,Pin.OUT),10000,2)#INB corresponds to IN-
button1 = Pin(16, Pin.IN, Pin.PULL_UP)
count = 0
try:
while True:
btnVal1 = button1.value() # Reads the value of button 1
if(btnVal1 == 0):
time.sleep(0.01)
while(btnVal1 == 0):
btnVal1 = button1.value()
if(btnVal1 == 1):
count = count + 1
print(count)
www.keyestudio.com
www.keyestudio.com
val = count % 2
if(val == 1):
INA.duty(0) #The range of duty cycle is 0-1023
INB.duty(700)
else:
INA.duty(0)
INB.duty(0)
except:
INA.duty(0)
INB.duty(0)
INA.deinit()
INB.deinit()
2. Test Result
1. Description
2. Component Knowledge
www.keyestudio.com
www.keyestudio.com
3. Control Pins
SDA SDA
SCL SCL
1. Description
2. Operations
www.keyestudio.com
www.keyestudio.com
www.keyestudio.com
www.keyestudio.com
3. Test Code
from time import sleep_ms, ticks_ms
from machine import I2C, Pin
from i2c_lcd import I2cLcd
DEFAULT_I2C_ADDR = 0x27
lcd.move_to(1, 0)
lcd.putstr('Hello')
lcd.move_to(1, 1)
lcd.putstr('keyestudio')
www.keyestudio.com
www.keyestudio.com
# 11. To turn ON the backlight:
#lcd.backlight_on()
# 12. To print a single character:
#lcd.putchar('x')
# 13. To print a custom character:
#happy_face = bytearray([0x00, 0x0A, 0x00, 0x04, 0x00, 0x11, 0x0E, 0x00])
#lcd.custom_char(0, happy_face)
#lcd.putchar(chr(0))
4. Test Result
The first line of the LCD1602 shows hello and the second
1. Description
2. Component Knowledge
www.keyestudio.com
www.keyestudio.com
this project .
3. Control Pin
Gas Sensor 23
4. Test Code
from time import sleep_ms, ticks_ms
from machine import I2C, Pin
from i2c_lcd import I2cLcd
DEFAULT_I2C_ADDR = 0x27
while True:
gasVal = gas.value() # Reads the value of button 1
print("gas =",gasVal) #Print it out in the shell
lcd.move_to(1, 1)
lcd.putstr('val: {}'.format(gasVal))
www.keyestudio.com
www.keyestudio.com
if(gasVal == 1):
#lcd.clear()
lcd.move_to(1, 0)
lcd.putstr('Safety ')
else:
lcd.move_to(1, 0)
lcd.putstr('dangerous')
time.sleep(0.1) #delay 0.1s
5. Test Result
"dangerous".
1. Component Knowledge
www.keyestudio.com
www.keyestudio.com
2. Control Pin
1. Test Code
# Import machine, time and dht modules.
import machine
import time
import dht
from time import sleep_ms, ticks_ms
from machine import I2C, Pin
from i2c_lcd import I2cLcd
DEFAULT_I2C_ADDR = 0x27
while True:
DHT.measure() # Start DHT11 to measure data once.
# Call the built-in function of DHT to obtain temperature
# and humidity data and print them in “Shell”.
print('temperature:',DHT.temperature(),'℃','humidity:',DHT.humidity(),'%')
lcd.move_to(1, 0)
www.keyestudio.com
www.keyestudio.com
lcd.putstr('T: {}'.format(DHT.temperature()))
lcd.move_to(1, 1)
lcd.putstr('H: {}'.format(DHT.humidity()))
time.sleep_ms(1000)
2. Test Result
1. Component Knowledge
To read the data in the tag, first put it into the reading
www.keyestudio.com
www.keyestudio.com
Lenz's law, then the RFID tag will supply power, thereby
2. Control Pins
SDA SDA
SCL SCL
1. Test Code
www.keyestudio.com
www.keyestudio.com
pwm = PWM(Pin(13))
pwm.freq(50)
button1 = Pin(16, Pin.IN, Pin.PULL_UP)
#i2c config
addr = 0x28
scl = 22
sda = 21
data = 0
while True:
if rc522.PICC_IsNewCardPresent():
#print("Is new card present!")
if rc522.PICC_ReadCardSerial() == True:
print("Card UID:")
#print(rc522.uid.uidByte[0 : rc522.uid.size])
for i in rc522.uid.uidByte[0 : rc522.uid.size]:
data = data + i
print(data)
if(data == 656):
www.keyestudio.com
www.keyestudio.com
pwm.duty(128)
print("open")
else:
print("error")
data = 0
btnVal1 = button1.value()
if(btnVal1 == 0):
pwm.duty(25)
print("close")
time.sleep(1)
2. Test Result
door will turn and open, and the shell shows "open". Click
"Error".
www.keyestudio.com
www.keyestudio.com
www.keyestudio.com
www.keyestudio.com
1. Description
release is “-”.
www.keyestudio.com
www.keyestudio.com
2. Test Code
# Import machine, time and dht modules.
from machine import Pin, PWM
from time import sleep_ms, ticks_ms
from machine import I2C, Pin
from i2c_lcd import I2cLcd
DEFAULT_I2C_ADDR = 0x27
while True:
btnVal1 = button1.value() # Read the value of button 1
if(btnVal1 == 0):
sleep_ms(10)
while(btnVal1 == 0):
time_count = time_count + 1 #Start counting the pressed time of the button
sleep_ms(200) #The time is 200ms cumulative
btnVal1 = button1.value()
if(btnVal1 == 1):
count = count + 1
print(count)
print(time_count)
if(time_count > 3): #If the pressed time of the button is more than 200*3ms ,add"-"
to password
lcd.clear()
#lcd.move_to(1, 1)
password = password + "-"
www.keyestudio.com
www.keyestudio.com
else:
lcd.clear()
password = password + "." #Otherwise add "."
lcd.putstr('{}'.format(password))
time_count = 0
btnVal2 = button2.value()
if(btnVal2 == 0):
if(password == correct_password): #If the password is correct
lcd.clear()
lcd.putstr("open")
pwm.duty(128) #Open the door
password = "" #Remove the password
sleep_ms(1000)
else: #If the password is wrong
lcd.clear()
lcd.putstr("error")
pwm.duty(25) #Close the door
sleep_ms(2000)
lcd.clear()
lcd.putstr("enter again")
password = "" #Remove the password
3. Test Result
www.keyestudio.com
www.keyestudio.com
easily.
1. Description
www.keyestudio.com
www.keyestudio.com
2. Test Code
import time
import network #Import network module
def STA_Setup(ssidRouter,passwordRouter):
print("Setup start")
sta_if = network.WLAN(network.STA_IF) #Set ESP32 in Station mode
if not sta_if.isconnected():
print('connecting to',ssidRouter)
#Activate ESP32’s Station mode, initiate a connection request to the router
#and enter the password to connect.
sta_if.active(True)
sta_if.connect(ssidRouter,passwordRouter)
#Wait for ESP32 to connect to router until they connect to each other successfully.
www.keyestudio.com
www.keyestudio.com
while not sta_if.isconnected():
pass
#Print the IP address assigned to ESP32 in “Shell”.
print('Connected, IP address:', sta_if.ifconfig())
print("Setup End")
try:
STA_Setup(ssidRouter,passwordRouter)
except:
sta_if.disconnect()
3. Test Result
address.
3. Resources
https://fs.keyestudio.com/KS5009
www.keyestudio.com