├── LICENSE ├── README.md ├── examples ├── recv.py └── send.py ├── nrf24.py ├── setup.py └── spi ├── BB-nRF24-SPI0-00A0.dts └── README.md /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | Python port of maniacbug NRF24L01 library. 294 | Copyright (C) 2013 João Paulo Barraca 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | pynrf24 2 | ======= 3 | 4 | Pure python port of the RF24 (https://github.com/maniacbug/RF24/) library for NRF24L01+ radios through SPI. 5 | 6 | All API methods were ported and prototypes were kept very similar. This should facilitate the reuse of code from the STM32 or Arduino platforms. 7 | The focus of this libary is to provide an API similar to the RF24 driver. Therefore, many things are not so pythonic, especially function names. 8 | The actually implementation is improved from the original RF24 code base and has many bug fixes solved, as well as improved performance. 9 | 10 | For more information regarding how to use this library, check the RF24 documentation: http://maniacbug.github.io/RF24/ 11 | Most of the information there will also be valid here. 12 | 13 | Tested on the the BeagleBone Black, Raspberry Pi, and Banana Pi. 14 | Should work without problems with NRF24L01 (non +) radios. 15 | 16 | Do not forget to check this [great tutorial](http://www.diyembedded.com/tutorials/nrf24l01_0/nrf24l01_tutorial_0.pdf) 17 | or the [original datasheet](http://www.nordicsemi.com/eng/Products/2.4GHz-RF/nRF24L01) 18 | 19 | 20 | Contact 21 | ------- 22 | 23 | For any information regarding this library please create an issue. 24 | 25 | Improvements to the code base are also welcome. 26 | 27 | Requirements 28 | ------------ 29 | 30 | * Python 2 31 | * SPI communication requires spidev: https://pypi.python.org/pypi/spidev 32 | * BBB: GPIO access requires Adafruit BBIO library: https://github.com/adafruit/adafruit-beaglebone-io-python 33 | * BBB: If using GPIO IRQ detection, a custom version of the Adafruit library can be used https://github.com/jpbarraca/adafruit-beaglebone-io-python in order to support a timeout when waiting for the IRQ line. 34 | 35 | 36 | Wiring 37 | ------ 38 | 39 | nRF24L01+ (top view) BeagleBoneBlack 40 | +-+-+ (header) 41 | |8|7| 1: GND -> P9 GND (P9_1 and P9_2) 42 | +-+-+ 2: 3.3V -> P9 3.3v (P9_3 and P9_4) 43 | |6|5| 3: CE -> P9_23 (configurable) 44 | +-+-+ 4: CSN -> SPI0.CS (P9_17) 45 | |4|3| 5: SCKL -> SPI0.SCLK (P9_22) 46 | +-+-+ 6: MOSI -> SPI0.D1 (P9_18) 47 | |2|1| 7: MISO -> SPI0.D0 (P9_21) 48 | +-+-+ 8: IRQ -> P9_24 (configurable) 49 | 50 | Examples 51 | -------- 52 | 53 | Initialization: 54 | 55 | pipes = [ [0xe7, 0xe7, 0xe7, 0xe7, 0xe7], [0xc2, 0xc2, 0xc2, 0xc2, 0xc2] ] 56 | 57 | radio = NRF24() 58 | radio.begin(1,0,"P9_23", "P9_24") #Set CE and IRQ pins 59 | radio.setRetries(15,15) 60 | radio.setPayloadSize(8) 61 | radio.setChannel(0x60) 62 | radio.setDataRate(NRF24.BR_250KBPS) 63 | radio.setPALevel(NRF24.PA_MAX) 64 | radio.openWritingPipe(pipes[0]) 65 | radio.openReadingPipe(1,pipes[1]) 66 | 67 | radio.printDetails() 68 | 69 | 70 | Sending Data: 71 | 72 | status = radio.write("HELLO") 73 | 74 | 75 | Receiving Data: 76 | 77 | #Wait for data 78 | pipe =[0] 79 | while not radio.available(pipe): 80 | time.sleep(10000/1000000.0) 81 | 82 | #Receive Data 83 | recv_buffer = [] 84 | radio.read(recv_buffer) 85 | 86 | #Print the buffer 87 | print recv_buffer 88 | 89 | 90 | Caveats 91 | ------- 92 | 93 | Performance with this driver (as well as with any other Python "driver") may be lower than expected. You will sacrifice performance for flexibility. 94 | Python is a high level language and there is too much stuff going on (e.g, Garbage Collection) for timing constrains to be respected. There is no assurance that you can transmit at 2Mbits/s. 95 | 96 | Benchmarks using an Nucleo 401RE and a BBB show a usable bitrate around 582kbits/s for a 2Mbit/s configuration. This was achieved using packets with 32 byte payloads, no CRC, and no Acknowledgements. According to the datasheet, for a 32 byte buffer, there will be more 65 bits of overhead, and the process will take at least 25.6us to upload the buffer, 130us for the PLL to lock, and 6us for the TX DS bit to be set. The total time spent will be of 160.5us + 25.6us + 130us + 6us = 322.1us, independently of the driver, and resulting in a usable bitrate of 795 Kb/s. Then you have to consider the latency of the SPI bus and code being executed at the uC. Actually, in this benchmark the SPI bus driver was taking 45% of the CPU. 97 | 98 | It works great in my case. Use AS-IS, but remember that YMMV. 99 | 100 | License 101 | ------- 102 | 103 | This program is free software: you can redistribute it and/or modify 104 | it under the terms of the GNU General Public License as published by 105 | the Free Software Foundation, either version 3 of the License, or 106 | (at your option) any later version. 107 | 108 | This program is distributed in the hope that it will be useful, 109 | but WITHOUT ANY WARRANTY; without even the implied warranty of 110 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 111 | GNU General Public License for more details. 112 | 113 | You should have received a copy of the GNU General Public License 114 | along with this program. If not, see . 115 | 116 | -------------------------------------------------------------------------------- /examples/recv.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # Example program to receive packets from the radio 5 | # 6 | # João Paulo Barraca 7 | # 8 | from nrf24 import NRF24 9 | import time 10 | 11 | pipes = [[0xe7, 0xe7, 0xe7, 0xe7, 0xe7], [0xc2, 0xc2, 0xc2, 0xc2, 0xc2]] 12 | 13 | radio = NRF24() 14 | radio.begin(1, 0, "P8_23", "P8_24") 15 | 16 | radio.setRetries(15,15) 17 | 18 | radio.setPayloadSize(8) 19 | radio.setChannel(0x60) 20 | radio.setDataRate(NRF24.BR_250KBPS) 21 | radio.setPALevel(NRF24.PA_MAX) 22 | 23 | radio.setAutoAck(1) 24 | 25 | radio.openWritingPipe(pipes[0]) 26 | radio.openReadingPipe(1, pipes[1]) 27 | 28 | radio.startListening() 29 | radio.stopListening() 30 | 31 | radio.printDetails() 32 | 33 | radio.startListening() 34 | 35 | while True: 36 | pipe = [0] 37 | while not radio.available(pipe, True): 38 | time.sleep(1000/1000000.0) 39 | 40 | recv_buffer = [] 41 | radio.read(recv_buffer) 42 | 43 | print recv_buffer 44 | -------------------------------------------------------------------------------- /examples/send.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # Example program to send packets to the radio 5 | # 6 | # João Paulo Barraca 7 | # 8 | 9 | from nrf24 import NRF24 10 | import time 11 | 12 | pipes = [[0xe7, 0xe7, 0xe7, 0xe7, 0xe7], [0xc2, 0xc2, 0xc2, 0xc2, 0xc2]] 13 | 14 | radio = NRF24() 15 | radio.begin(1, 0, "P8_23", "P8_24") #Set CE and IRQ pins 16 | radio.setRetries(15,15) 17 | radio.setPayloadSize(8) 18 | radio.setChannel(0x60) 19 | 20 | radio.setDataRate(NRF24.BR_250KBPS) 21 | radio.setPALevel(NRF24.PA_MAX) 22 | 23 | radio.openWritingPipe(pipes[1]) 24 | radio.openReadingPipe(1, pipes[0]) 25 | 26 | radio.startListening() 27 | radio.stopListening() 28 | 29 | radio.printDetails() 30 | 31 | while True: 32 | radio.write("PING") 33 | time.sleep(1) 34 | -------------------------------------------------------------------------------- /nrf24.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # Python port of Maniacbug NRF24L01 library 15 | # Author: Joao Paulo Barraca 16 | # 17 | # BeagleBoneBlack and Raspberry Pi use different GPIO access methods. 18 | # Select the most appropriate for you by uncommenting one of the 19 | # two imports. 20 | 21 | try: 22 | # For Raspberry Pi 23 | import RPi.GPIO as GPIO 24 | GPIO.setmode(GPIO.BCM) 25 | GPIO.setwarnings(False) 26 | except ImportError: 27 | try: 28 | #For BBBB 29 | import Adafruit_BBIO.GPIO as GPIO 30 | except ImportError: 31 | raise ImportError('Neither RPi.GPIO nor Adafruit_BBIO.GPIO module found.') 32 | 33 | # Try to Use spidev (which is faster) and then try Adafruit_BBIO 34 | try: 35 | import spidev 36 | ADAFRUID_BBIO_SPI = False 37 | except: 38 | from Adafruit_BBIO.SPI import SPI 39 | ADAFRUID_BBIO_SPI = True 40 | 41 | 42 | # Use a monotonic clock if available to avoid unwanted side effects from clock 43 | # changes 44 | try: 45 | from time import monotonic 46 | except ImportError: 47 | from time import time as monotonic 48 | 49 | import time 50 | import sys 51 | 52 | if sys.version > '3': 53 | long = int 54 | 55 | 56 | class NRF24: 57 | MAX_CHANNEL = 127 58 | MAX_PAYLOAD_SIZE = 32 59 | 60 | # PA Levels 61 | PA_MIN = 0x00 62 | PA_LOW = 0x01 63 | PA_HIGH = 0x02 64 | PA_MAX = 0x03 65 | PA_ERROR = 0x04 66 | 67 | # Bit rates 68 | BR_1MBPS = 0 69 | BR_2MBPS = 1 70 | BR_250KBPS = 2 71 | 72 | # CRC 73 | CRC_DISABLED = 0x0 74 | CRC_8 = 0x02 75 | CRC_16 = 0x04 76 | CRC_ENABLED = 0x08 77 | 78 | EN_CRC = 0x08 79 | CRCO = 0x04 80 | 81 | # Registers 82 | CONFIG = 0x00 83 | EN_AA = 0x01 84 | EN_RXADDR = 0x02 85 | SETUP_AW = 0x03 86 | SETUP_RETR = 0x04 87 | RF_CH = 0x05 88 | RF_SETUP = 0x06 89 | STATUS = 0x07 90 | OBSERVE_TX = 0x08 91 | RPD = 0x09 92 | RX_ADDR_P0 = 0x0A 93 | RX_ADDR_P1 = 0x0B 94 | RX_ADDR_P2 = 0x0C 95 | RX_ADDR_P3 = 0x0D 96 | RX_ADDR_P4 = 0x0E 97 | RX_ADDR_P5 = 0x0F 98 | TX_ADDR = 0x10 99 | RX_PW_P0 = 0x11 100 | RX_PW_P1 = 0x12 101 | RX_PW_P2 = 0x13 102 | RX_PW_P3 = 0x14 103 | RX_PW_P4 = 0x15 104 | RX_PW_P5 = 0x16 105 | FIFO_STATUS = 0x17 106 | DYNPD = 0x1C 107 | FEATURE = 0x1D 108 | 109 | # Bit Mnemonics */ 110 | MASK_RX_DR = 0x40 111 | MASK_TX_DS = 0x20 112 | MASK_MAX_RT = 0x10 113 | 114 | PWR_UP = 0x02 115 | PRIM_RX = 0x01 116 | PLL_LOCK = 0x10 117 | RX_DR = 0x40 118 | TX_DS = 0x20 119 | MAX_RT = 0x10 120 | TX_FULL = 0x01 121 | 122 | EN_DPL = 0x04 123 | EN_ACK_PAY = 0x02 124 | EN_DYN_ACK = 0x01 125 | 126 | # Shift counts 127 | ARD = 4 128 | ARC = 0 129 | PLOS_CNT = 4 130 | ARC_CNT = 0 131 | RX_P_NO = 1 132 | 133 | TX_REUSE = 6 134 | FIFO_FULL = 5 135 | TX_EMPTY = 4 136 | RX_FULL = 1 137 | RX_EMPTY = 0 138 | 139 | DPL_P5 = 5 140 | DPL_P4 = 4 141 | DPL_P3 = 3 142 | DPL_P2 = 2 143 | DPL_P1 = 1 144 | DPL_P0 = 0 145 | 146 | #Masks 147 | RX_P_NO_MASK = 0x0E 148 | 149 | # Instruction Mnemonics 150 | R_REGISTER = 0x00 151 | W_REGISTER = 0x20 152 | REGISTER_MASK = 0x1F 153 | ACTIVATE = 0x50 154 | R_RX_PL_WID = 0x60 155 | R_RX_PAYLOAD = 0x61 156 | W_TX_PAYLOAD = 0xA0 157 | W_ACK_PAYLOAD = 0xA8 158 | FLUSH_TX = 0xE1 159 | FLUSH_RX = 0xE2 160 | REUSE_TX_PL = 0xE3 161 | NOP = 0xFF 162 | 163 | # Non-P omissions 164 | LNA_HCURR = 0x01 165 | LNA_ON = 1 166 | LNA_OFF = 0 167 | 168 | # P model bit Mnemonics 169 | RF_DR_LOW = 0x20 170 | RF_DR_HIGH = 0x08 171 | RF_PWR_LOW = 0x02 172 | RF_PWR_HIGH = 0x04 173 | 174 | datarate_e_str_P = ["1MBPS", "2MBPS", "250KBPS"] 175 | model_e_str_P = ["nRF24L01", "nRF24l01+"] 176 | crclength_e_str_P = ["Disabled", "", "8 bits", "", "16 bits"] 177 | pa_dbm_e_str_P = ["PA_MIN", "PA_LOW", "PA_HIGH", "PA_MAX"] 178 | 179 | @staticmethod 180 | def print_single_status_line(name, value): 181 | print("{0:<16}= {1}".format(name, value)) 182 | 183 | @staticmethod 184 | def _to_8b_list(data): 185 | """Convert an arbitray iteratable or single int to a list of ints 186 | where each int is smaller than 256.""" 187 | if isinstance(data, str): 188 | data = [ord(x) for x in data] 189 | elif isinstance(data, (int, long)): 190 | data = [data] 191 | else: 192 | data = [int(x) for x in data] 193 | 194 | #for byte in data: 195 | # if byte < 0 or byte > 255: 196 | # raise RuntimeError("Value %d is larger than 8 bits" % byte) 197 | return data 198 | 199 | def __init__(self, major=None, minor=None, ce_pin=None, irq_pin=None): 200 | self.ce_pin = "P9_15" 201 | self.irq_pin = "P9_16" 202 | self.channel = 76 203 | self.data_rate = NRF24.BR_1MBPS 204 | self.data_rate_bits = 1000 205 | self.p_variant = False # False for RF24L01 and true for RF24L01P 206 | self.payload_size = 5 # *< Fixed size of payloads 207 | self.ack_payload_available = False # *< Whether there is an ack payload waiting 208 | self.dynamic_payloads_enabled = False # *< Whether dynamic payloads are enabled. 209 | self.ack_payload_length = 5 # *< Dynamic size of pending ack payload. 210 | self.pipe0_reading_address = None # *< Last address set on pipe 0 for reading. 211 | self.spidev = None 212 | self.last_error = None 213 | self.crc_length = 0 214 | self.auto_ack = 0x3F 215 | self.address_length = 5 216 | 217 | # If all parameters are available, lets start the radio! 218 | if major is not None and minor is not None and irq_pin is not None: 219 | self.begin(major, minor, ce_pin, irq_pin) 220 | 221 | def begin(self, major, minor, ce_pin, irq_pin): 222 | # Initialize SPI bus 223 | 224 | if ADAFRUID_BBIO_SPI: 225 | self.spidev = SPI(major, minor) 226 | self.spidev.bpw = 8 227 | try: 228 | self.spidev.msh = 10000000 # Maximum supported by NRF24L01+ 229 | except IOError: 230 | pass # Hardware does not support this speed 231 | else: 232 | self.spidev = spidev.SpiDev() 233 | self.spidev.open(major, minor) 234 | 235 | self.spidev.bits_per_word = 8 236 | 237 | try: 238 | self.spidev.max_speed_hz = 10000000 # Maximum supported by NRF24L01+ 239 | except IOError: 240 | pass # Hardware does not support this speed 241 | 242 | self.spidev.cshigh = False 243 | self.spidev.mode = 0 244 | self.spidev.loop = False 245 | self.spidev.lsbfirst = False 246 | self.spidev.threewire = False 247 | 248 | self.ce_pin = ce_pin 249 | self.irq_pin = irq_pin 250 | 251 | if self.ce_pin is not None: 252 | GPIO.setup(self.ce_pin, GPIO.OUT) 253 | 254 | GPIO.setup(self.irq_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) 255 | 256 | time.sleep(5 / 1000000.0) 257 | 258 | # Reset radio configuration 259 | self.reset() 260 | 261 | # Set 1500uS (minimum for 32B payload in ESB@250KBPS) timeouts, to make testing a little easier 262 | # WARNING: If this is ever lowered, either 250KBS mode with AA is broken or maximum packet 263 | # sizes must never be used. See documentation for a more complete explanation. 264 | self.setRetries(5, 15) 265 | 266 | # Restore our default PA level 267 | self.setPALevel(NRF24.PA_MAX) 268 | 269 | # Determine if this is a p or non-p RF24 module and then 270 | # reset our data rate back to default value. This works 271 | # because a non-P variant won't allow the data rate to 272 | # be set to 250Kbps. 273 | if self.setDataRate(NRF24.BR_250KBPS): 274 | self.p_variant = True 275 | 276 | # Then set the data rate to the slowest (and most reliable) speed supported by all 277 | # hardware. 278 | self.setDataRate(NRF24.BR_1MBPS) 279 | 280 | # Initialize CRC and request 2-byte (16bit) CRC 281 | self.setCRCLength(NRF24.CRC_16) 282 | 283 | # Disable dynamic payloads, to match dynamic_payloads_enabled setting 284 | self.write_register(NRF24.DYNPD, 0) 285 | 286 | # Reset current status 287 | # Notice reset and flush is the last thing we do 288 | self.write_register(NRF24.STATUS, NRF24.RX_DR | NRF24.TX_DS | NRF24.MAX_RT) 289 | 290 | # Set up default configuration. Callers can always change it later. 291 | # This channel should be universally safe and not bleed over into adjacent 292 | # spectrum. 293 | self.setChannel(self.channel) 294 | 295 | # Flush buffers 296 | self.flush_rx() 297 | self.flush_tx() 298 | self.clear_irq_flags() 299 | 300 | def end(self): 301 | if self.spidev: 302 | self.spidev.close() 303 | self.spidev = None 304 | 305 | def startListening(self): 306 | self.write_register(NRF24.CONFIG, self.read_register(NRF24.CONFIG) | NRF24.PWR_UP | NRF24.PRIM_RX) 307 | 308 | self.flush_tx() 309 | self.flush_rx() 310 | self.clear_irq_flags() 311 | 312 | # Restore the pipe0 address, if exists 313 | if self.pipe0_reading_address: 314 | self.write_register(self.RX_ADDR_P0, self.pipe0_reading_address) 315 | 316 | # Go! 317 | self.ce(1) 318 | 319 | def ce(self, level, pulse=0): 320 | # CE Pin is optional 321 | if self.ce_pin is not None: 322 | GPIO.output(self.ce_pin, level) 323 | if pulse > 0: 324 | time.sleep(pulse) 325 | GPIO.output(self.ce_pin, 1 - level) 326 | 327 | def irqWait(self, timeout=30000): 328 | # TODO: A race condition may occur here. => wait for level? 329 | if GPIO.input(self.irq_pin) == 0: # Pin is already down. Packet is waiting? 330 | return True 331 | 332 | try: 333 | return GPIO.wait_for_edge(self.irq_pin, GPIO.FALLING, timeout=timeout) == self.irq_pin 334 | except TypeError: # Timeout parameter not supported 335 | return GPIO.wait_for_edge(self.irq_pin, GPIO.FALLING) == 1 336 | except AttributeError: 337 | raise RuntimeError("GPIO lib does not support wait_for_edge()") 338 | 339 | def read_register(self, reg, length=1): 340 | buf = [NRF24.R_REGISTER | (NRF24.REGISTER_MASK & reg)] 341 | buf += [NRF24.NOP] * max(1, length) 342 | 343 | resp = self.spidev.xfer2(buf) 344 | if length == 1: 345 | return resp[1] 346 | 347 | return resp[1:] 348 | 349 | def write_register(self, reg, value): 350 | """ Write register value """ 351 | buf = [NRF24.W_REGISTER | (NRF24.REGISTER_MASK & reg)] 352 | buf += self._to_8b_list(value) 353 | self.spidev.xfer2(buf) 354 | 355 | def write_payload(self, buf): 356 | """ Writes data to the payload register, automatically padding it 357 | to match the required length. Returns the number of bytes 358 | actually written. """ 359 | 360 | buf = self._to_8b_list(buf) 361 | if self.dynamic_payloads_enabled: 362 | if len(buf) > self.MAX_PAYLOAD_SIZE: 363 | raise RuntimeError("Dynamic payload is larger than the " + 364 | "maximum size.") 365 | blank_len = 0 366 | else: 367 | if len(buf) > self.payload_size: 368 | raise RuntimeError("Payload is larger than the fixed payload" + 369 | "size (%d vs. %d bytes)" % (len(buf), self.payload_size)) 370 | blank_len = self.payload_size - len(buf) 371 | 372 | txbuffer = [NRF24.W_TX_PAYLOAD] + buf + ([0x00] * blank_len) 373 | self.spidev.xfer2(txbuffer) 374 | return len(txbuffer) - 1 375 | 376 | def read_payload(self, buf, buf_len=-1): 377 | """ Reads data from the payload register and sets the 378 | DR bit of the STATUS register. """ 379 | 380 | if buf_len < 0: 381 | buf_len = self.payload_size 382 | 383 | if not self.dynamic_payloads_enabled: 384 | data_len = min(self.payload_size, buf_len) 385 | blank_len = self.payload_size - data_len 386 | else: 387 | data_len = self.getDynamicPayloadSize() 388 | blank_len = 0 389 | 390 | txbuffer = [NRF24.R_RX_PAYLOAD] + [NRF24.NOP] * (blank_len + data_len + 1) 391 | 392 | payload = self.spidev.xfer2(txbuffer) 393 | del buf[:] 394 | buf += payload[1:data_len + 1] 395 | 396 | self.write_register(NRF24.STATUS, NRF24.RX_DR) 397 | 398 | return data_len 399 | 400 | def flush_rx(self): 401 | return self.spidev.xfer2([NRF24.FLUSH_RX])[0] 402 | 403 | def flush_tx(self): 404 | return self.spidev.xfer2([NRF24.FLUSH_TX])[0] 405 | 406 | def get_status(self): 407 | return self.spidev.xfer2([NRF24.NOP])[0] 408 | 409 | def print_status(self, status): 410 | status_str = "0x{0:02x} RX_DR={1:x} TX_DS={2:x} MAX_RT={3:x} RX_P_NO={4:x} TX_FULL={5:x}".format( 411 | status, 412 | 1 if status & NRF24.RX_DR else 0, 413 | 1 if status & NRF24.TX_DS else 0, 414 | 1 if status & NRF24.MAX_RT else 0, 415 | ((status >> NRF24.RX_P_NO) & int("111", 2)), 416 | 1 if status & NRF24.TX_FULL else 0) 417 | 418 | self.print_single_status_line("STATUS", status_str) 419 | 420 | def print_observe_tx(self, value): 421 | tx_str = "0x{0:02x} PLOS_CNT={1:x} ARC_CNT={2:x}".format( 422 | value, 423 | (value >> NRF24.PLOS_CNT) & 0xf, 424 | (value >> NRF24.ARC_CNT) & 0xf) 425 | self.print_single_status_line("OBSERVE_TX", tx_str) 426 | 427 | def print_byte_register(self, name, reg, qty=1): 428 | registers = ["0x{:0>2x}".format(self.read_register(reg+r)) for r in range(0, qty)] 429 | self.print_single_status_line(name, " ".join(registers)) 430 | 431 | def print_address_register(self, name, reg, qty=1): 432 | address_registers = ["0x{0:>02x}{1:>02x}{2:>02x}{3:>02x}{4:>02x}".format( 433 | *self.read_register(reg+r, 5)) 434 | for r in range(qty)] 435 | 436 | self.print_single_status_line(name, " ".join(address_registers)) 437 | 438 | def setChannel(self, channel): 439 | if channel < 0 or channel > self.MAX_CHANNEL: 440 | raise RuntimeError("Channel number out of range") 441 | self.channel = channel 442 | self.write_register(NRF24.RF_CH, channel) 443 | 444 | def getChannel(self): 445 | return self.read_register(NRF24.RF_CH) 446 | 447 | def setPayloadSize(self, size): 448 | self.payload_size = min(max(size, 1), NRF24.MAX_PAYLOAD_SIZE) 449 | 450 | def getPayloadSize(self): 451 | return self.payload_size 452 | 453 | def printDetails(self): 454 | self.print_status(self.get_status()) 455 | self.print_address_register("RX_ADDR_P0-1", NRF24.RX_ADDR_P0, 2) 456 | self.print_byte_register("RX_ADDR_P2-5", NRF24.RX_ADDR_P2, 4) 457 | self.print_address_register("TX_ADDR", NRF24.TX_ADDR) 458 | 459 | self.print_byte_register("RX_PW_P0-6", NRF24.RX_PW_P0, 6) 460 | self.print_byte_register("EN_AA", NRF24.EN_AA) 461 | self.print_byte_register("EN_RXADDR", NRF24.EN_RXADDR) 462 | self.print_byte_register("RF_CH", NRF24.RF_CH) 463 | self.print_byte_register("RF_SETUP", NRF24.RF_SETUP) 464 | self.print_byte_register("SETUP_RETR", NRF24.SETUP_RETR) 465 | self.print_byte_register("SETUP_AW", NRF24.SETUP_AW) 466 | self.print_observe_tx(self.read_register(NRF24.OBSERVE_TX)) 467 | self.print_byte_register("CONFIG", NRF24.CONFIG) 468 | self.print_byte_register("FIFO_STATUS", NRF24.FIFO_STATUS) 469 | self.print_byte_register("DYNPD", NRF24.DYNPD) 470 | self.print_byte_register("FEATURE", NRF24.FEATURE) 471 | 472 | self.print_single_status_line("Data Rate", NRF24.datarate_e_str_P[self.getDataRate()]) 473 | self.print_single_status_line("Model", NRF24.model_e_str_P[self.isPVariant()]) 474 | self.print_single_status_line("CRC Length", NRF24.crclength_e_str_P[self.getCRCLength()]) 475 | self.print_single_status_line("PA Power", NRF24.pa_dbm_e_str_P[self.getPALevel()]) 476 | 477 | def stopListening(self): 478 | self.ce(0) 479 | self.flush_tx() 480 | self.flush_rx() 481 | self.clear_irq_flags() 482 | 483 | # Enable TX 484 | self.write_register(NRF24.CONFIG, 485 | (self.read_register(NRF24.CONFIG) | NRF24.PWR_UP) & ~NRF24.PRIM_RX) 486 | 487 | # Enable pipe 0 for auto-ack 488 | self.write_register(NRF24.EN_RXADDR, self.read_register(NRF24.EN_RXADDR) | 1) 489 | 490 | def powerDown(self): 491 | self.write_register(NRF24.CONFIG, self.read_register(NRF24.CONFIG) & ~ NRF24.PWR_UP) 492 | 493 | def powerUp(self): 494 | self.write_register(NRF24.CONFIG, self.read_register(NRF24.CONFIG) | NRF24.PWR_UP) 495 | time.sleep(150e-6) 496 | 497 | def write(self, buf): 498 | self.last_error = None 499 | length = self.write_payload(buf) 500 | packet_time = ((1 + length + self.crc_length + self.address_length) * 8 + 9)/(self.data_rate_bits * 1000.) + 130e-6 501 | 502 | if self.auto_ack != 0: 503 | packet_time *= 2 504 | 505 | if self.retries != 0 and self.delay != 0: 506 | timeout = (packet_time + self.delay + 130e-6) * (self.retries + 1) 507 | else: 508 | timeout = packet_time * 2 # 2 is empiric 509 | 510 | self.ce(1) 511 | 512 | timeout += monotonic() 513 | while monotonic() < timeout: 514 | time.sleep(packet_time) 515 | status = self.get_status() 516 | if status & NRF24.TX_DS: 517 | self.ce(0) 518 | return True 519 | 520 | if status & NRF24.MAX_RT: 521 | self.last_error = 'MAX_RT' 522 | break 523 | 524 | self.ce(0) 525 | if self.last_error is None: 526 | self.last_error = 'TIMEOUT' 527 | 528 | self.flush_tx() # Avoid leaving the payload in tx fifo 529 | return False 530 | 531 | def startFastWrite(self, buf): 532 | """ 533 | Do not wait for CE HIGH->LOW 534 | """ 535 | # Send the payload 536 | self.write_payload(buf) 537 | 538 | self.ce(1) 539 | 540 | def startWrite(self, buf): 541 | # Send the payload 542 | self.write_payload(buf) 543 | 544 | # Allons! 545 | self.ce(1, 10e-6) 546 | 547 | def getDynamicPayloadSize(self): 548 | return self.spidev.xfer2([NRF24.R_RX_PL_WID, NRF24.NOP])[1] 549 | 550 | def available(self, pipe_num=None, irq_wait=False, irq_timeout=30000): 551 | status = self.get_status() 552 | result = False 553 | 554 | # Sometimes the radio specifies that there is data in one pipe but 555 | # doesn't set the RX flag... 556 | if status & NRF24.RX_DR or (status & NRF24.RX_P_NO_MASK != NRF24.RX_P_NO_MASK): 557 | result = True 558 | else: 559 | if irq_wait: # Will use IRQ wait 560 | if self.irqWait(irq_timeout): # Do we have a packet? 561 | status = self.get_status() # Seems like we do! 562 | if status & NRF24.RX_DR or (status & NRF24.RX_P_NO_MASK != NRF24.RX_P_NO_MASK): 563 | result = True 564 | 565 | 566 | if result and pipe_num is not None: 567 | del pipe_num[:] 568 | pipe_num.append((status & NRF24.RX_P_NO_MASK) >> NRF24.RX_P_NO) 569 | 570 | # Handle ack payload receipt 571 | if status & NRF24.TX_DS: 572 | self.write_register(NRF24.STATUS, NRF24.TX_DS) 573 | 574 | return result 575 | 576 | def read(self, buf, buf_len=-1): 577 | # Fetch the payload 578 | self.read_payload(buf, buf_len) 579 | 580 | # was this the last of the data available? 581 | return self.read_register(NRF24.FIFO_STATUS & NRF24.RX_EMPTY) 582 | 583 | def clear_irq_flags(self): 584 | self.write_register(NRF24.STATUS, NRF24.RX_DR | NRF24.TX_DS | NRF24.MAX_RT) 585 | 586 | def whatHappened(self): 587 | # Read the status & reset the status in one easy call 588 | # Or is that such a good idea? 589 | self.write_register(NRF24.STATUS, NRF24.RX_DR | NRF24.TX_DS | NRF24.MAX_RT) 590 | 591 | status = self.get_status() 592 | self.clear_irq_flags() 593 | 594 | # Report to the user what happened 595 | tx_ok = status & NRF24.TX_DS 596 | tx_fail = status & NRF24.MAX_RT 597 | rx_ready = status & NRF24.RX_DR 598 | return {'tx_ok': tx_ok, "tx_fail": tx_fail, "rx_ready": rx_ready} 599 | 600 | def openWritingPipe(self, value): 601 | # Note that the NRF24L01(+) 602 | # expects it LSB first. 603 | 604 | self.write_register(NRF24.RX_ADDR_P0, value) 605 | self.write_register(NRF24.TX_ADDR, value) 606 | if not self.dynamic_payloads_enabled: 607 | self.write_register(NRF24.RX_PW_P0, self.payload_size) 608 | 609 | def openReadingPipe(self, pipe, address): 610 | # If this is pipe 0, cache the address. This is needed because 611 | # openWritingPipe() will overwrite the pipe 0 address, so 612 | # startListening() will have to restore it. 613 | if pipe >= 6: 614 | raise RuntimeError("Invalid pipe number") 615 | if (pipe >= 2 and len(address) > 1) or len(address) > 5: 616 | raise RuntimeError("Invalid adress length") 617 | 618 | if pipe == 0: 619 | self.pipe0_reading_address = address 620 | 621 | self.write_register(NRF24.RX_ADDR_P0 + pipe, address) 622 | if not self.dynamic_payloads_enabled: 623 | self.write_register(NRF24.RX_PW_P0 + pipe, self.payload_size) 624 | 625 | # Note it would be more efficient to set all of the bits for all open 626 | # pipes at once. However, I thought it would make the calling code 627 | # more simple to do it this way. 628 | self.write_register(NRF24.EN_RXADDR, 629 | self.read_register(NRF24.EN_RXADDR) | (1 << pipe)) 630 | 631 | def closeReadingPipe(self, pipe): 632 | self.write_register(NRF24.EN_RXADDR, 633 | self.read_register(NRF24.EN_RXADDR) & ~(1 << pipe)) 634 | 635 | def toggle_features(self): 636 | buf = [NRF24.ACTIVATE, 0x73] 637 | self.spidev.xfer2(buf) 638 | 639 | def enableDynamicPayloads(self): 640 | # Enable dynamic payload throughout the system 641 | self.write_register(NRF24.FEATURE, self.read_register(NRF24.FEATURE) | NRF24.EN_DPL) 642 | 643 | # If it didn't work, the features are not enabled 644 | if not self.read_register(NRF24.FEATURE): 645 | # So enable them and try again 646 | self.toggle_features() 647 | self.write_register(NRF24.FEATURE, self.read_register(NRF24.FEATURE) | NRF24.EN_DPL) 648 | 649 | # Enable dynamic payload on all pipes 650 | 651 | # Not sure the use case of only having dynamic payload on certain 652 | # pipes, so the library does not support it. 653 | self.write_register(NRF24.DYNPD, self.read_register(NRF24.DYNPD) | 0b00111111) 654 | 655 | self.dynamic_payloads_enabled = True 656 | 657 | def enableAckPayload(self): 658 | # enable ack payload and dynamic payload features 659 | self.write_register(NRF24.FEATURE, 660 | self.read_register(NRF24.FEATURE) | NRF24.EN_ACK_PAY | NRF24.EN_DPL) 661 | 662 | # If it didn't work, the features are not enabled 663 | if not self.read_register(NRF24.FEATURE): 664 | # So enable them and try again 665 | self.toggle_features() 666 | self.write_register(NRF24.FEATURE, 667 | self.read_register(NRF24.FEATURE) | NRF24.EN_ACK_PAY | NRF24.EN_DPL) 668 | 669 | # Enable dynamic payload on pipes 0 & 1 670 | self.write_register(NRF24.DYNPD, self.read_register(NRF24.DYNPD) | NRF24.DPL_P1 | NRF24.DPL_P0) 671 | 672 | def writeAckPayload(self, pipe, buf, buf_len): 673 | txbuffer = [NRF24.W_ACK_PAYLOAD | (pipe & 0x7)] 674 | 675 | max_payload_size = 32 676 | data_len = min(buf_len, max_payload_size) 677 | txbuffer.extend(buf[0:data_len]) 678 | 679 | self.spidev.xfer2(txbuffer) 680 | 681 | def isAckPayloadAvailable(self): 682 | result = self.ack_payload_available 683 | self.ack_payload_available = False 684 | return result 685 | 686 | def isPVariant(self): 687 | return self.p_variant 688 | 689 | def setAutoAck(self, enable): 690 | if enable: 691 | self.write_register(NRF24.EN_AA, 0x3F) 692 | self.auto_ack = 0x3f 693 | if self.crc_length == 0: 694 | self.setCRCLength(NRF24.CRC_8) # Enhanced Shockburst requires at least 1 byte CRC 695 | else: 696 | self.auto_ack = 0 697 | self.write_register(NRF24.EN_AA, 0) 698 | 699 | def setAutoAckPipe(self, pipe, enable): 700 | if pipe <= 6: 701 | en_aa = self.read_register(NRF24.EN_AA) 702 | if enable: 703 | self.setCRCLength(NRF24.CRC_8) # Enhanced Shockburst requires at least 1 byte CRC 704 | en_aa |= 1 << pipe 705 | self.auto_ack |= 1 << pipe 706 | else: 707 | en_aa &= ~1 << pipe 708 | self.auto_ack &= ~1 << pipe 709 | 710 | self.write_register(NRF24.EN_AA, en_aa) 711 | 712 | def setAddressWidth(self, width): 713 | if width >= 2 and width <= 5: 714 | self.write_register(NRF24.SETUP_AW, width - 2) 715 | self.address_width = width 716 | 717 | def testCarrier(self): 718 | return self.read_register(NRF24.RPD) & 1 719 | 720 | def setPALevel(self, level): 721 | setup = self.read_register(NRF24.RF_SETUP) 722 | setup &= ~(NRF24.RF_PWR_LOW | NRF24.RF_PWR_HIGH) 723 | 724 | if level == NRF24.PA_MAX: 725 | setup |= NRF24.RF_PWR_LOW | NRF24.RF_PWR_HIGH 726 | elif level == NRF24.PA_HIGH: 727 | setup |= NRF24.RF_PWR_HIGH 728 | elif level == NRF24.PA_LOW: 729 | setup |= NRF24.RF_PWR_LOW 730 | elif level == NRF24.PA_MIN: 731 | pass 732 | elif level == NRF24.PA_ERROR: 733 | # On error, go to maximum PA 734 | setup |= NRF24.RF_PWR_LOW | NRF24.RF_PWR_HIGH 735 | 736 | self.write_register(NRF24.RF_SETUP, setup) 737 | 738 | def getPALevel(self): 739 | power = self.read_register(NRF24.RF_SETUP) & (NRF24.RF_PWR_LOW | NRF24.RF_PWR_HIGH) 740 | if power == (NRF24.RF_PWR_LOW | NRF24.RF_PWR_HIGH): 741 | return NRF24.PA_MAX 742 | elif power == NRF24.RF_PWR_HIGH: 743 | return NRF24.PA_HIGH 744 | elif power == NRF24.RF_PWR_LOW: 745 | return NRF24.PA_LOW 746 | else: 747 | return NRF24.PA_MIN 748 | 749 | def setDataRate(self, speed): 750 | setup = self.read_register(NRF24.RF_SETUP) 751 | setup &= ~(NRF24.RF_DR_LOW | NRF24.RF_DR_HIGH) 752 | 753 | if speed == NRF24.BR_250KBPS: 754 | # Must set the RF_DR_LOW to 1 RF_DR_HIGH (used to be RF_DR) is already 0 755 | # Making it '10'. 756 | self.data_rate_bits = 250 757 | self.data_rate = NRF24.BR_250KBPS 758 | setup |= NRF24.RF_DR_LOW 759 | elif speed == NRF24.BR_2MBPS: 760 | # Set 2Mbs, RF_DR (RF_DR_HIGH) is set 1 761 | # Making it '01' 762 | self.data_rate_bits = 2000 763 | self.data_rate = NRF24.BR_2MBPS 764 | setup |= NRF24.RF_DR_HIGH 765 | else: 766 | # 1Mbs 767 | self.data_rate_bits = 1000 768 | self.data_rate = NRF24.BR_1MBPS 769 | 770 | self.write_register(NRF24.RF_SETUP, setup) 771 | 772 | # Verify our result 773 | return self.read_register(NRF24.RF_SETUP) == setup 774 | 775 | def getDataRate(self): 776 | dr = self.read_register(NRF24.RF_SETUP) & (NRF24.RF_DR_LOW | NRF24.RF_DR_HIGH) 777 | # Order matters in our case below 778 | if dr == NRF24.RF_DR_LOW: 779 | # '10' = 250KBPS 780 | return NRF24.BR_250KBPS 781 | elif dr == NRF24.RF_DR_HIGH: 782 | # '01' = 2MBPS 783 | return NRF24.BR_2MBPS 784 | else: 785 | # '00' = 1MBPS 786 | return NRF24.BR_1MBPS 787 | 788 | def setCRCLength(self, length): 789 | config = self.read_register(NRF24.CONFIG) & ~(NRF24.EN_CRC | NRF24.CRCO) 790 | 791 | if length == NRF24.CRC_DISABLED: 792 | self.crc_length = 0 793 | elif length == NRF24.CRC_8: 794 | config |= NRF24.EN_CRC 795 | config &= ~NRF24.CRCO 796 | self.crc_length = 1 797 | else: 798 | config |= NRF24.EN_CRC 799 | config |= NRF24.CRCO 800 | self.crc_length = 2 801 | 802 | self.write_register(NRF24.CONFIG, config) 803 | 804 | def getCRCLength(self): 805 | result = NRF24.CRC_DISABLED 806 | config = self.read_register(NRF24.CONFIG) & (NRF24.CRCO | NRF24.EN_CRC) 807 | 808 | if config & NRF24.EN_CRC: 809 | if config & NRF24.CRCO: 810 | result = NRF24.CRC_16 811 | else: 812 | result = NRF24.CRC_8 813 | 814 | return result 815 | 816 | def disableCRC(self): 817 | disable = self.read_register(NRF24.CONFIG) & ~NRF24.EN_CRC 818 | self.write_register(NRF24.CONFIG, disable) 819 | 820 | def setRetries(self, delay, count): 821 | self.write_register(NRF24.SETUP_RETR, (delay & 0xf) << NRF24.ARD | (count & 0xf) << NRF24.ARC) 822 | self.delay = delay * 0.000250 823 | self.retries = count 824 | self.max_timeout = (self.payload_size / float(self.data_rate_bits) + self.delay) * self.retries 825 | self.timeout = (self.payload_size / float(self.data_rate_bits) + self.delay) 826 | 827 | def getRetries(self): 828 | return self.read_register(NRF24.SETUP_RETR) 829 | 830 | def getMaxTimeout(self): 831 | return self.max_timeout 832 | 833 | def getTimeout(self): 834 | return self.timeout 835 | 836 | def reset(self): 837 | """ Make sure the NRF is in the same state as after power up 838 | to avoid problems resulting from left over configuration 839 | from other programs.""" 840 | self.ce(0) 841 | reset_values = {0: 0x08, 1: 0x3F, 2: 0x02, 3: 0x03, 4: 0x03, 5: 0x02, 6: 0x06, 842 | 0x0a: [0xe7, 0xe7, 0xe7, 0xe7, 0xe7], 843 | 0x0b: [0xc2, 0xc2, 0xc2, 0xc2, 0xc2], 844 | 0x0c: 0xc3, 0x0d: 0xc4, 0x0e: 0xc5, 0x0f: 0xc6, 845 | 0x10: [0xe7, 0xe7, 0xe7, 0xe7, 0xe7], 846 | 0x11: 0, 0x12: 0, 0x13: 0, 0x14: 0, 0x15: 0, 0x16: 0, 847 | 0x1c: 0, 0x1d: 0} 848 | for reg, value in reset_values.items(): 849 | self.write_register(reg, value) 850 | 851 | self.flush_rx() 852 | self.flush_tx() 853 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from distutils.core import setup 4 | 5 | setup(name='nrf24', 6 | version='0.0.1', 7 | description='Python port of the RF24 library for NRF24L01+ radios', 8 | py_modules=['nrf24'], 9 | ) 10 | -------------------------------------------------------------------------------- /spi/BB-nRF24-SPI0-00A0.dts: -------------------------------------------------------------------------------- 1 | /* 2 | * Virtual cape for SPI0 on connector pins P9.22 P9.21 P9.18 P9.17 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | */ 8 | /dts-v1/; 9 | /plugin/; 10 | 11 | / { 12 | compatible = "ti,beaglebone", "ti,beaglebone-black"; 13 | 14 | /* identification */ 15 | part-number = "BB-nRF24-SPI0"; 16 | version = "00A0"; 17 | 18 | /* state the resources this cape uses */ 19 | exclusive-use = 20 | /* the pin header uses */ 21 | "P9.17", /* spi0_cs0 */ 22 | "P9.18", /* spi0_d1 */ 23 | "P9.21", /* spi0_d0 */ 24 | "P9.22", /* spi0_sclk */ 25 | /* the hardware ip uses */ 26 | "spi0"; 27 | 28 | fragment@0 { 29 | target = <&am33xx_pinmux>; 30 | __overlay__ { 31 | /* default state has all gpios released and mode set to uart1 */ 32 | bb_spi0_pins: pinmux_bb_spi0_pins { 33 | pinctrl-single,pins = < 34 | 0x150 0x30 /* spi0_sclk.spi0_sclk, INPUT_PULLUP | MODE0 */ 35 | 0x154 0x30 /* spi0_d0.spi0_d0, INPUT_PULLUP | MODE0 */ 36 | 0x158 0x10 /* spi0_d1.spi0_d1, OUTPUT_PULLUP | MODE0 */ 37 | 0x15c 0x10 /* spi0_cs0.spi0_cs0, OUTPUT_PULLUP | MODE0 */ 38 | >; 39 | }; 40 | }; 41 | }; 42 | 43 | fragment@1 { 44 | target = <&spi0>; /* spi0 is numbered correctly */ 45 | __overlay__ { 46 | status = "okay"; 47 | pinctrl-names = "default"; 48 | pinctrl-0 = <&bb_spi0_pins>; 49 | 50 | #address-cells = <1>; 51 | #size-cells = <0>; 52 | 53 | spidev: spidev@0{ 54 | #address-cells = <1>; 55 | #size-cells = <0>; 56 | 57 | compatible = "linux,spidev"; 58 | reg = <0>; 59 | spi-max-frequency = <10000000>; 60 | }; 61 | 62 | }; 63 | }; 64 | }; 65 | -------------------------------------------------------------------------------- /spi/README.md: -------------------------------------------------------------------------------- 1 | Intructions 2 | ==== 3 | 4 | Copy the file BB-nRF24-SPI0-00A0.dts to the BBB. 5 | Then compile it using the following command: 6 | 7 | dtc -O dtb -o BB-nRF24-SPI0-00A0.dtbo -b 0 -@ BB-nRF24-SPI0-00A0.dts 8 | 9 | This overlay is almost ready to be used. But first it must e copied 10 | to /lib/firmware 11 | 12 | cp BB-nRF24-SPI0-00A0.dtbo /lib/firmware 13 | 14 | If everything was done correctly, the overlay can be enabled by issuing: 15 | 16 | echo BB-nRF24-SPI0 > /sys/devices/bone_capemgr.8/slots 17 | 18 | This can be made "permanent" if the line above is inserted into 19 | /etc/rc.local 20 | 21 | A device should appear in /dev/spidev.1.0 22 | 23 | --------------------------------------------------------------------------------