I'm trying to make an IOT app. My android side is working good so far, however my ESP8266 is unable to read data from Firebase Database. There is no error while connecting to the internet using onboard ESP8266 though. Can anyone point to a possible error? Thank You
#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#define WIFI_SSID "WiFi"
#define WIFI_PASSWORD "xxxxxxxx"
#define FIREBASE_HOST "https://iot.firebaseio.com"
#define FIREBASE_AUTH "xxxxxxxx"
int LED1 = D5;
void setup()
{
Serial.begin(115200);
pinMode(LED1, OUTPUT);
Serial.println('\n');
wifiConnect();
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
delay(10);
}
void loop()
{
if(WiFi.status() != WL_CONNECTED)
{
wifiConnect();
}
delay(10);
Serial.print("Data from firebase:" + Firebase.getString("LED1") + "\n");
digitalWrite(LED1, Firebase.getString("LED1").toInt());
//digitalWrite(LED1, HIGH);
delay(10);
}
void wifiConnect()
{
WiFi.begin(WIFI_SSID, WIFI_PASSWORD); // Connect to the network
Serial.print("Connecting to ");
Serial.print(WIFI_SSID); Serial.println(" ...");
int teller = 0;
while (WiFi.status() != WL_CONNECTED)
{ // Wait for the Wi-Fi to connect
delay(1000);
Serial.print(++teller); Serial.print(' ');
}
Serial.println('\n');
Serial.println("Connection established!");
Serial.print("IP address:\t");
Serial.println(WiFi.localIP()); // Send the IP address of the ESP8266 to the computer
}
For anyone encountering this issue. I got it working by removing the forward slash '/' at the end and the https:// from the start of Host Address.
At the line:
#define FIREBASE_HOST "https://iot.firebaseio.com"
you should fix to:
#define FIREBASE_HOST "iot.firebaseio.com"
Related
I am currently having a problem with my ESP8266 establishing a stable connection to my mosquitto MQTT broker.
I have moved house and am therefore using a different network.
In the previous network, my ESP ran stably and I had no problems at all. The MQTTserver run on a Raspberry PI 4.
In the new network, as already mentioned, it breaks off every 15-30 minutes (no fixed length of time).
The code is of course adapted to the new network and the IP of the broker.
The code I use is probably the generally known code for connecting to the MQTT server.
I only added some I/O Ports.
Since the code worked without problems in the old network, I first thought that the WLAN connection was failing.
So in the loop I inserted the reestablishment with the WLAN.
But this is running stably:
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Connecting to Vodafone-947E
.....
WiFi connected
IP address:
192.168.0.52
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
..............
Can it be that my new router simply interrupts the connection after some time? Otherwise, I don't understand what the problem could be.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
//----------------------------------------------------------------------------------------------------------------------
#define wifi_ssid "xxxxxxx"
#define wifi_password "xxxxxxxxx"
#define mqtt_server "192.168.0.xxx"
//----------------------------------------------------------------------------------------------------------------------
WiFiClient espClient;
PubSubClient client(espClient);
bool status;
const int OutputPin2 = 12;
const int ResetPin = 4;
int ResetCounter =0;
//----------------------------------------------------------------------------------------------------------------------
void setup() {
Serial.begin(9600);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
pinMode(OutputPin2, OUTPUT);
pinMode(ResetPin, OUTPUT);
digitalWrite(OutputPin2, HIGH);
digitalWrite(ResetPin, HIGH);
}
//----------------------------------------------------------------------------------------------------------------------
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
WiFi.begin(wifi_ssid, wifi_password);
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId= "ESP8266-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
delay(100);
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
// ... and resubscribe
client.subscribe("esp3/LED");
} else {
ResetCounter++;
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
Serial.println(ResetCounter);
if (ResetCounter >=5)
{
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
//digitalWrite(ResetPin, LOW);
ResetCounter =0;
}
// Wait 5 seconds before retrying
delay(5000);
}
}
}
//----------------------------------------------------------------------------------------------------------------------
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
//----------------------------------------------------------------------------------------------------------------------
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(wifi_ssid);
WiFi.begin(wifi_ssid, wifi_password);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
//----------------------------------------------------------------------------------------------------------------------
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
client.subscribe ("esp3/LED");
if (strcmp(topic,"esp3/LED")) {
Serial.print("Changing output to ");
if(messageTemp == "on LED"){
Serial.println("on LED");
digitalWrite(OutputPin2, LOW); //Invertiertes Signal
delay(200);
}
else if(messageTemp == "off LED"){
Serial.println("off LED");
digitalWrite(OutputPin2, HIGH);
delay(200);
}
}
}
```
Fortunately, I was able to solve the problem. The reason was that the WLAN signal on the ESP8266 was simply too low. As a result, the ESP was not able to stay on the network permanently. I actually ruled this out because the router is only one room away. The problem is that many routers in the surrounding flats also transmit on the same frequency band and thus influence the signal. I bought a WLAN amplifier (of course this does not improve the situation with the signal overlapping). Now I have no more problems with disconnects from the ESP and this has been the case for 2 days.
I have an NodeMCU chip that needs to connect to my home wifi and post an http request. I use the chip in WIFI_STA_AP mode as I need the chip to both accept requests via http and issue requests by http.
I do not want to hard-code my home's SSID/Password into the chip, so I have written some code that places the ESP (NodeMCU) into AP mode, receives the SSID/Pass via an http request and saves it on EEPROM.
This works great.
In the code below, onTestWifi() is called when I call http://192.168.4.1/test_wifi?wifi_ssid=mySsid&wifi_password=myPassword. The ssid and password are provided to the WiFi.begin() function. However, if I accidentally type in the wrong password and use it in WiFi.begin(), the connection will always fail until reset the chip and then insert the correct password.
What am I missing? Is it possible to change the ESP's wifi credentials programmatically, without having to reset the chip? Resetting the chip causes the client (in the case, an iPhone app) to disconnect from the chip and this breaks the entire program flow.
Here's the experimentation code I am using:
#include <ESP8266WiFiMulti.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
ESP8266WebServer server(80);
ESP8266WiFiMulti WiFiMulti;
void setup() {
Serial.begin(115200);
Serial.println("");
delay(100);
Serial.println("Starting...");
WiFi.persistent(false);
WiFi.mode(WIFI_AP_STA);
WiFi.softAP("APSSID");
IPAddress ip = WiFi.softAPIP();
server.on("/test_wifi", onTestWifi);
server.begin();
yield();
}
void onTestWifi()
{
char ssid[30] = "";
char password[30] = "";
for (int i = 0; i < server.args(); i++)
{
String n = server.argName(i);
String v = server.arg(i);
if (n == "wifi_ssid")
v.toCharArray(ssid, 30);
else if (n == "wifi_password")
v.toCharArray(password, 30);
yield();
}
Serial.print("Connecting to: ");
Serial.print(ssid);
Serial.print(" ");
Serial.println(password);
delay(100);
WiFi.begin(ssid, password);
yield();
int counter = 0;
while (WiFi.status() != WL_CONNECTED && counter < 10)
{ // Wait for the Wi-Fi to connect
delay(1000);
Serial.print(++counter);
Serial.print(' ');
}
if (WiFi.status() != WL_CONNECTED)
{ // Failed to connect.
Serial.println("Connection failed!");
}
else {
Serial.println("Connection succeeded!");
}
yield();
}
void loop() {
server.handleClient();
}```
OK, so I figured it out. Had to add the line WiFi.disconnect(true) in the onTestWifi() function. Apparently it disconnects from the network and erases the credentials. This stuff is very poorly documented and I wasted days on it.
I hope someone finds it useful.
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
ESP8266WebServer server(80);
ESP8266WiFiMulti WiFiMulti;
void setup() {
Serial.begin(115200);
Serial.println("");
delay(100);
Serial.println("Starting...");
WiFi.persistent(false);
WiFi.mode(WIFI_AP_STA);
WiFi.softAP("APSSID");
IPAddress ip = WiFi.softAPIP();
server.on("/test_wifi", onTestWifi);
server.begin();
yield();
}
void onTestWifi()
{
char ssid[30] = "";
char password[30] = "";
for (int i = 0; i < server.args(); i++)
{
String n = server.argName(i);
String v = server.arg(i);
if (n == "wifi_ssid")
v.toCharArray(ssid, 30);
else if (n == "wifi_password")
v.toCharArray(password, 30);
yield();
}
Serial.print("Connecting to: ");
Serial.print(ssid);
Serial.print(" ");
Serial.println(password);
delay(100);
WiFi.begin(ssid, password);
yield();
int counter = 0;
while (WiFi.status() != WL_CONNECTED && counter < 10)
{ // Wait for the Wi-Fi to connect
delay(1000);
Serial.print(++counter);
Serial.print(' ');
}
if (WiFi.status() != WL_CONNECTED)
{ // Failed to connect.
Serial.println("Connection failed!");
}
else {
Serial.println("Connection succeeded!");
}
WiFi.disconnect(true); // <--- Added this line
yield();
}
void loop() {
server.handleClient();
}
I need to send my data to firebase via NODE MCU. I've created an application that is used to turn on and off led in node mcu. My node mcu connects with the wifi network but does not send data to firebase. The if(firebase.failed()) executes, but does not return an error code. In the serial monitor it just prints setting/number failed:. How can I fix this?
#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#include <ArduinoJson.h>
#define FIREBASE_HOST "http://temphu*****.firebaseio.com/"
#define FIREBASE_AUTH "VblTNS************OmWTW6n"
#define WIFI_SSID "A****"
#define WIFI_PASSWORD "9*****"
#define LED 2
void setup() {
pinMode(LED,OUTPUT);
digitalWrite(LED,0);
Serial.begin(9600);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println();
Serial.print("connected: ");
Serial.println(WiFi.localIP());
Firebase.begin(FIREBASE_HOST,FIREBASE_AUTH);
Firebase.setInt("LEDStatus",0);
}
void loop() {
if(Firebase.getInt("LEDStatus")) {
digitalWrite(LED,HIGH);
}
else {
digitalWrite(LED,LOW);
}
if (Firebase.failed()) { // Check for errors
Serial.print("setting /number failed:");
Serial.println(Firebase.error());
return;
}
delay(1000);
}
In the source code it clearly says that (https://raw.githubusercontent.com/FirebaseExtended/firebase-arduino/master/src/FirebaseError.h) two error codes are used in addition to regular HTTP error codes. Therefore Firebase rejection might not raise an error even though it fails.
So check the firebase rules and change read/write to true.
I'm trying to make a "home weight" with my ESP32 and display the value using IBMCloud, however I'm running into some issues with the Arduino IDE and my code.
I get this error:
Arduino:1.8.5 (Windows 10), Tarjeta:"ESP32 Dev Module, QIO, 80MHz, 4MB (32Mb), 921600, None"
C:\Users\XX\Documents\Arduino\IBM_Watson_Connect\IBM_Watson_Connect.ino:8:25: fatal error: ESP8266WiFi.h: No such file or directory
compilation terminated.
exit status 1
Compiling error for the ESP32 Dev Module card.
I'm using a ESP32 dev board. My code is this:
#include <ESP8266WiFi.h>
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient/releases/tag/v2.3
#include "HX711.h" //Load Cell Amplifier
HX711 cell(D2, D4); //Amplifier is connected to these pins on the NodeMCU ESP8266 Board
#define WLAN_SSID "XXXXX"
#define WLAN_PASS "XXXXX"
#define ORG "XXXXX"
#define DEVICE_TYPE "XXXXXX"
#define DEVICE_ID "XXXXX"
#define TOKEN "XXXXXXXX"
char server[] = ORG ".messaging.internetofthings.ibmcloud.com";
char topic[] = "iot-2/evt/status/fmt/json";
char authMethod[] = "use-token-auth";
char token[] = TOKEN;
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;
WiFiClient wifiClient;
PubSubClient client(server, 1883, NULL, wifiClient);
void setup() {
Serial.begin(115200);
Serial.println();
// Connect to WiFi access point.
Serial.println(); Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: "); Serial.println(WiFi.localIP());
}
int counter = 0;
void loop() {
if (!!!client.connected()) {
Serial.print("Reconnecting client to ");
Serial.println(server);
while (!!!client.connect(clientId, authMethod, token)) {
Serial.print(".");
delay(500);
}
Serial.println();
}
//----------Get data from load cell and amplifier
long valCalibrated = 0;
long val = 0;
float count = 0;
count = count + 1;
val = 0.5 * val + 0.5 * cell.read();
valCalibrated = (val - 4137240) / 234.20;
//----------Send data to IBM Waton IoT Service
String payload = "{\"d\":{\"weight\":";
payload += valCalibrated;
payload += "}}";
Serial.print("Sending payload: ");
Serial.println(payload);
if (client.publish(topic, (char*) payload.c_str())) {
Serial.println("Publish ok");
} else {
Serial.println("Publish failed");
}
++counter;
delay(100); //adjust delay to send more or less reads per unit time
}
Some places mentioned that the library was missing, that the board wasn't properly selected, the library wasn't updated.. I checked them all.. Arduino is updated, libraries are installed and updated, proper board is selected (I actually have tried all the other Esp32 related boards with the same result)
You're building a program for the ESP32, not the ESP8266. There are a lot of similarities but they're entirely different chips with different software.
So you don't use ESP8266WiFi.h with the ESP32. On the ESP32, the header file is just called WiFi.h (keeping more in line with WiFi support on Arduinos - the ESP32 Arduino Core is intended to be more compatible with the normal Arduino Core than the ESP8266 version was).
You need to
#include <WiFi.h>
instead of ESP8266WiFi.h
You can find the code for these files in the official repository for the Arduino SDK for the ESP32.
(It doesn't help that WiFi.h for the ESP32 identifies itself as ESP8266.h in its own comments...)
Here is my very simple and complete sketch.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
void setup() {
delay(1000);
Serial.begin(115200);
Serial.println();
WiFi.begin("ssid", "password"); //Edited out
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected! Ip: " + WiFi.localIP());
}
void loop() {
}
The serial output is as follows:
...
I would expect to see "Connected! Ip: 192.168.2.xxx" but for some reason the application isn't showing this.
I can ping the device if I scan which new devices entered the wifi net work, and the SSID and password data are correct (I've edited them out here).
Also, the only reason it should stop printing dots is because the state is now connected.
Edit: The output from Serial.setDebugOutput(true);
scandone
..ip:192.168.2.15,mask:255.255.255.0,gw:192.168.2.254
.
Here it shows that it does get connected.
It ends up getting fixed by adding .toString(), like this:
Serial.println("Connected! Ip: " + WiFi.localIP().toString());