我正在尝试打开arduino Galielo Gen 2和python客户端之间的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代码:
^{pr2}$尝试代码后,以下是arduino的结果:
收到大小为11的数据包 从255.255.255.255,端口0 内容: 温度
在python上我得到了这样的消息: 回溯(最近一次呼叫): 文件“C:/Users/enwan/Desktop/te/温度py“,第12行,英寸 rec_data,addr=客户端_插座.recvfrom(2048年) 超时:超时
有什么帮助吗?在
您尚未初始化运行python代码的计算机的地址。在
正在将此初始化为地址255.255.255.255,该地址不是有效的IP地址。它似乎没有得到远程IP。在
此外,在以下行中不会检索远程端口,而是将其设置为默认值0:
^{pr2}$因此,arduino试图将数据发送到端口0的ip地址255.255.255.255。结果,python代码有一个超时,因为arduino没有正确地寻址PC。在
您需要直接寻址您的python PC,即Set:
UDP库可能有一种方法可以根据您在arduino上收到的数据包来设置ip和端口,但是您必须了解如何获取这些信息。在
您从未在Python脚本中调用bind()将UDP套接字绑定到端口,因此操作系统不知道您希望UDP套接字接收任何数据包,因此从不向您传递任何数据包。在
以下是您需要的:
相关问题 更多 >
编程相关推荐