3 // Virtual Wire implementation for Arduino
4 // See the README file in this directory fdor documentation
6 // ASH Transceiver Software Designer's Guide of 2002.08.07
7 // http://www.rfm.com/products/apnotes/tr_swg05.pdf
10 // 1.5 2008-05-25: fixed a bug that could prevent messages with certain
11 // bytes sequences being received (false message start detected)
12 // 1.6 2011-09-10: Patch from David Bath to prevent unconditional reenabling of the receiver
13 // at end of transmission.
15 // Author: Mike McCauley (mikem@airspayce.com)
16 // Copyright (C) 2008 Mike McCauley
17 // $Id: VirtualWire.cpp,v 1.13 2013/08/06 23:43:41 mikem Exp mikem $
24 #elif defined(__MSP430G2452__) || defined(__MSP430G2553__) // LaunchPad specific
25 #include "legacymsp430.h"
27 #elif defined(MCU_STM32F103RE) // Maple etc
30 #error Platform not defined
33 #include "VirtualWire.h"
34 #include <util/crc16.h>
37 static uint8_t vw_tx_buf[(VW_MAX_MESSAGE_LEN * 2) + VW_HEADER_LEN]
38 = {0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x38, 0x2c};
40 // Number of symbols in vw_tx_buf to be sent;
41 static uint8_t vw_tx_len = 0;
43 // Index of the next symbol to send. Ranges from 0 to vw_tx_len
44 static uint8_t vw_tx_index = 0;
46 // Bit number of next bit to send
47 static uint8_t vw_tx_bit = 0;
49 // Sample number for the transmitter. Runs 0 to 7 during one bit interval
50 static uint8_t vw_tx_sample = 0;
52 // Flag to indicated the transmitter is active
53 static volatile uint8_t vw_tx_enabled = 0;
55 // Total number of messages sent
56 static uint16_t vw_tx_msg_count = 0;
58 // The digital IO pin number of the press to talk, enables the transmitter hardware
59 static uint8_t vw_ptt_pin = 10;
60 static uint8_t vw_ptt_inverted = 0;
62 // The digital IO pin number of the receiver data
63 static uint8_t vw_rx_pin = 11;
64 static uint8_t vw_rx_inverted = 0;
66 // The digital IO pin number of the transmitter data
67 static uint8_t vw_tx_pin = 12;
69 // Current receiver sample
70 static uint8_t vw_rx_sample = 0;
72 // Last receiver sample
73 static uint8_t vw_rx_last_sample = 0;
75 // PLL ramp, varies between 0 and VW_RX_RAMP_LEN-1 (159) over
76 // VW_RX_SAMPLES_PER_BIT (8) samples per nominal bit time.
77 // When the PLL is synchronised, bit transitions happen at about the
79 static uint8_t vw_rx_pll_ramp = 0;
81 // This is the integrate and dump integral. If there are <5 0 samples in the PLL cycle
82 // the bit is declared a 0, else a 1
83 static uint8_t vw_rx_integrator = 0;
85 // Flag indictate if we have seen the start symbol of a new message and are
86 // in the processes of reading and decoding it
87 static uint8_t vw_rx_active = 0;
89 // Flag to indicate that a new message is available
90 static volatile uint8_t vw_rx_done = 0;
92 // Flag to indicate the receiver PLL is to run
93 static uint8_t vw_rx_enabled = 0;
95 // Last 12 bits received, so we can look for the start symbol
96 static uint16_t vw_rx_bits = 0;
98 // How many bits of message we have received. Ranges from 0 to 12
99 static uint8_t vw_rx_bit_count = 0;
101 // The incoming message buffer
102 static uint8_t vw_rx_buf[VW_MAX_MESSAGE_LEN];
104 // The incoming message expected length
105 static uint8_t vw_rx_count = 0;
107 // The incoming message buffer length received so far
108 static volatile uint8_t vw_rx_len = 0;
110 // Number of bad messages received and dropped due to bad lengths
111 static uint8_t vw_rx_bad = 0;
113 // Number of good messages received
114 static uint8_t vw_rx_good = 0;
116 // 4 bit to 6 bit symbol converter table
117 // Used to convert the high and low nybbles of the transmitted data
118 // into 6 bit symbols for transmission. Each 6-bit symbol has 3 1s and 3 0s
119 // with at most 3 consecutive identical bits
120 static uint8_t symbols[] =
122 0xd, 0xe, 0x13, 0x15, 0x16, 0x19, 0x1a, 0x1c,
123 0x23, 0x25, 0x26, 0x29, 0x2a, 0x2c, 0x32, 0x34
126 // Cant really do this as a real C++ class, since we need to have
131 // Compute CRC over count bytes.
132 // This should only be ever called at user level, not interrupt level
133 uint16_t vw_crc(uint8_t *ptr, uint8_t count)
135 uint16_t crc = 0xffff;
138 crc = _crc_ccitt_update(crc, *ptr++);
142 // Convert a 6 bit encoded symbol into its 4 bit decoded equivalent
143 uint8_t vw_symbol_6to4(uint8_t symbol)
147 // Linear search :-( Could have a 64 byte reverse lookup table?
148 for (i = 0; i < 16; i++)
149 if (symbol == symbols[i]) return i;
150 return 0; // Not found
153 // Set the output pin number for transmitter data
154 void vw_set_tx_pin(uint8_t pin)
159 // Set the pin number for input receiver data
160 void vw_set_rx_pin(uint8_t pin)
165 // Set the rx pin inverted
166 void vw_set_rx_inverted(uint8_t inverted)
168 vw_rx_inverted = inverted;
171 // Set the output pin number for transmitter PTT enable
172 void vw_set_ptt_pin(uint8_t pin)
177 // Set the ptt pin inverted (low to transmit)
178 void vw_set_ptt_inverted(uint8_t inverted)
180 vw_ptt_inverted = inverted;
183 // Called 8 times per bit period
184 // Phase locked loop tries to synchronise with the transmitter so that bit
185 // transitions occur at about the time vw_rx_pll_ramp is 0;
186 // Then the average is computed over each bit period to deduce the bit value
189 // Integrate each sample
193 if (vw_rx_sample != vw_rx_last_sample)
195 // Transition, advance if ramp > 80, retard if < 80
196 vw_rx_pll_ramp += ((vw_rx_pll_ramp < VW_RAMP_TRANSITION)
198 : VW_RAMP_INC_ADVANCE);
199 vw_rx_last_sample = vw_rx_sample;
204 // Advance ramp by standard 20 (== 160/8 samples)
205 vw_rx_pll_ramp += VW_RAMP_INC;
207 if (vw_rx_pll_ramp >= VW_RX_RAMP_LEN)
209 // Add this to the 12th bit of vw_rx_bits, LSB first
210 // The last 12 bits are kept
213 // Check the integrator to see how many samples in this cycle were high.
214 // If < 5 out of 8, then its declared a 0 bit, else a 1;
215 if (vw_rx_integrator >= 5)
218 vw_rx_pll_ramp -= VW_RX_RAMP_LEN;
219 vw_rx_integrator = 0; // Clear the integral for the next cycle
223 // We have the start symbol and now we are collecting message bits,
224 // 6 per symbol, each which has to be decoded to 4 bits
225 if (++vw_rx_bit_count >= 12)
227 // Have 12 bits of encoded message == 1 byte encoded
228 // Decode as 2 lots of 6 bits into 2 lots of 4 bits
229 // The 6 lsbits are the high nybble
231 (vw_symbol_6to4(vw_rx_bits & 0x3f)) << 4
232 | vw_symbol_6to4(vw_rx_bits >> 6);
234 // The first decoded byte is the byte count of the following message
235 // the count includes the byte count and the 2 trailing FCS bytes
236 // REVISIT: may also include the ACK flag at 0x40
239 // The first byte is the byte count
240 // Check it for sensibility. It cant be less than 4, since it
241 // includes the bytes count itself and the 2 byte FCS
242 vw_rx_count = this_byte;
243 if (vw_rx_count < 4 || vw_rx_count > VW_MAX_MESSAGE_LEN)
245 // Stupid message length, drop the whole thing
246 vw_rx_active = false;
251 vw_rx_buf[vw_rx_len++] = this_byte;
253 if (vw_rx_len >= vw_rx_count)
255 // Got all the bytes now
256 vw_rx_active = false;
258 vw_rx_done = true; // Better come get it before the next one starts
263 // Not in a message, see if we have a start symbol
264 else if (vw_rx_bits == 0xb38)
266 // Have start symbol, start collecting message
270 vw_rx_done = false; // Too bad if you missed the last message
275 #if defined(__arm__) && defined(CORE_TEENSY)
276 // This allows the AVR interrupt code below to be run from an
277 // IntervalTimer object. It must be above vw_setup(), so the
278 // the TIMER1_COMPA_vect function name is defined.
282 #define SIGNAL(f) void f(void)
283 #ifdef TIMER1_COMPA_vect
284 #undef TIMER1_COMPA_vect
286 void TIMER1_COMPA_vect(void);
290 // Speed is in bits per sec RF rate
291 #if defined(__MSP430G2452__) || defined(__MSP430G2553__) // LaunchPad specific
292 void vw_setup(uint16_t speed)
294 // Calculate the counter overflow count based on the required bit speed
295 // and CPU clock rate
296 uint16_t ocr1a = (F_CPU / 8UL) / speed;
298 // This code is for Energia/MSP430
299 TA0CCR0 = ocr1a; // Ticks for 62,5 us
300 TA0CTL = TASSEL_2 + MC_1; // SMCLK, up mode
301 TA0CCTL0 |= CCIE; // CCR0 interrupt enabled
303 // Set up digital IO pins
304 pinMode(vw_tx_pin, OUTPUT);
305 pinMode(vw_rx_pin, INPUT);
306 pinMode(vw_ptt_pin, OUTPUT);
307 digitalWrite(vw_ptt_pin, vw_ptt_inverted);
310 #elif defined (ARDUINO) // Arduino specific
312 // Common function for setting timer ticks @ prescaler values for speed
313 // Returns prescaler index into {0, 1, 8, 64, 256, 1024} array
314 // and sets nticks to compare-match value if lower than max_ticks
315 // returns 0 & nticks = 0 on fault
316 static uint8_t _timer_calc(uint16_t speed, uint16_t max_ticks, uint16_t *nticks)
318 // Clock divider (prescaler) values - 0/3333: error flag
319 uint16_t prescalers[] = {0, 1, 8, 64, 256, 1024, 3333};
320 uint8_t prescaler=0; // index into array & return bit value
321 unsigned long ulticks; // calculate by ntick overflow
323 // Div-by-zero protection
331 // test increasing prescaler (divisor), decreasing ulticks until no overflow
332 for (prescaler=1; prescaler < 7; prescaler += 1)
334 // Amount of time per CPU clock tick (in seconds)
335 float clock_time = (1.0 / (float(F_CPU) / float(prescalers[prescaler])));
336 // Fraction of second needed to xmit one bit
337 float bit_time = ((1.0 / float(speed)) / 8.0);
338 // number of prescaled ticks needed to handle bit time @ speed
339 ulticks = long(bit_time / clock_time);
340 // Test if ulticks fits in nticks bitwidth (with 1-tick safety margin)
341 if ((ulticks > 1) && (ulticks < max_ticks))
343 break; // found prescaler
345 // Won't fit, check with next prescaler value
349 if ((prescaler == 6) || (ulticks < 2) || (ulticks > max_ticks))
360 void vw_setup(uint16_t speed)
362 uint16_t nticks; // number of prescaled ticks needed
363 uint8_t prescaler; // Bit values for CS0[2:0]
365 #ifdef __AVR_ATtiny85__
366 // figure out prescaler value and counter match value
367 prescaler = _timer_calc(speed, (uint8_t)-1, &nticks);
374 TCCR0A = _BV(WGM01); // Turn on CTC mode / Output Compare pins disconnected
376 // convert prescaler index to TCCRnB prescaler bits CS00, CS01, CS02
378 TCCR0B = prescaler; // set CS00, CS01, CS02 (other bits not needed)
380 // Number of ticks to count before firing interrupt
381 OCR0A = uint8_t(nticks);
383 // Set mask to fire interrupt when OCF0A bit is set in TIFR0
384 TIMSK |= _BV(OCIE0A);
386 #elif defined(__arm__) && defined(CORE_TEENSY)
387 // on Teensy 3.0 (32 bit ARM), use an interval timer
388 IntervalTimer *t = new IntervalTimer();
389 t->begin(TIMER1_COMPA_vect, 125000.0 / (float)(speed));
392 // This is the path for most Arduinos
393 // figure out prescaler value and counter match value
394 prescaler = _timer_calc(speed, (uint16_t)-1, &nticks);
400 TCCR1A = 0; // Output Compare pins disconnected
401 TCCR1B = _BV(WGM12); // Turn on CTC mode
403 // convert prescaler index to TCCRnB prescaler bits CS10, CS11, CS12
406 // Caution: special procedures for setting 16 bit regs
407 // is handled by the compiler
412 TIMSK1 |= _BV(OCIE1A);
415 TIMSK |= _BV(OCIE1A);
418 #endif // __AVR_ATtiny85__
420 // Set up digital IO pins
421 pinMode(vw_tx_pin, OUTPUT);
422 pinMode(vw_rx_pin, INPUT);
423 pinMode(vw_ptt_pin, OUTPUT);
424 digitalWrite(vw_ptt_pin, vw_ptt_inverted);
427 #elif defined(MCU_STM32F103RE) // Maple etc
428 HardwareTimer timer(MAPLE_TIMER);
429 void vw_setup(uint16_t speed)
431 // Set up digital IO pins
432 pinMode(vw_tx_pin, OUTPUT);
433 pinMode(vw_rx_pin, INPUT);
434 pinMode(vw_ptt_pin, OUTPUT);
435 digitalWrite(vw_ptt_pin, vw_ptt_inverted);
437 // Pause the timer while we're configuring it
439 timer.setPeriod((1000000/8)/speed);
440 // Set up an interrupt on channel 1
441 timer.setChannel1Mode(TIMER_OUTPUT_COMPARE);
442 timer.setCompare(TIMER_CH1, 1); // Interrupt 1 count after each update
443 void vw_Int_Handler(); // defined below
444 timer.attachCompare1Interrupt(vw_Int_Handler);
446 // Refresh the timer's count, prescale, and overflow
449 // Start the timer counting
455 // Start the transmitter, call when the tx buffer is ready to go and vw_tx_len is
456 // set to the total number of symbols to send
463 // Enable the transmitter hardware
464 digitalWrite(vw_ptt_pin, true ^ vw_ptt_inverted);
466 // Next tick interrupt will send the first bit
467 vw_tx_enabled = true;
470 // Stop the transmitter, call when all bits are sent
473 // Disable the transmitter hardware
474 digitalWrite(vw_ptt_pin, false ^ vw_ptt_inverted);
475 digitalWrite(vw_tx_pin, false);
477 // No more ticks for the transmitter
478 vw_tx_enabled = false;
481 // Enable the receiver. When a message becomes available, vw_rx_done flag
482 // is set, and vw_wait_rx() will return.
487 vw_rx_enabled = true;
488 vw_rx_active = false; // Never restart a partial message
492 // Disable the receiver
495 vw_rx_enabled = false;
498 // Return true if the transmitter is active
499 uint8_t vw_tx_active()
501 return vw_tx_enabled;
504 // Wait for the transmitter to become available
505 // Busy-wait loop until the ISR says the message has been sent
508 while (vw_tx_enabled)
512 // Wait for the receiver to get a message
513 // Busy-wait loop until the ISR says a message is available
514 // can then call vw_get_message()
521 // Wait at most max milliseconds for the receiver to receive a message
522 // Return the truth of whether there is a message
523 uint8_t vw_wait_rx_max(unsigned long milliseconds)
525 unsigned long start = millis();
527 while (!vw_rx_done && ((millis() - start) < milliseconds))
532 // Wait until transmitter is available and encode and queue the message
534 // The message is raw bytes, with no packet structure imposed
535 // It is transmitted preceded a byte count and followed by 2 FCS bytes
536 uint8_t vw_send(uint8_t* buf, uint8_t len)
540 uint16_t crc = 0xffff;
541 uint8_t *p = vw_tx_buf + VW_HEADER_LEN; // start of the message area
542 uint8_t count = len + 3; // Added byte count and FCS to get total number of bytes
544 if (len > VW_MAX_PAYLOAD)
547 // Wait for transmitter to become available
550 // Encode the message length
551 crc = _crc_ccitt_update(crc, count);
552 p[index++] = symbols[count >> 4];
553 p[index++] = symbols[count & 0xf];
555 // Encode the message into 6 bit symbols. Each byte is converted into
556 // 2 6-bit symbols, high nybble first, low nybble second
557 for (i = 0; i < len; i++)
559 crc = _crc_ccitt_update(crc, buf[i]);
560 p[index++] = symbols[buf[i] >> 4];
561 p[index++] = symbols[buf[i] & 0xf];
564 // Append the fcs, 16 bits before encoding (4 6-bit symbols after encoding)
565 // Caution: VW expects the _ones_complement_ of the CCITT CRC-16 as the FCS
566 // VW sends FCS as low byte then hi byte
568 p[index++] = symbols[(crc >> 4) & 0xf];
569 p[index++] = symbols[crc & 0xf];
570 p[index++] = symbols[(crc >> 12) & 0xf];
571 p[index++] = symbols[(crc >> 8) & 0xf];
573 // Total number of 6-bit symbols to send
574 vw_tx_len = index + VW_HEADER_LEN;
576 // Start the low level interrupt handler sending symbols
582 // Return true if there is a message available
583 uint8_t vw_have_message()
588 // Get the last message received (without byte count or FCS)
589 // Copy at most *len bytes, set *len to the actual number copied
590 // Return true if there is a message and the FCS is OK
591 uint8_t vw_get_message(uint8_t* buf, uint8_t* len)
595 // Message available?
599 // Wait until vw_rx_done is set before reading vw_rx_len
600 // then remove bytecount and FCS
601 rxlen = vw_rx_len - 3;
603 // Copy message (good or bad)
606 memcpy(buf, vw_rx_buf + 1, *len);
608 vw_rx_done = false; // OK, got that message thanks
610 // Check the FCS, return goodness
611 return (vw_crc(vw_rx_buf, vw_rx_len) == 0xf0b8); // FCS OK?
614 uint8_t vw_get_rx_good()
619 uint8_t vw_get_rx_bad()
624 // This is the interrupt service routine called when timer1 overflows
625 // Its job is to output the next bit from the transmitter (every 8 calls)
626 // and to call the PLL code if the receiver is enabled
627 //ISR(SIG_OUTPUT_COMPARE1A)
628 #if defined (ARDUINO) // Arduino specific
630 #ifdef __AVR_ATtiny85__
631 SIGNAL(TIM0_COMPA_vect)
632 #else // Assume Arduino Uno (328p or similar)
633 SIGNAL(TIMER1_COMPA_vect)
634 #endif // __AVR_ATtiny85__
637 if (vw_rx_enabled && !vw_tx_enabled)
638 vw_rx_sample = digitalRead(vw_rx_pin) ^ vw_rx_inverted;
640 // Do transmitter stuff first to reduce transmitter bit jitter due
641 // to variable receiver processing
642 if (vw_tx_enabled && vw_tx_sample++ == 0)
645 // Symbols are sent LSB first
646 // Finished sending the whole message? (after waiting one bit period
647 // since the last bit)
648 if (vw_tx_index >= vw_tx_len)
655 digitalWrite(vw_tx_pin, vw_tx_buf[vw_tx_index] & (1 << vw_tx_bit++));
663 if (vw_tx_sample > 7)
666 if (vw_rx_enabled && !vw_tx_enabled)
669 // LaunchPad or Maple:
670 #elif defined(__MSP430G2452__) || defined(__MSP430G2553__) || defined(MCU_STM32F103RE)
671 void vw_Int_Handler()
673 if (vw_rx_enabled && !vw_tx_enabled)
674 vw_rx_sample = digitalRead(vw_rx_pin) ^ vw_rx_inverted;
676 // Do transmitter stuff first to reduce transmitter bit jitter due
677 // to variable receiver processing
678 if (vw_tx_enabled && vw_tx_sample++ == 0)
681 // Symbols are sent LSB first
682 // Finished sending the whole message? (after waiting one bit period
683 // since the last bit)
684 if (vw_tx_index >= vw_tx_len)
691 digitalWrite(vw_tx_pin, vw_tx_buf[vw_tx_index] & (1 << vw_tx_bit++));
699 if (vw_tx_sample > 7)
702 if (vw_rx_enabled && !vw_tx_enabled)
705 #if defined(__MSP430G2452__) || defined(__MSP430G2553__)
706 interrupt(TIMER0_A0_VECTOR) Timer_A_int(void)