Error in sending data to cloud server and arduino lagging - arduino

The code im working on, is suppose to show temperature, humidity and able to take and show heart rate on the lcd. After data is shown, it will send data to "ThingSpeak". After sending, there will be a http code error -401 which is ok as it can only send data very 15 sec. But after awhile, it will change it error http code -301... and then it will hang. Another issue is when i try to use the temperature sensor with the heart rate sensor, the lcd will hang and it will not work till i reset.
#include "ThingSpeak.h"
#include "SPI.h"
#include "DHT.h"
#include <Ethernet.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(10, 9, 5, 4, 3, 2); //numbers of interface pins
#define redLED 8
int sensorPin = A8;
float tempC;
#define DHTPIN 6
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
float h;
#define USE_ARDUINO_INTERRUPTS true // Set-up low-level interrupts for most acurate BPM math.
#include <PulseSensorPlayground.h> // Includes the PulseSensorPlayground Library.
// Variables
const int PulseWire = A9; // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
const int blinkPin = 22; // The on-board Arduino LED, close to PIN 13.
int Threshold = 550; // Determine which Signal to "count as a beat" and which to ignore.
PulseSensorPlayground pulseSensor; // Creates an instance of the PulseSensorPlayground object called "pulseSensor"
byte mac[] = {0x90, 0xA2, 0xDA, 0x10, 0x40, 0x4F};
unsigned long myChannelNumber = ;
const char * myWriteAPIKey = "";
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(172, 17, 171, 199);
IPAddress myDns(172, 17, 171, 254);
float get_temperature(int pin)
{
float temperature = analogRead(pin); // Calculate the temperature based on the reading and send that value back
float voltage = temperature * 5.0;
voltage = voltage / 1024.0;
return ((voltage - 0.5) * 100);
}
EthernetClient client;
void setup()
{
lcd.begin(16, 2);
pinMode(redLED, OUTPUT);
pulseSensor.analogInput(PulseWire);
pulseSensor.blinkOnPulse(blinkPin); //auto-magically blink Arduino's LED with heartbeat.
pulseSensor.setThreshold(Threshold);
pulseSensor.begin();
dht.begin();
Ethernet.init(10); // Most Arduino Ethernet hardware
Serial.begin(9600); //Initialize serial
// start the Ethernet connection:
Serial.println("Initialize Ethernet with DHCP:");
if (Ethernet.begin(mac) == 0)
{
Serial.println("Failed to configure Ethernet using DHCP");
// Check for Ethernet hardware present
if (Ethernet.hardwareStatus() == EthernetNoHardware)
{
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
while (true)
{
delay(10); // do nothing, no point running without Ethernet hardware
}
}
if (Ethernet.linkStatus() == LinkOFF)
{
Serial.println("Ethernet cable is not connected.");
}
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, ip, myDns);
}
else
{
Serial.print(" DHCP assigned IP ");
Serial.println(Ethernet.localIP());
}
// give the Ethernet shield a second to initialize:
delay(1000);
ThingSpeak.begin(client); // Initialize ThingSpeak
}
void loop()
{
h = dht.readHumidity();
{
tempC = get_temperature(sensorPin);
}
if (tempC < 31)
{
lcd.setCursor(0, 0);
lcd.print(tempC);
lcd.print(" "); //print the temp
lcd.print((char)223); // to get ° symbol
lcd.print("C");
lcd.print(" ");
lcd.print(h);
lcd.print("%");
delay(750);
}
else if (tempC > 31)
{
lcd.setCursor(0, 0);
lcd.print(tempC);
lcd.print(" "); //print the temp
lcd.print((char)223); // to get ° symbol
lcd.print("C");
lcd.print(" ");
lcd.print(h);
lcd.print("%");
delay(750);
}
int myBPM = pulseSensor.getBeatsPerMinute(); // Calls function on our pulseSensor object that returns BPM as an "int".
// "myBPM" hold this BPM value now.
if (pulseSensor.sawStartOfBeat())
{
lcd.setCursor(0,1);
lcd.print("BPM:"); // Print phrase "BPM: "
lcd.println(myBPM); // Print the value inside of myBPM.
lcd.print(" ");
delay(100);
}
// Write to ThingSpeak channel.
ThingSpeak.setField(1, tempC);
ThingSpeak.setField(2, h);
ThingSpeak.setField(3, myBPM);
int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if (x == 200)
{
Serial.println("Channel update successful.");
}
else
{
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
}

Related

TTGO ESP32 + GSM 800l AT Commands

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

can't recieve a msg on node red published from arduino using mqtt protocol

i have a problem in my arduino code, i'm using esp8266 to get data from a sensor, and i have to send this data to node red dashboard using mqtt protocol. The problem is that i couldn't publish a "string".
this is my code:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#define Potentiometer A0
char ssid[] = "Fixbox-71CD43"; // your network SSID (name)
char pass[] = "ZTA0NWY2"; // your network password (use for WPA, or use as key for WEP)
//int keyIndex = 0; // your network key Index number (needed only for WEP)
const char* mqtt_server = "192.168.0.4";
int status = WL_IDLE_STATUS;
// if you don't want to use DNS (and reduce your sketch size)
// use the static IP instead of the name for the server:
// IPAddress server(74,125,232,128); // static IP for Google (no DNS)
//char server[] = "www.google.com"; // name address for Google (using DNS)
WiFiClient espclient;
PubSubClient client(espclient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
//char msg[MSG_BUFFER_SIZE];
//char message[50];
int sensorValue;
float VWC, Threshold1, Threshold2 , SubCalSlope, SubCalIntercept;
void setup() {
//*********************//*********************
// Declare variables for four 10HS sensors
//*********************//*********************
//*********************//*********************
unsigned long lastMsg = 0;
//*********************//*********************
//*********************//*********************
// SUBSTRATE CALIBRATION: You have to convert the voltage to VWC using soil or substrate specific calibration. Decagon has generic calibrations (check the 10HS manual at http://manuals.decagon.com/Manuals/13508_10HS_Web.pdf) or you can determine your own calibration. We used our own calibration for Fafard 1P (peat: perlite, Conrad Fafard, Inc., Agawam, MA)
SubCalSlope = 1.1785;
SubCalIntercept = -0.4938;
// IRRIGATION THRESHOLDS: Values used to trigger irrigation when the sensor readings are below a specific VWC (in units of m3/m3 or L/L)
Threshold1 = 0.4;
Threshold2 = 0.6;
//*********************//*********************
Serial.begin(115200);
// Configure digital pins D2 and D3 as outputs to apply voltage to all four sensors (D2: sensor 1 and 2; D3, sensor 3 and 4)
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
// client.setCallback(callback);
// initialize serial communication:
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// initialize the WiFi module:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi module not detected");
// don't continue:
while (true);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to WiFi network ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected.\nWiFi network status:");
printWifiStatus();
Serial.println("\nStarting connection to MQTT server...");
client.setServer(mqtt_server, 1883);
// if you get a connection, report back via serial:
}
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("GW_sensor/humidity", "hello world");
client.publish("GW_sensor/salinity", "hello world");
// ... and resubscribe
client.subscribe("GW_sensor/#");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi device's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
void loop() {
char msg[10];
char msgtext[25];
String themsg;
// if there are incoming bytes available
// from the server, read them and print them:
// if the server's disconnected, stop the client:
if (!client.connected()) {
reconnect();
}
client.loop();
//*********************
// Apply power to 10HS sensor
// Wait 10 ms,
delay(10);
// Measure the analog output from sensor #1 and #2 (red wires connected to analog pins A0 and A1)
sensorValue = analogRead(0);
// And turn the power to the sensors off
digitalWrite(2, LOW);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 1.1V) that is used to calculate the VWC using a calibration equation
VWC = sensorValue * (1.1/1023.0) * SubCalSlope + SubCalIntercept;
//*********************//*********************
// Print the VWC
Serial.print("VWC (m3/m3): ");
Serial.print(" = ");
Serial.print(VWC);
//*********************//*********************
unsigned long now = millis();
//send data every 6 second
if (now - lastMsg > 500) {
lastMsg = now;
// Check to see if the VWC reading is below Threshold1
if (VWC < Threshold1) {
// If so, write an error message to the screen
Serial.print("WARNING:(too low) Irrigation needed. ");
sprintf(msgtext,"Irrigation needed",VWC);
}
// If the measured VWC is > Threshold2
if (VWC > Threshold2) {
// Write an error message to the screen
Serial.print("WARNING:(too high) Irrigation not needed. ");
sprintf(msgtext,"Irrigation not needed",VWC);
}
sprintf(msg,"%i",VWC);
//publish sensor data to MQTT broker
client.publish("GW_sensor/VWC_msg", msgtext);
client.publish("GW_sensor/VWC_val", msg);
}
please can you help me to fix my code? it can only send the values to the broker and the msg.
thank you all!
Payload isn't a "String", its a char buffer.
You need something like this:
snprintf (msg, BUF_SIZE, "msg: %i", VWC)
client.publish("GW_sensor/VWC_msg", msg)
The PubSubClient repo even has an ESP8266 example: https://github.com/knolleary/pubsubclient/blob/master/examples/mqtt_esp8266/mqtt_esp8266.ino

How can I make a NeoPixels LED animation be toggled on/off by an OSC message?

Currently I am attempting to figure out how to control my Adafruit NeoPixels strip using OSC. More specifically, I am using TouchOSC to send/receive messages over WiFi from my NodeMCU ESP8266 microcontroller, which is connected to my NeoPixels.
I have downloaded some test code that somebody else made that listens for OSC messages to toggle the tiny LED on the NodeMCU board on/off. When the controller receives the message, it sends the message back to the TouchOSC client to tell whether or not the light is on (it's a toggle button). This all works perfectly fine.
I've written a simple function that animates the NeoPixel LED strip connected to the NodeMCU board. On its own, this also works perfectly fine.
What I've been struggling with is to figure out a way to get my function [the one called gwBlink()] to run in a loop when the LED is toggled on.
I've attached the code. Could somebody tell me what I'm doing wrong?? I would be eternally grateful for any help!! :)
The TouchOSC interface:
/**
* Send and receive OSC messages between NodeMCU and another OSC speaking device.
* Send Case: Press a physical button (connected to NodeMCU) and get informed about it on your smartphone screen
* Receive Case: Switch an LED (connected to NodeMCU) on or off via Smartphone
* Created by Fabian Fiess in November 2016
* Inspired by Oscuino Library Examples, Make Magazine 12/2015
*/
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <OSCMessage.h> // for sending OSC messages
#include <OSCBundle.h> // for receiving OSC messages
#include <Adafruit_NeoPixel.h>
#define PIN 3
Adafruit_NeoPixel strip = Adafruit_NeoPixel(58, 3, NEO_GRB + NEO_KHZ800);
char ssid[] = "XXX"; // your network SSID (name)
char pass[] = "XXX"; // your network password
// Button Input + LED Output
const int btnPin = 12; // D6 pin at NodeMCU
const int ledPin = 14; // D5 pin at NodeMCU
const int boardLed = LED_BUILTIN; // Builtin LED
boolean btnChanged = false;
int btnVal = 1;
WiFiUDP Udp; // A UDP instance to let us send and receive packets over UDP
const IPAddress destIp(192,168,0,10); // remote IP of the target device (i.e. THE PHONE)
const unsigned int destPort = 12000; // remote port of the target device where the NodeMCU sends OSC to
const unsigned int localPort = 10000; // local port to listen for UDP packets at the NodeMCU (another device must send OSC messages to this port)
unsigned int ledState = 1; // LOW means led is *on*
void setup() {
strip.begin();
strip.show();
Serial.begin(115200);
// Specify a static IP address for NodeMCU - only needeed for receiving messages)
// If you erase this line, your ESP8266 will get a dynamic IP address
WiFi.config(IPAddress(192,168,0,13),IPAddress(192,168,0,1), IPAddress(255,255,255,0));
// Connect to WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Starting UDP");
Udp.begin(localPort);
Serial.print("Local port: ");
Serial.println(Udp.localPort());
// btnInput + LED Output
pinMode(btnPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(boardLed, OUTPUT);
}
void loop() {
receiveOSC();
sendOSC();
}
void sendOSC(){
// read btnInput and send OSC
OSCMessage msgOut("/1/buttonListener");
if(digitalRead(btnPin) != btnVal) {
btnChanged = true;
btnVal = digitalRead(btnPin);
}
if(btnChanged == true){
btnChanged = false;
digitalWrite(ledPin, btnVal);
digitalWrite(boardLed, (btnVal + 1) % 2); // strange, but for the builtin LED 0 means on, 1 means off
Serial.print("Button: ");
Serial.println(btnVal);
msgOut.add(btnVal);
}
Udp.beginPacket(destIp, destPort);
msgOut.send(Udp);
Udp.endPacket();
msgOut.empty();
delay(100);
}
void receiveOSC(){
OSCMessage msgIN;
int size;
if((size = Udp.parsePacket())>0){
while(size--)
msgIN.fill(Udp.read());
if(!msgIN.hasError()){
msgIN.route("/1/toggleLED",toggleOnOff);
}
}
}
void gwBlink() {
// LED strip animation
uint16_t i, j;
for(i = 0; i < strip.numPixels(); i = i + 2) {
strip.setPixelColor(i, 0, 182, 90);
}
for(j = 1; j < strip.numPixels(); j = j + 2) {
strip.setPixelColor(j, 128, 128, 128);
}
strip.show();
delay(100);
for(i = 0; i < strip.numPixels(); i = i + 2) {
strip.setPixelColor(i, 128, 128, 128);
}
for(j = 1; j < strip.numPixels(); j = j + 2) {
strip.setPixelColor(j, 0, 182, 90);
}
strip.show();
delay(100);
}
void toggleOnOff(OSCMessage &msg, int addrOffset){
ledState = (boolean) msg.getFloat(0);
digitalWrite(boardLed, (ledState + 1) % 2); // Onboard LED works the wrong direction (1 = 0 bzw. 0 = 1)
digitalWrite(ledPin, ledState); // External LED
if (ledState) {
Serial.println("LED on");
gwBlink();
}
else {
Serial.println("LED off");
strip.clear();
}
ledState = !ledState; // toggle the state from HIGH to LOW to HIGH to LOW ...
}
This code actually works fine as far as switching the little LED on the board on/off, but my animation function isn't triggered.
I have only been working with NeoPixels for a short time, but I had problems when trying to use them & serial monitor simultaneously. Once I disabled the serial command (//Serial.begin(115200);), they worked fine. The documentation doesn't plainly state this, I discovered it in a thread where an Adafruit Admin referred to using serial while trying to also update the NeoPixels as a "pain".
If commenting out Serial.begin fixes your problem, then I guess you can experiment with:
*if (Serial.available()) {
int inByte = Serial.read();
Serial1.print(inByte, DEC);
}*
...idk, but it's worth trying.

Working a temprature sensor (LM35) with a GSM module (Sim800L)

I have a temperature sensor set up working with an LCD and a stick to adjust the brightness. I now want the temperature sensor to send a text whenever it reaches a certain temperature. Can somebody please help.
The GSM unit i have is the SIM800L
below is what I have so far :
#include<LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int sensor=A1; // Assigning Analog Pin A1 to variable 'sensor'
float tempc; //variable to store temperature in degree Celsius
float tempf; //variable to store temperature in Fahrenheit
float vout; //temporary variable to hold sensor reading
void setup()
{
pinMode(sensor,INPUT); // Configuring pin A1 as INPUT Pin
Serial.begin(9600);
lcd.begin(16,2);
delay(500);
}
void loop()
{
vout=analogRead(sensor);
vout=(vout*500)/1023;
tempc=vout; // Storing value in degrees Celsius
tempf=(vout*1.8)+32; // Converting Temperature value from degrees Celsius to Fahrenheit
lcd.setCursor(0,0);
lcd.print("DegreeC= ");
lcd.print(tempc);
lcd.setCursor(0,1);
lcd.print("Fahrenheit=");
lcd.print(tempf);
delay(1000); //Delay of 1 second for ease of viewing in serial monitor
}
you could use the library Fona to send SMS with a Sim800L
to send a message you use the command -> fona.sendSMS(sendto, message)
#include <SoftwareSerial.h>
#include "Adafruit_FONA.h"
//This part declares that the RX, TX and RST pins of the SIM800L must be connected
//to pin 2, 3 and 4 of the Arduino.
#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4
SoftwareSerial fonaSS = SoftwareSerial(FONA_RX, FONA_TX);
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
void setup() {
while (!Serial);
Serial.begin(115200);
Serial.println(F("FONA basic test"));
Serial.println(F("Initializing....(May take 3 seconds)"));
fonaSS.begin(9600);
if (!fona.begin(fonaSS)) {
Serial.println(F("Couldn't find FONA"));
while (1);
}
Serial.println(F("FONA is OK"));
char sendto[21], message[141];
:
:
//initialize sendto and message
:
:
if (!fona.sendSMS(sendto, message)) {
Serial.println(F("error"));
} else {
Serial.println(F("sent!"));
}
}
to adapt the program to your case: i have put some lines of codes from setup to loop (easy to understant sendto and message definitions in loop now)
#include <SoftwareSerial.h>
#include "Adafruit_FONA.h"
//This part declares that the RX, TX and RST pins of the SIM800L must be connected
//to pin 2, 3 and 4 of the Arduino.
#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4
SoftwareSerial fonaSS = SoftwareSerial(FONA_RX, FONA_TX);
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
void setup() {
fonaSS.begin(9600);
// you initialisation code
}
void loop()
{
vout=analogRead(sensor);
vout=(vout*500)/1023;
tempc=vout; // Storing value in degrees Celsius
tempf=(vout*1.8)+32; // Converting Temperature value from degrees Celsius to Fahrenheit
lcd.setCursor(0,0);
lcd.print("DegreeC= ");
lcd.print(tempc);
lcd.setCursor(0,1);
lcd.print("Fahrenheit=");
lcd.print(tempf);
delay(1000); //Delay of 1 second for ease of viewing in serial monitor
if (tempc > 30.0) {
SendSms();
}
}
void SendSms() {
char sendto[] = "+19999999999"; //put the desired destination phone number for sms here
char message[141];
sprintf(message, "Alert TEMP is %.2f", tempc);// limit to 140
//sends the message via SMS
if (!fona.sendSMS(sendto, message)) {
Serial.println(F("error"));
} else {
Serial.println(F("sent!"));
}
}
another way to send sms
you could test the hayes command: for example
void sendsms(){
Serial.println("Sending text message...");
fonaSS.print("AT+CMGF=1\r"); // SMS MODE
delay(100);
// phone number
fonaSS.print("AT+CMGS=\"+33676171212\"\r"); //indicate your phone number
delay(100);
// message here
fonaSS.print("Message test \r");
// CTR+Z in mode ASCII, to indicate the end of message
fonaSS.print(char(26));
delay(100);
fonaSS.println();
Serial.println("Text send");
}
#include <SoftwareSerial.h>
#include "Adafruit_FONA.h"
//This part declares that the RX, TX and RST pins of the SIM800L must be connected
//to pin 2, 3 and 4 of the Arduino.
#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
void setup() {
// you initialisation code
}
void loop()
{
vout=analogRead(sensor);
vout=(vout*500)/1023;
tempc=vout; // Storing value in degrees Celsius
tempf=(vout*1.8)+32; // Converting Temperature value from degrees Celsius to Fahrenheit
lcd.setCursor(0,0);
lcd.print("DegreeC= ");
lcd.print(tempc);
lcd.setCursor(0,1);
lcd.print("Fahrenheit=");
lcd.print(tempf);
delay(1000); //Delay of 1 second for ease of viewing in serial monitor
if (tempc > 30.0) {
SendSms();
}
}
void SendSms() {
char sendto[] = "+19999999999"; //put the desired destination phone number for sms here
char message[141];
sprintf(message, "Alert TEMP is %.2f", tempc);// limit to 140
//sends the message via SMS
if (!fona.sendSMS(sendto, message)) {
Serial.println(F("error"));
} else {
Serial.println(F("sent!"));
}
}

Sending data to Xively using Arduino mega + Gprs shield sim 900

I am using Arduino Mega2560 and GPRS Shield Sim900 and trying to send data to Xively using the code below.
What should I change in this code to send data to Xively with Sim900 GPRS Shield?
/*
* Xively WiFi Sensor Tutorial
*
* This sketch is designed to take sensors (from photocell) and
* upload the values to Xively at consistant intervals. At the
* same time it gets a setable value from Xively to adjust the
* brigthness of an LED. This sketch is reusable and can be
* adapted for use with many different sensors.
*
* Derived from Xively Ardino Sensor Client by Sam Mulube.
*
* By Calum Barnes 3-4-2013
* BSD 3-Clause License - [http://opensource.org/licenses/BSD-3-Clause]
* Copyright (c) 2013 Calum Barnes
*/
#include <SPI.h>
#include <WiFi.h>
#include <HttpClient.h>
#include <Xively.h>
char ssid[] = "SSID_HERE"; // your network SSID (name)
char pass[] = "PASS_HERE"; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
// Your Xively key to let you upload data
char xivelyKey[] = "API_KEY_HERE";
//your xively feed ID
#define xivelyFeed FEED_ID_HERE
//datastreams
char sensorID[] = "LIGHT_SENSOR_CHANNEL";
char ledID[] = "LED_CHANNEL";
// Analog pin which we're monitoring (0 and 1 are used by the Ethernet shield)
#define sensorPin A2
//led connected pin
#define ledPin 9
// Define the strings for our datastream IDs
XivelyDatastream datastreams[] = {
XivelyDatastream(sensorID, strlen(sensorID), DATASTREAM_FLOAT),
XivelyDatastream(ledID, strlen(ledID), DATASTREAM_FLOAT),
};
// Finally, wrap the datastreams into a feed
XivelyFeed feed(xivelyFeed, datastreams, 2 /* number of datastreams */);
WiFiClient client;
XivelyClient xivelyclient(client);
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm \n");
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
//pin setup
pinMode(sensorPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.println("Starting single datastream upload to Xively...");
Serial.println();
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, keyIndex, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected to wifi");
printWifiStatus();
}
void loop() {
//adjust LED level. set from Xively
int getReturn = xivelyclient.get(feed, xivelyKey); //get data from xively
if (getReturn > 0) {
Serial.println("LED Datastream");
Serial.println(feed[1]);
} else {
Serial.println("HTTP Error");
}
//write value to LED - change brightness
int level = feed[1].getFloat();
if (level < 0) {
level = 0;
} else if (level > 255) {
level = 255;
}
//actually write the value
digitalWrite(ledPin, level);
//read sensor values
int sensorValue = analogRead(sensorPin);
datastreams[0].setFloat(sensorValue);
//print the sensor valye
Serial.print("Read sensor value ");
Serial.println(datastreams[0].getFloat());
//send value to xively
Serial.println("Uploading it to Xively");
int ret = xivelyclient.put(feed, xivelyKey);
//return message
Serial.print("xivelyclient.put returned ");
Serial.println(ret);
Serial.println("");
//delay between calls
delay(15000);
}

Resources