Written by 2bndy5 in 2020
This is a simple example of using the RF24 class on a Raspberry Pi for streaming multiple payloads.
Remember to install the Python wrapper, then navigate to the "RF24/examples_linux" folder.
To run this example, enter
python3 streaming_data.py
and follow the prompts.
- Note
- this example requires python v3.7 or newer because it measures transmission time with
time.monotonic_ns()
.
2A simple example of streaming data from 1 nRF24L01 transceiver to another.
4This example was written to be used on 2 devices acting as 'nodes'.
9from RF24
import RF24, RF24_PA_LOW
12parser = argparse.ArgumentParser(
13 description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
20 help=
"the identifying radio number (or node ID number)",
27 help=
"'1' specifies the TX role. '0' specifies the RX role.",
39radio =
RF24(CE_PIN, CSN_PIN)
51def make_buffer(buf_iter: int) -> bytes:
52 """Returns a dynamically created payloads
54 :param int buf_iter: The position of the payload in the data stream
60 buff = bytes([buf_iter + (65
if 0 <= buf_iter < 26
else 71)])
61 for j
in range(SIZE - 1):
62 char = bool(j >= (SIZE - 1) / 2 + abs((SIZE - 1) / 2 - buf_iter))
63 char |= bool(j < (SIZE - 1) / 2 - abs((SIZE - 1) / 2 - buf_iter))
64 buff += bytes([char + 48])
68def master(count: int = 1):
69 """Uses all 3 levels of the TX FIFO to send a stream of data
71 :param int count: how many times to transmit the stream of data.
76 start_timer = time.monotonic_ns()
77 for multiplier
in range(count):
79 while buf_iter < SIZE:
80 buffer = make_buffer(buf_iter)
82 if not radio.writeFast(buffer):
84 if failures > 99
and buf_iter < 7
and multiplier < 2:
86 print(
"Too many failures detected. Aborting at payload ", buffer[0])
92 end_timer = time.monotonic_ns()
94 f
"Time to transmit data = {(end_timer - start_timer) / 1000} us.",
95 f
"Detected {failures} failures."
99def slave(timeout: int = 6):
100 """Listen for any payloads and print them out (suffixed with received
103 :param int timeout: The number of seconds to wait (with no transmission)
104 until exiting function.
106 radio.startListening()
108 start_timer = time.monotonic()
109 while (time.monotonic() - start_timer) < timeout:
110 if radio.available():
113 receive_payload = radio.read(radio.payloadSize)
114 print(
"Received:", receive_payload,
"-", count)
115 start_timer = time.monotonic()
117 print(
"Nothing received in", timeout,
"seconds. Leaving RX role")
119 radio.stopListening()
123def set_role() -> bool:
124 """Set the role using stdin stream. Role args can be specified using space
125 delimiters (e.g. 'R 10' calls `slave(10)` &
'T 3' calls `master(3)`)
128 -
True when role
is complete & app should
continue running.
129 -
False when app should exit
133 "*** Enter 'R' for receiver role.\n"
134 "*** Enter 'T' for transmitter role.\n"
135 "*** Enter 'Q' to quit example.\n"
139 user_input = user_input.split()
140 if user_input[0].upper().startswith(
"R"):
141 if len(user_input) > 1:
142 slave(int(user_input[1]))
146 if user_input[0].upper().startswith(
"T"):
147 if len(user_input) > 1:
148 master(int(user_input[1]))
152 if user_input[0].upper().startswith(
"Q"):
155 print(user_input[0],
"is an unrecognized input. Please try again.")
159if __name__ ==
"__main__":
161 args = parser.parse_args()
164 if not radio.begin():
165 raise RuntimeError(
"radio hardware is not responding")
169 address = [b
"1Node", b
"2Node"]
178 radio_number = args.node
179 if args.node
is None:
181 int(input(
"Which radio is this? Enter '0' or '1'. Defaults to '0' ")
or 0)
186 radio.setPALevel(RF24_PA_LOW)
189 radio.openWritingPipe(address[radio_number])
192 radio.openReadingPipe(1, address[
not radio_number])
196 radio.payloadSize = SIZE
205 if args.role
is None:
214 except KeyboardInterrupt:
215 print(
" Keyboard Interrupt detected. Powering down radio.")
Driver class for nRF24L01(+) 2.4GHz Wireless Transceiver.