ESP32 access point - arduino

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)

Related

My ESP32 is scanning all the nearby WiFi Networks but it does not connect to my WiFi Router using Arduino IDE (Return Value of WiFi.status API = 6)

I am trying to connect my ESP32 to my Wifi Router using Arduino IDE but it is not connecting & giving a connection failed or disconnected status. I also confirmed it is scanning all the available Wifi Networks but not connecting to my router. I even tried with another ESP32 board but the problem is still there.
I tried this code below. This code would scan/give the available Wifi networks and it did. Also, I was expecting this code to run smoothly but my ESP32 won't connect to my Wifi router.
#include<WiFi.h>
const char *ssid = "my_SSID";
const char *password = "my_Password";
void setup()
{
Serial.begin(115200);
delay(2000);
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
Serial.println("scan start");
// WiFi.scanNetworks will return the number of networks found
int n = WiFi.scanNetworks();
Serial.println("scan done");
if (n == 0) {
Serial.println("no networks found");
} else {
Serial.print(n);
Serial.println(" networks found");}
// Connect to my network.
WiFi.begin(ssid,password);
// Check Status of your WiFi Connection
int x = WiFi.status(); // If x=3 (Connected to Network) & If x=6 (Disconnected from Network)
Serial.print("WiFi Connection Status is ");
Serial.println(x);
while(WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("WiFi Connection Failed...");
WiFi.disconnect();
WiFi.reconnect(); }
//Print local IP address and start web server
Serial.println("\nConnecting");
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("ESP32 IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {}
1st image shows the output of my serial monitor. 2nd inamge shows the return value for WiFi.status function
Try this code:
#include<WiFi.h>
const char *ssid = "YourSSID";
const char *password = "YourPassword";
void initWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(1000);
}
Serial.println(WiFi.localIP());
}
void setup() {
Serial.begin(115200);
initWiFi();
Serial.print("RRSI: ");
Serial.println(WiFi.RSSI());
}
void loop() {
// put your main code here, to run repeatedly:
}
I was just having this same issue. I found that, for me, the issue was not in the ESP32. It was the WiFi Router. I had the security on the router set to 'WEP' in the router. When I changed the security to 'WPA2-PSK' the ESP32 device connected right away.

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)

NodeMCU gets strange IP address

Today I got my NodeMCU and I instantly started with coding. I wanted to connect to my WiFi and to my MQTT server.
I used the PubSub example for this.
In the serial monitor I get the message that I connected successfully with the WiFi, but I get the IP 172.20.10.6. However we have a 192.168... network.
Then when I try to reach my MQTT server it doesn't find it. When I try to give the NodeMCU a static IP it also says connected successfully and shows up the static IP I gave it, but I still can't connect to my MQTT server.
I can't ping the NodeMCU and don't find it in my Smartphone app "Fing".
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "myssid";
const char* password = "mypw";
const char* mqtt_server = "192.168.42.131";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup() {
pinMode(BUILTIN_LED, OUTPUT);
// Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
digitalWrite(BUILTIN_LED, LOW);
// Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is active low on the ESP-01)
} else {
digitalWrite(BUILTIN_LED, HIGH);
// Turn the LED off by making the voltage HIGH
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Once connected, publish an announcement...
//client.publish("outTopic", "hello world");
// ... and resubscribe
client.subscribe("mathistest");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
snprintf (msg, 75, "hello world #%ld", value);
}
}
You are most likely having a DHCP failure.
A 172.20.x.x address is a non-routable IP address (see: https://www.lifewire.com/what-is-a-private-ip-address-2625970) and the DHCP code is (likely) using that address when the address assignment fails.
Stepping back, DHCP is most likely failing because you are failing to connect to the Wifi network with the correct SSID and password.

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 between esp8266 and arduino with PubSubclient

I am using ESP8266 with arduino using WiFiEsp library.I want to make MQTT connection with arduino so I use PubSubclient library.i got error:
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
my code is:
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <WiFiEspUdp.h>
#include "SoftwareSerial.h"
#include <PubSubClient.h>
IPAddress server(212, 72, 74, 21);
char ssid[] = "atmel"; // your network SSID (name)
char pass[] = "bets56789"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
// Initialize the Ethernet client object
WiFiEspClient espClient;
PubSubClient client(espClient);
SoftwareSerial soft(2,3); // RX, TX
void setup() {
// initialize serial for debugging
Serial.begin(9600);
// initialize serial for ESP module
soft.begin(115200);
// initialize ESP module
WiFi.init(&soft);
// check for the presence of the shield
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue
while (true);
}
// attempt to connect to WiFi network
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network
status = WiFi.begin(ssid, pass);
}
// you're connected now, so print out the data
Serial.println("You're connected to the network");
//delay(2000);
//connect to MQTT server
client.setServer(server, 1883);
client.setCallback(callback);
}
//print any message received for subscribed topic
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void loop() {
// put your main code here, to run repeatedly:
if (!client.connected()) {
reconnect();
}
client.loop();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect, just a name to identify the client
if (client.connect("arduinoClient")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outSHADAB","hello world");
// ... and resubscribe
client.subscribe("inShadab");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
I am using ESP8266 with arduino using WiFiEsp library.I want to make MQTT connection with arduino so I use PubSubclient library
I don't think the PubSubClient supports the WiFiEsp as a network layer from an arduino.
While the doc list the ESP8266 I believe this is running the PubSubClient directly on the ESP8266 hardware.

Resources