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 transmitclass 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 valuesuint16_t value2;uint16_t value3;};//add the methods to serialise the data onto the network, in a derived classclass SUDPMessage : public SequencedMessage {public:SUDPMessage(void);byte getSequence(void) { return seq_; }void send(UDP*, IPAddress*, uint16_t);};//initialise the static memberbyte SequencedMessage::seq_= 0;//constructor increments the sequenceSUDPMessage::SUDPMessage(void) {SequencedMessage::seq_++;}//send the message to the networkvoid SUDPMessage::send(UDP* udp, IPAddress* dstIP, uint16_t dstPort) { //remember to copy the static member into the messagesequence = seq_; //send the packetudp->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);}
« Go back
Powered by Help Desk Software HESK, in partnership with SysAid Technologies