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