2025年1月6日 星期一

使用兩顆esp32實現ESP-NOW 1對1的雙向的通訊程式



兩顆程式一樣,只是MAC 位址不同,需注意。 
可以接收和傳送的程式:

 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
31
32
33
34
35
36
37
38
39
40
41
42
43
import network
import espnow

# 初始化 Wi-Fi 接口為 STA 模式
sta = network.WLAN(network.STA_IF)
sta.active(True)

# 獲取並顯示 ESP32 的 MAC 地址
mac_address = sta.config('mac')
mac_address_readable = ':'.join(['{:02x}'.format(b) for b in mac_address])
print("MAC Address:", mac_address_readable)

# 初始化 ESP-NOW
esp = espnow.ESPNow()
esp.active(True)

# 添加另一顆晶片的 MAC 地址
peer_mac = b'\xb0\xa7\x32\xc0\xc6\xbc'  # 另一顆晶片的 MAC 地址
esp.add_peer(peer_mac)

# 設置一個函數來處理接收到的訊息
def on_recv(peer, msg):
    if msg:
        print("Received from {}: {}".format(peer, msg))
        if msg == b'end':
            print("Ending communication")
            return True
    return False

# 主要的循環來發送和接收訊息
while True:
    # 傳送訊息
    message = b"Hello from ESP-NOW!"
    esp.send(peer_mac, message)
    print("Message sent:", message)
    
    # 接收訊息
    if on_recv(*esp.recv()):
        break  # 如果接收到 'end' 訊息,結束循環

    # 稍作延遲以避免過多的傳送
    import time
    time.sleep(1)

執行結果:
MPY: soft reboot
MAC Address: b0:a7:32:c0:c6:70
Message sent: b'Hello from ESP-NOW!'
Received from b'\xb0\xa72\xc0\xc6\xbc': b'Hello from ESP-NOW!'
Message sent: b'Hello from ESP-NOW!'
Received from b'\xb0\xa72\xc0\xc6\xbc': b'Hello from ESP-NOW!'
Message sent: b'Hello from ESP-NOW!'
Received from b'\xb0\xa72\xc0\xc6\xbc': b'Hello from ESP-NOW!'
Message sent: b'Hello from ESP-NOW!'
Received from b'\xb0\xa72\xc0\xc6\xbc': b'Hello from ESP-NOW!'
Message sent: b'Hello from ESP-NOW!'
Received from b'\xb0\xa72\xc0\xc6\xbc': b'Hello from ESP-NOW!'
Message sent: b'Hello from ESP-NOW!'
Received from b'\xb0\xa72\xc0\xc6\xbc': b'Hello from ESP-NOW!'
Message sent: b'Hello from ESP-NOW!'
Received from b'\xb0\xa72\xc0\xc6\xbc': b'Hello from ESP-NOW!'

沒有留言:

張貼留言