Problem Statement
I want my NodeMCU to fetch latest updated data from URL each time of the loop.
Currently it does not update the content fetched.
For example, Link: http://abcdxyz.xyz/io.php has just the digits 223838.
Once the NodeMCU starts running, & the link's information gets updated to 240000,
Yet the Arduino Serial Printer is showing 223838 even after the link getting updated on the server.
Here is my code:
#include "ESP8266WiFi.h"
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
# define LED D4 // Use built-in LED which connected to D4 pin or GPIO 2
String serverName = "http://abcdxyz.xyz/";
unsigned long timerDelay = 5000;
unsigned long lastTime = 0;
// WiFi parameters to be configured
const char* ssid = "XXXXXXXXX";
const char* password = "XXXXXXXXXX";
void setup() {
pinMode(LED, OUTPUT); // Initialize the LED as an output
Serial.begin(9600);
// Connect to WiFi
WiFi.begin(ssid, password);
// while wifi not connected yet, print '.'
// then after it connected, get out of the loop
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
//print a new line, then print WiFi connected and the IP address
Serial.println("");
Serial.println("WiFi connected");
// Print the IP address
Serial.println(WiFi.localIP());
}
void loop() {
//Calling An URL FOR DATA
if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status
HTTPClient http;
http.begin("http://abcdxyz.xyz/io.php"); //Specify the URL
int httpCode = http.GET(); //Make the request
if (httpCode > 0) { //Check for the returning code
String payload = http.getString();
Serial.println(httpCode);
Serial.println(payload);
}
else {
Serial.println("Error on HTTP request");
}
http.end(); //Free the resources
}
delay(1000);
//Calling URL ENDS
digitalWrite(LED, HIGH);
delay(100);
digitalWrite(LED, LOW);
}
Figured it out. The link has to be a new link each time to GET the latest records.
Follow the codes below:
void loop() {
//Calling An URL FOR DATA
if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status
HTTPClient http;
randNumber = random(1, 99999);
String crow = "http://abcdxyz.xyz/io.php?tag=";
crow += randNumber;
Serial.println(crow);
http.begin(crow); //Specify the URL
int httpCode = http.GET(); //Make the request
if (httpCode > 0) { //Check for the returning code
String payload = http.getString();
Serial.println(httpCode);
Serial.println(payload);
}
else {
Serial.println("Error on HTTP request");
}
http.end(); //Free the resources
}
delay(1000);
//Calling URL ENDS
digitalWrite(LED, HIGH);
delay(100);
digitalWrite(LED, LOW);
}
Related
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.
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()
I'm attempting to connect my Feather Huzzah to a local MQTT server but the program keeps blowing up and throwing a stack trace. When I attempt to decode the stack trace it's just empty, more frequently I only get part of the stack trace. Here's the code that I'm running, most of it is pretty similar to the pub/sub client example code for Arduino. I've tried erasing the flash on the device, that didn't seem to help.
Even stranger is that it worked once, but as soon as I tried it again adding the callback the code stopped working and blows up. If I try removing the callback nothing changes. I've tried stripping out a lot of the code just to see if I can get a consistent connection to MQTT, but that doesn't seem to be working either. The MQTT server is the latest Mosquitto from Ubuntu 18.04.
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <PubSubClient.h>
const char* ssid = "xxxxxxxx";
const char* password = "xxxxxxxxx";
const int hallPin = 14;
const int ledPin = 0;
const char* mqtt_server = "mosquitto.localdomain";
long lastMsg = 0;
char msg[100];
int value = 0;
int hallState = 0;
WiFiClient espClient;
PubSubClient client(espClient);
WiFiUDP ntpUDP;
// By default 'time.nist.gov' is used with 60 seconds update interval and
// no offset
NTPClient timeClient(ntpUDP);
// Setup and connect to the wifi
void setup_wifi() {
delay(100);
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());
Serial.println("Gateway: ");
Serial.println(WiFi.gatewayIP());
}
//Reconnect to the MQTT broker
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("/homeassistant/devices/doorbell", "hello world");
// ... and resubscribe
client.subscribe("/homeassistant/doorbell/receiver");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
//Process messages incoming from the broker
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]);
}
}
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(hallPin, INPUT);
Serial.begin(115200);
setup_wifi();
timeClient.begin();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
setup_wifi();
}
if (!client.connected()) {
reconnect();
}
hallState = digitalRead(hallPin);
if (hallState == LOW) {
digitalWrite(ledPin, HIGH);
generateAndSendMessage();
delay(1000); //Add in a delay so it doesn't send messages extremely rapidly
} else {
digitalWrite(ledPin, LOW);
}
}
void generateAndSendMessage() {
timeClient.update();
StaticJsonBuffer<100> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["sensor"] = "doorbell";
root["time"] = timeClient.getEpochTime();
root["value"] = 1;
root.printTo(msg);
Serial.println(msg);
client.publish("/homeassistant/devices/doorbell", msg);
}
Looking at the generateAndSendMessage function, I believe you are having an issue due to the size of the MQTT buffer.
The MQTT buffer is by default set to 128 bytes. This includes the length of the channel name along with the message.
The length of you channel is 32 bytes, and the json buffer you used to make the message is 100 bytes long. So you might just be exceeding the 128 byte mark.
Just declare this before including the PubSubClient.h
#define MQTT_MAX_PACKET_SIZE 200
This macro defines the buffer size of the PubSubClient to 200. You can change it to whatever you believe is required.
I hope this helps.
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
}
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();
}