我正在將 UDP 資料包從我的計算機發送到 esp8266,但在收到資料包后,它在 Arduino 串行監視器中看起來像這樣:

我發送的原始資料:

這是接收端的代碼塊(esp8266):
void udp_rcv()
{
int packetSize = UDP.parsePacket();
if (packetSize) {
Serial.print("Received packet! Size: ");
Serial.println(packetSize);
int len = UDP.read(packet, 255);
if (len > 0)
{
packet[len] = '\0';
}
Serial.print("Packet received: ");
Serial.println(packet[0]);
}
這是使用 python 從我的電腦發送 UDP 資料包的代碼:
pygame.event.pump()
roll = mapping(joystick.get_axis(0),-1,1,1000,2000)
pitch = mapping(joystick.get_axis(1),1,-1,1000,2000)
yaw = mapping(joystick.get_axis(2),-1,1,1000,2000)
throttle = mapping(joystick.get_axis(3),1,-1,1000,2000)
mode = joystick.get_button(6)
# Be sure to always send the data as floats
# The extra zeros on the message are there in order for the other scripts to do not complain about missing information
message = [roll, pitch, yaw, throttle, mode, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
buf = struct.pack('>' 'd' * len(message), *message)
sock.sendto(buf, (UDP_IP, UDP_PORT))
print( message)
我要做的就是使用我的操縱桿游戲手柄輸入通過 UDP 協議將其發送到 esp8266
uj5u.com熱心網友回復:
要跨不同平臺發送和接收資料,您需要了解您發送的資料型別和資料結構以及發送方和接收方的位元組序。
關于你的 Python 代碼
我不確定你為什么明確指定大端序>來打包資料,大多數現代計算機都使用小端序而不是大端序(除非你有摩托羅拉 68000 或 PowerPC 機器),此外所有的 MCU,如 Uno 和ESP8266 是小端MCU。<因此,指定 little endian with來打包資料會更有意義。
其次,您假設您的資料在其中,double但如果您查看螢屏截圖message,mode絕對不是一個double,而是一個int(在大多數現代 PC 上,int是 32 位長)。
因此,不要使用以下方式打包資料:
buf = struct.pack('>' 'd' * len(message), *message)
你真正應該做的是:
buf = struct.pack('<ddddiddddddddd', *message)
關于您的 Arduino 代碼
從 Python 代碼發送的資料是一系列位元組,在 C 中可以表示為:
struct __attribute__((packed)) JoyStick {
double roll;
double pitch;
double yaw;
double throttle;
int32_t mode;
double array[9];
};
由于資料包資料是一個陣列uint8_t(或char您可能宣告的),因此將資料復制到JoyStick_t型別變數中會更容易,這樣您就可以將資料作為struct.
int packetSize = UDP.parsePacket();
if (packetSize) {
Serial.printf("Received %d bytes\n", packetSize);
if (UDP.read(packet, packetSize) > 0)) {
JoyStick myJoystick; //create a struct
memcpy(&myJoystick, packet, packetSize); //copy packet array to the a struct
Serial.printf("%f %f %f %f %d\n",
myJoystick.roll,
myJoystick.pitch,
myJoystick.yaw,
myJoystick.throttle,
myJoystick.mode); // access the data in the struct
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/462579.html
