开发方式
- ESP32开发
- MicroPython
- Arduino
- ESP-IDF
MicroPython
- Thonny
- ch340
led闪烁
# main.py
from machine import Pin
import time
# esp32-cam的led
led1=Pin(4,Pin.OUT)
while True:
led1.value(1)
time.sleep(0.5)
led1.value(0)
time.sleep(0.5)
PWM
- pwm
- 频率
- 占空比
import machine
pwm0 = machine.PWM(machine.Pin(4))
# freq = pwm0.freq()
# 设置频率
pwm0.freq(1000)
# duty = pwm0.duty()
# 设置占空比 duty
# 0~1023
pwm0.duty(2)
呼吸灯
import machine
import time
pwm0 = machine.PWM(machine.Pin(4))
# freq = pwm0.freq()
# 设置频率
pwm0.freq(1000)
# duty = pwm0.duty()
# 设置占空比 duty
# 0~1023
while True:
for i in range(0,1024):
pwm0.duty(i)
time.sleep_ms(2)
for i in range(1023,-1,-1):
pwm0.duty(i)
time.sleep_ms(2)
WIFI
- 模式
- AP
- 提供信号
- STA
- 连接信号
- AP
import network
wlan = network.WLAN(network.STA_IF) # create station interface
wlan.active(True) # activate the interface
wlan.scan() # scan for access points
wlan.isconnected() # check if the station is connected to an AP
wlan.connect('essid', 'password') # connect to an AP
wlan.config('mac') # get the interface's MAC address
wlan.ifconfig() # get the interface's IP/netmask/gw/DNS addresses
socket
from socket import *
# 1. 创建udp套接字
udp_socket = socket(AF_INET, SOCK_DGRAM)
# 2. 准备接收方的地址
dest_addr = ('192.168.31.56', 8080)
# 3. 从键盘获取数据
send_data = "hello world"
# 4. 发送数据到指定的电脑上
udp_socket.sendto(send_data.encode('utf-8'), dest_addr)
# 5、获取电脑发送的数据
recv_data = udp_socket.recvfrom(1024)
# 6. 关闭套接字
udp_socket.close()
远程控制led
import time
import network
import socket
import machine
def do_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect('CMCC-cAGc', 'rjbgzvvf')
i = 1
while not wlan.isconnected():
print("正在链接...{}".format(i))
i += 1
time.sleep(1)
print('network config:', wlan.ifconfig())
def create_udp_socket():
# 1. 创建udp套接字
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定端口号
udp_socket.bind(("0.0.0.0",7788))
return udp_socket
def get_led():
# esp32-cam的led
return machine.Pin(4,machine.Pin.OUT)
def led_on(led):
led.value(1)
def led_off(led):
led.value(0)
def main():
do_connect()
udp_socket = create_udp_socket()
led1 = get_led()
while True:
# 一次接收1024
recv_data,sender_info = udp_socket.recvfrom(1024)
print("{}发送的数据,{}".format(sender_info,recv_data))
# 解码
recv_data_str = recv_data.decode("utf-8")
print("解码后的数据,{}".format(recv_data_str))
if recv_data_str == "light on":
led_on(led1)
elif recv_data_str == "light off":
led_off(led1)
if __name__ == "__main__":
main()
http请求
import socket
import time
import network
import re
from machine import Pin
# 全局变量,标记led灯
led = Pin(4, Pin.OUT)
def do_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect('CMCC-cAGc', 'rjbgzvvf')
i = 1
while not wlan.isconnected():
print("正在链接...{}".format(i))
i += 1
time.sleep(1)
print('network config:', wlan.ifconfig())
return wlan.ifconfig()[0]
def handle_request(client_socket):
"""
处理浏览器发送过来的数据
然后回送相对应的数据(html、css、js、img。。。)
:return:
"""
# 1. 接收
recv_content = client_socket.recv(1024).decode("utf-8")
print("-----接收到的数据如下----:")
# print(recv_content)
lines = recv_content.splitlines() # 将接收到的http的request请求数据按照行进行切割到一个列表中
# for line in lines:
# print("---")
# print(line)
# 2. 处理请求
# 提取出浏览器发送过来的request中的路径
# GET / HTTP/1.1
# GET /index.html HTTP/1.1
# .......
# lines[0]
# 提取出/index.html 或者 /
request_file_path = re.match(r"[^/]+(/[^ ]*)", lines[0]).group(1)
print("----提出来的请求路径是:----")
print(request_file_path)
# 完善对方访问主页的情况,如果只有/那么就认为浏览器要访问的是主页
if request_file_path == "/":
if led.value():
request_file_path = "led_on.html"
else:
request_file_path = "led_off.html"
if request_file_path == "/switch_btn":
if led.value():
led.value(0)
request_file_path = "led_off.html"
else:
led.value(1)
request_file_path = "led_on.html"
try:
# 取出对应的文件的数据内容
with open(request_file_path, "rb") as f:
content = f.read()
except Exception as ret:
# 如果要是有异常,那么就认为:找不到那个对应的文件,此时就应该对浏览器404
print(ret)
response_headers = "HTTP/1.1 404 Not Found\r\n"
response_headers += "Content-Type:text/html;charset=utf-8\r\n"
response_headers += "\r\n"
response_boy = "----sorry,the file you need not found-------"
response = response_headers + response_boy
# 3.2 给浏览器回送对应的数据
client_socket.send(response.encode("utf-8"))
else:
# 如果要是没有异常,那么就认为:找到了指定的文件,将其数据回送给浏览器即可
response_headers = "HTTP/1.1 200 OK\r\n"
response_headers += "Content-Type:text/html;charset=utf-8\r\n"
response_headers += "\r\n"
response_boy = content
response = response_headers.encode("utf-8") + response_boy
# 3.2 给浏览器回送对应的数据
client_socket.send(response)
# 4. 关闭套接字
client_socket.close()
def tcp_server_control_led():
print("---1---")
# 1. 创建套接字
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 为了保证在tcp先断开的情况下,下一次依然能够使用指定的端口,需要设置
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print("---2---")
# 2. 绑定本地信息
tcp_server_socket.bind(("", 80))
print("---3---")
# 3. 变成监听套接字
tcp_server_socket.listen(128)
print("---4---")
while True:
# 4. 等待客户端的链接
client_socket, client_info = tcp_server_socket.accept()
print("---5---")
print(client_info) # 打印 当前是哪个客户端进行了请求
print("---6---")
# 5. 为客户端服务
handle_request(client_socket)
print("---7---")
# 6. 关闭套接字
tcp_server_socket.close()
def main():
# 1. 链接wifi
ip = do_connect()
print("ip地址是:", ip)
# 3. 创建tcp服务器,等待客户端链接,然后根据客户端的命令控制LED灯
tcp_server_control_led()
if __name__ == "__main__":
main()
- led_on.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>www.itprojects.cn</title>
</head>
<body>
<span style="font-size: 60px;">远程控制LED系统</span>
<div>
<span style="font-size: 50px;vertical-align:middle;">开关</span>
<a href="/switch_btn">
<img src="https://doc.itprojects.cn/0006.zhishi.esp32/02.doc/assets/button_open.png" style="height:60px;vertical-align:middle;">
</a>
</div>
</body>
</html>
- led_off.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>www.itprojects.cn</title>
</head>
<body>
<span style="font-size: 60px;">远程控制LED系统</span>
<div>
<span style="font-size: 50px;vertical-align:middle;">开关</span>
<a href="/switch_btn">
<img src="https://doc.itprojects.cn/0006.zhishi.esp32/02.doc/assets/button_close.png" style="height:60px;vertical-align:middle;">
</a>
</div>
</body>
</html>
其他
语法
-
from machine import Pin
- led = machine.Pin(id,mode,pull)
- led:构建对象
- id:引脚编号
- mode:输入输出模式
- pull:上下拉电阻配置
- led.value([x])
- x:0,低电平
- x:1,高电平
- led.on()
- 输出高电平
- led.off()
- 输出低电平
- led = machine.Pin(id,mode,pull)
-
import time
- time.sleep(1)
- 延时1s
- time.sleep_ms(500)
- 延时500ms
- time.sleep_us(500)
- 延时500us
- start = time.ticks_ms()
- delta = time.ticks_diff(time.ticks_ms(),start)
- 计算毫秒差值
- time.sleep(1)
-
range(start,end,scan)
- 创建一个列表
- start:开始,默认0
- end:结束,但不包括
- scan:跳跃间距,默认1
led流水灯
from machine import Pin
import time
led_pin = [15,2,0,4,16,17,5,18]
leds = []
for i in ragne(8):
leds.append(Pin(led_pin[i],Pin.OUT))
if __name__ == "__main__":
for n in range(8):
leds[n].value(0)
while True:
for n in range(8):
leds[n] value(1)
time.sleep(0.05)
for n in range(8):
leds[n] value(0)
time.sleep(0.05)
蜂鸣器
from machine import Pin
import time
beep = Pin(25,Pin.OUT)
if __name__=="__main__":
i = 0
while Thre:
i = not i
beep.value(i)
time.sleep_us(250) # 频率2khz
继电器
from machine import Pin
import time
relay = Pin(25,Pin.OUT)
if __name__=="__main__":
i = 0
while Thre:
i = not i
relay.value(i)
time.sleep(1)
按键
from machine import Pin
import time
key1 = Pin(14,Pin.IN,PULL_UP)
key2 = Pin(27,Pin.IN,PULL_UP)
key3 = Pin(26,Pin.IN,PULL_UP)
key4 = Pin(25,Pin.IN,PULL_UP)
led1 = Pin(15,Pin.OUT)
led2 = Pin(2,Pin.OUT)
led3 = Pin(0,Pin.OUT)
led4 = Pin(4,Pin.OUT)
KEY1_PRESS,KEY2_PRESS,KEY3_PRESS,KEY4_PRESS = 1,2,3,4
key_en = 1
def key_scan():
global key_en
if key_en == 1 and (key1.value()==0 or key2.value()==0 or key3.value()==0 or key4.value()==0):
time.sleep_ms(10) # 消抖
key_en = 0
if key1.value()==0:
return KEY1_PRESS
if key2.value()==0:
return KEY2_PRESS
if key3.value()==0:
return KEY3_PRESS
if key4.value()==0:
return KEY4_PRESS
elif key1.value()==1 and key2.value()==1 and key3.value()==1 and key4.value()==1:
key_en = 1
return 0
if __name__=="__main__":
key = 0
i_led11,i_led2,i_led3,i_led4=0,0,0,0
led1.value(i_led1)
led2.value(i_led2)
led3.value(i_led3)
led4.value(i_led4)
while True:
key = key_scan()
if key==KEY1_PRESS:
i_led1 = not i_led1
led1.value(i_led1)
elif key==KEY2_PRESS:
i_led2 = not i_led2
led2.value(i_led2)
elif key==KEY3_PRESS:
i_led3 = not i_led3
led3.value(i_led3)
elif key==KEY4_PRESS:
i_led4 = not i_led4
led4.value(i_led4)