我正在尝试使用UDP与PC的Arduino UNO +以太网板进行通信,但是无法正确完成。
事实:
Arduino代码:
#include <SPI.h> // needed for Arduino versions later than 0018
#include <Ethernet.h>
#include <EthernetUdp.h> // UDP library from: bjoern@cs.stanford.edu 12/30/2008
byte mac\[\] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x3D};
IPAddress ip(192, 168, 1, 6); //IP of the arduino ethernet board
char link_IP\[\] = {192, 168, 1, 3}; //IP of the PC
unsigned int localPort = 51115; // local port to listen on
char message\[\] = "hello PC!"; //message intended to sended from the arduino
char packetBuffer\[UDP_TX_PACKET_MAX_SIZE\]; // UDP_TX_PACKET_MAX_SIZE = 24
unsigned long millis_before = millis(); //variable for delaying 5 seconds the message
EthernetUDP Udp;
void setup()
{
Serial.begin(9600); //serial com for debugging
Ethernet.begin(mac, ip); //starting Ethernet
if (Udp.begin(localPort)==1) Serial.println("port UDP is open"); //starting UDP on 51115
else while(1); //if UDP not open, infinte bucle
}
void loop()
{
if (millis_before + 5000 < millis()) //loop for waiting 5 seconds between messages
{
if (Udp.beginPacket(link_IP, 51115)==1) Serial.print("TX ready - "); // UDP packet to PC port 51115, if beginPacket returns 1 is OK
Serial.print("Lenght:");
Serial.print(Udp.write(message, 9)); //returns the length of the message
if (Udp.endPacket()==1) Serial.println(" - Sent!"); //if endPacket returns 1, is OK
millis_before = millis(); //reset timer
}
delay(10);
int packetSize = Udp.parsePacket(); //check size of UDP packet
if (packetSize)
{
IPAddress remote = Udp.remoteIP(); //save remote IP
for (int i = 0; i < 4; i++) //bucle for printing the remote IP
{
Serial.print(remote\[i\], DEC);
if (i < 3) Serial.print(".");
}
Serial.print(", port ");
Serial.println(Udp.remotePort()); //printing the remote port
Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); // read the packet into packetBufffer
// send a echo to the IP address and port that sent us the packet we received
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(packetBuffer, packetSize);
Udp.endPacket();
}
}
在将第一条消息发送给Arduino并收到ECHO之后,您可以在此处找到PacketSender和Wireshark捕获:
我非常感谢您的帮助。预先感谢
答案 0 :(得分:0)
已解决。问题出在IP的char数组格式中,用于传递数据包。我将其定义为4个字符数组,但应将其定义为文本字符数组:
char link_IP[] = "192.168.1.3"; //correct !!
char link_IP[] = {192, 168, 1, 3}; // Wrong