// comano para instalar biblioteca serial pip install pyserial // rodar script python C:/xampp/htdocs/balanca/read_serial.py código python import serial import time try: ser = serial.Serial('COM5', 9600, timeout=1) print("Conectado à porta COM5") ser.flush() while True: if ser.in_waiting > 0: try: line = ser.readline().decode('utf-8').rstrip() print(f"Received: {line}") with open('C:/xampp/htdocs/balanca/serial_data.json', 'w') as json_file: json.dump({'peso': line}, json_file) except UnicodeDecodeError: raw_data = ser.readline() print(f"Raw data (Unicode Error): {raw_data}") else: print("No data received...") time.sleep(1) # Wait 1 second before retrying except serial.SerialException as e: print(f"Erro ao conectar à porta COM5: {e}") ___________________________________________________________________________ import serial import json import os import time def parse_weight(data): try: # Verifica se o primeiro byte é o caractere ASCII de início de texto (STX) if data[0] == 0x02: # Extrai os dígitos do peso indicado (6 bytes a partir da posição 4) weight_bytes = data[4:10] weight_str = weight_bytes.decode('ascii').strip() weight = int(weight_str) print(f"Peso interpretado: {weight}") return weight else: print("Caractere STX não encontrado no início da mensagem") return 0.0 # Se o formato não estiver correto, retorna 0 except Exception as e: print(f"Erro ao interpretar dados: {e}") return 0.0 # Força valor zero para qualquer erro de interpretação try: ser = serial.Serial('COM5', 9600, timeout=1) print("Conexão à porta COM5 realizada com sucesso") ser.flush() while True: if ser.in_waiting > 0: try: raw_data = ser.read(18) # Leia 18 bytes conforme a documentação print(f"Raw data received: {raw_data}") weight = parse_weight(raw_data) if os.access('C:/xampp/htdocs/balanca/', os.W_OK): try: with open('C:/xampp/htdocs/balanca/serial_data.json', 'w') as json_file: json.dump({'peso': weight}, json_file) print("Dados escritos no arquivo JSON.") except Exception as e: print(f"Falha ao escrever no arquivo JSON: {e}") else: print("Sem permissão para escrever no diretório.") except Exception as e: print(f"Erro ao processar os dados: {e}") else: print("No data received...") time.sleep(1) except serial.SerialException as e: print(f"Erro ao conectar à porta COM5: {e}") except Exception as e: print(f"Ocorreu um erro geral: {e}")