Python:通过uart发送块之间的中断

时间:2017-08-31 07:06:09

标签: python serial-port uart interruption bytestream

我正在通过uart发送一些数据。我把单个文件分成5120byte部分(块)。在发送这个块之间存在中断(可能基于波特率值)我需要捕获这个中断并从发送数据切换到接收数据。这有可能吗?

发送数据的示例代码:

ser = serial.Serial(
    port='/dev/ttyS0',
    baudrate=115200)

def send():
    with open("path_to_my_file_to_send", "rb") as fh:
        while True:
            chunk = fh.read(5120)
            if not chunk: break
            ser.write(chunk)

def reveice():
global receivedData
receivedData = ""
time.sleep(0.001)
while ser.inWaiting() > 0:
    receivedData= ser.read(1)
while True:
    if len(receivedData ) == 1:
        print ("received data")
        break
    else:
        print("no received data")
        break

2 个答案:

答案 0 :(得分:1)

好的,我发现了一些可以改变这个问题的东西。 BaudRate只告诉我单块发送多长时间。但无论如何在每个块之后都有中断但是导致波特率设置值大(值超过1000000)可以在通过uart传输文件时提供间隙。如果我稍微增加一点波特率这个间隙是不规则的,但如果我们去4000000(我们在传输文件期间做其他操作)在每个块之后出现间隙。

答案 1 :(得分:0)

所以你可以做的是从你的发送中发送数据然后等待接收发送确认。这样semd就会知道它的数据已经成功收到,然后就可以发送新的数据了。如果不是它可以重新发送它或者它收到中断msg它可以停止。 在发送方,你可以收到然后发送确认。该确认可以是msgs的长度,可以在发送端验证。

ser = serial.Serial(
port='/dev/ttyS0',
baudrate=115200)

def send():
 with open("path_to_my_file_to_send", "rb") as fh:
  while True:
   chunk = fh.read(5120)
    if not chunk: break
    ser.write(chunk)
    #for interupt just send#
    ser.write(b'interupt')

def reveice():
 global receivedData
 receivedData = ""
 time.sleep(0.001)
 while ser.inWaiting() > 0:
  receivedData= ser.read(1)
  if b'interupt' in receivedData:
   #go to recv mode

 while True:
  if len(receivedData) == 1:
   print ("received data")
   break
 else:
  print("no received data")
  break