Skip to content

Instantly share code, notes, and snippets.

@Bolukan
Last active February 8, 2019 20:28
Show Gist options
  • Save Bolukan/5bcffaa8682c9ceecee8963e8e0175cd to your computer and use it in GitHub Desktop.
Save Bolukan/5bcffaa8682c9ceecee8963e8e0175cd to your computer and use it in GitHub Desktop.
Base code for using ESP8266WiFi
#if !defined(ESP8266)
#error This file is for ESP8266 only
#endif
#include <Arduino.h>
// WiFi
#include <ESP8266WiFi.h> // https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/ESP8266WiFi.h
// #include "secrets.h" // Uncomment this line and add secrets.h to your project
#ifndef SECRETS_H
#define SECRETS_H
const char WIFI_SSID[] = "ssid";
const char WIFI_PASSWORD[] = "password";
#endif
// ******************** WIFI ********************
// More events: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/ESP8266WiFiGeneric.h
void onSTAConnected(WiFiEventStationModeConnected e /*String ssid, uint8 bssid[6], uint8 channel*/) {
Serial.printf("WiFi Connected: SSID %s @ BSSID %.2X:%.2X:%.2X:%.2X:%.2X:%.2X Channel %d\n",
e.ssid.c_str(), e.bssid[0], e.bssid[1], e.bssid[2], e.bssid[3], e.bssid[4], e.bssid[5], e.channel);
}
void onSTADisconnected(WiFiEventStationModeDisconnected e /*String ssid, uint8 bssid[6], WiFiDisconnectReason reason*/) {
Serial.printf("WiFi Disconnected: SSID %s BSSID %.2X:%.2X:%.2X:%.2X:%.2X:%.2X Reason %d\n",
e.ssid.c_str(), e.bssid[0], e.bssid[1], e.bssid[2], e.bssid[3], e.bssid[4], e.bssid[5], e.reason);
// Reason: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/ESP8266WiFiType.h
}
void onSTAGotIP(WiFiEventStationModeGotIP e /*IPAddress ip, IPAddress mask, IPAddress gw*/) {
Serial.printf("WiFi GotIP: localIP %s SubnetMask %s GatewayIP %s\n",
e.ip.toString().c_str(), e.mask.toString().c_str(), e.gw.toString().c_str());
}
// ******************** SETUP ********************
void setup(){
// WiFi
static WiFiEventHandler e1, e2, e4;
/*
other setup code
*/
// WiFi events
e1 = WiFi.onStationModeConnected(onSTAConnected);
e2 = WiFi.onStationModeDisconnected(onSTADisconnected);
e4 = WiFi.onStationModeGotIP(onSTAGotIP);
WiFi.mode(WIFI_STA);
WiFi.setAutoConnect(false); // do not automatically connect on power on to the last used access point
WiFi.setAutoReconnect(true); // attempt to reconnect to an access point in case it is disconnected
WiFi.persistent(false); // Store no SSID/PASSWORD in flash
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}
// ******************** LOOP ********************
void loop()
{
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment