Created
September 3, 2024 16:37
-
-
Save anecdata/751c42dd7fc790d1bcbd912cb8514759 to your computer and use it in GitHub Desktop.
UART test code - sender & receiver, with CRC and ACK
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import board | |
import time | |
import random | |
import binascii | |
SENDER = True # False for RECEIVER | |
RECV_WAIT = 5_000_000_000 | |
def send(): | |
outbuf = bytearray(b'') | |
data_length = random.randrange(0, 32) | |
for _ in range(0, data_length): | |
outbuf.extend(f"{random.randrange(0, 256):02X}".encode()) | |
crc = f"{binascii.crc32(outbuf):08x}".encode() | |
outbuf.extend(crc) | |
outbuf.extend(b'\n') | |
written = uart.write(outbuf) | |
print(f"🔵 WRITTEN: {written} {outbuf} {crc}") | |
def recv(): | |
rcvd = False | |
if uart.in_waiting: | |
waiting = uart.in_waiting | |
inbuf = uart.readline() | |
if inbuf: | |
body = inbuf[0:len(inbuf)-9] | |
crc_calc = f"{binascii.crc32(body):08x}".encode() | |
crc_read = inbuf[len(inbuf)-9:len(inbuf)-1] | |
if crc_calc == crc_read: | |
rcvd = True | |
print(f"🟢 READ: {waiting} {len(inbuf)} {crc_calc} {crc_read} {inbuf}") | |
else: | |
print(f"🟠 READ: {waiting} {len(inbuf)} {crc_calc} {crc_read} {inbuf}") | |
else: | |
print(f"🟡 {waiting} nothing read") # shouldn't get here | |
else: | |
# print(f"⚪️ nothing waiting") | |
pass | |
return rcvd | |
uart = board.UART() | |
while True: | |
if SENDER: | |
send() | |
if not recv(): | |
print(f"🔴 no ACK received") | |
time.sleep(1) | |
else: | |
if recv(): | |
send() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment