linux下实现按下回车才发送的串口助手
找了半天全他妈是实时输入的,一个按回车才输入的软件都没有,遂自己写一个
Python真方便吧()
点击查看代码
import serial
import time
import sys
import threading
import argparse
from termcolor import colored
#!/usr/bin/env python3
def parse_args():
parser = argparse.ArgumentParser(description='Serial port communication tool with colored output')
parser.add_argument('-D', '--device', required=True, help='Serial port device (e.g., /dev/ttyUSB0)')
parser.add_argument('-b', '--baudrate', type=int, default=115200, help='Baudrate (default: 115200)')
parser.add_argument('--rx-color', default='green', help='Color for received data (default: green)')
parser.add_argument('--tx-color', default='cyan', help='Color for transmitted data (default: cyan)')
return parser.parse_args()
def receive_thread(ser, rx_color):
while True:
try:
if ser.in_waiting > 0:
data = ser.read(ser.in_waiting)
if data:
print(colored(f"RX: {data.decode('utf-8', errors='replace')}", rx_color))
except Exception as e:
print(colored(f"Error in receive thread: {e}", 'red'))
break
time.sleep(0.01)
def main():
args = parse_args()
try:
ser = serial.Serial(
port=args.device,
baudrate=args.baudrate,
bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
timeout=0.1
)
print(f"Connected to {args.device} at {args.baudrate} baud")
except Exception as e:
print(colored(f"Error opening serial port: {e}", 'red'))
sys.exit(1)
# Start receive thread
rx_thread = threading.Thread(target=receive_thread, args=(ser, args.rx_color), daemon=True)
rx_thread.start()
# Main loop for user input
try:
while True:
user_input = input("> ")
if user_input.lower() == "exit":
break
# Add newline to the input and send
message = user_input + '\n'
ser.write(message.encode('utf-8'))
print(colored(f"TX: {repr(message)}", args.tx_color))
except KeyboardInterrupt:
print("\nExiting...")
finally:
if ser.is_open:
ser.close()
print("Serial port closed")
if __name__ == "__main__":
main()

浙公网安备 33010602011771号