For the ESP8266 and PIR module to work with the defined Blynk application, it includes the Blynk header, the Simple timer, and defines the BLYNK_PRINT as serial for debugging purposes. You need to run the following code:
#define BLYNK_PRINT Serial #include <ESP8266WiFi.h> #include <BlynkSimpleEsp8266.h> #include <SimpleTimer.h>
Go to the Mobile application and then to Project Settings and email yourself the app_token:
char app_token[] = "TOKEN_FROM_EMAIL"; SimpleTimer timer; char ssid[] = "YOUR_WIFI_NETWORK"; char pass[] = "YOUR_PASSWORD"; int state; int counter=0; int flag=1; WidgetLED led1(V1); WidgetLED pirLED(V2);
This is the timer function that will be called every second to check the status of the PIR pin. All the logic for the ESP8266 application is in this function:
void timer_ev() { counter = counter+1; if(counter==5) { pirLED.off(); counter=0; flag = 1; } int pirStatus = digitalRead(D7); if (pirStatus) { if (flag == 1) { Serial.println(F("Sensor detected motion!")); Blynk.email("[email protected]","Subject: Security alert!", "Movement detected!"); Blynk.notify("Security alert! Someone is in the house!"); digitalWrite(D4, LOW); led1.on(); pirLED.on(); flag=2; } } }
Set up the Blynk with the mobile application token, and start the Wi-Fi connection with the ssid and pass for the router. You can modify the Wi-Fi setup using the WiFiManager so as not to hardcode the values in the code. Also, you can add the MQTT PubSubClient library and send Mosquitto a JSON message on a specific topic so that other devices are subscribed to receive the message. For example, you build a siren that will subscribe to the alarm topic, where the module will publish the alarm event. By receiving the alarm message the siren can start its horn. If a light system is subscribing to the alarm topic on receiving the alarm message it can start all the lights in the house:
void setup() { Serial.begin(115200); Blynk.begin(app_token, ssid, pass); pinMode(D4, OUTPUT); timer.setInterval(1000L, timer_ev); } BLYNK_WRITE(V0) { state = param.asInt(); if (state == 1){ digitalWrite(D4, LOW); led1.on(); } else { digitalWrite(D4, HIGH); led1.off(); } }
In the loop function, just run the timer and Blynk:
void loop() { Blynk.run(); timer.run(); }
Now move yourself in front of the sensor and you will start receiving messages from the Blynk application on your mobile. Also check the Serial Monitor for messages:
And the message received on the phone will be:
Please notice that the interval for sending messages on Blynk is 15 seconds and also that the maximum number of emails for Gmail is 500 per day.