我正在尝试在 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);
}
蟒蛇代码:
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,端口 0 接收到大小为 11 的数据包 内容:温度
在 python 上,我收到此消息: Traceback(最近一次调用最后一次):文件“C:/Users/enwan/Desktop/te/temp.py”,第 12 行,rec_data,addr = client_socket.recvfrom(2048)超时:定时出去
有什么帮助吗?