esp32作为wifi,通过8通道多路选择器+socket给手机发送数据
在板子运行时,手机可随时接入,不会影响板子
参考网站:micropython中给socket设置回调 - M - Jay 的个人博客
(60条消息) micropython中socket函数回调(非阻塞)(non-blocking)_Youkii-Chen的博客-CSDN博客
这两个参考的内容是,防止socket的accept函数阻塞主程序运行
项目整体代码如下:
import network import socket import time from machine import TouchPad, Pin #引入touchpad模块 from time import sleep from machine import UART import utime import ssd1306 import machine import ure scl = machine.Pin(22,machine.Pin.OUT,machine.Pin.PULL_UP) sda = machine.Pin(21,machine.Pin.OUT,machine.Pin.PULL_UP) S0 = Pin(26,Pin.OUT) S1 = Pin(27,Pin.OUT) S2 = Pin(14,Pin.OUT) uart2 = UART(2,115200) i2c = machine.SoftI2C(scl = scl,sda = sda,freq = 100000) oled = ssd1306.SSD1306_I2C(128,64,i2c,addr = 0x3C) def to_bin(value, number):#十进制数据,二进制位宽 bin_chars = "" temp = value-1 for i in range(number): bin_char = bin(temp % 2)[-1] temp = temp // 2 eval('S{}'.format(i)).value(int(bin_char)) #相当于Si.value(bin_char) bin_chars = bin_char + bin_chars return bin_chars.upper()#输出指定位宽的二进制字符串 def process(message): #从传感器端传来的压力和温度数值抽出压力数值并保留三位,然后转换为字符串 message = str(message) if len(message) >10 and float(message[11:18]): result = str(round(float(message[11:18]),3)) if len(result) > 5: result = result[:5] return result return None def print_text(msg,x,y): oled.fill(0) oled.text(msg[0],x,y-5) oled.text(msg[1],x-10,y+15) oled.show() touch_up = TouchPad(Pin(12)) #12是上 touch_down = TouchPad(Pin(13)) #13是下 num = 1 last_num = 1 last = 0 c_threshold = 250 count = 0 start = utime.ticks_ms() message = uart2.readline() #接收到的信息 message = process(message) print_text(["num"+str(num),str(0)+"MP"],50,10) to_bin(num,3) #多路选择器函数,二进制保持三位 port = 10000 #端口号 wlan = None #wlan listenSocket = None #套接字 PASSWORD = '12345678' WIFI_NAME = 'ESP-AP' #创建WiFi def createWifi(): global ap ap = network.WLAN(network.AP_IF) #创建接入点界面 ap.active(True) #激活界面 ap.config(essid=WIFI_NAME,authmode=4,password=PASSWORD) #设置接入点的ESSID,和WiFi 通道 while(ap.ifconfig()[0] == '0.0.0.0'): #等待连接 time.sleep(1) return True def accept_handler (sck:socket.socket): """ 当出现请求时,此函数会被回调并且接收请求 """ global conn conn, addr = sck.accept () # set a readable callback #Catch exceptions,stop program if interrupted accidentally in the 'try' try: createWifi() ip = ap.ifconfig()[0] #获取IP地址 print(ip) listenSocket = socket.socket (socket.AF_INET,socket.SOCK_STREAM) listenSocket.bind((ip, port)) listenSocket.setsockopt (socket.SOL_SOCKET,socket.SO_REUSEADDR, 1) # tcp quick re-use. listenSocket.setsockopt(socket.SOL_SOCKET, 20, accept_handler) listenSocket.listen (1) while True: touch_up_value = touch_up.read() touch_down_value = touch_down.read() ''' print("touch_up_value",touch_up_value) print("touch_down_value",touch_down_value) ''' if touch_up_value < c_threshold : #若读取的值大于阀值,则为没触摸 if touch_down_value > c_threshold and last <=0: #按上没按下 num = num + 1 last = last + 1 start = utime.ticks_ms() elif touch_down_value < c_threshold and last != -1: num= num -1 last = -1 start = utime.ticks_ms() end = utime.ticks_ms() if end - start > 500:#last每过一段时间要恢复为0 last = 0 if num>8: num = 1 if num < 1: num = 8 a=str(num)+"+"+str(message)+"\r\n" try: conn.send(a.encode('utf-8')) #esp32端发送数据 except: pass sleep(0.1) #延时0.1秒,实现每0.1秒判断一次触摸状态 try: command = conn.recv(1024).decode('utf-8') #esp32端接收数据 print("接收到",command) if "up" in command: num = num + 1 elif "down" in command: num = num - 1 except: pass print("传感器编号",num) to_bin(num,3) message_before = uart2.readline() #接收到的信息 print("处理之前",message_before) message_before = process(message_before) if message_before: message = message_before count = 0 else: count += 1 if count == 11: #如果连续10次接收到的都是None,则message=0 count = 0 message = 0 print("处理之后",message) if num != last_num:#如果num编号变过,则message立刻为0 message = 0 last_num = num print_text(["num"+str(num),str(message)+"MP"],50,10) ''' while True: data = conn.recv(1024) #接收数据(1024字节大小) if(len(data) == 0): #判断客户端是否断开连接 print("close socket") conn.close() #关闭套接字 break print(data) ''' except: if(listenSocket): #判断套接字是否为空 listenSocket.close() #关闭套接字
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具