Skip to content

Instantly share code, notes, and snippets.

@Robotto
Last active March 18, 2022 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Robotto/6557a3a636686efa9fca61e114979c96 to your computer and use it in GitHub Desktop.
Save Robotto/6557a3a636686efa9fca61e114979c96 to your computer and use it in GitHub Desktop.
ESP_UDP_BROADCAST.ino
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <WiFiClient.h>
String SSID = "IOT";
String PSK = "mrfunkfunk";
//UDP stuff:
WiFiUDP Udp;
const unsigned int udpPort = 1337;
const int UDP_PACKET_SIZE = 1; //change to whatever you need.
byte txBuffer[ UDP_PACKET_SIZE ]; //buffer to hold outgoing packets
IPAddress broadCastIP; //broadcast IP is determined dynamically from localIP() after successfull wifi connection.
void setup(void) {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
Serial.println("Hello!");
WiFi.hostname("John");
WiFi.begin(SSID, PSK);
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
Udp.begin(udpPort);
//Broadcast IP should be the same as local IP but ending in 255:
broadCastIP = WiFi.localIP();
broadCastIP[3] = 255;
}
uint8_t status = 0;
void loop(void) {
//HERE IS WHERE YOU CAN CHANGE STATUS SOMEHOW (uint8_t goes from 0 to 255)
if(status!=0) {
broadcast();
status=0;
}
}
void broadcast()
{
txBuffer[0] = status;
//txBuffer[1] = '\n'; //change UDP_PACKET_SIZE if you want to send more!
// Prints data to be transmitted in serial monitor
Serial.println("Transmitting: " + String((char*) txBuffer));
// Sends packet
Udp.beginPacket(broadCastIP, udpPort);
Udp.write(txBuffer, UDP_PACKET_SIZE);
Udp.endPacket();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment