I had a Node MCU module as shown in the photo.
My nodemcu
I had this tutorial from this link:Tutorial link
I had a problem with WIFI Configuring which from the code I had online it should be working with the browser 192.168.4.1 as shown as below. But with my LoLin NodeMCU V3 I cant reach to the browser page and always show the connection has timed out. Can I know is it my NodeMCU module problem?
p.s.
The wifi connection work well with hardcoding but not WIFI configuration)
The Module i found there is slightly different from normal Nodemcu with a yellow component on it.
I used ARDUINO IDE to compile and upload.
proper result with the browser for wifi configuration
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>
//Variables
int i = 0;
int statusCode;
const char* ssid = "Default_SSID";
const char* passphrase = "Default_Password";
String st;
String content;
//Function Decalration
bool testWifi(void);
void launchWeb(void);
void setupAP(void);
//Establishing Local server at port 80 whenever required
ESP8266WebServer server(80);
void setup()
{
Serial.begin(115200); //Initialising if(DEBUG)Serial Monitor
Serial.println();
Serial.println("Disconnecting current wifi connection");
WiFi.disconnect();
EEPROM.begin(512); //Initialasing EEPROM
delay(10);
pinMode(LED_BUILTIN, OUTPUT);
Serial.println();
Serial.println();
Serial.println("Startup");
//---------------------------------------- Read eeprom for ssid and pass
Serial.println("Reading EEPROM ssid");
String esid;
for (int i = 0; i < 32; ++i)
{
esid += char(EEPROM.read(i));
}
Serial.println();
Serial.print("SSID: ");
Serial.println(esid);
Serial.println("Reading EEPROM pass");
String epass = "";
for (int i = 32; i < 96; ++i)
{
epass += char(EEPROM.read(i));
}
Serial.print("PASS: ");
Serial.println(epass);
WiFi.begin(esid.c_str(), epass.c_str());
if (testWifi())
{
Serial.println("Succesfully Connected!!!");
return;
}
else
{
Serial.println("Turning the HotSpot On");
launchWeb();
setupAP();// Setup HotSpot
}
Serial.println();
Serial.println("Waiting.");
while ((WiFi.status() != WL_CONNECTED))
{
Serial.print(".");
delay(100);
server.handleClient();
}
}
void loop() {
if ((WiFi.status() == WL_CONNECTED))
{
for (int i = 0; i < 10; i++)
{
digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
digitalWrite(LED_BUILTIN, LOW);
delay(1000);
}
}
else
{
}
}
//----------------------------------------------- Fuctions used for WiFi credentials saving and connecting to it which you do not need to change
bool testWifi(void)
{
int c = 0;
Serial.println("Waiting for Wifi to connect");
while ( c < 20 ) {
if (WiFi.status() == WL_CONNECTED)
{
return true;
}
delay(500);
Serial.print("*");
c++;
}
Serial.println("");
Serial.println("Connect timed out, opening AP");
return false;
}
void launchWeb()
{
Serial.println("");
if (WiFi.status() == WL_CONNECTED)
Serial.println("WiFi connected");
Serial.print("Local IP: ");
Serial.println(WiFi.localIP());
Serial.print("SoftAP IP: ");
Serial.println(WiFi.softAPIP());
createWebServer();
// Start the server
server.begin();
Serial.println("Server started");
}
void setupAP(void)
{
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
int n = WiFi.scanNetworks();
Serial.println("scan done");
if (n == 0)
Serial.println("no networks found");
else
{
Serial.print(n);
Serial.println(" networks found");
for (int i = 0; i < n; ++i)
{
// Print SSID and RSSI for each network found
Serial.print(i + 1);
Serial.print(": ");
Serial.print(WiFi.SSID(i));
Serial.print(" (");
Serial.print(WiFi.RSSI(i));
Serial.print(")");
Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*");
delay(10);
}
}
Serial.println("");
st = "<ol>";
for (int i = 0; i < n; ++i)
{
// Print SSID and RSSI for each network found
st += "<li>";
st += WiFi.SSID(i);
st += " (";
st += WiFi.RSSI(i);
st += ")";
st += (WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*";
st += "</li>";
}
st += "</ol>";
delay(100);
WiFi.softAP("ElectronicsInnovation", "");
Serial.println("Initializing_softap_for_wifi credentials_modification");
launchWeb();
Serial.println("over");
}
void createWebServer()
{
{
server.on("/", []() {
IPAddress ip = WiFi.softAPIP();
String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
content = "<!DOCTYPE HTML>\r\n<html>Welcome to Wifi Credentials Update page";
content += "<form action=\"/scan\" method=\"POST\"><input type=\"submit\" value=\"scan\"></form>";
content += ipStr;
content += "<p>";
content += st;
content += "</p><form method='get' action='setting'><label>SSID: </label><input name='ssid' length=32><input name='pass' length=64><input type='submit'></form>";
content += "</html>";
server.send(200, "text/html", content);
});
server.on("/scan", []() {
//setupAP();
IPAddress ip = WiFi.softAPIP();
String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
content = "<!DOCTYPE HTML>\r\n<html>go back";
server.send(200, "text/html", content);
});
server.on("/setting", []() {
String qsid = server.arg("ssid");
String qpass = server.arg("pass");
if (qsid.length() > 0 && qpass.length() > 0) {
Serial.println("clearing eeprom");
for (int i = 0; i < 96; ++i) {
EEPROM.write(i, 0);
}
Serial.println(qsid);
Serial.println("");
Serial.println(qpass);
Serial.println("");
Serial.println("writing eeprom ssid:");
for (int i = 0; i < qsid.length(); ++i)
{
EEPROM.write(i, qsid[i]);
Serial.print("Wrote: ");
Serial.println(qsid[i]);
}
Serial.println("writing eeprom pass:");
for (int i = 0; i < qpass.length(); ++i)
{
EEPROM.write(32 + i, qpass[i]);
Serial.print("Wrote: ");
Serial.println(qpass[i]);
}
EEPROM.commit();
content = "{\"Success\":\"saved to eeprom... reset to boot into new wifi\"}";
statusCode = 200;
ESP.reset();
} else {
content = "{\"Error\":\"404 not found\"}";
statusCode = 404;
Serial.println("Sending 404");
}
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(statusCode, "application/json", content);
});
}
}
I had tried several times with the code provided online but same results came out with the browser couldnt work.
Be sure to first connect to AP ElectronnicsInnovation and type "http://192.168.4.1" in browser address.
(https - by default - don't works).
I try your code on esp8266 and it works fine.
Related
I am using ESP32 integrated Sim7600CE module to transfer data to Firebase Realtime database using http and got 400 Bad Request, please help me to solve this.
13:36:48.693 -> Status code: 400
13:36:48.833 -> Response: <html>
13:36:48.833 -> <head><title>400 The plain HTTP request was sent to HTTPS port</title></head>
13:36:48.833 -> <body>
13:36:48.833 -> <center><h1>400 Bad Request</h1></center>
#define TINY_GSM_MODEM_SIM7600
#define TINY_GSM_RX_BUFFER 650
#include <ArduinoJson.h>
#include <TinyGsmClient.h>
#include <ArduinoHttpClient.h> //https://github.com/arduino-libraries/ArduinoHttpClient
#include "TinyGsmClient.h"
#define SIM_RESET_PIN 15
#define SIM_AT_BAUDRATE 115200
#define GSM_PIN ""
#define SIM_TX 17
#define SIM_RX 16
const char FIREBASE_HOST[] = "smartgrid1-930b0-default-rtdb.firebaseio.com";
const String FIREBASE_AUTH = "zezoyo69fX9eqPDpjaom6CJAyXhnW081GlJ4ah5c";
const String FIREBASE_PATH = "/";
const int SSL_PORT = 443;
char APN[] = "v-internet"; //
char USER[] = "";
char PASS[] = "";
TinyGsm modem(Serial2);
TinyGsmClient gsm_client_secure_modem(modem);
HttpClient http_client = HttpClient(gsm_client_secure_modem, FIREBASE_HOST, SSL_PORT);
unsigned long previousMillis = 0;
// Hàm dùng để thiết lập modem SIM tạo kết nối GPRS
bool connectToGPRS() {
// Unlock SIM (nếu có)
if (GSM_PIN && modem.getSimStatus() != 3)
modem.simUnlock(GSM_PIN);
Serial.println("Ket noi toi nha mang...");
while (!modem.waitForNetwork(60000L)) {
Serial.println("._.");
delay(5000);
}
// Nếu không thấy sóng từ nhà mạng thì thoát hàm
if (!modem.isNetworkConnected())
return false;
Serial.println("Ket noi GPRS");
if (!modem.gprsConnect(APN)) {// Hàm kết nối tới gprs trả về true/false cho biết có kết nối được hay chưa
Serial.print("Khong the ket noi GPRS - ");
Serial.println(APN);
return false;
}
// Kiểm tra lại lần nữa để chắc cú
if (modem.isGprsConnected()){
Serial.println("Da ket noi duoc GPRS!");
return true;
}
return false;
}
// Hàm khởi động module SIM
bool initModemSIM() {
Serial.println("Bat dau khoi dong module SIM");
// Đặt chân reset của module xuống LOW để chạy
pinMode(SIM_RESET_PIN, OUTPUT);
digitalWrite(SIM_RESET_PIN, LOW);
delay(5000);
Serial2.begin(SIM_AT_BAUDRATE);// Module SIM giao tiếp với ESP qua cổng Serial2 bằng AT cmds
if (!modem.restart()) {
Serial.println("Khong the khoi dong lai module SIM => Co loi");
return false;
}
return true;
}
void setup() {
Serial.begin(115200);
if (initModemSIM()){
while(!connectToGPRS()) delay(100);
}
if (modem.isGprsConnected()) {
Serial.print(F("Connecting to "));
Serial.println(APN);
if (!modem.gprsConnect(APN, USER, PASS))
{
Serial.println(" fail");
delay(1000);
return;
}
}
if (initModemSIM()){
while(!connectToGPRS()) delay(100);
}
modem.restart();
String modemInfo = modem.getModemInfo();
Serial.print("Modem: ");
Serial.println(modemInfo);
http_client.setHttpResponseTimeout(10 * 1000); //^0 secs timeout
}
void loop() {
Serial.print(F("Connecting to "));
Serial.println(APN);
if (!modem.gprsConnect(APN, USER, PASS))
{
Serial.println(" fail");
delay(1000);
return;
}
Serial.println(" OK");
http_client.connect(FIREBASE_HOST, SSL_PORT);
while (true) {
if (!http_client.connected())
{
Serial.println();
http_client.stop();// Shutdown
Serial.println("HTTP not connect");
break;
}
else
{
dht_loop();
}
}
}
void PostToFirebase(const char* method, const String & path , const String & data, HttpClient* http)
{
String response;
int statusCode = 0;
http->connectionKeepAlive(); // Currently, this is needed for HTTPS
String url;
if (path[0] != '/')
{
url = "/";
}
url += path + ".json";
url += "?auth=" + FIREBASE_AUTH;
Serial.print("POST:");
Serial.println(url);
Serial.print("Data:");
Serial.println(data);
String contentType = "application/json";
http->put(url, contentType, data);
statusCode = http->responseStatusCode();
Serial.print("Status code: ");
Serial.println(statusCode);
response = http->responseBody();
Serial.print("Response: ");
Serial.println(response);
// if (!http->connected())
// {
// Serial.println();
// http->stop();// Shutdown
// Serial.println("HTTP POST disconnected");
// }
}
void dht_loop()
{
String h = String(random(1,100));
delay(100);
Serial.print("h = ");
Serial.println(h);
String Data = "{";
Data += "\"Sim\":" + h + "";
Data += "}";
PostToFirebase("PATCH", FIREBASE_PATH, Data, &http_client);
}
I am performing ESP32 OTA over the GSM. I have found some example code online, modified it slightly based on my board connections and was able to sucesfully perform a firmware update.
I use lilygo ESP32 GSM development board.
However, it frustrates me that I am not capable of understanding what really happens in the code at the low level. I really want to understand before I go any further with my project.
Full code for my OTA update:
#include <Update.h>
#define TINY_GSM_MODEM_SIM800
// Increase RX buffer
#define TINY_GSM_RX_BUFFER 1030
const char apn[] = "omnitel";
const char user[] = "omni";
const char pass[] = "omni";
#define MODEM_RST 5
#define MODEM_PWRKEY 4
#define MODEM_POWER_ON 23
#define MODEM_TX 27
#define MODEM_RX 26
#define LED_GPIO 13
#define LED_ON HIGH
#define LED_OFF LOW
#define SerialAT Serial1
#include <TinyGsmClient.h>
#include <CRC32.h>
#include "FS.h"
#include "SPIFFS.h"
#ifdef DUMP_AT_COMMANDS
#include <StreamDebugger.h>
StreamDebugger debugger(SerialAT, Serial);
TinyGsm modem(debugger);
#else
TinyGsm modem(SerialAT);
#endif
TinyGsmClient client(modem);
const char server[] = "myesptestserver.ddns.net";
const int port = 80;
const char resource[] = "/esp.bin"; //here de bin file
uint32_t knownCRC32 = 0x6f50d767;
uint32_t knownFileSize = 1024; // In case server does not send it
void setup()
{
SerialAT.begin(115200, SERIAL_8N1, MODEM_RX, MODEM_TX);
// Set console baud rate
Serial.begin(115200);
setupModem();
delay(10);
if (!SPIFFS.begin(true))
{
Serial.println("SPIFFS Mount Failed");
return;
}
SPIFFS.format();
listDir(SPIFFS, "/", 0);
// Set GSM module baud rate
delay(3000);
// Restart takes quite some time
// To skip it, call init() instead of restart()
Serial.println("Initializing modem...");
modem.restart();
String modemInfo = modem.getModemInfo();
Serial.print("Modem: ");
Serial.println(modemInfo);
// Unlock your SIM card with a PIN
//modem.simUnlock("1234");
}
void loop()
{
Serial.print("Waiting for network...");
if (!modem.waitForNetwork())
{
Serial.println(" fail");
delay(10000);
return;
}
Serial.println(" OK");
Serial.print("Connecting to ");
Serial.print(apn);
if (!modem.gprsConnect(apn, user, pass))
{
Serial.println(" fail");
delay(10000);
return;
}
Serial.println(" OK");
Serial.print("Connecting to ");
Serial.print(server);
// if you get a connection, report back via serial:
if (!client.connect(server, port))
{
Serial.println(" fail");
delay(10000);
return;
}
Serial.println(" OK");
// Make a HTTP request:
client.print(String("GET ") + resource + " HTTP/1.0\r\n");
client.print(String("Host: ") + server + "\r\n");
client.print("Connection: close\r\n\r\n");
long timeout = millis();
while (client.available() == 0)
{
if (millis() - timeout > 5000L)
{
Serial.println(">>> Client Timeout !");
client.stop();
delay(10000L);
return;
}
}
Serial.println("Reading header");
uint32_t contentLength = knownFileSize;
File file = SPIFFS.open("/update.bin", FILE_APPEND);
while (client.available())
{
String line = client.readStringUntil('\n');
line.trim();
//Serial.println(line); // Uncomment this to show response header
line.toLowerCase();
if (line.startsWith("content-length:"))
{
contentLength = line.substring(line.lastIndexOf(':') + 1).toInt();
}
else if (line.length() == 0)
{
break;
}
}
timeout = millis();
uint32_t readLength = 0;
CRC32 crc;
unsigned long timeElapsed = millis();
printPercent(readLength, contentLength);
while (readLength < contentLength && client.connected() && millis() - timeout < 10000L)
{
int i = 0;
while (client.available())
{
// read file data to spiffs
if (!file.print(char(client.read())))
{
Serial.println("Appending file");
}
//Serial.print((char)c); // Uncomment this to show data
//crc.update(c);
readLength++;
if (readLength % (contentLength / 13) == 0)
{
printPercent(readLength, contentLength);
}
timeout = millis();
}
}
file.close();
printPercent(readLength, contentLength);
timeElapsed = millis() - timeElapsed;
Serial.println();
client.stop();
Serial.println("stop client");
modem.gprsDisconnect();
Serial.println("gprs disconnect");
Serial.println();
float duration = float(timeElapsed) / 1000;
/*
Serial.print("Tamaño de Archivo: ");
Serial.println(contentLength);
Serial.print("Leido: ");
Serial.println(readLength);
Serial.print("Calculado. CRC32: 0x");
Serial.println(crc.finalize(), HEX);
Serial.print("Conocido CRC32: 0x");
Serial.println(knownCRC32, HEX);
Serial.print("Bajado en: ");
Serial.print(duration);
Serial.println("s");
Serial.println("Se genera una espera de 3 segundos");
for (int i = 0; i < 3; i++)
{
Serial.print(String(i) + "...");
delay(1000);
}
*/
//readFile(SPIFFS, "/update.bin");
updateFromFS();
// Do nothing forevermore
while (true)
{
delay(1000);
}
}
void appendFile(fs::FS &fs, const char *path, const char *message)
{
Serial.printf("Appending to file: %s\n", path);
File file = fs.open(path, FILE_APPEND);
if (!file)
{
Serial.println("Failed to open file for appending");
return;
}
if (file.print(message))
{
Serial.println("APOK");
}
else
{
Serial.println("APX");
}
}
void readFile(fs::FS &fs, const char *path)
{
Serial.printf("Reading file: %s\n", path);
File file = fs.open(path);
if (!file || file.isDirectory())
{
Serial.println("Failed to open file for reading");
return;
}
Serial.print("Read from file: ");
while (file.available())
{
Serial.write(file.read());
delayMicroseconds(100);
}
}
void writeFile(fs::FS &fs, const char *path, const char *message)
{
Serial.printf("Writing file: %s\n", path);
File file = fs.open(path, FILE_WRITE);
if (!file)
{
Serial.println("Failed to open file for writing");
return;
}
if (file.print(message))
{
Serial.println("File written");
}
else
{
Serial.println("Write failed");
}
}
void listDir(fs::FS &fs, const char *dirname, uint8_t levels)
{
Serial.printf("Listing directory: %s\n", dirname);
File root = fs.open(dirname);
if (!root)
{
Serial.println("Failed to open directory");
return;
}
if (!root.isDirectory())
{
Serial.println("Not a directory");
return;
}
File file = root.openNextFile();
while (file)
{
if (file.isDirectory())
{
Serial.print(" DIR : ");
Serial.println(file.name());
if (levels)
{
listDir(fs, file.name(), levels - 1);
}
}
else
{
Serial.print(" FILE: ");
Serial.print(file.name());
Serial.print(" SIZE: ");
Serial.println(file.size());
}
file = root.openNextFile();
}
}
void deleteFile(fs::FS &fs, const char *path)
{
Serial.printf("Deleting file: %s\n", path);
if (fs.remove(path))
{
Serial.println("File deleted");
}
else
{
Serial.println("Delete failed");
}
}
void updateFromFS()
{
File updateBin = SPIFFS.open("/update.bin");
if (updateBin)
{
if (updateBin.isDirectory())
{
Serial.println("Directory error");
updateBin.close();
return;
}
size_t updateSize = updateBin.size();
if (updateSize > 0)
{
Serial.println("Starting update");
performUpdate(updateBin, updateSize);
}
else
{
Serial.println("Error, archivo vacío");
}
updateBin.close();
// whe finished remove the binary from sd card to indicate end of the process
//fs.remove("/update.bin");
}
else
{
Serial.println("no such binary");
}
}
void performUpdate(Stream &updateSource, size_t updateSize)
{
if (Update.begin(updateSize))
{
size_t written = Update.writeStream(updateSource);
if (written == updateSize)
{
Serial.println("Writes : " + String(written) + " successfully");
}
else
{
Serial.println("Written only : " + String(written) + "/" + String(updateSize) + ". Retry?");
}
if (Update.end())
{
Serial.println("OTA finished!");
if (Update.isFinished())
{
Serial.println("Restart ESP device!");
ESP.restart();
}
else
{
Serial.println("OTA not fiished");
}
}
else
{
Serial.println("Error occured #: " + String(Update.getError()));
}
}
else
{
Serial.println("Cannot beggin update");
}
}
void printPercent(uint32_t readLength, uint32_t contentLength)
{
// If we know the total length
if (contentLength != -1)
{
Serial.print("\r ");
Serial.print((100.0 * readLength) / contentLength);
Serial.print('%');
}
else
{
Serial.println(readLength);
}
}
void setupModem()
{
#ifdef MODEM_RST
// Keep reset high
pinMode(MODEM_RST, OUTPUT);
digitalWrite(MODEM_RST, HIGH);
#endif
pinMode(MODEM_PWRKEY, OUTPUT);
pinMode(MODEM_POWER_ON, OUTPUT);
// Turn on the Modem power first
digitalWrite(MODEM_POWER_ON, HIGH);
// Pull down PWRKEY for more than 1 second according to manual requirements
digitalWrite(MODEM_PWRKEY, HIGH);
delay(100);
digitalWrite(MODEM_PWRKEY, LOW);
delay(1000);
digitalWrite(MODEM_PWRKEY, HIGH);
// Initialize the indicator as an output
pinMode(LED_GPIO, OUTPUT);
digitalWrite(LED_GPIO, LED_OFF);
}
From what I understand, the following part of the code reads my binary file that is stored in the server and read it into SPIFFS memory:
while (readLength < contentLength && client.connected() && millis() - timeout < 10000L)
{
int i = 0;
while (client.available())
{
// read file data to spiffs
if (!file.print(char(client.read())))
{
Serial.println("Appending file");
}
//Serial.print((char)c); // Uncomment this to show data
//crc.update(c);
readLength++;
if (readLength % (contentLength / 13) == 0)
{
printPercent(readLength, contentLength);
}
timeout = millis();
}
}
Then the updateFromFS() function is executed, which checks whether the binary is all good and then calls another function performUpdate(updateBin, updateSize);
void updateFromFS()
{
File updateBin = SPIFFS.open("/update.bin");
if (updateBin)
{
if (updateBin.isDirectory())
{
Serial.println("Directory error");
updateBin.close();
return;
}
size_t updateSize = updateBin.size();
if (updateSize > 0)
{
Serial.println("Starting update");
performUpdate(updateBin, updateSize);
}
else
{
Serial.println("Error, archivo vacío");
}
updateBin.close();
// whe finished remove the binary from sd card to indicate end of the process
//fs.remove("/update.bin");
}
else
{
Serial.println("no such binary");
}
}
in the performUpdate(updateBin, updateSize), 2 functions from Arduino Update Library are being called ( Update.begin(updateSize) and Update.writeStream(updateSource) ) and that is where I cant follow anymore...
void performUpdate(Stream &updateSource, size_t updateSize)
{
if (Update.begin(updateSize))
{
size_t written = Update.writeStream(updateSource);
if (written == updateSize)
{
Serial.println("Writes : " + String(written) + " successfully");
}
else
{
Serial.println("Written only : " + String(written) + "/" + String(updateSize) + ". Retry?");
}
if (Update.end())
{
Serial.println("OTA finished!");
if (Update.isFinished())
{
Serial.println("Restart ESP device!");
ESP.restart();
}
else
{
Serial.println("OTA not fiished");
}
}
else
{
Serial.println("Error occured #: " + String(Update.getError()));
}
}
else
{
Serial.println("Cannot beggin update");
}
}
I have found this Update library source code :
https://github.com/espressif/arduino-esp32/blob/master/libraries/Update/src/Updater.cpp
But it seems that this is beyond my knowledge to understand what really is going on in this code.
First of all, we pass only 1 variable to .begin method, but the function prototype requires more than that:
bool UpdateClass::begin(size_t size, int command, int ledPin, uint8_t ledOn, const char *label)
And then I am trying to understand what happens in function Update.writeStream(updateSource) but cant..
If anyone could shed some light here I would appreciate a lot! Thanks in advance...
The algorithm downloads the new firmware (.bin) from the cloud to the device's local memory and makes the firmware change with the UpdateClass library
(I see the texts in Spanish if you want we speak in Spanish)
Check the .h (only one argument required)
https://github.com/espressif/arduino-esp32/blob/master/libraries/Update/src/Update.h
/*
Call this to check the space needed for the update
Will return false if there is not enough space
*/
bool begin(size_t size=UPDATE_SIZE_UNKNOWN, int command = U_FLASH, int ledPin = -1, uint8_t ledOn = LOW, const char *label = NULL);
You could use the OTAdrive library and use it for OTA updates.
Check here for the esp32 gsm modem OTA example.
I am trying to use this code:
https://github.com/jatocode/WifiConnect/blob/master/WifiConnect/WifiConnect.ino with my ESP32.
The problem is that my wifi network name is "y&t" and when I am trying to use it the progrem saves to the EEPROM "y&26t" insted, with other networks names in my area it dosn't have a problem.
I will be greatful if somebady knows how to solve this problem.
Thanks to #Juraj I solved the problem.
I used in this code a decoder from here: https://circuits4you.com/2019/03/21/esp8266-url-encode-decode-example/
/*
Configuration AP example
The example shows a very simple Configuration Access Point.
created in August 2019
by Juraj Andrassy https://github.com/jandrassy
*/
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
#include <Arduino.h>
// #include <String.h>
String urldecode(String str);
unsigned char h2int(char c);
void setup() {
Serial.begin(115200);
delay(500);
// WiFi.disconnect(); // forget the persistent connection to test the Configuration AP
WiFi.persistent(true);
// waiting for connection to remembered Wifi network
Serial.println("Waiting for connection to WiFi");
WiFi.begin(); // use SSID and password stored by SDK
WiFi.waitForConnectResult();
if (WiFi.status() != WL_CONNECTED) {
Serial.println();
Serial.println("Could not connect to WiFi. Starting configuration AP...");
configAP();
} else {
Serial.println("WiFi connected");
}
}
void loop() {
}
void configAP() {
WiFiServer configWebServer(80);
WiFi.mode(WIFI_AP_STA); // starts the default AP (factory default or setup as persistent)
Serial.print("Connect your computer to the WiFi network ");
// Serial.print(WiFi.softAP());
Serial.println();
IPAddress ip = WiFi.softAPIP();
Serial.print("and enter http://");
Serial.print(ip);
Serial.println(" in a Web browser");
configWebServer.begin();
while (true) {
WiFiClient client = configWebServer.available();
if (client) {
char line[64];
int l = client.readBytesUntil('\n', line, sizeof(line));
line[l] = 0;
client.find((char*) "\r\n\r\n");
if (strncmp_P(line, PSTR("POST"), strlen("POST")) == 0) {
l = client.readBytes(line, sizeof(line));
line[l] = 0;
// parse the parameters sent by the html form
const char* delims = "=&";
strtok(line, delims);
const char* ssid = strtok(NULL, delims);
strtok(NULL, delims);
const char* pass = strtok(NULL, delims);
// decoding the ssid and the password for ASCII characters
String ssidS = String(ssid);
String ssidSdecode= urldecode(ssidS);
ssid=const_cast<char*>(ssidSdecode.c_str());
String passS = String(pass);
String passSdecode= urldecode(passS);
pass=const_cast<char*>(passSdecode.c_str());
// send a response before attemting to connect to the WiFi network
// because it will reset the SoftAP and disconnect the client station
client.println(F("HTTP/1.1 200 OK"));
client.println(F("Connection: close"));
client.println(F("Refresh: 10")); // send a request after 10 seconds
client.println();
client.println(F("<html><body><h3>Configuration AP</h3><br>connecting...</body></html>"));
client.stop();
Serial.println();
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
WiFi.waitForConnectResult();
// configuration continues with the next request
} else {
client.println(F("HTTP/1.1 200 OK"));
client.println(F("Connection: close"));
client.println();
client.println(F("<html><body><h3>Configuration AP</h3><br>"));
int status = WiFi.status();
if (status == WL_CONNECTED) {
client.println(F("Connection successful. Ending AP."));
} else {
client.println(F("<form action='/' method='POST'>WiFi connection failed. Enter valid parameters, please.<br><br>"));
client.println(F("SSID:<br><input type='text' name='i'><br>"));
client.println(F("Password:<br><input type='password' name='p'><br><br>"));
client.println(F("<input type='submit' value='Submit'></form>"));
}
client.println(F("</body></html>"));
client.stop();
if (status == WL_CONNECTED) {
delay(1000); // to let the SDK finish the communication
Serial.println("Connection successful. Ending AP.");
configWebServer.stop();
WiFi.mode(WIFI_STA);
}
}
}
}
}
String urldecode(String str) {
String encodedString="";
char c;
char code0;
char code1;
for (int i =0; i < str.length(); i++) {
c=str.charAt(i);
if (c == '+') {
encodedString+=' ';
} else if (c == '%') {
i++;
code0=str.charAt(i);
i++;
code1=str.charAt(i);
c = (h2int(code0) << 4) | h2int(code1);
encodedString+=c;
} else {
encodedString+=c;
}
yield();
}
return encodedString;
}
unsigned char h2int(char c) {
if (c >= '0' && c <='9') {
return((unsigned char)c - '0');
}
if (c >= 'a' && c <='f') {
return((unsigned char)c - 'a' + 10);
}
if (c >= 'A' && c <='F') {
return((unsigned char)c - 'A' + 10);
}
return(0);
}
The error I'm facing is about using talkback function of thingspeak to control my Arduino LED. it cannot execute the talkback command to off the led. The error is in my void get talkback. Please help me
#include "ThingSpeak.h"
#include <Ethernet.h>
#define redLED 8
byte mac[] = {0x90, 0xA2, 0xDA, 0x10, 0x40, 0x4F};
const String channelsAPIKey = "";
const String talkBackAPIKey = "";
const String talkBackID = "";
const String talkCommandID = "";
const unsigned int getTalkBackInterval = 10 * 1000;
const unsigned int updateChannelsInterval = 15 * 1000;
String talkBackCommand;
long lastConnectionTimeChannels = 0;
boolean lastConnectedChannels = false;
int failedCounterChannels = 0;
long lastConnectionTimeTalkBack = 0;
boolean lastConnectedTalkBack = false;
int failedCounterTalkBack = 0;
char charIn;
// Arduino Ethernet Client is initialized
EthernetClient client;
void setup()
{
Ethernet.init(10); // Most Arduino Ethernet hardware
Serial.begin(9600); //Initialize serial
// start the Ethernet connection:
pinMode(redLED, OUTPUT);
digitalWrite(redLED, HIGH);
}
void loop()
{
getTalkBack();
}
void getTalkBack()
{
String tsData;
tsData = talkBackID + "/commands/execute?api_key=" + talkBackAPIKey;
if ((!client.connected() && (millis() - lastConnectionTimeTalkBack > getTalkBackInterval)))
{
if (client.connect("api.thingspeak.com", 80))
{
client.println("GET /talkbacks/" + tsData + " HTTP/1.0");
client.println();
lastConnectionTimeTalkBack = millis();
if (client.connected())
{
Serial.println("---------------------------------------");
Serial.println("GET TalkBack command");
Serial.println();
Serial.println("Connecting to ThingSpeak");
Serial.println();
Serial.println();
Serial.println("Server response");
Serial.println();
failedCounterTalkBack = 0;
while (client.connected() && !client.available()) delay(2000); //waits for data
while (client.connected() || client.available())
{
charIn = client.read();
talkBackCommand += charIn;
Serial.print(charIn);
if (talkBackCommand == "LED_ON")
{
digitalWrite(redLED, HIGH);
}
if (talkBackCommand == "LED_OFF")
{
digitalWrite(redLED, LOW);
}
}
if (talkBackCommand = talkBackCommand.substring(talkBackCommand.indexOf("_CMD_") + 5));
{
Serial.println();
Serial.println();
Serial.println("Disconnected");
Serial.println();
Serial.println("--------");
Serial.println();
Serial.println("talkback command was");
Serial.println();
Serial.println("--------");
Serial.println();
Serial.println(talkBackCommand);
Serial.println("--------");
Serial.println();
}
}
else
{
failedCounterTalkBack++;
Serial.println("Connection to ThingSpeak failed (" + String(failedCounterTalkBack, DEC) + ")");
Serial.println();
lastConnectionTimeChannels = millis();
}
}
}
if (failedCounterTalkBack > 3 )
{
startEthernet();
}
client.stop();
Serial.flush();
}
The below is a image from my serial monitor. It shows that I can capture the command but couldn't execute it.
Looks like you are reading and appending all the received bytes to talkBackCommand. So, talkBackCommand is "HTTP/1.1 200 OK Date...." and if (talkBackCommand == "LED_ON") would never be true.
I think you wanted to see if the received data contain your commands LED_ON or LED_OFF. You can do something like this:
if (talkBackCommand.indexOf("LED_ON") != -1)
indexOf() locates a String in a String and returns index or -1 if not found.
See more info about indexOf() here: https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/indexof/
I have an arduino uno board with Ethernet shield. I use it to controlling lights with my relay. This is my code
#include <SPI.h>
#include <Ethernet.h>
#include <Time.h>
#include <Wire.h>
#include <DS1307RTC.h> // a basic DS1307 library that returns time as a time_t
// Enter a MAC address and IP address for your controller below.
byte mac[] = {0x90, 0xA2, 0xDA, 0x0D, 0x48, 0xD3 };
int lamp[] = {4, 7, 8, 9}; //pin buat relay
int lampAutoOnH[4];
int lampAutoOnM[4];
int lampAutoOffH[4];
int lampAutoOffM[4];
int j;
boolean lampAuto[4];
// The IP address will be dependent on your local network:
// assign an IP address for the controller:
byte ip[] = {192,168,0,20};
byte gateway[] = {192,168,0,1};
byte subnet[] = {255, 255, 255, 0};
// Initialize the Ethernet server library with the port you want to use.
EthernetServer server(80);
String readString;
// Declare Pin 8 as an LED because thats what we will be connecting the LED to.You could use any other pin and would then have to change the pin number.
void setup()
{
for(int i=0; i<4; i++){
pinMode(lamp[i], OUTPUT);
digitalWrite(lamp[i], LOW);
lampAuto[i] = false;
}
//trial with led, plug in to D1
//enable serial data print
Serial.begin(9600);
//start Ethernet
Ethernet.begin(mac, ip, gateway, subnet);
//Ethernet.begin(mac); //for DHCP
server.begin();
Serial.print("Server is at ");
Serial.println(Ethernet.localIP());
setSyncProvider(RTC.get); // the function to get the time from the RTC
if(timeStatus()!= timeSet)
Serial.println("Unable to sync with the RTC");
else{
Serial.println("RTC has set the system time");
printTime();
}
}
void loop()
{
// listen for incoming clients
EthernetClient client = server.available();
if (client){
while (client.connected()){
if (client.available()){
char c = client.read();
//read char by char HTTP request
if (readString.length() < 100){
//store characters to string
readString += c;
//Serial.print(c);
}
//Serial.write(c);
if (c == '\n') {
Serial.println(readString); //print to serial monitor for debuging
// Needed to Display Site:
client.println("HTTP/1.1 200 OK"); //send new page
client.println("Content-Type: text/html");
client.println();
client.println("<HTML>");
client.println("<HEAD>");
// what is being Displayed :
client.println("<TITLE>Home Automation</TITLE>");
client.println("<center>");
client.println("</HEAD>");
client.println("<BODY>");
client.println("<H1>Home Automation</H1>");
client.println("<hr />");
client.println("<center>");
client.println("Turn On Light1 ");
client.println(" Turn Off Light1<br /><br />");
client.println("Turn On Light2 ");
client.println(" Turn Off Light2<br /><br />");
client.println("Turn On Light3 ");
client.println(" Turn Off Light3<br /><br />");
client.println("Turn On Light4 ");
client.println(" Turn Off Light4<br /><br />");
client.println("Rekam IR<br /><br />");
client.println("Jika ingin mencoba auto, ketikkan : <br/><br/><b>");
client.println("http://192.168.1.20/?lightauto[angka][HHOn][MMOn][HHOff][MMOff]");
client.println("<b/></BODY>");
client.println("</HTML>");
delay(1);
cekLink();
printTime();
//stopping client
client.stop();
//clearing string for next read
readString="";
}
}
}
}
cekAuto();
}
void cekLink(){
// Code which needs to be Implemented:
if(readString.indexOf("?lighton") >0)//checks for on
{
String i = readString.substring(13, 14);
j = i.toInt()-1;
Serial.print("Lamp number '");
Serial.print(j+1);
Serial.print("' is on\nreadString = " + readString);
Serial.print(readString);
digitalWrite(lamp[j], HIGH);
lampAuto[j] = false;
}
else if(readString.indexOf("?lightoff") >0)//checks for off
{
String i = readString.substring(14, 15);
j = i.toInt()-1;
Serial.print("Lamp number '");
Serial.print(j+1);
Serial.print("' is off\nreadString = " + readString);
digitalWrite(lamp[j], LOW);
lampAuto[j] = false;
}else if(readString.indexOf("?lightauto") >0)//checks for on
{
//GET /?lightauto119171918
//0123456789012345678
String ll = readString.substring(15, 16);
String hhOn = readString.substring(16, 18);
String mmOn = readString.substring(18, 20);
String hhOff = readString.substring(20, 22);
String mmOff = readString.substring(22, 24);
j = ll.toInt()-1;
lampAuto[j] = true;
lampAutoOnH[j] = hhOn.toInt();
lampAutoOnM[j] = mmOn.toInt();
lampAutoOffH[j] = hhOff.toInt();
lampAutoOffM[j] = mmOff.toInt();
Serial.print("Lamp number '");
Serial.print(j+1);
Serial.print("' is auto. \n");
Serial.println("On at " + hhOn + ":" + mmOn);
Serial.println("Off at " + hhOff + ":" + mmOff);
Serial.print("readString = " + readString);
if(hour()>=lampAutoOnH[j])
digitalWrite(lamp[j], HIGH);
else if(hour()<=lampAutoOffH[j]&&minute()<=lampAutoOffM[j])
digitalWrite(lamp[j], HIGH);
else
digitalWrite(lamp[j], LOW);
}else if(readString.indexOf("?rekamIR") >0){
Serial.println("Rekam IR");
}
}
void printTime() {
Serial.print(hour());
printDigits(minute());
printDigits(second());
Serial.print(" ");
Serial.print(day());
Serial.print(" ");
Serial.print(month());
Serial.print(" ");
Serial.print(year());
Serial.println();
}
void printDigits(int digits){
//konversi waktu normal
Serial.print(":");
if(digits < 10)
Serial.print('0');
Serial.print(digits);
}
void cekAuto(){
for(int i=0; i<4; i++){
if(lampAuto[j]==true){
if(lampAutoOnH[i]==hour()&&lampAutoOnM[i]==minute())
digitalWrite(lamp[j], HIGH);
else if(lampAutoOffH[i]==hour()&&lampAutoOffM[i]==minute())
digitalWrite(lamp[j], LOW);
}
}
}
But when i add IRremote library to receive IR frequency,
#include <IRremote.h>
it doesn't work anymore. Can anyone help?