I created How to Set an ESP32 Access Point (AP) for Web Server tutorial Now I need to write code to another esp32 acting as a station and which has sensor data on it and it needs to transmit this to AP server which in turn will send the sensor payload to MySQL database in Bluehost. The AP server will act more like a gateway. I suppose we need to change the AP server into station mode temporarily to send the payload to database.. Request help to do this for handling the data in 40 acres farm. How to make a esp32 work both in station mode and AP mode. Please help
This URL below explains how a farmer in France did this.. Ir was on ESP2866.. The code is also there for the AP and Multiple ESP8266 Stations.. We need a tutorial in ESP32 with BME280 and the ESP32 Access Point to Transmit the readings from Nodes to mysql database in Bluehost.
Quoting from the article :
https://www.geekstips.com/two-esp8266-communication-talk-each-other/
Internet of Things project – Communication between ESP8266 modules
A very talented farmer from Europe, who grows vegetables on large, square fields has managed to implement a fully automatic temperature and moisture Wi-Fi monitoring system over a 5 squares km field using the benefits of interconnecting ESP8266 modules without using any wires. Yes, 5km, its a huge area, but it can easily be covered if you have imagination.
The complete solution including the 1-Wire sensors costed about 350 – 400$ using batteries from laptops cells and a simple phone card charged with 5$ / month, which for an industrial large scale monitoring system is extremely cheap. I saw people spending thousands dollars on a commercial Zig-Bee system, monitoring a small 100 m deposit, having the same results.
=======================================
Is it possible to have a tutorial with ESP32 and BME280 please ? The Access Point ESP32 can also act as a gateway and transfer the sensor data from ESP32 Station Nodes to Mysql database.
Hi.
First, I’m sorry for the delay in my response.
In order to send readings to your database, the ESP32 needs to be connected to the internet, so it needs to be set as an station.
If you don-t have access to a nearby wi-fi, you can connect your ESP32 tp the internet using a data plan from a SIM card for example: https://randomnerdtutorials.com/esp32-sim800l-publish-data-to-cloud/ This tutorial also explains how to send BME280 readings to database in Bluehost.
The ESP32 can be set as a station or as an access point. Not both at the same time. You need to turn off the access point to set it as station or vice versa. (However, I’ve never tried this).
What exact tutorial do you need?
Regards,
Sara
Hi Sara
Thanks for the reply.. You are right.. The code in https://www.geekstips.com/two-esp8266-communication-talk-each-other/ also switches some of the nodes used as AP into AP mode when collecting data from worker nodes which are always in station mode and then the AP nodes temporarily switches to Station mode and sends to Gateway and reverts back to AP mode for sends data collection.
I need a tutorial to make a station mode ESP32 (which has BMR280 sensor on it) send the data at intervals to AP (not as HTML) in ascii (like a csv format), which the AP Node will transmit to (https://randomnerdtutorials.com/esp32-sim800l-publish-data-to-cloud/) Gateway (TTGO T-Call ESP32 SIM800L)
I can format the sensor data sent by AP to Gateway ( and execute a post to mysql database in bluehost. To be more precise i need a tutorial which will send the snedor data from station nodes (having bme280 sensor data) to AP not in HTML to AP nodes but in say like a csv line. From there i will do the rest liek sending the csv type line data to gateway and complete the mysql insert.
if i know how to transmit the senor data from station node to AP Node in say a csv format ( I can check that in AP by printing it to Serial Monitor) , then i will do therest by using the same ode to make the AP to Gateway. Of course the AP will be switched to Station temporarily to send to Gateway.
I am trying to do the same what the farmer did in France to my 40 Acre field to monitor my crops. He was using Internet Wifi. I need to do thro SIM800 ESP32, since Internet Provider signals are not there in my remote area
My sincere apologies for taking up your time, but if i can translate your tutorials to a real application, that will be great. The only problem now is how to transmit the sensor data not in HTML to other devices/browser but in some csv format.
Thanks and Regards.
Jay (Jayanthi)
Hi Sara
- Figured out how to send BME280 sensor payload data from ESP32 client/node to ESP32 Server
- The 5 client nodes are set to IP address (192.168.1.5 to 192.168.1.10 )
- The ESP32 server has static address of 192.168.1.1 in station mode and able to receive the client wifi sensor data.
- But not able to send the payload of 5 client nodes (station mode) thro my home internet to mysql database on bluehost. This is because my server is in 192.168.1.1) and the wifi router is 192.168.0.1
- I need to correct the code to receive the client sensor data to my server in AP mode and transmit to my wifi router by switching to station mode to update my database in bluehost and again re-set the server to AP mode to receive sensor data from wifi clients. All devices server or clients are using ESP32 wifi dev32 board
Hi.
I saw these lines of code in a WiFi example from the WiFi library, and I think it should be what you’re looking for.
// Set WiFi to station mode and disconnect from an AP if it was previously connected WiFi.mode(WIFI_STA); WiFi.disconnect(); delay(100);
Not sure if this works.
Meanwhile, we’ve written a sample code to exchange data via WiFi between two ESP boards. If you want I can send you the example via email.
We’ll publish a post about that in a near future.
Regards,
Sara
Hi Sara
We can start a server in both AP and Station Mode by using command WiFi.mode(WIFI_AP_STA); I have in my code used WiFi.mode(WIFI_STA); and WiFi.mode(WIFI_AP) to reduce the confusion
We can operate in any one mode at a time.. 50% of code, sending BME280 data to mysql database is from your tutorials. The Server in AP mode gets data from the Client/node (which will always be in station mode) and switches to Station mode just to send the sensor data to mysql and again switches back to AP mode and listens to the node. Please find my working code (My Apologies to all, it not very professional code by a farmer) for use in the forum.
Now that i am able to do this, i am not happy, i am not able to cover distances with wifi for sensor data collection. I need multiple AP points for the sensor nodes to send payload via a gateway. The AP and Gateway needs to be powered all the time, but the node can be put to sleep for long periods
I am planning to use your TTGO Lora tutorial to cover sensor distance data travel problem. The ESP32 Heltec Lora board has similar client and server for your info. Hope we can have a similar tutorial for TTGO Board also. I think this discussion can be set to closed status and i hope to get back with a Lora boards which can cover long distance transmission (sensor data to Gateway)
code here : For AP/STA Server
// Server Code for switching between AP mode or Station Mode
// In AP Mode the server listens and gets data from Node/Client
// Switches to Statio mode and upadtes mysql database and again swithces
// back to AP mode listens for BME280 payload from client
#ifdef ESP32
#include <WiFi.h>
#include <HTTPClient.h>
#else
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#endif
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
// Access Point server name and passwd
const char* APssid = “ESP8266_AP”; // Any name can be given
const char* APpassword = “12345678”;
IPAddress IP(192, 168, 4, 15);
IPAddress mask = (255, 255, 255, 0);
const char* ssid = “Your internet ssid”;
const char* password = “Your internet passwd”;
IPAddress staIP(192, 168, 0, 102);
IPAddress stagateway(192, 168, 0, 1);
IPAddress stamask(255, 255, 255, 0);
WiFiServer server(80);
const char* serverName = “http://example.com/post-esp-data.php”;
String apiKeyValue = “tPmAT5Ab3j7F9”;
String sensorName = “BME280”;
String sensorLocation = “Office”;
#define SEALEVELPRESSURE_HPA (1013.25)
Adafruit_BME280 bme; // I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI
byte ledPin = 2;
int totalLength;
String request;
String httpRequestData;
void setup() {
Serial.begin(115200);
delay(300);
Serial.println(“**********************************************”);
Serial.println(“INITIAL SETUP STARTS IN AP MODE”);
Serial.println(“**********************************************”);
switch_to_ap_wifi();
delay(10000);
}
void loop() {
Serial.println(“**********************************************”);
Serial.println(” GETTING INTO LOOP IN AP MODE “);
Serial.println(“**********************************************”);
//delay(10000);
WiFiClient client = server.available();
if (!client) {return;}
digitalWrite(ledPin, LOW);
Serial.println(“Connected to client. There may be data comin in”);
request = client.readStringUntil(‘\r’);
Serial.println(“********************************”);
Serial.println(“From the station: ” + request);
client.flush();
Serial.print(“Byte sent to the station: “);
Serial.println(client.println(request + “ca” + “\r”));
digitalWrite(ledPin, HIGH);
digitalWrite(ledPin, HIGH);
totalLength = 0;
totalLength = sizeof(request);
Serial.print(“length of payload is : “);
//Serial.println(“********************************”);
Serial.println(totalLength);
if (totalLength > 11) {
Serial.println(“SWITCHING TO INTERNET WIFI MODE TO LOAD DATA”);
switch_to_internet_wifi();
delay(10000);
Serial.println(“**********************************************”);
Serial.println(” GETTING INTO AP MODE IN 10 SECONDS”);
Serial.println(“**********************************************”);
switch_to_ap_wifi();
delay(10000);
}
else
{
Serial.println(“**********************************************”);
Serial.println(” NO CLIENT DATA.. LOOPING BACK IN AP MODE”);
Serial.println(“**********************************************”);
}
}
void switch_to_internet_wifi() {
Serial.println(“AP server Wifi start disconnect”);
WiFi.disconnect();
delay(1000);
Serial.println(“AP server Wifi disconnected”);
Serial.println(“Now trying to connect server in station mode “);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(“.”);
}
server.begin();
delay(3000);
Serial.println(“”);
Serial.print(“Your internet ip is: “);
Serial.println(WiFi.localIP());
Serial.println(“Station Server started at port 80 in sta mode”);
Serial.println(“Now trying to load jlndigital”);
// Wait for WiFi connection
// if ((WiFi.status() == WL_CONNECTED)) {
WiFiClient client;
HTTPClient http;
// Your Domain name with URL path or IP address with path
Serial.print(“[HTTP] begin…\n”);
if (http.begin(client, “http://example.com/post-esp-data.php”)) {
// Specify content-type header
http.addHeader(“Content-Type”, “application/x-www-form-urlencoded”);
// Prepare your HTTP POST request data
//String httpRequestData = “api_key=” + apiKeyValue + “&sensor=” + sensorName + “&location=” + sensorLocation + “&value1=” + String(bme.readTemperature()) + “&value2=” + String(bme.readHumidity()) + “&value3=” + String(bme.readPressure()/100.0F) + “”;
//String httpRequestData = “api_key=tPmAT5Ab3j7F9&sensor=BME280&location=Test&value1=24.75&value2=49.54&value3=1005.14”;
httpRequestData = request;
Serial.print(“httpRequestData: “);
Serial.println(httpRequestData);
// You can comment the httpRequestData variable above
// then, use the httpRequestData variable below (for testing purposes without the BME280 sensor)
//String httpRequestData = “api_key=tPmAT5Ab3j7F9&sensor=BME280&location=Office&value1=24.75&value2=49.54&value3=1005.14”;
// Send HTTP POST request
int httpResponseCode = http.POST(httpRequestData);
// If you need an HTTP request with a content type: text/plain
//http.addHeader(“Content-Type”, “text/plain”);
//int httpResponseCode = http.POST(“Hello, World!”);
// If you need an HTTP request with a content type: application/json, use the following:
//http.addHeader(“Content-Type”, “application/json”);
//int httpResponseCode = http.POST(“{\”value1\”:\”19\”,\”value2\”:\”67\”,\”value3\”:\”78\”}”);
if (httpResponseCode > 0) {
Serial.print(“HTTP Response code: “);
Serial.println(httpResponseCode);
}
else {
Serial.print(“Error code: “);
Serial.println(httpResponseCode);
}
// Free resources
http.end();
Serial.println(“Now Ended http load”);
// Serial.println(“Waiting to switch to ap mode for 30 seconds”);
// Serial.println(“**********************************************”);
}
else {
Serial.println(“Unable to connect to HTTP”);
}
// }
//Send an HTTP POST request every 30 seconds 2 min now
delay(5000);
}
void switch_to_ap_wifi() {
// Serial.println(“**********************************************”);
Serial.println(“Disconnect wifi for all modes”);
WiFi.disconnect();
Serial.print(“Configuring server as access point…”);
WiFi.mode(WIFI_AP);
WiFi.softAP(APssid, APpassword);
WiFi.softAPConfig(IP, IP, mask);
/* while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(“.”);
}
*/
Serial.println(“”);
Serial.println(“WiFi connected in ap mode for 192, 168, 4, 15”);
// Start the server ——————————————————-
server.begin();
Serial.println(“WiFiServer started at port 80 in ap mode”);
// Print the IP address —————————————————
Serial.print(“Your AP IP Address is: “);
Serial.println(WiFi.softAPIP());
// Serial.println(“Waiting to switch to wifi mode for 10 seconds”);
// Serial.println(“**********************************************”);
delay(10000);
}
======================================================================================= Code for STA Client
=======================================================================================
Client/Node Code which has sensors to send payload to AP Server
/* Accesspoint – station communication without router
* see: https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/station-class.rst
* Works with: accesspoint_bare_01.ino
*/
#ifdef ESP32
#include <WiFi.h>
#include <HTTPClient.h>
#else
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#endif
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
byte ledPin = 2;
char ssid[] = “ESP8266_AP”; // SSID of your AP
char pass[] = “12345678”; // password of your AP
IPAddress server(192,168,4,15); // IP address of the AP
WiFiClient client;
String apiKeyValue = “tPmAT5Ab3j7F9”;
String sensorName = “BME280”;
String sensorLocation = “Node1”;
#define SEALEVELPRESSURE_HPA (1013.25)
Adafruit_BME280 bme; // I2C
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass); // connects to the WiFi AP
Serial.println();
Serial.println(“Connection to the AP Server”);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(“.”);
delay(500);
}
Serial.println();
Serial.println(“Connected to ap server”);
Serial.print(“LocalIP:”); Serial.println(WiFi.localIP());
Serial.println(“MAC:” + WiFi.macAddress());
Serial.print(“Gateway:”); Serial.println(WiFi.gatewayIP());
Serial.print(“AP MAC:”); Serial.println(WiFi.BSSIDstr());
pinMode(ledPin, OUTPUT);
// (you can also pass in a Wire library object like &Wire2)
bool status = bme.begin(0x76);
if (!status) {
Serial.println(“Could not find a valid BME280 sensor, check wiring or change I2C address!”);
while (1);
}
}
void loop() {
client.connect(server, 80);
digitalWrite(ledPin, LOW);
Serial.println(“********************************”);
Serial.print(“Byte sent to the AP: “);
// For Testing without BME280
//Serial.println(client.print(“api_key=tPmAT5Ab3j7F9&sensor=BME280&location=Office&value1=24.75&value2=49.54&value3=1005.14\r”));
//String Payload = “api_key=tPmAT5Ab3j7F9&sensor=BME280&location=Office&value1=24.75&value2=49.54&value3=1005.14\r”;
//Serial.println(client.print(Payload));
String Payload = “api_key=” + apiKeyValue + “&sensor=” + sensorName + “&location=” + sensorLocation + “&value1=” + String(bme.readTemperature()) + “&value2=” + String(bme.readHumidity()) + “&value3=” + String(bme.readPressure()/100.0F) + “\r”;
Serial.println(Payload);
Serial.println(client.print(Payload));
String answer = client.readStringUntil(‘\r’);
Serial.println(“From the AP: ” + answer);
client.flush();
digitalWrite(ledPin, HIGH);
client.stop();
delay(30000);
}
================================================================================================================================
Hi.
Thank you so much for sharing your code, it can be useful for other of our readers.
What distance would you like to cover between your sensor nodes?
The distance with LoRa depends on the surrounding environment (if it is an open field or if it has many obstacles in between) and also depends on the board you’re using.
Regards,
Sara
Hi Sara
Let me Wish you and Rui a happy new year. Without your tutorials, i could not have achieved what i wanted to improve my Farm… I have been thro many web sites, but yours was the one where i could get sensor data uploaded on my own domain in a single day.
Coming to your question, the spacing between any 2 sensor nodes should at least be 500 meters. This is to avoid too many access points to send the data to the ESP32 Publish Data to Cloud without Wi-Fi (TTGO T-Call ESP32 SIM800L). This TTGO iT-Call I want to use as a gateway (i do not have ISP wifi in the middle my Farm site). That is why i am thinking of using Lora boards instead of Plain ESP32 boards to bridge the distances in transmitting sensor data. The Heltec Lora Boards (from amazon site) is less than 30 USD per piece and the TTGO Lora board is around 50 USD in my country.. My goal is to use 10 nodes and one gateway (TTGO T-Call ESP3 SIM800L) and avoid Access Points. The Heltec Code can bridge the data transfer from the outermost node to the gateway by hopping over other nodes. That is my first impression.. Let me complete the project and post it in forum
Once again i thank you and Rui for the great tutorials..and a great 2020 year plus happy times in your new home.
Regards
Jay (Lakshminarayana Jayanthi)
Hi again.
Thank you so much for your nice words and I wish you a happy new year too.
LoRa boards can be a great option for what you want to achieve. If you are in an open field, you should easily achieve 500 meters with LoRa boards.
We have a LoRa section in the ESP32 course, and also these tutorials with the TTGO board:
https://randomnerdtutorials.com/ttgo-lora32-sx1276-arduino-ide/
https://randomnerdtutorials.com/esp32-lora-sensor-web-server/
I hope this helps.
Keep us updated.
Regards,
Sara
Just for a reference, we’ve published how to establish a Wi-Fi communication between ESP32/ESP8266 boards. Here are the tutorials: