开发者

Problem sending Bytes with pySerial and socat

开发者 https://www.devze.com 2023-02-21 20:07 出处:网络
I want to send some bytes via pySerial.I created virtual serial ports with socat for testing purposes:

I want to send some bytes via pySerial. I created virtual serial ports with socat for testing purposes:

socat PTY,link=./ptyp1,b9600 PTY,link=./ptyp2,b9600

Here's the python code:

ser = serial.Serial('./ptyp1')
x = struct.pack('B',2)
print binascii.hexlify(x) # 02
ser.write(x)
y = ser.read(2)
print binascii.hexlify(y) # 5e42

The ouput I get开发者_StackOverflow社区:

02   # x
5e42 # y

The output I expect:

02 # x
02 # y

What am I doing wrong here? Is it socat or python?

Edit:

I just noticed some other strange behavior for different x values. Here the ouput:

x = 12  => y = 5E 52 0D 0A 5E 50
x = 100 => y = 100 # why does it work here?

Solution:

The problem was that I read on the same port I wrote to. If I get it right socat "connects" the two ports as "in" and "out". So I have to read on ./ptyp2 if I write to ./ptyp1. After that, everything is fine.


The problem was that I read on the same port I wrote to. If I get it right socat "connects" the two ports as "in" and "out". So I have to read on ./ptyp2 if I write to ./ptyp1. After that, everything is fine.


I have installed socat to test your code. I have run this line :

socat PTY,link=./ptyp1,b9600 PTY,link=./ptyp2,b9600

Then, the following code works :

from binascii import hexlify
from serial import Serial, struct

ser = Serial('ptyp1')
x = struct.pack('B', 2)
print hexlify(x) # 02
ser.write(x)
y = ser.read()
print hexlify(y) # 5E
y = ser.read()
print hexlify(y) # 42

Ouput :

02
5e
42


What you seem to be getting back is the string "^B". It's possible that socat (or something else along the way) is interpreting the byte you're sending (\x02) as a control code of some sort.

Off the top of my head, Ctrl-B is the page-back mnemonic, but I'm not sure.

0

精彩评论

暂无评论...
验证码 换一张
取 消