led light is not responding over wifi from esp8266 - c++

Im trying to switch on and off led from from a local server created by esp8266.
Everything is working fine even esp also. Setup is working without ESP8266.
ESP is flashed with ESP8266_NONOS_SDK-2.2.0
Board used "Generic ESP8266 Module"
at COM Port 6
Arduino to bread board setup:-
pin 13 -> led
GND -> led
Arduino to ESP setup before burning sketch:-
Arduino - ESP8266
3.3v -> vcc + CH_PD
GND+RST -> GND + GPIO0
TXD -> TX
RXD -> RX
Arduino to ESP setup before burning sketch:-
Arduino - ESP8266
3.3v -> vcc + CH_PD
GND -> GND
TXD -> TX
RXD -> RX
COM output:
Connecting to lan
.......
WiFi connected
Server started
Use this URL to connect: http://192.168.43.80/
I already tried:-
using different pinsand also tried switching
RXD->TX and TXD->RX
the problem what i think im getting is the communication between ESP and arduino. Although blue led in ESP flashes when i click on ON or OFF and im getting response in SERIAL MONITOR also:-
COM OUTPUT:-
new client
GET /LED=OFF HTTP/1.1
Client disonnected
new client
GET /favicon.ico HTTP/1.1
Client disonnected
new client
GET /LED=ON HTTP/1.1
Client disonnected
new client
GET /favicon.ico HTTP/1.1
Client disonnected
Code I'm using:-
#include <ESP8266WiFi.h>
const char* ssid = "papa";
const char* password = "12345678ab";
int ledPin = 12; // GPIO13
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
// Connect to WiFi network
Serial.println();
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");
digitalWrite(ledPin, HIGH);
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
}
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}
// Read the first line of the request
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();
// Match the request
int value = LOW;
if (request.indexOf("/LED=ON") != -1) {
digitalWrite(ledPin, HIGH);
value = HIGH;
}
if (request.indexOf("/LED=OFF") != -1) {
digitalWrite(ledPin, LOW);
value = LOW;
}
// Set ledPin according to the request
//digitalWrite(ledPin, value);
// Return the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // do not forget this one
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.print("Led pin is now: ");
if(value == HIGH) {
client.print("On");
} else {
client.print("Off");
}
client.println("<br><br>");
client.println("<button>Turn On </button>");
client.println("<button>Turn Off </button><br />");
client.println("</html>");
delay(1);
Serial.println("Client disonnected");
Serial.println("");
}

Related

ESP8266 NodeMCU WiFiClient client errors

I want to send data from DHT11 to URL using an ESP8266 NodeMCU. I use the board "NodeMCU 1.0 (ESP-12E Module)".
My code is as follows:
#include <dht.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <SPI.h>
#include <MFRC522.h>
dht DHT;
#define DHTPIN 2
float humidityData;
float temperatureData;
const char* ssid = "My_SSID";
const char* password = "Wifi_Password";
//WiFiClient client;
char server[] = "192.168.1.1";
WiFiClient client;
void setup()
{
Serial.begin(115200);
delay(10);
// Connect to WiFi network
Serial.println();
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");
// Start the server
// server.begin();
Serial.println("Server started");
Serial.print(WiFi.localIP());
delay(1000);
Serial.println("connecting...");
}
void loop()
{
int chk = DHT.read11(DHTPIN);
humidityData = DHT.temperature;
temperatureData = DHT.humidity;
Sending_To_phpmyadmindatabase();
delay(30000); // interval
}
void Sending_To_phpmyadmindatabase() //CONNECTING WITH MYSQL
{
if (client.connect(server, 80)) {
Serial.println("connected");
// Make a HTTP request:
Serial.print("GET localhost/project_folder/dht.php?humidity=");
client.print("GET localhost/project_folder/dht.php?humidity=");
Serial.println(humidityData);
client.print(humidityData);
client.print("&temperature=");
Serial.println("&temperature=");
client.print(temperatureData);
Serial.println(temperatureData);
client.print(" "); //SPACE BEFORE HTTP/1.1
client.print("HTTP/1.1");
client.println();
client.println("Host: Your Local IP");
client.println("Connection: close");
client.println();
} else {
// if connection to the server failed:
Serial.println("connection to the server failed");
}
}
When it works correctly (1/3 of the running time), i get this serial message:
Connecting to Omni_777318
...........
WiFi connected
Server started
192.168.39.178connecting...
connected
GET localhost/michael/dht11.php?humidity=26.00
&temperature=
40.00
BUT! 2/3 of the time, i get a weird error that i dont understand:
tail 4
chksum 0xc9
csum 0xc9
v00044840
~ld
Connecting to Omni_777318
.....
ets Jan 8 2013,rst cause:4, boot mode:(3,7)
wdt reset
load 0x4010f000, len 3460, room 16
tail 4
chksum 0xcc
load 0x3fff20b8, len 40, room 4
tail 4
chksum 0xc9
csum 0xc9
v00044840
~ld
Anyone here who can help me solve this issue?
Cause 4 is a hardware watchdog reset, and in that case I suspect a power problem.
During the connection phases we observe current peak, and if the power supply is too weak ESP Reboot, as voltage falls under limit. In this case you must either change the power source, or put a capacitor of a few hundred microfarads on the supply terminals, as close as possible to ESP.

Compilation error: call to 'HTTPClient::begin' declared with attribute error: obsolete API, use ::begin(WiFiClient, url), How can i solve this issue?

I run this code and get the massage:
Compilation error: call to 'HTTPClient::begin' declared with attribute error: obsolete API, use ::begin(WiFiClient, url)
what can I do?
//----------------------------------------Include the NodeMCU ESP8266 Library
//----------------------------------------see here: https://www.youtube.com/watch?v=8jMr94B8iN0 to add NodeMCU ESP8266 library and board
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>
//----------------------------------------
#define ON_Board_LED 2 //--> Defining an On Board LED (GPIO2 = D4), used for indicators when the process of connecting to a wifi router
#define LED_D8 15 //--> Defines an LED Pin. D8 = GPIO15
//---------------------------------------SSID and Password of your WiFi router.
const char* ssid = "*wifi name*"; //--> Your wifi name or SSID.
const char* password = "*Wfif password*"; //--> Your wifi password.
//----------------------------------------
//----------------------------------------Web Server address / IPv4
// If using IPv4, press Windows key + R then type cmd, then type ipconfig (If using Windows OS).
const char *host = "https://localhost/";
//----------------------------------------
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
delay(500);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password); //--> Connect to your WiFi router
Serial.println("");
pinMode(ON_Board_LED,OUTPUT); //--> On Board LED port Direction output
digitalWrite(ON_Board_LED, HIGH); //--> Turn off Led On Board
pinMode(LED_D8,OUTPUT); //--> LED port Direction output
digitalWrite(LED_D8, LOW); //--> Turn off Led
//----------------------------------------Wait for connection
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
//----------------------------------------Make the On Board Flashing LED on the process of connecting to the wifi router.
digitalWrite(ON_Board_LED, LOW);
delay(250);
digitalWrite(ON_Board_LED, HIGH);
delay(250);
//----------------------------------------
}
//----------------------------------------
digitalWrite(ON_Board_LED, HIGH); //--> Turn off the On Board LED when it is connected to the wifi router.
//----------------------------------------If successfully connected to the wifi router, the IP Address that will be visited is displayed in the serial monitor
Serial.println("");
Serial.print("Successfully connected to : ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println();
//----------------------------------------
}
void loop() {
// put your main code here, to run repeatedly:
HTTPClient http; //--> Declare object of class HTTPClient
WiFiClient WiFiClient;
//----------------------------------------Getting Data from MySQL Database
String GetAddress, LinkGet, getData;
int id = 0; //--> ID in Database
GetAddress = "rafael/GetData.php";
LinkGet = host + GetAddress; //--> Make a Specify request destination
getData = "ID=" + String(id);
Serial.println("----------------Connect to Server-----------------");
Serial.println("Get LED Status from Server or Database");
Serial.print("Request Link : ");
Serial.println(LinkGet);
http.begin("LinkGet");
http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type header
int httpCodeGet = http.POST(getData); //--> Send the request
String payloadGet = http.getString(); //--> Get the response payload from server
Serial.print("Response Code : "); //--> If Response Code = 200 means Successful connection, if -1 means connection failed. For more information see here : https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
Serial.println(httpCodeGet); //--> Print HTTP return code
Serial.print("Returned data from Server : ");
Serial.println(payloadGet); //--> Print request response payload
if (payloadGet == "1") {
digitalWrite(LED_D8, HIGH); //--> Turn off Led
}
if (payloadGet == "0") {
digitalWrite(LED_D8, LOW); //--> Turn off Led
}
//----------------------------------------
Serial.println("----------------Closing Connection----------------");
http.end(); //--> Close connection
Serial.println();
Serial.println("Please wait 5 seconds for the next connection.");
Serial.println();
delay(5000); //--> GET Data at every 5 seconds
}
I want my esp8266 to connect to my database(MySql) and get a value to turn on/off a led light.
The esp im using is the NodeMCU epp8266.
Apart from the actual issue that causes the compile error there are several other things wrong with this code. I fixed the most obvious ones. See the explanations for the callouts below the code.
// <1>
#include <ESP8266WiFi.h>
//#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
//#include <ESP8266WiFi.h>
//#include <WiFiClient.h>
//#include <ESP8266WebServer.h>
//#include <ESP8266HTTPClient.h>
//#include <WiFiClientSecureBearSSL.h>
#define ON_Board_LED 2
#define LED_D8 15
const char* ssid = "********";
const char* password = "********";
// <2>
// <3>
const char* host = "http://192.168.1.1/";
// <4>
String GetAddress, LinkGet, getData;
int id = 0;
// <5>
HTTPClient http;
WiFiClient client;
// <6>
void connectWiFi() {
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
digitalWrite(ON_Board_LED, LOW);
delay(250);
digitalWrite(ON_Board_LED, HIGH);
delay(250);
}
digitalWrite(ON_Board_LED, HIGH);
Serial.println("");
Serial.print("Successfully connected to : ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println();
}
void setup() {
Serial.begin(115200);
delay(500);
// <7>
GetAddress = "rafael/GetData.php";
LinkGet = host + GetAddress;
getData = "ID=" + String(id);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
pinMode(ON_Board_LED, OUTPUT);
digitalWrite(ON_Board_LED, HIGH);
pinMode(LED_D8, OUTPUT);
digitalWrite(LED_D8, LOW);
}
void loop() {
// <8>
// // put your main code here, to run repeatedly:
// HTTPClient http; //--> Declare object of class HTTPClient
// WiFiClient WiFiClient;
// <9>
if (WiFi.status() != WL_CONNECTED) {
connectWiFi();
}
Serial.println("----------------Connect to Server-----------------");
Serial.println("Get LED Status from Server or Database");
Serial.print("Request Link : ");
Serial.println(LinkGet);
// <10>
http.begin(client, LinkGet);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
int httpCodeGet = http.POST(getData);
String payloadGet = http.getString();
Serial.print("Response Code : ");
Serial.println(httpCodeGet);
Serial.print("Returned data from Server : ");
Serial.println(payloadGet);
if (payloadGet == "1") {
digitalWrite(LED_D8, HIGH);
}
if (payloadGet == "0") {
digitalWrite(LED_D8, LOW);
}
Serial.println("----------------Closing Connection----------------");
http.end();
Serial.println();
Serial.println("Please wait 5 seconds for the next connection.");
Serial.println();
delay(5000);
}
Clean up the includes such that only those remain which you actually need.
With this sketch your host cannot be (and likely is not) reachable using SSL/TLS encryption (https -> http).
localhost is wrong as this would point to the ESP8266 itself (loopback). You need the PC IP address or possibly its hostname here.
Declare global variables globally i.e. outside loop().
Declare and initialize the HTTPClient and WiFiClient globally rather than inside the loop(). See my answer here https://stackoverflow.com/a/59701884/131929 for more.
Put the WiFi-connecting code in a separate function - you'll need it later.
Initialize the global variables in setup() rather than loop(); goes along with <4>.
Don't instantiate those over and over again; goes along with <5>.
Verify the device is still connected to WiFi every time loop() is invoked and re-connect if not.
Compile error: http.begin() takes a WiFiClient plus that actual HTTP address. This is what the compile error message tells you.

How to know client status in ESP8266?

I am following the code from
https://siytek.com/communication-between-two-esp8266/
I am trying to communicate between two ESP8266. The only problem is when the client disconnected due to power losses; the server freezes at the last status until the client turns on again.
I would let the server set the write (Relay, LOW) if the client disconnected and return to the normal loop when the client connected again.
Your support is highly appreciated.
Code for the client ESP
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
// Set WiFi credentials
#define WIFI_SSID "TheOtherESP"
#define WIFI_PASS "flashmeifyoucan"
// UDP
WiFiUDP UDP;
IPAddress remote_IP(192,168,4,1);
#define UDP_PORT 4210
void setup() {
// Setup IO
pinMode(LED_BUILTIN, OUTPUT);
// Setup serial port
Serial.begin(115200);
Serial.println();
// Begin WiFi
WiFi.begin(WIFI_SSID, WIFI_PASS);
WiFi.mode(WIFI_STA);
// Connecting to WiFi...
Serial.print("Connecting to ");
Serial.print(WIFI_SSID);
// Loop continuously while WiFi is not connected
while (WiFi.status() != WL_CONNECTED)
{
delay(100);
Serial.print(".");
}
// Connected to WiFi
Serial.println();
Serial.print("Connected! IP address: ");
Serial.println(WiFi.localIP());
// Begin UDP port
UDP.begin(UDP_PORT);
Serial.print("Opening UDP port ");
Serial.println(UDP_PORT);
}
void loop() {
// Sent to server
char PumpStatus = 1;
// Send Packet
UDP.beginPacket(remote_IP, UDP_PORT);
UDP.write(PumpStatus);
Serial.println("Pump ON");
digitalWrite(LED_BUILTIN,HIGH);
UDP.endPacket();
delay(1000);
PumpStatus = 0;
// Send Packet
UDP.beginPacket(remote_IP, UDP_PORT);
UDP.write(PumpStatus);
Serial.println("Pump OFF");
digitalWrite(LED_BUILTIN,LOW);
UDP.endPacket();
delay(1000);
}
Code for the Server ESP
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
// Set AP credentials
#define AP_SSID "TheOtherESP"
#define AP_PASS "flashmeifyoucan"
#define Relay 0
// UDP
WiFiUDP UDP;
IPAddress local_IP(192,168,4,1);
IPAddress gateway(192,168,4,1);
IPAddress subnet(255,255,255,0);
#define UDP_PORT 4210
// UDP Buffer
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];
void setup() {
// Setup LED pin
pinMode(LED_BUILTIN, OUTPUT);
pinMode(Relay, OUTPUT);
// Setup serial port
Serial.begin(115200);
Serial.println();
// Begin Access Point
Serial.println("Starting access point...");
WiFi.softAPConfig(local_IP, gateway, subnet);
WiFi.softAP(AP_SSID, AP_PASS);
Serial.println(WiFi.localIP());
// Begin listening to UDP port
UDP.begin(UDP_PORT);
Serial.print("Listening on UDP port ");
Serial.println(UDP_PORT);
}
void loop() {
// Receive packet
UDP.parsePacket();
UDP.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
if (packetBuffer[0]){
digitalWrite(LED_BUILTIN, HIGH);
Serial.println("Relay ON");
digitalWrite(Relay, HIGH);
} else {
digitalWrite(LED_BUILTIN, LOW);
Serial.println("Relay OFF");
digitalWrite(Relay, LOW);
}
}
In your server code, the UDP.parsePacket() returns the size of the packet in bytes, or 0 if no packets is available, so you should only proceed to read the packet and run the rest of codes if UDP.parsePacket() return a value other than 0.
void loop() {
if (UDP.parsePacket()) {
UDP.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
if (packetBuffer[0]){
digitalWrite(LED_BUILTIN, HIGH);
Serial.println("Relay ON");
digitalWrite(Relay, HIGH);
} else {
digitalWrite(LED_BUILTIN, LOW);
Serial.println("Relay OFF");
digitalWrite(Relay, LOW);
}
}
delay(100); // adjust this if necessary
}

Problem in Django cooperation with esp 8266

Hello i need help with my django project . I want to run program on ESP 8266 from django website. To test I create simple program with blink diode on ESP and I made button on my django website and it works but I use "webbrowser()" in views.py and it is not looks perfect (I need to stay on this webiste, a webiste made in django, not open a new one). I need help to create something what will work like:
I click the button on my django website, program in "views.py" send something to esp what runs program on it or change something in the ESP code, which is only going to run the code, and it won't open web browser.
my views.py:
def espON(request):
on = On.objects.all()
off = Off.objects.all()
menu = menu.objects.all()
webbrowser.open("http://my_ip/turnOn")
d = {'on':on, 'off':off, 'menu':menu,}
return render(request, 'on/index.html', d)
ESP code:
#include <ESP8266WiFi.h>
#include <Ticker.h>
#include <Math.h>
const char* ssid = "my_ssid"; //nazwa ssid sieci
const char* password = "my_password"; //haslo
#define LED 5
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
pinMode(LED, OUTPUT);
//Laczenie z siecia wifi
Serial.println();
Serial.println();
Serial.print("Laczenie z: ");
Serial.println(ssid);
IPAddress ip(my_ip); //ip
IPAddress gateway(my_ip2);
IPAddress subnet(my_ip3);
WiFi.config(ip, gateway, subnet);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi polaczone");
// Start
server.begin();
Serial.println("Serwer uruchomiony");
}
void loop() {
while (WiFi.status() == WL_CONNECTED){
WiFiClient client = server.available();
if (!client) {
return;
}
String request = client.readStringUntil('\r');
client.flush();
//condition
if (request.indexOf("/turnOn") > 0)
{
digitalWrite(LED, HIGH); //work
}
if (request.indexOf("/turnOff") > 0) //not
{
digitalWrite(LED, LOW);
}
}
}

Problem with MQTT server: Attempting MQTT connection...failed, rc=-2 try again in 5 seconds

I'am hosting MQTT server on rPi, server works fine and i'am able to connect to it using different machine (PC-ubuntu), but arduino(wemos d1 mini) has a problem with that.
I have already set allow_anonymous to true in config file, and run sudo ufw allow 1883.
Nothing seems to work for me :c
#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <Adafruit_INA219.h>
#include "arduino_secrets.h"
// Connect to the WiFi
const char* ssid = SECRET_SSID;
const char* password = SECRET_PASS;
//const char* mqtt_server = "192.168.0.158"; //at first was using this
IPAddress ip(192, 168, 1, 100); //then switched to this, but with no effect
IPAddress server(192, 168, 0, 158);
IPAddress mqtt_server = {192, 168, 0, 158};
WiFiClient espClient;
PubSubClient client(espClient);
const byte ledPin = D4; // digital pin 4 on a weMos D1 mini is next to ground so easy to stick a LED in.
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++) {
char receivedChar = (char)payload[i];
Serial.print(receivedChar);
if (receivedChar == '1')
digitalWrite(ledPin, HIGH);
if (receivedChar == '0')
digitalWrite(ledPin, LOW);
}
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("DUPADUPA")) {
delay(2000);
Serial.println("connected");
client.subscribe("real_unique_topic");
} 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()
{
Serial.begin(9600);
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
delay(5000);
digitalWrite(ledPin, LOW);
}
void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();
}
Also checked another lib: <ArduinoMqttClient.h>, but the same error appears.
PS: Also tried code from here: https://docs.arduino.cc/tutorials/uno-wifi-rev2/uno-wifi-r2-mqtt-device-to-device - works for "test.mosquitto.org", but not with rPi ip