Knowledgebase
emscom > emscom Help Desk > Knowledgebase

Search help:


Arduino UDP device control block example

Solution

The following example implements a simple device control block (DCB) which is continually transmitted from an Arduino Uno fitted with an Wiznet 5100 Ethernet shield.  A static sequence counter is implemented within the DCB, which might be used by the reciever to detect dropped packets.

The example shows how C's weak type casting can be used to populate a contigous structure within an instance of a C++ class.  The code also demonstrates how static members of a class, are separated from instances of the class.

#include <stdio.h>
#include <stdlib.h>
#include <Streaming.h>

#include <SPI.h>
#include <w5100.h>
#include <Ethernet.h>
#include <EthernetUdp.h>

// our message structure, the data we want to transmit
class SequencedMessage {
protected:
static byte seq_;   //note the static member is not stored contiguously 
byte sequence;    // so we need a property to hold the value when we send 
public:
uint16_t value1;  // just some values
uint16_t value2;
uint16_t value3;
};

//add the methods to serialise the data onto the network, in a derived class
class SUDPMessage : public SequencedMessage {
public:
SUDPMessage(void);
byte getSequence(void) { return seq_; }
void send(UDP*, IPAddress*, uint16_t);
};

//initialise the static member
byte SequencedMessage::seq_= 0;

//constructor increments the sequence
SUDPMessage::SUDPMessage(void) {
SequencedMessage::seq_++;
}

//send the message to the network
void SUDPMessage::send(UDP* udp, IPAddress* dstIP, uint16_t dstPort) {
        //remember to copy the static member into the message
sequence = seq_;

       //send the packet
udp->beginPacket(*dstIP, dstPort);
udp->write((byte*) this, sizeof(SequencedMessage));
udp->endPacket();
}

IPAddress dstIP(192, 168, 200, 64);
const uint16_t srcPort = 2000;
const uint16_t dstPort = 2000;

EthernetUDP udp;

void setup(void) {
Serial.begin(9600);
Serial << F("Setup...\r\n");
udp.begin(srcPort);
Serial << F("UDP bound to port ") << srcPort << "\r\n"
}

void loop(void) {
SUDPMessage* sMessage = new SUDPMessage;

sMessage->value1 = 10;
sMessage->value2 = 20;
sMessage->value3 = 30;
sMessage->send(&udp, &dstIP, dstPort);
Serial << "Sent msg seq=" << sMessage->getSequence() << "\r\n"; 

delete sMessage;
delay(1000);
}

 
Was this article helpful? yes / no
Related articles Arduino static class members
Dynamic Arrays
Arduino Processing Sketch to receive UDP Device Control Block
Arduino WiFiClient (TCP)
Read fixed length serial packet
Article details
Article ID: 53
Category: Arduino
Date added: 03-01-2014 05:59:39
Views: 904
Rating (Votes): Article rated 3.0/5.0 (8)

 
« Go back

 
Powered by Help Desk Software HESK, in partnership with SysAid Technologies