python接收字符并回显

 1 # -*- coding: utf-8 -*
 2 import serial
 3 import time
 4 # 打开串口
 5 ser = serial.Serial("/dev/ttyAMA0", 9600) #"/dev/ttyAMA0"为树莓派串口 win7为com7
 6 def main():
 7     while True:
 8         # 获得接收缓冲区字符
 9         count = ser.inWaiting()
10         if count != 0:
11             # 读取内容并回显
12             recv = ser.read(count)
13             ser.write(recv)
14         # 清空接收缓冲区
15         ser.flushInput()
16         # 必要的软件延时
17         time.sleep(0.1)
18     
19 if __name__ == '__main__':
20     try:
21         main()
22     except KeyboardInterrupt:
23         if ser != None:
24             ser.close()

python接收字符并回显

你可能感兴趣的:(python接收字符并回显)