How to read data from pyserial incrementally?

老子叫甜甜 提交于 2019-12-12 04:45:55

问题


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 ?

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()

回答1:


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

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



来源:https://stackoverflow.com/questions/22115386/how-to-read-data-from-pyserial-incrementally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!