繁体   English   中英

无法使用以太网上的UDP套接字将数据包从arduino发送到python客户端

[英]can't send packets from arduino to python client using UDP socket over ethernet

我正在尝试在arduino Galielo Gen 2和python client之间打开UDP套接字。 我想将温度传感器捕获的值从arduino发送到客户端,并从客户端接收回响应。

Arduino代码:

#include <Ethernet.h> //Load Ethernet Library
#include <EthernetUdp.h> //Load UDP Library
#include <SPI.h> //Load the SPI Library

byte mac[] = { 0x98, 0x4F, 0xEE, 0x01, 0xF1, 0xBE }; //Assign a mac address
IPAddress ip( 192,168,1,207);
//IPAddress gateway(192,168,1, 1);
//IPAddress subnet(255, 255, 255, 0);
unsigned int localPort = 5454; 
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; 
String datReq;  
int packetSize; 
EthernetUDP Udp; 

void setup() {
Serial.begin(9600); 
Ethernet.begin(mac, ip);
Udp.begin(localPort); 
delay(2000);
}

void loop() {

   int sensor = analogRead (A0); 
   float voltage = ((sensor*5.0)/1023.0);
   float temp = voltage *100;
   Serial.println(temp);  
  packetSize = Udp.parsePacket();
  if(packetSize>0)
  { 
    Serial.print("Received packet of size ");
    Serial.println(packetSize);
    Serial.print("From ");
    IPAddress remote = Udp.remoteIP();
    for (int i =0; i < 4; i++)
    {
      Serial.print(remote[i], DEC);
      if (i < 3)
      {
        Serial.print(".");
      }
    }
    Serial.print(", port ");
    Serial.println(Udp.remotePort());

  Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); 
  Serial.println("Contents:");
  Serial.println(packetBuffer);
  String datReq(packetBuffer); 
  Udp.beginPacket(Udp.remoteIP(), 5454 ); 
  Udp.print(temp);
  Udp.endPacket(); 
  }
  delay(50);
}

python代码

from socket import *
import time

address = ( '192.168.1.207', 5454) 
client_socket = socket(AF_INET, SOCK_DGRAM) 
client_socket.settimeout(5)

while(1):

    data = "Temperature" 
    client_socket.sendto(data, address)
    rec_data, addr = client_socket.recvfrom(2048)
    print rec_data 

尝试代码后,这是在arduino上的结果:

从端口255.255.255.255接收的大小为11的数据包内容:温度

在python上,我得到了以下消息:追溯(最近一次调用):文件“ C:/Users/enwan/Desktop/te/temp.py”,第12行,在rec_data中,addr = client_socket.recvfrom(2048)超时:已超时出

有什么帮助吗?

您尚未初始化运行python代码的计算机的地址。

IPAddress remote = Udp.remoteIP();

它正在初始化为地址255.255.255.255,这不是有效的IP地址。 它似乎没有获得远程IP。

此外,在下一行中不会检索远程端口,并且将其设置为默认值0:

Udp.remotePort()

因此,arduino尝试将数据发送到端口0的ip地址255.255.255.255。结果,由于arduino无法正确寻址PC,因此python代码超时。

您将需要直接寻址python PC,即。 组:

IPAddress remoteip(192,168,1,X);     // whatever your PC ip address is
Udp.beginPacket(remoteip, 5454 ); 
Udp.print(temp);
Udp.endPacket(); 

UDP库可能有一种方法可以根据您在arduino上收到的数据包来设置ip和端口,但是您必须阅读如何获取该信息。

您从未在Python脚本中调用bind()将UDP套接字绑定到端口,因此操作系统不知道您希望UDP套接字接收任何数据包,因此从不传递任何数据包。

这是您需要具备的:

client_socket = socket(AF_INET, SOCK_DGRAM) 
client_socket.bind(("", portNum))  # where portNum is the port number your Arduino is sending to
[...]
rec_data, addr = client_socket.recvfrom(2048)

暂无
暂无

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

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