udp_test.ino 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * This sketch sends random data over UDP on a ESP32 device
  3. *
  4. */
  5. #include <WiFi.h>
  6. #include <WiFiUdp.h>
  7. // WiFi network name and password:
  8. const char * networkName = "Lord Voldemodem(2,4Ghz)";
  9. const char * networkPswd = "R4Eo62TPW06J00g";
  10. //IP address to send UDP data to:
  11. // either use the ip address of the server or
  12. // a network broadcast address
  13. const char * udpAddress = "192.168.178.21";
  14. const int udpPort = 8888;
  15. //Are we currently connected?
  16. boolean connected = false;
  17. //The udp library class
  18. WiFiUDP udp;
  19. byte command[27] = {0x20, 0x00, 0x00, 0x00, 0x16, 0x02, 0x62, 0x3A, 0xD5, 0xED, 0xA3, 0x01, 0xAE, 0x08, 0x2D, 0x46, 0x61, 0x41, 0xA7, 0xF6, 0xDC, 0xAF, 0xD3, 0xE6, 0x00, 0x00, 0x1E};
  20. void setup(){
  21. // Initilize hardware serial:
  22. Serial.begin(115200);
  23. //Connect to the WiFi network
  24. connectToWiFi(networkName, networkPswd);
  25. }
  26. void loop(){
  27. //only send data when connected
  28. if(connected){
  29. //Send a packet
  30. udp.beginPacket(udpAddress,udpPort);
  31. udp.write(command, 27);
  32. udp.endPacket();
  33. }
  34. //Wait for 1 second
  35. delay(1000);
  36. }
  37. void connectToWiFi(const char * ssid, const char * pwd){
  38. Serial.println("Connecting to WiFi network: " + String(ssid));
  39. // delete old config
  40. WiFi.disconnect(true);
  41. //register event handler
  42. WiFi.onEvent(WiFiEvent);
  43. //Initiate connection
  44. WiFi.begin(ssid, pwd);
  45. Serial.println("Waiting for WIFI connection...");
  46. }
  47. //wifi event handler
  48. void WiFiEvent(WiFiEvent_t event){
  49. switch(event) {
  50. case SYSTEM_EVENT_STA_GOT_IP:
  51. //When connected set
  52. Serial.print("WiFi connected! IP address: ");
  53. Serial.println(WiFi.localIP());
  54. //initializes the UDP state
  55. //This initializes the transfer buffer
  56. udp.begin(WiFi.localIP(),udpPort);
  57. connected = true;
  58. break;
  59. case SYSTEM_EVENT_STA_DISCONNECTED:
  60. Serial.println("WiFi lost connection");
  61. connected = false;
  62. break;
  63. }
  64. }