Cosm example with temp and humidity sensor (DHT11) added - arduino

Added a temperature and humidity sensor (DHT11) to the standard Cosm Arduino sensor client example. Works for a short while then data streams flat line.
Any idea what could be causing the problem?
Many thanks
Staza
/**
* Cosm Arduino sensor client example.
*
`` * This sketch demonstrates connecting an Arduino to Cosm (https://cosm.com),
* using the new Arduino library to send and receive data.
/**
DHT11 temp and humidity sensor added to the COSM example code
**/
#include <SPI.h>
#include <Ethernet.h>
#include <HttpClient.h>
#include <Cosm.h>
#include <dht11.h>
//DHT11*********************************************************************
dht11 DHT11;
#define DHT11PIN 7//pin DHT11 sensor is connected to
//DHT11*********************************************************************
#define API_KEY "xxxxxx" // your Cosm API key
#define FEED_ID xxxxx // your Cosm feed ID
// MAC address for your Ethernet shield
byte mac[] = {xxxx, xxxx, xxxx, xxxx, xxxx, xxxx};
// Analog pin which we're monitoring (0 and 1 are used by the Ethernet shield)
int sensorPin = 2;
unsigned long lastConnectionTime = 0; // last time we connected to Cosm
const unsigned long connectionInterval = 15000; // delay between connecting to Cosm in milliseconds
// Initialize the Cosm library
// Define the string for our datastream ID
char sensorId[] = "sensor_reading";
char sensorId2[] = "DHT11_humidity_sensor_reading";
char sensorId3[] = "DHT11_temperature_sensor_reading";
CosmDatastream datastreams[] = {
CosmDatastream(sensorId, strlen(sensorId), DATASTREAM_FLOAT),
CosmDatastream(sensorId2, strlen(sensorId2), DATASTREAM_FLOAT),
CosmDatastream(sensorId3, strlen(sensorId3), DATASTREAM_FLOAT),
};
// Wrap the datastream into a feed
CosmFeed feed(FEED_ID, datastreams, 3 /* number of datastreams */);
EthernetClient client;
CosmClient cosmclient(client);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Cosm Sensor Client Example");
Serial.println("==========================");
Serial.println("Initializing network");
while (Ethernet.begin(mac) != 1) {
Serial.println("Error getting IP address via DHCP, trying again...");
delay(15000);
}
Serial.println("Network initialized");
Serial.println();
}
void loop() {
// main program loop
if (millis() - lastConnectionTime > connectionInterval) {
//check DHT11 sensor is working OK
int chk = DHT11.read(DHT11PIN);
Serial.print("Read DHT11 sensor: ");
switch (chk)
{
case 0: Serial.println("OK"); break;
case -1: Serial.println("Checksum error"); break;
case -2: Serial.println("Time out error"); break;
default: Serial.println("Unknown error"); break;
}
sendData(); // send data to Cosm
getData(); // read the datastream back from Cosm
lastConnectionTime = millis(); // update connection time so we wait before connecting again
}
}
// send the supplied values to Cosm, printing some debug information as we go
void sendData() {
int sensorValue = analogRead(sensorPin);
int humidityDHT11 = ((float)DHT11.humidity);
int tempDHT11 = ((float)DHT11.temperature);
datastreams[0].setFloat(sensorValue);
datastreams[1].setFloat(humidityDHT11); //DHT11 humidity value*******
datastreams[2].setFloat(tempDHT11); //DHT11 temp value********
Serial.print("Read sensor value ");
Serial.println(datastreams[0].getFloat());
Serial.print("Read DHT11 humidity sensor value ");
Serial.println(datastreams[1].getFloat());
Serial.print("Read DHT11 temperature sensor value ");
Serial.println(datastreams[2].getFloat());
Serial.println("Uploading to Cosm");
int ret = cosmclient.put(feed, API_KEY);
Serial.print("PUT return code: ");
Serial.println(ret);
Serial.println();
}
// get the value of the datastream from Cosm, printing out the value we received
void getData() {
Serial.println("Reading data from Cosm");
int ret = cosmclient.get(feed, API_KEY);
Serial.print("GET return code: ");
Serial.println(ret);
if (ret > 0) {
Serial.print("Datastream is: ");
Serial.println(feed[0]);
Serial.print("Sensor value is: ");
Serial.println(feed[0].getFloat());
Serial.print("Datastream is: ");
Serial.println(feed[1]);
Serial.print("Sensor value is: ");
Serial.println(feed[1].getFloat());
Serial.print("Datastream is: ");
Serial.println(feed[2]);
Serial.print("Sensor value is: ");
Serial.println(feed[2].getFloat());
}
Serial.println();
}

Cosm has a debug page which might give you a clue as to what's going wrong.
This is currently located at: https://cosm.com/users/YOURUSERNAME/debug and it lists all incoming requests in real time as they come through. If your device works initially, you should see it start making requests successfully, and depending on how long it takes till it flatlines you might be able to keep this page open and hopefully see when it starts failing.
Do you see anything in the Arduino serial output when it seems to stop working, or does it seem like the Arduino is still happily sending data?
The other thing you could try is using Wireshark to inspect network traffic over the wire. Setting this up is slightly more involved however, so I'd suggest trying the other approaches first.
If none of this seems feasible I'd suggest mailing Cosm support with your feed details and have them look into it.

Seconding smulube's suggestion to monitor the serial output. Additionally, eliminate the variable of the COSM code & Ethernet: start debugging the issue with a sketch that is just taking readings from the DHT11 and monitor what's going on in the Arduino's serial output on your computer (in the Tools dropdown menu).
I just received my DHT22 (RHT03) from Sparkfun last night and tried several samples that wouldn't compile (my fault, I'm sure). The sample that worked "out of the box" for me with my Arduino Uno came from Tom Boyd's page (be sure to scroll to the bottom for the most recent code): DHT11 / Aosong AM2302 humidity and temperature sensor
I'm curious: how long did it take for your sensor to flatline? I integrated the code from Tom with the Cosm code and it's been running without interruption for me for an hour now.
Cheers,
Reeves

Related

warning: overflow in implicit constant conversion [-Woverflow] in Arduino Mega 2560 WI-Fi R3

i want to record a long data for like 2 to 3 hours using microcontroller Arduino Mega 2560 WI-FI R3 but I got this warning in my code
below is the picture of the warning i got.
enter image description here
the warning come up when I put the time out constant more than 30000 milliseconds
below is the code I used for the Arduino
#include "DHT.h"
// Pin Definitions
#define DHT_PIN_OUT A1
#define DHTTYPE DHT11
#define MQ3_PIN_OUT A2
#define MQ4_PIN_OUT A3
#define MQ7_PIN_OUT A4
// Global variables and defines
// object initialization
DHT dht(DHT_PIN_OUT, DHTTYPE);
// define vars for testing menu
const int timeout = 180000; //define timeout of 1 hour
char menuOption = 0;
long time0;
// Setup the essentials for your circuit to work. It runs first every time your circuit is powered with electricity.
void setup()
{
// Setup Serial which is useful for debugging
// Use the Serial Monitor to view printed messages
Serial.begin(9600);
while (!Serial) ; // wait for serial port to connect. Needed for native USB
Serial.println("start");
dht.begin();
menuOption = menu();
}
// Main logic of your circuit. It defines the interaction between the components you selected. After setup, it runs over and over again, in an eternal loop.
void loop(){
if(menuOption == '1') {
delay(500); //delay 0.5 second
// DHT11 Humidity and Temperature Sensor
// Reading humidity in %
float dhtHumidity = dht.readHumidity();
// Read temperature in Celsius, for Fahrenheit use .readTempF()
float dhtTempC = dht.readTemperature();
float Alcohol = analogRead(MQ3_PIN_OUT);
float Methane = analogRead(MQ4_PIN_OUT);
float CarbonMonoxide = analogRead(MQ7_PIN_OUT);
Serial.print(F("Humidity: ")); Serial.print(dhtHumidity); Serial.print(F("[%]\t"));
Serial.print(F("Temp: ")); Serial.print(dhtTempC); Serial.print(F("[C]\t"));
Serial.print(F("Alcohol: ")); Serial.print(Alcohol); Serial.print(F(" \t"));
Serial.print(F("Methane: ")); Serial.print(Methane); Serial.print(F(" \t"));
Serial.print(F("Carbon Monoxide: ")); Serial.println(CarbonMonoxide); Serial.println(F(" \t"));
}
if (millis() - time0 > timeout){
menuOption = menu();
}
}
// Menu function for selecting the components to be tested
// Follow serial monitor for instrcutions
char menu(){
Serial.println(F("\nSensor Array"));
Serial.println(F("Press (1) to start the sensor array"));
while (!Serial.available());
// Read data from serial monitor if received
while (Serial.available()){
char c = Serial.read();
if (isAlphaNumeric(c))
{
if(c == '1')
Serial.println(F("Now running the sensor array"));
else{
Serial.println(F("illegal input!"));
menuOption = menu();
return 0;
}
time0 = millis();
return c;
}
}
}
sorry for my bad programming and silly question, I'm new to this kind of thing. and I just found out that people usually get answers from StackOverflow, so I just wanted to try asking because I have tried to google the answer but I can't find it.

How can I create an automated GPS tracker using A9G AI Thinker module?

I have an AI Thinker A9G module connected to an ESP8266 D1 mini. I have the following script to send and receive AT commands to/from the module. The idea is to get a SMS with the Google maps GPS location of the module onto my mobile phone.
// GPS tracker with AI Thinker A9G module and AZ Delivery D1 Mini ESP8266 module
#include <SoftwareSerial.h>
#define rxPin D7
#define txPin D8
SoftwareSerial A9modem(rxPin, txPin); // Pins D7 Rx and D8 Tx are used as used as software serial pins
String incomingData; // For storing incoming serial data
String gpsData; // For storing location data
char msg;
char call;
void setup()
{
Serial.begin(115200); // Baud rate for serial monitor
A9modem.begin(115200); // Baud rate for GSM shield
Serial.println("GPS/GSM A9G BEGIN");
Serial.println("Enter character for control option: ");
Serial.println("h : to disconnect a call");
Serial.println("s : to send a message");
Serial.println("r : to receive a message");
Serial.println("c : to make a call");
Serial.println("l : to read location");
Serial.println("d : to disconnect gps");
Serial.println();
delay(100);
// Set SMS mode to text mode
A9modem.print("AT+CMGF=1\r");
delay(100);
// Set GSM module to TP show the output on serial out
A9modem.print("AT+CNMI=2,2,0,0,0\r");
delay(100);
}
void loop()
{
ReceiveMessage();
gpsData = incomingData.substring(33, 52);
Serial.print("Location: ");
Serial.println(gpsData);
delay(2000);
if (Serial.available() > 0)
switch(Serial.read())
{
case 's':
SendMessage();
break;
case 'r':
ReceiveMessage();
break;
case 'c':
MakeCall();
break;
case 'h':
HangupCall();
break;
case 'l':
ReadLocation();
break;
case 'd':
DisconnectGps();
break;
}
}
void ReceiveMessage()
{
if (A9modem.available() > 0)
{
incomingData = A9modem.readString(); // Get the data from the serial port
Serial.print(incomingData);
delay(100);
}
}
void SendMessage()
{
A9modem.println("AT+CMGF=1"); // Sets the GSM Module into text mode
delay(1000); // Delay of one second
A9modem.println("AT+CMGS=\"xxxxxxxxxxxxx\"\r"); // Replace your mobile number here
delay(1000);
String sms = "http://maps.google.com/maps?q=" + gpsData; // Create the SMS location string
A9modem.println(sms);
delay(100);
A9modem.println((char)26); // ASCII code of CTRL+Z
delay(1000);
}
void MakeCall()
{
A9modem.println("ATD+xxxxxxxxxxxxx;"); // Replace your mobile number here
Serial.println("Calling "); // Print response over serial port
delay(1000);
}
void HangupCall()
{
A9modem.println("ATH");
Serial.println("Hangup Call");
delay(1000);
}
void DisconnectGps()
{
A9modem.println("AT+GPS=0");
Serial.println("Disconnect GPS");
delay(1000);
}
void ReadLocation()
{
A9modem.println("AT+GPS=1");
delay(1000);
A9modem.println("AT+LOCATION=2"); // Check location every two seconds
delay(2000);
}
So if I use the commands "l" and "s" in Arduino IDE serial monitor everything is working well but I don't know how to change the code in a way that I get a fully automated GPS tracker. The idea is the following: Power on starts the tracker. When gpsData string is not empty the first SMS will be send to my mobile phone. The next SMS follows 20 minutes later and so on until power is switched off. Could you help please?
Thanks in advance!
Finally I came up with this solution but I'm not very happy with it (it is working but I have to restart the module from time to time because there are no GPS data). There are 3 reasons for this: There is no error handling for the GPS function, I set the delays in a more ore less random way to get everything working but I don't know if the values make sense and I don't know if the substring() function is the best way to get the location from the serial response.
// GPS tracker with AI Thinker A9G module and AZ Delivery D1 Mini
ESP8266 module
#include <SoftwareSerial.h>
#define rxPin D7
#define txPin D8
SoftwareSerial A9modem(rxPin, txPin); // Pins D7 Rx and D8 Tx are used as used as software serial pins
String incomingData; // For storing incoming serial data
String gpsData; // For storing location data
int runGps = 1;
int sendSms = 0;
void setup()
{
pinMode(LED_BUILTIN, OUTPUT); // Use builtin LED for correct GPS status
Serial.begin(115200); // Baud rate for serial monitor
A9modem.begin(115200); // Baud rate for GSM shield
// Set SMS mode to text mode
A9modem.print("AT+CMGF=1\r");
delay(300);
// Set GSM module to TP show the output on serial out
A9modem.print("AT+CNMI=2,2,0,0,0\r");
delay(1000);
Serial.end();
delay(500);
}
void loop()
{
Serial.begin(115200);
ReceiveMessage(); // Start a new serial stream
gpsData = incomingData.substring(33, 52); // Strip all unnessesary data from the stream
Serial.print("Location: "); // Check if the location data are correct
Serial.println(gpsData);
delay(1000);
if(runGps == 1) { // Start GPS
ReadLocation();
delay(20000); // Wait for GPS to be ready
}
if(gpsData.length() == 19 && sendSms == 0) { // If the location string is correct send SMS
if (isdigit(gpsData.charAt(0))) { // Check if the stream starts with a number
SendMessage();
digitalWrite(LED_BUILTIN, HIGH);
delay(300);
digitalWrite(LED_BUILTIN, LOW);
delay(300);
digitalWrite(LED_BUILTIN, HIGH);
delay(300);
digitalWrite(LED_BUILTIN, LOW);
delay(300);
digitalWrite(LED_BUILTIN, HIGH);
}
}
if(runGps == 0 && sendSms == 1) {
runGps = 1;
sendSms = 0;
delay(6000); // Make sure that all SMS serial communication is over
while (A9modem.available()) {
A9modem.read(); // Delete all data from serial buffer
}
delay(300000); // If SMS was sent wait 5 minutes before running the main loop again
Serial.end();
delay(500);
}
}
void ReceiveMessage()
{
if (A9modem.available() > 0)
{
incomingData = A9modem.readString(); // Get the data from the serial port
Serial.print(incomingData);
delay(500);
}
}
void SendMessage()
{
sendSms = 1; // Stop starting the SendMessage function
A9modem.println("AT+CMGF=1"); // Sets the GSM Module into text mode
delay(1000);
A9modem.println("AT+CMGS=\"xxxxxxxxxx\"\r"); // Replace your mobile number here
delay(1000);
String sms = "http://maps.google.com/maps?q=" + gpsData; // Create the SMS string
A9modem.println(sms);
delay(500);
A9modem.println((char)26); // ASCII code of CTRL+Z
delay(500);
}
void ReadLocation()
{
runGps = 0; // Stop starting the ReadLocation function
A9modem.println("AT+GPS=1");
delay(1000);
A9modem.println("AT+LOCATION=2"); // Check location every two seconds
delay(2000);
}
Try turning ON the NMEA stream from the A9G. Say you want to get the NMEA data every t seconds, you can add and then call the following function once in the void setup()
void TurnOnNMEA(int t)
{
if(t > 3600)
t = 3600; // Because the max time is 3600s
A9modem.print("AT+GPSRD=");
A9modem.println(t);
while(!A9modem.available()); // wait till the A9G sends a response
char c;
while(A9modem.available())
{
c = A9modem.read();
Serial.print(c);
delay(2); // Time needed for the next character
}
}
This will start the NMEA data stream every t seconds which you can print using the following function,
void ReadNMEA()
{
char c; // Read each character from the stream as it comes
if(A9modem.available())
{
c = A9modem.read();
Serial.print(c);
delay(2); // Time needed for the next character
}
}
Parsing and decoding the NMEA is a bit tricky thing to do. There is a lot of information inside it and the decoding depends on what you want to do with it. If you just want the location, you can parse the $GNGGA line.
When parsing the data, DO NOT USE Arduino String() class. It is a very bad idea when handling this kind of stream. Instead, use char array.

How to communicate with HM-19 BLE Module and scan using ultrasonic sensor

I am working on my senior project for school, and part of what I need to do is use an HM-19 Bluetooth 5.0 module to connect to another Bluetooth 5.0 module and establish a master slave connection.
I can do that just fine, but when I include the code needed for my ultrasonic sensor to do scan, my commands to my HM-19 don't return anything and I can't do any of the basic functions such as finding connections. I have tested it with and without the ultrasonic sensor code and the problem occurs when I use the sensor portion of the code.
TO BE CLEAR, all I am trying to do is just have my Bluetooth 5.0 chip connect to another and do normal commands while also inputting into my serial monitor a distance when I put my hand in front. THIS IS JUST A TEST, once I get that done I will move to what I really want to do.
IT'S JUST A STARTING POINT IN A PROJECT. I have a function call for my sensor and my bluetooth chip in the void loop, that's all that is in there.
I just want to know how to fix this issue. How can I scan with my ultrasonic sensor and send commands to my Bluetooth module? Any help would be greatly appreciated.
[Here are the results when the sensor is commented][1] and [here are the unsuccessful results that results in an infinite loop where I can't get to the portion of the code that returns what the chip says][2]. Lastly, although most of the links include stuff for the HM-10, the commands are basically the same for the HM-19. I'm adding more because stack overflow won't let me edit this post until there are more characters or something. I hope you have a good day/evening person reading this.
Here is my code:
// SerialIn_SerialOut_HM-10_01
//
// Uses hardware serial to talk to the host computer and AltSoftSerial for communication with the bluetooth module
//
// What ever is entered in the serial monitor is sent to the connected device
// Anything received from the connected device is copied to the serial monitor
// Does not send line endings to the HM-10
//
// Pins
// BT VCC to Arduino 5V out.
// BT GND to GND
// Arduino D8 (SS RX) - BT TX no need voltage divider
// Arduino D9 (SS TX) - BT RX through a voltage divider (5v to 3.3v)
//
#include <AltSoftSerial.h>
AltSoftSerial BTserial;
// https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html
char c=' ';
boolean NL = true;
const int trigPin = 9;
const int echoPin = 10;
float duration, distance;
boolean wait_your_turn = false; //My attempt to make sure the sensor and the Bluetooth module don't interfere with each other
//if I'm sending data from the serial monitor to the bluetooth module and vice versa it switches to true and the bluetooth module
//does its thing, so the sensor doesn't get in the way.
void setup()
{
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
Serial.print("Sketch: "); Serial.println(__FILE__);
Serial.print("Uploaded: "); Serial.println(__DATE__);
Serial.println(" ");
BTserial.begin(9600);
Serial.println("BTserial started at 9600");
}
void loop()
{
Bluetooth();
Sensor();
}
void Sensor(){
if((wait_your_turn == true))
{}
else
{
Serial.println("Scanning for stuff.");
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration*.0343)/2;
if(distance <= 20)
{
Serial.println(distance);
delay(500);
}
}
}
void Bluetooth()
{
if (Serial.available())
{
if(wait_your_turn == false)
Serial.println("Serial is available");
wait_your_turn = true;
while(Serial.available()>0)
c = Serial.read();
Serial.write(c);
if(c!=10&c!=13)
BTserial.print(c);
}
if (BTserial.available())
{
// Serial.print("We are at the bluetooth portion.");
while(BTserial.available())
c = BTserial.read();
Serial.print(c);
wait_your_turn = false;
}
}
[1]: https://i.stack.imgur.com/Dn4i0.png
[2]: https://i.stack.imgur.com/s9Ifv.png
Sorry, I forgot about this question. I figured it out. What I did was have 1 Arduino control the Ultrasonic sensor and send a character to the other Arduino when something was in range of the sensor. The other Arduino would then read the character and based on the character send it would perform an action. Thank you everyone who commented and have a great rest of your days.

Get water level sensor info into esp8266-01 to upload to thingSpeak

I have a project in which I use an Arduino UNO and an esp8266-01.
The Arduino is used to gather water high and water low sensor information and then transmit that information over to turn on/off a latching relay for a water valve to fill my pool. It also turns off and on a solar panel to charge my batteries and also turns off and on the esp8266.
I want to be able to connect to the wifi every time the esp8266 comes on and then send water level sensor information and battery level sensor information up to thingSpeak.
In the following code I have made it so that the first time the esp8266 is powered up it tries to connect to the local wifi but since no ip and password is provided it go to access point mode and opens a sign in page. I also provide the user to input their thingSpeak write api. This data is saved to the esp8266's eeprom so that in the future it will auto connect and send information to thingSpeak. This works fine.
My problem is getting the information from the water level sensor and the battery level into the esp8266. I was first gathering the data on the Arduino and then having the esp8266 connect and upload the information using AT commands using SerialSoftware. However to get the AUTOCONNECT to work I had to reprogram the esp8266 and now it doesn't respond to AT commands. I have tried to reprogram the RX and TX pins on the ESP but it only has two reading when there is water present it reads 1024 and no water is 0. Nothing in between. The battery level doesn't register anything. Can I do this using the TX and RX pins somehow as an analog input or can I take the information (numbers) gathered on the Arduino and had them off to the ESP8266 using the TX (arduino) and RX (ESP)to send them to ThingSpeak. I am at a loss and need help.
Here is the code on the ESP8266
#include <FS.h>
#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
#include <EEPROM.h>
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h>
//NEW STUFF START
char Password[36]="";
char apiKey[16]="";
WiFiClient client;
//eeprom new end
char defaultHost[100] = ""; //Thing Speak IP address (sometime the web address causes issues with ESP's :/
long itt = 500;
long itt2 = 500;
const byte wifiResetPin = 13;
int interruptPinDebounce = 0;
long debouncing_time = 1000;
volatile unsigned long wifiResetLastMillis = 0;
bool shouldSaveConfig = false;
void saveConfigCallback () {
Serial.println("Should save config");
shouldSaveConfig = true;}
void handleWifiReset(){
if(millis()<wifiResetLastMillis){
wifiResetLastMillis = millis();
}
if((millis() - wifiResetLastMillis)>= debouncing_time){
Serial.println("Clearing WiFi data resetting");
WiFiManager wifiManager;
wifiManager.resetSettings();
SPIFFS.format();
ESP.reset();
delay(1000);
}
wifiResetLastMillis = millis();
}
int addr = 0;
void setup() {
//EEPROM.begin(512); //Initialize EEPROM
WiFiManager wifiManager;
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(wifiResetPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(wifiResetPin), handleWifiReset,FALLING);
WiFiManagerParameter customAPIKey("apiKey", "ThingSpeakWriteAPI", apiKey, 16);
//END NEW STUFF
//WiFiManager
//Local intialization. Once its business is done, there is no need to keep it around
//WiFiManager wifiManager;
//NEW STUFF START
//wifiManager.setSaveConfigCallback(saveConfigCallback);
wifiManager.addParameter(&customAPIKey);
//END NEW STUFF
//reset saved settings
//wifiManager.resetSettings();
//set custom ip for portal
//wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
//fetches ssid and pass from eeprom and tries to connect
//if it does not connect it starts an access point with the specified name
//here "AutoConnectAP"
//and goes into a blocking loop awaiting configuration
wifiManager.autoConnect("AutoConnectAP");
Serial.println("Connected");
//NEW STUFF START
strcpy(apiKey, customAPIKey.getValue());
if (shouldSaveConfig) {
Serial.println("saving config");
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
json["defaultHost"] = defaultHost;
json["apiKey"] = apiKey;
Serial.println("API");
Serial.print(apiKey);
String apiKey2 = String(apiKey);
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
Serial.println("failed to open config file for writing");
}
json.printTo(configFile);
json.printTo(Serial);
delay(1000);
configFile.close();
//end save
}
Serial.println("local ip");
Serial.println(WiFi.localIP());
//END NEW STUFF
//or use this for auto generated name ESP + ChipID
//wifiManager.autoConnect();
//Serial.println("WriteApi");
//Serial.println(apiKey);
//if you get here you have connected to the WiFi
//Serial.println("K)");
//save the custom parameters to FS
strcpy(apiKey,customAPIKey.getValue());
EEPROM.begin(512); //Initialize EEPROM
// write appropriate byte of the EEPROM.
// these values will remain there when the board is
// turned off.
EEPROM.write(addr, 'A'); //Write character A
addr++; //Increment address
EEPROM.write(addr, 'B'); //Write character A
addr++; //Increment address
EEPROM.write(addr, 'C'); //Write character A
//Write string to eeprom
String www = apiKey;
for(int i=0;i<www.length();i++) //loop upto string lenght www.length() returns length of string
{
EEPROM.write(0x0F+i,www[i]); //Write one by one with starting address of 0x0F
}
EEPROM.commit(); //Store data to EEPROM
//Read string from eeprom
}
//callback notifying us of the need to save config
void loop() {
Serial.begin(115200);
WiFiManager wifiManager;
if (WiFi.status() == WL_DISCONNECTED) {
wifiManager.autoConnect("AutoConnectAP");}
delay(5000);
if (WiFi.status() == WL_CONNECTED) { Serial.println("Connected");
WiFiClient client;
long itt = 500;
long itt2 = 500;
char defaultHost[100] = "api.thingspeak.com";
//HERE IS WHERE I CHANGE THE TX AND RX PIN FUNCTION
pinMode(1, FUNCTION_3);
pinMode(3, FUNCTION_3);
//THEN I ASSIGN THEM AS INPUT PINS
pinMode(1,INPUT);
pinMode(3,INPUT);
//ASSIGN EACH PIN TO AN INTERGER
const int waterInPin = 3; // Analog input pin that the potentiometer is attached to
const int BatteryInPin = 1; // Analog input pin that the battery is attached to
int waterSensorInValue;//reading our water lever sensor
int waterSensorOutValue;//conversion of water sensor value
int BatterySensorInValue;//reading our water lever sensor
int BatterySensorOutValue;//conversion of water sensor value
// put your main code here, to run repeatedly:
waterSensorInValue = analogRead(waterInPin);
BatterySensorInValue = analogRead(BatteryInPin);
waterSensorOutValue = map(waterSensorInValue,0,1024,0,225);
BatterySensorOutValue = map(BatterySensorInValue,0,1024,0,225);
Serial.println("WaterOutValue = ");
Serial.println(waterSensorOutValue );
Serial.println("WaterInValue = ");
Serial.println(waterSensorInValue );
Serial.println("BatteryOutValue = ");
Serial.println(BatterySensorOutValue );
Serial.println("BatteryInValue = ");
Serial.println(BatterySensorInValue);
//ASSIGN THE INPUT VALUES TO UPLOAD LONGS
itt = waterSensorInValue;
itt2 = BatterySensorInValue;
EEPROM.begin(512);
Serial.println(""); //Goto next line, as ESP sends some garbage when you reset it
Serial.print(char(EEPROM.read(addr))); //Read from address 0x00
addr++; //Increment address
Serial.print(char(EEPROM.read(addr))); //Read from address 0x01
addr++; //Increment address
Serial.println(char(EEPROM.read(addr))); //Read from address 0x02
//Read string from eeprom
String www;
//Here we dont know how many bytes to read it is better practice to use some terminating character
//Lets do it manually www.circuits4you.com total length is 20 characters
for(int i=0;i<16;i++)
{
www = www + char(EEPROM.read(0x0F+i)); //Read one by one with starting address of 0x0F
}
Serial.print(www); //Print the text on serial monitor
if (client.connect(defaultHost,80))
{ // "184.106.153.149" or api.thingspeak.com
itt++; //Replace with a sensor reading or something useful
//UPLOAD TO THINGSPEAK
String postStr = www;
postStr +="&field1=";
postStr += String(itt);
postStr +="&field2=";
postStr += String(itt2);
postStr += "\r\n\r\n\r\n";
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+String (www)+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n\n");
client.print(postStr);
Serial.println("% send to Thingspeak");
}
client.stop();
Serial.println("Waiting…");
}
delay(55000);
}
As I said almost everything works ok. The ESP8266 comes on when the Arduino turns it on. The sensor comes on and gets the value. A value is uploaded to ThingSpeak (just not a useful one.
Any Ideas, suggestions, examples, tutorials will be greatly appreciated. Thanks.
My suggestion is use only one ESP32 to do all this work.
It´s much simpler and easier than using two micro-controllers.
You can use the ESP32 to read and send the sensor data and save the trouble of communicating two different micros.

Arduino LORA Send and Receive Data

I tried to allow sending and receiving data using 2 Arduino Unos, 2 LORA chips (SX1278 433MHz), 2 antennas and 2 Arduino IDE.
Problem is with the receiving data command.
This is the code for SENDING command:
#include <SPI.h>
#include <LoRa.h>
int counter = 0;
const int ss = 10;
const int reset = 9;
const int dio0 = 2;
void setup() {
Serial.begin(9600);
LoRa.begin(433E6);
LoRa.setPins(ss, reset, dio0);
while (!Serial);
Serial.println("LoRa Sender");
}
void loop() {
Serial.print("Sending packet: ");
Serial.println(counter);
// send packet
LoRa.beginPacket();
LoRa.print("hello ");
LoRa.print(counter);
LoRa.endPacket();
counter++;
delay(5000);
}
On serial monitor, I succeed in sending packages, but not receiving. This is the RECEIVING code:
#include <SPI.h>
#include <LoRa.h>
const int ss = 10;
const int reset = 9;
const int dio0 = 2;
void setup() {
Serial.begin(9600);
LoRa.begin(433E6);
LoRa.setPins(ss, reset, dio0);
while (!Serial);
Serial.println("LoRa Receiver");
}
void loop() {
// try to parse packet
int packetSize = LoRa.parsePacket();
if (packetSize) {
// received a packet
Serial.print("Received packet '");
// read packet
while (LoRa.available()) {
Serial.print((char)LoRa.read());
Serial.print("hello ");
}
// print RSSI of packet
Serial.print("' with RSSI ");
Serial.println(LoRa.packetRssi());
}
}
I used instructions about connections from this git page:
https://github.com/sandeepmistry/arduino-LoRa
To make this board work, I had to explicitly initialize SPI
SPI.begin(/*sck*/ 5, /*miso*/ 19, /*mosi*/ 27, /*ss*/ cs);
It may be the same for yours. Also, you should properly initialize Lora:
while (!LoRa.begin(433E6)) {
Serial.print(".");
delay(500);
}
Serial.println("LoRa Initializing OK!");
With the code you posted, you don't really know if it initialized correcly or if it's actually sending any data.
First I haven't worked with Lora library. I worked with SX1278 libaray. So I can help you with that.
At first here is the link to the libaray - Lora SX1278.h library
Now you might ask why I'm not using the library from the original GitHub repo. Well I faced issue with that library and the issue is this:
The sx1278::getPacket() library function is modified to stabilize the Lora receive functionality. There was a bug which led the esp to panic. The payloadlength read from the REG_FIFO register was not checked for valid value which led to reading the REG_FIFO register read for over 65000 times. Moreover yield() is added in time consuming parts of this function.
That is why I'm using this custom library. Anyway, for you:
You can use this function to send packet:
T_packet_state = sx1278.sendPacketTimeoutACK(ControllerAddress, message); //T_packet_state is 0 if the packet data is sent successful.
Also to receive data use this function:
R_packet_state = sx1278.receivePacketTimeoutACK(); //R_packet_state is 0 if the packet data is received successfully.
And at the beginning of the code just define this few things:
//Lora SX1278:
#define LORA_MODE 10 //Add your suitable mode from the library
#define LORA_CHANNEL CH_6_BW_125 //Ch number and Bandwidth
#define LORA_ADDRESS 3 //Address of the device from which you will send data
uint8_t ControllerAddress = 5; //Address of receiving end device
My first decent answer on StackOverflow. Finger Crossed

Resources