Written by 2bndy5 in 2020
This is a simple example of using the RF24 class on a Raspberry Pi to transmit and respond with acknowledgment (ACK) transmissions. Notice that the auto-ack feature is enabled, but this example doesn't use automatic ACK payloads because automatic ACK payloads' data will always be outdated by 1 transmission. Instead, this example uses a call and response paradigm.
Remember to install the Python wrapper, then navigate to the "RF24/examples_linux" folder.
To run this example, enter
python3 manual_acknowledgements.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 sending data from 1 nRF24L01 transceiver to another
3with manually transmitted (non-automatic) Acknowledgement (ACK) payloads.
4This example still uses ACK packets, but they have no payloads. Instead the
5acknowledging response is sent with `write()`. This tactic allows for more
6updated acknowledgement payload data, where actual ACK payloads' data are
7outdated by 1 transmission because they have to loaded before receiving a
10This example was written to be used on 2 devices acting as 'nodes'.
12See documentation at https://nRF24.github.io/RF24
16from RF24
import RF24, RF24_PA_LOW, RF24_DRIVER
28if RF24_DRIVER ==
"MRAA":
30elif RF24_DRIVER ==
"wiringPi":
34radio =
RF24(CE_PIN, CSN_PIN)
38 raise RuntimeError(
"radio hardware is not responding")
42address = [b
"1Node", b
"2Node"]
50 int(input(
"Which radio is this? Enter '0' or '1'. Defaults to '0' ")
or 0)
55radio.setPALevel(RF24_PA_LOW)
58radio.openWritingPipe(address[radio_number])
61radio.openReadingPipe(1, address[
not radio_number])
80 """Transmits a message and an incrementing integer every second, then
81 wait for a response for up to 200 ms.
88 buffer = b
"Hello \x00" + bytes(counter)
89 start_timer = time.monotonic_ns()
90 result = radio.write(buffer)
93 print(
"Transmission failed or timed out")
95 radio.startListening()
96 timeout = time.monotonic() * 1000 + 200
98 while not radio.available()
and time.monotonic() * 1000 < timeout:
100 radio.stopListening()
101 end_timer = time.monotonic_ns()
102 decoded = buffer[:6].decode(
"utf-8")
104 f
"Transmission successful. Sent: {decoded}{counter[0]}.",
107 has_payload, pipe_number = radio.available_pipe()
110 received = radio.read(radio.payloadSize)
112 counter[0] = received[7:8][0]
113 decoded = bytes(received[:6]).decode(
"utf-8")
115 f
"Received {radio.payloadSize} bytes",
116 f
"on pipe {pipe_number}: {decoded}{counter[0]}.",
117 f
"Round-trip delay: {(end_timer - start_timer) / 1000} us.",
120 print(
"No response received.")
122 print(failures,
"failures detected. Leaving TX role.")
125def slave(timeout: int = 6):
126 """Listen for any payloads and print the transaction
128 :param int timeout: The number of seconds to wait (with no transmission)
129 until exiting function.
131 radio.startListening()
133 start_timer = time.monotonic()
134 while (time.monotonic() - start_timer) < timeout:
136 has_payload, pipe_number = radio.available_pipe()
138 received = radio.read(radio.payloadSize)
141 counter[0] = received[7:8][0] + 1
if received[7:8][0] < 255
else 0
144 buffer = b
"World \x00" + bytes(counter)
145 radio.stopListening()
146 radio.writeFast(buffer)
148 result = radio.txStandBy(150)
150 radio.startListening()
152 decoded = bytes(received[:6]).decode(
"utf-8")
154 f
"Received {radio.payloadSize} bytes"
155 f
"on pipe {pipe_number}: {decoded}{received[7:8][0]}.",
160 decoded = buffer[:6].decode(
"utf-8")
161 print(f
"Sent: {decoded}{counter[0]}")
163 print(
"Response failed or timed out")
164 start_timer = time.monotonic()
166 print(
"Nothing received in", timeout,
"seconds. Leaving RX role")
168 radio.stopListening()
171def set_role() -> bool:
172 """Set the role using stdin stream. Timeout arg for slave() can be
173 specified using a space delimiter (e.g. 'R 10' calls `slave(10)`)
176 - True when role is complete & app should continue running.
177 - False when app should exit
181 "*** Enter 'R' for receiver role.\n"
182 "*** Enter 'T' for transmitter role.\n"
183 "*** Enter 'Q' to quit example.\n"
187 user_input = user_input.split()
188 if user_input[0].upper().startswith(
"R"):
189 if len(user_input) > 1:
190 slave(int(user_input[1]))
194 if user_input[0].upper().startswith(
"T"):
197 if user_input[0].upper().startswith(
"Q"):
200 print(user_input[0],
"is an unrecognized input. Please try again.")
204if __name__ ==
"__main__":
208 except KeyboardInterrupt:
209 print(
" Keyboard Interrupt detected. Powering down radio.")
212 print(
" Run slave() on receiver\n Run master() on transmitter")
Driver class for nRF24L01(+) 2.4GHz Wireless Transceiver.