【问题标题】:Sending sensor data via UDP通过 UDP 发送传感器数据
【发布时间】:2017-05-16 15:01:05
【问题描述】:

我正在尝试通过 UDP 发送传感器数据。目前,我正在为 UDP 数据包的“打包”而苦苦挣扎。它说当我尝试发送它时没有声明“incomingData”。 我将不胜感激任何建议。 代码如下。 谢谢你:)

//Version 1.012

//necessary libraries
#include <SPI.h>
#include <Ethernet2.h>
#include <EthernetUdp2.h>

//Pin settings
#define CTD 19

//Network Settings
byte mac[] = { 0x90, 0xA2, 0xDA, 0x10, 0xEC, 0xAB };  //set MAC Address Ethernet Shield (Backside)
byte ip[]  = { XXX, XXX, X, X };                      //set IP-Address
byte gateway[] = { XXX, XXX, X, X };                  //set Gateway
byte subnet[]  = { 255, 255, 255, 1 };                //set Subnetmask


//local UDP port to listen on
unsigned int localPort = 4000;

//Recipient IP
IPAddress RecipientIP(127, 0, 0, 1);

//Recipient UDP port
unsigned int RecipientPort = 4444;

//Buffer for sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];

//EthernetUDP instance
EthernetUDP Udp;



void setup()
{
   //Start Ethernet
  Ethernet.begin(mac, ip);

  //Start UDP
  Udp.begin(localPort);

  //for debug only
  Serial.begin(9600);

  //Serial baud rate for CTD
  Serial1.begin(1200);

  //Version 1.012
Serial.print("Version 1.012");

  //CTD
  pinMode(CTD, INPUT);
}

void loop()
{

//If CTD is sending
if (Serial1.available())
{
  //read incoming data
  int incomingData = Serial1.read();

  //for debug only
  Serial.print("Data: ");
  Serial.println(incomingData, BIN);
}

//Send UDP packets
int packetSize = Udp.parsePacket();
  if (packetSize) {

    // read the packet into packetBufffer
    Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);

    // send to the IP address and port
    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    Udp.write(incomingData);
    Udp.endPacket();
  }
}

【问题讨论】:

  • 我认为 if (packetSize) 在您尝试发送数据时首先在 if (Serial1.available()) 之前执行,因此 incomingData 没有被声明,但您正尝试在 if (packetSize) 中使用它。因此你得到了错误。

标签: arduino udp declaration send


【解决方案1】:

在您的代码中,您已将 incomingData 声明为 intvoid loop () 函数内 if (Serial1.available())

但是如果上面的 if 循环失败,incomingData 将不会被声明并且说packetsize 大于零(数据包可用)然后if (packetSize) 段将被执行。因此incomingData 未被声明但它是使用过。这就是你得到你所说的错误的原因。

【讨论】:

  • incomingData设为全局并检查。
  • 有用吗
  • 0 反对票 接受 感谢您的建议。这绝对是有道理的;)我仍在为 UDP 数据包的传输而苦苦挣扎。我使用“Wireshark”作为传入数据包的控件。 UDP包的IP地址是我固定PC配置的IP吧?我更改了脚本,但仍然没有收到任何包裹:/ 谢谢!这是我的代码:0 反对票接受@Billa 谢谢您的建议。这绝对是有道理的;)我仍在为 UDP 数据包的传输而苦苦挣扎。我使用“Wireshark”作为传入数据包的控件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多