[英]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.