Go Down

Topic: Help required Adding WifiManager to a basic LED project Please. (Read 273 times) previous topic - next topic

fiatbravodriver

Sep 22, 2018, 09:49 am Last Edit: Sep 22, 2018, 10:05 am by fiatbravodriver Reason: Posting errors
Hello Community,

I am just getting started here and playing around with a cheap LED display. This sketch works fine but I want to convert it to use Wifimanager instead of having the network credentials hard coded.

I have spent days following documentation and messing around but to no avail.


I would be very grateful for any help.


Code: [Select]



#include <YoutubeApi.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>


//------------LED------------//
#include "DigitLedDisplay.h"

/* Arduino Pin to Display Pin
   D1 to DIN,
   D3 to CS,
   D2 to CLK */
  
DigitLedDisplay ld = DigitLedDisplay(5, 0, 4);


//------- I will Replace the following ------
char ssid[] = "*******"; // your network SSID (name)
char password[] = "*******";  // your network key
#define API_KEY "***********"  // your google apps API Token
#define CHANNEL_ID "********" // makes up the url of channel


//------------LED------------//

/////////////////////////////////

WiFiClientSecure client;
YoutubeApi api(API_KEY, client);

int api_mtbs = 60000; //mean time between api requests
long api_lasttime;   //last time api request has been done

long subs = 0;

void setup() {

  Serial.begin(9600);

//------------LED------------//

  /* Set the brightness min:1, max:15 */
  ld.setBright(10);

  /* Set the digit count */
  ld.setDigitLimit(8);


  // Set WiFi to station mode and disconnect from an AP if it was Previously
  // connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  // Attempt to connect to Wifi network:
  Serial.print("Connecting Wifi: ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  IPAddress ip = WiFi.localIP();
  Serial.println(ip);


}

void loop() {


  ld.printDigit(api.channelStats.subscriberCount);
  delay(500);



  if (millis() > api_lasttime + api_mtbs)  {
    if(api.getChannelStatistics(CHANNEL_ID))
    {
      Serial.println("---------Stats---------");
      Serial.print("Subscriber Count: ");
      Serial.println(api.channelStats.subscriberCount);
      Serial.print("View Count: ");
      Serial.println(api.channelStats.viewCount);
      Serial.print("Comment Count: ");
      Serial.println(api.channelStats.commentCount);
      Serial.print("Video Count: ");
      Serial.println(api.channelStats.videoCount);
      // Probably not needed :)
      //Serial.print("hiddenSubscriberCount: ");
      //Serial.println(api.channelStats.hiddenSubscriberCount);
      Serial.println("------------------------");

    }
    api_lasttime = millis();
  }


  ld.clear();

 
  
}


wvmarle

It appears you either failed to read the "how to use this forum" sticky, or you ignored the instructions given in it about a.o. how to post your code, which now appears mangled. Smileys have no place in computer code.
Quality of answers is related to the quality of questions. Good questions will get good answers. Useless answers are a sign of a poor question.


wvmarle

No WiFiManager in that sketch, maybe that's the problem?
Quality of answers is related to the quality of questions. Good questions will get good answers. Useless answers are a sign of a poor question.

fiatbravodriver

#4
Sep 22, 2018, 10:10 am Last Edit: Sep 22, 2018, 10:14 am by fiatbravodriver Reason: trying to provide help to get help
No WiFiManager in that sketch, maybe that's the problem?
Thanks, I am trying to get wifimanager added. I added the code and could get it to compile but could never get the access point to show. I stripped by bodged attempt out as I thought it would be easier for me to get assistance and save someone time having to work out whats good and not.

My other approach would be if someone can change this wifimanager enabled sketch to just use the led display from the first sketch.

Code: [Select]


#include <YoutubeApi.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <Wire.h>                 
#include <Adafruit_GFX.h>         
#include "Adafruit_LEDBackpack.h" 


// For storing configurations
#include "FS.h"
#include <ArduinoJson.h>

// WiFiManager Libraries
#include <DNSServer.h>            //Local DNS Server used for redirecting all rs to the configuration portal
#include <ESP8266WebServer.h>     //Local WebServer used to serve the configuration portal
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager WiFi Configuration Magic

const int resetConfigPin = D8; //When high will manually reset the wifi manager config

char apiKey[45] = "******";
char channelId[30] = "*****";

// label the displays with their i2c addresses
struct {
  uint8_t           addr;         // I2C address
  Adafruit_7segment seg7;         // 7segment object
} disp[] = {
  { 0x71, Adafruit_7segment() },  // High digits
  { 0x70, Adafruit_7segment() }   // Low digits
};

WiFiClientSecure client;
YoutubeApi *api;

unsigned long api_mtbs = 60000; //mean time between api requests
unsigned long api_lasttime;   //last time api request has been done

long subscriberCount = 0;

// flag for saving data
bool shouldSaveConfig = false;

//callback notifying us of the need to save config
void saveConfigCallback () {
  Serial.println("Should save config");
  shouldSaveConfig = true;
}

void setup() {

  Serial.begin(115200);
 
  for(uint8_t i=0; i<2; i++) {       // Initialize displays
    disp[i].seg7.begin(disp[i].addr);
    disp[i].seg7.clear();
    disp[i].seg7.writeDisplay();
  }

  if (!SPIFFS.begin()) {
    Serial.println("Failed to mount FS");
    return;
  }

  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
  loadConfig();

  WiFiManager wifiManager;
  wifiManager.setSaveConfigCallback(saveConfigCallback);

  // Adding an additional config on the WIFI manager webpage for the API Key and Channel ID
  WiFiManagerParameter customApiKey("apiKey", "API Key", apiKey, 50);
  WiFiManagerParameter customChannelId("channelId", "Channel ID", channelId, 35);
  wifiManager.addParameter(&customApiKey);
  wifiManager.addParameter(&customChannelId);

  // If it fails to connect it will create a YouTube-Counter access point
  wifiManager.autoConnect("YouTube-Counter", "supersecret");

  strcpy(apiKey, customApiKey.getValue());
  strcpy(channelId, customChannelId.getValue());

  if (shouldSaveConfig) {
    saveConfig();
  }

  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  // Force Config mode if there is no API key
  if(strcmp(apiKey, "") > 0) {
    Serial.println("Init YouTube API");
    api = new YoutubeApi(apiKey, client);
  } else {
    Serial.println("Forcing Config Mode");
    forceConfigMode();
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  IPAddress ip = WiFi.localIP();
  Serial.println(ip);

}

bool loadConfig() {
  File configFile = SPIFFS.open("/config.json", "r");
  if (!configFile) {
    Serial.println("Failed to open config file");
    return false;
  }

  size_t size = configFile.size();
  if (size > 1024) {
    Serial.println("Config file size is too large");
    return false;
  }

  // Allocate a buffer to store contents of the file.
  std::unique_ptr<char[]> buf(new char[size]);

  configFile.readBytes(buf.get(), size);

  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& json = jsonBuffer.parseObject(buf.get());

  if (!json.success()) {
    Serial.println("Failed to parse config file");
    return false;
  }

  strcpy(apiKey, json["apiKey"]);
  strcpy(channelId, json["channelId"]);
  return true;
}

bool saveConfig() {
  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& json = jsonBuffer.createObject();
  json["apiKey"] = apiKey;
  json["channelId"] = channelId;

  File configFile = SPIFFS.open("/config.json", "w");
  if (!configFile) {
    Serial.println("Failed to open config file for writing");
    return false;
  }

  json.printTo(configFile);
  return true;
}

void forceConfigMode() {
  Serial.println("Reset");
  WiFi.disconnect();
  Serial.println("Dq");
  delay(500);
  ESP.restart();
  delay(5000);
}

void loop() {

  if (digitalRead(resetConfigPin) == HIGH) {
    forceConfigMode();
  }
  if (millis() - api_lasttime > api_mtbs) {
    if(api->getChannelStatistics(channelId))
    {
      Serial.println("---------Stats---------");
      Serial.print("Subscriber Count: ");
      Serial.println(api->channelStats.subscriberCount);
      Serial.print("View Count: ");
      Serial.println(api->channelStats.viewCount);
      Serial.print("Comment Count: ");
      Serial.println(api->channelStats.commentCount);
      Serial.print("Video Count: ");
      Serial.println(api->channelStats.videoCount);
      // Probably not needed :)
      //Serial.print("hiddenSubscriberCount: ");
      //Serial.println(api->channelStats.hiddenSubscriberCount);
      Serial.println("------------------------");
     
      subscriberCount = api->channelStats.subscriberCount;
     
      uint16_t hi = subscriberCount / 10000, // Value on left (high digits) display
               lo = subscriberCount % 10000; // Value on right (low digits) display
      disp[0].seg7.print(hi, DEC);   // Write values to each display...
      disp[1].seg7.print(lo, DEC);

      // print() does not zero-pad the displays; this may produce a gap
      // between the high and low sections. Here we add zeros where needed...
      if(hi) {
        if(lo < 1000) {
          disp[1].seg7.writeDigitNum(0, 0);
          if(lo < 100) {
            disp[1].seg7.writeDigitNum(1, 0);
            if(lo < 10) {
              disp[1].seg7.writeDigitNum(3, 0);
            }
          }
        }
       } else {
         disp[0].seg7.clear(); // Clear 'hi' display
        }
       disp[0].seg7.writeDisplay(); // Push data to displays
       disp[1].seg7.writeDisplay();


    }
    api_lasttime = millis();
  }
}




Kind Regards
J

fiatbravodriver

I am a bit further ahead I just cant get the MAX7219 to actually display anything.


Code: [Select]


#include <YoutubeApi.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>

#include "DigitLedDisplay.h"
DigitLedDisplay ld = DigitLedDisplay(5, 0, 4);

#include <DoubleResetDetector.h>
// For entering Config mode by pressing reset twice
// Available on the library manager (DoubleResetDetector)
// https://github.com/datacute/DoubleResetDetector

#include <ArduinoJson.h>
// Required for the YouTubeApi and used for the config file
// Available on the library manager (ArduinoJson)
// https://github.com/bblanchon/ArduinoJson

#include <WiFiManager.h>
// For configuring the Wifi credentials without re-programing
// Availalbe on library manager (WiFiManager)
// https://github.com/tzapu/WiFiManager

// For storing configurations
#include "FS.h"

// Additional libraries needed by WiFiManager
#include <DNSServer.h>            //Local DNS Server used for redirecting all rs to the configuration portal
#include <ESP8266WebServer.h>     //Local WebServer used to serve the configuration portal

char apiKey[45] = "*******";
char channelId[30] = "********";

WiFiClientSecure client;
YoutubeApi *api;

unsigned long api_mtbs = 60000; //mean time between api requests
unsigned long api_lasttime;   //last time api request has been done

long subs = 0;

// flag for saving data
bool shouldSaveConfig = false;

// Number of seconds after reset during which a
// subseqent reset will be considered a double reset.
// This sketch uses drd.stop() rather than relying on the timeout
#define DRD_TIMEOUT 10

// RTC Memory Address for the DoubleResetDetector to use
#define DRD_ADDRESS 0

DoubleResetDetector drd(DRD_TIMEOUT, DRD_ADDRESS);

//callback notifying us of the need to save config
void saveConfigCallback () {
  Serial.println("Should save config");
  shouldSaveConfig = true;
}

void configModeCallback (WiFiManager *myWiFiManager) {
  Serial.println("Entered config mode");
  Serial.println(WiFi.softAPIP());

  // You could indicate on your screen or by an LED you are in config mode here

  // We don't want the next time the boar resets to be considered a double reset
  // so we remove the flag
  drd.stop();
}

void setup() {

  Serial.begin(115200);

  //------------LED------------//

  /* Set the brightness min:1, max:15 */
  ld.setBright(10);

  /* Set the digit count */
  ld.setDigitLimit(8);

  if (!SPIFFS.begin()) {
    Serial.println("Failed to mount FS");
    return;
  }

  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
  loadConfig();

  WiFiManager wifiManager;
  wifiManager.setAPCallback(configModeCallback);
  wifiManager.setSaveConfigCallback(saveConfigCallback);

  // Adding an additional config on the WIFI manager webpage for the API Key and Channel ID
  WiFiManagerParameter customApiKey("apiKey", "API Key", apiKey, 50);
  WiFiManagerParameter customChannelId("channelId", "Channel ID", channelId, 35);
  wifiManager.addParameter(&customApiKey);
  wifiManager.addParameter(&customChannelId);

  if (drd.detectDoubleReset()) {
    Serial.println("Double Reset Detected");
    wifiManager.startConfigPortal("YouTube-Counter", "supersecret");
  } else {
    Serial.println("No Double Reset Detected");
    wifiManager.autoConnect("YouTube-Counter", "supersecret");
  }

  strcpy(apiKey, customApiKey.getValue());
  strcpy(channelId, customChannelId.getValue());

  if (shouldSaveConfig) {
    saveConfig();
  }

  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  // Force Config mode if there is no API key
  if(strcmp(apiKey, "") > 0) {
    Serial.println("Init YouTube API");
    api = new YoutubeApi(apiKey, client);
  } else {
    Serial.println("Forcing Config Mode");
    forceConfigMode();
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  IPAddress ip = WiFi.localIP();
  Serial.println(ip);

  drd.stop();

}

bool loadConfig() {
  File configFile = SPIFFS.open("/config.json", "r");
  if (!configFile) {
    Serial.println("Failed to open config file");
    return false;
  }

  size_t size = configFile.size();
  if (size > 1024) {
    Serial.println("Config file size is too large");
    return false;
  }

  // Allocate a buffer to store contents of the file.
  std::unique_ptr<char[]> buf(new char[size]);

  configFile.readBytes(buf.get(), size);

  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& json = jsonBuffer.parseObject(buf.get());

  if (!json.success()) {
    Serial.println("Failed to parse config file");
    return false;
  }

  strcpy(apiKey, json["apiKey"]);
  strcpy(channelId, json["channelId"]);
  return true;
}

bool saveConfig() {
  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& json = jsonBuffer.createObject();
  json["apiKey"] = apiKey;
  json["channelId"] = channelId;

  File configFile = SPIFFS.open("/config.json", "w");
  if (!configFile) {
    Serial.println("Failed to open config file for writing");
    return false;
  }

  json.printTo(configFile);
  return true;
}

void forceConfigMode() {
  Serial.println("Reset");
  WiFi.disconnect();
  Serial.println("Dq");
  delay(500);
  ESP.restart();
  delay(5000);
}

void loop() {

  if (millis() - api_lasttime > api_mtbs) {
    if(api->getChannelStatistics(channelId))
    {
      Serial.println("---------Stats---------");
      Serial.print("Subscriber Count: ");
      Serial.println(api->channelStats.subscriberCount);
      Serial.print("View Count: ");
      Serial.println(api->channelStats.viewCount);
      Serial.print("Comment Count: ");
      Serial.println(api->channelStats.commentCount);
      Serial.print("Video Count: ");
      Serial.println(api->channelStats.videoCount);
      // Probably not needed :)
      //Serial.print("hiddenSubscriberCount: ");
      //Serial.println(api->channelStats.hiddenSubscriberCount);
      Serial.println("------------------------");

    }
    api_lasttime = millis();
  }
}


Go Up