MAX30102 Sensor not sending data to thingsboard - arduino

I'm having trouble with this I'm not sure if it's a code issue or a hardware issue, I am using a ESP32 and the sensors MAX3012, MPU6050 and a MLX90614. The issue I'm having is that when sending data to thingsboard the MAX30102 sensor is not showing data. But when I dont send data to thingsboard the sensor is working fine. I am out of ideas of what is going on.
#include <WiFi.h> // include the Arduino WiFi library
#include <ThingsBoard.h> // ThingsBoard SDK
#include <Wire.h>
#include "MAX30105.h"
#include "heartRate.h"
#include <Adafruit_MLX90614.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
Adafruit_MLX90614 mlx = Adafruit_MLX90614(); //0x5A
Adafruit_MPU6050 mpu; //0x68
MAX30105 particleSensor;
const byte RATE_SIZE = 0; //Increase this for more averaging. 4 is good.
byte rates[RATE_SIZE]; //Array of heart rates
byte rateSpot = 0;
long lastBeat = 0; //Time at which the last beat occurred
float beatsPerMinute;
long beatAvg;
#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x]))))) // Helper macro to calculate array size
#define WIFI_AP_NAME "Get your own Wifi" // WiFi access point
#define WIFI_PASSWORD "w1frjoyf00bar" // WiFi password
#define TOKEN "ESP32_Xian_Token" // Device Token
#define THINGSBOARD_SERVER "demo.thingsboard.io" // ThingsBoard server instance.
#define REPORTING_PERIOD_MS 500
#define BOTtoken "5862827027:AAE7Glekx7EkSufrcL3mrjN56-vm6tjwB6c" // your Bot Token (Get from Botfather)
#define CHAT_ID "1672688476" // your Chat ID from IDBot
// Initialize ThingsBoard client
WiFiClient espClient;
ThingsBoard tb(espClient);
//declare wifi connection for Thingsboard and Telegram
WiFiClient client;
WiFiClientSecure tlclient;
UniversalTelegramBot bot(BOTtoken, tlclient);
unsigned long lastSend;
int val;
int status = WL_IDLE_STATUS; // the Wifi radio's status
void InitWiFi() {
Serial.println("Connecting to AP ..."); // attempt to connect to WiFi network
tlclient.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
WiFi.begin(WIFI_AP_NAME, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to AP");
}
void reconnect() {
// Loop until we're reconnected
while (!tb.connected()) {
Serial.print("Connecting to ThingsBoard ...");
// Attempt to connect (clientId, username, password)
if ( tb.connect(THINGSBOARD_SERVER, TOKEN) ) {
Serial.println( "[DONE]" );
} else {
Serial.print( "[FAILED]" );
Serial.println( " : retrying in 5 seconds" );
delay( 5000 );
}
}
}
void setup() {
Serial.begin(115600);
WiFi.begin(WIFI_AP_NAME, WIFI_PASSWORD); // Connect to WiFi
tb.connect(THINGSBOARD_SERVER, TOKEN); // Connect to ThingsBoard
InitWiFi();
lastSend = 0;
particleSensor.begin(Wire, I2C_SPEED_FAST);
particleSensor.setup();
particleSensor.setPulseAmplitudeRed(0x0A); //Turn Red LED to low to indicate sensor is running
particleSensor.setPulseAmplitudeGreen(0); //Turn off Green LED
mlx.begin();
mpu.begin();
bot.sendMessage(CHAT_ID, "Bot started up", "");
mpu.setAccelerometerRange(MPU6050_RANGE_8_G);
Serial.print("Accelerometer range set to: ");
switch (mpu.getAccelerometerRange()) {
case MPU6050_RANGE_2_G:
Serial.println("+-2G");
break;
case MPU6050_RANGE_4_G:
Serial.println("+-4G");
break;
case MPU6050_RANGE_8_G:
Serial.println("+-8G");
break;
case MPU6050_RANGE_16_G:
Serial.println("+-16G");
break;
}
mpu.setGyroRange(MPU6050_RANGE_500_DEG);
Serial.print("Gyro range set to: ");
switch (mpu.getGyroRange()) {
case MPU6050_RANGE_250_DEG:
Serial.println("+- 250 deg/s");
break;
case MPU6050_RANGE_500_DEG:
Serial.println("+- 500 deg/s");
break;
case MPU6050_RANGE_1000_DEG:
Serial.println("+- 1000 deg/s");
break;
case MPU6050_RANGE_2000_DEG:
Serial.println("+- 2000 deg/s");
break;
}
mpu.setFilterBandwidth(MPU6050_BAND_5_HZ);
Serial.print("Filter bandwidth set to: ");
switch (mpu.getFilterBandwidth()) {
case MPU6050_BAND_260_HZ:
Serial.println("260 Hz");
break;
case MPU6050_BAND_184_HZ:
Serial.println("184 Hz");
break;
case MPU6050_BAND_94_HZ:
Serial.println("94 Hz");
break;
case MPU6050_BAND_44_HZ:
Serial.println("44 Hz");
break;
case MPU6050_BAND_21_HZ:
Serial.println("21 Hz");
break;
case MPU6050_BAND_10_HZ:
Serial.println("10 Hz");
break;
case MPU6050_BAND_5_HZ:
Serial.println("5 Hz");
break;
}
}
void loop() {
if ( !tb.connected() ) {
reconnect();
}
long irValue = particleSensor.getIR();
if (checkForBeat(irValue) == true)
{
//We sensed a beat!
long delta = millis() - lastBeat;
lastBeat = millis();
beatsPerMinute = 60 / (delta / 1000.0);
if (beatsPerMinute < 255 && beatsPerMinute > 20)
{
rates[rateSpot++] = (byte)beatsPerMinute; //Store this reading in the array
rateSpot %= RATE_SIZE; //Wrap variable
//Take average of readings
beatAvg = 0;
for (byte x = 0 ; x < RATE_SIZE ; x++)
beatAvg += rates[x];
beatAvg /= RATE_SIZE;
}
}
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp);
if (irValue < 50000)
Serial.println(" \nNo finger? ");
Serial.print("Avg BPM = ");
Serial.print(beatAvg);
tb.sendTelemetryFloat("BPM", beatAvg);
Serial.println(" ");
Serial.print("Accelerometer X: ");
Serial.print(a.acceleration.x, 1);
Serial.print(" m/s^2\n");
Serial.print("Accelerometer Y: ");
Serial.print(a.acceleration.y, 1);
Serial.print(" m/s^2\n");
Serial.print("Accelerometer Z: ");
Serial.print(a.acceleration.z, 1);
Serial.println(" m/s^2");
tb.sendTelemetryFloat("AccelX", a.acceleration.x);
tb.sendTelemetryFloat("AccelY", a.acceleration.y);
tb.sendTelemetryFloat("AccelZ", a.acceleration.z);
Serial.print("Gyroscope ");
Serial.print("X: ");
Serial.print(g.gyro.x, 1);
Serial.print(" rps\n");
Serial.print("Gyroscope Y: ");
Serial.print(g.gyro.y, 1);
Serial.print(" rps\n");
Serial.print("Gyroscope Z: ");
Serial.print(g.gyro.z, 1);
Serial.println(" rps");
tb.sendTelemetryFloat("GyroX", g.gyro.x);
tb.sendTelemetryFloat("GyroY", g.gyro.y);
tb.sendTelemetryFloat("GyroZ", g.gyro.z);
Serial.print("Ambient = ");
Serial.print(mlx.readAmbientTempC());
Serial.print("*C\nObject = ");
Serial.print(mlx.readObjectTempC());
Serial.println("*C");
tb.sendTelemetryFloat("Ambient Temp", mlx.readAmbientTempC());
tb.sendTelemetryFloat("Body Temp", mlx.readObjectTempC());
Serial.println("-----------------------------------------------------------------");
//BPM alert
if (beatAvg > 110){
Serial.println("Heart rate too High");
bot.sendMessage(CHAT_ID, "Oops someones heart is beating too fast", "");
}
else if (beatAvg > 60){
Serial.println("Heart rate too Low");
bot.sendMessage(CHAT_ID, "Oops someones heart is beating too slow", "");
}
// body and ambient temp alert
if (mlx.readObjectTempC() > 39) {
Serial.println("Oops someones too hot");
bot.sendMessage(CHAT_ID, "Oops someones too hot", "");
}
else if (mlx.readObjectTempC() < 35){
Serial.println("Oops someones too cold");
bot.sendMessage(CHAT_ID, "Oops someones too cold", "");
}
//fall detection x y z
if (g.gyro.x > 0.15) {
Serial.println("Oops someone fell");
bot.sendMessage(CHAT_ID, "Oops someone fell", "");
}
else if (g.gyro.x < -0.15){
Serial.println("Oops someone fell");
bot.sendMessage(CHAT_ID, "Oops someone fell", "");
}
if (g.gyro.y > 0.15) {
Serial.println("Oops someone fell");
bot.sendMessage(CHAT_ID, "Oops someone fell", "");
}
else if (g.gyro.y < -0.15){
Serial.println("Oops someone fell");
bot.sendMessage(CHAT_ID, "Oops someone fell", "");
}
if (g.gyro.z > 0.15) {
Serial.println("Oops someone fell");
bot.sendMessage(CHAT_ID, "Oops someone fell", "");
}
else if (g.gyro.z < -0.15){
Serial.println("Oops someone fell");
bot.sendMessage(CHAT_ID, "Oops someone fell", "");
}
}
This is the serial monitor when its not sending to thingsboard.
enter image description here
And this is when its sending to thingsboard.
enter image description here
Here is the circuit diagram for the project.
enter image description here
I tried using only the MAX30102 sensor.

Related

ESP32 writeStringEEPROM adds unwanted nembers when I use the letter '&'

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

ESP12F, cant get a relay to work with data from dht11

i've been trying to build a system that detects in one room of the house the temperature using an esp8266 and a dht11 sensor, this esp sends the data to a webserver while the ESP12F grabs this data and should turn the relay on when a certain value is reached, however i can't get the relay to work, as soon as i upload the code, the led on the module turns but not at its full power, i tried with another code to see if it was just a faulty relay, but it works perfectly with the same connections. The code from the client side of the system is below:
#include "ESP8266WiFi.h"
#include "ESP8266HTTPClient.h"
#include "WiFiClient.h"
#include "ESP8266WiFiMulti.h"
ESP8266WiFiMulti WiFiMulti;
const char* ssid = "*******";
const char* password = "********";
//Your IP address or domain name with URL path
const char* serverNameTemp = "http://192.168.1.188/temperature";
const char* serverNameHumi = "http://192.168.1.188/humidity";
const char* serverNamePres = "http://192.168.1.188/pressure";
#include "Wire.h"
#include "Adafruit_GFX.h"
#include "Adafruit_SSD1306.h"
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
String temperature;
String humidity;
String pressure;
const int relay = 5;
float temp_int = temperature.toFloat();
unsigned long previousMillis = 0;
const long interval = 2000;
void setup() {
Serial.begin(115200);
Serial.println();
pinMode(relay,OUTPUT);
digitalWrite(relay,LOW);
// Address 0x3C for 128x64, you might need to change this value (use an I2C scanner)
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
display.clearDisplay();
display.setTextColor(WHITE);
int int_temp = temperature.toFloat();
WiFi.mode(WIFI_STA);
WiFiMulti.addAP(ssid, password);
while((WiFiMulti.run() == WL_CONNECTED)) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected to WiFi");
}
void loop() {
unsigned long currentMillis = millis();
if(currentMillis - previousMillis >= interval) {
// Check WiFi connection status
if ((WiFiMulti.run() == WL_CONNECTED)) {
int int_temp = temperature.toFloat();
temperature = httpGETRequest(serverNameTemp);
humidity = httpGETRequest(serverNameHumi);
pressure = httpGETRequest(serverNamePres);
if(int_temp < 26){
digitalWrite(relay,LOW);
}
else if (int_temp > 26){
digitalWrite(relay,HIGH);
}
Serial.println("Temperature: " + temperature + " *C - Humidity: " + humidity + " % - Pressure: " + pressure + " hPa");
Serial.println(int_temp);
Serial.println(temperature.toFloat());
display.clearDisplay();
// display temperature
display.setTextSize(2);
display.setCursor(0,0);
display.print("T: ");
display.print(temperature);
display.print(" ");
display.setTextSize(1);
display.cp437(true);
display.write(248);
display.setTextSize(2);
display.print("C");
// display humidity
display.setTextSize(2);
display.setCursor(0, 25);
display.print("H: ");
display.print(humidity);
display.print(" %");
// display pressure
display.setTextSize(2);
display.setCursor(0, 50);
display.print("P:");
display.print(pressure);
display.setTextSize(1);
display.setCursor(110, 56);
display.print("hPa");
display.display();
// save the last HTTP GET Request
previousMillis = currentMillis;
}
else {
Serial.println("WiFi Disconnected");
}
}
}
String httpGETRequest(const char* serverName) {
WiFiClient client;
HTTPClient http;
// Your IP address with path or Domain name with URL path
http.begin(client, serverName);
// Send HTTP POST request
int httpResponseCode = http.GET();
String payload = "--";
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
payload = http.getString();
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
return payload;
}

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.

MQTT code stops working after a couple of hours

Made some code for a NodeMCU in the Arduino IDE to push a button using MQTT. The code works perfectly fine for some time, but after a couple of hours it will not respond anymore.
The code is very frankenstein, since I am a mega rookie, and is as follows:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Servo.h>
const char* ssid = "ap_name"; //change
const char* password = "ap_pw"; //change
const char* mqttServer = "server_ip"; //change
const int mqttPort = 1883;
const char* mqttUser = "server_name"; //change
const char* mqttPassword = "server_pw"; //change
WiFiClient espClient;
PubSubClient client(espClient);
Servo servo;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
servo.attach(D4);
servo.write(70);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP8266Client", mqttUser, mqttPassword )) {
Serial.println("connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
client.publish("esp/test", "Hello from ESP8266");
client.subscribe("esp/test");
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
if(*payload == 49){
rotServo();
Serial.println();
Serial.print("Roterar servo");
delay(3000);
client.publish("esp/test", "0");
}
Serial.println();
Serial.println("-----------------------");
}
void rotServo(){
servo.attach(D4);
servo.write(70);
delay(1000);
servo.write(175);
delay(2000);
servo.write(70);
delay(3000);
servo.detach();
}
void loop() {
client.loop();
}
Anyone that would know what might be causing it to stop working?
It could be because, you never reconnect if your client ever gets disconnected.
See the example here for more details, but here is the reconnect function from the example and how it is called in the loop. You would need to tailor it to suite your application.
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("outTopic", "hello world");
// ... and resubscribe
client.subscribe("inTopic");
} 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();
...
}
On another note, while I don't think it would cause your specific problem, in your callback, you just compare the contents of the payload to the number 49.
if(*payload == 49){
...
}
You should check that the topic is the actual topic you are interested in and that the length is also what you expect, before you start looking at the payload.

ESP 8266 Program Issue

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

Resources