串口读写代码连接冲突 [英] Clash of connection between serial port read and write codes
问题描述
这是从z1节点读取的代码
This is the code that reads from the z1 mote
while True:
if not ser.isOpen():
try:
ser = serial.Serial(z1port, z1baudrate,timeout=0, parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)
except:
sys.exit("Error connecting device")
queue = ser.inWaiting()
if queue > 0:
data = ser.read(1000)
print data
time.sleep(0.2)
这是我用它来写入节点的代码
And this is the code that I have that I use it to write to the mote
# some event-driven code here so that whenever a message is received then do:
print(str(msg.payload))
ser = serial.Serial("/dev/ttyUSB1")
print ser.isOpen()
ser.write(msg.payload)
第二个代码的输出应该是 if msg.payload = "hello":
The output from the second code should be if msg.payload = "hello":
hello
True
但随后读取的代码停止从串行端口读取(代码将运行但没有输入).我该如何解决这个问题?
But then the read code stops reading from the serial port (the code will run but no input). How do I solve this problem?
推荐答案
我使用@mhopeng 的想法编写了一个实现多线程编程的代码,其中一个函数处理读取,另一个处理写入.在它们都被调用之前,我将连接到串行端口并将其传递给两个线程.
I used the idea by @mhopeng to write a code that implements multithreading programming, where one function handles the reading and the other handles the writing. And before they are both called, I will connect to the serial port and pass it to both of the threads.
我不得不使用多线程,因为我需要一个单独的线程来随时根据用户输入进行写入.
I had to use multithreading because I needed a separate thread for writing at any time from the user input.
这篇关于串口读写代码连接冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!