ENع
→UART firmware
الدرس 26 · UART, I2C and SPI in firmware

UART in firmware: baud rate and ring buffers

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة10 خطوات5 أسئلةIntermediate
عن هذا الدرس

Write the receive side of a UART driver for an Arduino Uno R3 (ATmega328P, 16 MHz). Set the baud rate by dividing the clock (UBRR0 = 207 gives 9,615 baud), follow one byte's bits along the RX wire into UDR0, then let an interrupt move each byte into an 8-slot ring buffer that loop() empties when it has time. Watch head and tail chase each other round the ring, and see what happens when loop() stops reading for 100 ms. The Hardware lesson “Serial buses: UART, I2C and SPI” explains the wires and the frame; the DSA lesson “Ring buffers and deques under the hood” covers the data structure. Here you write the driver.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 26 · تفاعلي
01 / 10

One wire, no clock

UART sends bytes over one wire, the sender's TX to the receiver's RX, plus ground. There is no clock wire, so both ends must agree on a speed: the baud rate. On an Uno the PC reaches RX pin 0 through a USB chip.

UART   universal asynchronous receiver-transmitter
wires  TX -> RX, plus a shared ground
clock  none on the wire: both ends agree a baud rate
Uno    PC -> USB chip (ATmega16U2) -> RX pin 0 of the ATmega328P
the Hardware lesson "Serial buses: UART, I2C and SPI" covers the wires
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. One wire, no clock

    UART sends bytes over one wire, the sender's TX to the receiver's RX, plus ground. There is no clock wire, so both ends must agree on a speed: the baud rate. On an Uno the PC reaches RX pin 0 through a USB chip.

    UART   universal asynchronous receiver-transmitter
    wires  TX -> RX, plus a shared ground
    clock  none on the wire: both ends agree a baud rate
    Uno    PC -> USB chip (ATmega16U2) -> RX pin 0 of the ATmega328P
    the Hardware lesson "Serial buses: UART, I2C and SPI" covers the wires
  2. Set the baud rate

    The UART divides the 16 MHz clock. In double-speed mode the datasheet's rule is 16,000,000 ÷ (8 × (UBRR0 + 1)). UBRR0 = 207 gives 9,615 baud, 0.2% fast of 9,600: inside the 1.5% the receiver tolerates.

    line 1   UBRR0 = 207;  with U2X0 = 1 (double speed)
    rule     BAUD = f / (8 * (UBRR0 + 1))
             16,000,000 / (8 * 208) = 9615.4
    error    +0.16%  (datasheet table: 0.2%)
    limit    about ±1.5% for 8 data bits, double speed
    Arduino  Serial.begin(9600) picks the same 207
  3. A byte arrives: 'h'

    You type 'h'. It travels as 0x68 in a frame of 10 bits: a 0 start bit, eight data bits lowest first, then a 1 stop bit. Each bit lasts 1/9,615 s, so a byte takes 1.04 ms. The UART shifts it into UDR0.

    'h' = 0x68 = 01101000
    frame   0 0 0 0 1 0 1 1 0 1
            start, d0 .. d7 (lowest first), stop
    bit     104 µs     byte  10 bits = 1.04 ms
    speed   about 962 bytes a second
  4. The interrupt takes it

    Once the stop bit is in, the UART sets a flag and the RX interrupt fires: loop() pauses and the ISR runs. It reads UDR0 straight away. The chip holds only 2 received bytes, so the ISR must move each one out fast.

    RXC0 flag set  ->  ISR(USART_RX_vect) runs
    line 3   uint8_t c = UDR0;   c = 'h'
    reading UDR0 empties it and clears RXC0
    hardware buffer: 2 bytes ("a two level FIFO")
    at 9,615 baud a new byte can land every 1.04 ms
  5. Into the ring buffer

    The ISR works out n = (head + 1) % 8 = 1. That is not tail (0), so there is room: buf[0] = 'h' and head becomes 1. head is where the next byte goes; tail is the next one to read.

    ring     buf[8] in SRAM, head = 0, tail = 0 (empty)
    line 4   n = (0 + 1) % 8 = 1
    line 5   1 == tail (0)?  no, so there is room
    line 6   buf[0] = 'h';  head = 1
    head     where the ISR writes next
    tail     where loop() reads next
  6. More bytes, same ISR

    'i' and the newline arrive 1.04 ms apart, and each runs the same ISR: buf[1] = 'i', buf[2] = '\n', head = 3. Bytes waiting = (8 + head − tail) % 8 = 3, the sum Arduino's Serial.available() does.

    'i'   -> buf[1], head = 2
    '\n'  -> buf[2], head = 3
    waiting  (8 + 3 - 0) % 8 = 3
    loop() has not run a single line for these bytes
  7. loop() takes them out

    In loop(), head != tail means a byte is waiting. c = buf[tail] gives 'h' and tail moves on. Two more reads give 'i' and '\n'; now head == tail: empty. Only the ISR writes head and only loop() writes tail, so they never clash.

    line 7   head (3) != tail (0): a byte is waiting
    line 8   c = buf[0] = 'h'; tail = 1
             c = buf[1] = 'i';  tail = 2
             c = buf[2] = '\n'; tail = 3
    head == tail == 3: empty
    ISR writes head only, loop() writes tail only
  8. Round and round

    Next comes 'hello\n' while loop() reads. After slot 7, (7 + 1) % 8 = 0: head wraps back to slot 0, then 1. loop() has read 'h', 'e', 'l', so tail is 6. Waiting: (8 + 1 − 6) % 8 = 3.

    'hello\n' -> slots 3, 4, 5, 6, 7, then 0
    line 4   (7 + 1) % 8 = 0: the index wraps
    head = 1, tail = 6
    waiting  (8 + 1 - 6) % 8 = 3:  'l' 'o' '\n'
    no bytes move: only the two indexes go round
  9. Bug: the ring overflows

    Now loop() sits in delay(100); about 96 bytes can arrive meanwhile. A 20-byte line comes: 4 free slots fill, then (head + 1) % 8 == tail, so the ISR drops the other 16 and counts them in lost.

    loop()   delay(100): no reads for 100 ms
    arrive   100 ms / 1.04 ms = about 96 bytes
    ring     holds 7 at most (one slot stays empty)
    line     "the quick brown fox\n" (20 bytes)
    kept     "the "  dropped 16
    line 5   n == tail -> lost++  (lost = 16)
  10. Fix: read often, size it

    Read often, and size the ring for the longest gap between reads. A byte lands every 1.04 ms, so if loop() can be away 20 ms, about 20 arrive: use 32 slots. Arduino's Serial uses this same ring with 64 bytes on the Uno.

    gap 20 ms  ->  20 / 1.04 = about 20 bytes
    need 20 + 1 slots  ->  32 (a power of two)
    Arduino Serial on the Uno: 64-byte ring, 63 usable
      that is 66 ms of 9,600-baud text
    lost > 0 tells you it happened: check it while testing

اختبار يتاح بعد الخطوة الأخيرة.