如何从pyserial增量读取数据? [英] How to read data from pyserial incrementally?

查看:47
本文介绍了如何从pyserial增量读取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按 50 字节的块发送图像.我可以通过 Python 跨两个 xbees 串行发送它.现在,我想读取前 50 个字节并将其附加到一个变量,然后在接下来的 50 个字节之后附加它等等.但我根本找不到一个好的解决方案.有什么帮助吗?

I am trying to send an image by chunks of 50 bytes. I am able to send it via Python across two xbees serially. Now , i want to read first 50 bytes and append it to a variable , then after the next 50 bytes , append it and so on . But I cant find a good solution at all . Any help ?

我现在收到错误 f.write(data_stream[i:i+inc]).类型错误必须是字符串或缓冲区.发送方字节数、图像长度为6330.但在接收方是 129.我现在无处可去.## 发件人代码

I am now getting error f.write(data_stream[i:i+inc]). Type error must be string or buffer. The amount of bytes , length of image is 6330 in sending side . But in the receiving side it is 129. I am in no where now . ## Sender Code

import serial
from xbee import XBee

ser = serial.Serial('COM27',9600)  

fn='cameraman.jpeg'
f = open(fn, 'rb')
data = f.read()
f.close()
bytes = len(data)
inc=50
for i in range(0, bytes+1, inc): 
    string=data[i:i+inc]
    f.close()
     ser.write(string)

## Reciever Side
import serial

ser = serial.Serial(port='COM28', baudrate=9600,timeout=20)
inc=50
fileNames=[]
data_stream = []
while True:
  data_stream.append(ser.read(50))
  l=len(data_stream)
  print l
  for i in range(0, l+1, inc):
    fn1 = "image%s" % i
    fileNames.append(fn1)
    f = open(fn1, 'wb')
    f.write(data_stream[i:i+inc])
    print  fn1
    x.append(fn1)
    f.close()
 new_file = 'elmi666_image.jpg'
 dataList = []

 for fn in fileNames:
    f = open(fn, 'rb')
    dataList.append(f.read())
    f.close()
 f = open(new_file, 'wb')
 for data in dataList:
    f.write(data)
f.close()

推荐答案

使用 pyserial 读取 50 个字节的方法如下:

to read 50 bytes using pyserial here's how you should go:

from serial import Serial

data_stream = []
with Serial(SERIAL_PORT) as ser:
    while ser.open():
        data_stream.append(ser.read(50))
        # use data_stream

它从串行端口中每 50 个字节取一次,并将其附加到 data_stream 列表中.

which takes every 50 bytes from the serial port, and append it in the data_stream list.

这篇关于如何从pyserial增量读取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆