Arduino Leonardo choking after a few loops - arduino

I'm making a GPS tracker that sends the data to a server, but after 1-2 loops working perfectly (it sends the packages), it chokes (stops making output to Serial and does not send anything).
Why is this happening and how to fix it? The GPS is connected through UART via HardwareSerial and the GPRS also through UART via SoftwareSerial.
#include <GPRS_Shield_Arduino.h>
#include <TroykaGPS.h>
#include <SoftwareSerial.h>
#define IMEI "IMEI" //I removed the real IMEI
#define INTERVAL 30000
#define LEN 370
#define MAX_SIZE_MAS 16
char tcpBuffer[LEN];
SoftwareSerial GPRSSerial(10, 11);
GPS gps(Serial1);
GPRS gprs(GPRSSerial);
void setup() {
Serial.begin(9600);
while (!Serial) {}
Serial.println("Serial init OK");
delay(100);
Serial1.begin(115200);
Serial.println("GPS serial init OK");
GPRSSerial.begin(9600);
Serial.println("GPRS serial init OK");
delay(1000);
Serial.println("Waiting for network");
while (1) {
delay(1000);
if (gps.available()) {
gps.readParsing();
if (gps.getState() == GPS_OK) break;
} else {
Serial.println("GPS not available");
}
}
Serial.println("Network found!");
}
void loop() {
gprs.powerOn();
while (!gprs.init()) {
Serial.println("GPRS Init error");
}
Serial.println("GPRS init success");
delay(3000);
while (!gprs.join("internet.beeline.ru", "beeline", "beeline")) {
Serial.println("GPRS JOINING NETWORK ERROR");
delay(1000);
}
Serial.println("GPRS OK");
Serial.print("IP Address is ");
Serial.println(gprs.getIPAddress());
while (!gprs.connect(TCP, "*ip address*", 80)) {
//I replaced the real IP
Serial.println("Connect error");
delay(1000);
}
Serial.println("Connect success");
tcpSend();
gprs.close();
gprs.disconnect();
delay(100);
Serial.println("Sent");
gprs.powerOff();
delay(15000);
}
void tcpSend() {
tcpBufferForm();
gprs.send(tcpBuffer);
clearTcpBuffer();
}
void tcpBufferForm() {
//strcat(tcpBuffer, "GET /recvdata.php?filename=ard.txt&data=123 HTTP/1.0\r\n\r\n");
char buf[100];
if (gps.available()) {
gps.readParsing();
switch (gps.getState()) {
case GPS_OK:
char lon[16], lat[16], date[16], time[16];
gps.getTime(time, MAX_SIZE_MAS);
gps.getDate(date, MAX_SIZE_MAS);
dtostrf(gps.getLatitudeBase10(), 9, 6, lat);
dtostrf(gps.getLongitudeBase10(), 9, 6, lon);
sprintf(tcpBuffer, "GET /recvdata.php?filename=%s_%s.txt&data=%s_%s_%s_%s_%s HTTP/1.0\r\n\r\n", date, time, IMEI, date, time, lat, lon);
Serial.print("formed: ");
Serial.println(tcpBuffer);
Serial.print("pending to send...");
break;
case GPS_ERROR_DATA:
gprs.getDateTime(buf);
sprintf(tcpBuffer, "GET /recvdata.php?filename=%s_err.txt&data=ERROR_DATA_%s_%s HTTP/1.0\r\n\r\n", buf, buf, IMEI);
Serial.println("Sending GPS_ERROR_DATA");
Serial.print("formed: ");
Serial.println(tcpBuffer);
Serial.print("pending to send...");
break;
case GPS_ERROR_SAT:
gprs.getDateTime(buf);
sprintf(tcpBuffer, "GET /recvdata.php?filename=%s_err.txt&data=ERROR_SAT_%s_%s HTTP/1.0\r\n\r\n", buf, buf, IMEI);
Serial.println("Sending GPS_ERROR_SAT");
Serial.print("formed: ");
Serial.println(tcpBuffer);
Serial.print("pending to send...");
break;
}
}
}
void clearTcpBuffer() {
for (int t = 0; t < LEN; t++) {
tcpBuffer[t] = 0;
}
}

Moving the GPRS setup precess to the setup() helped

Related

Node mcu esp8266 disconnects from MQTT broker

I have two node mcu modules connected to the same network, running the same code and powered the same way. Both of them are subscribed to the topic Terma but one of them randomly disconnects and then reconnects to the MQTT broker meanwhile it stayed connected to the wifi uninterruptedly, the other module stays connected with no problem. I don't know if it is a network issue or if the node mcu is damaged.
here is the code:
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "Milagros";
const char* password = "18095381";
const char* mqtt_server = "192.168.1.133";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
digitalWrite(14, LOW);
client.publish("estado","1");
// but actually the LED is on; this is because
// it is active low on the ESP-01)
} else {
digitalWrite(14, HIGH);
client.publish("estado","0");
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("terma", "hello world 1");
// ... and resubscribe
client.subscribe("terma");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pinMode(14, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1884);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}

ESP8266 is not able to connect to mosquitto broker. "Attempting MQTT connection...failed, rc=-2 try again in 5 seconds"

I'm running a mosquitto broker and a node-red server in my PC , node-red is able to connect to mosquitto. The ESP8266 is able to connect to the WiFi but not to the broker a "Attempting MQTT connection...failed, rc=-2 try again in 5 seconds" message is displayed in the serial monitor. I'm also using MQTT explorer I don't know if it has something to do with it.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "Milagros";
const char* password = "18095381";
const char* mqtt_server = "192.168.1.133";
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is active low on the ESP-01)
} else {
digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("data", "hello world");
// ... and resubscribe
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
unsigned long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("data", msg);
}
}```

How to merge two arduino programs on Bluetooth and Fingerprint?

Bluetooth and fingerprint are not responding simultaneously.
Bluetooth is used for controlling "Find me alarm" and Fingerprint is used to control the open and close motors.
The bluetooth is used to trigger the buzzer to make a buzzing sound. The fingerprint is used to control the four motors which is used to open and close the door
How to merge these two programs?
Fingerprint :
#include <FPS_GT511C3.h>
#include <SoftwareSerial.h>
FPS_GT511C3 fps(5, 4);
int buttonstate = 0;
void setup()
{
Serial.begin(9600);
delay(100);
fps.Open();
fps.SetLED(true);
pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
pinMode(11,OUTPUT);
pinMode(13,INPUT);
pinMode(16,OUTPUT);
pinMode(17,OUTPUT);
pinMode(18,OUTPUT);
pinMode(19,OUTPUT);
}
void loop()
{
buttonstate=digitalRead(13);
if (fps.IsPressFinger())
{
fps.CaptureFinger(false);
int id = fps.Identify1_N();
if (id <200)
{
Serial.print("Verified ID:");
Serial.println(id);
digitalWrite(8,HIGH);
digitalWrite(9,LOW);
digitalWrite(10,HIGH);
digitalWrite(11,LOW);
delay(1000);
digitalWrite(8,LOW);
digitalWrite(9,LOW);
digitalWrite(10,LOW);
digitalWrite(11,LOW);
delay(100);
digitalWrite(16,HIGH);
digitalWrite(17,LOW);
digitalWrite(18,HIGH);
digitalWrite(19,LOW);
}
else
{
Serial.println("Finger not found");
}
}
else
{
Serial.println("Please press finger");
}
if(buttonstate == HIGH)
{
digitalWrite(8,LOW);
digitalWrite(9,HIGH);
digitalWrite(10,LOW);
digitalWrite(11,HIGH);
delay(1000);
digitalWrite(8,LOW);
digitalWrite(9,LOW);
digitalWrite(10,LOW);
digitalWrite(11,LOW);
delay(100);
digitalWrite(16,LOW);
digitalWrite(17,LOW);
digitalWrite(18,LOW);
digitalWrite(19,LOW);
}
delay(100);
}
Bluetooth :
#include<SoftwareSerial.h>
SoftwareSerial BT(14,15);
String readdatta;
void setup() {
BT.begin(9600);
Serial.begin(9600);
pinMode(12,OUTPUT);
}
void loop() {
char ch;
while(ch!=0)
{
ch=BT.read();
delay(100);
if(ch == '1')
{
digitalWrite(12,HIGH);
}
else
{
digitalWrite(12,HIGH);
}
}
ch = ' ';
}

There are no GPS data after connecting to the server

I'm trying to get GPS data and send it to the server via socket.
I'm using Arduino Uno and GPS/GSM module A7 Ai-Thinker.
And for Internet I use Ethernet shield connected to Wi-Fi router.
But I got trouble when I joined getting GPS data and sending it.
Separately that functions work fine. How I start A7, there is a loop where I type AT commands and send it to A7. About socket, I want to set connection at start function and keep it alive all the time.
But the problem is that when I initialized A7 and set socket connection, I go to the loop function and after first iteration there are no data at A7.
If I try to set connection with server first, and start A7 after it, A7 doesn't react to AT commands.
How can I keep connection with my server and don't lost connection with A7?
Code:
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#include <SPI.h>
#include <Ethernet.h>
//-------------------------------------------------------
static const int RXPin = 10, TXPin = 11;
static const uint32_t GPSBaud = 4800;
const String START_GPS = "START_GPS";
TinyGPSPlus gps;
SoftwareSerial gps_serial(RXPin, TXPin);
//-------------------------------------------------------
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
char server[] = "192.168.0.100";
int port = 8090;
IPAddress ip(192, 168, 0, 177);
EthernetClient client;
//-------------------------------------------------------
void initGpsConnection();
void startGps();
void initSocketConnection();
void sendData();
void setup()
{
Serial.begin(9600);
Serial.println();
initSocketConnection();
initGpsConnection();
sendData();
}
void loop()
{
while (gps_serial.available() > 0) {
if (gps.encode(gps_serial.read())) {
displayInfo();
//delay(1000);
}
}
if (millis() > 120000 && gps.charsProcessed() < 10)
{
Serial.println(F("No GPS detected: check wiring."));
//while(true);
}
if (!client.connected()) {
Serial.println();
Serial.println("Socket connection has been lost.");
client.stop();
//while (true);
}
}
void displayInfo()
{
Serial.print(F("Location: "));
if (gps.location.isValid())
{
Serial.print(gps.location.lat(), 6);
Serial.print(F(","));
Serial.print(gps.location.lng(), 6);
}
else
{
Serial.print(F("INVALID"));
}
Serial.print(F(" Date/Time: "));
if (gps.date.isValid()) {
Serial.print(gps.date.month() + "/" gps.date.day() + "/" + gps.date.year();
} else {
Serial.print(F("INVALID"));
}
Serial.print(F(" "));
if (gps.time.isValid()) {
Serial.print(gps.time.hour() + ":" + gps.time.minute() + ":" + gps.time.second());
} else {
Serial.print(F("INVALID"));
}
Serial.println();
}
void initGpsConnection() {
Serial.println("In init gps");
gps_serial.begin(GPSBaud);
Serial.println("after gps begin");
delay(1000);
startGps();
Serial.println("GPS connection has been set");
}
void startGps() {
Serial.println("Enter at commands, after that enter `start_gps`");
String response = "";
while (true) {
if (gps_serial.available()) {
Serial.write(gps_serial.read());
}
if (Serial.available()) {
char c = Serial.read();
response += c;
if (response.indexOf(START_GPS) > 0)
break;
gps_serial.write(c);
}
}
}
void initSocketConnection() {
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
Ethernet.begin(mac, ip);
}
delay(1000);
Serial.println("connecting...");
if (client.connect(server, port)) {
Serial.println("Connection with server has been set");
} else {
Serial.println("Connection with server has been failed");
}
}
void sendData(){
client.print("TEst ard");
}
The problem was at A7 connection. It was connected via 10, 11 pins at Ethernet shield. But 10-13 pins are reserved by A7. It's just needed connect A7 vie 8, 9 or others pins.

MQTT code stops working after a couple of hours

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

Resources