Subversion Repositories MK-Marlin

Rev

Details | Last modification | View Log | RSS feed

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