PlatformIO package of the Teensy core framework compatible with GCC 10 & C++20
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

678 line
16KB

  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. #if defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MKL26Z64__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) || defined(__IMXRT1052__) || defined(__IMXRT1062__)
  41. SoftwareSerial::SoftwareSerial(uint8_t rxPin, uint8_t txPin, bool inverse_logic /* = false */)
  42. {
  43. buffer_overflow = false;
  44. #if defined(__IMXRT1052__) || defined(__IMXRT1062__)
  45. if (rxPin == 0 && txPin == 1) {
  46. port = &Serial1;
  47. return;
  48. } else if (rxPin == 6 && txPin == 7) {
  49. port = &Serial2;
  50. return;
  51. } else if (rxPin == 14 && txPin == 15) {
  52. port = &Serial3;
  53. return;
  54. } else if (rxPin == 16 && txPin == 17) {
  55. port = &Serial4;
  56. return;
  57. } else if (rxPin == 21 && txPin == 20) {
  58. port = &Serial5;
  59. return;
  60. } else if (rxPin == 25 && txPin == 24) {
  61. port = &Serial6;
  62. return;
  63. } else if (rxPin == 28 && txPin == 29) {
  64. port = &Serial7;
  65. return;
  66. }
  67. #else
  68. if (rxPin == 0 && txPin == 1) {
  69. port = &Serial1;
  70. return;
  71. } else if (rxPin == 9 && txPin == 10) {
  72. port = &Serial2;
  73. return;
  74. } else if (rxPin == 7 && txPin == 8) {
  75. port = &Serial3;
  76. return;
  77. }
  78. #endif
  79. port = NULL;
  80. pinMode(txPin, OUTPUT);
  81. pinMode(rxPin, INPUT_PULLUP);
  82. txpin = txPin;
  83. rxpin = rxPin;
  84. txreg = portOutputRegister(digitalPinToPort(txPin));
  85. rxreg = portInputRegister(digitalPinToPort(rxPin));
  86. cycles_per_bit = 0;
  87. }
  88. void SoftwareSerial::begin(unsigned long speed)
  89. {
  90. if (port) {
  91. port->begin(speed);
  92. } else {
  93. cycles_per_bit = (uint32_t)(F_CPU + speed / 2) / speed;
  94. ARM_DEMCR |= ARM_DEMCR_TRCENA;
  95. ARM_DWT_CTRL |= ARM_DWT_CTRL_CYCCNTENA;
  96. }
  97. }
  98. void SoftwareSerial::end()
  99. {
  100. if (port) {
  101. port->end();
  102. port = NULL;
  103. } else {
  104. pinMode(txpin, INPUT);
  105. pinMode(rxpin, INPUT);
  106. }
  107. cycles_per_bit = 0;
  108. }
  109. // The worst case expected length of any interrupt routines. If an
  110. // interrupt runs longer than this number of cycles, it can disrupt
  111. // the transmit waveform. Increasing this number causes SoftwareSerial
  112. // to hog the CPU longer, delaying all interrupt response for other
  113. // libraries, so this should be made as small as possible but still
  114. // ensure accurate transmit waveforms.
  115. #define WORST_INTERRUPT_CYCLES 360
  116. static void wait_for_target(uint32_t begin, uint32_t target)
  117. {
  118. if (target - (ARM_DWT_CYCCNT - begin) > WORST_INTERRUPT_CYCLES+20) {
  119. uint32_t pretarget = target - WORST_INTERRUPT_CYCLES;
  120. //digitalWriteFast(12, HIGH);
  121. interrupts();
  122. while (ARM_DWT_CYCCNT - begin < pretarget) ; // wait
  123. noInterrupts();
  124. //digitalWriteFast(12, LOW);
  125. }
  126. while (ARM_DWT_CYCCNT - begin < target) ; // wait
  127. }
  128. size_t SoftwareSerial::write(uint8_t b)
  129. {
  130. elapsedMicros elapsed;
  131. uint32_t target;
  132. uint8_t mask;
  133. uint32_t begin_cycle;
  134. // use hardware serial, if possible
  135. if (port) return port->write(b);
  136. if (cycles_per_bit == 0) return 0;
  137. ARM_DEMCR |= ARM_DEMCR_TRCENA;
  138. ARM_DWT_CTRL |= ARM_DWT_CTRL_CYCCNTENA;
  139. // start bit
  140. target = cycles_per_bit;
  141. noInterrupts();
  142. begin_cycle = ARM_DWT_CYCCNT;
  143. *txreg = 0;
  144. wait_for_target(begin_cycle, target);
  145. // 8 data bits
  146. for (mask = 1; mask; mask <<= 1) {
  147. *txreg = (b & mask) ? 1 : 0;
  148. target += cycles_per_bit;
  149. wait_for_target(begin_cycle, target);
  150. }
  151. // stop bit
  152. *txreg = 1;
  153. interrupts();
  154. target += cycles_per_bit;
  155. while (ARM_DWT_CYCCNT - begin_cycle < target) ; // wait
  156. return 1;
  157. }
  158. void SoftwareSerial::flush()
  159. {
  160. if (port) port->flush();
  161. }
  162. // TODO implement reception using pin change DMA capturing
  163. // ARM_DWT_CYCCNT and the bitband mapped GPIO_PDIR register
  164. // to a circular buffer (8 bytes per event... memory intensive)
  165. int SoftwareSerial::available()
  166. {
  167. if (port) return port->available();
  168. return 0;
  169. }
  170. int SoftwareSerial::peek()
  171. {
  172. if (port) return port->peek();
  173. return -1;
  174. }
  175. int SoftwareSerial::read()
  176. {
  177. if (port) return port->read();
  178. return -1;
  179. }
  180. #else
  181. //
  182. // Lookup table
  183. //
  184. typedef struct _DELAY_TABLE
  185. {
  186. long baud;
  187. unsigned short rx_delay_centering;
  188. unsigned short rx_delay_intrabit;
  189. unsigned short rx_delay_stopbit;
  190. unsigned short tx_delay;
  191. } DELAY_TABLE;
  192. #if F_CPU == 16000000
  193. static const DELAY_TABLE PROGMEM table[] =
  194. {
  195. // baud rxcenter rxintra rxstop tx
  196. { 115200, 1, 17, 17, 12, },
  197. { 57600, 10, 37, 37, 33, },
  198. { 38400, 25, 57, 57, 54, },
  199. { 31250, 31, 70, 70, 68, },
  200. { 28800, 34, 77, 77, 74, },
  201. { 19200, 54, 117, 117, 114, },
  202. { 14400, 74, 156, 156, 153, },
  203. { 9600, 114, 236, 236, 233, },
  204. { 4800, 233, 474, 474, 471, },
  205. { 2400, 471, 950, 950, 947, },
  206. { 1200, 947, 1902, 1902, 1899, },
  207. { 600, 1902, 3804, 3804, 3800, },
  208. { 300, 3804, 7617, 7617, 7614, },
  209. };
  210. const int XMIT_START_ADJUSTMENT = 5;
  211. #elif F_CPU == 8000000
  212. static const DELAY_TABLE table[] PROGMEM =
  213. {
  214. // baud rxcenter rxintra rxstop tx
  215. { 115200, 1, 5, 5, 3, },
  216. { 57600, 1, 15, 15, 13, },
  217. { 38400, 2, 25, 26, 23, },
  218. { 31250, 7, 32, 33, 29, },
  219. { 28800, 11, 35, 35, 32, },
  220. { 19200, 20, 55, 55, 52, },
  221. { 14400, 30, 75, 75, 72, },
  222. { 9600, 50, 114, 114, 112, },
  223. { 4800, 110, 233, 233, 230, },
  224. { 2400, 229, 472, 472, 469, },
  225. { 1200, 467, 948, 948, 945, },
  226. { 600, 948, 1895, 1895, 1890, },
  227. { 300, 1895, 3805, 3805, 3802, },
  228. };
  229. const int XMIT_START_ADJUSTMENT = 4;
  230. #elif F_CPU == 20000000
  231. // 20MHz support courtesy of the good people at macegr.com.
  232. // Thanks, Garrett!
  233. static const DELAY_TABLE PROGMEM table[] =
  234. {
  235. // baud rxcenter rxintra rxstop tx
  236. { 115200, 3, 21, 21, 18, },
  237. { 57600, 20, 43, 43, 41, },
  238. { 38400, 37, 73, 73, 70, },
  239. { 31250, 45, 89, 89, 88, },
  240. { 28800, 46, 98, 98, 95, },
  241. { 19200, 71, 148, 148, 145, },
  242. { 14400, 96, 197, 197, 194, },
  243. { 9600, 146, 297, 297, 294, },
  244. { 4800, 296, 595, 595, 592, },
  245. { 2400, 592, 1189, 1189, 1186, },
  246. { 1200, 1187, 2379, 2379, 2376, },
  247. { 600, 2379, 4759, 4759, 4755, },
  248. { 300, 4759, 9523, 9523, 9520, },
  249. };
  250. const int XMIT_START_ADJUSTMENT = 6;
  251. #else
  252. #error This version of SoftwareSerial supports only 20, 16 and 8MHz processors
  253. #endif
  254. //
  255. // Statics
  256. //
  257. SoftwareSerial *SoftwareSerial::active_object = 0;
  258. char SoftwareSerial::_receive_buffer[_SS_MAX_RX_BUFF];
  259. volatile uint8_t SoftwareSerial::_receive_buffer_tail = 0;
  260. volatile uint8_t SoftwareSerial::_receive_buffer_head = 0;
  261. //
  262. // Debugging
  263. //
  264. // This function generates a brief pulse
  265. // for debugging or measuring on an oscilloscope.
  266. inline void DebugPulse(uint8_t pin, uint8_t count)
  267. {
  268. #if _DEBUG
  269. volatile uint8_t *pport = portOutputRegister(digitalPinToPort(pin));
  270. uint8_t val = *pport;
  271. while (count--)
  272. {
  273. *pport = val | digitalPinToBitMask(pin);
  274. *pport = val;
  275. }
  276. #endif
  277. }
  278. //
  279. // Private methods
  280. //
  281. /* static */
  282. inline void SoftwareSerial::tunedDelay(uint16_t delay) {
  283. uint8_t tmp=0;
  284. asm volatile("sbiw %0, 0x01 \n\t"
  285. "ldi %1, 0xFF \n\t"
  286. "cpi %A0, 0xFF \n\t"
  287. "cpc %B0, %1 \n\t"
  288. "brne .-10 \n\t"
  289. : "+r" (delay), "+a" (tmp)
  290. : "0" (delay)
  291. );
  292. }
  293. // This function sets the current object as the "listening"
  294. // one and returns true if it replaces another
  295. bool SoftwareSerial::listen()
  296. {
  297. if (active_object != this)
  298. {
  299. _buffer_overflow = false;
  300. uint8_t oldSREG = SREG;
  301. cli();
  302. _receive_buffer_head = _receive_buffer_tail = 0;
  303. active_object = this;
  304. SREG = oldSREG;
  305. return true;
  306. }
  307. return false;
  308. }
  309. //
  310. // The receive routine called by the interrupt handler
  311. //
  312. void SoftwareSerial::recv()
  313. {
  314. #if GCC_VERSION < 40302
  315. // Work-around for avr-gcc 4.3.0 OSX version bug
  316. // Preserve the registers that the compiler misses
  317. // (courtesy of Arduino forum user *etracer*)
  318. asm volatile(
  319. "push r18 \n\t"
  320. "push r19 \n\t"
  321. "push r20 \n\t"
  322. "push r21 \n\t"
  323. "push r22 \n\t"
  324. "push r23 \n\t"
  325. "push r26 \n\t"
  326. "push r27 \n\t"
  327. ::);
  328. #endif
  329. uint8_t d = 0;
  330. // If RX line is high, then we don't see any start bit
  331. // so interrupt is probably not for us
  332. if (_inverse_logic ? rx_pin_read() : !rx_pin_read())
  333. {
  334. // Wait approximately 1/2 of a bit width to "center" the sample
  335. tunedDelay(_rx_delay_centering);
  336. DebugPulse(_DEBUG_PIN2, 1);
  337. // Read each of the 8 bits
  338. for (uint8_t i=0x1; i; i <<= 1)
  339. {
  340. tunedDelay(_rx_delay_intrabit);
  341. DebugPulse(_DEBUG_PIN2, 1);
  342. uint8_t noti = ~i;
  343. if (rx_pin_read())
  344. d |= i;
  345. else // else clause added to ensure function timing is ~balanced
  346. d &= noti;
  347. }
  348. // skip the stop bit
  349. tunedDelay(_rx_delay_stopbit);
  350. DebugPulse(_DEBUG_PIN2, 1);
  351. if (_inverse_logic)
  352. d = ~d;
  353. // if buffer full, set the overflow flag and return
  354. if ((_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF != _receive_buffer_head)
  355. {
  356. // save new data in buffer: tail points to where byte goes
  357. _receive_buffer[_receive_buffer_tail] = d; // save new byte
  358. _receive_buffer_tail = (_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF;
  359. }
  360. else
  361. {
  362. #if _DEBUG // for scope: pulse pin as overflow indictator
  363. DebugPulse(_DEBUG_PIN1, 1);
  364. #endif
  365. _buffer_overflow = true;
  366. }
  367. }
  368. #if GCC_VERSION < 40302
  369. // Work-around for avr-gcc 4.3.0 OSX version bug
  370. // Restore the registers that the compiler misses
  371. asm volatile(
  372. "pop r27 \n\t"
  373. "pop r26 \n\t"
  374. "pop r23 \n\t"
  375. "pop r22 \n\t"
  376. "pop r21 \n\t"
  377. "pop r20 \n\t"
  378. "pop r19 \n\t"
  379. "pop r18 \n\t"
  380. ::);
  381. #endif
  382. }
  383. void SoftwareSerial::tx_pin_write(uint8_t pin_state)
  384. {
  385. if (pin_state == LOW)
  386. *_transmitPortRegister &= ~_transmitBitMask;
  387. else
  388. *_transmitPortRegister |= _transmitBitMask;
  389. }
  390. uint8_t SoftwareSerial::rx_pin_read()
  391. {
  392. return *_receivePortRegister & _receiveBitMask;
  393. }
  394. //
  395. // Interrupt handling
  396. //
  397. /* static */
  398. inline void SoftwareSerial::handle_interrupt()
  399. {
  400. if (active_object)
  401. {
  402. active_object->recv();
  403. }
  404. }
  405. #if defined(PCINT0_vect)
  406. ISR(PCINT0_vect)
  407. {
  408. SoftwareSerial::handle_interrupt();
  409. }
  410. #endif
  411. #if defined(PCINT1_vect)
  412. ISR(PCINT1_vect)
  413. {
  414. SoftwareSerial::handle_interrupt();
  415. }
  416. #endif
  417. #if defined(PCINT2_vect)
  418. ISR(PCINT2_vect)
  419. {
  420. SoftwareSerial::handle_interrupt();
  421. }
  422. #endif
  423. #if defined(PCINT3_vect)
  424. ISR(PCINT3_vect)
  425. {
  426. SoftwareSerial::handle_interrupt();
  427. }
  428. #endif
  429. //
  430. // Constructor
  431. //
  432. SoftwareSerial::SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic /* = false */) :
  433. _rx_delay_centering(0),
  434. _rx_delay_intrabit(0),
  435. _rx_delay_stopbit(0),
  436. _tx_delay(0),
  437. _buffer_overflow(false),
  438. _inverse_logic(inverse_logic)
  439. {
  440. setTX(transmitPin);
  441. setRX(receivePin);
  442. }
  443. //
  444. // Destructor
  445. //
  446. SoftwareSerial::~SoftwareSerial()
  447. {
  448. end();
  449. }
  450. void SoftwareSerial::setTX(uint8_t tx)
  451. {
  452. pinMode(tx, OUTPUT);
  453. digitalWrite(tx, HIGH);
  454. _transmitBitMask = digitalPinToBitMask(tx);
  455. uint8_t port = digitalPinToPort(tx);
  456. _transmitPortRegister = portOutputRegister(port);
  457. }
  458. void SoftwareSerial::setRX(uint8_t rx)
  459. {
  460. pinMode(rx, INPUT);
  461. if (!_inverse_logic)
  462. digitalWrite(rx, HIGH); // pullup for normal logic!
  463. _receivePin = rx;
  464. _receiveBitMask = digitalPinToBitMask(rx);
  465. uint8_t port = digitalPinToPort(rx);
  466. _receivePortRegister = portInputRegister(port);
  467. }
  468. //
  469. // Public methods
  470. //
  471. void SoftwareSerial::begin(long speed)
  472. {
  473. _rx_delay_centering = _rx_delay_intrabit = _rx_delay_stopbit = _tx_delay = 0;
  474. for (unsigned i=0; i<sizeof(table)/sizeof(table[0]); ++i)
  475. {
  476. long baud = pgm_read_dword(&table[i].baud);
  477. if (baud == speed)
  478. {
  479. _rx_delay_centering = pgm_read_word(&table[i].rx_delay_centering);
  480. _rx_delay_intrabit = pgm_read_word(&table[i].rx_delay_intrabit);
  481. _rx_delay_stopbit = pgm_read_word(&table[i].rx_delay_stopbit);
  482. _tx_delay = pgm_read_word(&table[i].tx_delay);
  483. break;
  484. }
  485. }
  486. // Set up RX interrupts, but only if we have a valid RX baud rate
  487. if (_rx_delay_stopbit)
  488. {
  489. if (digitalPinToPCICR(_receivePin))
  490. {
  491. *digitalPinToPCICR(_receivePin) |= _BV(digitalPinToPCICRbit(_receivePin));
  492. *digitalPinToPCMSK(_receivePin) |= _BV(digitalPinToPCMSKbit(_receivePin));
  493. }
  494. tunedDelay(_tx_delay); // if we were low this establishes the end
  495. }
  496. #if _DEBUG
  497. pinMode(_DEBUG_PIN1, OUTPUT);
  498. pinMode(_DEBUG_PIN2, OUTPUT);
  499. #endif
  500. listen();
  501. }
  502. void SoftwareSerial::end()
  503. {
  504. if (digitalPinToPCMSK(_receivePin))
  505. *digitalPinToPCMSK(_receivePin) &= ~_BV(digitalPinToPCMSKbit(_receivePin));
  506. }
  507. // Read data from buffer
  508. int SoftwareSerial::read()
  509. {
  510. if (!isListening())
  511. return -1;
  512. // Empty buffer?
  513. if (_receive_buffer_head == _receive_buffer_tail)
  514. return -1;
  515. // Read from "head"
  516. uint8_t d = _receive_buffer[_receive_buffer_head]; // grab next byte
  517. _receive_buffer_head = (_receive_buffer_head + 1) % _SS_MAX_RX_BUFF;
  518. return d;
  519. }
  520. int SoftwareSerial::available()
  521. {
  522. if (!isListening())
  523. return 0;
  524. return (_receive_buffer_tail + _SS_MAX_RX_BUFF - _receive_buffer_head) % _SS_MAX_RX_BUFF;
  525. }
  526. size_t SoftwareSerial::write(uint8_t b)
  527. {
  528. if (_tx_delay == 0) {
  529. setWriteError();
  530. return 0;
  531. }
  532. uint8_t oldSREG = SREG;
  533. cli(); // turn off interrupts for a clean txmit
  534. // Write the start bit
  535. tx_pin_write(_inverse_logic ? HIGH : LOW);
  536. tunedDelay(_tx_delay + XMIT_START_ADJUSTMENT);
  537. // Write each of the 8 bits
  538. if (_inverse_logic)
  539. {
  540. for (byte mask = 0x01; mask; mask <<= 1)
  541. {
  542. if (b & mask) // choose bit
  543. tx_pin_write(LOW); // send 1
  544. else
  545. tx_pin_write(HIGH); // send 0
  546. tunedDelay(_tx_delay);
  547. }
  548. tx_pin_write(LOW); // restore pin to natural state
  549. }
  550. else
  551. {
  552. for (byte mask = 0x01; mask; mask <<= 1)
  553. {
  554. if (b & mask) // choose bit
  555. tx_pin_write(HIGH); // send 1
  556. else
  557. tx_pin_write(LOW); // send 0
  558. tunedDelay(_tx_delay);
  559. }
  560. tx_pin_write(HIGH); // restore pin to natural state
  561. }
  562. SREG = oldSREG; // turn interrupts back on
  563. tunedDelay(_tx_delay);
  564. return 1;
  565. }
  566. void SoftwareSerial::flush()
  567. {
  568. if (!isListening())
  569. return;
  570. uint8_t oldSREG = SREG;
  571. cli();
  572. _receive_buffer_head = _receive_buffer_tail = 0;
  573. SREG = oldSREG;
  574. }
  575. int SoftwareSerial::peek()
  576. {
  577. if (!isListening())
  578. return -1;
  579. // Empty buffer?
  580. if (_receive_buffer_head == _receive_buffer_tail)
  581. return -1;
  582. // Read from "head"
  583. return _receive_buffer[_receive_buffer_head];
  584. }
  585. #endif