How to get numbers from sd card? - arduino

I am bad at coding. I have a file called Test.cal in sd card contained 6 numbers. 20,21,22,23,24,25
But I do not know how to get this six number. Can someone help me ? Below is my own thought about the coding.
#include <SD.h>
float meterTemp[6];
String theLines[15];
File myFile;
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
Serial.print("Initializing SD card...");
// On the Ethernet Shield, CS is pin 4. It's set as an output by default.
// Note that even if it's not used as the CS pin, the hardware SS pin
// (10 on most Arduino boards, 53 on the Mega) must be left as an output
// or the SD library functions will not work.
pinMode(53, OUTPUT);
if (!SD.begin(4)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
// re-open the file for reading:
myFile = SD.open("Test.cal");
if (myFile) {
//I want to put the file numbers into array, meterTemp[6], not inclduing comma, so when I get meterTemp[0]=-32, and so on.
// read from the file until there's nothing else in it:
while (myFile.available()) {
Serial.write(myFile.read());
}
// close the file:
myFile.close();
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
}
void loop()
{
// nothing happens after setup
}

#include <SD.h>
float meterTemp[6];
String theLines;
File myFile;
String filename="Test.cal";
int line=0;
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
Serial.print("Initializing SD card...");
// On the Ethernet Shield, CS is pin 4. It's set as an output by default.
// Note that even if it's not used as the CS pin, the hardware SS pin
// (10 on most Arduino boards, 53 on the Mega) must be left as an output
// or the SD library functions will not work.
pinMode(53, OUTPUT);
if (!SD.begin(4)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
// re-open the file for reading:
myFile = SD.open("Test.cal");
if (myFile) {
Serial.println("test.txt:");
;
// read from the file until there's nothing else in it:
while (myFile.available()) {
Serial.write(myFile.read());
theLines=readFile(filename,line);
Serial.println(theLines);
}
// close the file:
myFile.close();
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
}
void loop()
{
// nothing happens after setup
}
String readFile(String filename, int line)
{
char s[20];
char FileName[sizeof(filename)];
filename.toCharArray(FileName, sizeof(FileName));
File myFile = SD.open(FileName,FILE_READ);
if(myFile)
{
String recived = "";
int cur = 0;
char ch;
while (myFile.available())
{
ch = myFile.read();
if(ch == ',')
{
cur++;
if(cur == line)
{
myFile.close();
return String(recived);
}
}
else
{
recived += ch;
}
}
}
return "";
}

String readFile(String filename, int line)
{
char FileName[sizeof(filename)];
filename.toCharArray(FileName, sizeof(FileName));
File myFile = SD.open(FileName,FILE_READ);
if(myFile)
{
String recived = "";
int cur = 0;
char ch;
while (myFile.available())
{
ch = myFile.read();
if(ch == '\n')
{
cur++;
if(cur == line)
{
myFile.close();
return String(recived);
}
}
else
{
recived += ch;
}
}
}
return "";
}
It is from Arduino Visual code generator.Replace "\n" with your char

Related

Trying to understand ESP32 OTA over the GSM code

I am performing ESP32 OTA over the GSM. I have found some example code online, modified it slightly based on my board connections and was able to sucesfully perform a firmware update.
I use lilygo ESP32 GSM development board.
However, it frustrates me that I am not capable of understanding what really happens in the code at the low level. I really want to understand before I go any further with my project.
Full code for my OTA update:
#include <Update.h>
#define TINY_GSM_MODEM_SIM800
// Increase RX buffer
#define TINY_GSM_RX_BUFFER 1030
const char apn[] = "omnitel";
const char user[] = "omni";
const char pass[] = "omni";
#define MODEM_RST 5
#define MODEM_PWRKEY 4
#define MODEM_POWER_ON 23
#define MODEM_TX 27
#define MODEM_RX 26
#define LED_GPIO 13
#define LED_ON HIGH
#define LED_OFF LOW
#define SerialAT Serial1
#include <TinyGsmClient.h>
#include <CRC32.h>
#include "FS.h"
#include "SPIFFS.h"
#ifdef DUMP_AT_COMMANDS
#include <StreamDebugger.h>
StreamDebugger debugger(SerialAT, Serial);
TinyGsm modem(debugger);
#else
TinyGsm modem(SerialAT);
#endif
TinyGsmClient client(modem);
const char server[] = "myesptestserver.ddns.net";
const int port = 80;
const char resource[] = "/esp.bin"; //here de bin file
uint32_t knownCRC32 = 0x6f50d767;
uint32_t knownFileSize = 1024; // In case server does not send it
void setup()
{
SerialAT.begin(115200, SERIAL_8N1, MODEM_RX, MODEM_TX);
// Set console baud rate
Serial.begin(115200);
setupModem();
delay(10);
if (!SPIFFS.begin(true))
{
Serial.println("SPIFFS Mount Failed");
return;
}
SPIFFS.format();
listDir(SPIFFS, "/", 0);
// Set GSM module baud rate
delay(3000);
// Restart takes quite some time
// To skip it, call init() instead of restart()
Serial.println("Initializing modem...");
modem.restart();
String modemInfo = modem.getModemInfo();
Serial.print("Modem: ");
Serial.println(modemInfo);
// Unlock your SIM card with a PIN
//modem.simUnlock("1234");
}
void loop()
{
Serial.print("Waiting for network...");
if (!modem.waitForNetwork())
{
Serial.println(" fail");
delay(10000);
return;
}
Serial.println(" OK");
Serial.print("Connecting to ");
Serial.print(apn);
if (!modem.gprsConnect(apn, user, pass))
{
Serial.println(" fail");
delay(10000);
return;
}
Serial.println(" OK");
Serial.print("Connecting to ");
Serial.print(server);
// if you get a connection, report back via serial:
if (!client.connect(server, port))
{
Serial.println(" fail");
delay(10000);
return;
}
Serial.println(" OK");
// Make a HTTP request:
client.print(String("GET ") + resource + " HTTP/1.0\r\n");
client.print(String("Host: ") + server + "\r\n");
client.print("Connection: close\r\n\r\n");
long timeout = millis();
while (client.available() == 0)
{
if (millis() - timeout > 5000L)
{
Serial.println(">>> Client Timeout !");
client.stop();
delay(10000L);
return;
}
}
Serial.println("Reading header");
uint32_t contentLength = knownFileSize;
File file = SPIFFS.open("/update.bin", FILE_APPEND);
while (client.available())
{
String line = client.readStringUntil('\n');
line.trim();
//Serial.println(line); // Uncomment this to show response header
line.toLowerCase();
if (line.startsWith("content-length:"))
{
contentLength = line.substring(line.lastIndexOf(':') + 1).toInt();
}
else if (line.length() == 0)
{
break;
}
}
timeout = millis();
uint32_t readLength = 0;
CRC32 crc;
unsigned long timeElapsed = millis();
printPercent(readLength, contentLength);
while (readLength < contentLength && client.connected() && millis() - timeout < 10000L)
{
int i = 0;
while (client.available())
{
// read file data to spiffs
if (!file.print(char(client.read())))
{
Serial.println("Appending file");
}
//Serial.print((char)c); // Uncomment this to show data
//crc.update(c);
readLength++;
if (readLength % (contentLength / 13) == 0)
{
printPercent(readLength, contentLength);
}
timeout = millis();
}
}
file.close();
printPercent(readLength, contentLength);
timeElapsed = millis() - timeElapsed;
Serial.println();
client.stop();
Serial.println("stop client");
modem.gprsDisconnect();
Serial.println("gprs disconnect");
Serial.println();
float duration = float(timeElapsed) / 1000;
/*
Serial.print("Tamaño de Archivo: ");
Serial.println(contentLength);
Serial.print("Leido: ");
Serial.println(readLength);
Serial.print("Calculado. CRC32: 0x");
Serial.println(crc.finalize(), HEX);
Serial.print("Conocido CRC32: 0x");
Serial.println(knownCRC32, HEX);
Serial.print("Bajado en: ");
Serial.print(duration);
Serial.println("s");
Serial.println("Se genera una espera de 3 segundos");
for (int i = 0; i < 3; i++)
{
Serial.print(String(i) + "...");
delay(1000);
}
*/
//readFile(SPIFFS, "/update.bin");
updateFromFS();
// Do nothing forevermore
while (true)
{
delay(1000);
}
}
void appendFile(fs::FS &fs, const char *path, const char *message)
{
Serial.printf("Appending to file: %s\n", path);
File file = fs.open(path, FILE_APPEND);
if (!file)
{
Serial.println("Failed to open file for appending");
return;
}
if (file.print(message))
{
Serial.println("APOK");
}
else
{
Serial.println("APX");
}
}
void readFile(fs::FS &fs, const char *path)
{
Serial.printf("Reading file: %s\n", path);
File file = fs.open(path);
if (!file || file.isDirectory())
{
Serial.println("Failed to open file for reading");
return;
}
Serial.print("Read from file: ");
while (file.available())
{
Serial.write(file.read());
delayMicroseconds(100);
}
}
void writeFile(fs::FS &fs, const char *path, const char *message)
{
Serial.printf("Writing file: %s\n", path);
File file = fs.open(path, FILE_WRITE);
if (!file)
{
Serial.println("Failed to open file for writing");
return;
}
if (file.print(message))
{
Serial.println("File written");
}
else
{
Serial.println("Write failed");
}
}
void listDir(fs::FS &fs, const char *dirname, uint8_t levels)
{
Serial.printf("Listing directory: %s\n", dirname);
File root = fs.open(dirname);
if (!root)
{
Serial.println("Failed to open directory");
return;
}
if (!root.isDirectory())
{
Serial.println("Not a directory");
return;
}
File file = root.openNextFile();
while (file)
{
if (file.isDirectory())
{
Serial.print(" DIR : ");
Serial.println(file.name());
if (levels)
{
listDir(fs, file.name(), levels - 1);
}
}
else
{
Serial.print(" FILE: ");
Serial.print(file.name());
Serial.print(" SIZE: ");
Serial.println(file.size());
}
file = root.openNextFile();
}
}
void deleteFile(fs::FS &fs, const char *path)
{
Serial.printf("Deleting file: %s\n", path);
if (fs.remove(path))
{
Serial.println("File deleted");
}
else
{
Serial.println("Delete failed");
}
}
void updateFromFS()
{
File updateBin = SPIFFS.open("/update.bin");
if (updateBin)
{
if (updateBin.isDirectory())
{
Serial.println("Directory error");
updateBin.close();
return;
}
size_t updateSize = updateBin.size();
if (updateSize > 0)
{
Serial.println("Starting update");
performUpdate(updateBin, updateSize);
}
else
{
Serial.println("Error, archivo vacío");
}
updateBin.close();
// whe finished remove the binary from sd card to indicate end of the process
//fs.remove("/update.bin");
}
else
{
Serial.println("no such binary");
}
}
void performUpdate(Stream &updateSource, size_t updateSize)
{
if (Update.begin(updateSize))
{
size_t written = Update.writeStream(updateSource);
if (written == updateSize)
{
Serial.println("Writes : " + String(written) + " successfully");
}
else
{
Serial.println("Written only : " + String(written) + "/" + String(updateSize) + ". Retry?");
}
if (Update.end())
{
Serial.println("OTA finished!");
if (Update.isFinished())
{
Serial.println("Restart ESP device!");
ESP.restart();
}
else
{
Serial.println("OTA not fiished");
}
}
else
{
Serial.println("Error occured #: " + String(Update.getError()));
}
}
else
{
Serial.println("Cannot beggin update");
}
}
void printPercent(uint32_t readLength, uint32_t contentLength)
{
// If we know the total length
if (contentLength != -1)
{
Serial.print("\r ");
Serial.print((100.0 * readLength) / contentLength);
Serial.print('%');
}
else
{
Serial.println(readLength);
}
}
void setupModem()
{
#ifdef MODEM_RST
// Keep reset high
pinMode(MODEM_RST, OUTPUT);
digitalWrite(MODEM_RST, HIGH);
#endif
pinMode(MODEM_PWRKEY, OUTPUT);
pinMode(MODEM_POWER_ON, OUTPUT);
// Turn on the Modem power first
digitalWrite(MODEM_POWER_ON, HIGH);
// Pull down PWRKEY for more than 1 second according to manual requirements
digitalWrite(MODEM_PWRKEY, HIGH);
delay(100);
digitalWrite(MODEM_PWRKEY, LOW);
delay(1000);
digitalWrite(MODEM_PWRKEY, HIGH);
// Initialize the indicator as an output
pinMode(LED_GPIO, OUTPUT);
digitalWrite(LED_GPIO, LED_OFF);
}
From what I understand, the following part of the code reads my binary file that is stored in the server and read it into SPIFFS memory:
while (readLength < contentLength && client.connected() && millis() - timeout < 10000L)
{
int i = 0;
while (client.available())
{
// read file data to spiffs
if (!file.print(char(client.read())))
{
Serial.println("Appending file");
}
//Serial.print((char)c); // Uncomment this to show data
//crc.update(c);
readLength++;
if (readLength % (contentLength / 13) == 0)
{
printPercent(readLength, contentLength);
}
timeout = millis();
}
}
Then the updateFromFS() function is executed, which checks whether the binary is all good and then calls another function performUpdate(updateBin, updateSize);
void updateFromFS()
{
File updateBin = SPIFFS.open("/update.bin");
if (updateBin)
{
if (updateBin.isDirectory())
{
Serial.println("Directory error");
updateBin.close();
return;
}
size_t updateSize = updateBin.size();
if (updateSize > 0)
{
Serial.println("Starting update");
performUpdate(updateBin, updateSize);
}
else
{
Serial.println("Error, archivo vacío");
}
updateBin.close();
// whe finished remove the binary from sd card to indicate end of the process
//fs.remove("/update.bin");
}
else
{
Serial.println("no such binary");
}
}
in the performUpdate(updateBin, updateSize), 2 functions from Arduino Update Library are being called ( Update.begin(updateSize) and Update.writeStream(updateSource) ) and that is where I cant follow anymore...
void performUpdate(Stream &updateSource, size_t updateSize)
{
if (Update.begin(updateSize))
{
size_t written = Update.writeStream(updateSource);
if (written == updateSize)
{
Serial.println("Writes : " + String(written) + " successfully");
}
else
{
Serial.println("Written only : " + String(written) + "/" + String(updateSize) + ". Retry?");
}
if (Update.end())
{
Serial.println("OTA finished!");
if (Update.isFinished())
{
Serial.println("Restart ESP device!");
ESP.restart();
}
else
{
Serial.println("OTA not fiished");
}
}
else
{
Serial.println("Error occured #: " + String(Update.getError()));
}
}
else
{
Serial.println("Cannot beggin update");
}
}
I have found this Update library source code :
https://github.com/espressif/arduino-esp32/blob/master/libraries/Update/src/Updater.cpp
But it seems that this is beyond my knowledge to understand what really is going on in this code.
First of all, we pass only 1 variable to .begin method, but the function prototype requires more than that:
bool UpdateClass::begin(size_t size, int command, int ledPin, uint8_t ledOn, const char *label)
And then I am trying to understand what happens in function Update.writeStream(updateSource) but cant..
If anyone could shed some light here I would appreciate a lot! Thanks in advance...
The algorithm downloads the new firmware (.bin) from the cloud to the device's local memory and makes the firmware change with the UpdateClass library
(I see the texts in Spanish if you want we speak in Spanish)
Check the .h (only one argument required)
https://github.com/espressif/arduino-esp32/blob/master/libraries/Update/src/Update.h
/*
Call this to check the space needed for the update
Will return false if there is not enough space
*/
bool begin(size_t size=UPDATE_SIZE_UNKNOWN, int command = U_FLASH, int ledPin = -1, uint8_t ledOn = LOW, const char *label = NULL);
You could use the OTAdrive library and use it for OTA updates.
Check here for the esp32 gsm modem OTA example.

How to create variable filename and store variable on sd card with Arduino

The example "SD_Test" in the Arduino IDE works perfectly. Now i want to expand it.
First: I want to use a variable file name. I found some example in the internet and also in stackoverlow for this, but nothing works (still searching for a minimal example)
writeFile(SD, "/hello.txt", "Hello ");
i want
writeFile(SD, filename, "Hello ");
where filename is a variable which handles something like "file.txt"
Second: I want to do the same for the content, which i want to save in this file. So instead of
writeFile(SD, "/hello.txt", "Hello ");
i want
writeFile(SD, "/hello.txt", datas);
As an example: I can print out this
printf("%04x", datas);
Now i want to save this variable 'datas' with 4 hex in the file, exactly how it looks in the serial monitor.
You can use the following code for writing on the SD card.
You need to download two library files for this names are mentioned in the code.
Remember to format you SD card first into FAT32
Hope this will help you.
/* Author: Ashish Kumar
Org: INVOOTECH */
#include <SPI.h>
#include <SD.h>
Sd2Card card;
SdVolume volume;
File myFile;
char *b="hellow.txt";
char p;
const int chipSelect = 4;
void setup() {
Serial.begin(9600);
if (!card.init(SPI_HALF_SPEED, chipSelect)) //error statement
{
Serial.println("initialization failed. Things to check:");
return;
}
if (!volume.init(card)) //error statement
{
Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
return;
}
if (!SD.begin(4)) {
Serial.println("initialization failed!");
return;
}
}
void loop() {
myFile = SD.open(b);
if (myFile) {
p=myFile.read();
Serial.write(p);
}
// close the file:
myFile.close();
}
Okay. So what I have done is create a file in loop.
#include <SPI.h>
#include <SD.h>
File myFile;
int chipSelectNumber = 10;
String prefix = "test";
String extension = ".txt";
String filename;
int fileNumber=0;
void setup() {
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
initSDCard();
}
void loop() {
createFileAndEnterData();
}
//This Function will create file and Enter modbus data in the file
void createFileAndEnterData(){
String temp;
temp = prefix;
temp.concat(fileNumber);
temp.concat(extension);
filename = temp;
Serial.println(filename);
fileNumber++;
boolean statusFileCreate = createFile(filename);
if(statusFileCreate){
Serial.println("File Creation Successful");
}
else{
Serial.println("File Creation Unsuccessful");
}
delay(1000);
}
boolean createFile(String fileName){
myFile = SD.open(fileName, FILE_WRITE);
if(myFile){
Serial.print("Creating file : ");
Serial.print(fileName);
Serial.print(" ");
myFile.println("");
myFile.close();
return true;
}
else{
return false;
}
}
void initSDCard(){
Serial.print("Initializing SD card...");
if (!SD.begin(chipSelectNumber)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
}
void openFile(String fileName){
myFile = SD.open(fileName, FILE_WRITE);
if (myFile) {
Serial.println("Opened File");
} else {
Serial.println("error opening test.txt");
}
}
void deleteFile(String filename){
}
void writeFile(String fileName){
// re-open the file for reading:
myFile = SD.open(fileName);
if (myFile) {
Serial.println(fileName);
// read from the file until there's nothing else in it:
while (myFile.available()) {
Serial.write(myFile.read());
}
myFile.close();
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
}
There are some unnecessary functions, just avoid that.
The following function will create file:-
void createFileAndEnterData(){
String temp;
temp = prefix;
temp.concat(fileNumber);
temp.concat(extension);
filename = temp;
Serial.println(filename);
fileNumber++;
boolean statusFileCreate = createFile(filename);
if(statusFileCreate){
Serial.println("File Creation Successful");
}
else{
Serial.println("File Creation Unsuccessful");
}
delay(1000);
}
Hope this solves your problem.
Thank You.

integrating the AdafruitFona GSM shield with tiny gps library

i need help in integrating the two libraries so that i can send the GPS data via GSM . Information regarding the use of two special Serial is needed and also a help with the code is needed .
The below segmnet containts the code for the GPS shield this has to be used to generate the location and this data has to be sent via gsm to a mobile number.
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
/*
This sample sketch demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
It requires the use of SoftwareSerial, and assumes that you have a
4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/
static const int RXPin = 4, TXPin = 3;//was 4 and 3;
static const uint32_t GPSBaud = 9600;
// The TinyGPS++ object
TinyGPSPlus gps;
// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);
void setup()
{
Serial.begin(115200);
ss.begin(GPSBaud);
Serial.println(F("GPS GSM tracking system"));
Serial.println(F("Sabdadon Presents"));
Serial.print(F("Search and Rescue")); Serial.println(TinyGPSPlus::libraryVersion());
Serial.println(F("Sabarish"));
Serial.println();
}
void loop()
{
// This sketch displays information every time a new sentence is correctly encoded.
while (ss.available() > 0)
if (gps.encode(ss.read()))
displayInfo();
if (millis() > 500000 && gps.charsProcessed() < 10)
{
Serial.println(F("No GPS detected: check wiring."));
while(true);
}
}
void displayInfo()
{
delay(10000);
Serial.print(F("Location: "));
if (gps.location.isValid())
{
Serial.print(gps.location.lat(), 5);
Serial.print(F(","));
Serial.print(gps.location.lng(), 5);
// latitude=gps.location.lat();
//longitude=gps.location.lng();
//if(latitude && longitude)
}
else
{
Serial.print(F("INVALID"));
}
Serial.print(F(" Date/Time: "));
if (gps.date.isValid())
{
Serial.print(gps.date.month());
Serial.print(F("/"));
Serial.print(gps.date.day());
Serial.print(F("/"));
Serial.print(gps.date.year());
}
else
{
Serial.print(F("INVALID"));
}
Serial.print(F(" "));
if (gps.time.isValid())
{
if (gps.time.hour() < 10) Serial.print(F("0"));
Serial.print(gps.time.hour());
Serial.print(F(":"));
if (gps.time.minute() < 10) Serial.print(F("0"));
Serial.print(gps.time.minute());
Serial.print(F(":"));
if (gps.time.second() < 10) Serial.print(F("0"));
Serial.print(gps.time.second());
Serial.print(F("."));
if (gps.time.centisecond() < 10) Serial.print(F("0"));
Serial.print(gps.time.centisecond());
}
else
{
ss.read();
Serial.print(F("INVALID"));
}
Serial.println();
}
FOR GSM
#include "Adafruit_FONA.h"
#define FONA_RX 2//2
#define FONA_TX 3//3
#define FONA_RST 4//4
char replybuffer[255];
#include <SoftwareSerial.h>
#include <AltSoftSerial.h>
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
SoftwareSerial *fonaSerial = &fonaSS;
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0);
uint8_t type;
void setup()
{
while (!Serial);
Serial.begin(115200);
Serial.println(F("FONA basic test"));
Serial.println(F("Initializing....(May take 3 seconds)"));
fonaSerial->begin(4800);
if (! fona.begin(*fonaSerial)) {
Serial.println(F("Couldn't find FONA"));
while (1);
}
type = fona.type();
Serial.println(F("FONA is OK"));
Serial.print(F("Found "));
switch (type) {
case FONA800L:
Serial.println(F("FONA 800L")); break;
case FONA800H:
Serial.println(F("FONA 800H")); break;
case FONA808_V1:
Serial.println(F("FONA 808 (v1)")); break;
case FONA808_V2:
Serial.println(F("FONA 808 (v2)")); break;
case FONA3G_A:
Serial.println(F("FONA 3G (American)")); break;
case FONA3G_E:
Serial.println(F("FONA 3G (European)")); break;
default:
Serial.println(F("???")); break;
}
// Print module IMEI number.
char imei[15] = {0}; // MUST use a 16 character buffer for IMEI!
uint8_t imeiLen = fona.getIMEI(imei);
if (imeiLen > 0) {
Serial.print("Module IMEI: "); Serial.println(imei);
}
}
void loop()
{ Serial.print(F("FONA> "));
while (! Serial.available() ) {
if (fona.available()) {
Serial.write(fona.read());
}
}
// send an SMS!
char sendto[21], message[141];
flushSerial();
Serial.print(F("Send to #"));
readline(sendto, 20);
Serial.println(sendto);
Serial.print(F("Type out one-line message (140 char): "));
readline(message, 140);
Serial.println(message);
if (!fona.sendSMS(sendto, message)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("Sent!"));
}
}
void flushSerial() {
while (Serial.available())
Serial.read();
}
char readBlocking() {
while (!Serial.available());
return Serial.read();
}
uint16_t readnumber() {
uint16_t x = 0;
char c;
while (! isdigit(c = readBlocking())) {
//Serial.print(c);
}
Serial.print(c);
x = c - '0';
while (isdigit(c = readBlocking())) {
Serial.print(c);
x *= 10;
x += c - '0';
}
return x;
}
uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout) {
uint16_t buffidx = 0;
boolean timeoutvalid = true;
if (timeout == 0) timeoutvalid = false;
while (true) {
if (buffidx > maxbuff) {
//Serial.println(F("SPACE"));
break;
}
while (Serial.available()) {
char c = Serial.read();
//Serial.print(c, HEX); Serial.print("#"); Serial.println(c);
if (c == '\r') continue;
if (c == 0xA) {
if (buffidx == 0) // the first 0x0A is ignored
continue;
timeout = 0; // the second 0x0A is the end of the line
timeoutvalid = true;
break;
}
buff[buffidx] = c;
buffidx++;
}
if (timeoutvalid && timeout == 0) {
//Serial.println(F("TIMEOUT"));
break;
}
delay(1);
}
buff[buffidx] = 0; // null term
return buffidx;
}
Here is a step-by-step to mix your GPS input device and your GSM output device.
Remainder for Arduino principles:
The void setup() function is performed one time after startup.
The void loop() function is performed periodically after the
setup().
Step1 - declaration of GPS device and Serial link
// GPS and Serial link
static const int RXPin = 4, TXPin = 3;//was 4 and 3;
static const uint32_t GPSBaud = 9600;
// The TinyGPS++ object
TinyGPSPlus DeviceGPS;
// The serial connection to the GPS device
SoftwareSerial SerialGPS(RXPin, TXPin);
Step2 - declaration of GSM/FONA device and Serial link
Including the SendTo SMS number !!!
#define FONA_RX 2//2
#define FONA_TX 3//3
#define FONA_RST 4//4
// The serial connection to the GSM device
SoftwareSerial SerialFONA = SoftwareSerial(FONA_TX, FONA_RX);
// The FONA/GSM Cellular Module device
Adafruit_FONA DeviceFONA = Adafruit_FONA(FONA_RST);
// The destination SMS number
static const char *sSendTo = "<NUMBER>";
Step3 - setup() function for (Console, GPS and GSM)
It is possible to add some extra Init.
// only execute once
void setup()
{
// Wait and Init Console
while (!Serial); // Serial over USB
Serial.begin(115200);
// Init GPS link
SerialGPS.begin(GPSBaud);
Serial.print(F("TinyGPSPlus ver: "));
Serial.println(TinyGPSPlus::libraryVersion());
// Init GSM link
SerialFONA.begin(4800);
if (! DeviceFONA.begin(SerialFONA)) {
Serial.println(F("Couldn't find FONA"));
while (1); // Stop working
}
// Add some extra Init
}
Step4 - loop() function to wait GPS location and send SMS
It is possible to use String() to create the SMS based on the
acquired DeviceGPS.location.lng() and DeviceGPS.location.lat().
// executed periodicaly
void loop()
{
// check until GPS message
while (SerialGPS.available() > 0) {
// get for a complete GPS message
DeviceGPS.encode(SerialGPS.read());
}
// flush GSM serial link
while (SerialFONA.available() > 0) {
if (DeviceFONA.available()) {
DeviceFONA.flush();
}
}
// send an SMS!
char sendto[21], message[141];
// Wait for location (lng, lat, alt) is OK
if (DeviceGPS.location.isValid()) {
// ==> create SMS with longitude & latitude
}
}

Unable to send sms Arduino GSM Shield 2

I can't connect and I don't know why, can somebody help me?
The console returns:
"/tmp/arduino_ca13faa5535f759e3ad5c18bb4094ecd/SendSMS.ino: In function 'void setup()':
/tmp/arduino_ca13faa5535f759e3ad5c18bb4094ecd/SendSMS.ino:48:34: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
if (gsmAccess.begin(PINNUMBER) == GSM_READY) { "
#include <GSM.h>
#define PINNUMBER ""
// initialize the library instance
GSM gsmAccess;
GSM_SMS sms;
void setup() {
// initialize serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
;// wait for serial port to connect. Needed for native USB port only
}
Serial.println("SMS Messages Sender");
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter of begin() in quotes
while (notConnected) {
if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
notConnected = false;
} else {
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized");
}
void loop() {
Serial.print("Enter a mobile number: ");
char remoteNum[20]; // telephone number to send sms
readSerial(remoteNum);
Serial.println(remoteNum);
// sms text
Serial.print("Now, enter SMS content: ");
char txtMsg[200];
readSerial(txtMsg);
Serial.println("SENDING");
Serial.println();
Serial.println("Message:");
Serial.println(txtMsg);
// send the message
sms.beginSMS(remoteNum);
sms.print(txtMsg);
sms.endSMS();
Serial.println("\nCOMPLETE!\n");
}
/*
Read input serial
*/
int readSerial(char result[]) {
int i = 0;
while (1) {
while (Serial.available() > 0) {
char inChar = Serial.read();
if (inChar == '\n') {
result[i] = '\0';
Serial.flush();
return 0;
}
if (inChar != '\r') {
result[i] = inChar;
i++;
}
}
}
}
That's just a warning. The sketch is building fine. What do you see on the Serial Monitor window? (drag-select, copy and paste into a comment below.)
You haven't set the PIN to anything, like "1234". Do you have a PIN?

DELAY is crashing board if delay duration is greater than 30 seconds?

I have this variable, DELAY_INTERVAL, which I set to measure how long my arduino mega board will delay before submitting a request to my server again.
I've found that when this variable is set to 30 seconds my board runs fine but as soon as I set it to 45 seconds my board crashes.
I've inserted a bunch of printlns for debugging purposes:
void loop() {
Serial.print("Free RAM: ");
Serial.println(getFreeRam(), DEC);
Serial.println(1);
getEC();
Serial.println(2);
getPH();
Serial.println(3);
createPoint(ecSensorString, phSensorString);
Serial.println(4);
delay(DELAY_INTERVAL*1000);
Serial.println(5);
}
Note that this runs indefinitely for 30s but not 45s.
This is what the console outputs on 45s:
Free RAM: 6551
1
getEC:*OK
2
getPH:
3
a
postPointToServer:ec=*OK&ph=&interval=45s
b
c
d
e
f
g
h
4
<output monitor just stalls>
So I have identified that delay is the culprit here. But why and how can I solve this?
The rest of my code if anyone is interested.
void setup() {
//initRGB();
Serial.begin(9600);
ecSensorString.reserve(30);
phSensorString.reserve(30);
initSensors();
initWireless();
Serial.println("Setup Complete");
}
void loop() {
Serial.print("Free RAM: ");
Serial.println(getFreeRam(), DEC);
Serial.println(1);
getEC();
Serial.println(2);
getPH();
Serial.println(3);
createPoint(ecSensorString, phSensorString);
Serial.println(4);
delay(DELAY_INTERVAL*1000);
Serial.println(5);
}
void initWireless() {
/* Initialise the module */
if (!cc3000.begin()) {
Serial.println(F("Couldn't begin()! Check your wiring?"));
//displayRed();
while(1);
}
Serial.println(F("Initialization Complete"));
Serial.print(F("Attempting to connect to "));
Serial.println(WLAN_SSID);
if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
Serial.println(F("Failed!"));
//displayRed();
while(1);
}
Serial.println(F("Wireless Connected!"));
/* Wait for DHCP to complete */
while (!cc3000.checkDHCP()) {
delay(100); // ToDo: Insert a DHCP timeout!
}
Serial.println(F("DHCP Requested!"));
if (IP_NOT_DOMAIN) {
ip = cc3000.IP2U32(IP_1, IP_2, IP_3, IP_4);
} else {
ip = 0;
// Try looking up the website's IP address
while (ip == 0) {
if (! cc3000.getHostByName(WEBSITE, &ip)) {
Serial.println(F("Couldn't resolve!"));
}
delay(500);
}
}
}
void initSensors() {
Serial2.begin(38400);
Serial3.begin(38400);
// Tell the EC sensors to stop continuous mode
Serial2.print("c,0\r");
// Tell the pH sensor to stop all readings
Serial3.print("E\r");
// TODO: EC sensor's first reading is always empty, possibly delay?
}
void createPoint(String ec, String ph) {
if (ec && ph) {
postPointToServer("ec=" + ec + "&ph=" + ph);
} else if (ec) {
postPointToServer("ec=" + ec);
} else if (ph) {
postPointToServer("ph=" + ph);
} else {
Serial.println("createPoint: null");
}
}
void postPointToServer(String data) {
Serial.println("a");
char interval_c[20];
sprintf(interval_c, "&interval=%ds", DELAY_INTERVAL);
data += interval_c;
Serial.print("postPointToServer:");
Serial.println(data);
Serial.println("b");
Adafruit_CC3000_Client www = cc3000.connectTCP(ip, PORT);
Serial.println("c");
if (www.connected()) {
www.fastrprint(F("POST ")); www.fastrprint(WEBPAGE); www.fastrprint(F(" HTTP/1.1\r\n"));
www.fastrprint(F("Host: ")); www.fastrprint(WEBSITE); www.fastrprint(F("\r\n"));
Serial.println("d");
String auth_raw = serial + ":" + token;
char auth_input[200];
char auth_output[200];
auth_raw.toCharArray(auth_input, auth_raw.length() + 1);
base64_encode(auth_output, auth_input, auth_raw.length());
www.fastrprint(F("Authorization: Basic ")); www.fastrprint(auth_output); www.fastrprint(F("\r\n"));
www.fastrprint(F("Content-Type: application/x-www-form-urlencoded")); www.fastrprint(F("\r\n"));
Serial.println("e");
char len_c[7];
itoa(data.length(), len_c, 10);
www.fastrprint(F("Content-Length: ")); www.fastrprint(len_c); www.fastrprint(F("\r\n"));
// Extra empty line for post arguments
www.fastrprint(F("\r\n"));
Serial.println("f");
char data_c[200];
data.toCharArray(data_c, data.length() + 1);
www.fastrprint(data_c); www.fastrprint(F("\r\n"));
www.fastrprint(F("\r\n"));
www.println();
//displayGreen();
} else {
Serial.println(F("Connection failed"));
//displayRed();
}
Serial.println("g");
www.close();
Serial.println("h");
}
void getEC() {
ecSensorString = "";
Serial2.print("r\r"); // Read only 1
char inchar;
while (Serial2.available()) {
inchar = (char)Serial2.read();
if (inchar != '\r') {
ecSensorString += inchar;
}
}
Serial.print("getEC:");
Serial.println(ecSensorString);
}
void getPH() {
phSensorString = "";
Serial3.print("R\r"); // Read only 1
char inchar;
while (Serial3.available()) {
inchar = (char)Serial3.read();
if (inchar != '\r') {
phSensorString += inchar;
}
}
Serial.print("getPH:");
Serial.println(phSensorString);
}
I've had the same problem.
Do you need to put an L at the end to make an explicit conversion of this constant into a long integer:
delay(DELAY_INTERVAL*1000L);

Resources