Set parameters of ESP8266 through Arduino - arduino

The problem is that I want to execute the code below, but when ESP8266 is shut down, then I start it again, everything is gone.
So, is there a solution that I can make this ESP8266 work the same controlled by my Arduino Uno.
My program blow is to control the GPIO2 through web browser.
Thanks a lot to all of you!!
My Codes:
#include <ESP8266WiFi.h>
#include <aREST.h>
// Create aREST instance
aREST rest = aREST();
// WiFi parameters
const char* ssid = "Protect Big Dragon 4";
const char* password = "18717772056";
// The port to listen for incoming TCP connections
#define LISTEN_PORT 80
// Create an instance of the server
WiFiServer server(LISTEN_PORT);
void setup(void)
{
// Start Serial
Serial.begin(115200);
// Give name and ID to device
rest.set_id("2");
rest.set_name("lamp_control");
// Connect to WiFi
WiFi.begin(ssid, password);
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.println(WiFi.localIP());
}
void loop() {
// Handle REST calls
WiFiClient client = server.available();
if (!client) {
return;
}
while(!client.available()){
delay(1);
}
rest.handle(client);
}

So your ESP8266 loses your code when it is rebooted.
Sounds like the memory is faulty.
Try a different ESP8266 and let us know what occurs.

Related

ESP32 access point

I have 2 ESP32 boards, and I want to make them server/client in Arduino IDE. Just two boards, no router in between.
So far I have followed tutorials, and I have been able to connect to the ESP32 from my phone.
#include <WiFi.h>
WiFiServer server;
const char *ssid = "Zupa";
const char *password = "12345678";
void setup() {
Serial.begin(115200);
Serial.println();
Serial.print("Configuring access point...");
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
}
void loop() {
}
However, I cannot connect from other ESP32. Code as follows:
#include <WiFi.h>
#include <WiFiMulti.h>
WiFiMulti WiFiMulti;
void setup()
{
Serial.begin(115200);
delay(10);
enter code here
// We start by connecting to a WiFi network
WiFiMulti.addAP("Zupa", "12345678");
Serial.println();
Serial.println();
Serial.print("Wait for WiFi... ");
while(WiFiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
delay(500);
}
void loop()
{
const uint16_t port = 80;
const char * host = "192.168.1.4"; // ip
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
if (!client.connect(host, port)) {
Serial.println("connection failed");
Serial.println("wait 5 sec...");
delay(5000);
return;
}
// This will send the request to the server
client.print("Send this data to server");
//read back one line from server
String line = client.readStringUntil('\r');
client.println(line);
Serial.println("closing connection");
client.stop();
Serial.println("wait 5 sec...");
delay(5000);
}
What happens is it just says it cannot connect. The IP address is default, and I double checked it on the server side! How come I can connect from phone and not from ESP32?
Furthermore, how would I communicate between the two? I tried reading online, but everyone seems to do phone to ESP communication, not ESP to ESP. I also tried reading Mr. Kolbans book on ESP32, but with no success. I am quite new at this, and feel stuck.
All I had to change was the WiFi library from the ESP8266wifi.h to the Wifi.h which is compatible with ESP32.
(Source)
From the code examples is just a matter of changing the code to fit your specific needs.
#include <WiFi.h>
#include <WiFiClient.h>
void setup()
{
Serial.begin(115200);
delay(10);
// We start by connecting to a WiFi network
WiFi.mode(WIFI_STA); //Set wifi mode as station
WiFi.begin("Zupa", "12345678");//Connect to other ESP32
Serial.println();
Serial.println();
Serial.print("Wait for WiFi... ");
//Wait for WiFi to connect
while(WiFi.waitForConnectResult() != WL_CONNECTED){
Serial.print(".");
delay(1000);
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
delay(500);
}
void loop()
{
const uint16_t port = 80;
const char * host = "192.168.1.4"; // ip
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
if (!client.connect(host, port)) {
Serial.println("connection failed");
Serial.println("wait 5 sec...");
delay(5000);
return;
}
// This will send the request to the server
client.print("Send this data to server");
//read back one line from server
String line = client.readStringUntil('\r');
client.println(line);
Serial.println("closing connection");
client.stop();
Serial.println("wait 5 sec...");
delay(5000);
}
Try change the IP of client code to:
const char * host = "192.168.4.1"
Tip: I use the Finger app in Android or iOS to scan the network,
its very good to see the IP of each device connected.
(In your case, You need connect the mobile device into your Esp32's hot spot before use the Finger)

NodeMCU (ESP8266) Defining static IP, stops Firebase processing

Hello i am new to NodeMCU (ESP8266) i am building a small program to connect with WIFI (with internet) and if internet is not available i want to process request over IP address.
I am using firebase as a database / server to fetch the status. And process command through a URL like http://192.168.1.223/on?pin=04 if internet is connected then no problem i can update firebase entry, but with same network (LAN) connection over wifi i want to process i need to have static IP. But the concern is i am not able to make this IP address static, and if i make it static then my NodeMCU is not able to connect with firebase.
Here is how my code looks like:
#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#include <ESP8266WebServer.h>
#define FIREBASE_HOST "pushst-56f2c.firebaseio.com"
#define FIREBASE_AUTH "mhBpzrNyhhwEGwmFxkVFTIEylwrXMw0gm"
#define PATH "/clients/devicename/watermotor"
IPAddress ip(192, 168, 1, 223); //Node static IP
IPAddress dns(192, 168, 1, 223);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
char ssid[] = "MyNetwork";
char password[] = "Qwert98!!";
int wifiStatus = WL_IDLE_STATUS;
ESP8266WebServer server(80);
void setup() {
Serial.begin(115200);
delay(100);
Serial.println();
Serial.println();
Serial.print("Your are connecting to;");
Serial.println(ssid);
WiFi.begin(ssid, password);
WiFi.config(ip, dns, gateway, subnet);
while (WiFi.status() != WL_CONNECTED) {
digitalWrite(WIFI_CONNECT_LED, HIGH);
delay(500);
Serial.print(".");
}
wifiStatus = WiFi.status();
if(wifiStatus == WL_CONNECTED){
digitalWrite(WIFI_CONNECT_LED, LOW);
Serial.println("Your IP address is: ");
Serial.println(WiFi.localIP());
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
Firebase.set("/clients/devicename/watermotor/name", "Motor");
Firebase.set("/clients/devicename/watermotor/relay_status", "off");
Firebase.set("/clients/devicename/watermotor/device_status", "online");
Firebase.stream(PATH);
server.on("/on", handleOnRequest); //Associate the handler function
server.on("/off", handleOffRequest); //Associate the handler function
server.begin(); //Start the server
}
else{
Serial.println("");
Serial.println("WiFi not connected");
}
}
void loop() {
server.handleClient();
if (Firebase.failed()) {
Serial.println("streaming error");
Serial.println(Firebase.error());
delay(1000);
return;
}
if (Firebase.available()) {
Serial.println();
Serial.print("Firebase available");
Serial.println();
FirebaseObject event = Firebase.readEvent();
}
}
I am not sure if its there is some problem with FirebaseLibrary or its just the ESP8266!
Any suggestions will be helpful, thanks in advance! :)
You have wrong DNS server IP address. In your sketch it is the same as the static IP address you assign to esp. Then the name of the firebase host can't be resolved by DNS.
The DNS server is usually the router/gateway.
IPAddress dns(192,168,1,1)

MQTT Mosquitto and two ESP8266

My problem:
I have a Raspberry Pi, and I have installed the Mosquitto MQTT broker on it. My objective is to make 2 MQTT clients communicate over the Mosquitto broker, so I have installed the code below on two ESP8266 (WeMos D1 mini)
and I have created this MQTT command: mosquitto_pub -h 192.168.1.20 -t /wassim/led -m "on".
So, when I connect only one ESP client, I see the message "on" in the serial monitor. But when I connect the second ESP client, I can't see any message on the serial monitor... (But if on the terminal of the Raspberry, then I can see everything. On the clients I can't see anything). The code:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <MQTTClient.h>
float temp;
float lm;
String aw="";
const char* host = "192.168.1.20";
const char* ssid = "THOMSON1121";
const char* password = "Wassim";
WiFiClient net;
MQTTClient mqtt;
void connect();
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println("Booting...");
WiFi.mode(WIFI_AP_STA);
WiFi.begin(ssid, password);
mqtt.begin(host, net);
connect();
if(mqtt.subscribe("/wassim/led")) {
Serial.println("Subscription Valid !");
}
Serial.println("Setup completed...");
}
void loop() {
if (!mqtt.connected()) {
connect();
}
mqtt.loop();
delay(3000);
}
void connect() {
while(WiFi.waitForConnectResult() != WL_CONNECTED) {
WiFi.begin(ssid, password);
Serial.println("WiFi connection failed. Retry.");
}
Serial.print("Wifi connection successful - IP-Address: ");
Serial.println(WiFi.localIP());
while (!mqtt.connect(host)) {
Serial.print(".");
}
Serial.println("MQTT connected!");
}
void messageReceived(String topic, String payload, char * bytes, unsigned int length) {
Serial.print("incoming: ");
Serial.print(topic);
Serial.print(" - ");
Serial.print(payload);
Serial.println();
}
The change from one client to another is if(mqtt.subscribe("/wassim/tmp")).
MQTT is a 'message bus' application....in order to have multiple 'subscribers' receive the same message that is being put on the bus by a 'publisher', they both have to subscribe to the same topic...or at least enough of the topic + wildcard...in order to get sent that published message. You only have one of your two clients listening to the topic that your 'mosquitto_pub' command is sending out. For it to receive, you either specify the full topic (mqtt.subscribe("/wassim/led")), or a wildcard to pick up all the 'wassim' messages sent out (mqtt.subscribe("/wassim/#")).

I am unable to connect successfully to 8266 wifi module using arduino

Hi I am new to arduino programming and I am have an issue. I have successfully managed to display the wifi using esp8266 module i.e when I run my code the esp8266 module creates a wifi. It also asks for password but after that there is no output of successful connection. I am using the method wifi.softAp(username,password) for creation of wifi network. I have written the following code:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
const char* ssid = "Jeet";//Wifi username
const char* password = "wifibin12"; //Wifi password
ESP8266WebServer server(80);
void handleRoot() {
server.send(200, "text/plain", "<h1>hello from esp8266!</h1>");
}
void setup(void) {
// put your setup code here, to run once:
Serial.begin(115200);
//WiFi.mode(WIFI_AP);
Serial.print("this is my pass");
Serial.print(password);
WiFi.softAP(ssid, password);
Serial.print("Setting soft-Ap ... ");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
//If connection successful show IP address in serial monitor
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
server.on("/", handleRoot); //Which routine to handle at root location
server.begin(); //Start server
Serial.println("HTTP server started");
}
void loop() {
// put your main code here, to run repeatedly:
server.handleClient();
}
When I run the code I get ............. output continuously on serial monitor. Kindly help me fix this issue if anyone knows what I am doing wrong. Suggestions would also be appreciated.
It's getting stuck to while loop. Wifi.status() returns WL_CONNECTED when it is connected to wifi network (to another Access Point). So if you want just get AP to work you should try this:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
const char* ssid = "Jeet"; //Wifi username
const char* password = "wifibin12"; //Wifi password
ESP8266WebServer server(80);
void handleRoot() {
server.send(200, "text/plain", "<h1>hello from esp8266!</h1>");
}
void setup(void) {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.print("this is my pass");
Serial.print(password);
WiFi.softAP(ssid, password);
Serial.print("Setting soft-Ap ... ");
// Wait for connection
//If connection successful show IP address in serial monitor
Serial.println("");
Serial.print("AP name ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
server.on("/", handleRoot); //Which routine to handle at root location
server.begin(); //Start server
Serial.println("HTTP server started");
}
void loop() {
// put your main code here, to run repeatedly:
server.handleClient();
}
And WiFi.localIP() doesn't return AP's local ip. Default is 192.168.4.1.
I recommend looking docs and examples from here: https://github.com/esp8266/Arduino/tree/master/doc/esp8266wifi

MQTT on Arduino not working

I'm using Arduino Uno and Wi-Fi shield. I'm trying to implement MQTT protocol for communication and I tried two libraries for Arduino. First one is Knolleary's PubSubClient: http://pubsubclient.knolleary.net/ . I modified original example a little bit to use WiFi module instead of ethernet. Sending works but not every time (sometimes, the message is sent and sometimes not). But receiving via callback function doesn't work at all.
Here is my code:
/*
Basic MQTT example with Authentication
- connects to an MQTT server, providing username
and password
- publishes "hello world" to the desired topic
- subscribes to the desired topic
*/
#include <WiFi.h>
#include <PubSubClient.h>
char ssid[] = "[DELETED]"; // your network SSID (name)
char pass[] = "[DELETED]"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
// Update these with values suitable for your network.
IPAddress server(85, 119, 83, 194);
WiFiClient WifiClient;
void callbackFunc(char* topic, byte* payload, unsigned int length) {
Serial.println("test message received");
/*Serial.println();
Serial.println("=============== MESSAGE RECEIVED ================================");
Serial.print("Topic: ");
Serial.print(topic);
Serial.println();
Serial.println((const char *) payload);*/
}
PubSubClient client(server, 1883, callbackFunc, WifiClient);
void setup()
{
delay(2000);
Serial.begin(9600);
Serial.println("Starting....");
Serial.println("Initializing Wifi...");
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
}
// attempt to connect using WPA2 encryption:
Serial.println("Attempting to connect to WPA network...");
status = WiFi.begin(ssid, pass);
// if you're not connected, stop here:
if (status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
// If you are connected, print out success message
else
Serial.println("Connected to network");
if (client.connect("arduinoClient")) {
Serial.println("Connected to server! Sending message...");
client.publish("randy/test","hello world");
client.subscribe("randy/test");
Serial.println("Sent!");
}
else
{
Serial.println("ERROR: Cannot connect to MQTT server!");
Serial.println(client.state());
}
}
void loop()
{
client.loop();
delay(1000);
if (!client.connected())
{
if(!client.connect("arduinoClient"))
{
Serial.println("ERROR: Cannot connect to MQTT server!");
Serial.println(client.state());
}
else
{
client.subscribe("randy/test");
Serial.println("INFO: reconnected!");
}
}
}
As you can see, I'm using http://test.mosquitto.org/ for testing. I'm also using mosquitto on Ubuntu where I'm subscribed to the same topic and from where (another terminal window) I'm publishing to the same topic. Here is the picture of both windows:
As you can see, "hello world" message from Arduino is received successfully (but not every time), and when I publish "bla" message from another window, it's successfully received on mosquitto (on image) but NOT on Arduino. Is there something wrong with my code or? I found similar problem here: Arduino Knolleary PubSubClient will publish messages but can't receive them
It's worth noticing that it keeps getting reconnected all the time. As you can see, in loop() I put a part of code which will connect and subscribe again if connection is lost. On Serial Monitor I get "INFO: Reconnected!" message every 2-3 seconds.
Adafruit library
Then I tried the Adafruit library, but it won't connect at all! I tried with test.mosquitto.org and with io.adafruit.com from their example, but I just keep getting "Connection failed!" error. I tried making many changes and combinations but no luck so far. Once I managed to get "Failed to subscribe" instead of "Connection failed" but this was only once and next time with the same code I get "Connection failed" again.
Here's my code:
/*
Basic MQTT example with Authentication
- connects to an MQTT server, providing username
and password
- publishes "hello world" to the topic "outTopic"
- subscribes to the topic "inTopic"
*/
#include <WiFi.h>
#include <PubSubClient.h>
char ssid[] = "[DELETED]"; // your network SSID (name)
char pass[] = "[DELETED]"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
// Update these with values suitable for your network.
IPAddress server(85, 119, 83, 194);
WiFiClient WifiClient;
void callbackFunc(char* topic, byte* payload, unsigned int length) {
Serial.println("test message received");
/*Serial.println();
Serial.println("=============== MESSAGE RECEIVED ================================");
Serial.print("Topic: ");
Serial.print(topic);
Serial.println();
Serial.println((const char *) payload);*/
}
PubSubClient client(server, 1883, callbackFunc, WifiClient);
void setup()
{
delay(2000);
Serial.begin(9600);
Serial.println("Starting....");
Serial.println("Initializing Wifi...");
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
}
// attempt to connect using WPA2 encryption:
Serial.println("Attempting to connect to WPA network...");
status = WiFi.begin(ssid, pass);
// if you're not connected, stop here:
if (status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
// Ff you are connected, print out success message
else
Serial.println("Connected to network");
if (client.connect("arduinoClient")) {
Serial.println("Connected to server! Sending message...");
client.publish("randy/test","hello world");
client.subscribe("randy/test");
Serial.println("Sent!");
}
else
{
Serial.println("ERROR: Cannot connect to MQTT server!");
Serial.println(client.state());
}
}
void loop()
{
client.loop();
delay(1000);
if (!client.connected())
{
if(!client.connect("arduinoClient"))
{
Serial.println("ERROR: Cannot connect to MQTT server!");
Serial.println(client.state());
}
else
{
client.subscribe("randy/test");
Serial.println("INFO: reconnected!");
}
}
}
Any idea what's wrong with those libraries or my code?
As mentioned in the comments
When using example code on public brokers make sure you change the client id to something random as the odds of clashing with somebody else are pretty high. Because client ids have to be unique else they will cause a reconnection storm

Resources