RF22
RF22.h
1 // RF22.h
2 // Author: Mike McCauley (mikem@airspayce.com)
3 // Copyright (C) 2011 Mike McCauley
4 // $Id: RF22.h,v 1.23 2013/02/06 21:33:56 mikem Exp mikem $
5 //
6 /// \mainpage RF22 library for Arduino
7 ///
8 /// This is the Arduino RF22 library.
9 /// It provides an object-oriented interface for sending and receiving data messages with Hope-RF
10 /// RF22B based radio modules, and compatible chips and modules,
11 /// including the RFM22B transceiver module such as
12 /// this bare module: http://www.sparkfun.com/products/10153
13 /// and this shield: http://www.sparkfun.com/products/11018
14 ///
15 /// RF22 also supports some of the features of ZigBee and XBee,
16 /// (such as mesh routing and automatic route discovery),
17 /// but with a much less complicated system and less expensive radios.
18 ///
19 /// The Hope-RF (http://www.hoperf.com) RFM22B (http://www.hoperf.com/rf_fsk/fsk/RFM22B.htm)
20 /// is a low-cost ISM transceiver module. It supports FSK, GFSK, OOK over a wide
21 /// range of frequencies and programmable data rates.
22 ///
23 /// This library provides functions for sending and receiving messages of up to 255 octets on any
24 /// frequency supported by the RF22B, in a range of predefined data rates and frequency deviations.
25 /// Frequency can be set with 312Hz precision to any frequency from 240.0MHz to 960.0MHz.
26 ///
27 /// Up to 2 RF22B modules can be connected to an Arduino, permitting the construction of translators
28 /// and frequency changers, etc.
29 ///
30 /// This library provides classes for
31 /// - RF22: unaddressed, unreliable messages
32 /// - RF22Datagram: addressed, unreliable messages
33 /// - RF22ReliableDatagram: addressed, reliable, retransmitted, acknowledged messages.
34 /// - RF22Router: multi hop delivery from source node to destination node via 0 or more intermediate nodes
35 /// - RF22Mesh: multi hop delivery with automatic route discovery and rediscovery.
36 ///
37 /// The following modulation types are suppported with a range of modem configurations for
38 /// common data rates and frequency deviations:
39 /// - GFSK Gaussian Frequency Shift Keying
40 /// - FSK Frequency Shift Keying
41 /// - OOK On-Off Keying
42 ///
43 /// Support for other RF22B features such as on-chip temperature measurement, analog-digital
44 /// converter, transmitter power control etc is also provided.
45 ///
46 /// The latest version of this documentation can be downloaded from
47 /// http://www.airspayce.com/mikem/arduino/RF22
48 ///
49 /// Example Arduino programs are included to show the main modes of use.
50 ///
51 /// The version of the package that this documentation refers to can be downloaded
52 /// from http://www.airspayce.com/mikem/arduino/RF22/RF22-1.32.zip
53 /// You can find the latest version at http://www.airspayce.com/mikem/arduino/RF22
54 ///
55 /// You can also find online help and disussion at http://groups.google.com/group/rf22-arduino
56 /// Please use that group for all questions and discussions on this topic.
57 /// Do not contact the author directly, unless it is to discuss commercial licensing.
58 ///
59 /// Tested on Arduino Diecimila and Mega with arduino-0021
60 /// on OpenSuSE 11.1 and avr-libc-1.6.1-1.15,
61 /// cross-avr-binutils-2.19-9.1, cross-avr-gcc-4.1.3_20080612-26.5.
62 /// With HopeRF RFM22 modules that appear to have RF22B chips on board:
63 /// - Device Type Code = 0x08 (RX/TRX)
64 /// - Version Code = 0x06
65 /// Works on Duo. Works with Sparkfun RFM22 Wireless shields.
66 /// Works with Arduino 1.0 to at least 1.0.4
67 ///
68 /// \par Packet Format
69 ///
70 /// All messages sent and received by this RF22 library must conform to this packet format:
71 ///
72 /// - 8 nibbles (4 octets) PREAMBLE
73 /// - 2 octets SYNC 0x2d, 0xd4
74 /// - 4 octets HEADER: (TO, FROM, ID, FLAGS)
75 /// - 1 octet LENGTH (0 to 255), number of octets in DATA
76 /// - 0 to 255 octets DATA
77 /// - 2 octets CRC computed with CRC16(IBM), computed on HEADER, LENGTH and DATA
78 ///
79 /// For technical reasons, the message format is not compatible with the
80 /// 'HopeRF Radio Transceiver Message Library for Arduino' http://www.airspayce.com/mikem/arduino/HopeRF from the same author. Nor is it compatible with
81 /// 'Virtual Wire' http://www.airspayce.com/mikem/arduino/VirtualWire.pdf also from the same author.
82 ///
83 /// \par Connecting RFM-22 to Arduino
84 ///
85 /// If you have the Sparkfun RFM22 Shield (https://www.sparkfun.com/products/11018)
86 /// the connections described below are done for you on the shield, no changes required,
87 /// just add headers and plug it in to an Arduino (but not and Arduino Mega, see below)
88 ///
89 /// The physical connection between the RF22B and the Arduino require 3.3V, the 3 x SPI pins (SCK, SDI, SDO),
90 /// a Slave Select pin and an interrupt pin.
91 /// Note also that on the RFF22B, it is required to control the TX_ANT and X_ANT pins of the RFM22 in order to enable the
92 /// antenna connection. The RF22 library is configured so that GPIO0 and GPIO1 outputs can control TX_ANT and RX_ANT input pins
93 /// automatically. You must connect GPIO0 to TX_ANT and GPIO1 to RX_ANT for this automatic antenna switching to occur.
94 ///
95 /// Connect the RFM-22 to most Arduino's like this (Caution, Arduino Mega has different pins for SPI,
96 /// see below):
97 /// \code
98 /// Arduino RFM-22B
99 /// GND----------GND-\ (ground in)
100 /// SDN-/ (shutdown in)
101 /// 3V3----------VCC (3.3V in)
102 /// interrupt 0 pin D2-----------NIRQ (interrupt request out)
103 /// SS pin D10----------NSEL (chip select in)
104 /// SCK pin D13----------SCK (SPI clock in)
105 /// MOSI pin D11----------SDI (SPI Data in)
106 /// MISO pin D12----------SDO (SPI data out)
107 /// /--GPIO0 (GPIO0 out to control transmitter antenna TX_ANT
108 /// \--TX_ANT (TX antenna control in)
109 /// /--GPIO1 (GPIO1 out to control receiver antenna RX_ANT
110 /// \--RX_ANT (RX antenna control in)
111 /// \endcode
112 /// For an Arduino Mega:
113 /// \code
114 /// Mega RFM-22B
115 /// GND----------GND-\ (ground in)
116 /// SDN-/ (shutdown in)
117 /// 3V3----------VCC (3.3V in)
118 /// interrupt 0 pin D2-----------NIRQ (interrupt request out)
119 /// SS pin D53----------NSEL (chip select in)
120 /// SCK pin D52----------SCK (SPI clock in)
121 /// MOSI pin D51----------SDI (SPI Data in)
122 /// MISO pin D50----------SDO (SPI data out)
123 /// /--GPIO0 (GPIO0 out to control transmitter antenna TX_ANT
124 /// \--TX_ANT (TX antenna control in)
125 /// /--GPIO1 (GPIO1 out to control receiver antenna RX_ANT
126 /// \--RX_ANT (RX antenna control in)
127 /// \endcode
128 /// and you can then use the default constructor RF22().
129 /// You can override the default settings for the SS pin and the interrupt
130 /// in the RF22 constructor if you wish to connect the slave select SS to other than the normal one for your
131 /// Arduino (D10 for Diecimila, Uno etc and D53 for Mega)
132 /// or the interrupt request to other than pin D2.
133 ///
134 /// It is possible to have 2 radios connected to one arduino, provided each radio has its own
135 /// SS and interrupt line (SCK, SDI and SDO are common to both radios)
136 ///
137 /// Caution: on some Arduinos such as the Mega 2560, if you set the slave select pin to be other than the usual SS
138 /// pin (D53 on Mega 2560), you may need to set the usual SS pin to be an output to force the Arduino into SPI
139 /// master mode.
140 ///
141 /// Caution: Power supply requirements of the RF22 module may be relevant in some circumstances:
142 /// RF22 modules are capable of pulling 80mA+ at full power, where Arduino's 3.3V line can
143 /// give 50mA. You may need to make provision for alternate power supply for
144 /// the RF22, especially if you wish to use full transmit power, and/or you have
145 /// other shields demanding power. Inadequate power for the RF22 is reported to cause symptoms such as:
146 /// - reset's/bootups terminate with "init failed" messages
147 /// -random termination of communication after 5-30 packets sent/received
148 /// -"fake ok" state, where initialization passes fluently, but communication doesn't happen
149 /// -shields hang Arduino boards, especially during the flashing
150 ///
151 /// Caution: some RF22 breakout boards (such as the HAB-RFM22B-BOA HAB-RFM22B-BO) reportedly
152 /// have the TX_ANT and RX_ANT pre-connected to GPIO0 and GPIO1 round the wrong way. You can work with this
153 /// if you edit RF22.cpp and change the code that does spiWrite(RF22_REG_0B_GPIO_CONFIGURATION0, 0x12).
154 /// See the comments there
155 ///
156 /// Caution: If you are using a bare RF22 module without IO level shifters, you may have difficulty connecting
157 /// to a 5V arduino. The RF22 module is 3.3V and its IO pins are 3.3V not 5V. Some Arduinos (Diecimila and
158 /// Uno) seem to work OK with this, and some (Mega) do not always work reliably. Your Mileage May Vary.
159 /// For best result, use level shifters, or use a RF22 shield or board with level shifters built in,
160 /// such as the Sparkfun RFM22 shield http://www.sparkfun.com/products/11018.
161 /// You could also use a 3.3V IO Arduino such as a Pro.
162 /// It is recognised that it is difficult to connect
163 /// the Sparkfun RFM22 shield to a Mega, since the SPI pins on the Mega are different to other Arduinos,
164 /// But it is possible, by bending the SPI pins (D10, D11, D12, D13) on the
165 /// shield out of the way before plugging it in to the Mega and jumpering the shield pins to the Mega like this:
166 /// \code
167 /// RF22 Shield Mega
168 /// D10 D53
169 /// D13 D52
170 /// D11 D51
171 /// D12 D50
172 /// \endcode
173 ///
174 /// \par Interrupts
175 ///
176 /// The RF22 library uses interrupts to react to events in the RF22 module,
177 /// such as the reception of a new packet, or the completion of transmission of a packet.
178 /// The RF22 library interrupt service routine reads status from and writes data
179 /// to the the RF22 module via the SPI interface. It is very important therefore,
180 /// that if you are using the RF22 library with another SPI based deviced, that you
181 /// disable interrupts while you transfer data to and from that other device.
182 /// Use cli() to disable interrupts and sei() to reenable them.
183 ///
184 /// \par Memory
185 ///
186 /// The RF22 library requires non-trivial amounts of memory. The sample programs above all compile to
187 /// about 9 to 14kbytes each, which will fit in the flash proram memory of most Arduinos. However,
188 /// the RAM requirements are more critical. Most sample programs above will run on Duemilanova,
189 /// but not on Diecimila. Even on Duemilanova, the RAM requirements are very close to the
190 /// available memory of 2kbytes. Therefore, you should be vary sparing with RAM use in programs that use
191 /// the RF22 library on Duemilanova.
192 ///
193 /// The sample RF22Router and RF22Mesh programs compile to about 14kbytes,
194 /// and require more RAM than the others.
195 /// They will not run on Duemilanova or Diecimila, but will run on Arduino Mega.
196 ///
197 /// It is often hard to accurately identify when you are hitting RAM limits on Arduino.
198 /// The symptoms can include:
199 /// - Mysterious crashes and restarts
200 /// - Changes in behaviour when seemingly unrelated changes are made (such as adding print() statements)
201 /// - Hanging
202 /// - Output from Serial.print() not appearing
203 ///
204 /// With an Arduino Mega, with 8 kbytes of SRAM, there is much more RAM headroom for
205 /// your own elaborate programs.
206 /// This library is reported to work with Arduino Pro Mini, but that has not been tested by me.
207 ///
208 /// The Arduino UNO is now known to work with RF22.
209 ///
210 /// \par Automatic Frequency Control (AFC)
211 ///
212 /// The RF22M modules use an inexpensive crystal to control the frequency synthesizer, and therfore you can expect
213 /// the transmitter and receiver frequencies to be subject to the usual inaccuracies of such crystals. The RF22
214 /// contains an AFC circuit to compensate for differences in transmitter and receiver frequencies.
215 /// It does this by altering the receiver frequency during reception by up to the pull-in frequency range.
216 /// This RF22 library enables the AFC and by default sets the pull-in frequency range to
217 /// 0.05MHz, which should be sufficient to handle most situations. However, if you observe unexplained packet losses
218 /// or failure to operate correctly all the time it may be because your modules have a wider frequency difference, and
219 /// you may need to set the afcPullInRange to a differentvalue, using setFrequency();
220 ///
221 /// \par Performance
222 ///
223 /// Some simple speed performance tests have been conducted.
224 /// In general packet transmission rate will be limited by the modulation scheme.
225 /// Also, if your code does any slow operations like Serial printing it will also limit performance.
226 /// We disabled any printing in the tests below.
227 /// We tested with RF22::GFSK_Rb125Fd125, which is probably the fastest scheme available.
228 /// We tested with a 13 octet message length, over a very short distance of 10cm.
229 ///
230 /// Transmission (no reply) tests with modulation RF22::GFSK_Rb125Fd125 and a
231 /// 13 octet message show about 330 messages per second transmitted.
232 ///
233 /// Transmit-and-wait-for-a-reply tests with modulation RF22::GFSK_Rb125Fd125 and a
234 /// 13 octet message (send and receive) show about 160 round trips per second.
235 ///
236 /// \par Installation
237 ///
238 /// Install in the usual way: unzip the distribution zip file to the libraries
239 /// sub-folder of your sketchbook.
240 ///
241 /// This software is Copyright (C) 2011 Mike McCauley. Use is subject to license
242 /// conditions. The main licensing options available are GPL V2 or Commercial:
243 ///
244 /// \par Open Source Licensing GPL V2
245 ///
246 /// This is the appropriate option if you want to share the source code of your
247 /// application with everyone you distribute it to, and you also want to give them
248 /// the right to share who uses it. If you wish to use this software under Open
249 /// Source Licensing, you must contribute all your source code to the open source
250 /// community in accordance with the GPL Version 2 when your application is
251 /// distributed. See http://www.gnu.org/copyleft/gpl.html
252 ///
253 /// \par Commercial Licensing
254 ///
255 /// This is the appropriate option if you are creating proprietary applications
256 /// and you are not prepared to distribute and share the source code of your
257 /// application. Contact info@airspayce.com for details.
258 ///
259 /// \par Revision History
260 ///
261 /// \version 1.0 Initial release
262 ///
263 /// \version 1.1 Added rf22_snoop and rf22_specan examples
264 ///
265 /// \version 1.2 Changed default modulation to FSK_Rb2_4Fd36
266 /// Some internal reorganisation.
267 /// Added RF22Router and RF22Mesh classes plus sample programs to support multi-hop and
268 /// automatic route discovery.
269 /// \version 1.3 Removed some unnecessary debug messages. Added virtual doArp and isPhysicalAddress
270 /// functions to RF22Mesh to support other physical address interpretation schemes (IPV4/IPV6?)
271 /// \version 1.4 RF22Router and RF22Mesh were inadvertently left out of the distro.
272 /// \version 1.5 Improvements contributed by Peter Mousley: Modem config table is now in flash rather than SRAM,
273 /// saving 400 bytes of SRAM. Allow a user-defined buffer size. Thanks Peter.
274 /// \version 1.6 Fixed some minor typos on doc and clarified that this code is for the RF22B. Fixed errors in the
275 /// definition of the power output constants which were incorrectly set to the values for the RF22.
276 /// Reported by Fred Slamen. If you were using a previous version of RF22, you probably were not getting the output
277 /// power you thought.
278 /// \version 1.7 Added code to initialise GPIO0 and GPIO1 so they can automatically control the TX_ANT and RX_ANT
279 /// antenna switching inputs. You must connect GPIO0 to TX_ANT and GPIO1 to RX_ANT for this automatic
280 /// antenna switching to occur. Updated doc to reflect this new connection requirement
281 /// \version 1.8 Changed the name of RF22_ENLBD in RF22_REG_06_INTERRUPT_ENABLE2 to RF22_ENLBDI because it collided
282 /// with a define of the same name in RF22_REG_07_OPERATING_MODE. RF22_REG_05_INTERRUPT_ENABLE1 enable mask
283 /// incorrectly used RF22_IFFERROR instead of RF22_ENFFERR. Reported by Steffan Woltjer.
284 /// \version 1.9 Fixed typos in RF22_REG_21_CLOCk*. Reported by Steffan Woltjer.
285 /// \version 1.10 Fixed a problem where a IFFERR during transmission could cause an infinite loop and a hang.
286 /// Reported by Raymond Gilbert.
287 /// \version 1.11 Fixed an innocuous typo in RF22::handleInterrupt. Reported by Zhentao.
288 ///
289 /// \version 1.12 Improvements to RF22::init from Guy Molinari to improve compatibility with some
290 /// Arduinos. Now reported to be working with official Mega 2560 and Uno.
291 /// Updated so compiles on Arduino 1.0.
292 ///
293 /// \version 1.13 Announce google support group
294 ///
295 /// \version 1.14 Added definitions for bits and masks in RF22_REG_1D_AFC_LOOP_GEARSHIFT_OVERRIDE
296 /// and RF22_REG_1E_AFC_TIMING_CONTROL
297 ///
298 /// \version 1.15 Small alterations to initialisation code so that SS pin is not set to output: may cause
299 /// interference with other devices connected to the Arduino. Testing with Uno: OK.
300 ///
301 /// \version 1.16 Fixed a problem that prevented building with arduino 0021
302 ///
303 /// \version 1.17 Added optional AFC pull-in frequency range argument to setFrequency().
304 /// Default AFC pull-in range set to 0.05MHz
305 ///
306 /// \version 1.18 Changed default value for slave slect pin in constructor to be SS, ie the normal one for
307 /// the compiled Arduino (D10 for Diecimila, Uno etc and D53 for Mega). This is because some Arduinos such as Mega 2560
308 /// reportedly use the type of the SS pin to determine whether to run in slave or master mode. Therfore it
309 /// is preferred that the slave select pin actually be the normal SS pin.
310 ///
311 /// \version 1.19 Added new mode() function.
312 /// Fixed a potential race condition in RF22Datagram::recvfrom which might cause corrupt from, to, id or flags
313 /// under extreme circumstances. Improvements to interrupt hygeine by adding cli()_/sei() around all
314 /// RF22 register acceses. Found that 0 length transmit packets confuses the RF22, so they are now forbidden.
315 /// Added IPGateway example, which routes UDP messages from an internet connection using an
316 /// Ethernet Shield and sends them
317 /// to a radio whose ID is based on the UDP port. Replies are sent back to the originating UDP
318 /// address and port.
319 ///
320 /// \version 1.20 _mode is now volatile.
321 /// RF22::send() now waits until any previous transmission is complete before sending.
322 /// RF22::waitPacketSent() now waits for the RF22 to not be in _mode == RF22_MODE_TX
323 /// _txPacketSent member is now redundant and removed.
324 /// Improvements to interrupt handling and blocking. Now use ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
325 /// to prevent reenabling interrupts too soon. Thanks to Roland Mieslinger for this suggestion.
326 /// Added some performance measurements to documentation.
327 ///
328 /// \version 1.21 Fixed a case where a receiver buffer overflow could occur. Reported by Joe Tuttle.
329 ///
330 /// \version 1.22 Added documentation after testing with Sparkfun RFM22 Shield DEV-11018.
331 /// Fixed incorrect link to register calculator excel file, reported by Joey Morin.
332 ///
333 /// \version 1.23 Added support for alternative SPI interfaces, with default implementation for the standard
334 /// Arduino hardware SPI interface. Contributed by Joanna Rutkowska.
335 ///
336 /// \version 1.24 Fixed a problem that could cause corrupted receive messages if a transmit interrupted
337 /// a partial receive (as was common with eg ReliableDatagram with poor reception.
338 /// Also fixed possible receive buffer overrun.
339 /// \version 1.25 More rigorous use of const, additional register defines (RF22_CRCHDRS RF22_VARPKLEN)
340 /// and two methods (setPreambleLength()
341 /// and setSyncWords())made public. Patch provided by
342 /// Matthijs Kooijman.
343 /// \version 1.26 Added Cautions about RF22 IO voltages , level shifters and Mega. Include
344 /// Doxygen documentation in distribution.
345 /// \version 1.27 Updated author and distribution location details to airspayce.com
346 /// Added example demodulated data from an actual RF22 transmission assembled
347 /// by this RF22 library
348 /// \version 1.28 Fixed a problem that prevented packets of more than 59 octets being sent properly.
349 /// This problem was introduced in a recent update.
350 /// \version 1.29 Improvements to waitAvailableTimeout to make it robust on millis() rollover. Contributed by
351 /// Mats Byggmastar.
352 /// \version 1.30 More improvements to timeouts to be robust on millis() rollover. Contributed by
353 /// Mats Byggmastar.
354 /// \version 1.31 Added new function bool waitPacketSent(uint16_t timeout) requested by Benoit Joassart
355 /// \version 1.32 Can now specify interrupt number 2 in constructor.
356 ///
357 /// \author Mike McCauley (mikem@airspayce.com)
358 
359 #ifndef RF22_h
360 #define RF22_h
361 
362 #if ARDUINO >= 100
363 #include <Arduino.h>
364 #else
365 #include <wiring.h>
366 #include "pins_arduino.h"
367 #endif
368 
369 // These defs cause trouble on some versions of Arduino
370 #undef round
371 #undef double
372 
373 // This is the maximum numbe rof interrupts the librray can support
374 // Most Arduinos can handle 2, Megas can handle more
375 #define RF22_NUM_INTERRUPTS 3
376 
377 // This is the bit in the SPI address that marks it as a write
378 #define RF22_SPI_WRITE_MASK 0x80
379 
380 // This is the maximum message length that can be supported by this library. Limited by
381 // the single message length octet in the header.
382 // Yes, 255 is correct even though the FIFO size in the RF22 is only
383 // 64 octets. We use interrupts to refill the Tx FIFO during transmission and to empty the
384 // Rx FIFO during reception
385 // Can be pre-defined to a smaller size (to save SRAM) prior to including this header
386 #ifndef RF22_MAX_MESSAGE_LEN
387 //#define RF22_MAX_MESSAGE_LEN 255
388 #define RF22_MAX_MESSAGE_LEN 50
389 #endif
390 
391 // Max number of octets the RF22 Rx and Tx FIFOs can hold
392 #define RF22_FIFO_SIZE 64
393 
394 // Keep track of the mode the RF22 is in
395 #define RF22_MODE_IDLE 0
396 #define RF22_MODE_RX 1
397 #define RF22_MODE_TX 2
398 
399 // These values we set for FIFO thresholds (4, 55) are actually the same as the POR values
400 #define RF22_TXFFAEM_THRESHOLD 4
401 #define RF22_RXFFAFULL_THRESHOLD 55
402 
403 // This is the default node address,
404 #define RF22_DEFAULT_NODE_ADDRESS 0
405 
406 // This address in the TO addreess signifies a broadcast
407 #define RF22_BROADCAST_ADDRESS 0xff
408 
409 // Number of registers to be passed to setModemConfig()
410 #define RF22_NUM_MODEM_CONFIG_REGS 18
411 
412 // Register names
413 #define RF22_REG_00_DEVICE_TYPE 0x00
414 #define RF22_REG_01_VERSION_CODE 0x01
415 #define RF22_REG_02_DEVICE_STATUS 0x02
416 #define RF22_REG_03_INTERRUPT_STATUS1 0x03
417 #define RF22_REG_04_INTERRUPT_STATUS2 0x04
418 #define RF22_REG_05_INTERRUPT_ENABLE1 0x05
419 #define RF22_REG_06_INTERRUPT_ENABLE2 0x06
420 #define RF22_REG_07_OPERATING_MODE1 0x07
421 #define RF22_REG_08_OPERATING_MODE2 0x08
422 #define RF22_REG_09_OSCILLATOR_LOAD_CAPACITANCE 0x09
423 #define RF22_REG_0A_UC_OUTPUT_CLOCK 0x0a
424 #define RF22_REG_0B_GPIO_CONFIGURATION0 0x0b
425 #define RF22_REG_0C_GPIO_CONFIGURATION1 0x0c
426 #define RF22_REG_0D_GPIO_CONFIGURATION2 0x0d
427 #define RF22_REG_0E_IO_PORT_CONFIGURATION 0x0e
428 #define RF22_REG_0F_ADC_CONFIGURATION 0x0f
429 #define RF22_REG_10_ADC_SENSOR_AMP_OFFSET 0x10
430 #define RF22_REG_11_ADC_VALUE 0x11
431 #define RF22_REG_12_TEMPERATURE_SENSOR_CALIBRATION 0x12
432 #define RF22_REG_13_TEMPERATURE_VALUE_OFFSET 0x13
433 #define RF22_REG_14_WAKEUP_TIMER_PERIOD1 0x14
434 #define RF22_REG_15_WAKEUP_TIMER_PERIOD2 0x15
435 #define RF22_REG_16_WAKEUP_TIMER_PERIOD3 0x16
436 #define RF22_REG_17_WAKEUP_TIMER_VALUE1 0x17
437 #define RF22_REG_18_WAKEUP_TIMER_VALUE2 0x18
438 #define RF22_REG_19_LDC_MODE_DURATION 0x19
439 #define RF22_REG_1A_LOW_BATTERY_DETECTOR_THRESHOLD 0x1a
440 #define RF22_REG_1B_BATTERY_VOLTAGE_LEVEL 0x1b
441 #define RF22_REG_1C_IF_FILTER_BANDWIDTH 0x1c
442 #define RF22_REG_1D_AFC_LOOP_GEARSHIFT_OVERRIDE 0x1d
443 #define RF22_REG_1E_AFC_TIMING_CONTROL 0x1e
444 #define RF22_REG_1F_CLOCK_RECOVERY_GEARSHIFT_OVERRIDE 0x1f
445 #define RF22_REG_20_CLOCK_RECOVERY_OVERSAMPLING_RATE 0x20
446 #define RF22_REG_21_CLOCK_RECOVERY_OFFSET2 0x21
447 #define RF22_REG_22_CLOCK_RECOVERY_OFFSET1 0x22
448 #define RF22_REG_23_CLOCK_RECOVERY_OFFSET0 0x23
449 #define RF22_REG_24_CLOCK_RECOVERY_TIMING_LOOP_GAIN1 0x24
450 #define RF22_REG_25_CLOCK_RECOVERY_TIMING_LOOP_GAIN0 0x25
451 #define RF22_REG_26_RSSI 0x26
452 #define RF22_REG_27_RSSI_THRESHOLD 0x27
453 #define RF22_REG_28_ANTENNA_DIVERSITY1 0x28
454 #define RF22_REG_29_ANTENNA_DIVERSITY2 0x29
455 #define RF22_REG_2A_AFC_LIMITER 0x2a
456 #define RF22_REG_2B_AFC_CORRECTION_READ 0x2b
457 #define RF22_REG_2C_OOK_COUNTER_VALUE_1 0x2c
458 #define RF22_REG_2D_OOK_COUNTER_VALUE_2 0x2d
459 #define RF22_REG_2E_SLICER_PEAK_HOLD 0x2e
460 #define RF22_REG_30_DATA_ACCESS_CONTROL 0x30
461 #define RF22_REG_31_EZMAC_STATUS 0x31
462 #define RF22_REG_32_HEADER_CONTROL1 0x32
463 #define RF22_REG_33_HEADER_CONTROL2 0x33
464 #define RF22_REG_34_PREAMBLE_LENGTH 0x34
465 #define RF22_REG_35_PREAMBLE_DETECTION_CONTROL1 0x35
466 #define RF22_REG_36_SYNC_WORD3 0x36
467 #define RF22_REG_37_SYNC_WORD2 0x37
468 #define RF22_REG_38_SYNC_WORD1 0x38
469 #define RF22_REG_39_SYNC_WORD0 0x39
470 #define RF22_REG_3A_TRANSMIT_HEADER3 0x3a
471 #define RF22_REG_3B_TRANSMIT_HEADER2 0x3b
472 #define RF22_REG_3C_TRANSMIT_HEADER1 0x3c
473 #define RF22_REG_3D_TRANSMIT_HEADER0 0x3d
474 #define RF22_REG_3E_PACKET_LENGTH 0x3e
475 #define RF22_REG_3F_CHECK_HEADER3 0x3f
476 #define RF22_REG_40_CHECK_HEADER2 0x40
477 #define RF22_REG_41_CHECK_HEADER1 0x41
478 #define RF22_REG_42_CHECK_HEADER0 0x42
479 #define RF22_REG_43_HEADER_ENABLE3 0x43
480 #define RF22_REG_44_HEADER_ENABLE2 0x44
481 #define RF22_REG_45_HEADER_ENABLE1 0x45
482 #define RF22_REG_46_HEADER_ENABLE0 0x46
483 #define RF22_REG_47_RECEIVED_HEADER3 0x47
484 #define RF22_REG_48_RECEIVED_HEADER2 0x48
485 #define RF22_REG_49_RECEIVED_HEADER1 0x49
486 #define RF22_REG_4A_RECEIVED_HEADER0 0x4a
487 #define RF22_REG_4B_RECEIVED_PACKET_LENGTH 0x4b
488 #define RF22_REG_50_ANALOG_TEST_BUS_SELECT 0x50
489 #define RF22_REG_51_DIGITAL_TEST_BUS_SELECT 0x51
490 #define RF22_REG_52_TX_RAMP_CONTROL 0x52
491 #define RF22_REG_53_PLL_TUNE_TIME 0x53
492 #define RF22_REG_55_CALIBRATION_CONTROL 0x55
493 #define RF22_REG_56_MODEM_TEST 0x56
494 #define RF22_REG_57_CHARGE_PUMP_TEST 0x57
495 #define RF22_REG_58_CHARGE_PUMP_CURRENT_TRIMMING 0x58
496 #define RF22_REG_59_DIVIDER_CURRENT_TRIMMING 0x59
497 #define RF22_REG_5A_VCO_CURRENT_TRIMMING 0x5a
498 #define RF22_REG_5B_VCO_CALIBRATION 0x5b
499 #define RF22_REG_5C_SYNTHESIZER_TEST 0x5c
500 #define RF22_REG_5D_BLOCK_ENABLE_OVERRIDE1 0x5d
501 #define RF22_REG_5E_BLOCK_ENABLE_OVERRIDE2 0x5e
502 #define RF22_REG_5F_BLOCK_ENABLE_OVERRIDE3 0x5f
503 #define RF22_REG_60_CHANNEL_FILTER_COEFFICIENT_ADDRESS 0x60
504 #define RF22_REG_61_CHANNEL_FILTER_COEFFICIENT_VALUE 0x61
505 #define RF22_REG_62_CRYSTAL_OSCILLATOR_POR_CONTROL 0x62
506 #define RF22_REG_63_RC_OSCILLATOR_COARSE_CALIBRATION 0x63
507 #define RF22_REG_64_RC_OSCILLATOR_FINE_CALIBRATION 0x64
508 #define RF22_REG_65_LDO_CONTROL_OVERRIDE 0x65
509 #define RF22_REG_66_LDO_LEVEL_SETTINGS 0x66
510 #define RF22_REG_67_DELTA_SIGMA_ADC_TUNING1 0x67
511 #define RF22_REG_68_DELTA_SIGMA_ADC_TUNING2 0x68
512 #define RF22_REG_69_AGC_OVERRIDE1 0x69
513 #define RF22_REG_6A_AGC_OVERRIDE2 0x6a
514 #define RF22_REG_6B_GFSK_FIR_FILTER_COEFFICIENT_ADDRESS 0x6b
515 #define RF22_REG_6C_GFSK_FIR_FILTER_COEFFICIENT_VALUE 0x6c
516 #define RF22_REG_6D_TX_POWER 0x6d
517 #define RF22_REG_6E_TX_DATA_RATE1 0x6e
518 #define RF22_REG_6F_TX_DATA_RATE0 0x6f
519 #define RF22_REG_70_MODULATION_CONTROL1 0x70
520 #define RF22_REG_71_MODULATION_CONTROL2 0x71
521 #define RF22_REG_72_FREQUENCY_DEVIATION 0x72
522 #define RF22_REG_73_FREQUENCY_OFFSET1 0x73
523 #define RF22_REG_74_FREQUENCY_OFFSET2 0x74
524 #define RF22_REG_75_FREQUENCY_BAND_SELECT 0x75
525 #define RF22_REG_76_NOMINAL_CARRIER_FREQUENCY1 0x76
526 #define RF22_REG_77_NOMINAL_CARRIER_FREQUENCY0 0x77
527 #define RF22_REG_79_FREQUENCY_HOPPING_CHANNEL_SELECT 0x79
528 #define RF22_REG_7A_FREQUENCY_HOPPING_STEP_SIZE 0x7a
529 #define RF22_REG_7C_TX_FIFO_CONTROL1 0x7c
530 #define RF22_REG_7D_TX_FIFO_CONTROL2 0x7d
531 #define RF22_REG_7E_RX_FIFO_CONTROL 0x7e
532 #define RF22_REG_7F_FIFO_ACCESS 0x7f
533 
534 // These register masks etc are named wherever possible
535 // corresponding to the bit and field names in the RF-22 Manual
536 // RF22_REG_00_DEVICE_TYPE 0x00
537 #define RF22_DEVICE_TYPE_RX_TRX 0x08
538 #define RF22_DEVICE_TYPE_TX 0x07
539 
540 // RF22_REG_02_DEVICE_STATUS 0x02
541 #define RF22_FFOVL 0x80
542 #define RF22_FFUNFL 0x40
543 #define RF22_RXFFEM 0x20
544 #define RF22_HEADERR 0x10
545 #define RF22_FREQERR 0x08
546 #define RF22_LOCKDET 0x04
547 #define RF22_CPS 0x03
548 #define RF22_CPS_IDLE 0x00
549 #define RF22_CPS_RX 0x01
550 #define RF22_CPS_TX 0x10
551 
552 // RF22_REG_03_INTERRUPT_STATUS1 0x03
553 #define RF22_IFFERROR 0x80
554 #define RF22_ITXFFAFULL 0x40
555 #define RF22_ITXFFAEM 0x20
556 #define RF22_IRXFFAFULL 0x10
557 #define RF22_IEXT 0x08
558 #define RF22_IPKSENT 0x04
559 #define RF22_IPKVALID 0x02
560 #define RF22_ICRCERROR 0x01
561 
562 // RF22_REG_04_INTERRUPT_STATUS2 0x04
563 #define RF22_ISWDET 0x80
564 #define RF22_IPREAVAL 0x40
565 #define RF22_IPREAINVAL 0x20
566 #define RF22_IRSSI 0x10
567 #define RF22_IWUT 0x08
568 #define RF22_ILBD 0x04
569 #define RF22_ICHIPRDY 0x02
570 #define RF22_IPOR 0x01
571 
572 // RF22_REG_05_INTERRUPT_ENABLE1 0x05
573 #define RF22_ENFFERR 0x80
574 #define RF22_ENTXFFAFULL 0x40
575 #define RF22_ENTXFFAEM 0x20
576 #define RF22_ENRXFFAFULL 0x10
577 #define RF22_ENEXT 0x08
578 #define RF22_ENPKSENT 0x04
579 #define RF22_ENPKVALID 0x02
580 #define RF22_ENCRCERROR 0x01
581 
582 // RF22_REG_06_INTERRUPT_ENABLE2 0x06
583 #define RF22_ENSWDET 0x80
584 #define RF22_ENPREAVAL 0x40
585 #define RF22_ENPREAINVAL 0x20
586 #define RF22_ENRSSI 0x10
587 #define RF22_ENWUT 0x08
588 #define RF22_ENLBDI 0x04
589 #define RF22_ENCHIPRDY 0x02
590 #define RF22_ENPOR 0x01
591 
592 // RF22_REG_07_OPERATING_MODE 0x07
593 #define RF22_SWRES 0x80
594 #define RF22_ENLBD 0x40
595 #define RF22_ENWT 0x20
596 #define RF22_X32KSEL 0x10
597 #define RF22_TXON 0x08
598 #define RF22_RXON 0x04
599 #define RF22_PLLON 0x02
600 #define RF22_XTON 0x01
601 
602 // RF22_REG_08_OPERATING_MODE2 0x08
603 #define RF22_ANTDIV 0xc0
604 #define RF22_RXMPK 0x10
605 #define RF22_AUTOTX 0x08
606 #define RF22_ENLDM 0x04
607 #define RF22_FFCLRRX 0x02
608 #define RF22_FFCLRTX 0x01
609 
610 // RF22_REG_0F_ADC_CONFIGURATION 0x0f
611 #define RF22_ADCSTART 0x80
612 #define RF22_ADCDONE 0x80
613 #define RF22_ADCSEL 0x70
614 #define RF22_ADCSEL_INTERNAL_TEMPERATURE_SENSOR 0x00
615 #define RF22_ADCSEL_GPIO0_SINGLE_ENDED 0x10
616 #define RF22_ADCSEL_GPIO1_SINGLE_ENDED 0x20
617 #define RF22_ADCSEL_GPIO2_SINGLE_ENDED 0x30
618 #define RF22_ADCSEL_GPIO0_GPIO1_DIFFERENTIAL 0x40
619 #define RF22_ADCSEL_GPIO1_GPIO2_DIFFERENTIAL 0x50
620 #define RF22_ADCSEL_GPIO0_GPIO2_DIFFERENTIAL 0x60
621 #define RF22_ADCSEL_GND 0x70
622 #define RF22_ADCREF 0x0c
623 #define RF22_ADCREF_BANDGAP_VOLTAGE 0x00
624 #define RF22_ADCREF_VDD_ON_3 0x08
625 #define RF22_ADCREF_VDD_ON_2 0x0c
626 #define RF22_ADCGAIN 0x03
627 
628 // RF22_REG_10_ADC_SENSOR_AMP_OFFSET 0x10
629 #define RF22_ADCOFFS 0x0f
630 
631 // RF22_REG_12_TEMPERATURE_SENSOR_CALIBRATION 0x12
632 #define RF22_TSRANGE 0xc0
633 #define RF22_TSRANGE_M64_64C 0x00
634 #define RF22_TSRANGE_M64_192C 0x40
635 #define RF22_TSRANGE_0_128C 0x80
636 #define RF22_TSRANGE_M40_216F 0xc0
637 #define RF22_ENTSOFFS 0x20
638 #define RF22_ENTSTRIM 0x10
639 #define RF22_TSTRIM 0x0f
640 
641 // RF22_REG_14_WAKEUP_TIMER_PERIOD1 0x14
642 #define RF22_WTR 0x3c
643 #define RF22_WTD 0x03
644 
645 // RF22_REG_1D_AFC_LOOP_GEARSHIFT_OVERRIDE 0x1d
646 #define RF22_AFBCD 0x80
647 #define RF22_ENAFC 0x40
648 #define RF22_AFCGEARH 0x38
649 #define RF22_AFCGEARL 0x07
650 
651 // RF22_REG_1E_AFC_TIMING_CONTROL 0x1e
652 #define RF22_SWAIT_TIMER 0xc0
653 #define RF22_SHWAIT 0x38
654 #define RF22_ANWAIT 0x07
655 
656 // RF22_REG_30_DATA_ACCESS_CONTROL 0x30
657 #define RF22_ENPACRX 0x80
658 #define RF22_MSBFRST 0x00
659 #define RF22_LSBFRST 0x40
660 #define RF22_CRCHDRS 0x00
661 #define RF22_CRCDONLY 0x20
662 #define RF22_ENPACTX 0x08
663 #define RF22_ENCRC 0x04
664 #define RF22_CRC 0x03
665 #define RF22_CRC_CCITT 0x00
666 #define RF22_CRC_CRC_16_IBM 0x01
667 #define RF22_CRC_IEC_16 0x02
668 #define RF22_CRC_BIACHEVA 0x03
669 
670 // RF22_REG_32_HEADER_CONTROL1 0x32
671 #define RF22_BCEN 0xf0
672 #define RF22_BCEN_NONE 0x00
673 #define RF22_BCEN_HEADER0 0x10
674 #define RF22_BCEN_HEADER1 0x20
675 #define RF22_BCEN_HEADER2 0x40
676 #define RF22_BCEN_HEADER3 0x80
677 #define RF22_HDCH 0x0f
678 #define RF22_HDCH_NONE 0x00
679 #define RF22_HDCH_HEADER0 0x01
680 #define RF22_HDCH_HEADER1 0x02
681 #define RF22_HDCH_HEADER2 0x04
682 #define RF22_HDCH_HEADER3 0x08
683 
684 // RF22_REG_33_HEADER_CONTROL2 0x33
685 #define RF22_HDLEN 0x70
686 #define RF22_HDLEN_0 0x00
687 #define RF22_HDLEN_1 0x10
688 #define RF22_HDLEN_2 0x20
689 #define RF22_HDLEN_3 0x30
690 #define RF22_HDLEN_4 0x40
691 #define RF22_VARPKLEN 0x00
692 #define RF22_FIXPKLEN 0x08
693 #define RF22_SYNCLEN 0x06
694 #define RF22_SYNCLEN_1 0x00
695 #define RF22_SYNCLEN_2 0x02
696 #define RF22_SYNCLEN_3 0x04
697 #define RF22_SYNCLEN_4 0x06
698 #define RF22_PREALEN8 0x01
699 
700 // RF22_REG_6D_TX_POWER 0x6d
701 #define RF22_TXPOW 0x07
702 #define RF22_TXPOW_4X31 0x08 // Not used in RFM22B
703 #define RF22_TXPOW_1DBM 0x00
704 #define RF22_TXPOW_2DBM 0x01
705 #define RF22_TXPOW_5DBM 0x02
706 #define RF22_TXPOW_8DBM 0x03
707 #define RF22_TXPOW_11DBM 0x04
708 #define RF22_TXPOW_14DBM 0x05
709 #define RF22_TXPOW_17DBM 0x06
710 #define RF22_TXPOW_20DBM 0x07
711 // IN RFM23B
712 #define RF22_TXPOW_LNA_SW 0x08
713 
714 // RF22_REG_71_MODULATION_CONTROL2 0x71
715 #define RF22_TRCLK 0xc0
716 #define RF22_TRCLK_NONE 0x00
717 #define RF22_TRCLK_GPIO 0x40
718 #define RF22_TRCLK_SDO 0x80
719 #define RF22_TRCLK_NIRQ 0xc0
720 #define RF22_DTMOD 0x30
721 #define RF22_DTMOD_DIRECT_GPIO 0x00
722 #define RF22_DTMOD_DIRECT_SDI 0x10
723 #define RF22_DTMOD_FIFO 0x20
724 #define RF22_DTMOD_PN9 0x30
725 #define RF22_ENINV 0x08
726 #define RF22_FD8 0x04
727 #define RF22_MODTYP 0x30
728 #define RF22_MODTYP_UNMODULATED 0x00
729 #define RF22_MODTYP_OOK 0x01
730 #define RF22_MODTYP_FSK 0x02
731 #define RF22_MODTYP_GFSK 0x03
732 
733 // RF22_REG_75_FREQUENCY_BAND_SELECT 0x75
734 #define RF22_SBSEL 0x40
735 #define RF22_HBSEL 0x20
736 #define RF22_FB 0x1f
737 
738 // Define this to include Serial printing in diagnostic routines
739 #define RF22_HAVE_SERIAL
740 
741 #include <GenericSPI.h>
742 #include <HardwareSPI.h>
743 /////////////////////////////////////////////////////////////////////
744 /// \class RF22 RF22.h <RF22.h>
745 /// \brief Send and receive unaddressed, unreliable datagrams.
746 ///
747 /// This base class provides basic functions for sending and receiving unaddressed,
748 /// unreliable datagrams of arbitrary length to 255 octets per packet.
749 ///
750 /// Subclasses may use this class to implement reliable, addressed datagrams and streams,
751 /// mesh routers, repeaters, translators etc.
752 ///
753 /// On transmission, the TO and FROM addresses default to 0x00, unless changed by a subclass.
754 /// On reception the TO addressed is checked against the node address (defaults to 0x00) or the
755 /// broadcast address (which is 0xff). The ID and FLAGS are set to 0, and not checked by this class.
756 /// This permits use of the this base RF22 class as an
757 /// unaddresed, unreliable datagram service. Subclasses are expected to change this behaviour to
758 /// add node address, ids, retransmission etc
759 ///
760 /// Naturally, for any 2 radios to communicate that must be configured to use the same frequence and
761 /// modulation scheme.
762 class RF22
763 {
764 public:
765 
766  /// \brief Defines register values for a set of modem configuration registers
767  ///
768  /// Defines register values for a set of modem configuration registers
769  /// that can be passed to setModemConfig()
770  /// if none of the choices in ModemConfigChoice suit your need
771  /// setModemConfig() writes the register values to the appropriate RF22 registers
772  /// to set the desired modulation type, data rate and deviation/bandwidth.
773  /// Suitable values for these registers can be computed using the register calculator at
774  /// http://www.hoperf.com/upload/rf/RF22B%2023B%2031B%2042B%2043B%20Register%20Settings_RevB1-v5.xls
775  typedef struct
776  {
777  uint8_t reg_1c; ///< Value for register RF22_REG_1C_IF_FILTER_BANDWIDTH
778  uint8_t reg_1f; ///< Value for register RF22_REG_1F_CLOCK_RECOVERY_GEARSHIFT_OVERRIDE
779  uint8_t reg_20; ///< Value for register RF22_REG_20_CLOCK_RECOVERY_OVERSAMPLING_RATE
780  uint8_t reg_21; ///< Value for register RF22_REG_21_CLOCK_RECOVERY_OFFSET2
781  uint8_t reg_22; ///< Value for register RF22_REG_22_CLOCK_RECOVERY_OFFSET1
782  uint8_t reg_23; ///< Value for register RF22_REG_23_CLOCK_RECOVERY_OFFSET0
783  uint8_t reg_24; ///< Value for register RF22_REG_24_CLOCK_RECOVERY_TIMING_LOOP_GAIN1
784  uint8_t reg_25; ///< Value for register RF22_REG_25_CLOCK_RECOVERY_TIMING_LOOP_GAIN0
785  uint8_t reg_2c; ///< Value for register RF22_REG_2C_OOK_COUNTER_VALUE_1
786  uint8_t reg_2d; ///< Value for register RF22_REG_2D_OOK_COUNTER_VALUE_2
787  uint8_t reg_2e; ///< Value for register RF22_REG_2E_SLICER_PEAK_HOLD
788  uint8_t reg_58; ///< Value for register RF22_REG_58_CHARGE_PUMP_CURRENT_TRIMMING
789  uint8_t reg_69; ///< Value for register RF22_REG_69_AGC_OVERRIDE1
790  uint8_t reg_6e; ///< Value for register RF22_REG_6E_TX_DATA_RATE1
791  uint8_t reg_6f; ///< Value for register RF22_REG_6F_TX_DATA_RATE0
792  uint8_t reg_70; ///< Value for register RF22_REG_70_MODULATION_CONTROL1
793  uint8_t reg_71; ///< Value for register RF22_REG_71_MODULATION_CONTROL2
794  uint8_t reg_72; ///< Value for register RF22_REG_72_FREQUENCY_DEVIATION
795  } ModemConfig;
796 
797  /// Choices for setModemConfig() for a selected subset of common modulation types,
798  /// and data rates. If you need another configuration, use the register calculator.
799  /// and call setModemRegisters() with your desired settings
800  /// These are indexes into _modemConfig
801  typedef enum
802  {
803  UnmodulatedCarrier = 0, ///< Unmodulated carrier for testing
804  FSK_PN9_Rb2Fd5, ///< FSK, No Manchester, Rb = 2kbs, Fd = 5kHz, PN9 random modulation for testing
805 
806  FSK_Rb2Fd5, ///< FSK, No Manchester, Rb = 2kbs, Fd = 5kHz
807  FSK_Rb2_4Fd36, ///< FSK, No Manchester, Rb = 2.4kbs, Fd = 36kHz
808  FSK_Rb4_8Fd45, ///< FSK, No Manchester, Rb = 4.8kbs, Fd = 45kHz
809  FSK_Rb9_6Fd45, ///< FSK, No Manchester, Rb = 9.6kbs, Fd = 45kHz
810  FSK_Rb19_2Fd9_6, ///< FSK, No Manchester, Rb = 19.2kbs, Fd = 9.6kHz
811  FSK_Rb38_4Fd19_6, ///< FSK, No Manchester, Rb = 38.4kbs, Fd = 19.6kHz
812  FSK_Rb57_6Fd28_8, ///< FSK, No Manchester, Rb = 57.6kbs, Fd = 28.8kHz
813  FSK_Rb125Fd125, ///< FSK, No Manchester, Rb = 125kbs, Fd = 125kHz
814 
815  GFSK_Rb2Fd5, ///< GFSK, No Manchester, Rb = 2kbs, Fd = 5kHz
816  GFSK_Rb2_4Fd36, ///< GFSK, No Manchester, Rb = 2.4kbs, Fd = 36kHz
817  GFSK_Rb4_8Fd45, ///< GFSK, No Manchester, Rb = 4.8kbs, Fd = 45kHz
818  GFSK_Rb9_6Fd45, ///< GFSK, No Manchester, Rb = 9.6kbs, Fd = 45kHz
819  GFSK_Rb19_2Fd9_6, ///< GFSK, No Manchester, Rb = 19.2kbs, Fd = 9.6kHz
820  GFSK_Rb38_4Fd19_6, ///< GFSK, No Manchester, Rb = 38.4kbs, Fd = 19.6kHz
821  GFSK_Rb57_6Fd28_8, ///< GFSK, No Manchester, Rb = 57.6kbs, Fd = 28.8kHz
822  GFSK_Rb125Fd125, ///< GFSK, No Manchester, Rb = 125kbs, Fd = 125kHz
823 
824  OOK_Rb1_2Bw75, ///< OOK, No Manchester, Rb = 1.2kbs, Rx Bandwidth = 75kHz
825  OOK_Rb2_4Bw335, ///< OOK, No Manchester, Rb = 2.4kbs, Rx Bandwidth = 335kHz
826  OOK_Rb4_8Bw335, ///< OOK, No Manchester, Rb = 4.8kbs, Rx Bandwidth = 335kHz
827  OOK_Rb9_6Bw335, ///< OOK, No Manchester, Rb = 9.6kbs, Rx Bandwidth = 335kHz
828  OOK_Rb19_2Bw335, ///< OOK, No Manchester, Rb = 19.2kbs, Rx Bandwidth = 335kHz
829  OOK_Rb38_4Bw335, ///< OOK, No Manchester, Rb = 38.4kbs, Rx Bandwidth = 335kHz
830  OOK_Rb40Bw335 ///< OOK, No Manchester, Rb = 40kbs, Rx Bandwidth = 335kHz
832 
833  /// Constructor. You can have multiple instances, but each instance must have its own
834  /// interrupt and slave select pin. After constructing, you must call init() to initialise the intnerface
835  /// and the radio module
836  /// \param[in] slaveSelectPin the Arduino pin number of the output to use to select the RF22 before
837  /// accessing it. Defaults to the normal SS pin for your Arduino (D10 for Diecimila, Uno etc, D53 for Mega)
838  /// \param[in] interrupt The interrupt number to use. 0 - 2. Default is interrupt 0 (Arduino input pin 2)
839  /// \param[in] spi Pointer to the SPI interface object to use.
840  /// Defaults to the standard Arduino hardware SPI interface
841  RF22(uint8_t slaveSelectPin = SS, uint8_t interrupt = 0, GenericSPIClass *spi = &Hardware_spi);
842 
843  /// Initialises this instance and the radio module connected to it.
844  /// The following steps are taken:
845  /// - Initialise the slave select pin and the SPI interface library
846  /// - Software reset the RF22 module
847  /// - Checks the connected RF22 module is either a RF22_DEVICE_TYPE_RX_TRX or a RF22_DEVICE_TYPE_TX
848  /// - Attaches an interrupt handler
849  /// - Configures the RF22 module
850  /// - Sets the frequncy to 434.0 MHz
851  /// - Sets the modem data rate to FSK_Rb2_4Fd36
852  /// \return true if everything was successful
853  boolean init();
854 
855  /// Issues a software reset to the
856  /// RF22 module. Blocks for 1ms to ensure the reset is complete.
857  void reset();
858 
859  /// Reads a single register from the RF22
860  /// \param[in] reg Register number, one of RF22_REG_*
861  /// \return The value of the register
862  uint8_t spiRead(uint8_t reg);
863 
864  /// Writes a single byte to the RF22
865  /// \param[in] reg Register number, one of RF22_REG_*
866  /// \param[in] val The value to write
867  void spiWrite(uint8_t reg, uint8_t val);
868 
869  /// Reads a number of consecutive registers from the RF22 using burst read mode
870  /// \param[in] reg Register number of the first register, one of RF22_REG_*
871  /// \param[in] dest Array to write the register values to. Must be at least len bytes
872  /// \param[in] len Number of bytes to read
873  void spiBurstRead(uint8_t reg, uint8_t* dest, uint8_t len);
874 
875  /// Write a number of consecutive registers using burst write mode
876  /// \param[in] reg Register number of the first register, one of RF22_REG_*
877  /// \param[in] src Array of new register values to write. Must be at least len bytes
878  /// \param[in] len Number of bytes to write
879  void spiBurstWrite(uint8_t reg, const uint8_t* src, uint8_t len);
880 
881  /// Reads and returns the device status register RF22_REG_02_DEVICE_STATUS
882  /// \return The value of the device status register
883  uint8_t statusRead();
884 
885  /// Reads a value from the on-chip analog-digital converter
886  /// \param[in] adcsel Selects the ADC input to measure. One of RF22_ADCSEL_*. Defaults to the
887  /// internal temperature sensor
888  /// \param[in] adcref Specifies the refernce voltage to use. One of RF22_ADCREF_*.
889  /// Defaults to the internal bandgap voltage.
890  /// \param[in] adcgain Amplifier gain selection.
891  /// \param[in] adcoffs Amplifier offseet (0 to 15).
892  /// \return The analog value. 0 to 255.
893  uint8_t adcRead(uint8_t adcsel = RF22_ADCSEL_INTERNAL_TEMPERATURE_SENSOR,
894  uint8_t adcref = RF22_ADCREF_BANDGAP_VOLTAGE,
895  uint8_t adcgain = 0,
896  uint8_t adcoffs = 0);
897 
898  /// Reads the on-chip temperature sensoer
899  /// \param[in] tsrange Specifies the temperature range to use. One of RF22_TSRANGE_*
900  /// \param[in] tvoffs Specifies the temperature value offset. This is actually signed value
901  /// added to the measured temperature value
902  /// \return The measured temperature.
903  uint8_t temperatureRead(uint8_t tsrange = RF22_TSRANGE_M64_64C, uint8_t tvoffs = 0);
904 
905  /// Reads the wakeup timer value in registers RF22_REG_17_WAKEUP_TIMER_VALUE1
906  /// and RF22_REG_18_WAKEUP_TIMER_VALUE2
907  /// \return The wakeup timer value
908  uint16_t wutRead();
909 
910  /// Sets the wakeup timer period registers RF22_REG_14_WAKEUP_TIMER_PERIOD1,
911  /// RF22_REG_15_WAKEUP_TIMER_PERIOD2 and RF22_R<EG_16_WAKEUP_TIMER_PERIOD3
912  /// \param[in] wtm Wakeup timer mantissa value
913  /// \param[in] wtr Wakeup timer exponent R value
914  /// \param[in] wtd Wakeup timer exponent D value
915  void setWutPeriod(uint16_t wtm, uint8_t wtr = 0, uint8_t wtd = 0);
916 
917  /// Sets the transmitter and receiver centre frequency
918  /// \param[in] centre Frequency in MHz. 240.0 to 960.0. Caution, some versions of RF22 and derivatives
919  /// implemented more restricted frequency ranges.
920  /// \param[in] afcPullInRange Sets the AF Pull In Range in MHz. Defaults to 0.05MHz (50kHz).
921  /// Range is 0.0 to 0.159375
922  /// for frequencies 240.0 to 480MHz, and 0.0 to 0.318750MHz for frequencies 480.0 to 960MHz,
923  /// \return true if the selected frquency centre + (fhch * fhs) is within range and the afcPullInRange
924  /// is within range
925  boolean setFrequency(float centre, float afcPullInRange = 0.05);
926 
927  /// Sets the frequency hopping step size.
928  /// \param[in] fhs Frequency Hopping step size in 10kHz increments
929  /// \return true if centre + (fhch * fhs) is within limits
930  boolean setFHStepSize(uint8_t fhs);
931 
932  /// Sets the frequncy hopping channel. Adds fhch * fhs to centre frequency
933  /// \param[in] fhch The channel number
934  /// \return true if the selected frquency centre + (fhch * fhs) is within range
935  boolean setFHChannel(uint8_t fhch);
936 
937  /// Reads and returns the current RSSI value from register RF22_REG_26_RSSI. If you want to find the RSSI
938  /// of the last received message, use lastRssi() instead.
939  /// \return The current RSSI value
940  uint8_t rssiRead();
941 
942  /// Reads and returns the current EZMAC value from register RF22_REG_31_EZMAC_STATUS
943  /// \return The current EZMAC value
944  uint8_t ezmacStatusRead();
945 
946  /// Sets the parameters for the RF22 Idle mode in register RF22_REG_07_OPERATING_MODE.
947  /// Idle mode is the mode the RF22 will be in when not transmitting or receiving. The default idle mode
948  /// is RF22_XTON ie READY mode.
949  /// \param[in] mode Mask of mode bits, using RF22_SWRES, RF22_ENLBD, RF22_ENWT,
950  /// RF22_X32KSEL, RF22_PLLON, RF22_XTON.
951  void setMode(uint8_t mode);
952 
953  /// If current mode is Rx or Tx changes it to Idle. If the transmitter or receiver is running,
954  /// disables them.
955  void setModeIdle();
956 
957  /// If current mode is Tx or Idle, changes it to Rx.
958  /// Starts the receiver in the RF22.
959  void setModeRx();
960 
961  /// If current mode is Rx or Idle, changes it to Rx.
962  /// Starts the transmitter in the RF22.
963  void setModeTx();
964 
965  /// Returns the operating mode of the library.
966  /// \return the current mode, one of RF22_MODE_*
967  uint8_t mode();
968 
969  /// Sets the transmitter power output level in register RF22_REG_6D_TX_POWER.
970  /// Be a good neighbour and set the lowest power level you need.
971  /// After init(), the power wil be set to RF22_TXPOW_8DBM.
972  /// Caution: In some countries you may only select RF22_TXPOW_17DBM if you
973  /// are also using frequency hopping.
974  /// \param[in] power Transmitter power level, one of RF22_TXPOW_*
975  void setTxPower(uint8_t power);
976 
977  /// Sets all the registered required to configure the data modem in the RF22, including the data rate,
978  /// bandwidths etc. You cas use this to configure the modem with custom configuraitons if none of the
979  /// canned configurations in ModemConfigChoice suit you.
980  /// \param[in] config A ModemConfig structure containing values for the modem configuration registers.
981  void setModemRegisters(const ModemConfig* config);
982 
983  /// Select one of the predefined modem configurations. If you need a modem configuration not provided
984  /// here, use setModemRegisters() with your own ModemConfig.
985  /// \param[in] index The configuration choice.
986  /// \return true if index is a valid choice.
987  boolean setModemConfig(ModemConfigChoice index);
988 
989  /// Starts the receiver and checks whether a received message is available.
990  /// This can be called multiple times in a timeout loop
991  /// \return true if a complete, valid message has been received and is able to be retrieved by
992  /// recv()
993  boolean available();
994 
995  /// Starts the receiver and blocks until a valid received
996  /// message is available.
997  void waitAvailable();
998 
999  /// Starts the receiver and blocks until a received message is available or a timeout
1000  /// \param[in] timeout Maximum time to wait in milliseconds.
1001  /// \return true if a message is available
1002  bool waitAvailableTimeout(uint16_t timeout);
1003 
1004  /// Turns the receiver on if it not already on.
1005  /// If there is a valid message available, copy it to buf and return true
1006  /// else return false.
1007  /// If a message is copied, *len is set to the length (Caution, 0 length messages are permitted).
1008  /// You should be sure to call this function frequently enough to not miss any messages
1009  /// It is recommended that you call it in your main loop.
1010  /// \param[in] buf Location to copy the received message
1011  /// \param[in,out] len Pointer to available space in buf. Set to the actual number of octets copied.
1012  /// \return true if a valid message was copied to buf
1013  boolean recv(uint8_t* buf, uint8_t* len);
1014 
1015  /// Waits until any previous transmit packet is finished being transmitted with waitPacketSent().
1016  /// Then loads a message into the transmitter and starts the transmitter. Note that a message length
1017  /// of 0 is NOT permitted.
1018  /// \param[in] data Array of data to be sent
1019  /// \param[in] len Number of bytes of data to send (> 0)
1020  /// \return true if the message length was valid and it was correctly queued for transmit
1021  boolean send(const uint8_t* data, uint8_t len);
1022 
1023  /// Blocks until the RF22 is not in mode RF22_MODE_TX (ie until the RF22 is not transmitting).
1024  /// This effectively waits until any previous transmit packet is finished being transmitted.
1025  void waitPacketSent();
1026 
1027  /// Blocks until the RF22 is not in mode RF22_MODE_TX (ie until the RF22 is not transmitting)
1028  /// or until the timeout occuers, whichever happens first
1029  /// \param[in] timeout Maximum time to wait in milliseconds.
1030  /// \return true if the RF22 is not transmitting any more
1031  bool waitPacketSent(uint16_t timeout);
1032 
1033  /// Tells the receiver to accept messages with any TO address, not just messages
1034  /// addressed to this node or the broadcast address
1035  /// \param[in] promiscuous true if you wish to receive messages with any TO address
1036  void setPromiscuous(boolean promiscuous);
1037 
1038  /// Returns the TO header of the last received message
1039  /// \return The TO header
1040  uint8_t headerTo();
1041 
1042  /// Returns the FROM header of the last received message
1043  /// \return The FROM header
1044  uint8_t headerFrom();
1045 
1046  /// Returns the ID header of the last received message
1047  /// \return The ID header
1048  uint8_t headerId();
1049 
1050  /// Returns the FLAGS header of the last received message
1051  /// \return The FLAGS header
1052  uint8_t headerFlags();
1053 
1054  /// Returns the RSSI (Receiver Signal Strength Indicator)
1055  /// of the last received message. This measurement is taken when
1056  /// the preamble has been received. It is a (non-linear) measure of the received signal strength.
1057  /// \return The RSSI
1058  uint8_t lastRssi();
1059 
1060  /// Prints a data buffer in HEX.
1061  /// For diagnostic use
1062  /// \param[in] prompt string to preface the print
1063  /// \param[in] buf Location of the buffer to print
1064  /// \param[in] len Length of the buffer in octets.
1065  static void printBuffer(const char* prompt, const uint8_t* buf, uint8_t len);
1066 
1067  /// Sets the length of the preamble
1068  /// in 4-bit nibbles.
1069  /// Caution: this should be set to the same
1070  /// value on all nodes in your network. Default is 8.
1071  /// Sets the message preamble length in RF22_REG_34_PREAMBLE_LENGTH
1072  /// \param[in] nibbles Preamble length in nibbles of 4 bits each.
1073  void setPreambleLength(uint8_t nibbles);
1074 
1075  /// Sets the sync words for transmit and receive in registers RF22_REG_36_SYNC_WORD3
1076  /// to RF22_REG_39_SYNC_WORD0
1077  /// Caution: this should be set to the same
1078  /// value on all nodes in your network. Default is { 0x2d, 0xd4 }
1079  /// \param[in] syncWords Array of sync words
1080  /// \param[in] len Number of sync words to set
1081  void setSyncWords(const uint8_t* syncWords, uint8_t len);
1082 
1083 protected:
1084  /// This is a low level function to handle the interrupts for one instance of RF22.
1085  /// Called automatically by isr0() and isr1()
1086  /// Should not need to be called.
1087  void handleInterrupt();
1088 
1089  /// Clears the receiver buffer.
1090  /// Internal use only
1091  void clearRxBuf();
1092 
1093  /// Clears the transmitter buffer
1094  /// Internal use only
1095  void clearTxBuf();
1096 
1097  /// Fills the transmitter buffer with the data of a mesage to be sent
1098  /// \param[in] data Array of data bytes to be sent (1 to 255)
1099  /// \param[in] len Number of data bytes in data (> 0)
1100  /// \return true if the message length is valid
1101  boolean fillTxBuf(const uint8_t* data, uint8_t len);
1102 
1103  /// Appends the transmitter buffer with the data of a mesage to be sent
1104  /// \param[in] data Array of data bytes to be sent (0 to 255)
1105  /// \param[in] len Number of data bytes in data
1106  /// \return false if the resulting message would exceed RF22_MAX_MESSAGE_LEN, else true
1107  boolean appendTxBuf(const uint8_t* data, uint8_t len);
1108 
1109  /// Internal function to load the next fragment of
1110  /// the current message into the transmitter FIFO
1111  /// Internal use only
1112  void sendNextFragment();
1113 
1114  /// function to copy the next fragment from
1115  /// the receiver FIF) into the receiver buffer
1116  void readNextFragment();
1117 
1118  /// Clears the RF22 Rx and Tx FIFOs
1119  /// Internal use only
1120  void resetFifos();
1121 
1122  /// Clears the RF22 Rx FIFO
1123  /// Internal use only
1124  void resetRxFifo();
1125 
1126  /// Clears the RF22 Tx FIFO
1127  /// Internal use only
1128  void resetTxFifo();
1129 
1130  /// This function will be called by handleInterrupt() if an RF22 external interrupt occurs.
1131  /// This can only happen if external interrupts are enabled in the RF22
1132  /// (which they are not by default).
1133  /// Subclasses may override this function to get control when an RF22 external interrupt occurs.
1134  virtual void handleExternalInterrupt();
1135 
1136  /// This function will be called by handleInterrupt() if an RF22 wakeup timer interrupt occurs.
1137  /// This can only happen if wakeup timer interrupts are enabled in the RF22
1138  /// (which they are not by default).
1139  /// Subclasses may override this function to get control when an RF22 wakeup timer interrupt occurs.
1140  virtual void handleWakeupTimerInterrupt();
1141 
1142  /// Sets the TO header to be sent in all subsequent messages
1143  /// \param[in] to The new TO header value
1144  void setHeaderTo(uint8_t to);
1145 
1146  /// Sets the FROM header to be sent in all subsequent messages
1147  /// \param[in] from The new FROM header value
1148  void setHeaderFrom(uint8_t from);
1149 
1150  /// Sets the ID header to be sent in all subsequent messages
1151  /// \param[in] id The new ID header value
1152  void setHeaderId(uint8_t id);
1153 
1154  /// Sets the FLAGS header to be sent in all subsequent messages
1155  /// \param[in] flags The new FLAGS header value
1156  void setHeaderFlags(uint8_t flags);
1157 
1158  /// Start the transmission of the contents
1159  /// of the Tx buffer
1160  void startTransmit();
1161 
1162  /// ReStart the transmission of the contents
1163  /// of the Tx buffer after a atransmission failure
1164  void restartTransmit();
1165 
1166 protected:
1167  GenericSPIClass* _spi;
1168 
1169  /// Low level interrupt service routine for RF22 connected to interrupt 0
1170  static void isr0();
1171 
1172  /// Low level interrupt service routine for RF22 connected to interrupt 1
1173  static void isr1();
1174 
1175  /// Low level interrupt service routine for RF22 connected to interrupt 1
1176  static void isr2();
1177 
1178  /// Array of instances connected to interrupts 0 and 1
1180 
1181  volatile uint8_t _mode; // One of RF22_MODE_*
1182 
1183  uint8_t _idleMode;
1184  uint8_t _slaveSelectPin;
1185  uint8_t _interrupt;
1186  uint8_t _deviceType;
1187 
1188  // These volatile members may get changed in the interrupt service routine
1189  volatile uint8_t _bufLen;
1190  uint8_t _buf[RF22_MAX_MESSAGE_LEN];
1191 
1192  volatile boolean _rxBufValid;
1193 
1194  volatile boolean _txPacketSent;
1195  volatile uint8_t _txBufSentIndex;
1196 
1197  volatile uint16_t _rxBad;
1198  volatile uint16_t _rxGood;
1199  volatile uint16_t _txGood;
1200 
1201  volatile uint8_t _lastRssi;
1202 };
1203 
1204 /// @example rf22_client.pde
1205 /// Client side of simple client/server pair using RF22 class
1206 
1207 /// @example rf22_server.pde
1208 /// Server side of simple client/server pair using RF22 class
1209 
1210 /// @example rf22_datagram_client.pde
1211 /// Client side of simple client/server pair using RF22Datagram class
1212 
1213 /// @example rf22_datagram_server.pde
1214 /// Server side of simple client/server pair using RF22Datagram class
1215 
1216 /// @example rf22_reliable_datagram_client.pde
1217 /// Client side of simple client/server pair using RF22ReliableDatagram class
1218 
1219 /// @example rf22_reliable_datagram_server.pde
1220 /// Server side of simple client/server pair using RF22ReliableDatagram class
1221 
1222 /// @example rf22_router_client.pde
1223 /// Client side of RF22Router network chain
1224 
1225 /// @example rf22_router_server1.pde
1226 /// Server node for RF22Router network chain
1227 
1228 /// @example rf22_router_server2.pde
1229 /// Server node for RF22Router network chain
1230 
1231 /// @example rf22_router_server3.pde
1232 /// Server node for RF22Router network chain
1233 
1234 /// @example rf22_mesh_client.pde
1235 /// Client side of RF22Mesh network chain
1236 
1237 /// @example rf22_mesh_server1.pde
1238 /// Server node for RF22Mesh network chain
1239 
1240 /// @example rf22_mesh_server2.pde
1241 /// Server node for RF22Mesh network chain
1242 
1243 /// @example rf22_mesh_server3.pde
1244 /// Server node for RF22Mesh network chain
1245 
1246 /// @example rf22_test.pde
1247 /// Test suite for RF22 library
1248 
1249 /// @example rf22_snoop.pde
1250 /// Capture and print RF22 packet from the air
1251 
1252 /// @example rf22_specan.pde
1253 /// Simple spectrum analyser using the RSSI measurements of the RF22
1254 /// (see <a href="specan1.png">Sample output</a> showing a plot from 395.0MHz to 396.0MHz of a
1255 /// signal generator at 395.5MHz amplitude modulated at 100% 1kHz)
1256 ///
1257 
1258 /// @example IPGateway.pde
1259 /// Sketch to provide an IP gateway for a set of RF22 radios (Datagram, ReliableDatagram, Router or Mesh)
1260 /// Routes UDP messages from an internet connection using an Ethernet Shield and sends them
1261 /// to a radio whose ID is based on the UDP port. Replies are sent back to the originating UDP
1262 /// address and port
1263 
1264 /// @example SDRSharp_20130304_095231Z_433999kHz_AF.wav
1265 /// This is an audio .wav file of a typical transmission from an RF22, driven by the RF22 library.
1266 /// The RF22 was configured for the default: 434.0MHz, FSK_Rb2_4Fd36 (ie FM, 36kHz deviation, 2.4kbps)
1267 /// It was captured with a Funcube Pro+ dongle, using SDR# software. SDR# was configured
1268 /// for a centre frequency of 434.000MHZ, WFM mode with a filter bandwidth of 100kHz
1269 /// (wider than necessary to capture the 36+36 = 72kHz deviation of the signal)
1270 /// With a wav file viewer such as audacity, the modulation can clearly be seen, consisting of:
1271 /// - Preamble of 8 nibbles (16 cycles)
1272 /// - 2 Sync words 0x2d, 0xd4
1273 /// - 4 bytes TX header (all 0s, this was a broadcast)
1274 /// - 1 byte packet length
1275 /// - payload
1276 /// - 2 bytes CRC (IBM format)
1277 
1278 #endif