电脑与水枪通信的上位机程序

发布于: Mon 21 April 2025
作者 zzcko

类别 Python.

微信直播评论抓取后,需要与水枪等进行通信,这是上位机程序,用Python实现的USB转串口程序。

#!python

import serial
import time

ser = serial.Serial(
    port='COM3',
    baudrate=115200,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout=1,
)

def main():
    try:
        if not ser.is_open:
            ser.open()

        while True:
            if ser.in_waiting > 0:
                data = ser.readline().decode('utf-8').rstrip()
                print(f'{data}')

            ser.write(b'0')
            time.sleep(0.25)
            ser.write(b'255')
            time.sleep(0.25)
            # ser.write(999)

    except Exception as e:
        print(f"Error: {e}")
    finally:
        print(f"finally")
        ser.close()

if __name__ == '__main__':
    main()

链接