1.ESP32保存路径不要有空格和中文
ESP32推荐学习网站:
https://lingshunlab.com/book/esp32/esp32-pinout-reference
正点原子ESP
1.ESP32--LED闪烁实验
from machine import Pin
import time
LED=Pin(2,Pin.OUT)#GPIO2,设置为输出模式,输入模式为Pin.IN
while True:
LED.value(1)
time.sleep(0.5)
LED.value(0)
time.sleep(0.5)
2.ESP32--LED流水灯
from machine import Pin
import time
led_pin=[2,3,4,5]#定义GPIO口,设置为输出模式,输入模式为Pin.IN
leds=[]#led列表,保存管脚配置对象
for i in range(4):
leds.append(Pin(led_pin[i],Pin.OUT))
#leds=[Pin(led_pin[i],Pin.OUT) for i in range(0,4)]
if __name__=="__main__":
for n in range(4):#初始化0
leds[n].value(0)
#逐个点亮
while True:
for n in range(4):
leds[n].value(1)
time.sleep(0.25)
#逐个熄灭
for n in range(4):
leds[n].value(0)
time.sleep(0.25)
3.ESP32--蜂鸣器beep实验
from machine import Pin
import time
beep=Pin(2,Pin.OUT)#GPIO2,设置为输出模式,输入模式为Pin.IN
if __name__=="__main__":
i=0
while True:
i= not i
beep.value(i)
time.sleep_us(100000)
"""
while True:
beep.value(1)
time.sleep(0.5)
beep.value(0)
time.sleep(0.5)
4.ESP32-按键实验
from machine import Pin
import time
key1=Pin(4,Pin.IN,Pin.PULL_UP)#GPIO2,设置为输出模式,输入模式为Pin.IN,设置为上拉
key2=Pin(5,Pin.IN,Pin.PULL_UP)
led1=Pin(2,Pin.OUT)
led2=Pin(3,Pin.OUT)
KEY1_RPESS,KEY2_RPESS=1,2
key_en=1
def key_scan():
global key_en
if key_en==1 and (key1.value()==0 or key2.value()==0):
time.sleep_ms(10) #消抖
key=0
if key1.value()==0: #key1按下
return KEY1_RPESS
elif key2.value()==0: #key2按下
return KEY2_RPESS
elif key1.value()==1 and key2.value()==1:
key_en=1
return 0
if __name__=="__main__":
key=0
i_led1,i_led2=0,0#状态变量,
led1.value(i_led1)#熄灭
led1.value(i_led2)
while True:
key=key_scan()
if key==KEY1_RPESS:
i_led1=not i_led1
led1.value(i_led1)
elif key==KEY2_RPESS:
i_led2=not i_led2
led2.value(i_led2)
5.ESP32-中断实验
外部中断,通过按键来控制LED灯



6.ESP32-定时器实验
中断定时器实验;
from machine import Pin
from machine import Timer
led=Pin(2,Pin.OUT)
led_state=0
def time0_irq(time0): #定时器0中断函数
global led_state
led_state=not led_state
led.value(led_state)
if __name__=="__main__":
led.value(led_state)
time0=Timer(1)
time0.init(period=200,mode=Timer.PERIODIC,callback=time0_irq)
while True:
pass
7.ESP32--PWM呼吸灯
PWM呼吸灯实验;
from machine import Pin
from machine import PWM
import time
pwm=PWM(Pin(2),freq=1000, duty=0)#GPIO2,设置为输出模式,输入模式为Pin.IN
if __name__=="__main__":
duty_value=0
fx=1
while True:
if fx==1:
duty_value+=2
if duty_value>1010:
fx=0
else:
duty_value-=2
if duty_value<1:
fx=1
pwm.duty(duty_value)
time.sleep_ms(10)
8.ESP32--UART串口
UART串口实验:
from machine import Pin
from machine import UART
import time
uart=UART(2,115200,rx=16,tx=17)
if __name__=="__main__":
uart.write("Hello wrold")
while True:
if uart.any():
text=uart.read(128)
uart.write(text)
9.ESP32--ADC
ADC实验:
from machine import Pin
from machine import ADC
from machine import Timer#使用定时器定时采集
adc=ADC(Pin(15))
led=Pin(2,Pin.OUT)
adc.atten(ADC.ATTN_11DB)#开启衰减,量程最大3.3V
led_state=0
def time0_irq(time0):
global led_state
led_state = not led_state
led.value(led_state)
adc_vol=3.3*adc.read()/4095 #12位精度,3.3*AD/2^12
print("ADC检测电压:%.2fV",adc_vol)
def LED_irq(time0):
global led_state
led_state = not led_state
led.value(led_state)
if __name__=="__main__":
#定时器0用于定期采集电压
time0=Timer(0)
time0.init(period=500,mode=Timer.PERIODIC,callback=time0_irq)
#定时器1用于指示灯
time1=Timer(1)
time1.init(period=250,mode=Timer.PERIODIC,callback=LED_irq)
while True:
pass
10.ESP32--RTC

11.DHT11温湿度传感器
DHT11实验:
from machine import Pin
import time
import dht
dht11=dht.DHT11(Pin(15))
if __name__=="__main__":
#定时器0用于定期采集电压
time.sleep(1)#先稳定传感器
while True:
dht11.measure()
temp = dht11.temperature()
humi=dht11.humidity()
if temp==None:
print("检测失败")
else:
print("温度:%d C 湿度:%d RH",temp,humi)
time.sleep(2)#延时确保传感器正常工作
12.ESP32-OLED
ssd1306.py
#MicroPython SSD1306 OLED driver, I2C and SPI interfaces created by Adafruit
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)
class SSD1306:
def __init__(self, width, height, external_vcc):
self.width = width
self.height = height
self.external_vcc = external_vcc
self.pages = self.height // 8
# Note the subclass must initialize self.framebuf to a framebuffer.
# This is necessary because the underlying data buffer is different
# between I2C and SPI implementations (I2C needs an extra byte).
self.poweron()
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.height == 32 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 contrast(self, contrast):
self.write_cmd(SET_CONTRAST)
self.write_cmd(contrast)
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_framebuf()
def fill(self, col):
self.framebuf.fill(col)
def pixel(self, x, y, col):
self.framebuf.pixel(x, y, col)
def scroll(self, dx, dy):
self.framebuf.scroll(dx, dy)
def text(self, string, x, y, col=1):
self.framebuf.text(string, x, y, col)
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)
# Add an extra byte to the data buffer to hold an I2C data/command byte
# to use hardware-compatible I2C transactions. A memoryview of the
# buffer is used to mask this byte from the framebuffer operations
# (without a major memory hit as memoryview doesn't copy to a separate
# buffer).
self.buffer = bytearray(((height // 8) * width) + 1)
self.buffer[0] = 0x40 # Set first byte of data buffer to Co=0, D/C=1
self.framebuf = framebuf.FrameBuffer1(memoryview(self.buffer)[1:], width, height)
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_framebuf(self):
# Blast out the frame buffer using a single I2C transaction to support
# hardware I2C interfaces.
self.i2c.writeto(self.addr, self.buffer)
def poweron(self):
pass
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
self.buffer = bytearray((height // 8) * width)
self.framebuf = framebuf.FrameBuffer1(self.buffer, width, height)
super().__init__(width, height, external_vcc)
def write_cmd(self, cmd):
self.spi.init(baudrate=self.rate, polarity=0, phase=0)
self.cs.high()
self.dc.low()
self.cs.low()
self.spi.write(bytearray([cmd]))
self.cs.high()
def write_framebuf(self):
self.spi.init(baudrate=self.rate, polarity=0, phase=0)
self.cs.high()
self.dc.high()
self.cs.low()
self.spi.write(self.buffer)
self.cs.high()
def poweron(self):
self.res.high()
time.sleep_ms(1)
self.res.low()
time.sleep_ms(10)
self.res.high()
main.py
# IIC——OLED
from machine import Pin
import time
from machine import SoftI2C
from ssd1306 import SSD1306_I2C
#创建硬件件I2C对象
#i2c = I2C(0,sda=Pin(19),scl=Pin(18))
#创建软件I2C对象
i2c = SoftI2C(sda=Pin(23),scl=Pin(18))
oled=SSD1306_I2C(128,64,i2c)
if __name__=="__main__":
oled.fill(0)
oled.show()
oled.text("hello world")
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.show()
time.sleep(2)
oled.fill(0)
oled.text("hello world")
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
例外:补充
1.8X8显示字符
from machine import Pin, SoftI2C #从机器导入GPIO模块和软件I2C模块
import ssd1306 #导入之前已经上传的ssd1306.py库
from time import sleep
# ESP32 Pin assignment
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
# ESP8266 Pin assignment
#i2c = SoftI2C(scl=Pin(5), sda=Pin(4))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
oled.text('Hello, World 1!', 0, 0)
oled.text('Hello, World 2!', 0, 10)
oled.text('Hello, World 3!', 0, 20)
oled.show()
2.显示中文
from machine import Pin, I2C
#OLED=....
i2c = I2C(scl=Pin(22), sda=Pin(21))
from ssd1306 import SSD1306_I2C
OLED= SSD1306_I2C(128, 64, i2c)
#fonts=....
fonts= {
0xe585b3:
[0x10, 0x08, 0x08, 0x00, 0x3F, 0x01, 0x01, 0x01, 0xFF, 0x01, 0x02, 0x02, 0x04, 0x08, 0x30, 0xC0,
0x10, 0x10, 0x20, 0x00, 0xF8, 0x00, 0x00, 0x00, 0xFE, 0x00, 0x80, 0x80, 0x40, 0x20, 0x18, 0x06], # 关
0xe788b1:
[0x00, 0x01, 0x7E, 0x22, 0x11, 0x7F, 0x42, 0x82, 0x7F, 0x04, 0x07, 0x0A, 0x11, 0x20, 0x43, 0x1C,
0x08, 0xFC, 0x10, 0x10, 0x20, 0xFE, 0x02, 0x04, 0xF8, 0x00, 0xF0, 0x10, 0x20, 0xC0, 0x30, 0x0E], # 爱
0xe58d95:
[0x10, 0x08, 0x04, 0x3F, 0x21, 0x21, 0x3F, 0x21, 0x21, 0x3F, 0x01, 0x01, 0xFF, 0x01, 0x01, 0x01,
0x10, 0x20, 0x40, 0xF8, 0x08, 0x08, 0xF8, 0x08, 0x08, 0xF8, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x00], # 单
0xe8baab:
[0x02, 0x04, 0x1F, 0x10, 0x1F, 0x10, 0x1F, 0x10, 0x10, 0x7F, 0x00, 0x00, 0x03, 0x1C, 0xE0, 0x00,
0x00, 0x00, 0xF0, 0x10, 0xF0, 0x10, 0xF2, 0x14, 0x18, 0xF0, 0x50, 0x90, 0x10, 0x10, 0x50, 0x20], # 身
0xe78b97:
[0x00, 0x44, 0x29, 0x11, 0x2A, 0x4C, 0x89, 0x09, 0x19, 0x29, 0x49, 0x89, 0x08, 0x08, 0x50, 0x20,
0x80, 0x80, 0x00, 0xFC, 0x04, 0x04, 0xE4, 0x24, 0x24, 0x24, 0xE4, 0x24, 0x04, 0x04, 0x28, 0x10], # 狗
0xe68890:
[0x00, 0x00, 0x00, 0x3F, 0x20, 0x20, 0x20, 0x3E, 0x22, 0x22, 0x22, 0x22, 0x2A, 0x44, 0x40, 0x81,
0x50, 0x48, 0x40, 0xFE, 0x40, 0x40, 0x44, 0x44, 0x44, 0x28, 0x28, 0x12, 0x32, 0x4A, 0x86, 0x02], # 成
0xe995bf:
[0x08, 0x08, 0x08, 0x08, 0x08, 0x09, 0x08, 0xFF, 0x0A, 0x09, 0x08, 0x08, 0x09, 0x0A, 0x0C, 0x08,
0x00, 0x10, 0x20, 0x40, 0x80, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x80, 0x40, 0x20, 0x18, 0x06, 0x00], # 长"
0xe58d8f:
[0x20, 0x20, 0x20, 0x20, 0xFB, 0x20, 0x20, 0x22, 0x22, 0x24, 0x28, 0x20, 0x21, 0x21, 0x22, 0x24,
0x80, 0x80, 0x80, 0x80, 0xF0, 0x90, 0x90, 0x98, 0x94, 0x92, 0x92, 0x90, 0x10, 0x10, 0x50, 0x20], # 协
0xe4bc9a:
[0x01, 0x01, 0x02, 0x04, 0x08, 0x30, 0xCF, 0x00, 0x00, 0x7F, 0x02, 0x04, 0x08, 0x10, 0x3F, 0x10,
0x00, 0x00, 0x80, 0x40, 0x20, 0x18, 0xE6, 0x00, 0x00, 0xFC, 0x00, 0x00, 0x20, 0x10, 0xF8, 0x08] # 会
}
#函数部分
def chinese(ch_str, x_axis, y_axis):
offset_ = 0
for k in ch_str:
code = 0x00 # 将中文转成16进制编码
data_code = k.encode("utf-8")
code |= data_code[0] << 16
code |= data_code[1] << 8
code |= data_code[2]
byte_data = fonts[code]
for y in range(0, 16):
a_ = bin(byte_data[y]).replace('0b', '')
while len(a_) < 8:
a_ = '0'+ a_
b_ = bin(byte_data[y+16]).replace('0b', '')
while len(b_) < 8:
b_ = '0'+ b_
for x in range(0, 8):
OLED.pixel(x_axis + offset_ + x, y+y_axis, int(a_[x]))
OLED.pixel(x_axis + offset_ + x +8, y+y_axis, int(b_[x]))
offset_ += 16
chinese('关爱单身狗',16,4)
OLED.show()
OLED.text('hello world',0,32)
OLED.show()
13.ESP32-WIFI
from machine import Pin
import time
import network
led=Pin(2,Pin.OUT)
ssid="Mi10S"
password="jjh18776489677"
def wifi_connect():
wlan=network.WLAN(network.STA_IF)
wlan.active(True)
start_time=time.time()
if not wlan.isconnected():
print("WIFI connect ......")
wlan.connect(ssid,password)
while not wlan.isconnected():
led.value(1)
time.sleep_ms(250)
led.value(0)
time.sleep_ms(250)
if time.time()-start_time>10:
print("WIFI connect FAIL")
break
else:
led.value(0)
print("network information:",wlan.ifconfig())
if __name__=="__main__":
wifi_connect()
14.ESP32-Socket实验
socket实验,esp32作为客户端连接路由器热点,然后电脑也连接路由器,此时可在电脑端使用网络调试助手
设置:协议类型:TCP Server,本机主机地址ipconfig:电脑端IP地址IP4,ipconfig命令得到,本机主机端口:0-65535,不能是80,本处用1000
from machine import Pin
import time
import network
import usocket
led=Pin(2,Pin.OUT)
ssid="yb512"
password="512512512"
dest_ip="192.168.1.116"
dest_port=10000
def wifi_connect():
wlan=network.WLAN(network.STA_IF) #STA模式
wlan.active(True) #激活
start_time=time.time()
if not wlan.isconnected():
print("WIFI connect ......")
wlan.connect(ssid,password)#输入wifi账号密码
while not wlan.isconnected():
led.value(1)
time.sleep_ms(250)
led.value(0)
time.sleep_ms(250)
if time.time()-start_time>15:
print("WIFI connect Timeout")
break
return False
else:
led.value(0)
print("network information:",wlan.ifconfig())
return True
if __name__=="__main__":
if wifi_connect():
socket=usocket.socket()#采用默认配置
addr=(dest_ip,dest_port)#元组保存 服务器的IP地址和端口号
socket.connect(addr)
socket.send("hello wrold")
while True:
text=socket.recv(128)
if text==None:
pass
else:
print(text)
socket.send("get:"+text.decode("utf-8"))
time.sleep(250)
15.ESP32-MQTT
ESP32-MQTT是工作在TCP/IP 协议族上,通常会调用socket接口,是一个基于客户端-服务器的消息发布/订阅传输协议。
16.手机或者电脑控制ESP32
自己建立一个web server,就是自己建立一个网站服务器,就会有一个ip地址,在手机或电脑和esp32连接同一个wifi的情况下,让手机或电脑登录那个ip地址的网站就可以给esp32发送相应信息,esp32收到不同的信息执行不同操作,本代码就是实现控制开灯与关灯。
from machine import Pin
import network
import socket
led = Pin(2,Pin.OUT)
ssid = 'Mi10s' #wifi名称
password = 'jjh18776489677' #wifi密码
def wifi_connect():
wlan=network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("connecting to network ......")
wlan.connect(ssid,password)
while not wlan.isconnected():
led.value(1)
time.sleep_ms(250)
led.value(0)
time.sleep_ms(250)
led.value(0)
return False
else:
led.value(0)
print("network information:",wlan.ifconfig())
return True
def web_page():
html = """<html><head><meta name="viewport"
content="width=device-width, initial-scale=1"></head>
<body><h1>Ojay Server</h1><a
href=\"?led=on\"><button>ON</button></a>
<a
href=\"?led=off\"><button>OFF</button></a></body><html>"""
return html
if __name__=="__main__":
if wifi_connect():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('',80))
s.listen(5)
while True:
client, addr = s.accept()
print('Got a connection from %s' % str(addr))
request = conn.recv(1024)
request = str(request)
print('Content = %s' % request)
led_on = request.find('/?led=on')#接收到对象在第几个位置出现,返回出现的第几个位置
led_off = request.find('/?led=off')
if led_on == 6:#第六个位置接收到, href=\"?led=on\"(在第六个字符)
print('LED ON')
led.value(1)
if led_off == 6:
print('LED OFF')
led.value(0)
response = web_page()
conn.send('HTTP/1.1 200 OK\n')
conn.send('Content-Type: text/html\n')
conn.send('Connection: close\n\n')
conn.send('HTTP/1.1 200 OK\n')
conn.sendall(response)
conn.close()
if led_on == 6:
接收到的在第六个位置:
在返回的IP地址,复制在网页中打开即可,如192.168.191.5
参考:
https://blog.youkuaiyun.com/weixin_45116099/article/details/119191907
2024.8.15补,45年今天小鬼子投降。