/
main.py
89 lines (77 loc) · 2.46 KB
/
main.py
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# demo.py
# Kevin McAleer
# test the nRF24L01 modules to send and receive data
# Watch this video for more information about that library https://www.youtube.com/watch?v=aP8rSN-1eT0
from nrf24l01 import NRF24L01
from machine import SPI, Pin
from time import sleep
import struct
csn = Pin(14, mode=Pin.OUT, value=1) # Chip Select Not
ce = Pin(17, mode=Pin.OUT, value=0) # Chip Enable
led = Pin(25, Pin.OUT) # Onboard LED
payload_size = 20
# Define the channel or 'pipes' the radios use.
# switch round the pipes depending if this is a sender or receiver pico
# role = "send"
role = "receive"
if role == "send":
send_pipe = b"\xe1\xf0\xf0\xf0\xf0"
receive_pipe = b"\xd2\xf0\xf0\xf0\xf0"
else:
send_pipe = b"\xd2\xf0\xf0\xf0\xf0"
receive_pipe = b"\xe1\xf0\xf0\xf0\xf0"
def setup():
print("Initialising the nRF24L0+ Module")
nrf = NRF24L01(SPI(0), csn, ce, payload_size=payload_size)
nrf.open_tx_pipe(send_pipe)
nrf.open_rx_pipe(1, receive_pipe)
nrf.start_listening()
return nrf
def flash_led(times:int=None):
''' Flashed the built in LED the number of times defined in the times parameter '''
for _ in range(times):
led.value(1)
sleep(0.01)
led.value(0)
sleep(0.01)
def send(nrf, msg):
print("sending message.", msg)
nrf.stop_listening()
for n in range(len(msg)):
try:
encoded_string = msg[n].encode()
byte_array = bytearray(encoded_string)
buf = struct.pack("s", byte_array)
nrf.send(buf)
# print(role,"message",msg[n],"sent")
flash_led(1)
except OSError:
print(role,"Sorry message not sent")
nrf.send("\n")
nrf.start_listening()
# main code loop
flash_led(1)
nrf = setup()
nrf.start_listening()
msg_string = ""
while True:
msg = ""
if role == "send":
send(nrf, "Yello world")
send(nrf, "Test")
else:
# Check for Messages
if nrf.any():
package = nrf.recv()
message = struct.unpack("s",package)
msg = message[0].decode()
flash_led(1)
# Check for the new line character
if (msg == "\n") and (len(msg_string) <= 20):
print("full message",msg_string, msg)
msg_string = ""
else:
if len(msg_string) <= 20:
msg_string = msg_string + msg
else:
msg_string = ""