SoftwareSerial.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. /*
  2. SoftwareSerial.cpp (formerly NewSoftSerial.cpp) -
  3. Multi-instance software serial library for Arduino/Wiring
  4. -- Interrupt-driven receive and other improvements by ladyada
  5. (http://ladyada.net)
  6. -- Tuning, circular buffer, derivation from class Print/Stream,
  7. multi-instance support, porting to 8MHz processors,
  8. various optimizations, PROGMEM delay tables, inverse logic and
  9. direct port writing by Mikal Hart (http://www.arduiniana.org)
  10. -- Pin change interrupt macros by Paul Stoffregen (http://www.pjrc.com)
  11. -- 20MHz processor support by Garrett Mace (http://www.macetech.com)
  12. -- ATmega1280/2560 support by Brett Hagman (http://www.roguerobotics.com/)
  13. This library is free software; you can redistribute it and/or
  14. modify it under the terms of the GNU Lesser General Public
  15. License as published by the Free Software Foundation; either
  16. version 2.1 of the License, or (at your option) any later version.
  17. This library is distributed in the hope that it will be useful,
  18. but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  20. Lesser General Public License for more details.
  21. You should have received a copy of the GNU Lesser General Public
  22. License along with this library; if not, write to the Free Software
  23. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  24. The latest version of this library can always be found at
  25. http://arduiniana.org.
  26. */
  27. // When set, _DEBUG co-opts pins 11 and 13 for debugging with an
  28. // oscilloscope or logic analyzer. Beware: it also slightly modifies
  29. // the bit times, so don't rely on it too much at high baud rates
  30. #define _DEBUG 0
  31. #define _DEBUG_PIN1 11
  32. #define _DEBUG_PIN2 13
  33. //
  34. // Includes
  35. //
  36. #include <avr/interrupt.h>
  37. #include <avr/pgmspace.h>
  38. #include <Arduino.h>
  39. #include <SoftwareSerial.h>
  40. //
  41. // Lookup table
  42. //
  43. typedef struct _DELAY_TABLE
  44. {
  45. long baud;
  46. unsigned short rx_delay_centering;
  47. unsigned short rx_delay_intrabit;
  48. unsigned short rx_delay_stopbit;
  49. unsigned short tx_delay;
  50. } DELAY_TABLE;
  51. #if F_CPU == 16000000
  52. static const DELAY_TABLE PROGMEM table[] =
  53. {
  54. // baud rxcenter rxintra rxstop tx
  55. { 115200, 1, 17, 17, 12, },
  56. { 57600, 10, 37, 37, 33, },
  57. { 38400, 25, 57, 57, 54, },
  58. { 31250, 31, 70, 70, 68, },
  59. { 28800, 34, 77, 77, 74, },
  60. { 19200, 54, 117, 117, 114, },
  61. { 14400, 74, 156, 156, 153, },
  62. { 9600, 114, 236, 236, 233, },
  63. { 4800, 233, 474, 474, 471, },
  64. { 2400, 471, 950, 950, 947, },
  65. { 1200, 947, 1902, 1902, 1899, },
  66. { 600, 1902, 3804, 3804, 3800, },
  67. { 300, 3804, 7617, 7617, 7614, },
  68. };
  69. const int XMIT_START_ADJUSTMENT = 5;
  70. #elif F_CPU == 8000000
  71. static const DELAY_TABLE table[] PROGMEM =
  72. {
  73. // baud rxcenter rxintra rxstop tx
  74. { 115200, 1, 5, 5, 3, },
  75. { 57600, 1, 15, 15, 13, },
  76. { 38400, 2, 25, 26, 23, },
  77. { 31250, 7, 32, 33, 29, },
  78. { 28800, 11, 35, 35, 32, },
  79. { 19200, 20, 55, 55, 52, },
  80. { 14400, 30, 75, 75, 72, },
  81. { 9600, 50, 114, 114, 112, },
  82. { 4800, 110, 233, 233, 230, },
  83. { 2400, 229, 472, 472, 469, },
  84. { 1200, 467, 948, 948, 945, },
  85. { 600, 948, 1895, 1895, 1890, },
  86. { 300, 1895, 3805, 3805, 3802, },
  87. };
  88. const int XMIT_START_ADJUSTMENT = 4;
  89. #elif F_CPU == 20000000
  90. // 20MHz support courtesy of the good people at macegr.com.
  91. // Thanks, Garrett!
  92. static const DELAY_TABLE PROGMEM table[] =
  93. {
  94. // baud rxcenter rxintra rxstop tx
  95. { 115200, 3, 21, 21, 18, },
  96. { 57600, 20, 43, 43, 41, },
  97. { 38400, 37, 73, 73, 70, },
  98. { 31250, 45, 89, 89, 88, },
  99. { 28800, 46, 98, 98, 95, },
  100. { 19200, 71, 148, 148, 145, },
  101. { 14400, 96, 197, 197, 194, },
  102. { 9600, 146, 297, 297, 294, },
  103. { 4800, 296, 595, 595, 592, },
  104. { 2400, 592, 1189, 1189, 1186, },
  105. { 1200, 1187, 2379, 2379, 2376, },
  106. { 600, 2379, 4759, 4759, 4755, },
  107. { 300, 4759, 9523, 9523, 9520, },
  108. };
  109. const int XMIT_START_ADJUSTMENT = 6;
  110. #else
  111. #error This version of SoftwareSerial supports only 20, 16 and 8MHz processors
  112. #endif
  113. //
  114. // Statics
  115. //
  116. SoftwareSerial *SoftwareSerial::active_object = 0;
  117. char SoftwareSerial::_receive_buffer[_SS_MAX_RX_BUFF];
  118. volatile uint8_t SoftwareSerial::_receive_buffer_tail = 0;
  119. volatile uint8_t SoftwareSerial::_receive_buffer_head = 0;
  120. //
  121. // Debugging
  122. //
  123. // This function generates a brief pulse
  124. // for debugging or measuring on an oscilloscope.
  125. inline void DebugPulse(uint8_t pin, uint8_t count)
  126. {
  127. #if _DEBUG
  128. volatile uint8_t *pport = portOutputRegister(digitalPinToPort(pin));
  129. uint8_t val = *pport;
  130. while (count--)
  131. {
  132. *pport = val | digitalPinToBitMask(pin);
  133. *pport = val;
  134. }
  135. #endif
  136. }
  137. //
  138. // Private methods
  139. //
  140. /* static */
  141. inline void SoftwareSerial::tunedDelay(uint16_t delay) {
  142. uint8_t tmp=0;
  143. asm volatile("sbiw %0, 0x01 \n\t"
  144. "ldi %1, 0xFF \n\t"
  145. "cpi %A0, 0xFF \n\t"
  146. "cpc %B0, %1 \n\t"
  147. "brne .-10 \n\t"
  148. : "+r" (delay), "+a" (tmp)
  149. : "0" (delay)
  150. );
  151. }
  152. // This function sets the current object as the "listening"
  153. // one and returns true if it replaces another
  154. bool SoftwareSerial::listen()
  155. {
  156. if (active_object != this)
  157. {
  158. _buffer_overflow = false;
  159. uint8_t oldSREG = SREG;
  160. cli();
  161. _receive_buffer_head = _receive_buffer_tail = 0;
  162. active_object = this;
  163. SREG = oldSREG;
  164. return true;
  165. }
  166. return false;
  167. }
  168. //
  169. // The receive routine called by the interrupt handler
  170. //
  171. void SoftwareSerial::recv()
  172. {
  173. #if GCC_VERSION < 40302
  174. // Work-around for avr-gcc 4.3.0 OSX version bug
  175. // Preserve the registers that the compiler misses
  176. // (courtesy of Arduino forum user *etracer*)
  177. asm volatile(
  178. "push r18 \n\t"
  179. "push r19 \n\t"
  180. "push r20 \n\t"
  181. "push r21 \n\t"
  182. "push r22 \n\t"
  183. "push r23 \n\t"
  184. "push r26 \n\t"
  185. "push r27 \n\t"
  186. ::);
  187. #endif
  188. uint8_t d = 0;
  189. // If RX line is high, then we don't see any start bit
  190. // so interrupt is probably not for us
  191. if (_inverse_logic ? rx_pin_read() : !rx_pin_read())
  192. {
  193. // Wait approximately 1/2 of a bit width to "center" the sample
  194. tunedDelay(_rx_delay_centering);
  195. DebugPulse(_DEBUG_PIN2, 1);
  196. // Read each of the 8 bits
  197. for (uint8_t i=0x1; i; i <<= 1)
  198. {
  199. tunedDelay(_rx_delay_intrabit);
  200. DebugPulse(_DEBUG_PIN2, 1);
  201. uint8_t noti = ~i;
  202. if (rx_pin_read())
  203. d |= i;
  204. else // else clause added to ensure function timing is ~balanced
  205. d &= noti;
  206. }
  207. // skip the stop bit
  208. tunedDelay(_rx_delay_stopbit);
  209. DebugPulse(_DEBUG_PIN2, 1);
  210. if (_inverse_logic)
  211. d = ~d;
  212. // if buffer full, set the overflow flag and return
  213. if ((_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF != _receive_buffer_head)
  214. {
  215. // save new data in buffer: tail points to where byte goes
  216. _receive_buffer[_receive_buffer_tail] = d; // save new byte
  217. _receive_buffer_tail = (_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF;
  218. }
  219. else
  220. {
  221. #if _DEBUG // for scope: pulse pin as overflow indictator
  222. DebugPulse(_DEBUG_PIN1, 1);
  223. #endif
  224. _buffer_overflow = true;
  225. }
  226. }
  227. #if GCC_VERSION < 40302
  228. // Work-around for avr-gcc 4.3.0 OSX version bug
  229. // Restore the registers that the compiler misses
  230. asm volatile(
  231. "pop r27 \n\t"
  232. "pop r26 \n\t"
  233. "pop r23 \n\t"
  234. "pop r22 \n\t"
  235. "pop r21 \n\t"
  236. "pop r20 \n\t"
  237. "pop r19 \n\t"
  238. "pop r18 \n\t"
  239. ::);
  240. #endif
  241. }
  242. void SoftwareSerial::tx_pin_write(uint8_t pin_state)
  243. {
  244. if (pin_state == LOW)
  245. *_transmitPortRegister &= ~_transmitBitMask;
  246. else
  247. *_transmitPortRegister |= _transmitBitMask;
  248. }
  249. uint8_t SoftwareSerial::rx_pin_read()
  250. {
  251. return *_receivePortRegister & _receiveBitMask;
  252. }
  253. //
  254. // Interrupt handling
  255. //
  256. /* static */
  257. inline void SoftwareSerial::handle_interrupt()
  258. {
  259. if (active_object)
  260. {
  261. active_object->recv();
  262. }
  263. }
  264. #if defined(PCINT0_vect)
  265. ISR(PCINT0_vect)
  266. {
  267. SoftwareSerial::handle_interrupt();
  268. }
  269. #endif
  270. #if defined(PCINT1_vect)
  271. ISR(PCINT1_vect)
  272. {
  273. SoftwareSerial::handle_interrupt();
  274. }
  275. #endif
  276. #if defined(PCINT2_vect)
  277. ISR(PCINT2_vect)
  278. {
  279. SoftwareSerial::handle_interrupt();
  280. }
  281. #endif
  282. #if defined(PCINT3_vect)
  283. ISR(PCINT3_vect)
  284. {
  285. SoftwareSerial::handle_interrupt();
  286. }
  287. #endif
  288. //
  289. // Constructor
  290. //
  291. SoftwareSerial::SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic /* = false */) :
  292. _rx_delay_centering(0),
  293. _rx_delay_intrabit(0),
  294. _rx_delay_stopbit(0),
  295. _tx_delay(0),
  296. _buffer_overflow(false),
  297. _inverse_logic(inverse_logic)
  298. {
  299. setTX(transmitPin);
  300. setRX(receivePin);
  301. }
  302. //
  303. // Destructor
  304. //
  305. SoftwareSerial::~SoftwareSerial()
  306. {
  307. end();
  308. }
  309. void SoftwareSerial::setTX(uint8_t tx)
  310. {
  311. pinMode(tx, OUTPUT);
  312. digitalWrite(tx, HIGH);
  313. _transmitBitMask = digitalPinToBitMask(tx);
  314. uint8_t port = digitalPinToPort(tx);
  315. _transmitPortRegister = portOutputRegister(port);
  316. }
  317. void SoftwareSerial::setRX(uint8_t rx)
  318. {
  319. pinMode(rx, INPUT);
  320. if (!_inverse_logic)
  321. digitalWrite(rx, HIGH); // pullup for normal logic!
  322. _receivePin = rx;
  323. _receiveBitMask = digitalPinToBitMask(rx);
  324. uint8_t port = digitalPinToPort(rx);
  325. _receivePortRegister = portInputRegister(port);
  326. }
  327. //
  328. // Public methods
  329. //
  330. void SoftwareSerial::begin(long speed)
  331. {
  332. _rx_delay_centering = _rx_delay_intrabit = _rx_delay_stopbit = _tx_delay = 0;
  333. for (unsigned i=0; i<sizeof(table)/sizeof(table[0]); ++i)
  334. {
  335. long baud = pgm_read_dword(&table[i].baud);
  336. if (baud == speed)
  337. {
  338. _rx_delay_centering = pgm_read_word(&table[i].rx_delay_centering);
  339. _rx_delay_intrabit = pgm_read_word(&table[i].rx_delay_intrabit);
  340. _rx_delay_stopbit = pgm_read_word(&table[i].rx_delay_stopbit);
  341. _tx_delay = pgm_read_word(&table[i].tx_delay);
  342. break;
  343. }
  344. }
  345. // Set up RX interrupts, but only if we have a valid RX baud rate
  346. if (_rx_delay_stopbit)
  347. {
  348. if (digitalPinToPCICR(_receivePin))
  349. {
  350. *digitalPinToPCICR(_receivePin) |= _BV(digitalPinToPCICRbit(_receivePin));
  351. *digitalPinToPCMSK(_receivePin) |= _BV(digitalPinToPCMSKbit(_receivePin));
  352. }
  353. tunedDelay(_tx_delay); // if we were low this establishes the end
  354. }
  355. #if _DEBUG
  356. pinMode(_DEBUG_PIN1, OUTPUT);
  357. pinMode(_DEBUG_PIN2, OUTPUT);
  358. #endif
  359. listen();
  360. }
  361. void SoftwareSerial::end()
  362. {
  363. if (digitalPinToPCMSK(_receivePin))
  364. *digitalPinToPCMSK(_receivePin) &= ~_BV(digitalPinToPCMSKbit(_receivePin));
  365. }
  366. // Read data from buffer
  367. int SoftwareSerial::read()
  368. {
  369. if (!isListening())
  370. return -1;
  371. // Empty buffer?
  372. if (_receive_buffer_head == _receive_buffer_tail)
  373. return -1;
  374. // Read from "head"
  375. uint8_t d = _receive_buffer[_receive_buffer_head]; // grab next byte
  376. _receive_buffer_head = (_receive_buffer_head + 1) % _SS_MAX_RX_BUFF;
  377. return d;
  378. }
  379. int SoftwareSerial::available()
  380. {
  381. if (!isListening())
  382. return 0;
  383. return (_receive_buffer_tail + _SS_MAX_RX_BUFF - _receive_buffer_head) % _SS_MAX_RX_BUFF;
  384. }
  385. size_t SoftwareSerial::write(uint8_t b)
  386. {
  387. if (_tx_delay == 0) {
  388. setWriteError();
  389. return 0;
  390. }
  391. uint8_t oldSREG = SREG;
  392. cli(); // turn off interrupts for a clean txmit
  393. // Write the start bit
  394. tx_pin_write(_inverse_logic ? HIGH : LOW);
  395. tunedDelay(_tx_delay + XMIT_START_ADJUSTMENT);
  396. // Write each of the 8 bits
  397. if (_inverse_logic)
  398. {
  399. for (byte mask = 0x01; mask; mask <<= 1)
  400. {
  401. if (b & mask) // choose bit
  402. tx_pin_write(LOW); // send 1
  403. else
  404. tx_pin_write(HIGH); // send 0
  405. tunedDelay(_tx_delay);
  406. }
  407. tx_pin_write(LOW); // restore pin to natural state
  408. }
  409. else
  410. {
  411. for (byte mask = 0x01; mask; mask <<= 1)
  412. {
  413. if (b & mask) // choose bit
  414. tx_pin_write(HIGH); // send 1
  415. else
  416. tx_pin_write(LOW); // send 0
  417. tunedDelay(_tx_delay);
  418. }
  419. tx_pin_write(HIGH); // restore pin to natural state
  420. }
  421. SREG = oldSREG; // turn interrupts back on
  422. tunedDelay(_tx_delay);
  423. return 1;
  424. }
  425. void SoftwareSerial::flush()
  426. {
  427. if (!isListening())
  428. return;
  429. uint8_t oldSREG = SREG;
  430. cli();
  431. _receive_buffer_head = _receive_buffer_tail = 0;
  432. SREG = oldSREG;
  433. }
  434. int SoftwareSerial::peek()
  435. {
  436. if (!isListening())
  437. return -1;
  438. // Empty buffer?
  439. if (_receive_buffer_head == _receive_buffer_tail)
  440. return -1;
  441. // Read from "head"
  442. return _receive_buffer[_receive_buffer_head];
  443. }