1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| import serial
def open_ser(): port = 'com1' baudrate = 9600 try: global ser ser=serial.Serial("/dev/ttyUSB1",9600,timeout=0.5) if(ser.isOpen()==True): print("串口打开成功") except Exception as exc: print("串口打开异常",exc)
def send_msg(data): try: send_datas = str(data) ser.write(str(send_datas).encode("gbk")) print("已发送数据:",send_datas) except Exception as exc: print("发送异常", exc)
def read_msg(): try: print("等待接收数据") while True: data = ser.read(ser.in_waiting).decode('gbk') if data != '': break print("已接受到数据:",data) except Exception as exc: print("读取异常",exc)
def close_ser(): try: ser.close() if ser.isOpen(): print("串口未关闭") else: print("串口已关闭") except Exception as exc: print("串口关闭异常", exc)
def find_com(): plist = list(serial.tools.list_ports.comports())
if len(plist) <= 0: print ("The Serial port can't find!") else: plist_0 =list(plist[0]) serialName = plist_0[0] serialFd = serial.Serial(serialName,9600,timeout = 60) print ("check which port was really used >",serialFd.name)
open_ser() data = input("input\n") send_msg(data) read_msg() close_ser()
|