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.

SoftwareSerial8e1.cpp 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. //
  2. // Created by robin on 2/24/17.
  3. //
  4. // When set, _DEBUG co-opts pins 11 and 13 for debugging with an
  5. // oscilloscope or logic analyzer. Beware: it also slightly modifies
  6. // the bit times, so don't rely on it too much at high baud rates
  7. #define _DEBUG 0
  8. #define _DEBUG_PIN1 11
  9. #define _DEBUG_PIN2 13
  10. //
  11. // Includes
  12. //
  13. #include <avr/interrupt.h>
  14. #include <avr/pgmspace.h>
  15. #include <Arduino.h>
  16. #include "SoftwareSerial8e1.h"
  17. #include <util/delay_basic.h>
  18. //
  19. // Statics
  20. //
  21. SoftwareSerial8e1 *SoftwareSerial8e1::active_object = 0;
  22. uint8_t SoftwareSerial8e1::_receive_buffer[_SS_MAX_RX_BUFF];
  23. volatile uint8_t SoftwareSerial8e1::_receive_buffer_tail = 0;
  24. volatile uint8_t SoftwareSerial8e1::_receive_buffer_head = 0;
  25. //
  26. // Debugging
  27. //
  28. // This function generates a brief pulse
  29. // for debugging or measuring on an oscilloscope.
  30. #if _DEBUG
  31. inline void DebugPulse(uint8_t pin, uint8_t count)
  32. {
  33. volatile uint8_t *pport = portOutputRegister(digitalPinToPort(pin));
  34. uint8_t val = *pport;
  35. while (count--)
  36. {
  37. *pport = val | digitalPinToBitMask(pin);
  38. *pport = val;
  39. }
  40. }
  41. #else
  42. inline void DebugPulse(uint8_t, uint8_t) {}
  43. #endif
  44. //
  45. // Private methods
  46. //
  47. /* static */
  48. inline void SoftwareSerial8e1::tunedDelay(uint16_t delay) {
  49. _delay_loop_2(delay);
  50. }
  51. // This function sets the current object as the "listening"
  52. // one and returns true if it replaces another
  53. bool SoftwareSerial8e1::listen()
  54. {
  55. if (!_rx_delay_stopbit)
  56. return false;
  57. if (active_object != this)
  58. {
  59. if (active_object)
  60. active_object->stopListening();
  61. _buffer_overflow = false;
  62. _receive_buffer_head = _receive_buffer_tail = 0;
  63. active_object = this;
  64. setRxIntMsk(true);
  65. return true;
  66. }
  67. return false;
  68. }
  69. // Stop listening. Returns true if we were actually listening.
  70. bool SoftwareSerial8e1::stopListening()
  71. {
  72. if (active_object == this)
  73. {
  74. setRxIntMsk(false);
  75. active_object = NULL;
  76. return true;
  77. }
  78. return false;
  79. }
  80. //
  81. // The receive routine called by the interrupt handler
  82. //
  83. void SoftwareSerial8e1::recv()
  84. {
  85. #if GCC_VERSION < 40302
  86. // Work-around for avr-gcc 4.3.0 OSX version bug
  87. // Preserve the registers that the compiler misses
  88. // (courtesy of Arduino forum user *etracer*)
  89. asm volatile(
  90. "push r18 \n\t"
  91. "push r19 \n\t"
  92. "push r20 \n\t"
  93. "push r21 \n\t"
  94. "push r22 \n\t"
  95. "push r23 \n\t"
  96. "push r26 \n\t"
  97. "push r27 \n\t"
  98. ::);
  99. #endif
  100. uint8_t d = 0;
  101. // If RX line is high, then we don't see any start bit
  102. // so interrupt is probably not for us
  103. if (_inverse_logic ? rx_pin_read() : !rx_pin_read())
  104. {
  105. // Disable further interrupts during reception, this prevents
  106. // triggering another interrupt directly after we return, which can
  107. // cause problems at higher baudrates.
  108. setRxIntMsk(false);
  109. // Wait approximately 1/2 of a bit width to "center" the sample
  110. tunedDelay(_rx_delay_centering);
  111. DebugPulse(_DEBUG_PIN2, 1);
  112. // Read each of the 8 bits
  113. for (uint8_t i=8; i > 0; --i)
  114. {
  115. tunedDelay(_rx_delay_intrabit);
  116. d >>= 1;
  117. DebugPulse(_DEBUG_PIN2, 1);
  118. if (rx_pin_read())
  119. d |= 0x80;
  120. }
  121. if (_inverse_logic)
  122. d = ~d;
  123. // if buffer full, set the overflow flag and return
  124. uint8_t next = (_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF;
  125. if (next != _receive_buffer_head)
  126. {
  127. // save new data in buffer: tail points to where byte goes
  128. _receive_buffer[_receive_buffer_tail] = d; // save new byte
  129. _receive_buffer_tail = next;
  130. }
  131. else
  132. {
  133. DebugPulse(_DEBUG_PIN1, 1);
  134. _buffer_overflow = true;
  135. }
  136. // skip the parity bit
  137. tunedDelay(_rx_delay_stopbit);
  138. DebugPulse(_DEBUG_PIN1, 1);
  139. // skip the stop bit
  140. tunedDelay(_rx_delay_stopbit);
  141. DebugPulse(_DEBUG_PIN1, 1);
  142. // Re-enable interrupts when we're sure to be inside the stop bit
  143. setRxIntMsk(true);
  144. }
  145. #if GCC_VERSION < 40302
  146. // Work-around for avr-gcc 4.3.0 OSX version bug
  147. // Restore the registers that the compiler misses
  148. asm volatile(
  149. "pop r27 \n\t"
  150. "pop r26 \n\t"
  151. "pop r23 \n\t"
  152. "pop r22 \n\t"
  153. "pop r21 \n\t"
  154. "pop r20 \n\t"
  155. "pop r19 \n\t"
  156. "pop r18 \n\t"
  157. ::);
  158. #endif
  159. }
  160. uint8_t SoftwareSerial8e1::rx_pin_read()
  161. {
  162. return *_receivePortRegister & _receiveBitMask;
  163. }
  164. //
  165. // Interrupt handling
  166. //
  167. /* static */
  168. inline void SoftwareSerial8e1::handle_interrupt()
  169. {
  170. if (active_object)
  171. {
  172. active_object->recv();
  173. }
  174. }
  175. #if defined(PCINT0_vect)
  176. ISR(PCINT0_vect)
  177. {
  178. SoftwareSerial8e1::handle_interrupt();
  179. }
  180. #endif
  181. #if defined(PCINT1_vect)
  182. ISR(PCINT1_vect, ISR_ALIASOF(PCINT0_vect));
  183. #endif
  184. #if defined(PCINT2_vect)
  185. ISR(PCINT2_vect, ISR_ALIASOF(PCINT0_vect));
  186. #endif
  187. #if defined(PCINT3_vect)
  188. ISR(PCINT3_vect, ISR_ALIASOF(PCINT0_vect));
  189. #endif
  190. //
  191. // Constructor
  192. //
  193. SoftwareSerial8e1::SoftwareSerial8e1(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic /* = false */) :
  194. _rx_delay_centering(0),
  195. _rx_delay_intrabit(0),
  196. _rx_delay_stopbit(0),
  197. _tx_delay(0),
  198. _buffer_overflow(false),
  199. _inverse_logic(inverse_logic)
  200. {
  201. setTX(transmitPin);
  202. setRX(receivePin);
  203. }
  204. //
  205. // Destructor
  206. //
  207. SoftwareSerial8e1::~SoftwareSerial8e1()
  208. {
  209. end();
  210. }
  211. void SoftwareSerial8e1::setTX(uint8_t tx)
  212. {
  213. // First write, then set output. If we do this the other way around,
  214. // the pin would be output low for a short while before switching to
  215. // output high. Now, it is input with pullup for a short while, which
  216. // is fine. With inverse logic, either order is fine.
  217. digitalWrite(tx, _inverse_logic ? LOW : HIGH);
  218. pinMode(tx, OUTPUT);
  219. _transmitBitMask = digitalPinToBitMask(tx);
  220. uint8_t port = digitalPinToPort(tx);
  221. _transmitPortRegister = portOutputRegister(port);
  222. }
  223. void SoftwareSerial8e1::setRX(uint8_t rx)
  224. {
  225. pinMode(rx, INPUT);
  226. if (!_inverse_logic)
  227. digitalWrite(rx, HIGH); // pullup for normal logic!
  228. _receivePin = rx;
  229. _receiveBitMask = digitalPinToBitMask(rx);
  230. uint8_t port = digitalPinToPort(rx);
  231. _receivePortRegister = portInputRegister(port);
  232. }
  233. uint16_t SoftwareSerial8e1::subtract_cap(uint16_t num, uint16_t sub) {
  234. if (num > sub)
  235. return num - sub;
  236. else
  237. return 1;
  238. }
  239. //
  240. // Public methods
  241. //
  242. void SoftwareSerial8e1::begin(long speed)
  243. {
  244. _rx_delay_centering = _rx_delay_intrabit = _rx_delay_stopbit = _tx_delay = 0;
  245. // Precalculate the various delays, in number of 4-cycle delays
  246. uint16_t bit_delay = (F_CPU / speed) / 4;
  247. // 12 (gcc 4.8.2) or 13 (gcc 4.3.2) cycles from start bit to first bit,
  248. // 15 (gcc 4.8.2) or 16 (gcc 4.3.2) cycles between bits,
  249. // 12 (gcc 4.8.2) or 14 (gcc 4.3.2) cycles from last bit to stop bit
  250. // These are all close enough to just use 15 cycles, since the inter-bit
  251. // timings are the most critical (deviations stack 8 times)
  252. _tx_delay = subtract_cap(bit_delay, 15 / 4);
  253. // Only setup rx when we have a valid PCINT for this pin
  254. if (digitalPinToPCICR(_receivePin)) {
  255. #if GCC_VERSION > 40800
  256. // Timings counted from gcc 4.8.2 output. This works up to 115200 on
  257. // 16Mhz and 57600 on 8Mhz.
  258. //
  259. // When the start bit occurs, there are 3 or 4 cycles before the
  260. // interrupt flag is set, 4 cycles before the PC is set to the right
  261. // interrupt vector address and the old PC is pushed on the stack,
  262. // and then 75 cycles of instructions (including the RJMP in the
  263. // ISR vector table) until the first delay. After the delay, there
  264. // are 17 more cycles until the pin value is read (excluding the
  265. // delay in the loop).
  266. // We want to have a total delay of 1.5 bit time. Inside the loop,
  267. // we already wait for 1 bit time - 23 cycles, so here we wait for
  268. // 0.5 bit time - (71 + 18 - 22) cycles.
  269. _rx_delay_centering = subtract_cap(bit_delay / 2, (4 + 4 + 75 + 17 - 23) / 4);
  270. // There are 23 cycles in each loop iteration (excluding the delay)
  271. _rx_delay_intrabit = subtract_cap(bit_delay, 23 / 4);
  272. // There are 37 cycles from the last bit read to the start of
  273. // stopbit delay and 11 cycles from the delay until the interrupt
  274. // mask is enabled again (which _must_ happen during the stopbit).
  275. // This delay aims at 3/4 of a bit time, meaning the end of the
  276. // delay will be at 1/4th of the stopbit. This allows some extra
  277. // time for ISR cleanup, which makes 115200 baud at 16Mhz work more
  278. // reliably
  279. _rx_delay_stopbit = subtract_cap(bit_delay * 3 / 4, (37 + 11) / 4);
  280. #else // Timings counted from gcc 4.3.2 output
  281. // Note that this code is a _lot_ slower, mostly due to bad register
  282. // allocation choices of gcc. This works up to 57600 on 16Mhz and
  283. // 38400 on 8Mhz.
  284. _rx_delay_centering = subtract_cap(bit_delay / 2, (4 + 4 + 97 + 29 - 11) / 4);
  285. _rx_delay_intrabit = subtract_cap(bit_delay, 11 / 4);
  286. _rx_delay_stopbit = subtract_cap(bit_delay * 3 / 4, (44 + 17) / 4);
  287. #endif
  288. // Enable the PCINT for the entire port here, but never disable it
  289. // (others might also need it, so we disable the interrupt by using
  290. // the per-pin PCMSK register).
  291. *digitalPinToPCICR(_receivePin) |= _BV(digitalPinToPCICRbit(_receivePin));
  292. // Precalculate the pcint mask register and value, so setRxIntMask
  293. // can be used inside the ISR without costing too much time.
  294. _pcint_maskreg = digitalPinToPCMSK(_receivePin);
  295. _pcint_maskvalue = _BV(digitalPinToPCMSKbit(_receivePin));
  296. tunedDelay(_tx_delay); // if we were low this establishes the end
  297. }
  298. #if _DEBUG
  299. pinMode(_DEBUG_PIN1, OUTPUT);
  300. pinMode(_DEBUG_PIN2, OUTPUT);
  301. #endif
  302. listen();
  303. }
  304. void SoftwareSerial8e1::setRxIntMsk(bool enable)
  305. {
  306. if (enable)
  307. *_pcint_maskreg |= _pcint_maskvalue;
  308. else
  309. *_pcint_maskreg &= ~_pcint_maskvalue;
  310. }
  311. void SoftwareSerial8e1::end()
  312. {
  313. stopListening();
  314. }
  315. // Read data from buffer
  316. int SoftwareSerial8e1::read()
  317. {
  318. if (!isListening())
  319. return -1;
  320. // Empty buffer?
  321. if (_receive_buffer_head == _receive_buffer_tail)
  322. return -1;
  323. // Read from "head"
  324. uint8_t d = _receive_buffer[_receive_buffer_head]; // grab next byte
  325. _receive_buffer_head = (_receive_buffer_head + 1) % _SS_MAX_RX_BUFF;
  326. return d;
  327. }
  328. int SoftwareSerial8e1::available()
  329. {
  330. if (!isListening())
  331. return 0;
  332. return (_receive_buffer_tail + _SS_MAX_RX_BUFF - _receive_buffer_head) % _SS_MAX_RX_BUFF;
  333. }
  334. size_t SoftwareSerial8e1::write(uint8_t b)
  335. {
  336. if (_tx_delay == 0) {
  337. setWriteError();
  338. return 0;
  339. }
  340. // setTX(_receivePin);
  341. // By declaring these as local variables, the compiler will put them
  342. // in registers _before_ disabling interrupts and entering the
  343. // critical timing sections below, which makes it a lot easier to
  344. // verify the cycle timings
  345. volatile uint8_t *reg = _transmitPortRegister;
  346. uint8_t reg_mask = _transmitBitMask;
  347. uint8_t inv_mask = ~_transmitBitMask;
  348. uint8_t oldSREG = SREG;
  349. bool inv = _inverse_logic;
  350. uint16_t delay = _tx_delay;
  351. uint8_t p = 0;
  352. for (uint8_t t = 0x80; t; t >>= 1)
  353. if (b & t) p++;
  354. if (inv)
  355. b = ~b;
  356. cli(); // turn off interrupts for a clean txmit
  357. // Write the start bit
  358. if (inv)
  359. *reg |= reg_mask;
  360. else
  361. *reg &= inv_mask;
  362. tunedDelay(delay);
  363. // Write each of the 8 bits
  364. for (uint8_t i = 8; i > 0; --i)
  365. {
  366. if (b & 1) // choose bit
  367. *reg |= reg_mask; // send 1
  368. else
  369. *reg &= inv_mask; // send 0
  370. tunedDelay(delay);
  371. b >>= 1;
  372. }
  373. if (p & 0x01)
  374. *reg |= reg_mask; // send 1
  375. else
  376. *reg &= inv_mask; // send 0
  377. tunedDelay(_tx_delay);
  378. // restore pin to natural state
  379. if (inv)
  380. *reg &= inv_mask;
  381. else
  382. *reg |= reg_mask;
  383. SREG = oldSREG; // turn interrupts back on
  384. tunedDelay(_tx_delay);
  385. // setRX(_receivePin);
  386. // pinMode(_receivePin, INPUT);
  387. return 1;
  388. }
  389. void SoftwareSerial8e1::flush()
  390. {
  391. // There is no tx buffering, simply return
  392. }
  393. int SoftwareSerial8e1::peek()
  394. {
  395. if (!isListening())
  396. return -1;
  397. // Empty buffer?
  398. if (_receive_buffer_head == _receive_buffer_tail)
  399. return -1;
  400. // Read from "head"
  401. return _receive_buffer[_receive_buffer_head];
  402. }