ESP32S3——基于MicroPython开发(3)
ESP32S3——基于MicroPython开发(3)
第16章_DS18B20温度传感器实验








'''
实验名称:DS18B20温度传感器实验
接线说明:DS18B20温度传感器模块-->ESP32 IO
(DS)-->(13)
实验现象:程序下载成功后,软件shell控制台间隔1S输出DS18B20温度传感器采集的温度
'''
#导入Pin模块
from machine import Pin
import time
import onewire
import ds18x20
#定义DS18B20控制对象
ds18b20=ds18x20.DS18X20(onewire.OneWire(Pin(13)))
#程序入口
if __name__=="__main__":
roms = ds18b20.scan() #扫描是否存在DS18B20设备
print("DS18B20初始化成功!")
while True:
ds18b20.convert_temp()
time.sleep(1)
for rom in roms:
print("DS18B20检测温度:%.2f°C" %ds18b20.read_temp(rom))
第17章_DHT11温湿度传感器实验






'''
实验名称:DHT11温湿度传感器实验
接线说明:DHT11温湿度传感器模块-->ESP32 IO
(VCC)-->(5V)
(DATA)-->(21)
(GND)-->(GND)
实验现象:程序下载成功后,软件shell控制台间隔2S输出DHT11温湿度传感器采集的温度和湿度
'''
#导入Pin模块
from machine import Pin
import time
import dht
#定义DHT11控制对象
dht11=dht.DHT11(Pin(21))
#程序入口
if __name__=="__main__":
time.sleep(1) #首次启动间隔1S让传感器稳定
while True:
dht11.measure() #调用DHT类库中测量数据的函数
temp = dht11.temperature()
humi = dht11.humidity()
if temp==None:
print("DHT11传感器检测失败!")
else:
print("temp=%d°C humi=%dRH" %(temp,humi))
time.sleep(2) #如果延时时间过短,DHT11温湿度传感器不工作
第18章_超声波测距实验






HCSR04.py
import machine, time
from machine import Pin
__version__ = '0.2.0'
__author__ = 'Roberto Sánchez'
__license__ = "Apache License 2.0. https://www.apache.org/licenses/LICENSE-2.0"
class HCSR04:
"""
Driver to use the untrasonic sensor HC-SR04.
The sensor range is between 2cm and 4m.
The timeouts received listening to echo pin are converted to OSError('Out of range')
"""
# echo_timeout_us is based in chip range limit (400cm)
def __init__(self, trigger_pin, echo_pin, echo_timeout_us=500*2*30):
"""
trigger_pin: Output pin to send pulses
echo_pin: Readonly pin to measure the distance. The pin should be protected with 1k resistor
echo_timeout_us: Timeout in microseconds to listen to echo pin.
By default is based in sensor limit range (4m)
"""
self.echo_timeout_us = echo_timeout_us
# Init trigger pin (out)
self.trigger = Pin(trigger_pin, mode=Pin.OUT, pull=None)
self.trigger.value(0)
# Init echo pin (in)
self.echo = Pin(echo_pin, mode=Pin.IN, pull=None)
def _send_pulse_and_wait(self):
"""
Send the pulse to trigger and listen on echo pin.
We use the method `machine.time_pulse_us()` to get the microseconds until the echo is received.
"""
self.trigger.value(0) # Stabilize the sensor
time.sleep_us(5)
self.trigger.value(1)
# Send a 10us pulse.
time.sleep_us(10)
self.trigger.value(0)
try:
pulse_time = machine.time_pulse_us(self.echo, 1, self.echo_timeout_us)
return pulse_time
except OSError as ex:
if ex.args[0] == 110: # 110 = ETIMEDOUT
raise OSError('Out of range')
raise ex
def distance_mm(self):
"""
Get the distance in milimeters without floating point operations.
"""
pulse_time = self._send_pulse_and_wait()
# To calculate the distance we get the pulse_time and divide it by 2
# (the pulse walk the distance twice) and by 29.1 becasue
# the sound speed on air (343.2 m/s), that It's equivalent to
# 0.34320 mm/us that is 1mm each 2.91us
# pulse_time // 2 // 2.91 -> pulse_time // 5.82 -> pulse_time * 100 // 582
mm = pulse_time * 100 // 582
return mm
def distance_cm(self):
"""
Get the distance in centimeters with floating point operations.
It returns a float
"""
pulse_time = self._send_pulse_and_wait()
# To calculate the distance we get the pulse_time and divide it by 2
# (the pulse walk the distance twice) and by 29.1 becasue
# the sound speed on air (343.2 m/s), that It's equivalent to
# 0.034320 cm/us that is 1cm each 29.1us
cms = (pulse_time / 2) / 29.1
return cms
main.py
'''
实验名称:超声波测距实验
接线说明:HC-SR04超声波模块-->ESP32 IO
(VCC)-->(5V)
(Trig)-->(6)
(Echo)-->(21)
(GND)-->(GND)
实验现象:程序下载成功后,软件shell控制台间隔一段时间输出超声波模块测量距离
'''
#导入Pin模块
from machine import Pin
import time
from HCSR04 import HCSR04
#定义HCSR04控制对象
hcsr04=HCSR04(trigger_pin=6, echo_pin=21)
#程序入口
if __name__=="__main__":
while True:
distance=hcsr04.distance_cm()
print("distance=%.2fCM" %distance)
time.sleep(0.5)
第19章_红外遥控实验








'''
实验名称:红外遥控实验
接线说明:红外接收模块-->ESP32 IO
(IR)-->(12)
实验现象:程序下载成功后,当按下遥控器键时,软件shell控制台输出红外遥控器控制码(十六进制数)
'''
#导入Pin模块
from machine import Pin
import time
#定义IRED控制对象
ired=Pin(12,Pin.IN,Pin.PULL_UP)
#存储红外遥控器键值
gired_data=[0,0,0,0]
#外部中断函数
def ired_irq(ired):
ired_high_time=0 #保存高电平时间,鉴别数据1还是0
if ired.value()==0:
time_cnt=1000
while (not ired.value()) and time_cnt: #等待引导信号9ms低电平结束,若超过10ms强制退出
time.sleep_us(10)
time_cnt-=1
if time_cnt==0:
return
if ired.value()==1: #引导信号9ms低电平已过,进入4.5ms高电平
time_cnt=500
while ired.value() and time_cnt: #等待引导信号4.5ms高电平结束,若超过5ms强制退出
time.sleep_us(10)
time_cnt-=1
if time_cnt==0:
return
for i in range(4): #循环4次,读取4个字节数据
for j in range(8): #循环8次读取每位数据即一个字节
time_cnt=600
while (ired.value()==0) and time_cnt: #等待数据1或0前面的0.56ms结束,若超过6ms强制退出
time.sleep_us(10)
time_cnt-=1
if time_cnt==0:
return
time_cnt=20
while ired.value()==1: #等待数据1或0后面的高电平结束,若超过2ms强制退出
time.sleep_us(100)
ired_high_time+=1
if ired_high_time>20:
return
gired_data[i]>>=1 #先读取的为低位,然后是高位
if ired_high_time>=8: #如果高电平时间大于0.8ms,数据则为1,否则为0
gired_data[i]|=0x80
ired_high_time=0 #重新清零,等待下一次计算时间
if gired_data[2]!=~gired_data[3]: #校验控制码与反码,错误则返回
for i in range(4):
gired_data[i]=0
return
print("红外遥控器操作码:0x%02X" % gired_data[2])
#程序入口
if __name__=="__main__":
ired.irq(ired_irq,Pin.IRQ_FALLING)
while True:
pass
gired_data[i]>>=1 #先读取的为低位,然后是高位
if ired_high_time>=8: #如果高电平时间大于0.8ms,数据则为1,否则为0
gired_data[i]|=0x80
ired_high_time=0
重点:先右移,再判断bit,写最高位。这就是注释写的[先收到的是低位]的原因。
分步拆解(一个字节8bit,接收顺序:bit0 → bit1 → … → bit7)
gired_data[i] 初始:00000000
gired_data[i] >>=1
右移1位,最低位丢掉,最高位补0。- 判断当前收到的bit:
- 如果是
1:gired_data[i] |= 0x80→ 最高位(bit7)置1 - 如果是
0:不执行,最高位保持0
- 如果是
- 清空计时
ired_high_time=0,准备下一个bit
举个例子:接收字节 0b00000011(十进制3,bit0=1,bit1=1,其余0)
接收顺序:bit0(1) → bit1(1) → bit2(0) → bit3(0) → bit4(0) → bit5(0) → bit6(0) → bit7(0)
- 第1位(bit0=1)
- 右移:
00000000→00000000 - 置最高位1 →
10000000
- 右移:
- 第2位(bit1=1)
- 右移:
10000000→01000000 - 置最高位1 →
11000000
- 右移:
- 第3位(bit2=0)
- 右移:
11000000→01100000 - 不置位,保持
01100000
- 右移:
- 后面5位都是0,每次只右移,不置最高位
最后8bit收完:00000011
每次右移腾出最高位,新来的bit写到最高位。先发的bit会被不断往右挤,最终存到低bit位,正好适配NEC协议:先发低位。
第20章_舵机实验





servo.py
from machine import PWM
import math
# originally by Radomir Dopieralski http://sheep.art.pl
# from https://bitbucket.org/thesheep/micropython-servo
class Servo:
"""
A simple class for controlling hobby servos.
Args:
pin (machine.Pin): The pin where servo is connected. Must support PWM.
freq (int): The frequency of the signal, in hertz.
min_us (int): The minimum signal length supported by the servo.
max_us (int): The maximum signal length supported by the servo.
angle (int): The angle between the minimum and maximum positions.
"""
def __init__(self, pin, freq=50, min_us=600, max_us=2400, angle=180):
self.min_us = min_us
self.max_us = max_us
self.us = 0
self.freq = freq
self.angle = angle
self.pwm = PWM(pin, freq=freq, duty=0)
def write_us(self, us):
"""Set the signal to be ``us`` microseconds long. Zero disables it."""
if us == 0:
self.pwm.duty(0)
return
us = min(self.max_us, max(self.min_us, us))
duty = us * 1024 * self.freq // 1000000
self.pwm.duty(duty)
def write_angle(self, degrees=None, radians=None):
"""Move to the specified angle in ``degrees`` or ``radians``."""
if degrees is None:
degrees = math.degrees(radians)
degrees = degrees % 360
total_range = self.max_us - self.min_us
us = self.min_us + total_range * degrees // self.angle
self.write_us(us)
main.py
'''
实验名称:舵机实验
接线说明:SG90舵机模块-->ESP32 IO
橙色(信号线)-->(12)
红色(电源正)-->(5V)
褐色(电源负)-->(GND)
实验现象:程序下载成功后,SG90舵机循环以45°步进从0°旋转到180°
'''
#导入Pin模块
from machine import Pin
import time
from servo import Servo
#定义SG90舵机控制对象
my_servo = Servo(Pin(12))
#程序入口
if __name__=="__main__":
while True:
my_servo.write_angle(0) #角度0°
time.sleep(0.5)
my_servo.write_angle(45) #角度45°
time.sleep(0.5)
my_servo.write_angle(90) #角度90°
time.sleep(0.5)
my_servo.write_angle(135) #角度135°
time.sleep(0.5)
my_servo.write_angle(180) #角度180°
time.sleep(0.5)
第21章_OLED液晶显示实验









ssd1602.py
# MicroPython SSD1306 OLED driver, I2C and SPI interfaces
from micropython import const
import framebuf
# register definitions
SET_CONTRAST = const(0x81)
SET_ENTIRE_ON = const(0xA4)
SET_NORM_INV = const(0xA6)
SET_DISP = const(0xAE)
SET_MEM_ADDR = const(0x20)
SET_COL_ADDR = const(0x21)
SET_PAGE_ADDR = const(0x22)
SET_DISP_START_LINE = const(0x40)
SET_SEG_REMAP = const(0xA0)
SET_MUX_RATIO = const(0xA8)
SET_COM_OUT_DIR = const(0xC0)
SET_DISP_OFFSET = const(0xD3)
SET_COM_PIN_CFG = const(0xDA)
SET_DISP_CLK_DIV = const(0xD5)
SET_PRECHARGE = const(0xD9)
SET_VCOM_DESEL = const(0xDB)
SET_CHARGE_PUMP = const(0x8D)
# Subclassing FrameBuffer provides support for graphics primitives
# http://docs.micropython.org/en/latest/pyboard/library/framebuf.html
class SSD1306(framebuf.FrameBuffer):
def __init__(self, width, height, external_vcc):
self.width = width
self.height = height
self.external_vcc = external_vcc
self.pages = self.height // 8
self.buffer = bytearray(self.pages * self.width)
super().__init__(self.buffer, self.width, self.height, framebuf.MONO_VLSB)
self.init_display()
def init_display(self):
for cmd in (
SET_DISP | 0x00, # off
# address setting
SET_MEM_ADDR,
0x00, # horizontal
# resolution and layout
SET_DISP_START_LINE | 0x00,
SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0
SET_MUX_RATIO,
self.height - 1,
SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0
SET_DISP_OFFSET,
0x00,
SET_COM_PIN_CFG,
0x02 if self.width > 2 * self.height else 0x12,
# timing and driving scheme
SET_DISP_CLK_DIV,
0x80,
SET_PRECHARGE,
0x22 if self.external_vcc else 0xF1,
SET_VCOM_DESEL,
0x30, # 0.83*Vcc
# display
SET_CONTRAST,
0xFF, # maximum
SET_ENTIRE_ON, # output follows RAM contents
SET_NORM_INV, # not inverted
# charge pump
SET_CHARGE_PUMP,
0x10 if self.external_vcc else 0x14,
SET_DISP | 0x01,
): # on
self.write_cmd(cmd)
self.fill(0)
self.show()
def poweroff(self):
self.write_cmd(SET_DISP | 0x00)
def poweron(self):
self.write_cmd(SET_DISP | 0x01)
def contrast(self, contrast):
self.write_cmd(SET_CONTRAST)
self.write_cmd(contrast)
def rotate(self, rotate):
self.write_cmd(SET_COM_OUT_DIR | ((rotate & 1) << 3))
self.write_cmd(SET_SEG_REMAP | (rotate & 1))
def invert(self, invert):
self.write_cmd(SET_NORM_INV | (invert & 1))
def show(self):
x0 = 0
x1 = self.width - 1
if self.width == 64:
# displays with width of 64 pixels are shifted by 32
x0 += 32
x1 += 32
self.write_cmd(SET_COL_ADDR)
self.write_cmd(x0)
self.write_cmd(x1)
self.write_cmd(SET_PAGE_ADDR)
self.write_cmd(0)
self.write_cmd(self.pages - 1)
self.write_data(self.buffer)
class SSD1306_I2C(SSD1306):
def __init__(self, width, height, i2c, addr=0x3C, external_vcc=False):
self.i2c = i2c
self.addr = addr
self.temp = bytearray(2)
self.write_list = [b"\x40", None] # Co=0, D/C#=1
super().__init__(width, height, external_vcc)
def write_cmd(self, cmd):
self.temp[0] = 0x80 # Co=1, D/C#=0
self.temp[1] = cmd
self.i2c.writeto(self.addr, self.temp)
def write_data(self, buf):
self.write_list[1] = buf
self.i2c.writevto(self.addr, self.write_list)
class SSD1306_SPI(SSD1306):
def __init__(self, width, height, spi, dc, res, cs, external_vcc=False):
self.rate = 10 * 1024 * 1024
dc.init(dc.OUT, value=0)
res.init(res.OUT, value=0)
cs.init(cs.OUT, value=1)
self.spi = spi
self.dc = dc
self.res = res
self.cs = cs
import time
self.res(1)
time.sleep_ms(1)
self.res(0)
time.sleep_ms(10)
self.res(1)
super().__init__(width, height, external_vcc)
def write_cmd(self, cmd):
self.spi.init(baudrate=self.rate, polarity=0, phase=0)
self.cs(1)
self.dc(0)
self.cs(0)
self.spi.write(bytearray([cmd]))
self.cs(1)
def write_data(self, buf):
self.spi.init(baudrate=self.rate, polarity=0, phase=0)
self.cs(1)
self.dc(1)
self.cs(0)
self.spi.write(buf)
self.cs(1)
main.py
'''
实验名称:OLED液晶显示实验
接线说明:OLED(IIC)液晶模块-->ESP32 IO
GND-->(GND)
VCC-->(5V)
SCL-->(11)
SDA-->(12)
实验现象:程序下载成功后,OLED液晶屏显示字符信息
'''
#导入Pin模块
from machine import Pin
import time
from machine import SoftI2C
from ssd1306 import SSD1306_I2C #I2C的oled选该方法
#创建硬件I2C对象
#i2c=I2C(0,sda=Pin(19), scl=Pin(18), freq=400000)
#创建软件I2C对象
i2c = SoftI2C(sda=Pin(12), scl=Pin(11))
#创建OLED对象,OLED分辨率、I2C接口
oled = SSD1306_I2C(128, 64, i2c)
#程序入口
if __name__=="__main__":
oled.fill(0) #清空屏幕
oled.show() #执行显示
oled.text("Hello World!",0,0,1) #显示字符串
oled.show() #执行显示
oled.pixel(10,20,1) #显示一个像素点
oled.hline(0,10,100,1) #画横线
oled.vline(120,0,30,1) #画竖线
oled.line(10,40,100,60,1) #画指定坐标直线
oled.rect(50,20,50,30,1) #画矩形
oled.fill_rect(60,30,30,20,1) #画填充矩形
oled.show() #执行显示
time.sleep(2)
oled.fill(0) #清空屏幕
oled.text("Hello World!",0,0,1)
oled.show() #执行显示
time.sleep(1)
oled.scroll(10,0) #指定像素X轴移动
oled.fill_rect(0,0,10,8,0) #清除移动前显示区
oled.show() #执行显示
time.sleep(1)
oled.scroll(0,10) #指定像素Y轴移动
oled.fill_rect(0,0,128,10,0) #清除移动前显示区
oled.show() #执行显示
while True:
pass
浙公网安备 33010602011771号