Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save professionalsna/245e9d5ab049bc31fad80c296d4832af to your computer and use it in GitHub Desktop.
Save professionalsna/245e9d5ab049bc31fad80c296d4832af to your computer and use it in GitHub Desktop.
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
// network configuration. dns server, gateway and subnet are optional.
// the media access control (ethernet hardware) address for the shield:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// the dns server ip
IPAddress dnServer(192, 168, 1, 1);
// the router's gateway address:
IPAddress gateway(192, 168, 1, 1);
// the subnet:
IPAddress subnet(255, 255, 255, 0);
//the IP address is dependent on your network
IPAddress ip(192, 168, 1, 27);
// udp config
unsigned int localPort = 808; // local port to listen for UDP packets
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];
char ReplyBuffer[]="OK";
EthernetUDP Udp;
void setup() {
pinMode(4, OUTPUT);
digitalWrite(4, LOW);
Serial.begin(9600);
// initialize the ethernet device
Serial.print("Connecting to Router");
//Ethernet.begin(mac);
Ethernet.begin(mac, ip, dnServer, gateway, subnet);
//Ethernet.begin(mac, ip, dnServer);
//print out the IP address
Serial.print("IP = ");
Serial.println(Ethernet.localIP());
//udp begin
Udp.begin(localPort);
}
void loop() {
//if theres data available, read a packet
int packetSize = Udp.parsePacket();
if(packetSize)
{
//read the packet into packetBuffer
Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
Serial.print("Received packet of size ");
Serial.println(packetSize);
//read packets datata...
Serial.print("From ");
IPAddress remote = Udp.remoteIP();
for (int i =0; i < 4; i++)
{
Serial.print(remote[i], DEC);
if (i < 3)
{
Serial.print(".");
}
}
Serial.print(", port ");
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
Serial.println("Contents:");
Serial.println(packetBuffer); //Dsiplay receive data to SerialPort
//read packet data.. end
//send a reply to the IP address and porst that send us the packet we received
Udp.beginPacket(Udp.remoteIP(),Udp.remotePort());
Udp.println(ReplyBuffer);
Udp.endPacket();
}
delay(10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment