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?
Related
I have an ESP8266 that connects to WiFi and then calls an NTP server to get the time. Originally, I had set up the WiFi connection to work off a "config.h" file with SSID and password - the vanilla approach. Later, I set up a WiFi Manager with the AsyncWebServer library to avoid hardcoding credentials as shown in this tutorial by Rui Santos .
Now the user enters WiFi credentials on a web-page hosted by the ESP8266 which provides a Wireless Access Point. These credentials are stashed away in files on the local file-system (LittleFS) and accessed when making the WiFi connection from that point onwards. Upon connecting, the ESP8266 runs a web-server that hosts a static web-page.
This works fine and the ESP8266 connects to WiFi BUT the NTP service no longer works! I get a fixed time ~ 12:00 midnight from the NTP client. When I revert to connecting to WiFi the vanilla way, the NTP service works as expected.
Here is my code for making the WiFi connection in station mode. The class GuruWebServer has methods initializeaLittle(), readaLittle() and writeaLittle() for file-system operations. The key method, initializeWiFi(), returns true when connection is successfully made with the credentials stashed away in the file-system and returns false otherwise. The method has a loop with millis() in which the attempt to connect to WiFi is made until timeout (e.g. 60s).
I observe that the SSID and password are correctly recorded and WiFi connection is successfully made. Subsequently, using LanScan (on Mac), I can see the ESP8266 at the station IP address as configured. Using a browser, I can load the web-page it serves. However, I am no longer able to get the time-and-date from calling the NTP service.
bool GuruWebServer::initializeWiFi() {
/*
* Make WiFi connection when SSID and PWD are available
* and set up station for web-service.
*/
// Initialize LittleFS
this->initializeaLittle();
// Connect to WiFi
this->readaLittle(&SSID, Path2_SSID);
this->readaLittle(&PWD, Path2_PWD);
this->readaLittle(&IP, Path2_IP);
this->readaLittle(&Gateway, Path2_Gateway);
String conn_ack = (String)"SSID <" + SSID + "> | PWD <" + PWD + "> | IP <" + IP + "> | Gateway <" + Gateway + ">";
if (SSID == "" || PWD == "") { // Files not populated!
Serial.println("Found NO SSID or PWD!");
return false;
}
WiFi.mode(WIFI_STA);
localIP.fromString(IP.c_str());
localGateway.fromString(Gateway.c_str());
if (!WiFi.config(localIP, localGateway, subnet)) {
Serial.println("Configured NO station!");
return false;
}
WiFi.begin(SSID, PWD);
unsigned long _now = millis();
unsigned long _then = _now; // Marker for ticker
unsigned long _stop = _now; // Marker for timeout
unsigned long delta_minor = 0; // Time since last tick
unsigned long delta_major = 0; // Time since start
while (WiFi.status() != WL_CONNECTED) {
_now = millis();
delta_minor = _now - _then; // Time since last tick
delta_major = _now - _stop; // Time since start
if (delta_minor > 1000) { // Mark time and reset delta
_then = _now;
Serial.print (".");
}
if (delta_major > 60000) { // Stop attempting connection
String timely = (String)"Now " + _now + " Stop " + _stop + " Diff " + delta_major;
Serial.println(timely);
Serial.println("Made NO WiFi connection!");
return false; // Exit false
} // end IF
} // end WHILE WiFi
Serial.println(WiFi.localIP());
return true;
}
To get time, I have used NTPClient library in the main program as follows:
#include <NTPClient.h>
#include <WiFiUdp.h>
WiFiUDP NTP_UDP;
NTPClient timeClient(NTP_UDP, "us.pool.ntp.org");
and in the setup() function of "main.cpp", I have:
// Connect to the NTP client
delay(500);
timeClient.begin();
timeClient.setTimeOffset(-18000); // Central time GMT-5 ~ -5 x 3600
timeClient.update();
Serial.println(timeClient.getFormattedTime());
The github branch rev007 has the code with WiFi Manager and rev006 has the vanilla WiFi.
I have tried the following:
Used a different approach to get time on ESP8266 with "time.h" and configTime() function.
Configured the web-server to use a port other than 80 (e.g. 8211) in AsyncWebServer server(80);.
Grateful for any help figuring this out, thank you.
UPDATE
I have simplified the code to illustrate the problem. This single script sets up the ESP8266 as WiFi station. The device connects to WiFi successfully but is unsuccessful calling the NTP service.
#include <Arduino.h>
#include <time.h>
#include "LittleFS.h"
#include <ESP8266WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
WiFiUDP NTP_UDP;
NTPClient timeClient(NTP_UDP, "pool.ntp.org");
// Alt.
#include "config.h"
IPAddress localIP;
IPAddress localGateway;
IPAddress subnet(255, 255, 255, 0);
void setup() {
Serial.begin(9600);
WiFi.mode(WIFI_STA);
// Comment out from here --->
localIP.fromString(IP);
localGateway.fromString(Gateway);
if (!WiFi.config(localIP, localGateway, subnet)) {
Serial.println("Configured NO station!");
}
// <--- upto here!
WiFi.begin(SSID, PWD);
unsigned long _now = millis();
unsigned long _then = _now; // Marker for ticker
unsigned long _stop = _now; // Marker for timeout
unsigned long delta_minor = 0; // Time since last tick
unsigned long delta_major = 0; // Time since start
while (WiFi.status() != WL_CONNECTED) {
_now = millis();
delta_minor = _now - _then; // Time since last tick
delta_major = _now - _stop; // Time since start
if (delta_minor > 1000) { // Mark time and reset delta
_then = _now;
Serial.print (".");
}
if (delta_major > 60000) { // Stop attempting connection
String timely = (String)"Now " + _now + " Stop " + _stop + " Diff " + delta_major;
Serial.println(timely);
Serial.println("Made NO WiFi connection!");
} // end IF
} // end WHILE WiFi
Serial.println(WiFi.localIP());
// Connect to the NTP client
delay(3000);
timeClient.begin();
timeClient.setTimeOffset(-18000); // Central time GMT-5 ~ -5 x 3600
delay(3000);
timeClient.update();
Serial.println(timeClient.getFormattedTime());
}
void loop() {
// put your main code here, to run repeatedly:
}
When I comment out the code as shown so as not to configure the IP address from settings but let it be determined at run-time, then all is well.
I'm curious enough to try your code. The issue is without the proper DNS setup, the NTP(UDP) won't be able to resolve the NTP name "pool.ntp.org", I tested your code with slightly modification and simplification. Without specifying the DNS with WiFi.config(localIP, localGateway, subnet), the timeClient.update() simply can't establish a NTP connection, by adding a DNS IP to WiFi.config(localIP, localGateway, subnet, dns), the following code works like a charm.
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
WiFiUDP NTP_UDP;
NTPClient timeClient(NTP_UDP, "pool.ntp.org");
#include "config.h"
IPAddress localIP(192, 168, 0, 120); // my local ip
IPAddress localGateway(192, 168, 0, 1); // my local gateway
IPAddress subnet(255, 255, 255, 0);
IPAddress dns(1, 1, 1, 1); // CloudFlare DNS server
void setup() {
Serial.begin(9600);
while (!Serial);
WiFi.mode(WIFI_STA);
WiFi.begin(SSID, PWD);
WiFi.config(localIP, localGateway, subnet, dns);
int count = 0;
while (WiFi.status() != WL_CONNECTED) {
delay(500);
if (count++ > 20) ESP.restart(); //timeout, reboot
}
Serial.println(WiFi.localIP());
// Connect to the NTP client
timeClient.begin();
timeClient.setTimeOffset(8*3600); //my timezone
if (timeClient.update())
Serial.println(timeClient.getFormattedTime());
}
void loop() {
}
If you want using WiFiManager just leave wifiManager.setSTAStaticIPConfig and use this after wifiManager.autoConnect
WiFi.begin();
WiFi.config(IPAddress(192, 168, 1, 148), IPAddress(192, 168, 1, 1), IPAddress(192, 168, 1, 1), IPAddress(255, 255, 255, 0));
It working for me on ESP8266.
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.
Please i wish somebody could help me with this. I've been struggling into it since a couple of weeks, i am so new to that.
I want to send data from ESP32 SIM800L to a mqtt broker.
The mqtt server is running on my local machine and the ESP32 SIM800 can perfectly connect to APN.
I saw many tutorials doing it with WIFI connection but not GPRS(what i am using).
I finally find this: tinyGSM and this :arduino mqtt mongodb
And i adapted it as follows, but still getting connection failed:
// Your GPRS credentials (leave empty, if not needed)
const char apn[] = "internet.tn"; // APN (example: internet.vodafone.pt) use https://wiki.apnchanger.org
const char gprsUser[] = ""; // GPRS User
const char gprsPass[] = ""; // GPRS Password
// SIM card PIN (leave empty, if not defined)
const char simPIN[] = "";
uint32_t lastReconnectAttempt = 0;
// TTGO T-Call pins
#define MODEM_RST 5
#define MODEM_PWKEY 4
#define MODEM_POWER_ON 23
#define MODEM_TX 27
#define MODEM_RX 26
#define I2C_SDA 21
#define I2C_SCL 22
// Set serial for debug console (to Serial Monitor, default speed 115200)
#define SerialMon Serial
// Set serial for AT commands (to SIM800 module)
#define SerialAT Serial1
// Configure TinyGSM library
#define TINY_GSM_MODEM_SIM800 // Modem is SIM800
#define TINY_GSM_RX_BUFFER 1024 // Set RX buffer to 1Kb
#include <Wire.h>
#include <TinyGsmClient.h>
#include <PubSubClient.h>
#ifdef DUMP_AT_COMMANDS
#include <StreamDebugger.h>
StreamDebugger debugger(SerialAT, SerialMon);
TinyGsm modem(debugger);
#else
TinyGsm modem(SerialAT);
#endif
// I2C for SIM800 (to keep it running when powered from battery)
TwoWire I2CPower = TwoWire(0);
const char* broker = "localhost";
const char* topicInit = "GsmClientTest/init";
// Function prototypes
void subscribeReceive(char* topic, byte* payload, unsigned int length);
// TinyGSM Client for Internet connection
// gsm and MQTT related objects
TinyGsmClient client(modem);
PubSubClient mqtt(client);
long mqtttimer = 0; // Timer for counting 5 seconds and retrying mqtt connection
byte mqtttarea = 1;
#define uS_TO_S_FACTOR 1000000 /* Conversion factor for micro seconds to seconds */
#define TIME_TO_SLEEP 3600 /* Time ESP32 will go to sleep (in seconds) 3600 seconds = 1 hour */
void mqttCallback(char* topic, byte* payload, unsigned int len) {
SerialMon.print("Message arrived [");
SerialMon.print(topic);
SerialMon.print("]: ");
SerialMon.write(payload, len);
SerialMon.println();}
boolean mqttConnect() {
SerialMon.print("Connecting to ");
SerialMon.print(broker);
// Connect to MQTT Broker
boolean status = mqtt.connect("GsmClientTest");
// Or, if you want to authenticate MQTT:
//boolean status = mqtt.connect("GsmClientName", "mqtt_user", "mqtt_pass");
if (status == false) {
SerialMon.println(" fail");
return false;
}
SerialMon.println(" success");
mqtt.publish(topicInit, "GsmClientTest started");
// mqtt.subscribe(topicLed);
return mqtt.connected();}
void setup() {
SerialMon.begin(9600);
// Start I2C communication
I2CPower.begin(I2C_SDA, I2C_SCL, 400000);
// Set modem reset, enable, power pins
pinMode(MODEM_PWKEY, OUTPUT);
pinMode(MODEM_RST, OUTPUT);
pinMode(MODEM_POWER_ON, OUTPUT);
digitalWrite(MODEM_PWKEY, LOW);
digitalWrite(MODEM_RST, HIGH);
digitalWrite(MODEM_POWER_ON, HIGH);
// Set GSM module baud rate and UART pins
SerialAT.begin(9600, SERIAL_8N1, MODEM_RX, MODEM_TX);
delay(3000);
// Restart SIM800 module, it takes quite some time
// To skip it, call init() instead of restart()
SerialMon.println("Initializing modem...");
modem.restart();
// use modem.init() if you don't need the complete restart
// Unlock your SIM card with a PIN if needed
if (strlen(simPIN) && modem.getSimStatus() != 3 ) {
modem.simUnlock(simPIN);
}
SerialMon.print("Connecting to APN: ");
SerialMon.print(apn);
if (!modem.gprsConnect(apn, gprsUser, gprsPass)) {
SerialMon.println(" fail");
}
else {
SerialMon.println(" OK");
}
// MQTT Broker setup
mqtt.setServer(broker, 1883);
mqtt.setCallback(mqttCallback);
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
}
void loop() {
// This is needed at the top of the loop!
if (!mqtt.connected()) {
SerialMon.println("=== MQTT NOT CONNECTED ===");
// Reconnect every 10 seconds
uint32_t t = millis();
if (t - lastReconnectAttempt > 10000L) {
lastReconnectAttempt = t;
if (mqttConnect()) {
lastReconnectAttempt = 0;
}
}
delay(100);
return;
}
mqtt.publish(topicInit, "Hello");
mqtt.loop();
}
You set the broker's name to localhost:
const char* broker = "localhost";
localhost and the IP address 127.0.0.1 mean "the host that this code is running on". When you're typing commands on the computer running the broker, localhost will mean that computer. There's no way it will work on the ESP32.
You need to name or IP address of the computer running the broker. How you find that will depend on the operating system you're running.
If that computer is on your local network it's probably using a private IP address like 10.0.1.x or 192.168.1.x. If that's the case you'll need to either use port forwarding in your router to forward packets to it (and then you'll use your router's IP address and not your broker's).
If you're using your router's IP address, that can change without warning, so you'll need to use something like Dynamic DNS to keep up to date with its current IP address.
You'll likely be better off running the broker outside of your network on a cloud-based virtual server or by using one of the several commercial MQTT services out there. Most of them have a free tier which will allow a reasonable amount of traffic per month.
Regardless, localhost will never work here. You need the real, public IP address or name of your broker.
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...)
Background:
I am trying to upload data from a simple on off sensor to learn the Xively methods. I am using an Arduino Uno with a WiFi Shield. I made some simple alterations to an example sketch from the Xively library to keep it very simple. I have read the documentation and the FAQ's plus searched the web. There was a similar question (Can't connect to Xively using Arduino + wifi shield, "ret = -1 No sockets available) and the answer was to reduce the number of libraries loaded. I'm using the same library list recommended in that post.I have also updated my Arduino IDE and downloaded the latest xively and HTTP library. The code compiles without error. I re-loaded my device on the xively website and got a new API key and number as well. Plus, I ensured the channel was added with the correct sensor name. I have also checked my router and ensured the WiFi shield was connecting properly.
Problem: I can't see the data on the Xively website and I keep getting the following error messages on the serial monitor from the Arduino:
xivelyclint.put returned -1
also, after several tries, I get "No socket available"
Question: Is there an problem with the code or is it something else?
Current Arduino code (actual ssid, password and API key and number removed):
#include <SPI.h>
#include <WiFi.h>
#include <HttpClient.h>
#include <Xively.h>
char ssid[] = "ssid"; // your network SSID (name)
char pass[] = "password"; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
// Your Xively key to let you upload data
char xivelyKey[] = "api_key";
// Analog pin which we're monitoring (0 and 1 are used by the Ethernet shield)
int sensorPin = 2;
// Define the strings for our datastream IDs
char sensorId[] = "sensor_id";
XivelyDatastream datastreams[] = {
XivelyDatastream(sensorId, strlen(sensorId), DATASTREAM_INT),
};
// Finally, wrap the datastreams into a feed
XivelyFeed feed(feed no., datastreams, 1 /* number of datastreams */);
WiFiClient client;
XivelyClient xivelyclient(client);
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Starting single datastream upload to Xively...");
Serial.println();
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected to wifi");
printWifiStatus();
}
void loop() {
int sensorValue = digitalRead(sensorPin);
datastreams[0].setInt(sensorValue);
Serial.print("Read sensor value ");
Serial.println(datastreams[0].getInt());
Serial.println("Uploading it to Xively");
int ret = xivelyclient.put(feed, xivelyKey);
Serial.print("xivelyclient.put returned ");
Serial.println(ret);
Serial.println();
delay(15000);
}