from machine import Pin
from time import sleep
import ssd1306
import machine
# Set up I2C for the OLED display
i2c = machine.I2C(0, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
# Set up the serial communication to receive data
uart = machine.UART(1, baudrate=9600, tx=17, rx=16) # Use UART1 for serial communication
while True:
if uart.any(): # Check if data is available in the buffer
data = uart.read() # Read the data
if data:
try:
decoded_data = data.decode('utf-8').strip() # Decode the bytes to string and strip extra spaces or newlines
# Display the received data on the OLED screen
oled.fill(0) # Clear the display
oled.text("Received Data:", 0, 0)
oled.text(decoded_data, 0, 10)
oled.show()
except Exception as e:
# If there is an error during decoding, show error message
oled.fill(0)
oled.text("Error decoding:", 0, 0)
oled.text(str(e), 0, 10)
oled.show()
else:
oled.fill(0)
oled.text("No data received.", 0, 0)
oled.show()
else:
# Optionally display a message when no data is received
oled.fill(0)
oled.text("Waiting for data...", 0, 0)
oled.show()
sleep(1)