|
| 1 | +/* |
| 2 | + * This sketch sends random data over UDP on a ESP32 device |
| 3 | + * |
| 4 | + */ |
| 5 | +#include <WiFi.h> |
| 6 | +#include <WiFiUdp.h> |
| 7 | + |
| 8 | +// WiFi network name and password: |
| 9 | +const char * networkName = "your-ssid"; |
| 10 | +const char * networkPswd = "your-password"; |
| 11 | + |
| 12 | +//IP address to send UDP data to: |
| 13 | +// either use the ip address of the server or |
| 14 | +// a network broadcast address |
| 15 | +const char * udpAddress = "192.168.0.255"; |
| 16 | +const int udpPort = 3333; |
| 17 | + |
| 18 | +//Are we currently connected? |
| 19 | +boolean connected = false; |
| 20 | + |
| 21 | +//The udp library class |
| 22 | +WiFiUDP udp; |
| 23 | + |
| 24 | +void setup(){ |
| 25 | + // Initilize hardware serial: |
| 26 | + Serial.begin(115200); |
| 27 | + |
| 28 | + //Connect to the WiFi network |
| 29 | + connectToWiFi(networkName, networkPswd); |
| 30 | +} |
| 31 | + |
| 32 | +void loop(){ |
| 33 | + //only send data when connected |
| 34 | + if(connected){ |
| 35 | + //Send a packet |
| 36 | + udp.beginPacket(udpAddress,udpPort); |
| 37 | + udp.printf("Seconds since boot: %u", millis()/1000); |
| 38 | + udp.endPacket(); |
| 39 | + } |
| 40 | + //Wait for 1 second |
| 41 | + delay(1000); |
| 42 | +} |
| 43 | + |
| 44 | +void connectToWiFi(const char * ssid, const char * pwd){ |
| 45 | + Serial.println("Connecting to WiFi network: " + String(ssid)); |
| 46 | + |
| 47 | + // delete old config |
| 48 | + WiFi.disconnect(true); |
| 49 | + //register event handler |
| 50 | + WiFi.onEvent(WiFiEvent); |
| 51 | + |
| 52 | + //Initiate connection |
| 53 | + WiFi.begin(ssid, pwd); |
| 54 | + |
| 55 | + Serial.println("Waiting for WIFI connection..."); |
| 56 | +} |
| 57 | + |
| 58 | +//wifi event handler |
| 59 | +void WiFiEvent(WiFiEvent_t event){ |
| 60 | + switch(event) { |
| 61 | + case SYSTEM_EVENT_STA_GOT_IP: |
| 62 | + //When connected set |
| 63 | + Serial.print("WiFi connected! IP address: "); |
| 64 | + Serial.println(WiFi.localIP()); |
| 65 | + //initializes the UDP state |
| 66 | + //This initializes the transfer buffer |
| 67 | + udp.begin(WiFi.localIP(),udpPort); |
| 68 | + connected = true; |
| 69 | + break; |
| 70 | + case SYSTEM_EVENT_STA_DISCONNECTED: |
| 71 | + Serial.println("WiFi lost connection"); |
| 72 | + connected = false; |
| 73 | + break; |
| 74 | + } |
| 75 | +} |
0 commit comments