How to combine my sketch with wifi manager?

I want to see a sketch where you have tried to add some code to disable the PIR.

this is one of all that I tried but not work…plz help how to add virtual pin to on off pir sensor?

#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>
#include <DHT.h>

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "xxx";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "PULPSTONE";
char pass[] = "internet";
BLYNK_WRITE(V1){
  int control4DigitalPins = param.asInt();
  if(control4DigitalPins == 1){
    digitalWrite(D2, HIGH);
    digitalWrite(D3, HIGH);
    digitalWrite(D7, HIGH);
    digitalWrite(D8, HIGH);
  }
  else{
    digitalWrite(D2, LOW);
    digitalWrite(D3, LOW);
    digitalWrite(D7, LOW);
    digitalWrite(D8, LOW);
  }
}

#define DHTPIN 2          // What digital pin we're connected to
#define ledPower 16

// Uncomment whatever type you're using!
#define DHTTYPE DHT11     // DHT 11
//#define DHTTYPE DHT22   // DHT 22, AM2302, AM2321
//#define DHTTYPE DHT21   // DHT 21, AM2301
#define pirPin 14                // Input for HC-S501
int pValue;                   // Place to store read PIR Value
int pinValue;                   //Variable to read virtual pin

DHT dht(DHTPIN, DHTTYPE);
SimpleTimer timer;

// This function sends Arduino's up time every second to Virtual Pin (5).
// In the app, Widget's reading frequency should be set to PUSH. This means
// that you define how often to send data to Blynk App.
void sendSensor()
{
  float h = dht.readHumidity();
  float t = dht.readTemperature(); // or dht.readTemperature(true) for Fahrenheit

  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  int p=digitalRead(14);
   
  // You can send any value at any time.
  // Please don't send more that 10 values per second.
  Blynk.virtualWrite(V5, h);
  Blynk.virtualWrite(V6, t);
 if(p==HIGH)
 Blynk.notify("Gerakan terdeteksi");
}
BLYNK_WRITE(V0)
{
 pinValue = param.asInt();    
} 

void setup()
{
  pinMode (ledPower,OUTPUT);
  digitalWrite (ledPower, HIGH);
  pinMode(14,INPUT);
  Serial.begin(9600); // See the connection status in Serial Monitor
  Blynk.begin(auth, ssid, pass);

  dht.begin();

  // Setup a function to be called every second
  timer.setInterval(1000L, sendSensor);
}

void loop()
{
  Blynk.run(); // Initiates Blynk
  timer.run(); // Initiates SimpleTimer
}

Take a look at this:

bool pirEnabled = false;

BLYNK_WRITE(V1){
  if(pirEnabled == true){
    int control4DigitalPins = param.asInt();
    if(control4DigitalPins == 1){
      digitalWrite(D2, HIGH);
      digitalWrite(D3, HIGH);
      digitalWrite(D7, HIGH);
      digitalWrite(D8, HIGH);
    }
    else{
      digitalWrite(D2, LOW);
      digitalWrite(D3, LOW);
      digitalWrite(D7, LOW);
      digitalWrite(D8, LOW);
    }
  }
}

BLYNK_WRITE(V2){  // button in switch mode
  if(param.asInt()){
    pirEnabled = true;  
  }
  else{
    pirEnabled = false;     
  }
}
1 Like

Actually I was thinking you had PIR tied to V1, maybe remove the outer if statement I added in V1 and use this in sendSensor() function.

 if((p==HIGH) && (pirEnabled == true)){
    Blynk.notify("Gerakan terdeteksi");
 }
#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>
#include <DHT.h>

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "xxx";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "PULPSTONE";
char pass[] = "internet";
bool pirEnabled = false;

BLYNK_WRITE(V1){
  if(pirEnabled == true){
    int control4DigitalPins = param.asInt();
    if(control4DigitalPins == 1){
      digitalWrite(D2, HIGH);
      digitalWrite(D3, HIGH);
      digitalWrite(D7, HIGH);
      digitalWrite(D8, HIGH);
    }
    else{
      digitalWrite(D2, LOW);
      digitalWrite(D3, LOW);
      digitalWrite(D7, LOW);
      digitalWrite(D8, LOW);
    }
  }
}

BLYNK_WRITE(V2){  // button in switch mode
  if(param.asInt()){
    pirEnabled = true;  
  }
  else{
    pirEnabled = false;     
  }
}

#define DHTPIN 2          // What digital pin we're connected to
#define ledPower 16

// Uncomment whatever type you're using!
#define DHTTYPE DHT11     // DHT 11
//#define DHTTYPE DHT22   // DHT 22, AM2302, AM2321
//#define DHTTYPE DHT21   // DHT 21, AM2301

DHT dht(DHTPIN, DHTTYPE);
SimpleTimer timer;

// This function sends Arduino's up time every second to Virtual Pin (5).
// In the app, Widget's reading frequency should be set to PUSH. This means
// that you define how often to send data to Blynk App.
void sendSensor()
{
  float h = dht.readHumidity();
  float t = dht.readTemperature(); // or dht.readTemperature(true) for Fahrenheit

  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  int p=digitalRead(14);
   
  // You can send any value at any time.
  // Please don't send more that 10 values per second.
  Blynk.virtualWrite(V5, h);
  Blynk.virtualWrite(V6, t);
 if((p==HIGH) && (pirEnabled == true)){
    Blynk.notify("Gerakan terdeteksi");
 }

void setup()
{
  pinMode (ledPower,OUTPUT);
  digitalWrite (ledPower, HIGH);
  pinMode(14,INPUT);
  Serial.begin(9600); // See the connection status in Serial Monitor
  Blynk.begin(auth, ssid, pass);

  dht.begin();

  // Setup a function to be called every second
  timer.setInterval(1000L, sendSensor);
}

void loop()
{
  Blynk.run(); // Initiates Blynk
  timer.run(); // Initiates SimpleTimer
}


error compilling…any suggestion
exit status 1
a function-definition is not allowed here before ‘{’ token

You are missing a closing bracket at the end of sendSensor but also see my note above about V1.

so which part should I edit

Ad the V2 button and the revised if statement round Blynk.notifty(). Remove outer if that I added to V1 unless you also want V2 to control V1.

im edited this code but V2 is not working to stop n start pir sensor…
note : uploading done (success but V2 not working)

#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>
#include <DHT.h>

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "xxx";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "PULPSTONE";
char pass[] = "internet";
bool pirEnabled = false;

BLYNK_WRITE(V1){
  if(pirEnabled == true){
    int control4DigitalPins = param.asInt();
    if(control4DigitalPins == 1){
      digitalWrite(D2, HIGH);
      digitalWrite(D3, HIGH);
      digitalWrite(D7, HIGH);
      digitalWrite(D8, HIGH);
    }
    else{
      digitalWrite(D2, LOW);
      digitalWrite(D3, LOW);
      digitalWrite(D7, LOW);
      digitalWrite(D8, LOW);
    }
  }
}

BLYNK_WRITE(V2){  // button in switch mode
  if(param.asInt()){
    pirEnabled = true;  
  }
  else{
    pirEnabled = false;     
  }
}

#define DHTPIN 2          // What digital pin we're connected to
#define ledPower 16

// Uncomment whatever type you're using!
#define DHTTYPE DHT11     // DHT 11
//#define DHTTYPE DHT22   // DHT 22, AM2302, AM2321
//#define DHTTYPE DHT21   // DHT 21, AM2301

DHT dht(DHTPIN, DHTTYPE);
SimpleTimer timer;

// This function sends Arduino's up time every second to Virtual Pin (5).
// In the app, Widget's reading frequency should be set to PUSH. This means
// that you define how often to send data to Blynk App.
void sendSensor()
{
  float h = dht.readHumidity();
  float t = dht.readTemperature(); // or dht.readTemperature(true) for Fahrenheit

  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  int p=digitalRead(14);
   
  // You can send any value at any time.
  // Please don't send more that 10 values per second.
  Blynk.virtualWrite(V5, h);
  Blynk.virtualWrite(V6, t);
 if(p==HIGH)
 Blynk.notify("Gerakan terdeteksi");
}

void setup()
{
  pinMode (ledPower,OUTPUT);
  digitalWrite (ledPower, HIGH);
  pinMode(14,INPUT);
  Serial.begin(9600); // See the connection status in Serial Monitor
  Blynk.begin(auth, ssid, pass);

  dht.begin();

  // Setup a function to be called every second
  timer.setInterval(1000L, sendSensor);
}

void loop()
{
  Blynk.run(); // Initiates Blynk
  timer.run(); // Initiates SimpleTimer
}

Try this if V1 is your button widget.

BLYNK_WRITE(V1){
digitalWrite(control4DigitalPins, param.asInt());
if(control4DigitalPins == 1){
    digitalWrite(D2, HIGH);
    digitalWrite(D3, HIGH);
    digitalWrite(D7, HIGH);
    digitalWrite(D8, HIGH);
  }
  else{
    digitalWrite(D2, LOW);
    digitalWrite(D3, LOW);
    digitalWrite(D7, LOW);
    digitalWrite(D8, LOW);
  }
}

I have used a button to reset the Wifi, because IF you choose a correct WiFi SSID and Password, but by mistake you put a wrong or invalid Blynk Token, you will never get in fake SSID then ESP restart per your code. am I wrong? Thanks for this tip, I will try to implement in a way for avoiding using a extra button.

I’m confused by the question. If you chose the correct SSID and password, why would you WANT to reset them?

I think that he’s saying that if you enter the wrong Blynk Auth code then you’ll never be able to use the widget button in the app to trigger a WifiManager reset so you’ll never be able to correct the Auth code (unless you trigger a WifiManager reset using a physical button, or re-flash the MCU).

Pete.

When using WifiManager to connect at start-up, sometimes I like to put a simple check in there so that if it does not connect to blynk it will reset the credentials and restart the device.

Blynk.config(blynk_token);
  bool result = Blynk.connect();

  if (result != true)
  {
  Serial.println("BLYNK Connection Fail");
  Serial.println(blynk_token);
  wifiManager.resetSettings();
  ESP.reset();
  delay (5000);
  }
  else
  {
  Serial.println("BLYNK Connected!! Yay again");
   }

Although when using the WifiManager config with button, I don’t do this. That way you can start your device with or without internet/blynk, and still have it function.

I guess it all depends on the application, and the execution.

2 Likes

This only makes sense if you’re using wifimanager to pass the Blynk credentials to your board. If that is the case, there’s a much simpler workaround. Turn off your router, and boot the ESP. When it doesn’t find the SSID, it will open the AP, and you can correct your mistake.

1 Like

… or temporary block the particular ESP MAC address, doing so you don’t disrupt the network operation through the router…

1 Like

Hi there,
I was also looking for that exact combination. but unfortunately your code doesn’t work for me. I get:

C:\Users\admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WebServer\src/ESP8266WebServer.h:33:39: error: previous declaration of ‘HTTPMethod HTTP_HEAD’

enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS };

what am I doing wrong ?
lg
Thorsten

I’m new to coding and i do have similar issue(code combining).Could you sort it out?

wifimanager code


//Ported to ESP32
#ifdef ESP32
  #include <esp_wifi.h>
  #include <WiFi.h>
  #include <WiFiClient.h>

  #define ESP_getChipId()   ((uint32_t)ESP.getEfuseMac())

  #define LED_ON      HIGH
  #define LED_OFF     LOW  
#else
  #include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
  //needed for library
  #include <DNSServer.h>
  #include <ESP8266WebServer.h>  

  #define ESP_getChipId()   (ESP.getChipId())

  #define LED_ON      LOW
  #define LED_OFF     HIGH
#endif

// SSID and PW for Config Portal
String ssid = "ESP_" + String(ESP_getChipId(), HEX);
const char* password = "your_password";

// SSID and PW for your Router
String Router_SSID;
String Router_Pass;

// Use false if you don't like to display Available Pages in Information Page of Config Portal
// Comment out or use true to display Available Pages in Information Page of Config Portal
// Must be placed before #include <ESP_WiFiManager.h> 
#define USE_AVAILABLE_PAGES     false

#include <ESP_WiFiManager.h>              //https://github.com/khoih-prog/ESP_WiFiManager

// Onboard LED I/O pin on NodeMCU board
const int PIN_LED = 2; // D4 on NodeMCU and WeMos. GPIO2/ADC12 of ESP32. Controls the onboard LED.

void heartBeatPrint(void)
{
  static int num = 1;

  if (WiFi.status() == WL_CONNECTED)
    Serial.print("H");        // H means connected to WiFi
  else
    Serial.print("F");        // F means not connected to WiFi
  
  if (num == 80) 
  {
    Serial.println();
    num = 1;
  }
  else if (num++ % 10 == 0) 
  {
    Serial.print(" ");
  }
} 

void check_status()
{
  static ulong checkstatus_timeout = 0;

  //KH
  #define HEARTBEAT_INTERVAL    10000L
  // Print hearbeat every HEARTBEAT_INTERVAL (10) seconds.
  if ((millis() > checkstatus_timeout) || (checkstatus_timeout == 0))
  {
    heartBeatPrint();
    checkstatus_timeout = millis() + HEARTBEAT_INTERVAL;
  }
}

void setup() 
{
  // put your setup code here, to run once:
  // initialize the LED digital pin as an output.
  pinMode(PIN_LED, OUTPUT);
  Serial.begin(115200);
  Serial.println("\nStarting");
  
  unsigned long startedAt = millis();
  
  digitalWrite(PIN_LED, LED_ON); // turn the LED on by making the voltage LOW to tell us we are in configuration mode.
  
  //Local intialization. Once its business is done, there is no need to keep it around
  // Use this to default DHCP hostname to ESP8266-XXXXXX or ESP32-XXXXXX
  ESP_WiFiManager ESP_wifiManager;
  // Use this to personalize DHCP hostname (RFC952 conformed)
  //ESP_WiFiManager ESP_wifiManager("ConfigOnStartup");
  
  ESP_wifiManager.setMinimumSignalQuality(-1);
  // Set static IP, Gateway, Subnetmask, DNS1 and DNS2. New in v1.0.5
  ESP_wifiManager.setSTAStaticIPConfig(IPAddress(192,168,2,114), IPAddress(192,168,2,1), IPAddress(255,255,255,0), 
                                        IPAddress(192,168,2,1), IPAddress(8,8,8,8));

  // We can't use WiFi.SSID() in ESP32as it's only valid after connected. 
  // SSID and Password stored in ESP32 wifi_ap_record_t and wifi_config_t are also cleared in reboot
  // Have to create a new function to store in EEPROM/SPIFFS for this purpose
  Router_SSID = ESP_wifiManager.WiFi_SSID();
  Router_Pass = ESP_wifiManager.WiFi_Pass();
  
  //Remove this line if you do not want to see WiFi password printed
  Serial.println("Stored: SSID = " + Router_SSID + ", Pass = " + Router_Pass);
  
  //Check if there is stored WiFi router/password credentials.
  //If not found, device will remain in configuration mode until switched off via webserver.
  Serial.print("Opening configuration portal.");
  
  if (Router_SSID != "")
  {
    ESP_wifiManager.setConfigPortalTimeout(60); //If no access point name has been previously entered disable timeout.
    Serial.println("Timeout 60s");
  }
  else
    Serial.println("No timeout");

  // SSID to uppercase 
  ssid.toUpperCase();  

  //it starts an access point 
  //and goes into a blocking loop awaiting configuration
  if (!ESP_wifiManager.startConfigPortal((const char *) ssid.c_str(), password)) 
    Serial.println("Not connected to WiFi but continuing anyway.");
  else 
    Serial.println("WiFi connected...yeey :)");

  digitalWrite(PIN_LED, LED_OFF); // Turn led off as we are not in configuration mode.
 
  // For some unknown reason webserver can only be started once per boot up 
  // so webserver can not be used again in the sketch.
  #define WIFI_CONNECT_TIMEOUT        30000L
  #define WHILE_LOOP_DELAY            200L
  #define WHILE_LOOP_STEPS            (WIFI_CONNECT_TIMEOUT / ( 3 * WHILE_LOOP_DELAY ))
  
  startedAt = millis();
  
  while ( (WiFi.status() != WL_CONNECTED) && (millis() - startedAt < WIFI_CONNECT_TIMEOUT ) )
  {   
    #ifdef ESP32
      WiFi.mode(WIFI_STA);
      WiFi.persistent (true);
      // We start by connecting to a WiFi network
    
      Serial.print("Connecting to ");
      Serial.println(Router_SSID);
    
      WiFi.begin(Router_SSID.c_str(), Router_Pass.c_str());
    #endif

    int i = 0;
    while((!WiFi.status() || WiFi.status() >= WL_DISCONNECTED) && i++ < WHILE_LOOP_STEPS)
    {
      delay(WHILE_LOOP_DELAY);
    }    
  }

  Serial.print("After waiting ");
  Serial.print((millis()- startedAt) / 1000);
  Serial.print(" secs more in setup(), connection result is ");

  if (WiFi.status() == WL_CONNECTED)
  {
    Serial.print("connected. Local IP: ");
    Serial.println(WiFi.localIP());
  }
  //else
  //  Serial.println(ESP_wifiManager.getStatus(WiFi.status()));
}


void loop() 
{
  // put your main code here, to run repeatedly
  check_status();
}

Code which i want to combine with wifimanager:-


#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsClient.h>
#include <Hash.h>


// @@@@@@@@@@@@@@@ You only need to midify modify wi-fi and domain info @@@@@@@@@@@@@@@@@@@@
const char* ssid     = "enter your ssid name"; //enter your ssid/ wi-fi(case sensitiv) router name - 2.4 Ghz only
const char* password = "enter ssid password";     // enter ssid password (case sensitiv)
char host[] = "espiot.herokuapp.com"; //enter your Heroku domain name like "espiot.herokuapp.com" 
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

int port = 80;
char path[] = "/ws"; 
ESP8266WiFiMulti WiFiMulti;
WebSocketsClient webSocket;
const int relayPin = 16;
DynamicJsonBuffer jsonBuffer;
String currState;
int pingCount=0;
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) { //uint8_t *


    switch(type) {
        case WStype_DISCONNECTED:
           Serial.println("Disconnected! ");
           Serial.println("Connecting...");
               webSocket.begin(host, port, path);
               webSocket.onEvent(webSocketEvent);
            break;
            
        case WStype_CONNECTED:
            {
             Serial.println("Connected! ");
			    // send message to server when Connected
				    webSocket.sendTXT("Connected");
            }
            break;
            
        case WStype_TEXT:
            Serial.println("Got data");
              //data = (char*)payload;
           processWebScoketRequest((char*)payload);
            break;
            
        case WStype_BIN:

            hexdump(payload, length);
            Serial.print("Got bin");
            // send data to server
            webSocket.sendBIN(payload, length);
            break;
    }

}

void setup() {
    Serial.begin(115200);
    Serial.setDebugOutput(true);
    
    pinMode(relayPin, OUTPUT);
    
      for(uint8_t t = 4; t > 0; t--) {
          delay(1000);
      }
    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    
    //Serial.println(ssid);
    WiFiMulti.addAP(ssid, password);

    //WiFi.disconnect();
    while(WiFiMulti.run() != WL_CONNECTED) {
      Serial.print(".");
        delay(100);
    }
    Serial.println("Connected to wi-fi");
    webSocket.begin(host, port, path);
    webSocket.onEvent(webSocketEvent);

}

void loop() {
    webSocket.loop();
	//If you make change to delay mak sure adjust the ping
    delay(2000);
	// make sure after every 40 seconds send a ping to Heroku
	//so it does not terminate the websocket connection
	//This is to keep the conncetion alive between ESP and Heroku
	if (pingCount > 20) {
		pingCount = 0;
		webSocket.sendTXT("\"heartbeat\":\"keepalive\"");
	}
	else {
		pingCount += 1;
	}
}

void processWebScoketRequest(String data){

            JsonObject& root = jsonBuffer.parseObject(data);
            String device = (const char*)root["device"];
            String location = (const char*)root["location"];
            String state = (const char*)root["state"];
            String query = (const char*)root["query"];
            String message="";

            Serial.println(data);
            if(query == "cmd"){ //if query check state
              Serial.println("Received command!");
                    if(state=="on"){
                      digitalWrite(relayPin, HIGH);
                      message = "{\"state\":\"ON\"}";
                      currState = "ON";
                    }else{
                      digitalWrite(relayPin, LOW);
                      message = "{\"state\":\"OFF\"}";
                      currState = "OFF";
                    }
                  
            }else if(query == "?"){ //if command then execute   
              Serial.println("Received query!");
              int state = digitalRead(relayPin);
                 if(currState=="ON"){
                      message = "{\"state\":\"ON\"}";
                    }else{
                      message = "{\"state\":\"OFF\"}";
                    }
            }else{//can not recognized the command
              Serial.println("Command is not recognized!");
            }
            Serial.print("Sending response back");
            Serial.println(message);
                  // send message to server
                  webSocket.sendTXT(message);
                  if(query == "cmd" || query == "?"){webSocket.sendTXT(message);}
}

The problem started from ESP8266 core 2.6.0+ as new declaration of HTTP_HEAD conflicts with the one in WiFiManager.

You can fix the issue by using this new WiFiManager (latest version v1.0.5)

I just saw you’re using ESP_WiFiManager sample code. It’s better to post in a new topic, not in the very old one.

I just create a new topic just to support forum members using ESP_WiFiManager

Please repost your issue there. Many people and I certainly will try to help.