Issue with writing InfluxDB code to ESP32 chip using OTA - influxdb

I'm trying to write a program for my ESP32 that writes to InfluxDB but also maintains an OTA access server and it appears that the two functions are having some impact on each other that's causing the OTA server to not work (i.e. the OTA page does not appear when I enter the IP address into the browser). I've narrowed the problem down to the
client.writePoint(sensor)
function that InfluxDB uses to write data to buffer and I'm unsure of how to remedy that. The OTA functionality works when I comment out the line that references the above function. I've included this code below.
//PASTE THIS IN ABOVE EXISTING HEADERS
//#include <WiFi.h> //if file already has these libraries, remove it from one of the places
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Update.h>
const char* host = "esp32";
const char* ssid = "ssid";
const char* password = "pwd";
WebServer server(80);
// end OTA header file
//BEGIN HEADER FILE
#if defined(ESP32)
#include <WiFiMulti.h>
WiFiMulti wifiMulti;
#define DEVICE "TEST"
#elif defined(ESP8266)
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifiMulti;
#define DEVICE "ESP8266"
#endif
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>
/* Self inclusions -> Not from InfluxDB */
#define Vdd 3.3
#define Aout 35
#define LINEAR LOW
#define SQ_ROOT HIGH
const int R_0 = -1812; //Change this to your own R0 measurements
#include "max6675.h"
#include <WiFi.h>
#include <WiFiUdp.h>
/* End Self Inclusions */
// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
#define INFLUXDB_URL "url"
// InfluxDB v2 server or cloud API authentication token ( Data -> Tokens -> MQ Sensors)
#define INFLUXDB_TOKEN "token"
// InfluxDB v2 organization id (Use: InfluxDB UI -> User -> About -> Common Ids )
#define INFLUXDB_ORG "org"
// InfluxDB v2 bucket name (Use: InfluxDB UI -> Data -> Buckets)
#define INFLUXDB_BUCKET "bucket"
// Set timezone string according to https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
// Examples:
// Pacific Time: "PST8PDT"
// Eastern: "EST5EDT"
// Japanesse: "JST-9"
// Central Europe: "CET-1CEST,M3.5.0,M10.5.0/3"
#define TZ_INFO "EST5EDT"
// InfluxDB client instance with preconfigured InfluxCloud certificate
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
// Data Point
Point sensor("VOC_data"); // Data point
// END HEADER FILE
void setup() { //make sure this line appears one time only
Serial.begin(115200); //make sure there are not two serial/begin functions in setup
Serial.println("started"); //TS COMMENT
// Connect to WiFi network
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("\n\nACCESS UPDATES AT: http://");
Serial.print(WiFi.localIP());
Serial.println("\n\n");
pinMode(Aout, INPUT);
// Add tags
sensor.addTag("device", DEVICE);
// Accurate time is necessary for certificate validation and writing in batches
// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/
// Syncing progress and the time will be printed to Serial.
timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov");
// Check server connection
if (client.validateConnection()) {
Serial.print("Connected to InfluxDB: ");
Serial.println(client.getServerUrl());
} else {
Serial.print("InfluxDB connection failed: ");
Serial.println(client.getLastErrorMessage());
}
/*use mdns for host name resolution*/
if (!MDNS.begin(host)) { //http://esp32.local
Serial.println("Error setting up MDNS responder!");
while (1) {
delay(1000);
}
}
Serial.println("mDNS responder started");
/*return index page which is stored in serverIndex */
server.on("/", HTTP_GET, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/html", loginIndex);
Serial.println("init1 complete"); //TS COMMENT
});
server.on("/serverIndex", HTTP_GET, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/html", serverIndex);
Serial.println("init2 complete"); //TS COMMENT
});
/*handling uploading firmware file */
server.on("/update", HTTP_POST, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
ESP.restart();
Serial.println("init3 complete"); //TS COMMENT
}, []() {
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START) {
Serial.printf("Update: %s\n", upload.filename.c_str());
Serial.println("init4 complete"); //TS COMMENT
if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
Serial.println("Check at line 201");
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_WRITE) {
/* flashing firmware to ESP*/
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
Serial.println("Check at line 207");
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_END) {
if (Update.end(true)) { //true to set the size to the current progress
Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
} else {
Serial.println("Check at line 214");
Update.printError(Serial);
}
}
});
server.begin();
} //delete if void setup() line is deleted
void loop() { //make sure this line does not appear twice
server.handleClient();
float a0 = analogRead(Aout); // get raw reading from sensor
float v_o = a0 * 4.6 / 1023; // convert reading to volts
float R_S = (4.6-v_o) * 1000 / v_o; // apply formula for getting RS
float R_a = R_S/R_0; // formula for the ratio
float PPM = pow(R_a,-2.95) * 1000; //apply formula for getting PPM
float PPM_ALCOHOL = pow(-13.17*log(R_S/R_0) + 10.35 ,1);
//double PPM = pow(static_cast<double>(R_S/R_0),-2.95) * 1000;
//float PPMnew = a0*0.065156122+0.746160521;
sensor.clearFields();
// Store measured value into point
sensor.addField("VOC_Sensor", a0);
sensor.addField("VOC_PPM", PPM);
//sensor.addField("VOC_RS", R_S);
//sensor.addField("VOC_ALCOHOL", PPM_ALCOHOL);
/****************************** Self inclusions -> Not from InfluxDB ******************************/
Serial.print("Sensor Voltage: ");
Serial.print(v_o); //VOC concentration
Serial.println(" V"); //units
Serial.print("VOC Concentration calculation in arduino: ");
Serial.print(PPM); //VOC concentration
Serial.println(" PPM"); //units
Serial.print("Raw signal: ");
Serial.print(a0); //VOC concentration
Serial.println(" "); //units
delay(1000);
/***************************************************************************************************/
// Print what are we exactly writing
Serial.println(WiFi.localIP());
Serial.println("Line 286");
Serial.println(sensor.toLineProtocol());
// Write point
if (client.writePoint(sensor)) {
Serial.println("InfluxDB write successful");
} else {
Serial.print("InfluxDB write failed: ");
Serial.println(client.getLastErrorMessage());
}
Serial.println("Wait 200ms");
delay(200);
} //delete if void loop() line is deleted
The serial output displays
Connected to ssid
ACCESS UPDATES AT: ESP32_IP_ADDRESS
and then continues to display the "InfluxDB write successful" message with each data point.

Related

memory error: "conn.connect(server_addr, 3306, user, password)"

Recently I dived into making an Arduino project. I use Arduino IDE 2.0.3 and the board, LILYGO T-PICOC3.
When I tried to let my board connect to the MySQL server, I encountered an issue...
This is my sketch. I uploaded it to the board successfully
#include <WiFiEspAT.h>
#include <TFT_eSPI.h>
#include <SPI.h>
#include <Button2.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
#include "pico/stdlib.h"
#include "hardware/gpio.h"
//#include "MAX30105.h"
#include <Wire.h>
//#include "heartRate.h"
//#define I2C_SDA 12
//#define I2C_SCL 13
byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress server_addr(xxx, xxx, xx, xxx);
char user[] = "project" ;
char password[] = "1234";
WiFiClient client;
MySQL_Connection conn((Client *)&client);
char ssid[] = "Home3";
char pass[] = "12341234";
// max30102 setup ----
//MAX30105 particleSensor;
//long lastbeat;
// max30102 setup ----
void setup() {
Serial.begin(115200);
// power supply ----
pinMode(22, OUTPUT);
digitalWrite(22,HIGH);
// power supply ----
// esp32 setup ----
Serial2.setTX(8);
Serial2.setRX(9);
Serial2.begin(115200);
// esp32 setup ----
// max30102 segment ----
//if (particleSensor.begin(Wire, I2C_SPEED_FAST) == false){
// Serial.println("MAX30102 was not found");
// while(true);
//}
//particleSensor.setup();
//particleSensor.setPulseAmplitudeRed(0x0A);
//Serial.print("max30102 is online!");
// max30102 segment ----
// WiFi start ----
WiFi.init(Serial2);
WiFi.begin(ssid, pass);
Serial.println("connecting to wifi");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1600);
}
Serial.println("Connected to network");
pinMode(29, OUTPUT);
digitalWrite(29, HIGH);
IPAddress ip = WiFi.localIP();
Serial.print("My IP address is: ");
Serial.println(ip);
// WiFi start ----
// connect to database ----
Serial.println("Connecting to the database");
if (conn.connect(server_addr, 3306, user, password)){
delay(1000);
}
Serial.println("unSuccessfully connect!");
conn.close();
// connect to database ----
}
void loop() {
//long irvalue = particleSensor.getIR();
//if (checkForBeat(irvalue) == true){
// long delta = millis() - lastbeat;
// lastbeat = millis();
// float beatsperminute = 60 / (delta/1000.0);
//}
}
And I got the message from Output :
Sketch uses 340796 bytes (16%) of program storage space. Maximum is 2093056 bytes.
Global variables use 69008 bytes (26%) of dynamic memory, leaving 193136 bytes for local variables. Maximum is 262144 bytes.
Resetting COM5
Converting to uf2, output size: 714240, start address: 0x2000
Flashing G: (RPI-RP2)
Wrote 714240 bytes to G:/NEW.UF2
Everything seems fine so far... but as I check out the Serial Monitor, I receive a Memory error when the process reaches the code " conn.connect(server_addr, 3306, user, password) "
12:33:29.765 -> Connected to network
12:33:29.810 -> My IP address is: 192.168.0.159
12:33:29.810 -> Connecting to the database
12:33:29.810 -> ...trying...
12:33:31.116 -> Memory error.
12:33:32.481 -> Memory error.
12:33:32.481 -> Error: -1 = unSuccessfully connect!
I was originally trying to integrate the Max30102 module into my board, but after the error occurred, I uncommented the code associated with Max30102 and try it again. In the end, It turned out the same. In addition, I change the “server_addr” for the other MySQL server and restart Arduino IDE and nothing changed too. Perhaps the problem is derived from the hardware, the libraries, or the potentially incomplete uploading?

Send data from NodeMcu(ESP266) to ESP32 using esp now?

I am trying to send some data from a Nodemcu(esp8266) to ESP32. I am trying to use espnow for that purpose, but I am really stuck, I cant merge the Master and Slave for both the boards, I find the codes to be far different I tried some modifications and I can send data from the Nodemcu but can't receive it on the ESP32. I am trying to send two analog values for a Gesture control car.
The master code or the controller code running on the Nodemcu is given below
#include <ESP8266WiFi.h>
#include <espnow.h>
#define MUX_A D4
#define MUX_B D3
#define MUX_C D2
#define ANALOG_INPUT A0
#define CHANNEL 4
extern "C" {
}
uint8_t remoteMac[] = {0x24, 0x6F, 0x28, 0xB6, 0x24, 0x49};
struct __attribute__((packed)) DataStruct {
//char text[32];
int x;
int y;
unsigned long time;
};
DataStruct myData;
unsigned long lastSentMillis;
unsigned long sendIntervalMillis = 1000;
unsigned long sentMicros;
unsigned long ackMicros;
int xAxis;
int yAxis;
int zAxis;
void InitESPNow() {
WiFi.disconnect();
if (esp_now_init()==0) {
Serial.println("ESPNow Init Success");
}
else {
Serial.println("ESPNow Init Failed");
// Retry InitESPNow, add a counte and then restart?
// InitESPNow();
// or Simply Restart
ESP.restart();
}
}
void sendData() {
if (millis() - lastSentMillis >= sendIntervalMillis) {
lastSentMillis += sendIntervalMillis;
myData.time = millis();
uint8_t bs[sizeof(myData)];
memcpy(bs, &myData, sizeof(myData));
sentMicros = micros();
esp_now_send(NULL, bs, sizeof(myData)); // NULL means send to all peers
Serial.println("sent data");
Serial.println(myData.x);
Serial.println(myData.y);
}
}
void sendCallBackFunction(uint8_t* mac, uint8_t sendStatus) {
ackMicros = micros();
Serial.print("Trip micros "); Serial.println(ackMicros - sentMicros);
Serial.printf("Send status = %i", sendStatus);
Serial.println();
Serial.println();
}
void setup() {
Serial.begin(115200); Serial.println();
Serial.println("Starting EspnowController.ino");
WiFi.mode(WIFI_STA); // Station mode for esp-now controller
WiFi.disconnect();
Serial.printf("This mac: %s, ", WiFi.macAddress().c_str());
Serial.printf("slave mac: %02x%02x%02x%02x%02x%02x", remoteMac[0], remoteMac[1], remoteMac[2], remoteMac[3], remoteMac[4], remoteMac[5]);
Serial.printf(", channel: %i\n",CHANNEL);
InitESPNow();
esp_now_set_self_role(ESP_NOW_ROLE_CONTROLLER);
esp_now_add_peer(remoteMac, ESP_NOW_ROLE_SLAVE, CHANNEL, NULL, 0);
esp_now_register_send_cb(sendCallBackFunction);
Serial.print("Message ");
pinMode(MUX_A, OUTPUT);
pinMode(MUX_B, OUTPUT);
pinMode(MUX_C, OUTPUT);
Serial.println("Setup finished");
}
void changeMux(int c, int b, int a) {
digitalWrite(MUX_A, a);
digitalWrite(MUX_B, b);
digitalWrite(MUX_C, c);
}
void loop() {
changeMux(LOW, LOW, LOW);
xAxis = analogRead(ANALOG_INPUT); //Value of the sensor connected to pin 0 of IC
changeMux(LOW, LOW, HIGH);
yAxis = analogRead(ANALOG_INPUT); //Value of the sensor connected to pin 1 of IC
changeMux(LOW, HIGH, LOW);
zAxis = analogRead(ANALOG_INPUT); //Value of the sensor connected to pin 2 of IC
changeMux(LOW, HIGH, LOW);
myData.x= xAxis;
myData.y= yAxis;
sendData();
delay(500);
}
The slave code running on the ESP32 is given below
#include <esp_now.h>
#include <WiFi.h>
#include <esp_wifi.h>
#define CHANNEL 4
uint8_t mac[] = {0x36, 0x33, 0x33, 0x33, 0x33, 0x33};
struct __attribute__((packed)) DataStruct {
//char text[32];
int x;
int y;
unsigned long time;
};
DataStruct myData;
// Init ESP Now with fallback
void setup() {
Serial.begin(115200);
Serial.println("ESPNow/Basic/Slave Example");
//Set device in AP mode to begin with
WiFi.mode(WIFI_AP);
// configure device AP mode
// This is the mac address of the Slave in AP Mode
esp_wifi_set_mac(ESP_IF_WIFI_STA, &mac[0]);
Serial.print("AP MAC: "); Serial.println(WiFi.softAPmacAddress());
// Init ESPNow with a fallback logic
if (esp_now_init()!=0) {
Serial.println("*** ESP_Now init failed");
while(true) {};
}
// Once ESPNow is successfully Init, we will register for recv CB to
// get recv packer info.
esp_now_register_recv_cb(OnDataRecv);
Serial.print("Aheloiioi");
}
// callback when data is recv from Master
void OnDataRecv(const uint8_t *mac_addr, const uint8_t *data, int data_len) {
memcpy(&myData, data, sizeof(myData));
char macStr[18];
snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x",
mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);
Serial.print("Last Packet Recv from: "); Serial.println(macStr);
Serial.print("Last Packet Recv Data: "); Serial.println(myData.x); Serial.println(myData.y);
Serial.println("");
}
void loop() {
// Chill
}
This is the only output I get on the ESP32
ESPNow/Basic/Slave Example
AP MAC: 24:6F:28:B6:24:49
Aheloiioi
While this is the output on Nodemcu
Starting EspnowController.ino
This mac: BC:DD:C2:B5:E3:2B, slave mac: 246f28b62449, channel: 4
ESPNow Init Success
Message Setup finished
sent data
10
8
Trip micros 7320
Send status = 1
sent data
9
8
Trip micros 6817
Send status = 1
sent data
10
9
Trip micros 6731
Send status = 1
and it continues
If there are any other methods to send data, please do mention
I never use esp_now before so I didn't test it myself, but I think this has nothing to do with the library or esp32, it is just a minor mistake of c++ usage.
On your sendData() function of your esp8266, you did this:
uint8_t bs[sizeof(myData)];
memcpy(bs, &myData, sizeof(myData));
sentMicros = micros();
esp_now_send(NULL, bs, sizeof(myData));
The bs has a type of uint8_t and is an array, and you try to copy the data that has a type of struct myData into the array. And you then try to pass the array into the esp_now_send(). I quickly took a look at the esp_now_send() function prototype definition, the esp_now_send() need to pass in the address (which has a type of uint8_t) of your data structure myData.
I don't know know why you need to do the memcpy, but I think it will easier and simply to just directly pass in the pointer of myData into the function call.
void sendData() {
if (millis() - lastSentMillis >= sendIntervalMillis) {
lastSentMillis += sendIntervalMillis;
myData.time = millis();
esp_now_send(NULL, (uint8_t *)&myData, sizeof(myData)); // NULL means send to all peers
Serial.println("sent data");
Serial.println(myData.x);
Serial.println(myData.y);
}
}
Please let me know if this work?

ESP8266 Subscribe to AWS IOT topic

Hi I need to create a lambda function which will access the AWS thing and publish MQTT message, I'd like to get the published message on the ESP8266 which was connected to the thing as well, and controlled turn on/off the LED on ESP8266. So far I have uploaded the private.der, cert.der and ca.der to the ESP8266 absolutely, but it couldn't subscribed AWS IOT, please point me in the right tips then please share.
Code:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <ArduinoJson.h>
#define OUT_TOPIC "$aws/things/devices/shadow/update"
#define IN_TOPIC "$aws/things/devices/shadow/update/delta"
const char* ssid = "sid";
const char* password = "password";
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org");
const char* AWS_endpoint = "endpoint.amazonaws.com";//MQTT broker ip
const char* json = "{\"state\":{\"reported\":{\"led\":\"off\"}}}";
StaticJsonDocument<1024> doc;
WiFiClientSecure espClient;
PubSubClient mqttClient(espClient);//set MQTT port number to 8883 as per standard
PubSubClient client(AWS_endpoint, 8883, espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup_wifi() {
delay(10);// We start by connecting to a WiFi network
espClient.setBufferSizes(512, 512);
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());
timeClient.begin();
while(!timeClient.update()){
timeClient.forceUpdate();
}
espClient.setX509Time(timeClient.getEpochTime());
int qos = 0;//Maximum size of data that can be communicated
Serial.println(MQTT_MAX_PACKET_SIZE);
if(mqttClient.subscribe(IN_TOPIC, qos)){
Serial.println("Subscribed.");
Serial.println("Success!!");
}
deserializeJson(doc, json);
JsonObject obj = doc.as<JsonObject>();
if(mqttClient.publish(OUT_TOPIC, json)){
Serial.println("Published!!");
}
}
void setup() {
Serial.begin(115200);
Serial.setDebugOutput(true);
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
setup_wifi();
delay(1000);
if (!SPIFFS.begin()) {
Serial.println("Failed to mount file system");
return;
}
Serial.print("Heap: "); Serial.println(ESP.getFreeHeap());
//replace cert.crt eith your uploaded file name
File cert = SPIFFS.open("/cert.der", "r");
if (!cert) {
Serial.println("Failed to open cert file");
}
else
Serial.println("Success to open cert file");
delay(1000);
if (espClient.loadCertificate(cert))
Serial.println("cert loaded");
else
Serial.println("cert not loaded");
// Load private key file
File private_key = SPIFFS.open("/private.der", "r");//replace private eith your uploaded file name
if (!private_key) {
Serial.println("Failed to open private cert file");
}
else
Serial.println("Success to open private cert file");
delay(1000);
if (espClient.loadPrivateKey(private_key))
Serial.println("private key loaded");
else
Serial.println("private key not loaded");
// Load CA file
File ca = SPIFFS.open("/ca.der", "r");
//replace ca eith your uploaded file name
if (!ca) {
Serial.println("Failed to open ca ");
}
else
Serial.println("Success to open ca");
delay(1000);
if(espClient.loadCACert(ca))
Serial.println("ca loaded");
else
Serial.println("ca failed");
Serial.print("Heap: ");
Serial.println(ESP.getFreeHeap());
}
void callback (char* topic, byte* payload, unsigned int length) {
Serial.println("Received. topic=");
Serial.println(topic);
char subsc[length];
for(int i=0; i<length; i++){
subsc [i]=(char)payload[i];
subsc [length]='\0';
Serial.print(subsc);
}
Serial.print("\n");
digitalWrite(LED_BUILTIN, HIGH);
}
void mqttLoop() {
mqttClient.loop();
delay(100);
//digitalWrite(LED_pin, LOW);
digitalWrite(LED_BUILTIN, LOW);
Serial.print(".");
}
void loop() {
It looks like you're using the older forms of WiFiClientSecure certificate handling. I'll assume that's working OK and you're able to establish an SSL connection.
Your IN_TOPIC needs to be updated slightly to: $aws/things/<name-of-your-thing>/shadow/update/accepted (where hopefully you know what <name-of-your-thing> is). You can get this from the thing shadow on your AWS console.
Similarly AWS_endpoint needs updating: it should be of the form <random-stuff-specific-to-you>.iot.<region>.amazonaws.com. You can also find it from the same place as the MQTT topics.
You only want one instance of PubSubClient. I'll assume you delete client and keep mqttClient. You'll need to update the instantiation to include the AWS endpoint and port as you have done for client.
Before calling mqttClient.subscribe(...) you need to register the callback:
mqttClient.setCallback(::callback);
then connect to AWS:
mqttClient.connect("some-unique-name");
Finally, you need to edit PubSubClient.h (look for it in Arduino/libraries/PubSubClient/src) to update MQTT_MAX_PACKET_SIZE. The default is 128 and I've found that too small with AWS's messages. I've made mine 1024:
#define MQTT_MAX_PACKET_SIZE 1024
and that appears ample.
Once that compiles and runs you'll start seeing callback(...) called with the topics you've subscribed to and you can implement the function to do whatever you need.
The PubSubClient doesn't do much error reporting to help diagnose what's going on. I'm currently refactoring it a bit and including more diagnostic information and will eventually issue a pull request. Let me know if you'd like my hacked version before I get that far.

fatal error: ESP8266WiFi.h: No such file or directory

I'm trying to make a "home weight" with my ESP32 and display the value using IBMCloud, however I'm running into some issues with the Arduino IDE and my code.
I get this error:
Arduino:1.8.5 (Windows 10), Tarjeta:"ESP32 Dev Module, QIO, 80MHz, 4MB (32Mb), 921600, None"
C:\Users\XX\Documents\Arduino\IBM_Watson_Connect\IBM_Watson_Connect.ino:8:25: fatal error: ESP8266WiFi.h: No such file or directory
compilation terminated.
exit status 1
Compiling error for the ESP32 Dev Module card.
I'm using a ESP32 dev board. My code is this:
#include <ESP8266WiFi.h>
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient/releases/tag/v2.3
#include "HX711.h" //Load Cell Amplifier
HX711 cell(D2, D4); //Amplifier is connected to these pins on the NodeMCU ESP8266 Board
#define WLAN_SSID "XXXXX"
#define WLAN_PASS "XXXXX"
#define ORG "XXXXX"
#define DEVICE_TYPE "XXXXXX"
#define DEVICE_ID "XXXXX"
#define TOKEN "XXXXXXXX"
char server[] = ORG ".messaging.internetofthings.ibmcloud.com";
char topic[] = "iot-2/evt/status/fmt/json";
char authMethod[] = "use-token-auth";
char token[] = TOKEN;
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;
WiFiClient wifiClient;
PubSubClient client(server, 1883, NULL, wifiClient);
void setup() {
Serial.begin(115200);
Serial.println();
// Connect to WiFi access point.
Serial.println(); Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: "); Serial.println(WiFi.localIP());
}
int counter = 0;
void loop() {
if (!!!client.connected()) {
Serial.print("Reconnecting client to ");
Serial.println(server);
while (!!!client.connect(clientId, authMethod, token)) {
Serial.print(".");
delay(500);
}
Serial.println();
}
//----------Get data from load cell and amplifier
long valCalibrated = 0;
long val = 0;
float count = 0;
count = count + 1;
val = 0.5 * val + 0.5 * cell.read();
valCalibrated = (val - 4137240) / 234.20;
//----------Send data to IBM Waton IoT Service
String payload = "{\"d\":{\"weight\":";
payload += valCalibrated;
payload += "}}";
Serial.print("Sending payload: ");
Serial.println(payload);
if (client.publish(topic, (char*) payload.c_str())) {
Serial.println("Publish ok");
} else {
Serial.println("Publish failed");
}
++counter;
delay(100); //adjust delay to send more or less reads per unit time
}
Some places mentioned that the library was missing, that the board wasn't properly selected, the library wasn't updated.. I checked them all.. Arduino is updated, libraries are installed and updated, proper board is selected (I actually have tried all the other Esp32 related boards with the same result)
You're building a program for the ESP32, not the ESP8266. There are a lot of similarities but they're entirely different chips with different software.
So you don't use ESP8266WiFi.h with the ESP32. On the ESP32, the header file is just called WiFi.h (keeping more in line with WiFi support on Arduinos - the ESP32 Arduino Core is intended to be more compatible with the normal Arduino Core than the ESP8266 version was).
You need to
#include <WiFi.h>
instead of ESP8266WiFi.h
You can find the code for these files in the official repository for the Arduino SDK for the ESP32.
(It doesn't help that WiFi.h for the ESP32 identifies itself as ESP8266.h in its own comments...)

arduino uno + wifishield cannot connect bluemix using token

I have arduino uno + wifishield and if fails to connect to Bluemix. It gives this error:
"Closed connection from 194.228.11.222. The operation is not authorized."
Any idea why the connection gets kicked out? What operation is not authorized?
Thanks for any idea ;)
======
Here is the code:
#include <SPI.h>
#include <Ethernet.h>
#include <WiFi.h>
#include <WifiIPStack.h>
#include <IPStack.h>
#include <Countdown.h>
#include <MQTTClient.h>
#define MQTT_MAX_PACKET_SIZE 100
#define SIZE 100
#define MQTT_PORT 1883
#define PUBLISH_TOPIC "iot-2/evt/status/fmt/json"
#define SUBSCRIBE_TOPIC "iot-2/cmd/+/fmt/json"
#define USERID "use-token-auth"
#define CLIENT_ID "d:6735ra:hlinoponie:petasek"
#define MS_PROXY "6735ra.messaging.internetofthings.ibmcloud.com"
#define AUTHTOKEN “xxxxx”
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0xD6, 0x8F };
WiFiClient c;
IPStack ipstack(c);
MQTT::Client<IPStack, Countdown, 100, 1> client = MQTT::Client<IPStack, Countdown, 100, 1>(ipstack);
String deviceEvent;
char ssid[] = “XXXXX”; // your network SSID (name)
char pass[] = “XXXXX”; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
void setup() {
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while (true);
}
String fv = WiFi.firmwareVersion();
if ( fv != "1.1.0" )
Serial.println("Please upgrade the firmware");
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
// wait 5 seconds for connection:
delay(5000);
}
// you're connected now, so print out the data:
Serial.print("Hooray!!! You're connected to the network\n");
}
void loop() {
float tep = mojeDHT.readTemperature();
float vlh = mojeDHT.readHumidity();
int rc = -1;
if (!client.isConnected()) {
Serial.println("Connecting to Watson IoT Foundation ...");
rc = ipstack.connect((char*)MS_PROXY, MQTT_PORT);
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
data.MQTTVersion = 3;
data.clientID.cstring = (char*)CLIENT_ID;
data.username.cstring = (char*)USERID;
data.password.cstring = (char*)AUTHTOKEN;
data.keepAliveInterval = 60;
rc = -1;
while ((rc = client.connect(data)) != 0) {
Serial.println("rc=");
Serial.println(rc);
delay(2000);
}
Serial.println("Connected successfully\n");
// Serial.println("Temperature(in C)\tDevice Event (JSON)");
Serial.println("____________________________________________________________________________");
}
Serial.println("\n");
MQTT::Message message;
message.qos = MQTT::QOS0;
message.retained = false;
deviceEvent = String("{\"d\":{\"myName\":\"Arduino Uno\",\"temperature\":");
char buffer[60];
// convert double to string
dtostrf(getTemp(),1,2, buffer);
deviceEvent += buffer;
deviceEvent += "}}";
Serial.print("\t");
Serial.print(buffer);
Serial.print("\t\t");
deviceEvent.toCharArray(buffer, 60);
Serial.println(buffer);
message.payload = buffer;
message.payloadlen = strlen(buffer);
rc = client.publish(PUBLISH_TOPIC, message);
if (rc != 0) {
Serial.print("return code from publish was ");
Serial.println(rc);
}
client.yield(5000);
}
/*
This function is reproduced as is from Arduino site => http://playground.arduino.cc/Main/InternalTemperatureSensor
*/
double getTemp(void) {
unsigned int wADC;
double t;
ADMUX = (_BV(REFS1) | _BV(REFS0) | _BV(MUX3));
ADCSRA |= _BV(ADEN); // enable the ADC
delay(20); // wait for voltages to become stable.
ADCSRA |= _BV(ADSC); // Start the ADC
// Detect end-of-conversion
while (bit_is_set(ADCSRA,ADSC));
// Reading register "ADCW" takes care of how to read ADCL and ADCH.
wADC = ADCW;
// The offset of 324.31 could be wrong. It is just an indication.
t = (wADC - 324.31 ) / 1.22;
// The returned temperature is in degrees Celcius.
return (t);
}
It might be the case your organizations is configured to block non-secure connections (since you are using port 1883). Check the step 5 on this recipe
https://developer.ibm.com/recipes/tutorials/connect-an-arduino-uno-device-to-the-ibm-internet-of-things-foundation/
I noticed this error in the log: The topic is not valid: Topic="lwt" ClientID="d:6735ra:hlinoponie:petasek" Reason="The topic does not match an allowed rule".
I didn't see that topic listed in your code, but you may want to check to see how that may be getting set as topic.

Resources