AutoConnectWithFeedbackLED.ino 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // LED will blink when in config mode
  2. #include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
  3. //for LED status
  4. #include <Ticker.h>
  5. Ticker ticker;
  6. #ifndef LED_BUILTIN
  7. #define LED_BUILTIN 13 // ESP32 DOES NOT DEFINE LED_BUILTIN
  8. #endif
  9. int LED = LED_BUILTIN;
  10. void tick()
  11. {
  12. //toggle state
  13. digitalWrite(LED, !digitalRead(LED)); // set pin to the opposite state
  14. }
  15. //gets called when WiFiManager enters configuration mode
  16. void configModeCallback (WiFiManager *myWiFiManager) {
  17. Serial.println("Entered config mode");
  18. Serial.println(WiFi.softAPIP());
  19. //if you used auto generated SSID, print it
  20. Serial.println(myWiFiManager->getConfigPortalSSID());
  21. //entered config mode, make led toggle faster
  22. ticker.attach(0.2, tick);
  23. }
  24. void setup() {
  25. WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
  26. // put your setup code here, to run once:
  27. Serial.begin(115200);
  28. //set led pin as output
  29. pinMode(LED, OUTPUT);
  30. // start ticker with 0.5 because we start in AP mode and try to connect
  31. ticker.attach(0.6, tick);
  32. //WiFiManager
  33. //Local intialization. Once its business is done, there is no need to keep it around
  34. WiFiManager wm;
  35. //reset settings - for testing
  36. // wm.resetSettings();
  37. //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
  38. wm.setAPCallback(configModeCallback);
  39. //fetches ssid and pass and tries to connect
  40. //if it does not connect it starts an access point with the specified name
  41. //here "AutoConnectAP"
  42. //and goes into a blocking loop awaiting configuration
  43. if (!wm.autoConnect()) {
  44. Serial.println("failed to connect and hit timeout");
  45. //reset and try again, or maybe put it to deep sleep
  46. ESP.restart();
  47. delay(1000);
  48. }
  49. //if you get here you have connected to the WiFi
  50. Serial.println("connected...yeey :)");
  51. ticker.detach();
  52. //keep LED on
  53. digitalWrite(LED, LOW);
  54. }
  55. void loop() {
  56. // put your main code here, to run repeatedly:
  57. }