import json import serial import os import sys import time # Function to clear the screen def clear_screen(): if os.name == 'nt': # for Windows _ = os.system('cls') else: # for macOS and Linux(here, os.name is 'posix') _ = os.system('clear') # Setup serial connection serial_port = '/dev/ttyACM0' baud_rate = 9600 # Adjust this depending on your device try: ser = serial.Serial(serial_port, baud_rate) print("Serial port opened successfully. Reading data...") buffer = '' # Initialize a buffer to accumulate data while True: data_in = ser.read(ser.inWaiting() or 1) # Read available data or block for one byte if data_in: # Decode byte to string and accumulate in buffer buffer += data_in.decode('utf-8') # Check if a complete message has been received (indicated by a newline) if '\n' in buffer: # Split buffer at the first newline; [0] is the complete message, [1] is the start of the next message complete_message, buffer = buffer.split('\n', 1) # Clear the screen before printing new values clear_screen() # Attempt to parse the JSON string try: data_dict = json.loads(complete_message) data_array = data_dict["data"] # Print each value in the data array as separate rows for i, value in enumerate(data_array, start=1): print(f"Channel {i}: {value}") except json.JSONDecodeError: print("Error decoding JSON. Check the format of the incoming data.") except serial.SerialException as e: print(f"Error opening serial port: {e}") except KeyboardInterrupt: print("Program terminated by user.") finally: ser.close() # Ensure the serial port is closed on exit