AutoConnectWithFeedbackLED.ino 2.1 KB

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