1、
from machine import Pin
from neopixel import NeoPixel
import time
if __name__=="__main__"
#创建RBG灯带控制对象,包含5个像素(5个RGB LED)
rgb_led = NeoPixel(Pin(4,Pin.OUT),5)
#定义RGB颜色
RED=(255,0,0)
GREEN(0,255,0)
BLUE =(0,0,255)
YELLOW=(255,150,0)
WHITE=(255,255,255)# 白色
BLACK=(0,0,0)#黑色(不亮)
COLORS =(RED,GREEN,BLUE,YELLOW,WHITE,BLACK)
for color in COLORS:#逐一点亮每个RGB LED
for i in range(5):
rgb_led[i]=(color[0], color[1], color[2])
rgb_led.write()
time.sleep_ms(200)
time.sleep_ms(300)
2、
from machine import Pin
import time
import tm1637
if __name__=="__main__":
# 定义数码管控制对象
display =tm1637.TM1637(clk=Pin(16),dio=Pin(17))
# 显示小数
display.numbers(13,14)# 13.14
time.sleep(2)
#显示十六进制
display.hex(100)#0x64
time.sleep(2)
#亮度调节
display.brightness(0)
time.sleep(2)
display.brightness(7)
time.sleep(2)
#显示温度值
display.temperature(26)
time.sleep(2)
display.temperature(-10)#低温报警:Lo
time.sleep(2)
display.temperature(100)#高温报警:Hi
time.sleep(2)
#显示字符串
display.show("ABCD")
time.sleep(2)
#字符串滚动显示
display.scroll("18712345678",500)
#倒计时10秒
num = 10
while num >=0:
display.number(num)
num -= 1
time.sleep(1)
3、
import ds18x20
import onewire
from machine import Pin
from machine import Timer
import sys
#创建单总线驱动对象
ow= onewire.OneWire(Pin(4))
#定义DS18B20控制对象
ds18b20=ds18x20.DS18X20(ow)
#扫描设备,获取64位序列码,返回结果保存列表中
roms =ds18b20.scan()
if not roms:
print("没有扫描到DS18B20设备,请检查硬件连接!")
sys.exit()
else:
print("扫描到DS18B20设备,序列码是:",roms)
#定时器回调函数#
def get_temp(timer0):
ds18b20.convert_temp()
for rom in roms:
temp= ds18b20.read_temp(rom)
print("Ds18B20的温度是:%.2f℃"% temp)
if __name__=="__main__":
timer0 =Timer(0)
timer0.init(mode=Timer.PERIODIC, period=1000,callback=get_temp)
while True:
pass
4、
from machine import Pin
import network
import time
led1=Pin(15,Pin.OUT,value=1)
#准备手机热点
ssid="yishen"
password="20020618"
def wifi_connect():
#创建WLAN对象,STA模式
wlan=network.WLAN(network.STA_IF)
#激活WIFI模块
wlan.active(True)
#记录当前的时间用于WIFI连接的超时判定
start_time=time.time()
if not wlan.isconnected():
#准备建立连接
print(wlan.scan())
wlan.connect(ssid,password)
#等待连接让LED闪烁
while not wlan.isconnected():
led1.value(not led1.value())
time.sleep_ms(300)
#判定超时
if time.time()-start_time>30:
print("WIFI连接超时")
return False
else:
#已经连接成功
led1.value(0)
print("网络配置信息",wlan.ifconfig())
return True
if __name__=="__main__":
wifi_connect()
5、
"""
通过socket编程实现一个简易的HTTP服务器
使用手机可以连接到服务器帮控制LED开关
测试:在手机的浏览器输入开发板的IP地址
"""
from machine import Pin
import network
import time
import socket
import sys
# 定义LED控制对象,作为连接WIFI指示灯
led1 = Pin(15, Pin.OUT, value=1)
# 准备手机热点
ssid = "yishen"
password = "20020618"
def wifi_connect():
# 创建WLAN对象,STA模式(ESP32开发板连接手机热点-AP)
wlan = network.WLAN(network.STA_IF)
# 激活WIFI模块
wlan.active(True)
# 记录当前时间,用于WIFI连接的超时判定
start_time = time.time()
if not wlan.isconnected():
# 准备建立连接
# print(wlan.scan())
print("开始连接WIFI...")
wlan.connect(ssid, password)
# 等待连接让LED1闪烁
while not wlan.isconnected():
led1.value(not led1.value())
time.sleep_ms(300)
# 超时判定
if time.time() - start_time > 30:
print("WIFI连接超时!")
return False
else:
# 已经连接成功(如果之前连接过WIFI,上电后会自动连接)
led1.value(0)
print("网络配置信息", wlan.ifconfig()) # 重点关注IP地址
return True
# 网页数据
def web_page():
# 获取开关灯的状态
if led1.value() == 0:
led_state = " "
else:
led_state = "checked"
html = \
"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTTP</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
font-family: Arial;
text-align: center;
margin: 0px auto;
padding-top: 30px;
}
.switch {
position: relative;
display: inline-block;
width: 120px;
height: 68px
}
.switch input {
display: none
}
.slider {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
border-radius: 34px
}
.slider:before {
position: absolute;
content: "";
height: 52px;
width: 52px;
left: 8px;
bottom: 8px;
background-color: #fff;
-webkit-transition: .4s;
transition: .4s;
border-radius: 68px
}
input:checked+.slider {
background-color: #2196F3
}
input:checked+.slider:before {
-webkit-transform: translateX(52px);
-ms-transform: translateX(52px);
transform: translateX(52px)
}
</style>
<script>
function toggleCheckbox(element) {
var xhr = new XMLHttpRequest();
if (element.checked) {
xhr.open("GET", "/?led1=on", true);
}
else {
xhr.open("GET", "/?led1=off", true);
}
xhr.send();
}
</script>
</head>
<body>
<h1>ESP32 LED</h1>
<label class="switch">
<input type="checkbox" onchange="toggleCheckbox(this)" %s>
<span class="slider"></span>
</label>
</body>
</html>
""" % (led_state)
return html
if __name__ == "__main__":
# 连接WiFi
while True:
try:
if wifi_connect():
break
except Exception as ex:
print("WIFI连接异常:", ex)
time.sleep_ms(1000)
print("WIFI连接成功!")
try:
# 创建HTTP通信的套接字(本质就是TCP通信)
http_socket = socket.socket()
# 设置地址重用选项
http_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 绑定地址
http_socket.bind(("0.0.0.0", 80))
# 设置监听
http_socket.listen()
print("创建HTTP服务器成功")
except Exception as ex:
print("创建HTTP服务器失败:", ex)
sys.exit()
# 服务器一直运行
while True:
try:
# 等待客户端连接,返回两个数据,分别是和客户端通信的套接字、客户端地址
client, addr = http_socket.accept()
print("客户端%s建立了连接" % str(addr))
# 接收客户端请求数据
request = client.recv(1024)
request = str(request)
print("收到客户端请求=%s" % request)
# GET /?led1=off HTTP/1.1......
# GET /?led1=on HTTP/1.1......
if request.find("/?led1=on") == 6:
led1.value(1)
elif request.find("/?led1=off") == 6:
led1.value(0)
# 发送响应:给客户端返回数据
client.send("HTTP/1.1 200 OK\n") # 状态行
client.send("Content-Type: text/html\n") # 响应头
client.send("Connection: close\n\n") # 响应头
response = web_page() # 响应消息体
client.write(response) # 发送响应消息
client.close() # 关闭本次通信
except Exception as ex:
print("HTTP通信异常:", ex)
6、
from machine import Pin
import network
import time
import socket
import onewire
import ds18x20
#创建单总线驱动对象
ow= onewire.OneWire(Pin(4))
#定义DS18B20控制对象
ds18b20=ds18x20.DS18X20(ow)
#扫描设备,获取64位序列码,返回结果保存列表中
# 初始化LED对象
led1 = Pin(15, Pin.OUT, value=1)
roms =ds18b20.scan()
#定时器回调函数#
def get_temp(timer0):
ds18b20.convert_temp()
for rom in roms:
temp= ds18b20.read_temp(rom)
print("Ds18B20的温度是:%.2f℃"% temp)
# 准备手机热点
ssid = "yishen"
password = "20020618"
def wifi_connect(ssid, password):
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
start_time = time.time()
if not wlan.isconnected():
print("连接到WiFi...")
wlan.connect(ssid, password)
while not wlan.isconnected():
pass
print("网络配置信息:", wlan.ifconfig())
return wlan
# 准备网页数据
def web_page(temp):
html = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>DS18B20</title>
<style>
html {
font-family: Arial;
display: inline-block;
margin: 0px auto;
text-align: center;
}
h2 {
font-size: 3.0rem;
}
p {
font-size: 3.0rem;
}
.units {
font-size: 1.2rem;
}
.ds-labels {
font-size: 1.5rem;
vertical-align: middle;
padding-bottom: 15px;
}
</style>
</head>
<body>
<h2>ESP32</h2>
<p><i class="fas fa-thermometer-half" style="color:#059e8a;"></i>
<span class="ds-labels">Temperature</span>
<span id="temperature">""" + "%0.1f" % temp + """</span>
<sup class="units">°C</sup>
</p>
<p><i class="fas fa-thermometer-half" style="color:#059e8a;"></i>
<span class="ds-labels">Temperature</span>
<span id="temperature">""" + str(round(temp * (9 / 5) + 32.0, 1)) + """</span>
<sup class="units">°F</sup>
</p>
</body>
</html>
"""
return html
if __name__ == '__main__':
# 初始化WiFi连接
wlan = wifi_connect(ssid, password)
try:
# 创建TCP套接字并绑定地址
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('0.0.0.0', 80))
s.listen(5)
print('HTTP服务器已启动.')
while True:
conn, addr = s.accept()
print('客户端地址:', addr)
request_data = conn.recv(1024)
request_data = str(request_data)
print('收到请求:', request_data)
# 获取DS18B20传感器数据
get_temp(None) # 此处传入None,因为定时器回调函数不需要参数
# 读取最新得到的温度数据
temp = ds18b20.read_temp(roms[0]) # 假定只有一个DS18B20设备
# 准备并发送网页响应
response = web_page(temp)
conn.send(b'HTTP/1.1 200 OK\n')
conn.send(b'Content-Type: text/html\n')
conn.send(b'Connection: close\n\n')
conn.sendall(response)
conn.close()
except Exception as ex:
print("HTTP服务器异常:", ex)