NodeMCU ESP8266 Client-Server communication - arduino

I am trying to connect two ESP8266 boards to communicate with each other. The client board first connects to the server and sends a message, the character 'd', after the server receives the message it replies with "Hello from server".
Server
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
char *ssid = "SSID";
char *pass = "PASS";
int stat;
WiFiServer server(8080);
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid,pass);
Serial.println("Connecting to wifi ");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
delay(500);
}
Serial.print("SSID :");
Serial.print(ssid);
Serial.println("ip: ");
Serial.print(WiFi.localIP());
server.begin();
}
void loop() {
WiFiClient client = server.available();
if(client){
if(client.connected()){
Serial.println("Client connected");
if(client.available() > 0){
delay(500);
char data = client.read();
Serial.println(data);
delay(500);
}
char d[] = "Hello from server";
client.println(d);
}
client.stop();
}
}
Client
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
char *ssid = "SSID";
char *pass = "PASS";
char *host = "ip";
WiFiClient client;
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid,pass);
Serial.println("Connecting to wifi");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
delay(500);
}
//Serial.println("Connecting to wifi network");
Serial.print("SSID: ");
Serial.print(ssid);
Serial.println("Connected");
}
void loop() {
// put your main code here, to run repeatedly:
if(client.connect(host, 8080)) {
Serial.println("Connected to server");
client.println('d');
if(client.available() > 0){
delay(500);
Serial.println(client.read());
delay(500);
}
else{
Serial.println("No data received");
}
}
else{
Serial.println("Cannot connect to server");
}
client.stop();
}
The problem is that the message from client is received by the server. But the reply is not sent. When I try to see the reply from server using serial monitor in the client it gets connected to the server and the message is sent but the reply is not received.
I'm new to this domain and would like to know whether I'm doing it correctly or not. Any suggestions and solutions will help a lot.
Thank you.

Related

Node mcu esp8266 disconnects from MQTT broker

I have two node mcu modules connected to the same network, running the same code and powered the same way. Both of them are subscribed to the topic Terma but one of them randomly disconnects and then reconnects to the MQTT broker meanwhile it stayed connected to the wifi uninterruptedly, the other module stays connected with no problem. I don't know if it is a network issue or if the node mcu is damaged.
here is the code:
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "Milagros";
const char* password = "18095381";
const char* mqtt_server = "192.168.1.133";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
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(".");
}
randomSeed(micros());
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(14, LOW);
client.publish("estado","1");
// but actually the LED is on; this is because
// it is active low on the ESP-01)
} else {
digitalWrite(14, HIGH);
client.publish("estado","0");
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("terma", "hello world 1");
// ... and resubscribe
client.subscribe("terma");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pinMode(14, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1884);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}

ESP8266 is not able to connect to mosquitto broker. "Attempting MQTT connection...failed, rc=-2 try again in 5 seconds"

I'm running a mosquitto broker and a node-red server in my PC , node-red is able to connect to mosquitto. The ESP8266 is able to connect to the WiFi but not to the broker a "Attempting MQTT connection...failed, rc=-2 try again in 5 seconds" message is displayed in the serial monitor. I'm also using MQTT explorer I don't know if it has something to do with it.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "Milagros";
const char* password = "18095381";
const char* mqtt_server = "192.168.1.133";
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
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...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("data", "hello world");
// ... and resubscribe
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
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 loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
unsigned long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("data", msg);
}
}```

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)

Code not connecting to MQTT local server

I am trying to connect my Arduino Uno with WiFi shield to my MQTT server. I am running it local on my Mac. It seems to be stuck in the while loop. I think it doesn't connect to the broker. Here is my code. What could be the problem with the loop? Or is there another problem?
#include <WiFi.h>
#include <MQTTClient.h>
const char ssid[] = " : /*filed in*: ";
const char pass[] = " /*filed in*/ ";
WiFiClient net;
MQTTClient client;
unsigned long lastMillis = 0;
void setup() {
Serial.begin(9600);
WiFi.begin(ssid, pass);
// Note: Local domain names (e.g. "Computer.local" on OSX) are not supported by Arduino.
// You need to set the IP address directly.
client.begin("10.0.1.5", net);
client.onMessage(messageReceived);
connect();
}
void connect() {
Serial.print("checking wifi...");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}
Serial.println("wifi connected");
Serial.print("\nconnecting...");
while (!client.connect("Arduino test")) {
Serial.print(".");
delay(1000);
}
Serial.println("\nconnected!");
Serial.println("connected");
client.subscribe("hello");
// client.unsubscribe("/hello");
}
void loop() {
client.loop();
if (!client.connected()) {
connect();
Serial.print("not");
}
// publish a message roughly every second.
if (millis() - lastMillis > 1000) {
lastMillis = millis();
client.publish("hello world");
}
}
void messageReceived(String &topic, String &payload) {
Serial.println("incoming: " + topic + " - " + payload);
}

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.

Resources