AutoConnectWithFeedbackLED.ino 2.3 KB

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