Esp01 Wifi Hotspot + web server not working - arduino

I am trying to make a simple esp01 wifi hotspot + a simple webpage with 3 buttons that send ints(1,2,3) over serial when pressed. But the wifi hotspot isn't working.
Here is the code:
#include <ESP8266WiFi>;
#include <WiFiClient>;
#include <ESP8266WebServer>;
const char *ssid = "test";
const char *password = "password";
IPAddress local_IP(192,168,4,22);
IPAddress gateway(192,168,4,9);
IPAddress subnet(255,255,255,0);
WiFiServer server(80);
void setup() {
delay(1000);
Serial.begin(9600);
WiFi.softAPConfig(local_IP, gateway, subnet);
WiFi.softAP(ssid, password);
server.begin();
}
void loop() {
WiFiClient client = server.available();
if (!client)
{
return;
}
while(!client.available())
{
delay(1);
}
String request = client.readStringUntil('\r');
client.flush();
if (request.indexOf("/R1") != -1)
{
Serial.println("1");
}else if (request.indexOf("/R2") != -1)
{
Serial.println("2");
}else if (request.indexOf("/R3") != -1)
{
Serial.println("3");
}
client.println("Content-Type: text/html");
client.println("");
client.println("<!DOCTYPE html>");
client.println("<html>");
client.println("<head><title>ESP01 RELAY Control</title></head>");
client.println("<body>");
client.println("<br>");
client.println("<button href=\"/R1\">R:1</button>");
client.println("<button href=\"/R2\">R:2</button>");
client.println("<button href=\"/R3\">R:3</button>");
client.println("<br>");
client.println("<button href=\"/T1\">T:1</button>");
client.println("<button href=\"/T2\">T:2</button>");
client.println("<button href=\"/T3\">T:3</button>");
client.println("</body>");
client.println("</html>");
delay(1);
}

To program an ESP8622 it is best practice to use the Serial.println() command to debug your code. For setting up a working access point (AP) on a ESP8622 module, use the following code;
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
const char *ssid = "test";
const char *password = "password";
IPAddress local_IP(192,168,4,22);
IPAddress gateway(192,168,4,9);
IPAddress subnet(255,255,255,0);
WiFiServer server(80);
void setup() {
delay(1000);
Serial.begin(9600);
Serial.print("Setting soft-AP configuration ... ");
Serial.println(WiFi.softAPConfig(local_IP, gateway, subnet) ? "Ready" : "Failed!");
Serial.print("Setting soft-AP ... ");
Serial.println(WiFi.softAP(ssid, password) ? "Ready" : "Failed!");
Serial.print("Soft-AP IP address = ");
Serial.println(WiFi.softAPIP());
server.begin();
}
void loop() {
WiFiClient client = server.available();
if(client){
while (client.connected()) {
if(client.available()){
Serial.println("Connected to client");
}
}
// close the connection:
client.stop();
}
}

Related

Sending request to ChatGPT from ESP8266

I'm trying to send JSON messages to https://api.openai.com/v1/completions using ESP8266. The problem is why when the program is run it always results in bad requests?
This is my code:
#include <WiFiClientSecure.h>
#include <ESP8266HTTPClient.h>
//#include <HttpClient.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ArduinoJson.h> // library untuk menangani JSON
const char* ssid = "DIVA MEDIA";
const char* password = "media1213";
const char* host = "api.openai.com";
const int httpsPort = 443;
WiFiClient client;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
if (!client.connect(host, httpsPort)) {
Serial.println("Connection failed");
return;
}
HTTPClient http;
WiFiClient client;
// JSON data yang akan dikirim
String jsonData = "{\"prompt\":\"What is the capital of France?\",\"model\":\"text-davinci-002\"}";
// Kirim permintaan ke API OpenAI
http.begin(client,"https://api.openai.com/v1/completions");
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", "Bearer api");
int httpCode = http.POST(jsonData);
// Cek kode respon
if (httpCode > 0) {
String response = http.getString();
Serial.println(response);
} else {
Serial.println("Error: " + http.errorToString(httpCode));
}
http.end();
// Delay sebelum mengirim permintaan berikutnya
delay(5000);
}
void loop() {
// nothing to do here
}
and this is error:

NodeMCU ESP8266 Client-Server communication

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.

Measure ESP32 CPU Utilization

I am communicating two ESP32 boards which are connected to a Wifi Network. One ESP32 board is the Server and the other is the client. I want to measure the ESP32 CPU utlization on the client ESP32. I have no idea how to do it and have not yet found any useful resources on the internet. Can someone help me with this?
This is the code on server
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
const char* ssid = "XXXXX";
const char* password = "XXXX";
AsyncWebServer server(80);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid,password);
while (WiFi.status()!= WL_CONNECTED){
delay(200);
Serial.println("Connecting to Wifi...");
}
Serial.println("Connected to Wifi");
Serial.println(WiFi.localIP());
server.on("/test", HTTP_GET, [](AsyncWebServerRequest *request){
Serial.println("Request received from esp32client");
request->send(200, "text/plain", "Hello from ESP32Server to ESP32Client");
});
server.on("/test1", HTTP_GET, [](AsyncWebServerRequest *request){
Serial.println("Request received from PC-Client");
request->send(300, "text/plain", "Hello from ESP32Server to PC");
});
server.begin();
}
void loop() {
// put your main code here, to run repeatedly:
}
This is the code on Client
#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "XXXXX";
const char* password ="XXXXX";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid,password);
while (WiFi.status()!= WL_CONNECTED){
delay(500);
Serial.println("Connecting to Wifi...");
}
Serial.println("Connected to Wifi Network...");
Serial.println(WiFi.localIP());
}
void loop() {
HTTPClient http;
http.begin("http://192.168.43.35/test");
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
Serial.println(httpCode);
Serial.println(payload);
}
else {
Serial.println("Error on HTTP request");
}
http.end();
delay(30000);
}
Use this function to get CPU load
vTaskGetRunTimeStats(char *buffer);
It tells CPU utilization by currently running task on esp32.
API documentation here.

ESP8266 Using wifimanager with onSoftAPModeProbeRequestReceived

I would like to use https://github.com/tzapu/WiFiManager in conjunction with onSoftAPModeProbeRequestReceived. The end goal is to config the wifi with WifiMaager then "switch over" and send probe request information via the wifi.
I get this to work without wifi manager using the following
#include <ESP8266httpUpdate.h>
#include <ESP8266WiFi.h>
#include <esp8266httpclient.h>
#include <stdio.h>
const char* ssid = "someap"; // The SSID (name) of the Wi-Fi
network you want to connect to
const char* password = ""; // The password of the Wi-Fi network
int status = WL_IDLE_STATUS;
String macAddr = "";
WiFiEventHandler probeRequestPrintHandler;
WiFiEventHandler probeRequestBlinkHandler;
bool blinkFlag;
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
Serial.print("Starting");
WiFi.persistent(false);
WiFi.mode(WIFI_AP);
WiFi.softAP(ssid, password);
probeRequestPrintHandler =
WiFi.onSoftAPModeProbeRequestReceived(&onProbeRequestPrint);
probeRequestBlinkHandler =
WiFi.onSoftAPModeProbeRequestReceived(&onProbeRequestBlink);
while ( status != 3)
{
Serial.print("Attempting to connect to network, SSID: ");
Serial.println(ssid);
status = WiFi.status();
WiFi.begin(ssid, password);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println(WiFi.localIP());
}
void onProbeRequestPrint(const WiFiEventSoftAPModeProbeRequestReceived& evt)
{
if (macAddr != macToString(evt.mac))
{
macAddr = macToString(evt.mac);
Serial.print("Probe request from: ");
Serial.print(macToString(evt.mac));
Serial.print(" RSSI: ");
Serial.println(evt.rssi);
}
}
void onProbeRequestBlink(const WiFiEventSoftAPModeProbeRequestReceived&) {
blinkFlag = true;
}
void loop() {
if (blinkFlag) {
HTTPClient http; //Declare an object of class HTTPClient
http.begin("http://requestbin.fullcontact.com/110f1ss6a1?test=true");
//Specify request destination
int httpCode = http.GET();
Serial.println(httpCode);
if (httpCode > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
Serial.println(payload); //Print the response payload
}
http.end(); //Close connection
macAddr="";
blinkFlag = false;
digitalWrite(LED_BUILTIN, LOW);
delay(100);
digitalWrite(LED_BUILTIN, HIGH);
status = 0;
}
delay(1000);
}
String macToString(const unsigned char* mac) {
char buf[20];
snprintf(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return String(buf);
}
When the connection is established we rely on WiFiEventHandler probeRequestPrintHandler; and WiFiEventHandler probeRequestBlinkHandler; This does work and does collect the mac address, how ever it can not connect to the AP. Do I need to close the current wifi mode open the connection then close it?
Seems all I needed to do is add WiFi.begin(); before void loop()

Hold button more than 5 seconds, do something. Arduino

I have a hobby project that sends a string "1" or a string "0" to my webserver. My arduino work as a client, and It works, but now I want to add another statement.
If the button is held down 5 sec or longer, send string "5" to my webserver. I do not know how I can get the button to count the seconds I have hold the button. Can you please help?
Here is the code:
#include <SPI.h>
#include <WiFi.h>
byte mac[] = { 0xDE, 0xFD, 0xBE, 0xEF, 0xFE, 0xED }; // MAC adresse
char ssid[] = "test";
char pass[] = "123456789";
IPAddress ip(192, 168, 0, 143); // Klient IP
IPAddress server(192,168,0,100); // Server IP
int port = 2056;
boolean btnpressed = false;
int status = WL_IDLE_STATUS;
WiFiClient client;
unsigned long lastConnectionTime = 0;
boolean lastConnected = false;
const unsigned long postingInterval = 1000;
void setup() {
attachInterrupt(0, AlarmPressed, RISING);
// Opne serial port
Serial.begin(9600);
while (!Serial) {
;
}
while ( status != WL_CONNECTED) {
Serial.print(" SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
delay(1000); //
printWifiStatus();
Serial.println("Connecting to server");
}
}
void loop() {
if (client.available()) {
char c = client.read();
Serial.print(c);
client.stop();
}
if (!client.connected() && lastConnected) {
Serial.println("Disconnecting.");
Serial.println();
client.stop();
}
if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
SendData();
}
lastConnected = client.connected();
} // Slutten paa loop
void AlarmPressed() {
btnpressed = true;
}
void SendData() {
// if there's a successful connection:
if (client.connect(server, port)) {
Serial.println("Connecting...");
// Send data til server:
if (btnpressed == false){
client.write("0");
Serial.print("No Alarm");
Serial.println();
btnpressed = false;
}
else {
client.write("1");
Serial.print("Alarm !");
Serial.println();
}
// note the time that the connection was made:
lastConnectionTime = millis();
}
else {
// if you couldn't make a connection:
Serial.println("Connection failed");
Serial.println("Disconnecting.");
Serial.println();
client.stop();
}
}
void printWifiStatus() {
Serial.print(" SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("Signalstyrke til forbindelsen (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}

Resources