AutoConnectWithFeedbackLED.ino 2.1 KB

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