简体   繁体   English

如何使用 Python socket.send() 而不是 8 位发送一个 16 位字

[英]How can I send a 16 bit word useing Python socket.send() instead of a 8bit one

I trying to build up an SPI communication between my PC and a sensor-device.我试图在我的 PC 和传感器设备之间建立 SPI 通信。 For that, I use a TCP/IP to SPI Converter.为此,我使用 TCP/IP 到 SPI 转换器。 This side of the project is already working.该项目的这一方面已经在运作。 I can send something over TCP/IP to the converter and it does its job.我可以通过 TCP/IP 向转换器发送一些东西,它就完成了它的工作。

So where is the problem?那么问题出在哪里呢? I use the socket lib.我使用套接字库。 in Python 3.8 to do the TCP/IP side:在Python 3.8做TCP/IP端:

import socket, sys

TCP_IP = '192.168.100.100'
TCP_PORT = 1003
BUFFER_SIZE = 1024

s = socket.socket()

try:
    s.connect((TCP_IP, TCP_PORT))

except socket.error as mag:
    print (" Socket Erroer: " + str(mag))

s.send(b'\x8000')
data = s.recv(BUFFER_SIZE)
print(data)

What I want to do is to send (in binary ) 1000 0000 0000 0000 (= 8000 in Hex).我想要做的是发送(二进制1000 0000 0000 0000 (= 8000 十六进制)。 But python split the \x8000 into \x80\x00 and send it as two 8 bit words as 1000 0000 and then a second package 0000 0000. But the converter needs it as a 16 bit word otherwise, it fills it up.但是 python 将 \x8000 拆分为 \x80\x00 并将其作为两个 8 位字作为 1000 0000 发送,然后发送第二个 package 0000 0000。但是转换器需要它作为 16 位字,否则它会填满。 And the SPI-signal is 0000 0000 1000 0000 0000 0000 0000 0000, that's terrible, I can't read a single register without the first 8 bits. SPI 信号是0000 0000 1000 0000 0000 0000 0000 0000,太糟糕了,没有前 8 位我无法读取单个寄存器。

So is there a way to send /x8000 as one 16 bit word?那么有没有办法将 /x8000 作为一个 16 位字发送? I would also like to know more about the datatype (or whatever it is) b' something ' what is that?我还想了解更多关于数据类型(或任何数据类型)的信息 b' something '那是什么? What does it?它有什么作用?

Thank you for reading this.谢谢您阅读此篇。 I'm open to all suggestions and critics.我对所有建议和批评持开放态度。 I hope you can help me thank you for every attempt!我希望你能帮助我感谢你的每一次尝试!

You can use Python raw socket to include 16bits in a single packet and send.您可以使用 Python 原始套接字在单个数据包中包含 16 位并发送。

b'something' is python notation that converts the string "something" into its binary form(bytes), by default with utf-8 . b'something'是 python 符号,它将字符串“something”转换为二进制形式(字节),默认情况下为utf-8
For example if you code a=b'Hello' , a will have \x48\x65\x6C\x6C\x6F .例如,如果您编写a=b'Hello' ,则a将具有\x48\x65\x6C\x6C\x6F

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM