Pyserial Sending More than One Byte

こ雲淡風輕ζ 提交于 2019-12-01 07:32:44

问题


First time poster.

Before I start, I just want to say that I am a beginner programmer so bear with me, but I can still follow along quite well.

I have a wireless device called a Pololu Wixel, which can send and receive data wirelessly. I'm using two of them. One to send and one to receive. It's USB so it can plug straight into my Raspberry Pi or PC, so all I have to do is connect to the COM port through a terminal to read and write data to it. It comes with a testing terminal program that allows me to send 1-16 bytes of info. I've done this and I've sent and received 2 bytes (which is what I need) with no problem.

Now here's my problem: When I open up the Ubuntu terminal and use Pyserial to connect to the correct sending Wixel COM Port and write a value larger than 255, my receiving COM port, which is connected to another instance of Terminal also using Pyserial, doesn't read the right value, hence I think I'm not being able to read and write two bytes, but only one. After doing something reading online in the pyserial documentation, I believe, not know, that Pyserial can only read and write 5,6,7, or 8 bits at a time.

I hope my problem is obvious now. How the heck can I write 2 bytes worth of info to the COM port to my device and send it to the other device which needs to read those 2 bytes through, all using pyserial?

I hope this all makes sense, and I would greatly appreciate any help.

Thanks

UPDATE Okay, I think I've got this going now. So I did:

import serial

s=serial.Serial(3) //device #1 at COM Port 4 (sending)
r=serial.Serial(4) //device #4 at COM Port 5 (receiving)

s.timeout=1
r.timeout=1

s.write('0x80')
r.readline()
  //Output said: '0x80'

s.write('hh')
r.readline()
  //Output said: 'hh'

Honestly, I think this solves my problem. Maybe there never was a problem to begin with. Maybe I can take my 16bit binary data from the program, example "1101101011010101", turn it into characters (I've seen something called char() before I think that's it)

then use s.write('WHATEVER') then use r.readline() and convert back to binary


回答1:


You'll likely need to pull your number apart into multiple bytes, and send the pieces in little endian or big endian order.

EG:

low_byte = number % 256
high_byte = number // 256

That should get you up to 65535. You can reconstruct the number on the other side with high_byte * 256 + low_byte.



来源:https://stackoverflow.com/questions/20108635/pyserial-sending-more-than-one-byte

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