Skip to content

Instantly share code, notes, and snippets.

@hareendranmg
Created August 18, 2023 10:01
Show Gist options
  • Save hareendranmg/377059f27543e9e5151adea0ac49e0ec to your computer and use it in GitHub Desktop.
Save hareendranmg/377059f27543e9e5151adea0ac49e0ec to your computer and use it in GitHub Desktop.
This script sends hexadecimal data to a serial port, records the response along with timestamps, and logs the interactions in "serial_log.txt". Useful for serial communication testing and tracking.
import serial
import sys
from datetime import datetime
def send_serial_request(port, baudrate, hex_value):
# Create a serial port object
ser = serial.Serial(port=port, baudrate=baudrate, timeout=1)
# Check if the port is open
if ser.is_open:
print(f"Serial port opened: {port}")
else:
print("Failed to open serial port")
return
try:
# Convert the hex value to bytes
hex_bytes = bytearray.fromhex(hex_value)
# Send the hex bytes over the serial port
ser.write(hex_bytes)
# Read the response from the serial port
response = ser.read(
ser.in_waiting or 20
) # Read all available bytes or at least 20 byte
# Convert the response to a hex
response = response.hex()
# Get the current timestamp
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Print the response
print("Response:", response)
# Write the request, response, and timestamp to a file
with open("serial_log.txt", "a+") as f:
f.write(f"Timestamp: {timestamp}\n")
f.write(f"Request: {hex_value}\n")
f.write(f"Response: {response}\n")
f.write(f"*****************************************\n")
finally:
# Close the serial port
ser.close()
print("Serial port closed")
if __name__ == "__main__":
if len(sys.argv) != 4:
print("Usage: python script_name.py port baudrate hex_value")
else:
port_name = sys.argv[1]
baud_rate = int(sys.argv[2])
hex_value = sys.argv[3]
send_serial_request(port_name, baud_rate, hex_value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment