ESP 8266 Program Issue - arduino

Description
I am writing a web server on ESP-8266(01), that will control 3 locks using Arduino Mega.
The locks will be controlled by Bluetooth ESP 8266 (get method from phone) and using my laptops browser.
I can do it all with bluetooth HC-05 (easily).
The issue I am facing is with my ESP-8266 wifi module.
I need to send 3 different strings from ESP for Arduino to read it.
If it's "AAAA" Arduino will read it and unlock door one, if it BBBB then door 2 and etc etc.....
So I used this code:
#include <ESP8266WiFi.h>
const char* ssid = "Do-Not-Ask-For-Password";
const char* password = "ITISMYPASSWORD";
//const char* ssid = "`STAR-NET-Azhar-32210352";
//const char* password = "ITISMYPASSWORD";
int ledPin = 2; // GPIO2
WiFiServer server(80);
// Update these with values suitable for your network.
IPAddress ip(192,168,8,128); //Node static IP
IPAddress gateway(192,168,8,1);
IPAddress subnet(255,255,255,0);
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);
WiFi.config(ip, gateway, subnet);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// 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() {
ESP.wdtDisable();
// 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);
// }
if(!client.available()){
delay(1);
client.flush();
}
// Read the first line of the request
String request = client.readStringUntil('\r');
//Serial.println(request);
client.flush();
// Match the request
int value1 = LOW;
int value2 = LOW;
int value3 = LOW;
if (request.indexOf("/LOCK=ON1") != -1) {
//digitalWrite(ledPin, HIGH);
value1 = HIGH;
Serial.println("AAAA");
}
if(request.indexOf("/LOCK=ON2") != -1){
value2 = HIGH;
Serial.println("BBBB");
}
if(request.indexOf("/LOCK=ON3") != -1){
value3 = HIGH;
Serial.println("CCCC");
}
// 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.println("<br><br>");
client.print("LOCK ONE IS NOW: ");
if(value1 == HIGH) {
client.print("UNLOCKED");
// Serial.println("A");
} else {
client.print("LOCKED");
}
client.println("<br><br>");
client.print("LOCK TWO IS NOW: ");
if(value2 == HIGH) {
client.print("UNLOCKED");
// Serial.println("B");
} else {
client.print("LOCKED");
}
client.println("<br><br>");
client.print("LOCK THREE IS NOW: ");
if(value3 == HIGH) {
client.print("UNLOCKED");
//Serial.println("C");
} else {
client.print("LOCKED");
}
client.println("<br><br>");
client.println("CLICK HERE TO UNLOCK THE LOCK ONE<br>");
client.println("CLICK HERE TO UNLOCK THE LOCK TWO<br>");
client.println("CLICK HERE TO UNLOCK THE LOCK THREE<br>");
client.println("</html>");
delay(100);
//Serial.println("client disconnected");
// Serial.println("");
}
The Result I Get on Browser is ( Which is What i need):
enter image description here
ISSUE:
Now The Issue Is Some Times it misses the serial data i send, For Example if i click unlock door 1, It sends data and i click unlock door 2 it does nothn and when i reset it sends data from all 3 but for two to 3 times and then module resets it self ....
This Is What I got From Serial Monitor:
enter image description here
Now i have searched alot and its watchdre out what i did wrong in the code.
this is how my ESP is connected:
vcc & CHPD to 3.3V ragulator
gnd to gnd of powersuply and to arduino gnd...
GP 0 ------> 3.3v with 2.2k Resistor ( in non flashing state).
Rst ------> 3.3v with resistor
RX to TX
TX to RX
Any Ideas how to fix it?
Is There any other way to control Arduino pins (6 different pins) from ESP 8266 module??
ive been trying from many days please help!!

Ok I am Posting It For those who are facing the same problem!! i took the Hello ESP example And Modified it to Print Serial!!!
On Mega My Serial Was Started at 9600 and i started Serial On ESP at 9600 aswell :| So This is the Code .... Slow Server and WDT issue is Almost Gone....
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
//const int RELAY_PIN = 2; //RELAY
const char* ssid = "Do-Not-Ask-For-Password";
const char* password = "AeDrki$32ILA!$#2";
MDNSResponder mdns;
ESP8266WebServer server(80);
void handleRoot() {
server.send(200, "text/plain", "hWelcome To Door Unlock Project By Haziq Sheikh");
}
void handleNotFound(){
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
void setup(void){
// pinMode(RELAY_PIN, OUTPUT);
Serial.begin(9600);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
//digitalWrite(RELAY_PIN, 1);
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// digitalWrite(RELAY_PIN, 0);
if (mdns.begin("esp8266", WiFi.localIP())) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.on("/lock1", [](){
server.send(200, "text/plain", "Okay Door One Unlocked");
Serial.println("AAAA");
});
server.on("/lock2", [](){
server.send(200, "text/plain", "Okay -- Door 2 Unlocked");
Serial.println("BBBB");
});
server.on("/lock3", [](){
server.send(200, "text/plain", "Okay -- Door 3 is Unlocked");
Serial.println("CCCC");
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop(void){
server.handleClient();
}

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);
}
}```

How would I create a simple Arduino script that allows me to turn on and off LEDBuitIn remotely?

I'm working on a project that includes working with arduino hardware remotely. I would like to learn how to create a simple script that allows me to turn on and off the Led builtin to my MKR1000 wirelessly. I could then use this knowledge in more complicated projects. After doing some research and looking at the arduino library's sample webserver program, I came up with this Frankenstein of code. After working for hours I just keep on making it worse, I could really use some guidance on what I'm doing wrong, why and how to fix it.
My Frankenstein code:
#include <WiFi101.h>
#include <SPI.h>
char ssid[] = "ARROW_015D80";
char pass[] = "KRR3K47XZXM3NYRHV7GX";
int status = WL_IDLE_STATUS;
int LED = LED_BUILTIN;
int LEDState = digitalRead(LED);
WiFiServer server(80);
void setup() {
while (!Serial) {
}
Serial.begin(9600);
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("Yo, where the wifi shield at?");
while(true);
}
while (status !=WL_CONNECTED) {
Serial.print("Connecting to ssid: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
delay(10000);
}
server.begin();
printWiFiStatus();
}
void loop() {
WiFiClient client = server.available();
if (client) {
Serial.println("+1 Client");
String currentLine = "";
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
if (c == '\n') {
if(currentLine.length() == 0) {
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
client.println("Refresh: 1"); // refresh the page automatically every 5 sec
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.print("State of button:");
if (LEDState == HIGH){
client.print("ON");
}
if (LEDState == LOW){
client.print("OFF");
}
client.println("<br>");
client.println("</html>");
client.println();
break;
}
else {
currentLine = "";
}
}
else if (c !='\r') {
currentLine += c;
}
if (currentLine.endsWith("GET /H")) {
digitalWrite(LED, HIGH);
}
if (currentLine.endsWith("Get /L")) {
digitalWrite(LED, LOW);
}
if (currentLine.endsWith("Get /stop")){
client.stop();
Serial.println ("Client disconnected");
}
}
}
}
}
void printWiFiStatus() {
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
According to the videos and the mismatch of information, this program should connect the arduino to the internet, print the arduino's ip address in the serial monitor and I should be able to change the state of the built in LED by changing the end of the ip address search.
Instead, after showing the ip address and displaying the page, with the button state on it. When I try to change the url to change the button state it bugs out. It takes me to the "This page can't be reached" and the serialmonitor bug out.
Never mind, I found a video online that explain clearly how to write the code I'm looking for. It is extremely helpful : https://www.youtube.com/watch?v=H0p7GVPdlyU
It also link to a page with all the code for it.

ESP8266 and IFTTT

I am working on a simple device that alerts me when a button is pushed. At this time I am just trying to get the ESP8266 to activate the webhook event on it's own. It will connect to the wifi, but will not activate the event. I don't know if I'm going about this the wrong way or not. The http.Get() command returns back a -1. How do I activate the webhook? Any help is appreciated. The code is below.
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
const char* ssid="ATT2506";
const char* password = "XXXXXXXX";
int ledPin = 2;
void setup() {
pinMode(ledPin,OUTPUT);
digitalWrite(ledPin,HIGH);
Serial.begin(115200);
Serial.println();
Serial.print("Wifi connecting to ");
Serial.println( ssid );
WiFi.begin(ssid,password);
Serial.println();
Serial.print("Connecting");
while( WiFi.status() != WL_CONNECTED ){
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("Wifi Connected Success!");
Serial.print("NodeMCU IP Address : ");
Serial.println(WiFi.localIP() );
digitalWrite( ledPin , LOW);
}
void loop() {
if (WiFi.status() != WL_CONNECTED){
digitalWrite( ledPin , HIGH);
}
if (1==1) { //Check WiFi connection status
HTTPClient http; //Declare an object of class HTTPClient
http.begin("https://maker.ifttt.com/trigger/csalarm/with/key/XXXXXXXXXXX"); //Specify request destination
int httpCode = http.GET(); //Send the request
Serial.println(httpCode);
if (httpCode > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
Serial.println(1); //Print the response payload
}
http.end(); //Close connection
}
delay(30000); //Send a request every 30 seconds
}

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