通过UDP发送传感器数据

时间:2017-05-16 15:01:06

标签: arduino udp declaration send

我试图通过UDP发送传感器数据。目前我正在努力解决#34;包装问题。 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();
  }
}

1 个答案:

答案 0 :(得分:1)

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

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