import serial
import serial
import time
Com = 'com9'
Baudrate = 38400
Parity = serial.PARITY_EVEN
Timeout = 0.5
#Parity = serial.PARITY_NONE
Bytesize = serial.EIGHTBITS
serialFd = serial.Serial(port = Com,baudrate=Baudrate,parity=Parity)
print(serialFd.name)
print(serialFd.port)
print(serialFd.baudrate)
print(serialFd.bytesize)
print(serialFd.parity)
print(serialFd.stopbits)
print(serialFd.timeout)
#可以通过这样实现读取和定义波特率,停止位等等
PC端程序
import serial
import time
import threading
lock = threading.Lock()
Com = 'com9'
Baudrate = 38400
Parity = serial.PARITY_EVEN
Timeout = 0.5
#Parity = serial.PARITY_NONE
Bytesize = serial.EIGHTBITS
serialFd = serial.Serial(port = Com,baudrate=Baudrate,parity=Parity)
def ReadUART():
try:
while True:
count = serialFd.inWaiting()
if count >0:
lock.acquire()
data = serialFd.read(count)#.decode(encoding='ascii')
print("receive data is",data)
print("the number of receive %d" % count)
lock.release()
except KeyboardInterrupt:
if serial != None:
serial.close()
def WriteUART(mm):
try:
serialFd.write(mm.encode('utf-8'))
#serialFd.write(mm)
time.sleep(0.5)
print("write is ", mm, type(mm.encode('utf-8')))
except:
print("can't open the port")
ReadUARTThread = threading.Thread(target=ReadUART)
ReadUARTThread.setDaemon(True) #设置为守护线程 在结束后立马结束
ReadUARTThread.start()
i = 0
while i<20:
mm = 'lcy'
WriteUARTThread = threading.Thread(target = WriteUART,args=(mm,))
WriteUARTThread.start()
time.sleep(0.5)
i += 1
print('-'*10)
ARM端程序:
import serial
import time
import threading
lock = threading.Lock()
Com = '/dev/ttymxc4'
#Com = 'com9'
Baudrate = 38400
Parity = serial.PARITY_EVEN
Timeout = 0.5
#Parity = serial.PARITY_NONE
Bytesize = serial.EIGHTBITS
serialFd = serial.Serial(port = Com,baudrate=Baudrate,parity=Parity)
def ReadUART():
try:
while True:
count = serialFd.inWaiting()
if count >0:
lock.acquire()
data = serialFd.read(count)#.decode(encoding='ascii')
print("receive data is",data)
print("the number of receive %d" % count)
try:
WriteUART(data.decode(encoding='utf-8'))
except Exception as e:
print(e)
lock.release()
except KeyboardInterrupt:
if serial != None:
serial.close()
def WriteUART(mm):
try:
serialFd.write(mm.encode('utf-8'))
#serialFd.write(mm)
time.sleep(0.5)
print("write is ", mm, type(mm.encode('utf-8')))
except:
print("can't open the port")
#WriteUARTThread = threading.Thread(target=WriteUART,args=())
ReadUARTThread = threading.Thread(target=ReadUART)
#ReadUARTThread.setDaemon(True) #设置为守护线程 在结束后立马结束
ReadUARTThread.start()
print('-'*10)
运行时需要先运行ARM端的程序,一直在读,当读到PC端发来字符时就将字符转回去,原理很简单