我在访问收到的udp字符串时遇到问题,但我可以通过串口获取它。我只需要使用loop()函数中的ethercard库将传入的udp数据转换为变量,这样我就可以在我的程序中使用它们。这就是我正在使用的代码:
#include <EtherCard.h>
#include <IPAddress.h>
#define STATIC 1 // set to 1 to disable DHCP (adjust myip/gwip values below)
#if STATIC
// ethernet interface ip address
static byte myip[] = { 192,168,1,200 };
// gateway ip address
static byte gwip[] = { 192,168,1,1 };
#endif
// ethernet mac address - must be unique on your network
static byte mymac[] = { 0x70,0x69,0x69,0x2D,0x30,0x31 };
byte Ethernet::buffer[500]; // tcp/ip send and receive buffer
//callback that prints received packets to the serial port
void udpSerialPrint(word port, byte ip[4], const char *data, word len) {
Serial.println(data);
}
void setup(){
Serial.begin(57600);
Serial.println("\n[backSoon]");
if (ether.begin(sizeof Ethernet::buffer, mymac, 10) == 0)
Serial.println( "Failed to access Ethernet controller");
#if STATIC
ether.staticSetup(myip, gwip);
#else
if (!ether.dhcpSetup())
Serial.println("DHCP failed");
#endif
ether.printIp("IP: ", ether.myip);
ether.printIp("GW: ", ether.gwip);
ether.printIp("DNS: ", ether.dnsip);
//register udpSerialPrint() to port 1337
ether.udpServerListenOnPort(&udpSerialPrint, 1337);
//register udpSerialPrint() to port 42.
ether.udpServerListenOnPort(&udpSerialPrint, 42);
}
void loop(){
//this must be called for ethercard functions to work.
ether.packetLoop(ether.packetReceive());
//? incoming = data; <--- this is my problem
//Serial.println(incoming);
}
它只是EtherPL库附带的UDPListener示例的略微修改版本。 谢谢
答案 0 :(得分:0)
我自己仍然处于陡峭的学习曲线,但已经设法在单位之间进行UDP谈话,所以希望以下帮助。怀疑最快的方法是创建一个全局变量,例如:
char gUDPdata [30] =“”;
然后在你的udpSerialPrint例程中添加以下内容以获得快速而脏的结果。这会将“数据”复制到您可以在主循环中看到的全局变量。
Serial.println(data);
data[0] = 0;
strcpy(data, gUDPdata);
然后在你的主循环中,应该在udpSerialPrint例程中生成与Serial.print相同的内容。
Serial.println(gUDPdata);