MarlinSerial.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * MarlinSerial.cpp - Hardware serial library for Wiring
  24. * Copyright (c) 2006 Nicholas Zambetti. All right reserved.
  25. *
  26. * Modified 23 November 2006 by David A. Mellis
  27. * Modified 28 September 2010 by Mark Sproul
  28. * Modified 14 February 2016 by Andreas Hardtung (added tx buffer)
  29. * Modified 01 October 2017 by Eduardo José Tagle (added XON/XOFF)
  30. * Modified 10 June 2018 by Eduardo José Tagle (See #10991)
  31. */
  32. // Disable HardwareSerial.cpp to support chips without a UART (Attiny, etc.)
  33. #include "MarlinConfig.h"
  34. #if USE_MARLINSERIAL && (defined(UBRRH) || defined(UBRR0H) || defined(UBRR1H) || defined(UBRR2H) || defined(UBRR3H))
  35. #include "MarlinSerial.h"
  36. #include "Marlin.h"
  37. struct ring_buffer_r {
  38. unsigned char buffer[RX_BUFFER_SIZE];
  39. volatile ring_buffer_pos_t head, tail;
  40. };
  41. #if TX_BUFFER_SIZE > 0
  42. struct ring_buffer_t {
  43. unsigned char buffer[TX_BUFFER_SIZE];
  44. volatile uint8_t head, tail;
  45. };
  46. #endif
  47. #if UART_PRESENT(SERIAL_PORT)
  48. ring_buffer_r rx_buffer = { { 0 }, 0, 0 };
  49. #if TX_BUFFER_SIZE > 0
  50. ring_buffer_t tx_buffer = { { 0 }, 0, 0 };
  51. #endif
  52. static bool _written;
  53. #endif
  54. #if ENABLED(SERIAL_XON_XOFF)
  55. constexpr uint8_t XON_XOFF_CHAR_SENT = 0x80, // XON / XOFF Character was sent
  56. XON_XOFF_CHAR_MASK = 0x1F; // XON / XOFF character to send
  57. // XON / XOFF character definitions
  58. constexpr uint8_t XON_CHAR = 17, XOFF_CHAR = 19;
  59. uint8_t xon_xoff_state = XON_XOFF_CHAR_SENT | XON_CHAR;
  60. #endif
  61. #if ENABLED(SERIAL_STATS_DROPPED_RX)
  62. uint8_t rx_dropped_bytes = 0;
  63. #endif
  64. #if ENABLED(SERIAL_STATS_RX_BUFFER_OVERRUNS)
  65. uint8_t rx_buffer_overruns = 0;
  66. #endif
  67. #if ENABLED(SERIAL_STATS_RX_FRAMING_ERRORS)
  68. uint8_t rx_framing_errors = 0;
  69. #endif
  70. #if ENABLED(SERIAL_STATS_MAX_RX_QUEUED)
  71. ring_buffer_pos_t rx_max_enqueued = 0;
  72. #endif
  73. // A SW memory barrier, to ensure GCC does not overoptimize loops
  74. #define sw_barrier() asm volatile("": : :"memory");
  75. #if ENABLED(EMERGENCY_PARSER)
  76. #include "emergency_parser.h"
  77. #endif
  78. // "Atomically" read the RX head index value without disabling interrupts:
  79. // This MUST be called with RX interrupts enabled, and CAN'T be called
  80. // from the RX ISR itself!
  81. FORCE_INLINE ring_buffer_pos_t atomic_read_rx_head() {
  82. #if RX_BUFFER_SIZE > 256
  83. // Keep reading until 2 consecutive reads return the same value,
  84. // meaning there was no update in-between caused by an interrupt.
  85. // This works because serial RX interrupts happen at a slower rate
  86. // than successive reads of a variable, so 2 consecutive reads with
  87. // the same value means no interrupt updated it.
  88. ring_buffer_pos_t vold, vnew = rx_buffer.head;
  89. sw_barrier();
  90. do {
  91. vold = vnew;
  92. vnew = rx_buffer.head;
  93. sw_barrier();
  94. } while (vold != vnew);
  95. return vnew;
  96. #else
  97. // With an 8bit index, reads are always atomic. No need for special handling
  98. return rx_buffer.head;
  99. #endif
  100. }
  101. #if RX_BUFFER_SIZE > 256
  102. static volatile bool rx_tail_value_not_stable = false;
  103. static volatile uint16_t rx_tail_value_backup = 0;
  104. #endif
  105. // Set RX tail index, taking into account the RX ISR could interrupt
  106. // the write to this variable in the middle - So a backup strategy
  107. // is used to ensure reads of the correct values.
  108. // -Must NOT be called from the RX ISR -
  109. FORCE_INLINE void atomic_set_rx_tail(ring_buffer_pos_t value) {
  110. #if RX_BUFFER_SIZE > 256
  111. // Store the new value in the backup
  112. rx_tail_value_backup = value;
  113. sw_barrier();
  114. // Flag we are about to change the true value
  115. rx_tail_value_not_stable = true;
  116. sw_barrier();
  117. // Store the new value
  118. rx_buffer.tail = value;
  119. sw_barrier();
  120. // Signal the new value is completely stored into the value
  121. rx_tail_value_not_stable = false;
  122. sw_barrier();
  123. #else
  124. rx_buffer.tail = value;
  125. #endif
  126. }
  127. // Get the RX tail index, taking into account the read could be
  128. // interrupting in the middle of the update of that index value
  129. // -Called from the RX ISR -
  130. FORCE_INLINE ring_buffer_pos_t atomic_read_rx_tail() {
  131. #if RX_BUFFER_SIZE > 256
  132. // If the true index is being modified, return the backup value
  133. if (rx_tail_value_not_stable) return rx_tail_value_backup;
  134. #endif
  135. // The true index is stable, return it
  136. return rx_buffer.tail;
  137. }
  138. // (called with RX interrupts disabled)
  139. FORCE_INLINE void store_rxd_char() {
  140. // Get the tail - Nothing can alter its value while this ISR is executing, but there's
  141. // a chance that this ISR interrupted the main process while it was updating the index.
  142. // The backup mechanism ensures the correct value is always returned.
  143. const ring_buffer_pos_t t = atomic_read_rx_tail();
  144. // Get the head pointer - This ISR is the only one that modifies its value, so it's safe to read here
  145. ring_buffer_pos_t h = rx_buffer.head;
  146. // Get the next element
  147. ring_buffer_pos_t i = (ring_buffer_pos_t)(h + 1) & (ring_buffer_pos_t)(RX_BUFFER_SIZE - 1);
  148. // This must read the M_UCSRxA register before reading the received byte to detect error causes
  149. #if ENABLED(SERIAL_STATS_DROPPED_RX)
  150. if (TEST(M_UCSRxA, M_DORx) && !++rx_dropped_bytes) --rx_dropped_bytes;
  151. #endif
  152. #if ENABLED(SERIAL_STATS_RX_BUFFER_OVERRUNS)
  153. if (TEST(M_UCSRxA, M_DORx) && !++rx_buffer_overruns) --rx_buffer_overruns;
  154. #endif
  155. #if ENABLED(SERIAL_STATS_RX_FRAMING_ERRORS)
  156. if (TEST(M_UCSRxA, M_FEx) && !++rx_framing_errors) --rx_framing_errors;
  157. #endif
  158. // Read the character from the USART
  159. uint8_t c = M_UDRx;
  160. #if ENABLED(EMERGENCY_PARSER)
  161. emergency_parser.update(c);
  162. #endif
  163. // If the character is to be stored at the index just before the tail
  164. // (such that the head would advance to the current tail), the RX FIFO is
  165. // full, so don't write the character or advance the head.
  166. if (i != t) {
  167. rx_buffer.buffer[h] = c;
  168. h = i;
  169. }
  170. #if ENABLED(SERIAL_STATS_DROPPED_RX)
  171. else if (!++rx_dropped_bytes) --rx_dropped_bytes;
  172. #endif
  173. #if ENABLED(SERIAL_STATS_MAX_RX_QUEUED)
  174. // Calculate count of bytes stored into the RX buffer
  175. const ring_buffer_pos_t rx_count = (ring_buffer_pos_t)(h - t) & (ring_buffer_pos_t)(RX_BUFFER_SIZE - 1);
  176. // Keep track of the maximum count of enqueued bytes
  177. NOLESS(rx_max_enqueued, rx_count);
  178. #endif
  179. #if ENABLED(SERIAL_XON_XOFF)
  180. // If the last char that was sent was an XON
  181. if ((xon_xoff_state & XON_XOFF_CHAR_MASK) == XON_CHAR) {
  182. // Bytes stored into the RX buffer
  183. const ring_buffer_pos_t rx_count = (ring_buffer_pos_t)(h - t) & (ring_buffer_pos_t)(RX_BUFFER_SIZE - 1);
  184. // If over 12.5% of RX buffer capacity, send XOFF before running out of
  185. // RX buffer space .. 325 bytes @ 250kbits/s needed to let the host react
  186. // and stop sending bytes. This translates to 13mS propagation time.
  187. if (rx_count >= (RX_BUFFER_SIZE) / 8) {
  188. // At this point, definitely no TX interrupt was executing, since the TX ISR can't be preempted.
  189. // Don't enable the TX interrupt here as a means to trigger the XOFF char, because if it happens
  190. // to be in the middle of trying to disable the RX interrupt in the main program, eventually the
  191. // enabling of the TX interrupt could be undone. The ONLY reliable thing this can do to ensure
  192. // the sending of the XOFF char is to send it HERE AND NOW.
  193. // About to send the XOFF char
  194. xon_xoff_state = XOFF_CHAR | XON_XOFF_CHAR_SENT;
  195. // Wait until the TX register becomes empty and send it - Here there could be a problem
  196. // - While waiting for the TX register to empty, the RX register could receive a new
  197. // character. This must also handle that situation!
  198. while (!TEST(M_UCSRxA, M_UDREx)) {
  199. if (TEST(M_UCSRxA,M_RXCx)) {
  200. // A char arrived while waiting for the TX buffer to be empty - Receive and process it!
  201. i = (ring_buffer_pos_t)(h + 1) & (ring_buffer_pos_t)(RX_BUFFER_SIZE - 1);
  202. // Read the character from the USART
  203. c = M_UDRx;
  204. #if ENABLED(EMERGENCY_PARSER)
  205. emergency_parser.update(c);
  206. #endif
  207. // If the character is to be stored at the index just before the tail
  208. // (such that the head would advance to the current tail), the FIFO is
  209. // full, so don't write the character or advance the head.
  210. if (i != t) {
  211. rx_buffer.buffer[h] = c;
  212. h = i;
  213. }
  214. #if ENABLED(SERIAL_STATS_DROPPED_RX)
  215. else if (!++rx_dropped_bytes) --rx_dropped_bytes;
  216. #endif
  217. }
  218. sw_barrier();
  219. }
  220. M_UDRx = XOFF_CHAR;
  221. // Clear the TXC bit -- "can be cleared by writing a one to its bit
  222. // location". This makes sure flush() won't return until the bytes
  223. // actually got written
  224. SBI(M_UCSRxA, M_TXCx);
  225. // At this point there could be a race condition between the write() function
  226. // and this sending of the XOFF char. This interrupt could happen between the
  227. // wait to be empty TX buffer loop and the actual write of the character. Since
  228. // the TX buffer is full because it's sending the XOFF char, the only way to be
  229. // sure the write() function will succeed is to wait for the XOFF char to be
  230. // completely sent. Since an extra character could be received during the wait
  231. // it must also be handled!
  232. while (!TEST(M_UCSRxA, M_UDREx)) {
  233. if (TEST(M_UCSRxA,M_RXCx)) {
  234. // A char arrived while waiting for the TX buffer to be empty - Receive and process it!
  235. i = (ring_buffer_pos_t)(h + 1) & (ring_buffer_pos_t)(RX_BUFFER_SIZE - 1);
  236. // Read the character from the USART
  237. c = M_UDRx;
  238. #if ENABLED(EMERGENCY_PARSER)
  239. emergency_parser.update(c);
  240. #endif
  241. // If the character is to be stored at the index just before the tail
  242. // (such that the head would advance to the current tail), the FIFO is
  243. // full, so don't write the character or advance the head.
  244. if (i != t) {
  245. rx_buffer.buffer[h] = c;
  246. h = i;
  247. }
  248. #if ENABLED(SERIAL_STATS_DROPPED_RX)
  249. else if (!++rx_dropped_bytes) --rx_dropped_bytes;
  250. #endif
  251. }
  252. sw_barrier();
  253. }
  254. // At this point everything is ready. The write() function won't
  255. // have any issues writing to the UART TX register if it needs to!
  256. }
  257. }
  258. #endif // SERIAL_XON_XOFF
  259. // Store the new head value - The main loop will retry until the value is stable
  260. rx_buffer.head = h;
  261. }
  262. #if TX_BUFFER_SIZE > 0
  263. // (called with TX irqs disabled)
  264. FORCE_INLINE void _tx_udr_empty_irq(void) {
  265. // Read positions
  266. uint8_t t = tx_buffer.tail;
  267. const uint8_t h = tx_buffer.head;
  268. #if ENABLED(SERIAL_XON_XOFF)
  269. // If an XON char is pending to be sent, do it now
  270. if (xon_xoff_state == XON_CHAR) {
  271. // Send the character
  272. M_UDRx = XON_CHAR;
  273. // clear the TXC bit -- "can be cleared by writing a one to its bit
  274. // location". This makes sure flush() won't return until the bytes
  275. // actually got written
  276. SBI(M_UCSRxA, M_TXCx);
  277. // Remember we sent it.
  278. xon_xoff_state = XON_CHAR | XON_XOFF_CHAR_SENT;
  279. // If nothing else to transmit, just disable TX interrupts.
  280. if (h == t) CBI(M_UCSRxB, M_UDRIEx); // (Non-atomic, could be reenabled by the main program, but eventually this will succeed)
  281. return;
  282. }
  283. #endif
  284. // If nothing to transmit, just disable TX interrupts. This could
  285. // happen as the result of the non atomicity of the disabling of RX
  286. // interrupts that could end reenabling TX interrupts as a side effect.
  287. if (h == t) {
  288. CBI(M_UCSRxB, M_UDRIEx); // (Non-atomic, could be reenabled by the main program, but eventually this will succeed)
  289. return;
  290. }
  291. // There is something to TX, Send the next byte
  292. const uint8_t c = tx_buffer.buffer[t];
  293. t = (t + 1) & (TX_BUFFER_SIZE - 1);
  294. M_UDRx = c;
  295. tx_buffer.tail = t;
  296. // Clear the TXC bit (by writing a one to its bit location).
  297. // Ensures flush() won't return until the bytes are actually written/
  298. SBI(M_UCSRxA, M_TXCx);
  299. // Disable interrupts if there is nothing to transmit following this byte
  300. if (h == t) CBI(M_UCSRxB, M_UDRIEx); // (Non-atomic, could be reenabled by the main program, but eventually this will succeed)
  301. }
  302. #ifdef M_USARTx_UDRE_vect
  303. ISR(M_USARTx_UDRE_vect) { _tx_udr_empty_irq(); }
  304. #endif
  305. #endif // TX_BUFFER_SIZE
  306. #ifdef M_USARTx_RX_vect
  307. ISR(M_USARTx_RX_vect) { store_rxd_char(); }
  308. #endif
  309. // Public Methods
  310. void MarlinSerial::begin(const long baud) {
  311. uint16_t baud_setting;
  312. bool useU2X = true;
  313. #if F_CPU == 16000000UL && SERIAL_PORT == 0
  314. // Hard-coded exception for compatibility with the bootloader shipped
  315. // with the Duemilanove and previous boards, and the firmware on the
  316. // 8U2 on the Uno and Mega 2560.
  317. if (baud == 57600) useU2X = false;
  318. #endif
  319. if (useU2X) {
  320. M_UCSRxA = _BV(M_U2Xx);
  321. baud_setting = (F_CPU / 4 / baud - 1) / 2;
  322. }
  323. else {
  324. M_UCSRxA = 0;
  325. baud_setting = (F_CPU / 8 / baud - 1) / 2;
  326. }
  327. // assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register)
  328. M_UBRRxH = baud_setting >> 8;
  329. M_UBRRxL = baud_setting;
  330. SBI(M_UCSRxB, M_RXENx);
  331. SBI(M_UCSRxB, M_TXENx);
  332. SBI(M_UCSRxB, M_RXCIEx);
  333. #if TX_BUFFER_SIZE > 0
  334. CBI(M_UCSRxB, M_UDRIEx);
  335. #endif
  336. _written = false;
  337. }
  338. void MarlinSerial::end() {
  339. CBI(M_UCSRxB, M_RXENx);
  340. CBI(M_UCSRxB, M_TXENx);
  341. CBI(M_UCSRxB, M_RXCIEx);
  342. CBI(M_UCSRxB, M_UDRIEx);
  343. }
  344. int MarlinSerial::peek(void) {
  345. const ring_buffer_pos_t h = atomic_read_rx_head(), t = rx_buffer.tail;
  346. return h == t ? -1 : rx_buffer.buffer[t];
  347. }
  348. int MarlinSerial::read(void) {
  349. const ring_buffer_pos_t h = atomic_read_rx_head();
  350. // Read the tail. Main thread owns it, so it is safe to directly read it
  351. ring_buffer_pos_t t = rx_buffer.tail;
  352. // If nothing to read, return now
  353. if (h == t) return -1;
  354. // Get the next char
  355. const int v = rx_buffer.buffer[t];
  356. t = (ring_buffer_pos_t)(t + 1) & (RX_BUFFER_SIZE - 1);
  357. // Advance tail - Making sure the RX ISR will always get an stable value, even
  358. // if it interrupts the writing of the value of that variable in the middle.
  359. atomic_set_rx_tail(t);
  360. #if ENABLED(SERIAL_XON_XOFF)
  361. // If the XOFF char was sent, or about to be sent...
  362. if ((xon_xoff_state & XON_XOFF_CHAR_MASK) == XOFF_CHAR) {
  363. // Get count of bytes in the RX buffer
  364. const ring_buffer_pos_t rx_count = (ring_buffer_pos_t)(h - t) & (ring_buffer_pos_t)(RX_BUFFER_SIZE - 1);
  365. if (rx_count < (RX_BUFFER_SIZE) / 10) {
  366. #if TX_BUFFER_SIZE > 0
  367. // Signal we want an XON character to be sent.
  368. xon_xoff_state = XON_CHAR;
  369. // Enable TX ISR. Non atomic, but it will eventually enable them
  370. SBI(M_UCSRxB, M_UDRIEx);
  371. #else
  372. // If not using TX interrupts, we must send the XON char now
  373. xon_xoff_state = XON_CHAR | XON_XOFF_CHAR_SENT;
  374. while (!TEST(M_UCSRxA, M_UDREx)) sw_barrier();
  375. M_UDRx = XON_CHAR;
  376. #endif
  377. }
  378. }
  379. #endif
  380. return v;
  381. }
  382. ring_buffer_pos_t MarlinSerial::available(void) {
  383. const ring_buffer_pos_t h = atomic_read_rx_head(), t = rx_buffer.tail;
  384. return (ring_buffer_pos_t)(RX_BUFFER_SIZE + h - t) & (RX_BUFFER_SIZE - 1);
  385. }
  386. void MarlinSerial::flush(void) {
  387. // Set the tail to the head:
  388. // - Read the RX head index in a safe way. (See atomic_read_rx_head.)
  389. // - Set the tail, making sure the RX ISR will always get a stable value, even
  390. // if it interrupts the writing of the value of that variable in the middle.
  391. atomic_set_rx_tail(atomic_read_rx_head());
  392. #if ENABLED(SERIAL_XON_XOFF)
  393. // If the XOFF char was sent, or about to be sent...
  394. if ((xon_xoff_state & XON_XOFF_CHAR_MASK) == XOFF_CHAR) {
  395. #if TX_BUFFER_SIZE > 0
  396. // Signal we want an XON character to be sent.
  397. xon_xoff_state = XON_CHAR;
  398. // Enable TX ISR. Non atomic, but it will eventually enable it.
  399. SBI(M_UCSRxB, M_UDRIEx);
  400. #else
  401. // If not using TX interrupts, we must send the XON char now
  402. xon_xoff_state = XON_CHAR | XON_XOFF_CHAR_SENT;
  403. while (!TEST(M_UCSRxA, M_UDREx)) sw_barrier();
  404. M_UDRx = XON_CHAR;
  405. #endif
  406. }
  407. #endif
  408. }
  409. #if TX_BUFFER_SIZE > 0
  410. void MarlinSerial::write(const uint8_t c) {
  411. _written = true;
  412. // If the TX interrupts are disabled and the data register
  413. // is empty, just write the byte to the data register and
  414. // be done. This shortcut helps significantly improve the
  415. // effective datarate at high (>500kbit/s) bitrates, where
  416. // interrupt overhead becomes a slowdown.
  417. // Yes, there is a race condition between the sending of the
  418. // XOFF char at the RX ISR, but it is properly handled there
  419. if (!TEST(M_UCSRxB, M_UDRIEx) && TEST(M_UCSRxA, M_UDREx)) {
  420. M_UDRx = c;
  421. // clear the TXC bit -- "can be cleared by writing a one to its bit
  422. // location". This makes sure flush() won't return until the bytes
  423. // actually got written
  424. SBI(M_UCSRxA, M_TXCx);
  425. return;
  426. }
  427. const uint8_t i = (tx_buffer.head + 1) & (TX_BUFFER_SIZE - 1);
  428. // If global interrupts are disabled (as the result of being called from an ISR)...
  429. if (!ISRS_ENABLED()) {
  430. // Make room by polling if it is possible to transmit, and do so!
  431. while (i == tx_buffer.tail) {
  432. // If we can transmit another byte, do it.
  433. if (TEST(M_UCSRxA, M_UDREx)) _tx_udr_empty_irq();
  434. // Make sure compiler rereads tx_buffer.tail
  435. sw_barrier();
  436. }
  437. }
  438. else {
  439. // Interrupts are enabled, just wait until there is space
  440. while (i == tx_buffer.tail) { sw_barrier(); }
  441. }
  442. // Store new char. head is always safe to move
  443. tx_buffer.buffer[tx_buffer.head] = c;
  444. tx_buffer.head = i;
  445. // Enable TX ISR - Non atomic, but it will eventually enable TX ISR
  446. SBI(M_UCSRxB, M_UDRIEx);
  447. }
  448. void MarlinSerial::flushTX(void) {
  449. // No bytes written, no need to flush. This special case is needed since there's
  450. // no way to force the TXC (transmit complete) bit to 1 during initialization.
  451. if (!_written) return;
  452. // If global interrupts are disabled (as the result of being called from an ISR)...
  453. if (!ISRS_ENABLED()) {
  454. // Wait until everything was transmitted - We must do polling, as interrupts are disabled
  455. while (tx_buffer.head != tx_buffer.tail || !TEST(M_UCSRxA, M_TXCx)) {
  456. // If there is more space, send an extra character
  457. if (TEST(M_UCSRxA, M_UDREx))
  458. _tx_udr_empty_irq();
  459. sw_barrier();
  460. }
  461. }
  462. else {
  463. // Wait until everything was transmitted
  464. while (tx_buffer.head != tx_buffer.tail || !TEST(M_UCSRxA, M_TXCx)) sw_barrier();
  465. }
  466. // At this point nothing is queued anymore (DRIE is disabled) and
  467. // the hardware finished transmission (TXC is set).
  468. }
  469. #else // TX_BUFFER_SIZE == 0
  470. void MarlinSerial::write(const uint8_t c) {
  471. _written = true;
  472. while (!TEST(M_UCSRxA, M_UDREx)) sw_barrier();
  473. M_UDRx = c;
  474. }
  475. void MarlinSerial::flushTX(void) {
  476. // No bytes written, no need to flush. This special case is needed since there's
  477. // no way to force the TXC (transmit complete) bit to 1 during initialization.
  478. if (!_written) return;
  479. // Wait until everything was transmitted
  480. while (!TEST(M_UCSRxA, M_TXCx)) sw_barrier();
  481. // At this point nothing is queued anymore (DRIE is disabled) and
  482. // the hardware finished transmission (TXC is set).
  483. }
  484. #endif // TX_BUFFER_SIZE == 0
  485. /**
  486. * Imports from print.h
  487. */
  488. void MarlinSerial::print(char c, int base) {
  489. print((long)c, base);
  490. }
  491. void MarlinSerial::print(unsigned char b, int base) {
  492. print((unsigned long)b, base);
  493. }
  494. void MarlinSerial::print(int n, int base) {
  495. print((long)n, base);
  496. }
  497. void MarlinSerial::print(unsigned int n, int base) {
  498. print((unsigned long)n, base);
  499. }
  500. void MarlinSerial::print(long n, int base) {
  501. if (base == 0) write(n);
  502. else if (base == 10) {
  503. if (n < 0) { print('-'); n = -n; }
  504. printNumber(n, 10);
  505. }
  506. else
  507. printNumber(n, base);
  508. }
  509. void MarlinSerial::print(unsigned long n, int base) {
  510. if (base == 0) write(n);
  511. else printNumber(n, base);
  512. }
  513. void MarlinSerial::print(double n, int digits) {
  514. printFloat(n, digits);
  515. }
  516. void MarlinSerial::println(void) {
  517. print('\r');
  518. print('\n');
  519. }
  520. void MarlinSerial::println(const String& s) {
  521. print(s);
  522. println();
  523. }
  524. void MarlinSerial::println(const char c[]) {
  525. print(c);
  526. println();
  527. }
  528. void MarlinSerial::println(char c, int base) {
  529. print(c, base);
  530. println();
  531. }
  532. void MarlinSerial::println(unsigned char b, int base) {
  533. print(b, base);
  534. println();
  535. }
  536. void MarlinSerial::println(int n, int base) {
  537. print(n, base);
  538. println();
  539. }
  540. void MarlinSerial::println(unsigned int n, int base) {
  541. print(n, base);
  542. println();
  543. }
  544. void MarlinSerial::println(long n, int base) {
  545. print(n, base);
  546. println();
  547. }
  548. void MarlinSerial::println(unsigned long n, int base) {
  549. print(n, base);
  550. println();
  551. }
  552. void MarlinSerial::println(double n, int digits) {
  553. print(n, digits);
  554. println();
  555. }
  556. // Private Methods
  557. void MarlinSerial::printNumber(unsigned long n, uint8_t base) {
  558. if (n) {
  559. unsigned char buf[8 * sizeof(long)]; // Enough space for base 2
  560. int8_t i = 0;
  561. while (n) {
  562. buf[i++] = n % base;
  563. n /= base;
  564. }
  565. while (i--)
  566. print((char)(buf[i] + (buf[i] < 10 ? '0' : 'A' - 10)));
  567. }
  568. else
  569. print('0');
  570. }
  571. void MarlinSerial::printFloat(double number, uint8_t digits) {
  572. // Handle negative numbers
  573. if (number < 0.0) {
  574. print('-');
  575. number = -number;
  576. }
  577. // Round correctly so that print(1.999, 2) prints as "2.00"
  578. double rounding = 0.5;
  579. for (uint8_t i = 0; i < digits; ++i)
  580. rounding *= 0.1;
  581. number += rounding;
  582. // Extract the integer part of the number and print it
  583. unsigned long int_part = (unsigned long)number;
  584. double remainder = number - (double)int_part;
  585. print(int_part);
  586. // Print the decimal point, but only if there are digits beyond
  587. if (digits) {
  588. print('.');
  589. // Extract digits from the remainder one at a time
  590. while (digits--) {
  591. remainder *= 10.0;
  592. int toPrint = int(remainder);
  593. print(toPrint);
  594. remainder -= toPrint;
  595. }
  596. }
  597. }
  598. // Preinstantiate
  599. MarlinSerial customizedSerial;
  600. #endif // USE_MARLINSERIAL && (UBRRH || UBRR0H || UBRR1H || UBRR2H || UBRR3H)
  601. // For AT90USB targets use the UART for BT interfacing
  602. #if !USE_MARLINSERIAL && ENABLED(BLUETOOTH)
  603. HardwareSerial bluetoothSerial;
  604. #endif