傳送端程式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import machine import network import espnow import time # 初始化 Wi-Fi 接口為 STA 模式 sta = network.WLAN(network.STA_IF) sta.active(True) # 初始化 ESP-NOW esp = espnow.ESPNow() esp.active(True) # 添加另一顆晶片的 MAC 地址 peer_mac = b'\xb0\xa7\x32\xc0\xc6\xbc' # 另一顆晶片的 MAC 地址 esp.add_peer(peer_mac) # 設定 GPIO0 為按鈕 button = machine.Pin(0, machine.Pin.IN, machine.Pin.PULL_UP) while True: if button.value() == 0: # 檢測按鈕是否按下 print("Button pressed, sending message...") esp.send(peer_mac, b"Button pressed!") time.sleep(0.5) # 避免反彈,稍作延遲 |
接收端程式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import machine import network import espnow import time # 初始化 Wi-Fi 接口為 STA 模式 sta = network.WLAN(network.STA_IF) sta.active(True) # 初始化 ESP-NOW esp = espnow.ESPNow() esp.active(True) # 設定 GPIO2 為 LED led = machine.Pin(2, machine.Pin.OUT) led.off() # 初始狀態關閉 LED def on_recv(peer, msg): if msg: print("Received message:", msg) led.on() # 點亮 LED time.sleep(1) # 點亮 1 秒 led.off() # 關閉 LED # 保持程式運行 while True: # 接收訊息 if on_recv(*esp.recv()): break # 如果接收到 'end' 訊息,結束循環 pass |
執行結果:
如最上面的影片
傳送端終端機的資訊:
MPY: soft reboot
Button pressed, sending message...
Button pressed, sending message...
Button pressed, sending message...
接收端終端機的資訊:
Received message: b'Button pressed!'
Received message: b'Button pressed!'
Received message: b'Button pressed!'
沒有留言:
張貼留言