# Tactiverge Academy — companion code for "Serial communication and UART"
# Lesson: https://tactiverge.win/academy/embedded-systems/embedded-communication/serial-and-uart/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
def uart_frame(byte, parity=None):
    """Return the line levels for one UART frame, in the order they are sent."""
    bits = [0]                                     # start bit (line pulled low)
    data = [(byte >> i) & 1 for i in range(8)]     # least significant bit first
    bits += data
    if parity == "even":
        bits.append(sum(data) % 2)                 # makes the count of 1s even
    bits.append(1)                                 # stop bit (back to idle high)
    return bits

print("A  8N1:", uart_frame(ord("A")))
print("A  8E1:", uart_frame(ord("A"), parity="even"))
print("C  8E1:", uart_frame(ord("C"), parity="even"))

for baud in [9600, 115200]:
    bit_us = 1e6 / baud
    print(f"{baud:6d} baud: {bit_us:6.2f} us per bit, {baud // 10:5d} bytes per second")
