Thinger.IO client setup for GPRS enabled ESP32 project - arduino

I've been using the Thinger.io platform for some of my IoT projects (mostly ESP8266 modules) for quite a long time now. The way I implemented it is something similar to that:
#include <ThingerESP8266.h>
#include <ESP8266WIFI.h>
#define USERNAME "username"
#define DEVICE_ID "deviceid"
#define DEVICE_CREDENTIAL "devicecredential"
ThingerESP8266 thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL);
void connectToWifi() {
...
}
void setup() {
connectToWifi();
}
void loop() {
thing.handle();
}
and it just works. It is good to also mention that I've been using WiFi all the way.
Now I am trying to achieve the same by taking advantage of a controller called TTGO T-Call ESP32. It is GPRS enabled (using the TinyGsmClient.h) and I have inserted a SIM card inside of it which successfully connects to the internet. The issue is that I can not really establish a connection to the Thinger.io platform where my devices are hosted. This is what my code looks like (making a reference to this library example)
// Your GPRS credentials (leave empty, if not needed)
const char apn[] = ""; // 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[] = "";
// 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
// Define the serial console for debug prints, if needed
//#define DUMP_AT_COMMANDS
#include <Wire.h>
#include <TinyGsmClient.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);
// TinyGSM Client for Internet connection
TinyGsmClient client(modem);
#define uS_TO_S_FACTOR 1000000UL /* Conversion factor for micro seconds to seconds */
#define TIME_TO_SLEEP 3600 /* Time ESP32 will go to sleep (in seconds) 3600 seconds = 1 hour */
#define IP5306_ADDR 0x75
#define IP5306_REG_SYS_CTL0 0x00
bool setPowerBoostKeepOn(int en){
I2CPower.beginTransmission(IP5306_ADDR);
I2CPower.write(IP5306_REG_SYS_CTL0);
if (en) {
I2CPower.write(0x37); // Set bit1: 1 enable 0 disable boost keep on
} else {
I2CPower.write(0x35); // 0x37 is default reg value
}
return I2CPower.endTransmission() == 0;
}
void connectToApn(){
SerialMon.println("Connecting to: internet.vivacom.bg ... ");
while(!modem.gprsConnect(apn, gprsUser, gprsPass))
delay(500);
SerialMon.println("Successfully connected to: internet.vivacom.bg");
}
// #include <ThingerCore32.h> => ArduinoJson.h: No such file or directory
// #include <ThingerESP8266.h> => ESP8266WiFi.h : No such file or directory
#define USERNAME ""
#define DEVICE_ID ""
#define DEVICE_CREDENTIAL ""
#include <ThingerESP32.h>
ThingerESP32 thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL);
//#include "arduino_secrets.h"
// Server details
const char server[] = "vsh.pp.ua";
const char resource[] = "/TinyGSM/logo.txt";
const int port = 80;
#include <ArduinoHttpClient.h>
HttpClient http(client, server, port);
void setup() {
// Set serial monitor debugging window baud rate to 115200
SerialMon.begin(115200);
// Start I2C communication
I2CPower.begin(I2C_SDA, I2C_SCL, 400000);
// Keep power when running from battery
bool isOk = setPowerBoostKeepOn(1);
SerialMon.println(String("IP5306 KeepOn ") + (isOk ? "OK" : "FAIL"));
// 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(115200, 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();
// Unlock your SIM card with a PIN if needed
if (strlen(simPIN) && modem.getSimStatus() != 3 ) {
modem.simUnlock(simPIN);
}
// Configure the wake up source as timer wake up
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
// Connect to APN
connectToApn();
}
void loop() {
thing.handle();
SerialMon.println("In the loop ...");
delay(3000);
SerialMon.print(F("Performing HTTP GET request... "));
int err = http.get(resource);
if (err != 0) {
SerialMon.println(F("failed to connect"));
delay(10000);
return;
}
int status = http.responseStatusCode();
SerialMon.print(F("Response status code: "));
SerialMon.println(status);
if (!status) {
delay(10000);
return;
}
SerialMon.println(F("Response Headers:"));
while (http.headerAvailable()) {
String headerName = http.readHeaderName();
String headerValue = http.readHeaderValue();
SerialMon.println(" " + headerName + " : " + headerValue);
}
int length = http.contentLength();
if (length >= 0) {
SerialMon.print(F("Content length is: "));
SerialMon.println(length);
}
if (http.isResponseChunked()) {
SerialMon.println(F("The response is chunked"));
}
String body = http.responseBody();
SerialMon.println(F("Response:"));
SerialMon.println(body);
SerialMon.print(F("Body length is: "));
SerialMon.println(body.length());
// Put ESP32 into deep sleep mode (with timer wake up)
// esp_deep_sleep_start();
}
NOTE: The board I've picked from the Arduino IDE is called ESP32 Wrover Module

It would be better if you ask this question on the thinger community, the thinger.io https://community.thinger.io/ where the thinger devs or community will be listening.
I have some working code, see below, this works with SIM7000E, but it should work OK with SIM800 the code should work the same. I have noticed that you are not using the thinger library (ThingerTinyGSM.h) and this is probably why the device isn't connecting to thinger.
#define THINGER_SERIAL_DEBUG //This will provide debug messages of what thinger
code is trying to do
#define _DISABLE_TLS_ //TLS needs to be disabled if using ESP32 (not sure why, this is a known bug)
// Select your modem:
//#define TINY_GSM_MODEM_SIM800 //Note SimCom docs state that SIM7000e used same commands as SIM800
#define TINY_GSM_MODEM_SIM7000 //Note SimCom docs state that SIM7000e used same commands as SIM800
#define APN_NAME "..."
#define APN_USER "..."
#define APN_PSWD "..."
//Pins for connecting to SIM module using 2nd Serial connection
#define RXD1 16
#define TXD1 17
#include <TinyGsmClient.h>
#include <ThingerTinyGSM.h>
//Thinger credentials
#define USERNAME "...." //Thinger Account User Name
#define DEVICE_ID "...." //Thinger device IC
#define DEVICE_CREDENTIAL "...." //Thinger device credential (password)
ThingerTinyGSM thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL, Serial2);
/*******************************
**** SET-UP **** SET-UP ****
********************************/
void setup() {
// open serial for debugging
Serial.begin(115200);
Serial2.begin(115200, SERIAL_8N1, RXD1, TXD1);
delay(1000);
Serial.println(); Serial.println();
Serial.println("Starting Thinger GSM Test");
delay(1000);
// set APN, you can remove user and password from call if your apn does not require them
thing.setAPN(APN_NAME, APN_USER, APN_PSWD);
////// Thinger resource output example (i.e. reading a sensor value)
thing["Status"] >> [](pson & out) {
out["Timer(ms)"] = millis();
out["device"] = String(DEVICE_ID);
};
}
void loop() {
thing.handle();
}

This is the code which worked for me:
const char apn[] = ""; // 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[] = "";
// 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>
TinyGsm modem(SerialAT);
// TinyGSM Client for Internet connection
TinyGsmClient client(modem);
void connectToApn(){
SerialMon.println("Connecting to: internet.vivacom.bg ... ");
while(!modem.gprsConnect(apn, gprsUser, gprsPass))
delay(500);
SerialMon.println("Successfully connected to: internet.vivacom.bg");
}
#define USERNAME ""
#define DEVICE_ID ""
#define DEVICE_CREDENTIAL ""
#include <ThingerTinyGSM.h>
ThingerTinyGSM thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL, Serial1);
void setup() {
// Set serial monitor debugging window baud rate to 115200
SerialMon.begin(115200);
// 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(115200, 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();
// Unlock your SIM card with a PIN if needed
if (strlen(simPIN) && modem.getSimStatus() != 3 ) {
modem.simUnlock(simPIN);
}
// Connect to APN
connectToApn();
}
void loop() {
thing.handle();
}

Related

Arduino sending UID data to a real-time database via Firebase

Hello and thank you for your time,
I am having issues with sending data to my real-time Firebase database. When I do send the data, it constantly only returns a 10 value instead of my UID. This is my code
#include <WiFi.h>
#include <FirebaseESP32.h>
#include <SPI.h>
#include <MFRC522.h>
#define FIREBASE_HOST "https://matt-rfid-default-rtdb.asia-southeast1.firebasedatabase.app/" //Paste you Realtime database url here
#define FIREBASE_AUTH "AIzaSyBZ3dtXOSlsLBZ0PbytXflmJv2laqfqMD8" ///// <---- Paste your API key here
#define WIFI_SSID "Sharma Home"
#define WIFI_PASSWORD "0162229410p"
#define RST_PIN 4 // Configurable, see typical pin layout above
#define SS_PIN 5 // Configurable, see typical pin layout above
MFRC522 rfid(SS_PIN, RST_PIN);
FirebaseData firebaseData;
FirebaseJson json;
MFRC522::MIFARE_Key key;
void setup()
{
Serial.begin(115200);
SPI.begin(); // Init SPI bus
rfid.PCD_Init(); // Init MFRC522
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
Firebase.reconnectWiFi(true);
Serial.println("Tap an RFID/NFC tag on the RFID-RC522 reader");
}
void loop()
{
//json.set("/one", Sdata);
if (rfid.PICC_IsNewCardPresent())
{ // new tag is available
if (rfid.PICC_ReadCardSerial())
{ // NUID has been readed
Serial.print("UID:");
for (int i = 0; i < rfid.uid.size; i++)
{
Firebase.updateNode(firebaseData,"/CARD ID NO:",json);
Serial.print(rfid.uid.uidByte[i], DEC);
//int sData = (rfid.uid.uidByte[i], DEC);
//json.set("/UID" + (rfid.uid.uidByte[i], DEC));
}
Serial.println();
rfid.PICC_HaltA(); // halt PICC
rfid.PCD_StopCrypto1(); // stop encryption on PCD
}
}
}
I want to receive the UID values in my database.

TTGO ESP32 + GSM 800l AT Commands

Good day all
I'm working on a project that takes sensor data and sends it to an online database using HTTP requests.Im ussing the TTGO esp32 sim 800 board, Everything works fine and all the data is stored in my online database the problem is that I cant get the AT commands to work, I need the Signal strength, battery voltage, and amount of Data available on the sim card.
Can someone please assist with this matter?
kind regards Hansie
Code
#include <HCSR04.h>
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
// 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
// Define the serial console for debug prints, if needed
//#define DUMP_AT_COMMANDS
#include <Wire.h>
#include <TinyGsmClient.h>
#define uS_TO_S_FACTOR 1000000UL /* Conversion factor for micro seconds to seconds */
#define TIME_TO_SLEEP 36 /* Time ESP32 will go to sleep (in seconds) 3600 seconds = 1 hour */
#define IP5306_ADDR 0x75
#define IP5306_REG_SYS_CTL0 0x00
// 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
int deviceID=101;
const int trigPin = 5;
const int echoPin = 18;
//Calculation variable for depth
//define sound speed in cm/uS
long duration;
float distanceCm;
double damDepth =200;
// Your GPRS credentials
const char apn[] = "Vodacom APN"; // APN
const char gprsUser[] = ""; // GPRS User
const char gprsPass[] = ""; // GPRS Password
// SIM card PIN (leave empty, if not defined)
const char simPIN[] = "";
// Server details
const char server[] = "grow-with-pierre.com"; // domain name:
const char resource[] = "/post-data.php"; // resource path, for example: /post-data.php
const int port = 80; // server port number
// Keep this API Key value to be compatible with the PHP code
String apiKeyValue = "tPmAT5Ab3j7F9";
#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);
// TinyGSM Client for Internet connection
TinyGsmClient client(modem);
bool setPowerBoostKeepOn(int en)
{
I2CPower.beginTransmission(IP5306_ADDR);
I2CPower.write(IP5306_REG_SYS_CTL0);
if (en)
{
I2CPower.write(0x37); // Set bit1: 1 enable 0 disable boost keep on
} else
{
I2CPower.write(0x35); // 0x37 is default reg value
}
return I2CPower.endTransmission() == 0;
}
void setup()
{
Serial.begin(115200); // Starts the serial communication
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
// Set serial monitor debugging window baud rate to 115200
SerialMon.begin(115200);
// Start I2C communication
I2CPower.begin(I2C_SDA, I2C_SCL, 400000);
// Keep power when running from battery
bool isOk = setPowerBoostKeepOn(1);
SerialMon.println(String("IP5306 KeepOn ") + (isOk ? "OK" : "FAIL"));
// 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(115200, 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);
}
// Configure the wake up source as timer wake up
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
}
void loop()
{
postData();
Serial.print(String(" Percentage: ") + depth());
// Put ESP32 into deep sleep mode (with timer wake up)
esp_deep_sleep_start();
}
String postData()
{
SerialMon.print("Connecting to APN: ");
SerialMon.print(apn);
if (!modem.gprsConnect(apn, gprsUser, gprsPass))
{
SerialMon.println(" fail");
}
else
{
SerialMon.println(" OK");
SerialMon.print("Connecting to ");
SerialMon.print(server);
if (!client.connect(server, port))
{
SerialMon.println(" fail");
}
else
{
SerialMon.println(" OK");
// Making an HTTP POST request
SerialMon.println("Performing HTTP POST request...");
String httpRequestData = "api_key=" + apiKeyValue + "&value1=" + String(deviceID)
+ "&value2=" + String(distanceCm) + "&value3=" + String(80) + "&value4=" + String(40) + ""+ "&value5=" + String(50) + "";
// then, use the httpRequestData variable below (for testing purposes without the BME280 sensor)
// String httpRequestData = "api_key=tPmAT5Ab3j7F9&value1=24.75&value2=49.54&value3=1005.14";
client.print(String("POST ") + resource + " HTTP/1.1\r\n");
client.print(String("Host: ") + server + "\r\n");
client.println("Connection: close");
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(httpRequestData.length());
client.println();
client.println(httpRequestData);
unsigned long timeout = millis();
while (client.connected() && millis() - timeout < 10000L)
{
// Print available data (HTTP response from server)
while (client.available())
{
char c = client.read();
SerialMon.print(c);
timeout = millis();
}
}
SerialMon.println();
// Close client and disconnect
client.stop();
SerialMon.println(F("Server disconnected"));
modem.gprsDisconnect();
SerialMon.println(F("GPRS disconnected"));
}
}
}
float depth() //Find Depth in cm
{
double persentage;
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distanceCm = duration * SOUND_SPEED/2;
// Prints the distance in the Serial Monitor
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
persentage = (distanceCm/damDepth)*100;
if(persentage>=100)
{
persentage=100;
}
else
{
persentage=100- persentage;
}
return persentage;
}
For at least some of the desired functions, it isn't necessary to push AT-commands.
Try signalStrength = modem.getSignalQuality(); instead. It works for me on the Lilygo T-Call SIM800L. You can check out TinyGSM's Github-page for additional commands or this handy class reference

How to publish and subscribe to MQTT broker through GSM Module in Arduino/ESP8266?

I am currently working in a project where I have to publish and possibly subscribe to MQTT topic over GSM network (I am using ESP8266 and Ai Thinker A6 GSM Module). So far I am able to publish message to the broker once using MQTT Example code from TinyGSM library,where they pass the GPRS client instance to Pubsub Client class, but when I add a code in loop to publish message continuously every n seconds. The message is published only once or twice and then freezes.
I doubt the mqttclient.loop() function in the void loop(). But, I am just wondering is there any other library which is completely tested, because the TinyGSM developer itself has mentioned this code is not tested in github.
The example code with mqtt publish in loop
// Select your modem:
#define TINY_GSM_MODEM_SIM800
// #define TINY_GSM_MODEM_SIM808
// #define TINY_GSM_MODEM_SIM868
// #define TINY_GSM_MODEM_SIM900
// #define TINY_GSM_MODEM_SIM7000
// #define TINY_GSM_MODEM_SIM5360
// #define TINY_GSM_MODEM_SIM7600
// #define TINY_GSM_MODEM_UBLOX
// #define TINY_GSM_MODEM_SARAR4
// #define TINY_GSM_MODEM_M95
// #define TINY_GSM_MODEM_BG96
// #define TINY_GSM_MODEM_A6
// #define TINY_GSM_MODEM_A7
// #define TINY_GSM_MODEM_M590
// #define TINY_GSM_MODEM_MC60
// #define TINY_GSM_MODEM_MC60E
// #define TINY_GSM_MODEM_ESP8266
// #define TINY_GSM_MODEM_XBEE
// #define TINY_GSM_MODEM_SEQUANS_MONARCH
// Set serial for debug console (to the Serial Monitor, default speed 115200)
#define SerialMon Serial
// Set serial for AT commands (to the module)
// Use Hardware Serial on Mega, Leonardo, Micro
#define SerialAT Serial1
// or Software Serial on Uno, Nano
//#include <SoftwareSerial.h>
//SoftwareSerial SerialAT(2, 3); // RX, TX
// See all AT commands, if wanted
// #define DUMP_AT_COMMANDS
// Define the serial console for debug prints, if needed
#define TINY_GSM_DEBUG SerialMon
// Range to attempt to autobaud
#define GSM_AUTOBAUD_MIN 9600
#define GSM_AUTOBAUD_MAX 115200
// Add a reception delay - may be needed for a fast processor at a slow baud rate
// #define TINY_GSM_YIELD() { delay(2); }
// Define how you're planning to connect to the internet
#define TINY_GSM_USE_GPRS true
#define TINY_GSM_USE_WIFI false
// set GSM PIN, if any
#define GSM_PIN ""
// Your GPRS credentials, if any
const char apn[] = "YourAPN";
const char gprsUser[] = "";
const char gprsPass[] = "";
// Your WiFi connection credentials, if applicable
const char wifiSSID[] = "YourSSID";
const char wifiPass[] = "YourWiFiPass";
// MQTT details
const char* broker = "broker.hivemq.com";
const char* topicLed = "GsmClientTest/led";
const char* topicInit = "GsmClientTest/init";
const char* topicLedStatus = "GsmClientTest/ledStatus";
#include <TinyGsmClient.h>
#include <PubSubClient.h>
// Just in case someone defined the wrong thing..
#if TINY_GSM_USE_GPRS && not defined TINY_GSM_MODEM_HAS_GPRS
#undef TINY_GSM_USE_GPRS
#undef TINY_GSM_USE_WIFI
#define TINY_GSM_USE_GPRS false
#define TINY_GSM_USE_WIFI true
#endif
#if TINY_GSM_USE_WIFI && not defined TINY_GSM_MODEM_HAS_WIFI
#undef TINY_GSM_USE_GPRS
#undef TINY_GSM_USE_WIFI
#define TINY_GSM_USE_GPRS true
#define TINY_GSM_USE_WIFI false
#endif
#ifdef DUMP_AT_COMMANDS
#include <StreamDebugger.h>
StreamDebugger debugger(SerialAT, SerialMon);
TinyGsm modem(debugger);
#else
TinyGsm modem(SerialAT);
#endif
TinyGsmClient client(modem);
PubSubClient mqtt(client);
#define LED_PIN 13
int ledStatus = LOW;
uint32_t lastReconnectAttempt = 0;
void mqttCallback(char* topic, byte* payload, unsigned int len) {
SerialMon.print("Message arrived [");
SerialMon.print(topic);
SerialMon.print("]: ");
SerialMon.write(payload, len);
SerialMon.println();
// Only proceed if incoming message's topic matches
if (String(topic) == topicLed) {
ledStatus = !ledStatus;
digitalWrite(LED_PIN, ledStatus);
mqtt.publish(topicLedStatus, ledStatus ? "1" : "0");
}
}
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() {
// Set console baud rate
SerialMon.begin(115200);
delay(10);
pinMode(LED_PIN, OUTPUT);
// !!!!!!!!!!!
// Set your reset, enable, power pins here
// !!!!!!!!!!!
SerialMon.println("Wait...");
// Set GSM module baud rate
// TinyGsmAutoBaud(SerialAT,GSM_AUTOBAUD_MIN,GSM_AUTOBAUD_MAX);
SerialAT.begin(9600);
delay(3000);
// Restart takes quite some time
// To skip it, call init() instead of restart()
SerialMon.println("Initializing modem...");
modem.restart();
// modem.init();
String modemInfo = modem.getModemInfo();
SerialMon.print("Modem Info: ");
SerialMon.println(modemInfo);
#if TINY_GSM_USE_GPRS
// Unlock your SIM card with a PIN if needed
if ( GSM_PIN && modem.getSimStatus() != 3 ) {
modem.simUnlock(GSM_PIN);
}
#endif
#if TINY_GSM_USE_WIFI
// Wifi connection parameters must be set before waiting for the network
SerialMon.print(F("Setting SSID/password..."));
if (!modem.networkConnect(wifiSSID, wifiPass)) {
SerialMon.println(" fail");
delay(10000);
return;
}
SerialMon.println(" success");
#endif
#if TINY_GSM_USE_GPRS && defined TINY_GSM_MODEM_XBEE
// The XBee must run the gprsConnect function BEFORE waiting for network!
modem.gprsConnect(apn, gprsUser, gprsPass);
#endif
SerialMon.print("Waiting for network...");
if (!modem.waitForNetwork()) {
SerialMon.println(" fail");
delay(10000);
return;
}
SerialMon.println(" success");
if (modem.isNetworkConnected()) {
SerialMon.println("Network connected");
}
#if TINY_GSM_USE_GPRS
// GPRS connection parameters are usually set after network registration
SerialMon.print(F("Connecting to "));
SerialMon.print(apn);
if (!modem.gprsConnect(apn, gprsUser, gprsPass)) {
SerialMon.println(" fail");
delay(10000);
return;
}
SerialMon.println(" success");
if (modem.isGprsConnected()) {
SerialMon.println("GPRS connected");
}
#endif
// MQTT Broker setup
mqtt.setServer(broker, 1883);
mqtt.setCallback(mqttCallback);
}
void 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;
}
else
{
mqtt.publish("Topic/test","Hi");
delay(1000);
}
mqtt.loop();
}

Attempting MQTT connection...failed, rc=-4 try again in 5 seconds

I used aREST to access to my NODEMCU but it says "Attempting MQTT connection...failed, rc=-4 try again in 5 seconds" on serial monitor
My code:
// Control ESP8266 anywhere
// Import required libraries
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <WiFiClientSecure.h>
#include <aREST.h>
// Clients
WiFiClient espClient;
PubSubClient client(espClient);
// Create aREST instance
aREST rest = aREST(client);
// Unique ID to identify the device for cloud.arest.io
char* device_id = "aliziveh79";
// WiFi parameters
const char* ssid = "Samsung J7";
const char* password = "Movahed12341234";
// Functions
void callback(char* topic, byte* payload, unsigned int length);
void setup(void)
{
// Start Serial
Serial.begin(115200);
// Set callback
client.setCallback(callback);
// Give name and ID to device
rest.set_id(device_id);
rest.set_name("relay_anywhere");
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Set output topic
char* out_topic = rest.get_topic();
}
void loop() {
// Connect to the cloud
rest.loop(client);
}
// Handles message arrived on subscribed topic(s)
void callback(char* topic, byte* payload, unsigned int length) {
rest.handle_callback(client, topic, payload, length);
}
I used aREST to access to my NODEMCU but it says Attempting MQTT connection...failed, rc=-4 try again in 5 seconds" on serial monitor
Return code -4 is a timeout trying to connect to the broker
// Possible values for client.state()
#define MQTT_CONNECTION_TIMEOUT -4
#define MQTT_CONNECTION_LOST -3
#define MQTT_CONNECT_FAILED -2
#define MQTT_DISCONNECTED -1
#define MQTT_CONNECTED 0
#define MQTT_CONNECT_BAD_PROTOCOL 1
#define MQTT_CONNECT_BAD_CLIENT_ID 2
#define MQTT_CONNECT_UNAVAILABLE 3
#define MQTT_CONNECT_BAD_CREDENTIALS 4
#define MQTT_CONNECT_UNAUTHORIZED 5
This most likely means the address for your broker is wrong (but I don't see where you are specifying that in the code you have provided)
When you connect the client, you have to change the name of the Device:
if (client.connect("CHANGE_THIS_IT_HAS_TO_BE_DIFFERENT_FOR_EACH_DEVICE"))
I use the MAC Address to change it dynamically

How can I get rid of error: 'SerialUSB' was not declared in this scope in my Arduino Sketch?

The code is below, slightly modified from a tutorial. I am working on a Teensy3.1. I added #include <SoftwareSerial.h> but it did not help. I also tried SerialUSB.begin(9600); instead of WiredSerial.begin(9600); //use native port on Due
#include <SoftwareSerial.h>
//minimal sketch for connection to ADS129n family. Load this script and open Tools/SerialMonitor.
//You should see text like this
// Device Type (ID Control Register): 62 Channels: 8
//If you see "Channels: 0" then check your wiring
#include "ads1298.h"
#include "adsCMD.h"
#include <Arduino.h>
#include <SPI.h> // include the SPI library:
int gMaxChan = 0; //maximum number of channels supported by ads129n = 4,6,8
int gIDval = 0; //Device ID : lower 5 bits of ID Control Register
int activeSerialPort = 0; //data will be sent to serial port that last sent commands. E.G. bluetooth or USB port
const int kPIN_LED = 13;//pin with in-built light - typically 13, 11 for Teensy 2.0.
#if defined(__SAM3X8E__)
#define isDUE //Detect Arduino Due
#define WiredSerial SerialUSB //Use Due's Native port
#else
#define WiredSerial Serial
#endif
void setup(){
using namespace ADS1298;
//prepare pins to be outputs or inputs
//pinMode(PIN_SCLK, OUTPUT); //optional - SPI library will do this for us
//pinMode(PIN_DIN, OUTPUT); //optional - SPI library will do this for us
//pinMode(PIN_DOUT, INPUT); //optional - SPI library will do this for us
pinMode(IPIN_CS, OUTPUT);
pinMode(PIN_START, OUTPUT);
pinMode(IPIN_DRDY, INPUT);
//pinMode(PIN_CLKSEL, OUTPUT);//*optional
//pinMode(IPIN_RESET, OUTPUT);//*optional
//pinMode(IPIN_PWDN, OUTPUT);//*optional
//start small peripheral interface
SPI.begin();
SPI.setBitOrder(MSBFIRST);
#ifndef isDUE
SPI.setClockDivider(SPI_CLOCK_DIV4); //http://forum.pjrc.com/threads/1156-Teensy-3-SPI-Basic-Clock-Questions
#endif
SPI.setDataMode(SPI_MODE1);
//Start ADS1298
delay(500); //wait for the ads129n to be ready - it can take a while to charge caps
adc_send_command(SDATAC); // Send SDATAC Command (Stop Read Data Continuously mode)
delay(10);
// Determine model number and number of channels available
gIDval = adc_rreg(ID); //lower 5 bits of register 0 reveal chip type
switch (gIDval & B00011111 ) { //least significant bits reports channels
case B10000: //16
gMaxChan = 4; //ads1294
break;
case B10001: //17
gMaxChan = 6; //ads1296
break;
case B10010: //18
gMaxChan = 8; //ads1298
break;
case B11110: //30
gMaxChan = 8; //ads1299
break;
default:
gMaxChan = 0;
}
//start serial port
SerialUSB.begin(9600); //use native port on Due
//WiredSerial.begin(9600); //use native port on Due
while (WiredSerial.read() >= 0) {} //http://forum.arduino.cc/index.php?topic=134847.0
//while (!WiredSerial) ; //required by Leonardo http://arduino.cc/en/Serial/IfSerial (ads129n requires 3.3v signals, Leonardo is 5v)
delay(200); // Catch Due reset problem
pinMode(kPIN_LED, OUTPUT);
}
void loop()
{
WiredSerial.print("Device Type (ID Control Register): "); SerialUSB.print(gIDval); SerialUSB.print(" Channels: "); SerialUSB.println(gMaxChan);
digitalWrite(kPIN_LED, HIGH); // turn the LED on (HIGH is the voltage level)
if (gMaxChan > 0)
delay(500); //long pause if OK
else
delay(50); //rapid blink if error
digitalWrite(kPIN_LED, LOW); // turn the LED off by making the voltage LOW
delay(500);
}
Try using Serial instead of SerialUSB, I've tried it while using Arduino UNO.

Resources