realtime database does not display data from pzem-004t - c

I have created a program to display realtime firebase data sent from nodemcu ESP8266 + PZEM-004T, but the data does not appear in the realtime database, but on the serial monitor Arduino IDE it works fine.
My output:
My sketch:
#include <PZEM004Tv30.h>
#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#define FIREBASE_HOST "iotmonitor-d8aee-default-rtdb.firebaseio.com" //Firebase url non SSL(https://)
#define FIREBASE_AUTH "C7j...Gid" //Secret Key Database
#define WIFI_SSID "IKWAN_BRILink" //Nama WiFi
#define WIFI_PASSWORD "Orbit121" // Password Wifi
PZEM004Tv30 pzem(12, 13);
float harga_KWh = 1.444; //Biaya per KWh
void setup() {
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println();
Serial.print("connected: ");
Serial.println(WiFi.localIP());
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
}
void loop() {
float voltage = pzem.voltage();
float current = pzem.current();
float power = pzem.power();
float energy = pzem.energy();
if (isnan(voltage) ) {
voltage = 0;
}
if (isnan(current) ) {
current = 0;
}
if (isnan(power) ) {
power = 0;
}
if (isnan(energy) ) {
energy = 0;
}
float totalHarga = energy * harga_KWh;
Firebase.setString("volt", String(voltage));
Firebase.setString("current", String(current));
Firebase.setFloat("watt", power);
Firebase.setString("kwh", String(energy, 1));
Firebase.setString("rp", String(totalHarga, 3));
Serial.print("Voltage = ");
Serial.print(voltage);
Serial.println("v");
Serial.print("Current = ");
Serial.print(current, 2);
Serial.println("A");
Serial.print("Watt = ");
Serial.print(power);
Serial.println("watt");
Serial.print("KWh = ");
Serial.print(energy, 1);
Serial.println("KWh");
Serial.print("Harga = Rp ");
Serial.print(totalHarga, 3);
Serial.println();
delay(2000);
}

Related

How to decode ECG data frame in Polar H10?

I'm using ArduinoBLE.h library to connect Polar H10 and refer to this documentation to obtain the ECG data.
I have managed to start streaming and get info from the Custom Characteristic UUID "FB005C82-02E7-F387-1CAD-8ACD2D8DF0C8".
This is the information that was obtained:
(0x) 00-14-D1-22
Is this represent the ECG and how should I extract it?
Also, how to modify the sampling_rate? It does not show in the documentation.
Below is my code:
#include <ArduinoBLE.h>
#define BLE_ARDUINO_NAME "Arduino"
// Polar Gatt Service and Characteristics
#define PMD_SERVICE_UUID "FB005C80-02E7-F387-1CAD-8ACD2D8DF0C8"
#define PMD_CONTROL_CHARACTERISTIC_UUID "FB005C81-02E7-F387-1CAD-8ACD2D8DF0C8"
#define PMD_DATA_CHARACTERISTIC_UUID "FB005C82-02E7-F387-1CAD-8ACD2D8DF0C8"
#define POLAR_HR_SERVICE_UUID "180D"
#define POLAR_HR_CHARACTERISTIC_UUID "2A37"
// Polar H10 Sampling Frequency
#define POLAR_SAMPLE_RATE 130
// POLAR_HR_CHARACTERISTIC_UUID FLAG VALIDATE
#define ENERGY_EXPENDED_PRESENT_BIT 3
#define RR_INTERVAL_PRESENT_BIT 4
#define HEART_RATE_FORMAT_BIT 0
// Unit Measurement Convert Parameter
#define RR_INTERVAL_UNIT 1024
// Control Parameters
bool scanRequried = true;
bool requestStreamRequired = true;
BLEDevice POLAR_Peripheral;
BLEService HR_Service;
BLECharacteristic HR_Characteristic;
BLEService PMD_Service;
BLECharacteristic PMD_Control;
BLECharacteristic PMD_Data;
void polarPMD() {
PMD_Service = POLAR_Peripheral.service(PMD_SERVICE_UUID);
if (!PMD_Service.hasCharacteristic(PMD_CONTROL_CHARACTERISTIC_UUID))
Serial.println("PMD_CONTROL_CHARACTERISTIC_UUID Not Found");
else if (!PMD_Service.hasCharacteristic(PMD_DATA_CHARACTERISTIC_UUID))
Serial.println("PMD_DATA_CHARACTERISTIC_UUID Not Found");
PMD_Control = PMD_Service.characteristic(PMD_CONTROL_CHARACTERISTIC_UUID);
PMD_Data = PMD_Service.characteristic(PMD_DATA_CHARACTERISTIC_UUID);
PMD_Control.subscribe();
PMD_Data.subscribe();
}
void requestECGStream() {
if (requestStreamRequired) {
// Request Stream Setting
const uint8_t REQUEST_STREAM[] = {0x01,0x02};
const uint8_t REQUEST_ECG[] = {0x01,0x00};
if (PMD_Control.writeValue(REQUEST_STREAM, 2))
Serial.println("Success 0x01,0x02");
if (PMD_Control.writeValue(REQUEST_ECG, 2))
Serial.println("Success 0x01,0x00");
requestStreamRequired = false;
}
}
void startStream() {
const uint8_t REQUEST_STREAM[] = {0x02, 0x00, 0x00, 0x01, 0x82, 0x00, 0x01, 0x01, 0x0E, 0x00};
PMD_Control.writeValue(REQUEST_STREAM, 10);
while (POLAR_Peripheral.connected()) {
if (PMD_Data.valueUpdated()) {
PMD_Data.read();
readData(PMD_Data.value());
Serial.println();
}
}
polarDisconnect();
scanRequried = true;
requestStreamRequired = true;
}
void readData(const uint8_t *data) {
int size = sizeof(data) / sizeof(data[0]);
for (int i = 0; i < size; i++) {
unsigned char c = data[i];
Serial.print(c, HEX);
if (i < size - 1) {
Serial.print("-");
}
}
Serial.println("");
}
bool polarDataValid () {
if (!POLAR_Peripheral.discoverAttributes()) {
Serial.println("* Attributes discovery failed!");
Serial.println(" ");
polarDisconnect();
return false;
}
return true;
}
void polarDisconnect() {
POLAR_Peripheral.disconnect();
Serial.println("Decive Disconnected...");
scanRequried = true;
requestStreamRequired = true;
}
void polarConnect() {
Serial.println("Connecting to the device...");
if (POLAR_Peripheral.connect()) {
Serial.println("* Connected");
Serial.println(" ");
} else {
Serial.println("* Ops, Fail Connection");
Serial.println(" ");
scanRequried = true;
requestStreamRequired = true;
}
}
bool polarDiscover () {
BLEDevice peripheral;
Serial.println("Searching HEART RATE SERVICE device...");
do
{
BLE.scanForUuid(POLAR_HR_SERVICE_UUID);
peripheral = BLE.available();
} while (!peripheral);
if (peripheral) {
Serial.println("* POLAR H10 device found!");
Serial.print("* Device MAC address: ");
Serial.println(peripheral.address());
Serial.print("* Device name: ");
Serial.println(peripheral.localName());
Serial.print("* Advertised service UUID: ");
Serial.println(peripheral.advertisedServiceUuid());
Serial.println(" ");
BLE.stopScan();
scanRequried = false;
}
POLAR_Peripheral = peripheral;
}
void setup() {
Serial.begin(9600);
while (!Serial) {
Serial.println("Serial Initialization Failed.");
}
// begin initialization
while (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
}
BLE.setDeviceName(BLE_ARDUINO_NAME);
BLE.setLocalName(BLE_ARDUINO_NAME);
BLE.advertise();
Serial.println(String(BLE_ARDUINO_NAME) + " (Central Device)");
Serial.println("");
}
void loop() {
// Find Polar Device and Connect it.
if (scanRequried) {
polarDiscover();
polarConnect();
}
if (polarDataValid()) {
polarPMD();
requestECGStream();
if(!requestStreamRequired) {
startStream();
}
}
}
and below is the output:
Arduino (Central Device)
Searching HEART RATE SERVICE device...
* POLAR H10 device found!
* Device MAC address: c0:d2:62:ca:3d:46
* Device name: Polar H10 B1915225
* Advertised service UUID: 180d
Connecting to the device...
* Connected
Success 0x01,0x02
Success 0x01,0x00
0-5E-AB-8A
0-19-6B-FA
0-56-DB-69
0-E6-31-8
Below is the parts of the information provided by the documentation mentioned.
ECG signal is not my area, but here are some suggestions.
the size of Electrocardiogram is 3B and its unit is uV as the description of the Frame types ECG, so extract the leading 3 octets of the outputs and try explaining them in either big-endian or little-endian.
0-5E-AB-8A would be either 0x005EAB=24235uV or 0xAB5E00=11230720uV
0-19-6B-FA would be either 0x00196B=6507uV or 0x6B1900=7018752uV
0-56-DB-69 would be either 0x0056DB=22235uV or 0xDB5600=14374400uV
0-E6-31-8 would be either 0x00E631=58929uV or 0x31E600=3270144uV
the results explained by big-endian look more reasonable.
void readData(const uint8_t *data) {
int size = sizeof(data) / sizeof(data[0]);
The expression sizeof(data) brings out the size of the pointer data actually, so the value of size would be a constant number which is determined by the compiler, i.e. 4, not in the runtime and this results in every output has only four octets.
If the total size of the result of PMD_Data.value() is assigned to size, the output might have more octets just as the RFU field described in the Frame types ECG.

Is there a way to calculate -time interval- using Esp32 timers?

I want to calculate time interval with timers. I'm using arduino ide. Also i can not decide which library to useful.
I just tried something following code.
I'm using this library
#include <ESP32Time.h>
int a;
int b;
int ldrValue;
#define LDR 0
/* create a hardware timer */
hw_timer_t * timer = NULL;
int timeThatPast;
/* motor pin */
int motor = 14;
/* motor state */
volatile byte state = LOW;
void IRAM_ATTR onTimer(){
state = !state;
digitalWrite(motor, state);
}
void setup() {
Serial.begin(115200);
pinMode(motor, OUTPUT);
/* Use 1st timer of 4 */
/* 1 tick take 1/(80MHZ/80) = 1us so we set divider 80 and count up */
timer = timerBegin(0, 80, false);
/* Attach onTimer function to our timer */
timerAttachInterrupt(timer, &onTimer, true);
//********************ALARM*******************
/* Set alarm to call onTimer function every second 1 tick is 1us
=> 1 second is 1000000us */
/* Repeat the alarm (third parameter) */
timerAlarmWrite(timer, 7000000, false);
//********************************************
/* Start an alarm */
timerAlarmEnable(timer);
Serial.println("start timer");
}
void loop() {
int ldrValue = analogRead(LDR);
ldrValue = map(ldrValue, 0, 4095, 0, 10000);
if(ldrValue > 8500){
a = timerRead(timer);
digitalWrite(motor,HIGH);
while(1){
int ldrValue = analogRead(LDR);
ldrValue = map(ldrValue, 0, 4095, 0, 10000);
if(ldrValue < 8500){
b = timerRead(timer);
digitalWrite(motor,LOW);
Serial.print("Entering Loop");
Serial.println(a);
Serial.println("**********");
Serial.println("**********");
Serial.print("Exiting loop");
Serial.println(b);
int difference = b - a;
Serial.println("Difference");
Serial.println(difference);
break;
}
}
}
}
Use millis or micros if you need more precise timing.
Here is an example sketch:
long lastDoTime = 0;
void setup(){
Serial.begin(115200);
delay(1000);
Serial.println("Hello! We will do something at every ms");
}
void doThisAtEvery(int ms){
if( millis() - lastDoTime >= ms ){
// Must save the lastDoTime
lastDoTime = millis();
// Do some stuff at every ms
}
}
void loop(){
// It will do the thing in every 100 ms.
doThisAtEvery(100);
}
If you want to toggle a pin let's say every 100 microsec
long lastToggleTime = 0;
int motorPin = 14;
boolean lastPinState = LOW;
void setup(){
Serial.begin(115200);
}
void togglePinEvery(int micros){
if( micros() - lastToggleTime >= micros ){
lastToggleTime = micros();
digitalWrite(motorPin,!lastPinState);
lastPinState = !lastPinState;
}
}
void loop(){
togglePinEvery(100);
}
EDIT Since you wanted timers only.
Here is a detailed explanation about timers: https://techtutorialsx.com/2017/10/07/esp32-arduino-timer-interrupts/
Code example:
volatile int interruptCounter;
int totalInterruptCounter;
hw_timer_t * timer = NULL;
portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;
void IRAM_ATTR onTimer() {
portENTER_CRITICAL_ISR(&timerMux);
interruptCounter++;
portEXIT_CRITICAL_ISR(&timerMux);
}
void setup() {
Serial.begin(115200);
timer = timerBegin(0, 80, true);
timerAttachInterrupt(timer, &onTimer, true);
timerAlarmWrite(timer, 1000000, true);
timerAlarmEnable(timer);
}
void loop() {
if (interruptCounter > 0) {
portENTER_CRITICAL(&timerMux);
interruptCounter--;
portEXIT_CRITICAL(&timerMux);
totalInterruptCounter++;
Serial.print("An interrupt as occurred. Total number: ");
Serial.println(totalInterruptCounter);
}
}

Need to have 2 decimals in lcd.print

I have this program that prins to an LCD with watchdog interrupt. But the problem is that i need to have 2 decimals after seconds.
the code is as follows:
#include <Arduino.h>
#include "DFRobot_RGBLCD.h"
#include <stm32l4xx_hal_iwdg.h>
#include <Wire.h>
#define I2C2_SCL PB10
#define I2C2_SDA PB11
DFRobot_RGBLCD lcd(16,2);
TwoWire dev_i2c (I2C2_SDA, I2C2_SCL);
IWDG_HandleTypeDef watchdog;
void Start();
void Pause();
int paused = 0;
int milli = 0;
volatile byte state = HIGH;
void setup() {
pinMode(A2, INPUT_PULLUP);
pinMode(A3, INPUT_PULLUP);
lcd.init();
Serial.begin(9600);
dev_i2c.begin();
attachInterrupt(A2, Start, FALLING);
attachInterrupt(A3, Pause,RISING);
watchdog.Instance = IWDG;
watchdog.Init.Prescaler = IWDG_PRESCALER_256;
watchdog.Init.Reload = 1220;
watchdog.Init.Window = 0x0FFF;
HAL_IWDG_Init(&watchdog);
delay(1);
}
void loop() {
if(state){
delay(250);
lcd.setCursor(0, 0);
lcd.print("Sekunder: ");
lcd.print(millis()/1000-pause);
delay(100);
}
else{
delay(1000);
paused++;
HAL_IWDG_Refresh(&watchdog);
}
}
void Start(){
state = HIGH;
HAL_IWDG_Refresh(&watchdog);
delay(10);
}
void Pause(){
state = !state;
delay(10);
}
I have tried to put the -pause outside the lcd.print, but that didnt work. i've also tried this codeline: ```
lcd.print(millis()/1000.0, 2-paused);
But it seems like it takes -paused from the number 2. Do anyone have suggestion to how i can make it work so i get the 2 decimals?
String seconds = String(millis() / 1000.0, 2);
lcd.print(seconds);

Want to publish array of 768 to publish to MQTT using Esp32 wrover module

I am trying to publish the array of 786 to the MQTT Topic using ESP32 Wrover module but at the MQTT box, I am only receiving an array of 249. I am using PubSubClient Library,
What I tried in the PubSubClient library MQTT_MAX_PACKET_SIZE increase size 512 bytes still receiving the same bytes of 249 on MQTT protocol.
Code:
//#include <ArduinoJson.h>
#include <WiFi.h>
//#include <PubSubClient.h>
#include <Wire.h>
#include "MLX90640_API.h"
#include "MLX90640_I2C_Driver.h"
//#ifndef MQTT_MAX_PACKET_SIZE
////#define MQTT_MAX_PACKET_SIZE 256
//#define MQTT_MAX_PACKET_SIZE 1000
//#endif
#define MQTT_MAX_PACKET_SIZE 1000
const byte MLX90640_address = 0x33; //Default 7-bit unshifted address of the MLX90640
#define TA_SHIFT 8 //Default shift for MLX90640 in open air
float mlx90640To[768];
//char mlx90640To[768];
paramsMLX90640 mlx90640;
// Replace the next variables with your SSID/Password combination
//const char* ssid = "TP-Link_63DD";
//const char* password = "123456";
//
//const char* mqtt_server = "broker.emqx.io";
const char* ssid = "TP-Link_63DD";
const char* password = "123456";
const char* mqttServer = "broker.emqx.io";
//const char* mqttServer =" mqtt.dioty.co";
const int mqttPort = 1883;
const char* mqttUser = "******";
const char* mqttPassword = "12345";
//const char* mqttServer ="broker.hivemq.com";
//const int mqttPort = 1883;
//const char* mqttUser = "***********";
//const char* mqttPassword = "12345";
const byte led_gpio = 27;
#define row 24
#define clom 32
#define pixel 768
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
char msg[765];
int value = 0;
#define cap 800
//int lastMsg = 0;
//int value = 0;
void setup()
{
Wire.begin();
Wire.setClock(400000); //Increase I2C clock speed to 400kHz
Serial.begin(115200); //Fast serial as possible
// setup_wifi();
// client.setServer(mqtt_server, 1883);
// client.setCallback(callback);
pinMode(led_gpio, OUTPUT);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
client.setServer(mqttServer, mqttPort);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP32Client", mqttUser, mqttPassword )) {
Serial.println("connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
while (!Serial); //Wait for user to open terminal
//Serial.println("MLX90640 IR Array Example");
if (isConnected() == false)
{
Serial.println("MLX90640 not detected at default I2C address. Please check wiring. Freezing.");
while (1);
}
Serial.println("MLX90640 online!");
//Get device parameters - We only have to do this once
int status;
uint16_t eeMLX90640[832];
status = MLX90640_DumpEE(MLX90640_address, eeMLX90640);
if (status != 0)
Serial.println("Failed to load system parameters");
status = MLX90640_ExtractParameters(eeMLX90640, &mlx90640);
if (status != 0)
Serial.println("Parameter extraction failed");
//Once params are extracted, we can release eeMLX90640 array
//MLX90640_SetRefreshRate(MLX90640_address, 0x02); //Set rate to 2Hz
MLX90640_SetRefreshRate(MLX90640_address, 0x03); //Set rate to 4Hz
//MLX90640_SetRefreshRate(MLX90640_address, 0x07); //Set rate to 64Hz
}
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(".");
}
Serial.println("");
Serial.println("WiFi connected");
//delay(1000);
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
// Feel free to add more if statements to control more GPIOs with MQTT
// If a message is received on the topic esp32/output, you check if the message is either "on" or "off".
// Changes the output state according to the message
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("\n Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Subscribe
client.subscribe("esp32/output");
// client.subscribe("esp32/temperature");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
// StaticJsonBuffer<200> JSONbuffer;
void loop()
{
int boardArray [pixel];
int boardArrayTwo [row][clom];
client.loop();
//char mlx90640To[768];
// long startTime = millis();
for (byte x = 0 ; x < 2 ; x++)
{
uint16_t mlx90640Frame[834];
int status = MLX90640_GetFrameData(MLX90640_address, mlx90640Frame);
float vdd = MLX90640_GetVdd(mlx90640Frame, &mlx90640);
float Ta = MLX90640_GetTa(mlx90640Frame, &mlx90640);
float tr = Ta - TA_SHIFT; //Reflected temperature based on the sensor ambient temperature
float emissivity = 0.95;
MLX90640_CalculateTo(mlx90640Frame, &mlx90640, emissivity, tr, mlx90640To);
//Serial.print("vdd= "); Serial.print(vdd);Serial.println("\n"); // used to print vdd
// Serial.print("Ta= "); Serial.print(Ta);Serial.println("\n"); // used to print Ta
// Serial.print("tr= "); Serial.print(tr);Serial.println("\n"); // used to print tr
//
Serial.println(" ");
}
//long stopTime = millis();
//
// StaticJsonBuffer<5000> JSONbuffer;
/*******************DynamicJsonDocument*****************************/
DynamicJsonDocument doc(13000);
//JsonObject& JSONencoder = JSONbuffer.createObject();
// JSONencoder["device"] = "ESP32";
// JSONencoder["sensorType"] = "T-Scanner";
// JsonArray& values = JSONencoder.createNestedArray("v");
doc["device"] = "ESP32";
doc["sensorType"] = "T-Scanner";
char arr[786];
for (int x = 0 ; x < 768 ; x++) //768 384
{
//if(x % 8 == 0) Serial.println();
Serial.print(mlx90640To[x],0); //value from sensor print on com port
// boardArray[x] = mlx90640To[x];
// values.add((uint8_t)mlx90640To[x]);
// array.add((uint8_t)mlx90640To[x]);
doc["values"][x] = (uint8_t)mlx90640To[x]; // AARAY value of 786 is store in values
Serial.print(",");
//delay(1000);
}
/* for (int x = 0; x < row; ++x)
{
for (int k = 0; k < clom; ++k){
boardArrayTwo[x][k] = boardArray[clom*x + k];
// tempData=boardArrayTwo[x][k];
// values.add(boardArrayTwo[x][k]);
// printf("%d ", boardArrayTwo[x][k]);
//n=sprintf(reply_buff," number %d ",tempData);
} } */
digitalWrite(led_gpio, HIGH);
//serializeJson(doc, Serial);
// JSONencoder.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
Serial.println("\nSending message to MQTT topic..");
// Serial.println(JSONmessageBuffer);
char JSONmessageBuffer[cap]; // JSON MESSAGE CHAR BUFFER
Serial.println(serializeJson(doc, Serial));
size_t n = serializeJson(doc, JSONmessageBuffer); // formation of serialization of data
size_t sizeq = sizeof(JSONmessageBuffer) / sizeof(JSONmessageBuffer[0]);
Serial.println(" JSONmessageBuffer_size");
Serial.println(sizeq);
// delay(1000);
// snprintf(JSONmessageBuffer,768,"%d",serializeJson(doc, Serial));
//snprintf(JSONmessageBuffer,768,"%ld",serializeJson(doc, Serial));
Serial.println("\nJSONmessageBuffer:::");
Serial.println(JSONmessageBuffer);
//Serial.println("\nJSONmessageBuffer_size");
//Serial.println(n);
//*************************Data send to PUBLISH TO MQTT TOPIC******************************/
//if (client.publish("ev8051/esp32/temperature",JSONmessageBuffer) == true) // sending JSONmessageBuffer data to topic "ev8051/esp32/temperature"
// boolean beginPublish(const char* topic, unsigned int plength, boolean retained);
// boolean publish(const char* topic, const uint8_t * payload, unsigned int plength);
if(client.publish("ev8051/esp32/temperature",JSONmessageBuffer,n) == true)
{
Serial.println("\nSuccess sending message");
} else {
Serial.println("\nError sending message");
}
client.endPublish();
if (!client.connected()) {
reconnect();
}
client.loop();
Serial.println("-------------");
//delay(1000);
delay(1000);
}
//Returns true if the MLX90640 is detected on the I2C bus
boolean isConnected()
{
Wire.beginTransmission((uint8_t)MLX90640_address);
if (Wire.endTransmission() != 0)
return (false); //Sensor did not ACK
return (true);
}
Please help...
Thanks in advance.

Arduino GPS and GPRS Shield stop working when stored data to database

i'm trying to make a live tracking for car. i used GPS Shield and GPRS Shield. it works to get GPS latitude and longatitude, and it works to store the data to my database. But, the problem is, when it get the gps coordinates, then my GPS Shield Turning off automatically when the GPRS Shield finished store the data in my database.
I use GPS/GSM/GPRS Shield from DFRobotcan and GPRS Shield from SeedStudio. i can't used my GPRS from DFRobot because i can't get signal. it's not the problem for me.
the problem is why my GPS shield shuting down when the GPRS Shield done to store the data? anyone help me
Here's my amateur code.
#include <SoftwareSerial.h>
#include <String.h>
double lati, longati, latitudefix, longatitudefix;
String latu, longatu, latdir, londir, latitudebener, longatitudebener;
SoftwareSerial mySerial(7, 8);
String id="1310220001";
void setup()
{
mySerial.begin(19200); // the GPRS baud rate
pinMode(3,OUTPUT);//The default digital driver pins for the GSM and GPS mode
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
digitalWrite(5,HIGH);
delay(1500);
digitalWrite(5,LOW);
digitalWrite(3,LOW);//Enable GSM mode
digitalWrite(4,HIGH);//Disable GPS mode
delay(2000);
Serial.begin(9600);
delay(5000);//GPS ready
Serial.println("AT");
delay(2000);
//turn on GPS power supply
Serial.println("AT+CGPSPWR=1");
delay(1000);
//reset GPS in autonomy mode
Serial.println("AT+CGPSRST=1");
delay(1000);
digitalWrite(4,LOW);//Enable GPS mode
digitalWrite(3,HIGH);//Disable GSM mode
delay(2000);
Serial.println("$GPGGA statement information: ");
}
void loop()
{
while(1)
{
Serial.print("UTC:");
UTC();
Serial.print("Lat:");
latitude();
Serial.print("Dir:");
lat_dir();
Serial.print("Lon:");
longitude();
Serial.print("Dir:");
lon_dir();
Serial.print("Alt:");
altitude();
convert();
//Serial.println(latitudebener);
//Serial.println(longatitudebener);
Serial.println(' ');
Serial.println(' ');
if(latitudebener!="0.00000"&&longatitudebener!="0.00000"){
sendlocation();
}
else{
};
}
}
void convert(){
char bufferlat[20];
latitudebener=dtostrf(latitudefix,5,5,bufferlat);
char bufferlon[20];
longatitudebener=dtostrf(longatitudefix,5,5,bufferlon);
}
void sendlocation(){
mySerial.println("AT+CSQ");
delay(100);
mySerial.println("AT+CGATT?");
delay(100);
mySerial.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");//setting the SAPBR, the connection type is using gprs
delay(1000);
mySerial.println("AT+SAPBR=3,1,\"APN\",\"AXIS\"");//setting the APN, the second need you fill in your local apn server
delay(4000);
mySerial.println("AT+SAPBR=1,1");//setting the SAPBR, for detail you can refer to the AT command mamual
delay(2000);;
mySerial.println("AT+HTTPINIT"); //init the HTTP request
delay(2000);
mySerial.println("AT+HTTPPARA=\"URL\",\"www.hamasa.cu.cc/editlocation.php?id="+id+"&latitude="+latitudebener+"&longatitude="+longatitudebener+"&latdir="+latdir+"&londir="+londir+"\"");
delay(2000);
mySerial.println("AT+HTTPACTION=0");//submit the request
Serial.println("8");
delay(5000);//the delay is very important, the delay time is base on the return from the website, if the return datas are very large, the time required longer.
mySerial.println("AT+HTTPREAD");// read the data from the website you access
delay(300);
mySerial.println("");
delay(100);
}
//void sms()
//{
// mySerial.println("AT+CMGF=1\r"); //Because we want to send the SMS in text mode
// delay(100);
// ShowSerialData();
// mySerial.println("AT + CMGS = \"+6283815535385\"");//send sms message,
// //be careful need to add a country code before the cellphone number
//
// delay(100);
// ShowSerialData();
// mySerial.println("bisa bil, latitudenya:"+latitudebener+""+latdir+", terus longatitudenya:"+longatitudebener+""+londir);//the content of the message
// delay(100);
// ShowSerialData();
// mySerial.println((char)26);//the ASCII code of the ctrl+z is 26
// delay(100);
// ShowSerialData();
// mySerial.println();
// ShowSerialData();
//}
void ShowSerialData()
{
while(mySerial.available()!=0)
Serial.write(mySerial.read());
}
double Datatransfer(char *data_buf,char num)//convert the data to the float type
{ //*data_buf:the data array
double temp=0.0; //the number of the right of a decimal point
unsigned char i,j;
if(data_buf[0]=='-')
{
i=1;
//process the data array
while(data_buf[i]!='.')
temp=temp*10+(data_buf[i++]-0x30);
for(j=0;j<num;j++)
temp=temp*10+(data_buf[++i]-0x30);
//convert the int type to the float type
for(j=0;j<num;j++)
temp=temp/10;
//convert to the negative numbe
temp=0-temp;
}
else//for the positive number
{
i=0;
while(data_buf[i]!='.')
temp=temp*10+(data_buf[i++]-0x30);
for(j=0;j<num;j++)
temp=temp*10+(data_buf[++i]-0x30);
for(j=0;j<num;j++)
temp=temp/10 ;
}
return temp;
}
char ID()//Match the ID commands
{
char i=0;
char value[6]={
'$','G','P','G','G','A' };//match the gps protocol
char val[6]={
'0','0','0','0','0','0' };
while(1)
{
if(Serial.available())
{
val[i] = Serial.read();//get the data from the serial interface
if(val[i]==value[i]) //Match the protocol
{
i++;
if(i==6)
{
i=0;
return 1;//break out after get the command
}
}
else
i=0;
}
}
}
void comma(char num)//get ','
{
char val;
char count=0;//count the number of ','
while(1)
{
if(Serial.available())
{
val = Serial.read();
if(val==',')
count++;
}
if(count==num)//if the command is right, run return
return;
}
}
void UTC()//get the UTC data -- the time
{
char i;
char time[9]={
'0','0','0','0','0','0','0','0','0'
};
double t=0.0;
if( ID())//check ID
{
comma(1);//remove 1 ','
//get the datas after headers
while(1)
{
if(Serial.available())
{
time[i] = Serial.read();
i++;
}
if(i==9)
{
i=0;
t=Datatransfer(time,2);//convert data
t=t+70000.00;//convert to the chinese time GMT+8 Time zone
Serial.println(t);//Print data
return;
}
}
}
}
void latitude()//get latitude
{
char i;
char lat[10]={
'0','0','0','0','0','0','0','0','0','0'};
if( ID())
{
comma(2);
while(1)
{
if(Serial.available())
{
lat[i] = Serial.read();
i++;
}
if(i==10)
{
i=0;
char buzz[20];
lati=Datatransfer(lat,5);
latu=dtostrf(lati,5,5,buzz);
String latijam=latu.substring(0,1);
String latimin=latu.substring(1,3);
String latidet=latu.substring(4,9);
double latijamd = latijam.toInt();
double latimind = latimin.toInt();
double latidetd = latidet.toInt();
double latmin = latimind+(latidetd*0.00001);
latitudefix= latijamd+(latmin/60);
Serial.println(latitudefix,5);
return;
}
}
}
}
void lat_dir()//get dimensions
{
char i=0,val;
if( ID())
{
comma(3);
while(1)
{
if(Serial.available())
{
val = Serial.read();
latdir=String(val);
Serial.print(latdir);
Serial.println();
i++;
}
if(i==1)
{
i=0;
return;
}
}
}
}
void longitude()//get longitude
{
char i;
char lon[11]={
'0','0','0','0','0','0','0','0','0','0','0' };
if( ID())
{
comma(4);
while(1)
{
if(Serial.available())
{
lon[i] = Serial.read();
i++;
}
if(i==11)
{
i=0;
//Serial.println(Datatransfer(lon,5),5);
char buffer[20];
longati=Datatransfer(lon,5);
longatu=dtostrf(longati,5,5,buffer);
String longatijam=longatu.substring(0,3);
String longatimin=longatu.substring(3,5);
String longatidet=longatu.substring(6,11);
double longatijamd = longatijam.toInt();
double longatimind = longatimin.toInt();
double longatidetd = longatidet.toInt();
double longmin = longatimind+(longatidetd*0.00001);
longatitudefix= longatijamd+(longmin/60);
Serial.println(longatitudefix,5);
return;
}
}
}
}
void lon_dir()//get direction data
{
char i=0,val;
if( ID())
{
comma(5);
while(1)
{
if(Serial.available())
{
val = Serial.read();
londir=String(val);
Serial.print(londir);
Serial.println();
i++;
}
if(i==1)
{
i=0;
return;
}
}
}
}
void altitude()//get altitude data
{
char i,flag=0;
char alt[8]={
'0','0','0','0','0','0','0','0'
};
if( ID())
{
comma(9);
while(1)
{
if(Serial.available())
{
alt[i] = Serial.read();
if(alt[i]==',')
flag=1;
else
i++;
}
if(flag)
{
i=0;
Serial.println(Datatransfer(alt,1),1);//print altitude data
return;
}
}
}
}
try to use external power. is that works?
actually it should be :
digitalWrite(3,LOW);//Enable GSM mode
digitalWrite(4,HIGH);//Disable GPS mode
The problem may be a software serial port conflict, because GPS and GSM shields both use serial ports. In your case you have coupled shields. While receiving a GPS signal, GSM is switched off, and when a signal is acquired, the GPS turns off and GSM begin to work.

Resources