NRF24.h 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. // NRF24.h
  2. // Author: Mike McCauley
  3. // Copyright (C) 2012 Mike McCauley
  4. // $Id: NRF24.h,v 1.2 2014/05/20 06:00:55 mikem Exp mikem $
  5. //
  6. /// \mainpage NRF24 library for Arduino
  7. ///
  8. /// This NRF24 library has now been superceded by the RadioHead
  9. /// library http://www.airspayce.com/mikem/arduino/RadioHead
  10. /// RadioHead and its RH_NRF24 driver provides all the features supported by NRF24, and much more
  11. /// besides, including Reliable Datagrams, Addressing, Routing and Meshes. All the platforms that
  12. /// NRF24 supported are also supported by RadioHead.
  13. ///
  14. /// This library will no longer be maintained or updated, but we will continue to publish
  15. /// it for the benefit of the the community, and you may continue to use it within the terms of
  16. /// the license. Nevertheless we recommend upgrading to RadioHead where
  17. /// possible.
  18. ///
  19. /// This is the Arduino NRF24 library.
  20. /// It provides an object-oriented interface for sending and receiving data messages with Nordic nRF24L01
  21. /// based radio modules, such as the sparkfun WRL-00691 http://www.sparkfun.com/products/691
  22. ///
  23. /// The nRF24L01 (http://www.sparkfun.com/datasheets/Wireless/Nordic/nRF24L01P_Product_Specification_1_0.pdf)
  24. /// is a low-cost 2.4GHz ISM transceiver module. It supports a number of channel frequencies in the 2.4GHz band
  25. /// and a range of data rates.
  26. ///
  27. /// This library provides functions for sending and receiving messages of up to 32 octets on any
  28. /// frequency supported by the nRF24L01, at a selected data rate.
  29. ///
  30. /// Up to 2 nRF24L01 modules can be connected to an Arduino, permitting the construction of translators
  31. /// and frequency changers, etc.
  32. ///
  33. /// This library provides classes for
  34. /// - NRF24: addressed, reliable, retransmitted, acknowledged messages (using nrf24 Enhanced Shockburst)
  35. ///
  36. /// Example Arduino programs are included to show the main modes of use.
  37. ///
  38. /// The version of the package that this documentation refers to can be downloaded
  39. /// from http://www.airspayce.com/mikem/arduino/NRF24/NRF24-1.14.zip
  40. /// You can find the latest version at http://www.airspayce.com/mikem/arduino/NRF24
  41. ///
  42. /// You can also find online help and disussion at
  43. /// http://groups.google.com/group/NRF24-arduino
  44. /// Please use that group for all questions and discussions on this topic.
  45. /// Do not contact the author directly, unless it is to discuss commercial licensing.
  46. /// Before asking a question or reporting a bug, please read http://www.catb.org/esr/faqs/smart-questions.html
  47. ///
  48. /// Tested on Arduino Diecimila, Duemilanove and Mega with arduino 1.0
  49. /// on OpenSuSE 12.1 with avr-libc-1.7.1-1.1, cross-avr-binutils-2.19.1-33.1
  50. /// and cross-avr-gcc-4.3.3_20100125-28.1, and with arduino-0021 on the same platforms
  51. ///
  52. /// \par Packet Format
  53. ///
  54. /// All messages sent and received by this NRF24 library must conform to this packet format, as specified by
  55. /// the nRF24L01 product specificaiton:
  56. ///
  57. /// - 1 octets PREAMBLE
  58. /// - 4 octets ADDRESS
  59. /// - 9 bits packet control field
  60. /// - 0 to 32 octets PAYLOAD
  61. /// - 2 octets CRC
  62. ///
  63. /// \par Connecting nRF24L01 to Arduino
  64. ///
  65. /// The physical connection between the nRF24L01 and the Arduino require 3.3V, the 3 x SPI pins (SCK, SDI, SDO),
  66. /// a Chip Enable pin and a Slave Select pin.
  67. /// If you are using the Sparkfun WRL-00691 module, it has a voltage regulator on board and
  68. /// can be run with 5V VCC
  69. /// The examples below assume the Sparkfun WRL-00691 module
  70. ///
  71. /// Connect the nRF24L01 to most Arduino's like this (Caution, Arduino Mega has different pins for SPI,
  72. /// see below),
  73. /// \code
  74. /// Arduino Sparkfun WRL-00691
  75. /// 3V3 or 5V----VCC (3.3V to 7V in)
  76. /// pin D8-----------CE (chip enable in)
  77. /// SS pin D10----------CSN (chip select in)
  78. /// SCK pin D13----------SCK (SPI clock in)
  79. /// MOSI pin D11----------SDI (SPI Data in)
  80. /// MISO pin D12----------SDO (SPI data out)
  81. /// IRQ (Interrupt output, not connected)
  82. /// GND----------GND (ground in)
  83. /// \endcode
  84. ///
  85. /// For an Arduino Leonardo (the SPI pins do not come out on the Digital pins as for normal Arduino, but only
  86. /// appear on the ICSP header)
  87. /// \code
  88. /// Leonardo Sparkfun WRL-00691
  89. /// 3V3 or 5V----VCC (3.3V to 7V in)
  90. /// pin D8-----------CE (chip enable in)
  91. /// SS pin D10----------CSN (chip select in)
  92. /// SCK ICSP pin 3----------SCK (SPI clock in)
  93. /// MOSI ICSP pin 4----------SDI (SPI Data in)
  94. /// MISO ICSP pin 1----------SDO (SPI data out)
  95. /// IRQ (Interrupt output, not connected)
  96. /// GND----------GND (ground in)
  97. /// \endcode
  98. /// and initialise the NRF24 object like this to explicitly set the SS pin
  99. /// NRF24 nrf24(8, 10);
  100. ///
  101. /// For an Arduino Mega:
  102. /// \code
  103. /// Mega Sparkfun WRL-00691
  104. /// 3V3 or 5V----VCC (3.3V to 7V in)
  105. /// pin D8-----------CE (chip enable in)
  106. /// SS pin D53----------CSN (chip select in)
  107. /// SCK pin D52----------SCK (SPI clock in)
  108. /// MOSI pin D51----------SDI (SPI Data in)
  109. /// MISO pin D50----------SDO (SPI data out)
  110. /// IRQ (Interrupt output, not connected)
  111. /// GND----------GND (ground in)
  112. /// \endcode
  113. /// and you can then use the default constructor NRF24().
  114. /// You can override the default settings for the CSN and CE pins
  115. /// in the NRF24() constructor if you wish to connect the slave select CSN to other than the normal one for your
  116. /// Arduino (D10 for Diecimila, Uno etc and D53 for Mega)
  117. ///
  118. /// Caution: on some Arduinos such as the Mega 2560, if you set the slave select pin to be other than the usual SS
  119. /// pin (D53 on Mega 2560), you may need to set the usual SS pin to be an output to force the Arduino into SPI
  120. /// master mode.
  121. ///
  122. /// Caution: this module has not been proved to work with Leonardo, at least without level
  123. /// shifters between the NRF24 and the Leonardo. Tests seem to indicate that such level shifters would be required
  124. /// with Leonardo to make it work.
  125. ///
  126. /// It is possible to have 2 radios conected to one arduino, provided each radio has its own
  127. /// CSN and CE line (SCK, SDI and SDO are common to both radios)
  128. ///
  129. /// \par Example programs
  130. ///
  131. /// The following example programs are provided:
  132. /// -nrf24_ping_client, nrf24_pin_server. This is a matched pair. The client sends (acknowledged)
  133. /// 4 byte timestamp to the server which replies (acknowledged).
  134. /// The client measures the round-trip time and prints it. Typical RTT is 1-2 msec.
  135. /// These are compatible radio wise with the ping_client and ping_server programs that come with the Mirf library
  136. /// though the electrical connections are different
  137. /// -nrf24_specan. Example sketch showing how to create a primitive spectrum analyser
  138. /// with the NRF24 class. The nRF24L01 received power detector is only one bit, but
  139. /// this will show which channels have more than -64dBm present.
  140. /// -nrf24_audio_tx, nrf24_audio_rx. This is a matched pair. The clinet sends a stream of audio samples measured
  141. /// from analog input 0 to the receiver, which reconstructs them on output D6. See comments in those files for
  142. /// electrical requirements. The pair demonstrates the use of NRF24 in NOACK modefor improved performance
  143. /// (but no reliability). Can achieve 6.4kHz sample rate. Dont expect good quality audio!
  144. ///
  145. /// \par Radio Performance
  146. ///
  147. /// The performance of this radio seems to be very good. I was able to build ping client/server
  148. /// that was able to achieve over 800 round trips per second
  149. /// (at 0dBm power, 2Mbps, channel 1, 4 byte payload each way, 1 checksum byte) when the radios were next to each other.
  150. /// This rate could still be achieved at 15m distance, but the orientation of the radios and
  151. /// obstructions became critical. The human body can easily block these signals.
  152. /// Best response was when the chip antennas were broadside to each other.
  153. ///
  154. /// It is possible to get even better streaming performance using NOACK mode (see the nrf24_audio_tx sample)
  155. /// at the cost of nop reliability.
  156. /// In NOACK mode, at 2Mbps, 32 byte payload, can get about 1900 packets per second: 60800 bytes of payload per second
  157. ///
  158. /// Frequency accuracy may be debatable. For nominal frequency of 2401.000 MHz (ie channel 1),
  159. /// my Yaesu VR-5000 receiver indicated the center frequency for my test radios
  160. /// was 2401.121 MHz. Its not clear to me if the Yaesu
  161. /// is the source of the error, but I tend to believe it, which would make the nRF24l01 frequency out by 121kHz.
  162. ///
  163. /// \par Radio operating strategy and defaults
  164. ///
  165. /// The radio is enabled all the time, and switched between TX and RX modes depending on
  166. /// whether there is any data to send. Sending data sets the radio to TX mode.
  167. /// After data is sent, the radion automatically returns to Standby II mode. Calling waitAvailable() or
  168. /// waitAvailableTimeout() starts the radio in RX mode.
  169. ///
  170. /// The radio is configured by default to Channel 2, 2Mbps, 0dBm power, 5 bytes address, payload width 1, CRC enabled
  171. /// 1 byte CRC, Auto-Ack mode. Enhanced shockburst is used.
  172. /// P1 is the receive pipe. P0 is set to the transmit address to enable autoack.
  173. ///
  174. /// \par Memory
  175. ///
  176. /// Memory usage of this program is minimal. The compiled ping client and server programs are about 4000 bytes.
  177. /// RAM requirements of the library are minimal.
  178. ///
  179. /// \par Installation
  180. ///
  181. /// Install in the usual way: unzip the distribution zip file to the libraries
  182. /// sub-folder of your sketchbook.
  183. ///
  184. /// This software is Copyright (C) 2012 Mike McCauley. Use is subject to license
  185. /// conditions. The main licensing options available are GPL V2 or Commercial:
  186. ///
  187. /// \par Donations
  188. ///
  189. /// This library is offered under a free GPL license for those who want to use it that way.
  190. /// We try hard to keep it up to date, fix bugs
  191. /// and to provide free support. If this library has helped you save time or money, please consider donating at
  192. /// http://www.airspayce.com or here:
  193. ///
  194. /// \htmlonly <form action="https://www.paypal.com/cgi-bin/webscr" method="post"><input type="hidden" name="cmd" value="_donations" /> <input type="hidden" name="business" value="mikem@airspayce.com" /> <input type="hidden" name="lc" value="AU" /> <input type="hidden" name="item_name" value="Airspayce" /> <input type="hidden" name="item_number" value="NRF24" /> <input type="hidden" name="currency_code" value="USD" /> <input type="hidden" name="bn" value="PP-DonationsBF:btn_donateCC_LG.gif:NonHosted" /> <input type="image" alt="PayPal — The safer, easier way to pay online." name="submit" src="https://www.paypalobjects.com/en_AU/i/btn/btn_donateCC_LG.gif" /> <img alt="" src="https://www.paypalobjects.com/en_AU/i/scr/pixel.gif" width="1" height="1" border="0" /></form> \endhtmlonly
  195. ///
  196. /// \par Open Source Licensing GPL V2
  197. ///
  198. /// This is the appropriate option if you want to share the source code of your
  199. /// application with everyone you distribute it to, and you also want to give them
  200. /// the right to share who uses it. If you wish to use this software under Open
  201. /// Source Licensing, you must contribute all your source code to the open source
  202. /// community in accordance with the GPL Version 2 when your application is
  203. /// distributed. See http://www.gnu.org/copyleft/gpl.html
  204. ///
  205. /// \par Commercial Licensing
  206. ///
  207. /// This is the appropriate option if you are creating proprietary applications
  208. /// and you are not prepared to distribute and share the source code of your
  209. /// application. Contact info@airspayce.com for details.
  210. ///
  211. /// \par Revision History
  212. ///
  213. /// \version 1.0 Initial release
  214. ///
  215. /// \version 1.1 Changed default value for slave slect pin in constructor to be SS, ie the normal one for
  216. /// the compiled Arduino (D10 for Diecimila, Uno etc and D53 for Mega). This is because some Arduinos such as Mega 2560
  217. /// reportedly use the type of the SS pin to determine whether to run in slave or master mode. Therfore it
  218. /// is preferred that the slave select pin actually be the normal SS pin.
  219. ///
  220. /// \version 1.2 Updated documentation about what happens during init, and that SPI is initialised to 8MHz
  221. /// (but can be set to other frequencies after calling init()
  222. /// \version 1.3 Fixed error in title of main page
  223. /// \version 1.4 Fixed typo in nrf24_test.pde, reported by TOM.
  224. /// \version 1.6 Fixed an error NRF24::setRF in setting data rate to 250kbps. Reported by Shiu Kumar.
  225. /// \version 1.7 Improvements to waitPacketSent() so if the chip is not in transmit mode, it wont wait forever.
  226. /// Improvements to isSending() so it returns false if the chip is not in transmit mode.
  227. /// \version 1.8 Fixed a conflict between 2 definitions of NRF24_TX_FULL. The one in 07 STATUS is changed to
  228. /// NRF24_STATUS_TX_FULL. Reported by Charles-Henri Hallard.
  229. /// Updated author and distribution location details to airspayce.com
  230. /// \version 1.9 Improvements to waitAvailableTimeout to make it robust on millis() rollover.
  231. /// \version 1.10 Testing with Leonardo and update documentation to reflect special electrical
  232. /// connection needs on Leonardo.
  233. /// \version 1.11 NRF24_COMMAND_W_ACK_PAYLOAD(c) is now a macro that takes a pipe number parameter.
  234. /// Added new function setRetry(), a convenience for setting ARD and ARC retry parameter.
  235. /// Can now customise the radio configuration byte with setConfiguration().
  236. /// Added new examples crazyflie and crazyflie_client that use the NRF24 library to
  237. /// communicate with Crazyflie quadcopters and transmitters.
  238. /// \version 1.12 NRF24::init, powerUpRx, powerUpTx will now fail if no device is connected;
  239. /// \version 1.13 Added End Of Life notice. This library will no longer be maintained
  240. /// and updated: use RadioHead instead.
  241. /// \version 1.14 Fixed problem that prevented 250kbps data rate working.
  242. ///
  243. /// \author Mike McCauley (mikem@airspayce.com) DO NOT CONTACT THE AUTHOR DIRECTLY: USE THE LISTS
  244. #ifndef NRF24_h
  245. #define NRF24_h
  246. #if ARDUINO >= 100
  247. #include <Arduino.h>
  248. #include "SoftSpi.h"
  249. #else
  250. #include <wiring.h>
  251. #include <pins_arduino.h>
  252. #endif
  253. // These defs cause trouble on some versions of Arduino
  254. #undef round
  255. #undef double
  256. // This is the bit in the SPI address that marks it as a write
  257. #define NRF24_SPI_WRITE_MASK 0x80
  258. // This is the maximum message length that can be supported by this library. Limited by
  259. // the suported message lengths oin the nRF24
  260. // Can be pre-defined to a smaller size (to save SRAM) prior to including this header
  261. #ifndef NRF24_MAX_MESSAGE_LEN
  262. #define NRF24_MAX_MESSAGE_LEN 32
  263. #endif
  264. // Keep track of the mode the NRF24 is in
  265. #define NRF24_MODE_IDLE 0
  266. #define NRF24_MODE_RX 1
  267. #define NRF24_MODE_TX 2
  268. // These values we set for FIFO thresholds are actually the same as the POR values
  269. #define NRF24_TXFFAEM_THRESHOLD 4
  270. #define NRF24_RXFFAFULL_THRESHOLD 55
  271. // This is the default node address,
  272. #define NRF24_DEFAULT_NODE_ADDRESS 0x00000000
  273. // This address in the TO addreess signifies a broadcast
  274. #define NRF24_BROADCAST_ADDRESS 0xffffffffff
  275. // SPI Command names
  276. #define NRF24_COMMAND_R_REGISTER 0x00
  277. #define NRF24_COMMAND_W_REGISTER 0x20
  278. #define NRF24_COMMAND_R_RX_PAYLOAD 0x61
  279. #define NRF24_COMMAND_W_TX_PAYLOAD 0xa0
  280. #define NRF24_COMMAND_FLUSH_TX 0xe1
  281. #define NRF24_COMMAND_FLUSH_RX 0xe2
  282. #define NRF24_COMMAND_REUSE_TX_PL 0xe3
  283. #define NRF24_COMMAND_R_RX_PL_WID 0x60
  284. #define NRF24_COMMAND_W_ACK_PAYLOAD(pipe) (0xa8|(pipe&0x7))
  285. #define NRF24_COMMAND_W_TX_PAYLOAD_NOACK 0xb0
  286. #define NRF24_COMMAND_NOP 0xff
  287. // Register names
  288. #define NRF24_REGISTER_MASK 0x1f
  289. #define NRF24_REG_00_CONFIG 0x00
  290. #define NRF24_REG_01_EN_AA 0x01
  291. #define NRF24_REG_02_EN_RXADDR 0x02
  292. #define NRF24_REG_03_SETUP_AW 0x03
  293. #define NRF24_REG_04_SETUP_RETR 0x04
  294. #define NRF24_REG_05_RF_CH 0x05
  295. #define NRF24_REG_06_RF_SETUP 0x06
  296. #define NRF24_REG_07_STATUS 0x07
  297. #define NRF24_REG_08_OBSERVE_TX 0x08
  298. #define NRF24_REG_09_RPD 0x09
  299. #define NRF24_REG_0A_RX_ADDR_P0 0x0a
  300. #define NRF24_REG_0B_RX_ADDR_P1 0x0b
  301. #define NRF24_REG_0C_RX_ADDR_P2 0x0c
  302. #define NRF24_REG_0D_RX_ADDR_P3 0x0d
  303. #define NRF24_REG_0E_RX_ADDR_P4 0x0e
  304. #define NRF24_REG_0F_RX_ADDR_P5 0x0f
  305. #define NRF24_REG_10_TX_ADDR 0x10
  306. #define NRF24_REG_11_RX_PW_P0 0x11
  307. #define NRF24_REG_12_RX_PW_P1 0x12
  308. #define NRF24_REG_13_RX_PW_P2 0x13
  309. #define NRF24_REG_14_RX_PW_P3 0x14
  310. #define NRF24_REG_15_RX_PW_P4 0x15
  311. #define NRF24_REG_16_RX_PW_P5 0x16
  312. #define NRF24_REG_17_FIFO_STATUS 0x17
  313. #define NRF24_REG_1C_DYNPD 0x1c
  314. #define NRF24_REG_1D_FEATURE 0x1d
  315. // These register masks etc are named wherever possible
  316. // corresponding to the bit and field names in the nRF24L01 Product Specification
  317. // #define NRF24_REG_00_CONFIG 0x00
  318. #define NRF24_MASK_RX_DR 0x40
  319. #define NRF24_MASK_TX_DS 0x20
  320. #define NRF24_MASK_MAX_RT 0x10
  321. #define NRF24_EN_CRC 0x08
  322. #define NRF24_CRCO 0x04
  323. #define NRF24_PWR_UP 0x02
  324. #define NRF24_PRIM_RX 0x01
  325. // #define NRF24_REG_01_EN_AA 0x01
  326. #define NRF24_ENAA_P5 0x20
  327. #define NRF24_ENAA_P4 0x10
  328. #define NRF24_ENAA_P3 0x08
  329. #define NRF24_ENAA_P2 0x04
  330. #define NRF24_ENAA_P1 0x02
  331. #define NRF24_ENAA_P0 0x01
  332. // #define NRF24_REG_02_EN_RXADDR 0x02
  333. #define NRF24_ERX_P5 0x20
  334. #define NRF24_ERX_P4 0x10
  335. #define NRF24_ERX_P3 0x08
  336. #define NRF24_ERX_P2 0x04
  337. #define NRF24_ERX_P1 0x02
  338. #define NRF24_ERX_P0 0x01
  339. // #define NRF24_REG_03_SETUP_AW 0x03
  340. #define NRF24_AW_3_BYTES 0x01
  341. #define NRF24_AW_4_BYTES 0x02
  342. #define NRF24_AW_5_BYTES 0x03
  343. // #define NRF24_REG_04_SETUP_RETR 0x04
  344. #define NRF24_ARD 0xf0
  345. #define NRF24_ARC 0x0f
  346. // #define NRF24_REG_05_RF_CH 0x05
  347. #define NRF24_RF_CH 0x7f
  348. // #define NRF24_REG_06_RF_SETUP 0x06
  349. #define NRF24_CONT_WAVE 0x80
  350. #define NRF24_RF_DR_LOW 0x20
  351. #define NRF24_PLL_LOCK 0x10
  352. #define NRF24_RF_DR_HIGH 0x08
  353. #define NRF24_PWR 0x06
  354. #define NRF24_PWR_m18dBm 0x00
  355. #define NRF24_PWR_m12dBm 0x02
  356. #define NRF24_PWR_m6dBm 0x04
  357. #define NRF24_PWR_0dBm 0x06
  358. // #define NRF24_REG_07_STATUS 0x07
  359. #define NRF24_RX_DR 0x40
  360. #define NRF24_TX_DS 0x20
  361. #define NRF24_MAX_RT 0x10
  362. #define NRF24_RX_P_NO 0x0e
  363. #define NRF24_STATUS_TX_FULL 0x01
  364. // #define NRF24_REG_08_OBSERVE_TX 0x08
  365. #define NRF24_PLOS_CNT 0xf0
  366. #define NRF24_ARC_CNT 0x0f
  367. // #define NRF24_REG_09_RPD 0x09
  368. #define NRF24_RPD 0x01
  369. // #define NRF24_REG_17_FIFO_STATUS 0x17
  370. #define NRF24_TX_REUSE 0x40
  371. #define NRF24_TX_FULL 0x20
  372. #define NRF24_TX_EMPTY 0x10
  373. #define NRF24_RX_FULL 0x02
  374. #define NRF24_RX_EMPTY 0x01
  375. // #define NRF24_REG_1C_DYNPD 0x1c
  376. #define NRF24_DPL_P5 0x20
  377. #define NRF24_DPL_P4 0x10
  378. #define NRF24_DPL_P3 0x08
  379. #define NRF24_DPL_P2 0x04
  380. #define NRF24_DPL_P1 0x02
  381. #define NRF24_DPL_P0 0x01
  382. // #define NRF24_REG_1D_FEATURE 0x1d
  383. #define NRF24_EN_DPL 0x04
  384. #define NRF24_EN_ACK_PAY 0x02
  385. #define NRF24_EN_DYN_ACK 0x01
  386. /////////////////////////////////////////////////////////////////////
  387. /// \class NRF24 NRF24.h <NRF24.h>
  388. /// \brief Send and receive addressed, reliable, acknowledged datagrams by nRF24L01.
  389. ///
  390. /// This base class provides basic functions for sending and receiving addressed, reliable,
  391. /// automatically acknowledged and retransmitted
  392. /// datagrams via nRF24L01 of arbitrary length to 32 octets per packet.
  393. /// Sender and receiver must each know the addreesses of the other, so arbitrary meshes and stars are
  394. /// not possible at this level.
  395. /// Directed replies (ie replies sent back to the original sender) are not possible
  396. /// (the address of the sender is not carried in the message).
  397. /// See subclasses for support for this.
  398. ///
  399. /// Subclasses may use this class to implement streams,
  400. /// mesh routers, repeaters, translators etc.
  401. ///
  402. /// On transmission, the addresses of this node defaults to 0x0000000000, unless changed by a subclass.
  403. ///
  404. /// The radio is configured to use Enhanced Shockburst with retransmits.
  405. /// TX_ADDR and RX_ADDR_P0 are set to the transmit address (ie the address of the destination for the next message
  406. /// RX_ADDR_P1 is set to the address of this node
  407. /// RX_ADDR_P2 is set to RX_ADDR_P1 with the LSbyte set to 0xff, for use as a broadcast address
  408. ///
  409. /// Naturally, for any 2 radios to communicate that must be configured to use the same frequency and
  410. /// data rate, and with compatible addresses
  411. class NRF24
  412. {
  413. public:
  414. /// \brief Defines convenient values for setting data rates in setRF()
  415. typedef enum
  416. {
  417. NRF24DataRate1Mbps = 0, ///< 1 Mbps
  418. NRF24DataRate2Mbps, ///< 2 Mbps
  419. NRF24DataRate250kbps ///< 250 kbps
  420. } NRF24DataRate;
  421. /// \brief Convenient values for setting transmitter power in setRF()
  422. /// These are designed to agree with the values for RF_PWR
  423. /// To be passed to setRF();
  424. typedef enum
  425. {
  426. NRF24TransmitPowerm18dBm = 0, ///< -18 dBm
  427. NRF24TransmitPowerm12dBm, ///< -12 dBm
  428. NRF24TransmitPowerm6dBm, ///< -6 dBm
  429. NRF24TransmitPower0dBm ///< 0 dBm
  430. } NRF24TransmitPower;
  431. /// Constructor. You can have multiple instances, but each instance must have its own
  432. /// chip enable and slave select pin.
  433. /// After constructing, you must call init() to initialise the interface
  434. /// and the radio module
  435. /// \param[in] chipEnablePin the Arduino pin to use to enable the chip for4 transmit/receive
  436. /// \param[in] chipSelectPin the Arduino pin number of the output to use to select the NRF24 before
  437. /// accessing it
  438. NRF24(uint8_t chipEnablePin = 4, uint8_t chipSelectPin = SS);
  439. /// Initialises this instance and the radio module connected to it.
  440. /// The following steps are taken:g
  441. /// - Set the chip enable and chip select pins to output LOW, HIGH respectively.
  442. /// - Initialise the SPI output pins
  443. /// - Initialise the SPI interface library to 8MHz (Hint, if you want to lower
  444. /// the SPI frequency (perhaps where you have other SPI shields, low voltages etc),
  445. /// call SPI.setClockDivider() after init()).
  446. /// -Flush the receiver and transmitter buffers
  447. /// - Set the radio to receive with powerUpRx();
  448. /// \return true if everything was successful
  449. boolean init();
  450. /// Execute an SPI command that requires neither reading or writing
  451. /// \param[in] command the SPI command to execute, one of NRF24_COMMAND_*
  452. /// \return the value of the device status register
  453. uint8_t spiCommand(uint8_t command);
  454. /// Reads a single command byte from the NRF24
  455. /// \param[in] command Command number, one of NRF24_COMMAND_*
  456. /// \return the single byte returned by the command
  457. uint8_t spiRead(uint8_t command);
  458. /// Writes a single command byte to the NRF24
  459. /// \param[in] command Command number, one of NRF24_COMMAND_*
  460. /// \param[in] val The value to write
  461. /// \return the value of the device status register
  462. uint8_t spiWrite(uint8_t command, uint8_t val);
  463. /// Reads a number of consecutive bytes from a command using burst read mode
  464. /// \param[in] command Command number of NRF24_COMMAND_*
  465. /// \param[in] dest Array to write the bytes returned by the command to. Must be at least len bytes
  466. /// \param[in] len Number of bytes to read
  467. /// \return the value of the device status register
  468. void spiBurstRead(uint8_t command, uint8_t* dest, uint8_t len);
  469. /// Write a number of consecutive bytes to a command using burst write mode
  470. /// \param[in] command Command number of the first register, one of NRF24_COMMAND_*
  471. /// \param[in] src Array of bytes to write. Must be at least len bytes
  472. /// \param[in] len Number of bytes to write
  473. /// \return the value of the device status register
  474. uint8_t spiBurstWrite(uint8_t command, uint8_t* src, uint8_t len);
  475. /// Reads a single register from the NRF24
  476. /// \param[in] reg Register number, one of NRF24_REG_*
  477. /// \return The value of the register
  478. uint8_t spiReadRegister(uint8_t reg);
  479. /// Writes a single byte to the NRF24, and at the ame time reads the current STATUS register
  480. /// \param[in] reg Register number, one of NRF24_REG_*
  481. /// \param[in] val The value to write
  482. /// \return the current STATUS (read while the command is sent)
  483. uint8_t spiWriteRegister(uint8_t reg, uint8_t val);
  484. /// Reads a number of consecutive registers from the NRF24 using burst read mode
  485. /// \param[in] reg Register number of the first register, one of NRF24_REG_*
  486. /// \param[in] dest Array to write the register values to. Must be at least len bytes
  487. /// \param[in] len Number of bytes to read
  488. /// \return the value of the device status register
  489. void spiBurstReadRegister(uint8_t reg, uint8_t* dest, uint8_t len);
  490. /// Write a number of consecutive registers using burst write mode
  491. /// \param[in] reg Register number of the first register, one of NRF24_REG_*
  492. /// \param[in] src Array of new register values to write. Must be at least len bytes
  493. /// \param[in] len Number of bytes to write
  494. /// \return the value of the device status register
  495. uint8_t spiBurstWriteRegister(uint8_t reg, uint8_t* src, uint8_t len);
  496. /// Reads and returns the device status register NRF24_REG_02_DEVICE_STATUS
  497. /// \return The value of the device status register
  498. uint8_t statusRead();
  499. /// Flush the TX FIFOs
  500. /// \return the value of the device status register
  501. uint8_t flushTx();
  502. /// Flush the RX FIFOs
  503. /// \return the value of the device status register
  504. uint8_t flushRx();
  505. /// Sets the transmit and receive channel number.
  506. /// The frequency used is (2400 + channel) MHz
  507. /// \return true on success
  508. boolean setChannel(uint8_t channel);
  509. /// Sets the chip configuration that will be used to set
  510. /// the NRF24 NRF24_REG_00_CONFIG register. This allows you to change some
  511. /// chip configuration for compatibility with libraries other than this one.
  512. /// You should not normally need to call this.
  513. /// Defaults to NRF24_EN_CRC, which is the standard configuraiton for this library.
  514. /// \param[in] configuration The chip configuration to be used.
  515. /// \return true on success
  516. boolean setConfiguration(uint8_t configuration);
  517. /// Sets the first len bytes of the address for the given NRF24 receiver pipe
  518. /// This is an internal function and is not normally used by appications, but
  519. /// can be used for specialised applications.
  520. /// \param[in] pipe The index of the pipe to set, from 0 to 5
  521. /// \param[in] address The new address for receiving. Must match the transmit address
  522. /// of the transmitting node
  523. /// \param[in] len Number of bytes of receive address to set.
  524. /// \return true on success
  525. boolean setPipeAddress(uint8_t pipe, uint8_t* address, uint8_t len);
  526. /// Set the Auto Retransmit Delay and Auto Retransmit Count
  527. /// for Auto retransmission (ART). See section 7.4.2 in the NRF24 documentation
  528. /// It may be very important to set an appropriate delay and count
  529. /// for your application, especially with
  530. /// 250kbps (i.e. slow) data rate. The defaults are OK for faster data rates. If
  531. /// the delay is too short, the symptoms wil be unreliable transmission, or tranmsission failures
  532. /// \param[in] delay The number of 250 microsecond intervals to wait for an ACK.
  533. /// \param[in] count The number of retries to us.
  534. /// \return true on success
  535. boolean setRetry(uint8_t delay, uint8_t count = 3);
  536. /// Sets the first len bytes of the address of this node
  537. /// Normally len is the same length as setAddressLength, but can be smaller in order to set the
  538. /// least significant bytes of the address
  539. /// \param[in] address The new address for receiving. Must match the setTransmitAddress of the transmitting node.
  540. /// \param[in] len Number of bytes of receive address to set.
  541. /// \return true on success
  542. boolean setThisAddress(uint8_t* address, uint8_t len);
  543. /// Sets the next transmit address
  544. /// \param[in] address The new address for transmitting. Must match the setThisAddress of the receiving node.
  545. /// \param[in] len Number of bytes of receive address to set.
  546. /// \return true on success
  547. boolean setTransmitAddress(uint8_t* address, uint8_t len);
  548. /// Sets the number of bytes transmitted
  549. /// in each payload
  550. /// \param[in] size Size of the transmitted payload in bytes
  551. /// \return true on success
  552. boolean setPayloadSize(uint8_t size);
  553. /// Sets the data rate and tranmitter power to use
  554. /// \param [in] data_rate The data rate to use for all packets transmitted and received. One of NRF24DataRate
  555. /// \param [in] power Transmitter power. One of NRF24TransmitPower.
  556. /// \return true on success
  557. boolean setRF(uint8_t data_rate, uint8_t power);
  558. /// Sets the radio in power down mode.
  559. /// Sets chip enable to LOW.
  560. /// \return true on success
  561. boolean powerDown();
  562. /// Sets the radio in RX mode.
  563. /// Sets chip enable to HIGH to enable the chip in RX mode.
  564. /// \return true on success
  565. boolean powerUpRx();
  566. /// Sets the radio in TX mode.
  567. /// Pulses the chip enable LOW then HIGH to enable the chip in TX mode.
  568. /// \return true on success
  569. boolean powerUpTx();
  570. /// Sends data to the address set by setTransmitAddress()
  571. /// Sets the radio to TX mode
  572. /// \param [in] data Data bytes to send.
  573. /// \param [in] len Number of data bytes to set in teh TX buffer. The actual size of the
  574. /// transmitted data payload is set by setPayloadSize
  575. /// \param [in] noack Optional parameter if true sends the message NOACK mode. Requires that the NOACK feature be
  576. /// enabled with spiWriteRegister(NRF24_REG_1D_FEATURE, NRF24_EN_DYN_ACK);
  577. /// \return true on success
  578. boolean send(uint8_t* data, uint8_t len, boolean noack = false);
  579. /// Blocks until the current message (if any)
  580. /// has been transmitted
  581. /// \return true on success, false if the Max retries were exceeded, or if the chip is not in transmit mode.
  582. boolean waitPacketSent();
  583. /// Indicates if the chip is in transmit mode and
  584. /// there is a packet currently being transmitted
  585. /// \return true if the chip is in transmit mode and there is a transmission in progress
  586. boolean isSending();
  587. /// Prints the value of all chip registers
  588. /// for debugging purposes
  589. /// \return true on success
  590. boolean printRegisters();
  591. /// Checks whether a received message is available.
  592. /// This can be called multiple times in a timeout loop
  593. /// \return true if a complete, valid message has been received and is able to be retrieved by
  594. /// recv()
  595. boolean available();
  596. /// Starts the receiver and blocks until a valid received
  597. /// message is available.
  598. void waitAvailable();
  599. /// Starts the receiver and blocks until a received message is available or a timeout
  600. /// \param[in] timeout Maximum time to wait in milliseconds.
  601. /// \return true if a message is available
  602. bool waitAvailableTimeout(uint16_t timeout);
  603. /// Turns the receiver on if it not already on.
  604. /// If there is a valid message available, copy it to buf and return true
  605. /// else return false.
  606. /// If a message is copied, *len is set to the length (Caution, 0 length messages are permitted).
  607. /// You should be sure to call this function frequently enough to not miss any messages
  608. /// It is recommended that you call it in your main loop.
  609. /// \param[in] buf Location to copy the received message
  610. /// \param[in,out] len Pointer to available space in buf. Set to the actual number of octets copied.
  611. /// \return true if a valid message was copied to buf
  612. boolean recv(uint8_t* buf, uint8_t* len);
  613. protected:
  614. private:
  615. uint8_t _configuration;
  616. uint8_t _chipEnablePin;
  617. uint8_t _chipSelectPin;
  618. };
  619. /// @example nrf24_audio_rx.pde
  620. /// Example sketch showing how to create an audio digital receiver
  621. /// with the NRF24 class.
  622. /// Works with the nrf24_audio_tx sample transmitter
  623. /// Connect audio output to pin 6, through a low pass filter consisting of a 1k resistor in series followed by a
  624. /// 0.0033 microfarad capacitor to ground (48kHz filter).
  625. /// The audio quality is poor: dont expect hi-fi!
  626. /// We have to change the PWM frequency to 62 kHz so we can get bandwidth reasonable
  627. /// audio out through the low pass filter
  628. /// Tested on UNO
  629. /// @example nrf24_audio_tx.pde
  630. /// Example sketch showing how to create an audio digital transmitter
  631. /// with the NRF24 class.
  632. /// Connect a 1Vp-p audio sigal to analog input 0, connected through a 1uF capacitor
  633. /// Works with the nrf24_audio_rx sample receiver
  634. /// The audio quality is poor: dont expect hi-fi!
  635. ///
  636. /// This code sends about 250 messages per second, each with 32 8 bit samples from analog input 0
  637. /// It uses the NRF4 in NOACK mode. The receiver never acknowledges or replies
  638. /// Tested on UNO
  639. /// @example nrf24_ping_client.pde
  640. /// Example sketch showing how to create a simple messageing client
  641. /// with the NRF24 class.
  642. /// It is designed to work with the example nrf24_ping_server
  643. /// It also works with ping_server from the Mirf library
  644. /// @example nrf24_ping_server.pde
  645. /// Example sketch showing how to create a simple messageing server
  646. /// with the NRF24 class.
  647. /// It is designed to work with the example nrf24_ping_client.
  648. /// It also works with ping_client from the Mirf library
  649. /// @example nrf24_specan.pde
  650. /// Example sketch showing how to create a primitive spectrum analyser
  651. /// with the NRF24 class.
  652. /// The nRF24L01 received power detector is only one bit, but
  653. /// this will show which channels have more than -64dBm present
  654. /// @example nrf24_test.pde
  655. /// Test suite for the NRF24 class.
  656. /// @example crazyflie.ino
  657. /// This sketch act like a Crazyflie quadcopter http://www.bitcraze.se/
  658. /// using the CRTP radiolink protocol:
  659. /// http://wiki.bitcraze.se/projects:crazyflie:firmware:comm_protocol
  660. /// @example crazyflie_client.ino
  661. /// This sketch act like a Crazyflie client (ie the transmitter) using the CRTP radiolink protocol:
  662. /// http://wiki.bitcraze.se/projects:crazyflie:firmware:comm_protocol
  663. /// to control a Crazyflie quadcopter http://www.bitcraze.se/
  664. /// using a RC transmitter in trainer mode, such as the Spektrum DX6i and others.
  665. #endif