I want to make LoRa receiver where LoRa messages will be sent to Firebase, but I always fail - firebase

Here's my code. I failed so many times. I managed to send the message between the LoRa receiver and the LoRa transmitter, but failed to upload to Firebase. It's said that I need primary expression, but when I look at other code and follow that, it doesn't use the code recommended by Arduino IDE.
I'm using and ESP32 and RFM95 SX1276.
#include <SPI.h>
#include <LoRa.h>
#include <WiFi.h>
#include <WiFiClient.h>
const char* ssid = "*******";
const char* password = "******";
#include <Firebase.h>
#define FIREBASE_HOST "************************"
#define FIREBASE_AUTH "************"
#define ss 5
#define rst 14
#define dio0 2
#define BAND 915E6
// Initialize variables to get and save LoRa data
int rssi;
String loRaMessage;
String temperature;
String humidity;
String readingID;
String suhu;
String lembab;
FirebaseData data;
String processor(const String& var){
//Serial.println(var);
if(var == "TEMPERATURE"){
return temperature;
}
else if(var == "HUMIDITY"){
return humidity;
} else if (var == "RRSI") {
return String(rssi);
}
return String();
}
void startLoRA(){
int counter;
LoRa.setPins(ss, rst, dio0);
while (!LoRa.begin(BAND) && counter < 10) {
Serial.print(".");
counter++;
delay(500);
}
if (counter == 10) {
// Increment readingID on every new reading
Serial.println("Starting LoRa failed!");
}
Serial.println("LoRa Initialization OK!");
}
void setup(){
Serial.begin(115200);
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
//WIFI
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() !=WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("Connected to the Network");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
startLoRA();
}
void loop(){
// Check if there are LoRa packets available
int packetSize = LoRa.parsePacket();
if (packetSize){
String LoRaData = LoRa.readString();
while (LoRa.available()){
Serial.print((char)LoRa.read());
}
// Get RSSI
rssi = LoRa.packetRssi();
Serial.print("With RSSI ");
Serial.println(rssi);
int pos1 = LoRaData.indexOf('/');
int pos2 = LoRaData.indexOf('&');
readingID = LoRaData.substring(0,pos1);
temperature = LoRaData.substring(pos1 + 1, pos2);
humidity = LoRaData.substring(pos2 + 1, LoRaData.length());
if (readingID =="001"){
suhu= temperature;
Serial.print(F("Suhu :"));
Serial.println(suhu);
Serial.println(F("C"));
lembab= humidity;
Serial.print(F("Kelembaban : "));
Serial.print(lembab);
Serial.println("%");
String fbsuhu = String (suhu) + String("C");
String fblembab = String (lembab) + String("%");
Firebase.setString (FirebaseData, "Suhu :", fbsuhu);
Firebase.setString (FirebaseData, "Lembab :", fblembab);
}
}
}

As far as I understand the Firebase library, it's Firebase.setString(key, value);. So only two arguments. You are passing three.

Related

Arduino HTTP Client not connecting to Firebase

I am trying to post GPS data to firebase using the Arduino Uno R3, SIM800L and NEO6M via GPRS. I have managed to connect to the APN, but I can't get the "http_client.connect()" to work. It keeps giving the same error.
Code
#define TINY_GSM_MODEM_SIM800
#define TINY_GSM_RX_BUFFER 256
#include <TinyGsmClient.h>
#include <ArduinoHttpClient.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#define SerialMonitor Serial
#define ARDUINO_GPS_RX 3
#define ARDUINO_GPS_TX 2
TinyGPSPlus tinyGPS;
SoftwareSerial ss(ARDUINO_GPS_TX , ARDUINO_GPS_RX);
#define gpsPort ss
#define rxPin 9
#define txPin 8
SoftwareSerial sim800(txPin,rxPin);
const char FIREBASE_HOST[] = "realtimedatabase.firebaseio.com";
const String FIREBASE_AUTH = "";
const String FIREBASE_PATH = "/gps-data/coordinate/employee_03";
const int SSL_PORT = 443;
char apn[] = "";
char user[] = "";
char pass[] = "";
TinyGsm modem(sim800);
TinyGsmClientSecure gsm_client_secure_modem(modem,0);
HttpClient http_client = HttpClient(gsm_client_secure_modem, FIREBASE_HOST, SSL_PORT);
unsigned long previousMillis = 0;
void setup()
{
Serial.begin(9600);
gpsPort.begin(9600);
Serial.println(F("gps serial initialize"));
sim800.begin(9600);
Serial.println(F("SIM800A serial initialize"));
Serial.println(F("Initializing modem..."));
modem.init();
String modemInfo = modem.getModemInfo();
Serial.print(F("Modem: "));
Serial.println(modemInfo);
http_client.setHttpResponseTimeout(10 * 1000);
}
void loop()
{
Serial.print(F("Connecting to "));
Serial.print(apn);
if (!modem.gprsConnect(apn, user, pass))
{
Serial.println(F(" fail"));
//delay(1000);
return;
}
Serial.println(F(" OK"));
if (modem.isGprsConnected()) { Serial.println("GPRS connected"); }
http_client.connect(FIREBASE_HOST, SSL_PORT);
while (true) {
if (!http_client.connected())
{
Serial.println();
http_client.stop();// Shutdown
Serial.println(F("HTTP not connected"));
break;
}
else
{
//ss.listen();
gps_loop();
}
}
}
void PostToFirebase(const char* method, const String & path , const String & data, HttpClient* http)
{
String response;
int statusCode = 0;
http->connectionKeepAlive();
String url;
if (path[0] != '/')
{
url = "/";
}
url += path + ".json";
url += "?auth=" + FIREBASE_AUTH;
Serial.print("POST:");
Serial.println(url);
Serial.print("Data:");
Serial.println(data);
String contentType = "application/json";
http->put(url, contentType, data);
statusCode = http->responseStatusCode();
Serial.print(F("Status code: "));
Serial.println(statusCode);
response = http->responseBody();
Serial.print(F("Response: "));
Serial.println(response);
if (!http->connected())
{
Serial.println();
http->stop();// Shutdown
Serial.println(F("HTTP POST disconnected"));
}
}
void gps_loop()
{
// ss.listen();
boolean newData = false;
for (unsigned long start = millis(); millis() - start < 2000;){
//ss.listen();
while (ss.available()){
if (tinyGPS.encode(ss.read())){
newData = true;
break;
}
}
}
if(true){
newData = false;
String latitude, longitude;
latitude = String(tinyGPS.location.lat(), 6);
longitude = String(tinyGPS.location.lng(), 6);
Serial.print("Latitude= ");
Serial.print(latitude);
Serial.print(" Longitude= ");
Serial.println(longitude);
String gpsData = "{";
gpsData += "\"lat\":" + latitude + ",";
gpsData += "\"lng\":" + longitude + "";
gpsData += "}";
PostToFirebase("PATCH", FIREBASE_PATH, gpsData, &http_client);
}
}
Error
gps serial initialize
SIM800A serial initialize
Initializing modem...
Modem: SIM800 R14.18
Connecting to apn OK
GPRS connected
HTTP not connected
Connecting to apn OK
GPRS connected
I have tried using ESP8266 (Wemos D1 R1) to save my GPS data to the database via WiFi, and that worked. Now, the problem is I can't connect to the firebase database using my Arduino and SIM800L. What should I do?

Unable to establish connection to mosquitto broker from Arduino+ESP8266

I am using Arduino Uno and ESP8266 for WIFI connectivity. My Laptop on which mosquitto broker is running and Arduino(through ESP8266) is are both connected to wifi network. But I am unable to establish a connection to mqtt server.
I am using the follwing code.
#define FASTLED_INTERNAL
#include <SoftwareSerial.h>
#include <DHT.h>
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <WiFiEspUdp.h>
#include <PubSubClient.h>
#include <FastLED.h>
#define DHTPIN 2
#define DHTTYPE DHT11
#define ESP_RX 9
#define ESP_TX 8
#define WIFI_AP "Anurag"
#define WIFI_PASSWORD "qwerty12345"
#define NUM_LED 64
#define DATA_PIN 5
#define CLOCK_PIN 13
static const int RXPin = 4, TXPin = 3;
static const uint32_t baudRate = 9600;
static const int rainSensorMin = 0;
static const int rainSensorMax = 1024;
WiFiEspClient espClient;
PubSubClient mqttClient(espClient);
IPAddress broker(192,168,43,235);
SoftwareSerial ESP8266(ESP_RX, ESP_TX);
DHT dht(DHTPIN, DHTTYPE);
int status = WL_IDLE_STATUS;
char *ID = "uno";
char *TOPIC = "weatherStats";
int AT_cmd_time;
boolean AT_cmd_result = false;
CRGB leds[NUM_LED];
void setup() {
//pinMode(13, OUTPUT);
//FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LED);
Serial.begin(9600);
//ss.begin(baudRate);
initWiFi();
dht.begin();
mqttClient.setServer(broker,1883);
Serial.println("GPS, DHT11, and, Raindrop detector started.");
}
void loop() {
status = WiFi.status();
if ( status != WL_CONNECTED) {
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(WIFI_AP);
// Connect to WPA/WPA2 network
status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
delay(500);
}
Serial.println("Connected to AP");
}
delay(3000);
float h = dht.readHumidity();
float t = dht.readTemperature();
int rainReading = analogRead(A0);
int range = map(rainReading, rainSensorMin, rainSensorMax, 0, 2);
if(!mqttClient.connected()){
reconnect_mqtt();
}
mqttClient.loop();
mqttClient.publish(TOPIC,"one step forward");
//Serial.println("Satellites: " + String(gps.satellites.value()));
if (!isnan(h) || !isnan(t))
Serial.print("Temparture: " + String(t) + "°C | " + " Humidity: " + String(h) + " | ");
else {
Serial.println("Failed to obtain temparature and humidity data");
}
switch (range) {
case 0:
Serial.print("Rain Warning : 1");
break;
case 1:
Serial.print("Rain Warning : 0");
break;
}
Serial.println(" | Lat: 22.716191217468406 Lon: 72.44229199663788");
}
void initWiFi(){
ESP8266.begin(9600);
WiFi.init(&ESP8266);
// check for the presence of the shield
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue
while (true) {
}
}
// attempt to connect to WiFi network
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(WIFI_AP);
//Connect to WPA/WPA2 network
status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
}
}
void reconnect_mqtt(){
while(!mqttClient.connected()){
Serial.println("Attempting MQTT Connection");
if(mqttClient.connect(ID)){
Serial.println("MQTT connection established.");
Serial.print("Publishing to: ");
Serial.println(TOPIC);
}
else{
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
Runnig this code I keep getting output "try again in 5 seconds". Please help.

ESP12F, cant get a relay to work with data from dht11

i've been trying to build a system that detects in one room of the house the temperature using an esp8266 and a dht11 sensor, this esp sends the data to a webserver while the ESP12F grabs this data and should turn the relay on when a certain value is reached, however i can't get the relay to work, as soon as i upload the code, the led on the module turns but not at its full power, i tried with another code to see if it was just a faulty relay, but it works perfectly with the same connections. The code from the client side of the system is below:
#include "ESP8266WiFi.h"
#include "ESP8266HTTPClient.h"
#include "WiFiClient.h"
#include "ESP8266WiFiMulti.h"
ESP8266WiFiMulti WiFiMulti;
const char* ssid = "*******";
const char* password = "********";
//Your IP address or domain name with URL path
const char* serverNameTemp = "http://192.168.1.188/temperature";
const char* serverNameHumi = "http://192.168.1.188/humidity";
const char* serverNamePres = "http://192.168.1.188/pressure";
#include "Wire.h"
#include "Adafruit_GFX.h"
#include "Adafruit_SSD1306.h"
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
String temperature;
String humidity;
String pressure;
const int relay = 5;
float temp_int = temperature.toFloat();
unsigned long previousMillis = 0;
const long interval = 2000;
void setup() {
Serial.begin(115200);
Serial.println();
pinMode(relay,OUTPUT);
digitalWrite(relay,LOW);
// Address 0x3C for 128x64, you might need to change this value (use an I2C scanner)
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
display.clearDisplay();
display.setTextColor(WHITE);
int int_temp = temperature.toFloat();
WiFi.mode(WIFI_STA);
WiFiMulti.addAP(ssid, password);
while((WiFiMulti.run() == WL_CONNECTED)) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected to WiFi");
}
void loop() {
unsigned long currentMillis = millis();
if(currentMillis - previousMillis >= interval) {
// Check WiFi connection status
if ((WiFiMulti.run() == WL_CONNECTED)) {
int int_temp = temperature.toFloat();
temperature = httpGETRequest(serverNameTemp);
humidity = httpGETRequest(serverNameHumi);
pressure = httpGETRequest(serverNamePres);
if(int_temp < 26){
digitalWrite(relay,LOW);
}
else if (int_temp > 26){
digitalWrite(relay,HIGH);
}
Serial.println("Temperature: " + temperature + " *C - Humidity: " + humidity + " % - Pressure: " + pressure + " hPa");
Serial.println(int_temp);
Serial.println(temperature.toFloat());
display.clearDisplay();
// display temperature
display.setTextSize(2);
display.setCursor(0,0);
display.print("T: ");
display.print(temperature);
display.print(" ");
display.setTextSize(1);
display.cp437(true);
display.write(248);
display.setTextSize(2);
display.print("C");
// display humidity
display.setTextSize(2);
display.setCursor(0, 25);
display.print("H: ");
display.print(humidity);
display.print(" %");
// display pressure
display.setTextSize(2);
display.setCursor(0, 50);
display.print("P:");
display.print(pressure);
display.setTextSize(1);
display.setCursor(110, 56);
display.print("hPa");
display.display();
// save the last HTTP GET Request
previousMillis = currentMillis;
}
else {
Serial.println("WiFi Disconnected");
}
}
}
String httpGETRequest(const char* serverName) {
WiFiClient client;
HTTPClient http;
// Your IP address with path or Domain name with URL path
http.begin(client, serverName);
// Send HTTP POST request
int httpResponseCode = http.GET();
String payload = "--";
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
payload = http.getString();
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
return payload;
}

ESP8266 stopped receiving data from firebase

I am trying to receive data from firebase to my ESP8266 so that I can send a mail using received data on button press. But the ESP stops receiving data after a couple of minutes. Can anyone tell the reason behind it?
Here's the code.
#include <ESP8266WiFi.h>
#include "Gsender.h"
#include <FirebaseArduino.h>
#define FIREBASE_HOST "iotapp11.firebaseio.com"
int button = 0;
const char* ssid = "Redmi 3s";
const char* password = "alohomora";
void setup()
{
pinMode(button,INPUT);
Serial.begin(115200);
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");}
Serial.println(" connected");
Serial.println(WiFi.localIP());
Firebase.begin(FIREBASE_HOST);
}
void loop(){
Firebase.get(FIREBASE_HOST); //Tried putting it in void setup and even removed it but nothing worked.
int but_val = digitalRead(button);
Gsender *gsender = Gsender::Instance();
String emailid =Firebase.getString("Email");
String subject =Firebase.getString("Subject");
String content =Firebase.getString("Content");
Serial.println(emailid);
Serial.println(subject);
Serial.println(content);
if ( but_val == LOW){
Serial.println("Button pressed");
delay(1000);
gsender->Subject(subject)->Send(emailid, content) ;
Serial.println("Message sent.");
delay(1000);
} else {
Serial.println("Button Not pressed");
delay(1000);
}
}

ESP32 Radio - How to improve the sound quality?

I got this ESP32 Radio source code from this site.
I love it because its very simple radio and works fine on ESP32.
But sometime the sound is very choppy.
I suspect maybe because a lack of proper buffers, but I don't know how to fix it.
The code:
/*
WITHOUT OLED, only ESP32 & VS1053
VS1053 - connections detail
XRST = EN (D3)
MISO = D19
MOSI = D23
SCLK = D18
VCC = 5V / 3.3 V
Gnd = Gnd
*/
#include <VS1053.h> //ESP_VS1053_Library
#include <Preferences.h> //For reading and writing into the ROM memory
Preferences preferences;
unsigned int counter,old_counter,new_counter;
#include "helloMp3.h"
#include <WiFi.h>
#include <HTTPClient.h>
#include <esp_wifi.h>
char ssid[] = "SSID"; // your network SSID (name)
char pass[] = "PASSWORD"; // your network password
char *host[7] = {"184.95.47.178","us4.internet-radio.com","us3.internet-radio.com","us3.internet-radio.com","174.36.206.197","sj64.hnux.com","uk7.internet-radio.com"};
char *path[7] = {"/","/","/live.m3u","/","/","/","/"};
int port[7] = {9328,8266,8371,8297,8000,80,8226};
char *sname[7] = {"Love-Radio-USA","Smooth-Jazz-Florida","Best-Rock-Radio","Country-Radio","Venice-Classic-Radio","Smooth-Jazz-Global","UK-Top-40"};
int change=13;
bool x=true;
int status = WL_IDLE_STATUS;
WiFiClient client;
uint8_t mp3buff[32]; // vs1053 likes 32 bytes at a time
// Wiring of VS1053 board (SPI connected in a standard way)
#define VS1053_CS 32 //32
#define VS1053_DCS 33 //33
#define VS1053_DREQ 35 //15
#define VOLUME 100 // volume level 0-100
VS1053 player(VS1053_CS, VS1053_DCS, VS1053_DREQ);
void setup () {
pinMode(change,INPUT_PULLUP);
// initialize SPI
Serial.begin(115200);
delay(500);
// initialize SPI bus;
SPI.begin();
// initialize VS1053 player
player.begin();
// player.switchToMp3Mode(); // optional, some boards require this
player.setVolume(VOLUME);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
// display.drawString(0,15," Connecting..");
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
Serial.print("IP address:");
Serial.println(WiFi.localIP());
preferences.begin("my-app", false);
counter = preferences.getUInt("counter", 0);
old_counter=counter;
Serial.printf("Current counter value1: %u\n", counter);
//if(counter>0) counter=0;
//Serial.printf("Current counter value2: %u\n", counter);
delay(100);
player.playChunk(hello2, sizeof(hello2)); //VS1053 is wake up & running
station_connect(counter);
}
void loop() {
if (client.available() > 0) {
uint8_t bytesread = client.read(mp3buff, 32);
player.playChunk(mp3buff, bytesread);
}
if(digitalRead(change)==0 and x==true){
x=false;
counter = counter+1;
if(counter>6) counter=0;
preferences.putUInt("counter",counter);
new_counter=counter;
Serial.printf("Old_Counter: %u\n",old_counter);
Serial.printf("New_Counter: %u\n",new_counter);
Serial.printf("Set counter to new_value: %u\n", counter);
delay(500);
if(old_counter != new_counter) {
player.softReset();
x=true;
station_connect(new_counter);
preferences.putUInt("counter",new_counter);
}
}
}
void station_connect (int station_no ) {
if (client.connect(host[station_no],port[station_no]) ) {
Serial.println("Connected now");
}
Serial.print(host[station_no]);
Serial.println(path[station_no]);
Serial.println(sname[station_no]);
client.print(String("GET ") + path[station_no] + " HTTP/1.1\r\n" +
"Host: " + host[station_no] + "\r\n" +
"Connection: close\r\n\r\n");
}
How to improve the sound quality? Please help
Thanks for all the helpers! :)

Resources