AutoConnectWithFeedbackLED.ino 2.1 KB

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