Move default pins over to Getting Started defaults
[RF24-C.git] / RF24.h
blob9af58443a1f82b5d72fcff12366eb49c0f787f08
1 /*
2 Copyright (C) 2011 James Coliz, Jr. <maniacbug@ymail.com>
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 version 2 as published by the Free Software Foundation.
7 */
9 #ifndef __RF24_H__
10 #define __RF24_H__
12 #include <stddef.h>
13 #include <avr/pgmspace.h>
15 typedef enum { RF24_PA_MIN = 0,RF24_PA_LOW, RF24_PA_HIGH, RF24_PA_MAX, RF24_PA_ERROR } rf24_pa_dbm_e ;
16 typedef enum { RF24_1MBPS = 0, RF24_2MBPS, RF24_250KBPS } rf24_datarate_e;
17 typedef enum { RF24_CRC_DISABLED = 0, RF24_CRC_8, RF24_CRC_16 } rf24_crclength_e;
19 /**
20 * Driver for nRF24L01(+) 2.4GHz Wireless Transceiver
23 class RF24
25 private:
26 uint8_t ce_pin; /**< "Chip Enable" pin, activates the RX or TX role */
27 uint8_t csn_pin; /**< SPI Chip select */
28 bool wide_band; /* 2Mbs data rate in use? */
29 bool p_variant; /* False for RF24L01 and true for RF24L01P */
30 uint8_t payload_size; /**< Fixed size of payloads */
31 bool ack_payload_available; /**< Whether there is an ack payload waiting */
32 bool dynamic_payloads_enabled; /**< Whether dynamic payloads are enabled. */
33 uint8_t ack_payload_length; /**< Dynamic size of pending ack payload. */
34 uint64_t pipe0_reading_address; /**< Last address set on pipe 0 for reading. */
36 protected:
37 /**
38 * @name Low-level internal interface.
40 * Protected methods that address the chip directly. Regular users cannot
41 * ever call these. They are documented for completeness and for developers who
42 * may want to extend this class.
44 /**@{*/
46 /**
47 * Set chip select pin
49 * Running SPI bus at PI_CLOCK_DIV2 so we don't waste time transferring data
50 * and best of all, we make use of the radio's FIFO buffers. A lower speed
51 * means we're less likely to effectively leverage our FIFOs and pay a higher
52 * AVR runtime cost as toll.
54 * @param mode HIGH to take this unit off the SPI bus, LOW to put it on
56 void csn(int mode);
58 /**
59 * Set chip enable
61 * @param level HIGH to actively begin transmission or LOW to put in standby. Please see data sheet
62 * for a much more detailed description of this pin.
64 void ce(int level);
66 /**
67 * Read a chunk of data in from a register
69 * @param reg Which register. Use constants from nRF24L01.h
70 * @param buf Where to put the data
71 * @param len How many bytes of data to transfer
72 * @return Current value of status register
74 uint8_t read_register(uint8_t reg, uint8_t* buf, uint8_t len);
76 /**
77 * Read single byte from a register
79 * @param reg Which register. Use constants from nRF24L01.h
80 * @return Current value of register @p reg
82 uint8_t read_register(uint8_t reg);
84 /**
85 * Write a chunk of data to a register
87 * @param reg Which register. Use constants from nRF24L01.h
88 * @param buf Where to get the data
89 * @param len How many bytes of data to transfer
90 * @return Current value of status register
92 uint8_t write_register(uint8_t reg, const uint8_t* buf, uint8_t len);
94 /**
95 * Write a single byte to a register
97 * @param reg Which register. Use constants from nRF24L01.h
98 * @param value The new value to write
99 * @return Current value of status register
101 uint8_t write_register(uint8_t reg, uint8_t value);
104 * Write the transmit payload
106 * The size of data written is the fixed payload size, see getPayloadSize()
108 * @param buf Where to get the data
109 * @param len Number of bytes to be sent
110 * @return Current value of status register
112 uint8_t write_payload(const void* buf, uint8_t len);
115 * Read the receive payload
117 * The size of data read is the fixed payload size, see getPayloadSize()
119 * @param buf Where to put the data
120 * @param len Maximum number of bytes to read
121 * @return Current value of status register
123 uint8_t read_payload(void* buf, uint8_t len);
126 * Empty the receive buffer
128 * @return Current value of status register
130 uint8_t flush_rx(void);
133 * Empty the transmit buffer
135 * @return Current value of status register
137 uint8_t flush_tx(void);
140 * Retrieve the current status of the chip
142 * @return Current value of status register
144 uint8_t get_status(void);
147 * Decode and print the given status to stdout
149 * @param status Status value to print
151 * @warning Does nothing if stdout is not defined. See fdevopen in stdio.h
153 void print_status(uint8_t status);
156 * Decode and print the given 'observe_tx' value to stdout
158 * @param value The observe_tx value to print
160 * @warning Does nothing if stdout is not defined. See fdevopen in stdio.h
162 void print_observe_tx(uint8_t value);
165 * Print the name and value of an 8-bit register to stdout
167 * Optionally it can print some quantity of successive
168 * registers on the same line. This is useful for printing a group
169 * of related registers on one line.
171 * @param name Name of the register
172 * @param reg Which register. Use constants from nRF24L01.h
173 * @param qty How many successive registers to print
175 void print_byte_register(prog_char* name, uint8_t reg, uint8_t qty = 1);
178 * Print the name and value of a 40-bit address register to stdout
180 * Optionally it can print some quantity of successive
181 * registers on the same line. This is useful for printing a group
182 * of related registers on one line.
184 * @param name Name of the register
185 * @param reg Which register. Use constants from nRF24L01.h
186 * @param qty How many successive registers to print
188 void print_address_register(prog_char* name, uint8_t reg, uint8_t qty = 1);
191 * Turn on or off the special features of the chip
193 * The chip has certain 'features' which are only available when the 'features'
194 * are enabled. See the datasheet for details.
196 void toggle_features(void);
197 /**@}*/
199 public:
201 * @name Primary public interface
203 * These are the main methods you need to operate the chip
205 /**@{*/
208 * Constructor
210 * Creates a new instance of this driver. Before using, you create an instance
211 * and send in the unique pins that this chip is connected to.
213 * @param _cepin The pin attached to Chip Enable on the RF module
214 * @param _cspin The pin attached to Chip Select
216 RF24(uint8_t _cepin, uint8_t _cspin);
219 * Begin operation of the chip
221 * Call this in setup(), before calling any other methods.
223 void begin(void);
226 * Start listening on the pipes opened for reading.
228 * Be sure to call openReadingPipe() first. Do not call write() while
229 * in this mode, without first calling stopListening(). Call
230 * isAvailable() to check for incoming traffic, and read() to get it.
232 void startListening(void);
235 * Stop listening for incoming messages
237 * Do this before calling write().
239 void stopListening(void);
242 * Write to the open writing pipe
244 * Be sure to call openWritingPipe() first to set the destination
245 * of where to write to.
247 * This blocks until the message is successfully acknowledged by
248 * the receiver or the timeout/retransmit maxima are reached. In
249 * the current configuration, the max delay here is 60ms.
251 * The maximum size of data written is the fixed payload size, see
252 * getPayloadSize(). However, you can write less, and the remainder
253 * will just be filled with zeroes.
255 * @param buf Pointer to the data to be sent
256 * @param len Number of bytes to be sent
257 * @return True if the payload was delivered successfully false if not
259 bool write( const void* buf, uint8_t len );
262 * Test whether there are bytes available to be read
264 * @return True if there is a payload available, false if none is
266 bool available(void);
269 * Read the payload
271 * Return the last payload received
273 * The size of data read is the fixed payload size, see getPayloadSize()
275 * @note I specifically chose 'void*' as a data type to make it easier
276 * for beginners to use. No casting needed.
278 * @param buf Pointer to a buffer where the data should be written
279 * @param len Maximum number of bytes to read into the buffer
280 * @return True if the payload was delivered successfully false if not
282 bool read( void* buf, uint8_t len );
285 * Open a pipe for writing
287 * Only one pipe can be open at once, but you can change the pipe
288 * you'll listen to. Do not call this while actively listening.
289 * Remember to stopListening() first.
291 * Addresses are 40-bit hex values, e.g.:
293 * @code
294 * openWritingPipe(0xF0F0F0F0F0);
295 * @endcode
297 * @param address The 40-bit address of the pipe to open. This can be
298 * any value whatsoever, as long as you are the only one writing to it
299 * and only one other radio is listening to it. Coordinate these pipe
300 * addresses amongst nodes on the network.
302 void openWritingPipe(uint64_t address);
305 * Open a pipe for reading
307 * Up to 6 pipes can be open for reading at once. Open all the
308 * reading pipes, and then call startListening().
310 * @see openWritingPipe
312 * @warning Pipes 1-5 should share the first 32 bits.
313 * Only the least significant byte should be unique, e.g.
314 * @code
315 * openReadingPipe(1,0xF0F0F0F0AA);
316 * openReadingPipe(2,0xF0F0F0F066);
317 * @endcode
319 * @warning Pipe 0 is also used by the writing pipe. So if you open
320 * pipe 0 for reading, and then startListening(), it will overwrite the
321 * writing pipe. Ergo, do an openWritingPipe() again before write().
323 * @todo Enforce the restriction that pipes 1-5 must share the top 32 bits
325 * @param number Which pipe# to open, 0-5.
326 * @param address The 40-bit address of the pipe to open.
328 void openReadingPipe(uint8_t number, uint64_t address);
330 /**@}*/
332 * @name Optional Configurators
334 * Methods you can use to get or set the configuration of the chip.
335 * None are required. Calling begin() sets up a reasonable set of
336 * defaults.
338 /**@{*/
340 * Set the number and delay of retries upon failed submit
342 * @param delay How long to wait between each retry, in multiples of 250us,
343 * max is 15. 0 means 250us, 15 means 4000us.
344 * @param count How many retries before giving up, max 15
346 void setRetries(uint8_t delay, uint8_t count);
349 * Set RF communication channel
351 * @param channel Which RF channel to communicate on, 0-127
353 void setChannel(uint8_t channel);
356 * Set Static Payload Size
358 * This implementation uses a pre-stablished fixed payload size for all
359 * transmissions. If this method is never called, the driver will always
360 * transmit the maximum payload size (32 bytes), no matter how much
361 * was sent to write().
363 * @todo Implement variable-sized payloads feature
365 * @param size The number of bytes in the payload
367 void setPayloadSize(uint8_t size);
370 * Get Static Payload Size
372 * @see setPayloadSize()
374 * @return The number of bytes in the payload
376 uint8_t getPayloadSize(void);
379 * Get Dynamic Payload Size
381 * For dynamic payloads, this pulls the size of the payload off
382 * the chip
384 * @return Payload length of last-received dynamic payload
386 uint8_t getDynamicPayloadSize(void);
389 * Enable custom payloads on the acknowledge packets
391 * Ack payloads are a handy way to return data back to senders without
392 * manually changing the radio modes on both units.
394 * @see examples/pingpair_pl/pingpair_pl.pde
396 void enableAckPayload(void);
399 * Enable dynamically-sized payloads
401 * This way you don't always have to send large packets just to send them
402 * once in a while. This enables dynamic payloads on ALL pipes.
404 * @see examples/pingpair_pl/pingpair_dyn.pde
406 void enableDynamicPayloads(void);
409 * Determine whether the hardware is an nRF24L01+ or not.
411 * @return true if the hardware is nRF24L01+ (or compatible) and false
412 * if its not.
414 bool isPVariant(void) ;
417 * Enable or disable auto-acknowlede packets
419 * This is enabled by default, so it's only needed if you want to turn
420 * it off for some reason.
422 * @param enable Whether to enable (true) or disable (false) auto-acks
424 void setAutoAck(bool enable);
427 * Enable or disable auto-acknowlede packets on a per pipeline basis.
429 * AA is enabled by default, so it's only needed if you want to turn
430 * it off/on for some reason on a per pipeline basis.
432 * @param pipe Which pipeline to modify
433 * @param enable Whether to enable (true) or disable (false) auto-acks
435 void setAutoAck( uint8_t pipe, bool enable ) ;
438 * Set Power Amplifier (PA) level to one of four levels.
439 * Relative mnemonics have been used to allow for future PA level
440 * changes. According to 6.5 of the nRF24L01+ specification sheet,
441 * they translate to: RF24_PA_MIN=-18dBm, RF24_PA_LOW=-12dBm,
442 * RF24_PA_MED=-6dBM, and RF24_PA_HIGH=0dBm.
444 * @param level Desired PA level.
446 void setPALevel( rf24_pa_dbm_e level ) ;
449 * Fetches the current PA level.
451 * @return Returns a value from the rf24_pa_dbm_e enum describing
452 * the current PA setting. Please remember, all values represented
453 * by the enum mnemonics are negative dBm. See setPALevel for
454 * return value descriptions.
456 rf24_pa_dbm_e getPALevel( void ) ;
459 * Set the transmission data rate
461 * @warning setting RF24_250KBPS will fail for non-plus units
463 * @param speed RF24_250KBPS for 250kbs, RF24_1MBPS for 1Mbps, or RF24_2MBPS for 2Mbps
464 * @return true if the change was successful
466 bool setDataRate(rf24_datarate_e speed);
469 * Fetches the transmission data rate
471 * @return Returns the hardware's currently configured datarate. The value
472 * is one of 250kbs, RF24_1MBPS for 1Mbps, or RF24_2MBPS, as defined in the
473 * rf24_datarate_e enum.
475 rf24_datarate_e getDataRate( void ) ;
478 * Set the CRC length
480 * @param length RF24_CRC_8 for 8-bit or RF24_CRC_16 for 16-bit
482 void setCRCLength(rf24_crclength_e length);
485 * Get the CRC length
487 * @return RF24_DISABLED if disabled or RF24_CRC_8 for 8-bit or RF24_CRC_16 for 16-bit
489 rf24_crclength_e getCRCLength(void);
492 * Disable CRC validation
495 void disableCRC( void ) ;
497 /**@}*/
499 * @name Advanced Operation
501 * Methods you can use to drive the chip in more advanced ways
503 /**@{*/
506 * Print a giant block of debugging information to stdout
508 * @warning Does nothing if stdout is not defined. See fdevopen in stdio.h
510 void printDetails(void);
513 * Enter low-power mode
515 * To return to normal power mode, either write() some data or
516 * startListening, or powerUp().
518 void powerDown(void);
521 * Leave low-power mode - making radio more responsive
523 * To return to low power mode, call powerDown().
525 void powerUp(void) ;
528 * Test whether there are bytes available to be read
530 * Use this version to discover on which pipe the message
531 * arrived.
533 * @param[out] pipe_num Which pipe has the payload available
534 * @return True if there is a payload available, false if none is
536 bool available(uint8_t* pipe_num);
539 * Non-blocking write to the open writing pipe
541 * Just like write(), but it returns immediately. To find out what happened
542 * to the send, catch the IRQ and then call whatHappened().
544 * @see write()
545 * @see whatHappened()
547 * @param buf Pointer to the data to be sent
548 * @param len Number of bytes to be sent
549 * @return True if the payload was delivered successfully false if not
551 void startWrite( const void* buf, uint8_t len );
554 * Write an ack payload for the specified pipe
556 * The next time a message is received on @p pipe, the data in @p buf will
557 * be sent back in the acknowledgement.
559 * @warning According to the data sheet, only three of these can be pending
560 * at any time. I have not tested this.
562 * @param pipe Which pipe# (typically 1-5) will get this response.
563 * @param buf Pointer to data that is sent
564 * @param len Length of the data to send, up to 32 bytes max. Not affected
565 * by the static payload set by setPayloadSize().
567 void writeAckPayload(uint8_t pipe, const void* buf, uint8_t len);
570 * Determine if an ack payload was received in the most recent call to
571 * write().
573 * Call read() to retrieve the ack payload.
575 * @warning Calling this function clears the internal flag which indicates
576 * a payload is available. If it returns true, you must read the packet
577 * out as the very next interaction with the radio, or the results are
578 * undefined.
580 * @return True if an ack payload is available.
582 bool isAckPayloadAvailable(void);
585 * Call this when you get an interrupt to find out why
587 * Tells you what caused the interrupt, and clears the state of
588 * interrupts.
590 * @param[out] tx_ok The send was successful (TX_DS)
591 * @param[out] tx_fail The send failed, too many retries (MAX_RT)
592 * @param[out] rx_ready There is a message waiting to be read (RX_DS)
594 void whatHappened(bool& tx_ok,bool& tx_fail,bool& rx_ready);
597 * Test whether there was a carrier on the line for the
598 * previous listening period.
600 * Useful to check for interference on the current channel.
602 * @return true if was carrier, false if not
604 bool testCarrier(void);
607 * Test whether a signal (carrier or otherwise) greater than
608 * or equal to -64dBm is present on the channel. Valid only
609 * on nRF24L01P (+) hardware. On nRF24L01, use testCarrier().
611 * Useful to check for interference on the current channel and
612 * channel hopping strategies.
614 * @return true if signal => -64dBm, false if not
616 bool testRPD(void) ;
618 /**@}*/
622 * @example GettingStarted.pde
624 * This is an example which corresponds to my "Getting Started" blog post
625 * for Getting Started with nRF24L01+ radios.
627 * It is an example of how to use the RF24 class. Write this sketch to two
628 * different nodes. Put one of the nodes into 'transmit' mode by connecting
629 * with the serial monitor and sending a 'T'. The ping node sends the current
630 * time to the pong node, which responds by sending the value back. The ping
631 * node can then see how long the whole cycle took.
635 * @example led_remote.pde
637 * This is an example of how to use the RF24 class to control a remote
638 * bank of LED's using buttons on a remote control.
640 * Every time the buttons change on the remote, the entire state of
641 * buttons is send to the led board, which displays the state.
645 * @example pingpair.pde
647 * This is an example of how to use the RF24 class. Write this sketch to two
648 * different nodes, connect the role_pin to ground on one. The ping node sends
649 * the current time to the pong node, which responds by sending the value back.
650 * The ping node can then see how long the whole cycle took.
654 * @example starping.pde
656 * This sketch is a more complex example of using the RF24 library for Arduino.
657 * Deploy this on up to six nodes. Set one as the 'pong receiver' by tying the
658 * role_pin low, and the others will be 'ping transmit' units. The ping units
659 * unit will send out the value of millis() once a second. The pong unit will
660 * respond back with a copy of the value. Each ping unit can get that response
661 * back, and determine how long the whole cycle took.
663 * This example requires a bit more complexity to determine which unit is which.
664 * The pong receiver is identified by having its role_pin tied to ground.
665 * The ping senders are further differentiated by a byte in eeprom.
669 * @example pingpair_pl.pde
671 * This is an example of how to do two-way communication without changing
672 * transmit/receive modes. Here, a payload is set to the transmitter within
673 * the Ack packet of each transmission. Note that the payload is set BEFORE
674 * the sender's message arrives.
678 * @example pingpair_irq.pde
680 * This is an example of how to user interrupts to interact with the radio.
681 * It builds on the pingpair_pl example, and uses ack payloads.
685 * @example pingpair_sleepy.pde
687 * This is an example of how to use the RF24 class to create a battery-
688 * efficient system. It is just like the pingpair.pde example, but the
689 * ping node powers down the radio and sleeps the MCU after every
690 * ping/pong cycle.
694 * @example scanner.pde
696 * Example to detect interference on the various channels available.
697 * This is a good diagnostic tool to check whether you're picking a
698 * good channel for your application.
700 * Inspired by cpixip.
701 * See http://arduino.cc/forum/index.php/topic,54795.0.html
705 * @mainpage Driver for nRF24L01(+) 2.4GHz Wireless Transceiver
707 * Design Goals: This library is designed to be...
708 * @li Maximally compliant with the intended operation of the chip
709 * @li Easy for beginners to use
710 * @li Consumed with a public interface that's similiar to other Arduino standard libraries
711 * @li Built against the standard SPI library.
713 * Please refer to:
715 * @li <a href="http://maniacbug.github.com/RF24/">Documentation Main Page</a>
716 * @li <a href="http://maniacbug.github.com/RF24/classRF24.html">RF24 Class Documentation</a>
717 * @li <a href="https://github.com/maniacbug/RF24/">Source Code</a>
718 * @li <a href="https://github.com/maniacbug/RF24/archives/master">Downloads Page</a>
719 * @li <a href="http://www.nordicsemi.com/files/Product/data_sheet/nRF24L01_Product_Specification_v2_0.pdf">Chip Datasheet</a>
721 * This chip uses the SPI bus, plus two chip control pins. Remember that pin 10 must still remain an output, or
722 * the SPI hardware will go into 'slave' mode.
724 * @section More More Information
726 * @subpage FAQ
729 #endif // __RF24_H__
730 // vim:ai:cin:sts=2 sw=2 ft=cpp