Advanced RF24 API¶
-
RF24.resend(send_only: bool =
False)[source]¶ Manually re-send the first-out payload from TX FIFO buffers.
This function is meant to be used for payloads that failed to transmit using the
send()function. If a payload failed to transmit using thewrite()function, just callclear_status_flags()and re-start the pulse on the nRF24L01’s CE pin.- Returns:
Data returned from this function follows the same pattern that
send()returns with the added condition that this function will returnFalseif the TX FIFO buffer is empty.- Parameters:
- send_only: bool =
False¶ This parameter only applies when the
ackattribute is set toTrue. Pass this parameter asTrueif the RX FIFO is not to be manipulated. Many other libraries’ behave as though this parameter isTrue(e.g. The popular TMRh20 Arduino RF24 library). This parameter defaults toFalse. If this parameter is set toTrue, then useread()to get the ACK payload (if there is any) from the RX FIFO. Remember that the RX FIFO can only hold up to 3 payloads at once.
- send_only: bool =
Note
The nRF24L01 normally removes a payload from the TX FIFO buffer after successful transmission, but not when this function is called. The payload (successfully transmitted or not) will remain in the TX FIFO buffer until
flush_tx()is called to remove them. Alternatively, using this function also allows the failed payload to be over-written by usingsend()orwrite()to load a new payload into the TX FIFO buffer.
-
RF24.write(buf: bytes | bytearray, ask_no_ack: bool =
False, write_only: bool =False) bool[source]¶ This non-blocking and helper function to
send()can only handle one payload at a time.This function isn’t completely non-blocking as we still need to wait for the necessary SPI transactions to complete. Example usage of this function can be seen in the IRQ pin example and in the Stream example’s “master_fifo()” function
- Returns:
Trueif the payload was added to the TX FIFO buffer.Falseif the TX FIFO buffer is already full, and no payload could be added to it.- Parameters:
- buf: bytes | bytearray¶
The payload to transmit. This bytearray must have a length greater than 0 and less than 32 bytes, otherwise a
ValueErrorexception is thrown when thedynamic_payloadsattribute is enabled.If the
dynamic_payloadsattribute is disabled for data pipe 0 and this bytearray’s length is less than thepayload_lengthattribute for data pipe 0, then this bytearray is padded with zeros until its length is equal to thepayload_lengthattribute for data pipe 0.If the
dynamic_payloadsattribute is disabled for data pipe 0 and this bytearray’s length is greater thanpayload_lengthattribute for data pipe 0, then this bytearray’s length is truncated to equal thepayload_lengthattribute for data pipe 0.
- ask_no_ack: bool =
False¶ Pass this parameter as
Trueto tell the nRF24L01 not to wait for an acknowledgment from the receiving nRF24L01. This parameter directly controls aNO_ACKflag in the transmission’s Packet Control Field (9 bits of information about the payload). Therefore, it takes advantage of an nRF24L01 feature specific to individual payloads, and its value is not saved anywhere. You do not need to specify this for every payload if theauto_ackattribute is disabled, however setting this parameter toTruewill work despite theauto_ackattribute’s setting.Important
If the
allow_ask_no_ackattribute is disabled (set toFalse), then this parameter will have no affect at all. By default theallow_ask_no_ackattribute is enabled.Note
Each transmission is in the form of a packet. This packet contains sections of data around and including the payload. See Chapter 7.3 in the nRF24L01 Specifications Sheet for more details.
- write_only: bool =
False¶ This function will not manipulate the nRF24L01’s CE pin if this parameter is
True. The default value ofFalsewill ensure that the CE pin is HIGH upon exiting this function. This function does not set the CE pin LOW at any time. Use this parameter asTrueto fill the TX FIFO buffer before beginning transmissions.Note
The nRF24L01 doesn’t initiate sending until a mandatory minimum 10 µs pulse on the CE pin is achieved. If the
write_onlyparameter isFalse, then that pulse is initiated before this function exits. However, we have left that 10 µs wait time to be managed by the MCU in cases of asynchronous application, or it is managed by usingsend()instead of this function. According to the Specification sheet, if the CE pin remains HIGH for longer than 10 µs, then the nRF24L01 will continue to transmit all payloads found in the TX FIFO buffer.
Warning
A note paraphrased from the nRF24L01+ Specifications Sheet:
It is important to NEVER to keep the nRF24L01+ in TX mode for more than 4 ms at a time. If the [
auto_ackattribute is] enabled, nRF24L01+ is never in TX mode longer than 4 ms.Tip
Use this function at your own risk. Because of the underlying “Enhanced ShockBurst Protocol”, disobeying the 4 ms rule is easily avoided if the
auto_ackattribute is greater than0. Alternatively, you MUST use nRF24L01’s IRQ pin and/or user-defined timer(s) to AVOID breaking the 4 ms rule. If the nRF24L01+ Specifications Sheet explicitly states this, we have to assume radio damage or misbehavior as a result of disobeying the 4 ms rule. See also table 18 in the nRF24L01 specification sheet for calculating an adequate transmission timeout sentinel.Added in version 1.2.0: Added
write_onlyparameter
- RF24.load_ack(buf: bytes | bytearray, pipe_number: int) bool[source]¶
Load a payload into the TX FIFO for use on a specific data pipe.
This payload will then be appended to the automatic acknowledgment (ACK) packet that is sent when new data is received on the specified pipe. See
read()on how to fetch a received custom ACK payloads.- Parameters:
- buf: bytes | bytearray¶
This will be the data attached to an automatic ACK packet on the incoming transmission about the specified
pipe_numberparameter. This must have a length in range [1, 32] bytes, otherwise aValueErrorexception is thrown. Any ACK payloads will remain in the TX FIFO buffer until transmitted successfully orflush_tx()is called.- pipe_number: int¶
This will be the pipe number to use for deciding which transmissions get a response with the specified
bufparameter’s data. This number must be in range [0, 5], otherwise aIndexErrorexception is thrown.
- Returns:
Trueif payload was successfully loaded onto the TX FIFO buffer.Falseif it wasn’t because TX FIFO buffer is full.
Note
this function takes advantage of a special feature on the nRF24L01 and needs to be called for every time a customized ACK payload is to be used (not for every automatic ACK packet – this just appends a payload to the ACK packet). The
ack,auto_ack, anddynamic_payloadsattributes are also automatically enabled (with respect to data pipe 0) by this function when necessary.Tip
The ACK payload must be set prior to receiving a transmission. It is also worth noting that the nRF24L01 can hold up to 3 ACK payloads pending transmission. Using this function does not over-write existing ACK payloads pending; it only adds to the queue (TX FIFO buffer) if it can. Use
flush_tx()to discard unused ACK payloads when done listening.
- property RF24.power : bool¶
This
boolattribute controls the power state of the nRF24L01.This is exposed for convenience.
Falsebasically puts the nRF24L01 to sleep (AKA power down mode) with ultra-low current consumption. No transmissions are executed when sleeping, but the nRF24L01 can still be accessed through SPI. Upon instantiation, this driver class puts the nRF24L01 to sleep until the MCU invokes RX/TX modes. This driver class will only power down the nRF24L01 after exiting aThe with statementblock.Truepowers up the nRF24L01. This is the first step towards entering RX/TX modes (see alsolistenattribute). Powering up is automatically handled by thelistenattribute as well as thesend()andwrite()functions.
Note
This attribute needs to be
Trueif you want to put radio on Standby-II (highest current consumption) or Standby-I (moderate current consumption) modes. The state of the CE pin determines which Standby mode is achieved. See Chapter 6.1.2-7 of the nRF24L01+ Specifications Sheet for more details.
- property RF24.address_length : int¶
This
intis the length (in bytes) used of RX/TX addresses.A valid input value must be an
intin range [3, 5]. Default is set to the nRF24L01’s maximum of 5. Any invalid input value results in a address length of 2 bytes.Changed in version 2.1.0: A
ValueErrorexception was thrown when an invalid input value was encountered.This was changed to allow setting the address length to 2 bytes (for possible reverse engineering protocol purposes).
-
RF24.address(index: int =
-1)[source]¶ Returns the current TX address or optionally RX address. (read-only)
This function returns the full content of the nRF24L01’s registers about RX/TX addresses despite what
address_lengthis set to.- Parameters:
- index: int =
-1¶ the number of the data pipe whose address is to be returned. A valid index ranges [0,5] for RX addresses or any negative number for the TX address. Otherwise an
IndexErroris thrown. This parameter defaults to-1.
- index: int =
Added in version 1.2.0.
- property RF24.last_tx_arc : int¶
Return the number of attempts made for last transmission (read-only).
This attribute resets to 0 at the beginning of every transmission in TX mode. Remember that the number of automatic retry attempts made for each transmission is configured with the
arcattribute or theset_auto_retries()function.
- property RF24.is_plus_variant : bool¶
A
booldescribing if the nRF24L01 is a plus variant or not (read-only).This information is determined upon instantiation.
Added in version 1.2.0.
Debugging Output¶
-
RF24.print_details(dump_pipes: bool =
False) None[source]¶ This debugging function outputs all details about the nRF24L01.
Some information may be irrelevant depending on nRF24L01’s state/condition.
- Prints:
Is a plus variantTrue means the transceiver is a nRF24L01+. False means the transceiver is a nRF24L01 (not a plus variant).ChannelThe current setting of thechannelattributeRF Data RateThe current setting of the RFdata_rateattribute.RF Power AmplifierThe current setting of thepa_levelattribute.CRC bytesThe current setting of thecrcattributeAddress lengthThe current setting of theaddress_lengthattributeTX Payload lengthsThe current setting of thepayload_lengthattribute for TX operations (concerning data pipe 0)Auto retry delayThe current setting of theardattributeAuto retry attemptsThe current setting of thearcattributeRe-use TX FIFOIs the first payload in the TX FIFO to be re-used for subsequent transmissions (this flag is set toTruewhen enteringresend()and reset toFalsewhenresend()exits)Packets lost on current channelTotal amount of packets lost (transmission failures). This only resets when thechannelis changed. This count will only go up to 15.Retry attempts made for last transmissionAmount of attempts to re-transmit during last transmission (resets per payload)IRQ on Data ReadyThe current setting of the IRQ pin on “Data Ready” eventIRQ on Data SentThe current setting of the IRQ pin on “Data Sent” eventIRQ on Data FailThe current setting of the IRQ pin on “Data Fail” eventData ReadyIs there RX data ready to be read? (state of theirq_drflag)Data SentHas the TX data been sent? (state of theirq_dsflag)Data FailedHas the maximum attempts to re-transmit been reached? (state of theirq_dfflag)TX FIFO fullIs the TX FIFO buffer full? (state of thetx_fullflag)TX FIFO emptyIs the TX FIFO buffer empty?RX FIFO fullIs the RX FIFO buffer full?RX FIFO emptyIs the RX FIFO buffer empty?Custom ACK payloadIs the nRF24L01 setup to use an extra (user defined) payload attached to the acknowledgment packet? (state of theackattribute)Ask no ACKThe current setting of theallow_ask_no_ackattribute.Automatic AcknowledgmentThe status of theauto_ackfeature. If this value is a binary representation, then each bit represents the feature’s status for each pipe.Dynamic PayloadsThe status of thedynamic_payloadsfeature. If this value is a binary representation, then each bit represents the feature’s status for each pipe.Primary ModeThe current mode (RX or TX) of communication of the nRF24L01 device.Power ModeThe power state can be Off, Standby-I, Standby-II, or On.
- Parameters:
- dump_pipes: bool =
False¶ Trueappends the output and prints:the current address used for TX transmissions. This value is the entire content of the nRF24L01’s register about the TX address (despite what
address_lengthis set to).Pipe [#] ([open/closed]) bound: [address]where#represent the pipe number, theopen/closedstatus is relative to the pipe’s RX status, andaddressis the full value stored in the nRF24L01’s RX address registers (despite whataddress_lengthis set to).if the pipe is open, then the output also prints
expecting [X] byte static payloadswhereXis thepayload_length(in bytes) the pipe is setup to receive whendynamic_payloadsis disabled for that pipe.
Set this parameter to
False(it default value) to skips this extra information.
- dump_pipes: bool =
Changed in version v2.1.0: Changed the default value for the
dump_pipesparameter toTrue
- RF24.print_pipes() None[source]¶
Prints all information specific to pipe’s addresses, RX state, & expected static payload sizes (if configured to use static payloads).
This method is called from
print_details()if thedump_pipesparameter is set toTrue.Changed in version v2.1.0: Changed this method’s name from the private method
_dump_pipes()to a public methodprint_pipes().
-
circuitpython_nrf24l01.rf24.address_repr(buf: bytes | bytearray, reverse: bool =
True, delimit: str ='') str[source]¶ Convert a buffer into a hexlified string.
This method is primarily used in
print_pipes()to display how the address is used by the radio.>>> from circuitpython_nrf24l01.rf24 import address_repr >>> address_repr(b"1Node") '65646F4E31'- Parameters:
- buf: bytes | bytearray¶
The buffer of bytes to convert into a hexlified string.
- reverse: bool =
True¶ A
boolto control the resulting endianness.Trueoutputs the result as big endian.Falseoutputs the result as little endian. This parameter defaults toTruesincebytearrayandbytesobjects are stored in big endian but written in little endian.- delimit: str =
''¶ A
chrorstrto use as a delimiter between bytes. Defaults to an empty string.
- Returns:
A string of hexadecimal characters in big endian form of the specified
bufparameter.
Changed in version 2.1.0: Added parameters
reverseanddelimitThis function proved vital to debugging and developing
RF24NetworkHeader&RF24NetworkFrame.
Status Byte¶
- property RF24.tx_full : bool¶
An
boolto represent if the TX FIFO is full. (read-only)Calling this does not execute an SPI transaction. It only exposes that latest data contained in the STATUS byte that’s always returned from any other SPI transactions. Use the
update()function to manually refresh this data when needed (especially after callingflush_tx()).
- property RF24.irq_dr : bool¶
A
boolthat represents the “Data Ready” interrupted flag. (read-only)- Returns:
Important
It is recommended that this flag is only used when the IRQ pin is active. To determine if there is a payload in the RX FIFO, use
fifo(),any(), orpipe. Notice that callingread()also resets this status flag.Pass
data_recvparameter asTruetoclear_status_flags()and reset this. As this is a virtual representation of the interrupt event, this attribute will always be updated despite what the actual IRQ pin is configured to do about this event.Calling this does not execute an SPI transaction. It only exposes that latest data contained in the STATUS byte that’s always returned from any other SPI transactions. Use the
update()function to manually refresh this data when needed (especially after callingclear_status_flags()).
- property RF24.irq_df : bool¶
A
boolthat represents the “Data Failed” interrupted flag. (read-only)- Returns:
Pass
data_failparameter asTruetoclear_status_flags()and reset this. As this is a virtual representation of the interrupt event, this attribute will always be updated despite what the actual IRQ pin is configured to do about this event.Calling this does not execute an SPI transaction. It only exposes that latest data contained in the STATUS byte that’s always returned from any other SPI transactions. Use the
update()function to manually refresh this data when needed (especially after callingclear_status_flags()).
- property RF24.irq_ds : bool¶
A
boolthat represents the “Data Sent” interrupted flag. (read-only)- Returns:
Pass
data_sentparameter asTruetoclear_status_flags()and reset this. As this is a virtual representation of the interrupt event, this attribute will always be updated despite what the actual IRQ pin is configured to do about this event.Calling this does not execute an SPI transaction. It only exposes that latest data contained in the STATUS byte that’s always returned from any other SPI transactions. Use the
update()function to manually refresh this data when needed (especially after callingclear_status_flags()).
- RF24.update() True[source]¶
This function gets an updated status byte over SPI.
Refreshing the status byte is vital to checking status of the interrupt flags, RX pipe number related to current RX payload, and if the TX FIFO buffer is full. This function returns nothing, but internally updates the
irq_dr,irq_ds,irq_df,pipe, andtx_fullattributes. Internally this is a helper function toavailable(),send(), andresend()functions.- Returns:
Truefor every call. This value is meant to allow this function to be used inThe if statementorThe while statementin conjunction with attributes related to the refreshed status byte.
Changed in version 1.2.3: Arbitrarily returns
True.
- property RF24.pipe : int | None¶
The number of the data pipe that received the next available payload in the RX FIFO. (read only)
Changed in version 1.2.0: Changed from method to property
In previous versions of this library, this attribute was a read-only function (
pipe()).Calling this does not execute an SPI transaction. It only exposes that latest data contained in the STATUS byte that’s always returned from any other SPI transactions. Use the
update()function to manually refresh this data when needed (especially after callingflush_rx()).
-
RF24.clear_status_flags(data_recv: bool =
True, data_sent: bool =True, data_fail: bool =True)[source]¶ This clears the interrupt flags in the status register.
Internally, this is automatically called by
send(),write(),read().- Parameters:
Note
Clearing the
data_failflag is necessary for continued transmissions from the nRF24L01 (locks the TX FIFO buffer whenirq_dfisTrue) despite whether or not the MCU is taking advantage of the interrupt (IRQ) pin. Call this function only when there is an antiquated status flag (after you’ve dealt with the specific payload related to the status flags that were set), otherwise it can cause payloads to be ignored and occupy the RX/TX FIFO buffers. See Appendix A of the nRF24L01+ Specifications Sheet for an outline of proper behavior.
FIFO management¶
- RF24.flush_rx()[source]¶
Flush all 3 levels of the RX FIFO.
Note
The nRF24L01 RX FIFO is 3 level stack that holds payload data. This means that there can be up to 3 received payloads (each of a maximum length equal to 32 bytes) waiting to be read (and removed from the stack) by
read(). This function clears all 3 levels.
- RF24.flush_tx()[source]¶
Flush all 3 levels of the TX FIFO.
Note
The nRF24L01 TX FIFO is 3 level stack that holds payload data. This means that there can be up to 3 payloads (each of a maximum length equal to 32 bytes) waiting to be transmit by
send(),resend()orwrite(). This function clears all 3 levels. It is worth noting that the payload data is only removed from the TX FIFO stack upon successful transmission (see alsoresend()as the handling of failed transmissions can be altered).
-
circuitpython_nrf24l01.rf24.FIFO_EMPTY =
1¶ A constant to represent a FIFO state when it is empty.
-
circuitpython_nrf24l01.rf24.FIFO_FULL =
2¶ A constant to represent a FIFO state when it neither full nor empty (contains 1 or 2 payloads).
-
circuitpython_nrf24l01.rf24.FIFO_OCCUPIED =
0¶ A constant to represent a FIFO state when it is full.
-
RF24.fifo(about_tx: bool =
False, check_empty: bool | None =None) int | bool[source]¶ This provides the status of the TX/RX FIFO buffers. (read-only)
- Parameters:
- Throws:
This will raise a
RuntimeErrorwhen the data over the MISO line is corrupted.- Returns:
A
boolanswer to the question:”Is the [TX/RX](
about_tx) FIFO buffer [empty/full](check_empty)?If the
check_emptyparameter is not specified: anintin range [0, 2] for which:FIFO_EMPTYmeans the specified FIFO buffer is emptyFIFO_FULLmeans the specified FIFO buffer is fullFIFO_OCCUPIEDmeans the specified FIFO buffer is neither full nor empty (1 or 2 payloads)
Changed in version 2.1.6: Throws a
RuntimeErrorwhen binary corruption is observed on the SPI bus’ MISO line.
Ambiguous Signal Detection¶
- property RF24.rpd : bool¶
Returns
Trueif signal was detected orFalseif not. (read-only)The RPD (Received Power Detector) flag is triggered in the following cases:
During RX mode (when
listenisTrue) and an arbitrary RF transmission with a gain above -64 dBm threshold is/was present.When a packet is received (instigated by the nRF24L01 used to detect/”listen” for incoming packets).
Note
See also section 6.4 of the Specification Sheet concerning the RPD flag. Ambient temperature affects the -64 dBm threshold. The latching of this flag happens differently under certain conditions.
Added in version 1.2.0.
- RF24.start_carrier_wave()[source]¶
Starts a continuous carrier wave test.
This is a basic test of the nRF24L01’s TX output. It is a commonly required test for telecommunication regulations. Calling this function may introduce interference with other transceivers that use frequencies in range [2.4, 2.525] GHz. To verify that this test is working properly, use the following code on a separate nRF24L01 transceiver:
# declare objects for SPI bus and CSN pin and CE pin nrf = RF24(spi, csn, ce) # set nrf.pa_level, nrf.channel, & nrf.data_rate values to # match the corresponding attributes on the device that is # transmitting the carrier wave nrf.listen = True if nrf.rpd: print("carrier wave detected")The
pa_level,channel&data_rateattributes are vital factors to the success of this test. Be sure these attributes are set to the desired test conditions before calling this function. See also therpdattribute.Note
To preserve backward compatibility with non-plus variants of the nRF24L01, this function will also change certain settings if
is_plus_variantisFalse. These settings changes includedisabling
crcdisabling
auto_ackchanging the TX address to
b"\xFF\xFF\xFF\xFF\xFF"loading a 32-byte payload (each byte is
0xFF) into the TX FIFO buffer
Finally the radio continuously behaves like using
resend()to establish the constant carrier wave. Ifis_plus_variantisTrue, then none of these changes are needed nor applied.Added in version 1.2.0.
- RF24.stop_carrier_wave()[source]¶
Stops a continuous carrier wave test.
See
start_carrier_wave()for more details.Note
Calling this function puts the nRF24L01 to sleep (AKA power down mode).
Hint
If the radio is a non-plus variant (
is_plus_variantreturnsFalse), then useThe with statementto re-establish the previous settings:# let `nrf` be the instantiated RF24 object with nrf: pass # settings are now restoredAdded in version 1.2.0.