ESP8266 and IFTTT - arduino

I am working on a simple device that alerts me when a button is pushed. At this time I am just trying to get the ESP8266 to activate the webhook event on it's own. It will connect to the wifi, but will not activate the event. I don't know if I'm going about this the wrong way or not. The http.Get() command returns back a -1. How do I activate the webhook? Any help is appreciated. The code is below.
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
const char* ssid="ATT2506";
const char* password = "XXXXXXXX";
int ledPin = 2;
void setup() {
pinMode(ledPin,OUTPUT);
digitalWrite(ledPin,HIGH);
Serial.begin(115200);
Serial.println();
Serial.print("Wifi connecting to ");
Serial.println( ssid );
WiFi.begin(ssid,password);
Serial.println();
Serial.print("Connecting");
while( WiFi.status() != WL_CONNECTED ){
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("Wifi Connected Success!");
Serial.print("NodeMCU IP Address : ");
Serial.println(WiFi.localIP() );
digitalWrite( ledPin , LOW);
}
void loop() {
if (WiFi.status() != WL_CONNECTED){
digitalWrite( ledPin , HIGH);
}
if (1==1) { //Check WiFi connection status
HTTPClient http; //Declare an object of class HTTPClient
http.begin("https://maker.ifttt.com/trigger/csalarm/with/key/XXXXXXXXXXX"); //Specify request destination
int httpCode = http.GET(); //Send the request
Serial.println(httpCode);
if (httpCode > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
Serial.println(1); //Print the response payload
}
http.end(); //Close connection
}
delay(30000); //Send a request every 30 seconds
}

Related

nodemcu esp8266 http request returns -1 " connection Fails "

I tried to Run this code but the connection fails and HTTPCode returns -1 , I'm using WIFI manager and it works sucessfully connected to the network
the link is worked successfully on POSTman and data posted in Database
Hi All, I tried to Run this code but the connection fails and HTTPCode returns -1 , I'm using WIFI manager and it works sucessfully connected to the network
the link is worked successfully on POSTman and data posted in Database
#include <OneWire.h>
#include <DallasTemperature.h>
#include <ESP8266WiFi.h>
#include <WiFiManager.h>
#include <ESP8266HTTPClient.h>
#include <Wire.h>
IPAddress staticIP750_100(192,168,1,16);
IPAddress gateway750_100(192,168,1,1);
IPAddress subnet750_100(255,255,255,0);
HTTPClient http;
#define ONE_WIRE_BUS 2 // DS18B20 on NodeMCU pin D4
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);
float temp_0;
const char* host = "http://mysite2020.info";
void setup()
{
Serial.begin(115200);
WiFiManager wifimanger ;
DS18B20.begin();
Wire.begin(D2, D1)
readTemp();
WiFi.mode(WIFI_STA);
wifimanger.autoConnect("Inlet Device","12345");
while ((!(WiFi.status() == WL_CONNECTED))){
delay(300);
Serial.println("...");
}
Serial.println("WiFi connected");
WiFi.config(staticIP750_100, gateway750_100, subnet750_100);
WiFi.hostname("Inlet Device") ;
delay(3000);
Serial.println("Welcome To Device No : 1");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Your Gateway is : ");
Serial.println((WiFi.gatewayIP().toString().c_str()));
Serial.println("Your Hostname is : ");
Serial.println((WiFi.hostname()));
delay(3000);
Serial.println("Welcome to my Project!");
delay(3000);
}
void loop() {
Serial.println(host); // Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort))
{
Serial.println("connection failed");
return;
}
Serial.print("Requesting URL: ");
sendtemp ();
}
void sendtemp ()
{
temp_0=23.26;
String url = "http://mysite2020.info/Api/insert_mssqlserver.php?Reading=" + String(temp_0);
Serial.println(url);
http.begin(url);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
auto httpCode = http.GET();
Serial.println(httpCode); //Print HTTP return code
String payload = http.getString();
Serial.println(payload); //Print request response payload
http.end(); //Close connection Serial.println();
Serial.println("closing connection");
delay(500);
}

How to fetch Real-Time data from URL in NodeMcu using Arduino?

Problem Statement
I want my NodeMCU to fetch latest updated data from URL each time of the loop.
Currently it does not update the content fetched.
For example, Link: http://abcdxyz.xyz/io.php has just the digits 223838.
Once the NodeMCU starts running, & the link's information gets updated to 240000,
Yet the Arduino Serial Printer is showing 223838 even after the link getting updated on the server.
Here is my code:
#include "ESP8266WiFi.h"
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
# define LED D4 // Use built-in LED which connected to D4 pin or GPIO 2
String serverName = "http://abcdxyz.xyz/";
unsigned long timerDelay = 5000;
unsigned long lastTime = 0;
// WiFi parameters to be configured
const char* ssid = "XXXXXXXXX";
const char* password = "XXXXXXXXXX";
void setup() {
pinMode(LED, OUTPUT); // Initialize the LED as an output
Serial.begin(9600);
// Connect to WiFi
WiFi.begin(ssid, password);
// while wifi not connected yet, print '.'
// then after it connected, get out of the loop
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
//print a new line, then print WiFi connected and the IP address
Serial.println("");
Serial.println("WiFi connected");
// Print the IP address
Serial.println(WiFi.localIP());
}
void loop() {
//Calling An URL FOR DATA
if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status
HTTPClient http;
http.begin("http://abcdxyz.xyz/io.php"); //Specify the URL
int httpCode = http.GET(); //Make the request
if (httpCode > 0) { //Check for the returning code
String payload = http.getString();
Serial.println(httpCode);
Serial.println(payload);
}
else {
Serial.println("Error on HTTP request");
}
http.end(); //Free the resources
}
delay(1000);
//Calling URL ENDS
digitalWrite(LED, HIGH);
delay(100);
digitalWrite(LED, LOW);
}
Figured it out. The link has to be a new link each time to GET the latest records.
Follow the codes below:
void loop() {
//Calling An URL FOR DATA
if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status
HTTPClient http;
randNumber = random(1, 99999);
String crow = "http://abcdxyz.xyz/io.php?tag=";
crow += randNumber;
Serial.println(crow);
http.begin(crow); //Specify the URL
int httpCode = http.GET(); //Make the request
if (httpCode > 0) { //Check for the returning code
String payload = http.getString();
Serial.println(httpCode);
Serial.println(payload);
}
else {
Serial.println("Error on HTTP request");
}
http.end(); //Free the resources
}
delay(1000);
//Calling URL ENDS
digitalWrite(LED, HIGH);
delay(100);
digitalWrite(LED, LOW);
}

ESP8266 Using wifimanager with onSoftAPModeProbeRequestReceived

I would like to use https://github.com/tzapu/WiFiManager in conjunction with onSoftAPModeProbeRequestReceived. The end goal is to config the wifi with WifiMaager then "switch over" and send probe request information via the wifi.
I get this to work without wifi manager using the following
#include <ESP8266httpUpdate.h>
#include <ESP8266WiFi.h>
#include <esp8266httpclient.h>
#include <stdio.h>
const char* ssid = "someap"; // The SSID (name) of the Wi-Fi
network you want to connect to
const char* password = ""; // The password of the Wi-Fi network
int status = WL_IDLE_STATUS;
String macAddr = "";
WiFiEventHandler probeRequestPrintHandler;
WiFiEventHandler probeRequestBlinkHandler;
bool blinkFlag;
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
Serial.print("Starting");
WiFi.persistent(false);
WiFi.mode(WIFI_AP);
WiFi.softAP(ssid, password);
probeRequestPrintHandler =
WiFi.onSoftAPModeProbeRequestReceived(&onProbeRequestPrint);
probeRequestBlinkHandler =
WiFi.onSoftAPModeProbeRequestReceived(&onProbeRequestBlink);
while ( status != 3)
{
Serial.print("Attempting to connect to network, SSID: ");
Serial.println(ssid);
status = WiFi.status();
WiFi.begin(ssid, password);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println(WiFi.localIP());
}
void onProbeRequestPrint(const WiFiEventSoftAPModeProbeRequestReceived& evt)
{
if (macAddr != macToString(evt.mac))
{
macAddr = macToString(evt.mac);
Serial.print("Probe request from: ");
Serial.print(macToString(evt.mac));
Serial.print(" RSSI: ");
Serial.println(evt.rssi);
}
}
void onProbeRequestBlink(const WiFiEventSoftAPModeProbeRequestReceived&) {
blinkFlag = true;
}
void loop() {
if (blinkFlag) {
HTTPClient http; //Declare an object of class HTTPClient
http.begin("http://requestbin.fullcontact.com/110f1ss6a1?test=true");
//Specify request destination
int httpCode = http.GET();
Serial.println(httpCode);
if (httpCode > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
Serial.println(payload); //Print the response payload
}
http.end(); //Close connection
macAddr="";
blinkFlag = false;
digitalWrite(LED_BUILTIN, LOW);
delay(100);
digitalWrite(LED_BUILTIN, HIGH);
status = 0;
}
delay(1000);
}
String macToString(const unsigned char* mac) {
char buf[20];
snprintf(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return String(buf);
}
When the connection is established we rely on WiFiEventHandler probeRequestPrintHandler; and WiFiEventHandler probeRequestBlinkHandler; This does work and does collect the mac address, how ever it can not connect to the AP. Do I need to close the current wifi mode open the connection then close it?
Seems all I needed to do is add WiFi.begin(); before void loop()

Arduino can't show out respond get from mqtt server through esp8266

I'm trying to let my Arduino and esp8266 send data to thingsboard and then subscribe to thingsboard's mqtt channel and get a timestamp from it but for some unknown reason, it just doesn't work. Checked server-side and it was ok, tried postman to simulate request and also getting the correct response from the server.
Also, I had read the documentation about esp8266 and it somehow did state that it only can have 1 connection simultaneously. But tried to let my Arduino to only subscribe to channel but it still doesn't work.
My code:(I'm using Arduino Mega for this)
#include "DHT.h"
#include <WiFiEspClient.h>
#include <WiFiEsp.h>
#include <WiFiEspUdp.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <TimeLib.h>
#define WIFI_AP "CEC"
#define WIFI_PASSWORD "#CEC#2017#CEC#"
#define TOKEN "A1_TEST_TOKEN"
// DHT
#define DHTPIN 2
#define DHTTYPE DHT22
char thingsboardServer[] = "192.168.0.250";
// Initialize the Ethernet client object
WiFiEspClient espClient;
// Initialize DHT sensor.
DHT dht(DHTPIN, DHTTYPE);
PubSubClient client(espClient);
int status = WL_IDLE_STATUS;
unsigned long lastSend;
unsigned long lastSync;
void setup() {
// initialize serial for debugging
Serial.begin(9600);
Serial1.begin(9600);
Serial2.begin(9600);
//serial pin
pinMode(LED_RUN_pin, OUTPUT);
//dht.begin();
InitWiFi();
lastSend = 0;
lastSync = 0;
//client subscribe thingsboard rpc PUBLISH msg
client.setServer( thingsboardServer, 1883 );
client.setCallback(on_message);
}
void loop() {
status = WiFi.status();
if ( status != WL_CONNECTED) {
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(WIFI_AP);
// Connect to WPA/WPA2 network
status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
delay(500);
}
}
if ( !client.connected() ) {
reconnect();
}
if ( millis() - lastSend > 30000 ) { // Update and send after 30 seconds
getAndSendTemperatureAndHumidityData();
lastSend = millis();
}
client.loop();
}
void getAndSendTemperatureAndHumidityData()
{
Serial.println("Collecting temperature data.");
// Reading temperature or humidity takes about 250 milliseconds!
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
String temperature = String(t);
String humidity = String(h);
// Prepare a JSON payload string
String payload = "{";
payload += "\"temperature\":"; payload += temperature; payload += ",";
payload += "\"humidity\":"; payload += humidity;
payload += "}";
// Send payload
char attributes[100];
payload.toCharArray( attributes, 100 );
client.publish( "v1/devices/me/rpc/request/1", attributes , 1);
//Serial.println( attributes );
}
// Prepare a JSON payload string
String payload = "{method: getTime, params:{}}";
// Send payload
char attributes[100];
payload.toCharArray( attributes, 100 );
client.publish( "v1/A1_TEST_TOKEN/rpc", attributes );
//Serial.println( attributes );
}
void InitWiFi()
{
// initialize serial for ESP module
Serial1.begin(9600);
// initialize ESP module
WiFi.init(&Serial1);
// check for the presence of the shield
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue
while (false);
}
Serial.println("Connecting to AP ...");
// attempt to connect to WiFi network
while ( status != WL_CONNECTED) {
// Connect to WPA/WPA2 network
status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
delay(500);
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
//Serial.print("Connecting to Thingsboard node ...");
// Attempt to connect (clientId, username, password)
if ( client.connect("Arduino Uno Device", TOKEN, NULL) ) {
Serial.println( "[DONE]" );
delay(500);
// Serial.println("Subscribing RPC");
client.subscribe("v1/devices/me/rpc/request/+");
} else {
Serial.print( "[FAILED] [ rc = " );
Serial.print( client.state() );
Serial.println( " : retrying in 20 seconds]" );
// Wait 20 seconds before retrying
delay( 20000 );
}
}
}
void printDigits(int digits){
// utility function for digital clock display: prints preceding colon and leading 0
Serial.print(":");
if(digits < 10)
Serial.print('0');
Serial.print(digits);
}
// The callback for when a PUBLISH message is received from the server.
void on_message (char* topic, byte* payload, unsigned int length) {
//Serial.println("On message");
char json[length + 1];
strncpy (json, (char*)payload, length);
json[length] = '\23';
Serial.print("Topic: ");
Serial.println(topic);
Serial.print("Message: ");
Serial.println(json);
// Decode JSON request
StaticJsonBuffer<200> jsonBuffer;
JsonObject& data = jsonBuffer.parseObject((char*)json);
if (!data.success())
{
Serial.println("parseObject() failed");
return;
}
}
Probably a stupid remark, but is your TOKEN a valid Thingsboard device token? I assume you entered the value A1_TEST_TOKEN to hide your real authentication token.
I also assume you are trying to send sensor data (telemetry) to Thingsboard. Why did you decide to use the RPC API for sending data? I think it might be easier to use the MQTT Device API instead.
I don't have any experience in developing for Arduino. I am using Thingsboard together with a Raspberry PI to write and display sensor data. Hope you find a solution for your problem!

ESP 8266 Program Issue

Description
I am writing a web server on ESP-8266(01), that will control 3 locks using Arduino Mega.
The locks will be controlled by Bluetooth ESP 8266 (get method from phone) and using my laptops browser.
I can do it all with bluetooth HC-05 (easily).
The issue I am facing is with my ESP-8266 wifi module.
I need to send 3 different strings from ESP for Arduino to read it.
If it's "AAAA" Arduino will read it and unlock door one, if it BBBB then door 2 and etc etc.....
So I used this code:
#include <ESP8266WiFi.h>
const char* ssid = "Do-Not-Ask-For-Password";
const char* password = "ITISMYPASSWORD";
//const char* ssid = "`STAR-NET-Azhar-32210352";
//const char* password = "ITISMYPASSWORD";
int ledPin = 2; // GPIO2
WiFiServer server(80);
// Update these with values suitable for your network.
IPAddress ip(192,168,8,128); //Node static IP
IPAddress gateway(192,168,8,1);
IPAddress subnet(255,255,255,0);
void setup() {
Serial.begin(115200);
delay(10);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
WiFi.config(ip, gateway, subnet);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
}
void loop() {
ESP.wdtDisable();
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
// Serial.println("new client");
// while(!client.available()){
// delay(1);
// }
if(!client.available()){
delay(1);
client.flush();
}
// Read the first line of the request
String request = client.readStringUntil('\r');
//Serial.println(request);
client.flush();
// Match the request
int value1 = LOW;
int value2 = LOW;
int value3 = LOW;
if (request.indexOf("/LOCK=ON1") != -1) {
//digitalWrite(ledPin, HIGH);
value1 = HIGH;
Serial.println("AAAA");
}
if(request.indexOf("/LOCK=ON2") != -1){
value2 = HIGH;
Serial.println("BBBB");
}
if(request.indexOf("/LOCK=ON3") != -1){
value3 = HIGH;
Serial.println("CCCC");
}
// Set ledPin according to the request
//digitalWrite(ledPin, value);
// Return the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // do not forget this one
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<br><br>");
client.print("LOCK ONE IS NOW: ");
if(value1 == HIGH) {
client.print("UNLOCKED");
// Serial.println("A");
} else {
client.print("LOCKED");
}
client.println("<br><br>");
client.print("LOCK TWO IS NOW: ");
if(value2 == HIGH) {
client.print("UNLOCKED");
// Serial.println("B");
} else {
client.print("LOCKED");
}
client.println("<br><br>");
client.print("LOCK THREE IS NOW: ");
if(value3 == HIGH) {
client.print("UNLOCKED");
//Serial.println("C");
} else {
client.print("LOCKED");
}
client.println("<br><br>");
client.println("CLICK HERE TO UNLOCK THE LOCK ONE<br>");
client.println("CLICK HERE TO UNLOCK THE LOCK TWO<br>");
client.println("CLICK HERE TO UNLOCK THE LOCK THREE<br>");
client.println("</html>");
delay(100);
//Serial.println("client disconnected");
// Serial.println("");
}
The Result I Get on Browser is ( Which is What i need):
enter image description here
ISSUE:
Now The Issue Is Some Times it misses the serial data i send, For Example if i click unlock door 1, It sends data and i click unlock door 2 it does nothn and when i reset it sends data from all 3 but for two to 3 times and then module resets it self ....
This Is What I got From Serial Monitor:
enter image description here
Now i have searched alot and its watchdre out what i did wrong in the code.
this is how my ESP is connected:
vcc & CHPD to 3.3V ragulator
gnd to gnd of powersuply and to arduino gnd...
GP 0 ------> 3.3v with 2.2k Resistor ( in non flashing state).
Rst ------> 3.3v with resistor
RX to TX
TX to RX
Any Ideas how to fix it?
Is There any other way to control Arduino pins (6 different pins) from ESP 8266 module??
ive been trying from many days please help!!
Ok I am Posting It For those who are facing the same problem!! i took the Hello ESP example And Modified it to Print Serial!!!
On Mega My Serial Was Started at 9600 and i started Serial On ESP at 9600 aswell :| So This is the Code .... Slow Server and WDT issue is Almost Gone....
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
//const int RELAY_PIN = 2; //RELAY
const char* ssid = "Do-Not-Ask-For-Password";
const char* password = "AeDrki$32ILA!$#2";
MDNSResponder mdns;
ESP8266WebServer server(80);
void handleRoot() {
server.send(200, "text/plain", "hWelcome To Door Unlock Project By Haziq Sheikh");
}
void handleNotFound(){
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
void setup(void){
// pinMode(RELAY_PIN, OUTPUT);
Serial.begin(9600);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
//digitalWrite(RELAY_PIN, 1);
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// digitalWrite(RELAY_PIN, 0);
if (mdns.begin("esp8266", WiFi.localIP())) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.on("/lock1", [](){
server.send(200, "text/plain", "Okay Door One Unlocked");
Serial.println("AAAA");
});
server.on("/lock2", [](){
server.send(200, "text/plain", "Okay -- Door 2 Unlocked");
Serial.println("BBBB");
});
server.on("/lock3", [](){
server.send(200, "text/plain", "Okay -- Door 3 is Unlocked");
Serial.println("CCCC");
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop(void){
server.handleClient();
}

Resources