Sending GPS location via GSM module - arduino

I am using a SIM900A GSM module and a NEO-6m GPS module. I want to send the location via the GSM module when the GSM module receives a message.
My code is working when I am receiving and sending any message with the help of the GSM module, but it is not working when I join the two, i.e. GPS and GSM modules.
Here is my code for the two.
#include <SoftwareSerial.h>
// GPS
#include <TinyGPS.h>
// GSM
SoftwareSerial SIM900A(9, 10);
SoftwareSerial mySerial(5, 6);
TinyGPS gps;
void setup() {
Serial.begin(9600);
SIM900A.begin(9600);
SIM900A.println("AT+CNMI=2,2,0,0,0");
mySerial.begin(9600);
delay(1000);
}
void loop() {
bool newdata = false;
String buffer = readSIM900A();
if(SIM900A.available() > 0)
Serial.println(SIM900A.read());
if (buffer.startsWith("\r\n+CMT: ")) {
// printing the number
Serial.println(buffer.substring(9, 22));
// Remove first 51 characters
// buffer.remove(0, 51);
int len = buffer.length();
// printing message
Serial.println(buffer.substring(51, len-2));
if (buffer.substring(51, len-2) == "location") {
Serial.println("Sending location");
// GPS
if (mySerial.available()) {
char c = mySerial.read();
if (gps.encode(c)) {
newdata = true;
}
}
if (newdata) {
long int lat, lon;
unsigned long age, age1, date, time, chars;
gps.get_position(&lat, &lon, &age);
gps.get_datetime(&date, &time, &age);
Serial.print("Lat/Long(10^-5 deg): ");
Serial.print(lat);
Serial.print(", ");
Serial.print(lon);
Serial.print(" Fix age: ");
Serial.print(age); Serial.println("ms.");
Serial.print("Date(ddmmyy): "); Serial.print(date);
Serial.print(" Time(hhmmsscc): ");
Serial.print(time);
Serial.print(" Fix age: "); Serial.print(age);
Serial.println("ms.");
Serial.print("Alt(cm): "); Serial.print(gps.altitude());
Serial.print(" Speed(mps): "); Serial.print(gps.f_speed_mps());
// setting GSM module
SIM900A.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode
delay(1000); // Delay of 1000 milli seconds or 1 second
// sending location from which code word had come
SIM900A.println("AT+CMGS=\"" + buffer.substring(9, 22) + "\"\r");
// Replace x with mobile number
Serial.println("AT+CMGS=\"" + buffer.substring(9, 22) + "\"\r");
delay(1000);
SIM900A.print("Lat/Long(10^-5 deg): ");
SIM900A.print(lat);
SIM900A.print(", ");
SIM900A.print(lon);
SIM900A.print(" Fix age: ");
SIM900A.print(age); SIM900A.println("ms.");
SIM900A.print("Date(ddmmyy): "); SIM900A.print(date);
SIM900A.print(" Time(hhmmsscc): ");
SIM900A.print(time);
SIM900A.print(" Fix age: "); SIM900A.print(age);
SIM900A.println("ms.");
SIM900A.print("Alt(cm): "); SIM900A.print(gps.altitude());
SIM900A.print(" Speed(mps): "); SIM900A.print(gps.f_speed_mps());
SIM900A.println((char)26);// ASCII code of CTRL+Z
delay(1000);
}
}
}
delay(100);
}
String readSIM900A() {
String buffer;
while (SIM900A.available()) {
char c = SIM900A.read();
buffer.concat(c);
delay(10);
}
return buffer;
}
Above is my final code when the GPS and GSM modules are handled together. They are working totally fine when they are handled separately.
Connections:
Connected Tx, Rx pin of SIM900A to 9, 10 of Arduino Nano respectively, and Tx, Rx of GPS module to 5, 6 respectively. And I also made ground common with Arduino.

#include <NeoSWSerial.h>
//#include <SoftwareSerial.h>
#include <AltSoftSerial.h>
// GPS
#include <TinyGPS.h>
// GSM
static const int RXPin = 8, TXPin = 9;
AltSoftSerial SIM900A(RXPin, TXPin);
NeoSWSerial mySerial(5, 6);
TinyGPS gps;
void setup()
{
Serial.begin(9600);
SIM900A.begin(9600);
SIM900A.println("AT+CNMI=2,2,0,0,0");
mySerial.begin(9600);
delay(1000);
}
void loop()
{
bool newdata = false;
String buffer = readSIM900A();
if(SIM900A.available() > 0)
Serial.println(SIM900A.read());
if (buffer.startsWith("\r\n+CMT: "))
{
// printing the number
Serial.println(buffer.substring(9, 22));
// Remove first 51 characters
// buffer.remove(0, 51);
int len = buffer.length();
// Remove \r\n from tail
// buffer.remove(len - 2, 2);
// printing message
Serial.println(buffer.substring(51, len-2));
if (buffer.substring(51, len-2) == "location")
{
Serial.println("Sending location");
// GPS
if (mySerial.available())
{
char c = mySerial.read();
if (gps.encode(c))
{
newdata = true;
}
}
if (newdata)
{
long int lat, lon;
unsigned long age, age1, date, time, chars;
gps.get_position(&lat, &lon, &age);
gps.get_datetime(&date, &time, &age);
Serial.print("Lat/Long(10^-5 deg): ");
Serial.print(lat);
Serial.print(", ");
Serial.print(lon);
Serial.print(" Fix age: ");
Serial.print(age); Serial.println("ms.");
Serial.print("Date(ddmmyy): "); Serial.print(date); Serial.print("
Time(hhmmsscc): ");
Serial.print(time);
Serial.print(" Fix age: "); Serial.print(age);
Serial.println("ms.");
Serial.print("Alt(cm): "); Serial.print(gps.altitude());
Serial.print(" Speed(mps): "); Serial.print(gps.f_speed_mps());
// setting GSM module
SIM900A.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode
delay(1000); // Delay of 1000 milli seconds or 1 second
// sending location from which code word had come
SIM900A.println("AT+CMGS=\"" + buffer.substring(9, 22) + "\"\r"); //
Replace x with mobile number
Serial.println("AT+CMGS=\"" + buffer.substring(9, 22) + "\"\r");
delay(1000);
SIM900A.print("Lat/Long(10^-5 deg): ");
SIM900A.print(lat);
SIM900A.print(", ");
SIM900A.print(lon);
SIM900A.print(" Fix age: ");
SIM900A.print(age); SIM900A.println("ms.");
SIM900A.print("Date(ddmmyy): "); SIM900A.print(date);
SIM900A.print(" Time(hhmmsscc): ");
SIM900A.print(time);
SIM900A.print(" Fix age: "); SIM900A.print(age);
SIM900A.println("ms.");
SIM900A.print("Alt(cm): "); SIM900A.print(gps.altitude());
SIM900A.print(" Speed(mps): "); SIM900A.print(gps.f_speed_mps());
SIM900A.println((char)26);// ASCII code of CTRL+Z
delay(1000);
}
}
}
delay(100);
}
String readSIM900A()
{
String buffer;
while (SIM900A.available())
{
char c = SIM900A.read();
buffer.concat(c);
delay(10);
}
return buffer;
}
P.S : I have changed the pins for GSM and rest part is same. Except adding AltSoftSerial it is a library same as SoftwareSerial (Download it from manage libraries and it requires pins 8 and 9). Don't change pin number in sketch change the connections.

Related

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

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

Error in sending data to cloud server and arduino lagging

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));
}
}

Code error in smart irrigation system, using dht11 sensor

I have wrtitten a code for automatically watering plant using esp8266, dht11, moisture sensor but my code has some error, i dont know how to fix it
#include <DHT.h>
#include <ESP8266WiFi.h>
String apiKey = "X5AQ3EGIKMBYW31H"; // Enter your Write API key here
const char* server = "api.thingspeak.com";
const char *ssid = "CircuitLoop"; // Enter your WiFi Name
const char *pass = "circuitdigest101"; // Enter your WiFi Password
#define DHTPIN D3 // GPIO Pin where the dht11 is connected
DHT dht(DHTPIN, DHT11);
WiFiClient client;
const int moisturePin = A0; // moisteure sensor pin
const int motorPin = D0;
unsigned long interval = 10000;
unsigned long previousMillis = 0;
unsigned long interval1 = 1000;
unsigned long previousMillis1 = 0;
float moisturePercentage; //moisture reading
float h; // humidity reading
float t; //temperature reading
void setup()
{
Serial.begin(115200);
delay(10);
pinMode(motorPin, OUTPUT);
digitalWrite(motorPin, LOW); // keep motor off initally
dht.begin();
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print("."); // print ... till not connected
}
Serial.println("");
Serial.println("WiFi connected");
}
void loop()
{
unsigned long currentMillis = millis(); // grab current time
h = dht.readHumidity(); // read humiduty
t = dht.readTemperature(); // read temperature
if (isnan(h) || isnan(t))
{
Serial.println("Failed to read from DHT sensor!");
return;
}
moisturePercentage = ( 100.00 - ( (analogRead(moisturePin) / 1023.00) * 100.00 ) );
if ((unsigned long)(currentMillis - previousMillis1) >= interval1) {
Serial.print("Soil Moisture is = ");
Serial.print(moisturePercentage);
Serial.println("%");
previousMillis1 = millis();
}
if (moisturePercentage < 50) {
digitalWrite(motorPin, HIGH); // tun on motor
}
if (moisturePercentage > 50 && moisturePercentage < 55) {
digitalWrite(motorPin, HIGH); //turn on motor pump
}
if (moisturePercentage > 56) {
digitalWrite(motorPin, LOW); // turn off mottor
}
if ((unsigned long)(currentMillis - previousMillis) >= interval) {
sendThingspeak(); //send data to thing speak
previousMillis = millis();
client.stop();
}
}
void sendThingspeak() {
if (client.connect(server, 80))
{
String postStr = apiKey; // add api key in the postStr string
postStr += "&field1=";
postStr += String(moisturePercentage); // add mositure readin
postStr += "&field2=";
postStr += String(t); // add tempr readin
postStr += "&field3=";
postStr += String(h); // add humidity readin
postStr += "\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: " + apiKey + "\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length()); //send lenght of the string
client.print("\n\n");
client.print(postStr); // send complete string
Serial.print("Moisture Percentage: ");
Serial.print(moisturePercentage);
Serial.print("%. Temperature: ");
Serial.print(t);
Serial.print(" C, Humidity: ");
Serial.print(h);
Serial.println("%. Sent to Thingspeak.");
}
}
This is the error which i get
Arduino: 1.8.9 (Windows 8.1), Board: "Generic ESP8266 Module, 80 MHz, Flash, Disabled, All SSL ciphers (most compatible), ck, 26 MHz, 40MHz, DOUT (compatible), 512K (no SPIFFS), 2, nonos-sdk 2.2.1 (legacy), v2 Lower Memory, Disabled, None, Only Sketch, 115200"
sketch_oct03a:7:16: error: 'D3' was not declared in this scope
#define DHTPIN D3 // GPIO Pin where the dht11 is connected
^
C:\Users\Shweta\Desktop\Libraries\sketch_oct03a\sketch_oct03a.ino:8:9: note: in expansion of macro 'DHTPIN'
DHT dht(DHTPIN, DHT11);
^
sketch_oct03a:12:22: error: 'D0' was not declared in this scope
const int motorPin = D0;
^
exit status 1
'D3' was not declared in this scope
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
Digital pins are not prefixed with D, unlike their analog counterparts.
#define DHTPIN 3
const int motorPin = 0;

trouble in Sending link google map GPS through SMS by arduino,sim 900a and NEO 6m

I have trouble in sending link's googlemap( GPS ) through SMS by module SIM 900a, NEO 6m ( GPS module) and arduino
Here's my code:
#include <SoftwareSerial.h>
#include <TinyGPS.h>
TinyGPS gps;
SoftwareSerial serialgps (4,5);
int year;
byte month,day,hour,minute,second,hundredths;
unsigned long chars;
unsigned short sentences, failed_checksum;
float latitude;
float longitude;
void setup()
{
Serial.begin(19200);
serialgps.begin(9600);
while(serialgps.available())
{
int c = serialgps.read();
int count=c;
for( count=0; count<5;count++)
{
if (gps.encode(c))
{
gps.f_get_position(&latitude, &longitude);
Serial.print("Lat/Long: ");
Serial.print(latitude, 5);
Serial.print(", ");
Serial.println(longitude, 5);
gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths);
Serial.print("Date: "); Serial.print(month, DEC); Serial.print("/");
Serial.print(day, DEC); Serial.print("/"); Serial.print(year);
Serial.print(" Time: "); Serial.print(hour, DEC); Serial.print(":");
Serial.print(minute, DEC); Serial.print(":"); Serial.print(second, DEC);
Serial.print("."); Serial.println(hundredths, DEC);
Serial.print("Altitude (meters): "); Serial.println(gps.f_altitude());
Serial.print("Course (degrees): "); Serial.println(gps.f_course());
Serial.print("Speed(kmph): "); Serial.println(gps.f_speed_kmph());
Serial.print("Satellites: "); Serial.println(gps.satellites());
Serial.println();
SendSMS(latitude,longitude);
gps.stats(&chars, &sentences, &failed_checksum);
}
}
}
}
void loop() {}
after having GPS,now i bring it to SMS by AT Comand
void SendSMS(float latitude,float longitude )
{
delay (1000);
Serial.print("AT\r");
delay(1000);
while (Serial.available()>0)
{ char inchar= (char)Serial.read();
}
Serial.println();
Serial.println("AT+CMGF=1\r"); // sets the SMS mode to text
delay(100);
delay(1200);
Serial.print("AT+CMGS=\""); // send the SMS number
Serial.print("01682740718");
Serial.println("\"");
delay(1000);
Serial.print("Localtion:"); // noi dung SMS
Serial.print("www.google.com.vn/maps/place/");
Serial.print(latitude, 5);
Serial.print(",");
Serial.print(longitude, 5);
Serial.print("\r");
delay(500);
Serial.println((char)26);//o código ASCII do ctrl + z é 26
delay(500);
Serial.write(0x1A);
Serial.write(0x0D);
Serial.write(0x0A);
}

RFID (SoftwareSerial) influences/breaks connection with SD (SPI)

I'm creating a RFID logger with Arduino. I connected a RFID scanner, RTC module and a SD card reader. All parts are working fine together but when i started combining different sketches a problem occured.
Reading files and writing to files on the SD card is no problem as long as i don't scan a RFID card. When input is received from the RFID scanner it is no longer possible to read or write to the sd card. The connection seems to be "disconnected" as soon as RFID input is received.
I tried using different pins for the RFID scanner, another sequence of initializing in the setup but it doesn't make a difference.
Is this a limitation of the Arduino or am I doing something wrong?
I'm using a ATS125KRW RFID shield and a Catalex MicroSD card adpater in combination with a Arduino Mega.
// SD
#include <SD.h>
File myFile;
char idArray[100][11];
char nameArray[100][11];
// RTC
#include <Wire.h>
#include "RTClib.h"
RTC_DS1307 rtc;
// RFID
#include <SoftwareSerial.h>
SoftwareSerial rfid = SoftwareSerial(A8 , A9); //(RX,TX)
String cardID; //string to store card id
char c;
char cardArray[11];
int incomingByte = 0; // for incoming serial data
String rfidInput;
boolean logtosd;
void setup()
{
Serial.begin(9600);
initializeRFID();
initializeSD();
initializeRTC();
readfromSD();
}
void loop()
{
while(rfid.available()>0)
{
c = rfid.read();
rfidInput += c;
}
if(rfidInput.length() >=12)
{
Serial.print("SCanned: ");
Serial.println(rfidInput);
//writetoSD(rfidInput);
writetoSD("kaart");
rfidInput = "";
}
while(Serial.available()>0)
{
c = Serial.read();
cardID += c;
}
if(cardID.length() >= 2)
{
writetoSD(cardID);
cardID = "";
}
}
void initializeSD()
{
// GND en VCC aansluiting via pin 48 en 49
pinMode(48, OUTPUT); // set pin to output
digitalWrite(48, LOW); // GND pin dus LOW
pinMode(49, OUTPUT); // set pin to output
digitalWrite(49, HIGH); // VCC pin dus HIGH
pinMode(53, OUTPUT);
if (!SD.begin(53))
{
Serial.println("SD initialization failed");
return;
}
Serial.println("SD initialized");
}
void readfromSD()
{
//open the file for reading:
myFile = SD.open("db.txt");
if (myFile)
{
char line[25]; //Array to store entire line
int linenumber = 0;
int arrayPlace = 0;
while (myFile.available())
{
char ch = myFile.read();
if(ch != '\n')
{
line[arrayPlace] = ch;
arrayPlace ++;
}
else
{
char id[11];
char name[11];
//get ID from entire line
for(int x = 0; x <= 10 ; x++)
{
id[x] = line[x];
}
//Get NAME from entire line
for(int x = 11; x <= 19 ; x++)
{
if (line[x] != ';')
{
name[x-11] = line[x];
}
else
{
// NULL TERMINATE THE ARRAY
name[x-11] = '\0';
//STOP
x = 20;
}
}
// save name to nameArray
for(int x = 0; x <= 11 ; x++)
{
nameArray[linenumber][x] = name[x];
}
// NULL TERMINATE THE ARRAY
id[10] = '\0';
// save id to idArray
for(int x = 0; x <= 11 ; x++)
{
idArray[linenumber][x] = id[x];
}
linenumber +=1;
arrayPlace = 0;
} //else
} //while
// close the file:
myFile.close();
}
else
{
// if the file didn't open, print an error:
Serial.println("error opening db.txt");
}
}
void writetoSD(String cardID)
{
//open file for writing
myFile = SD.open("test.txt", FILE_WRITE);
// if the file opened okay, write to it:
if (myFile)
{
Serial.println("Writing time to test.txt...");
DateTime now = rtc.now();
myFile.print(now.day(), DEC);
myFile.print('/');
myFile.print(now.month(), DEC);
myFile.print('/');
myFile.print(now.year(), DEC);
myFile.print(' ');
myFile.print(now.hour(), DEC);
myFile.print(':');
myFile.print(now.minute(), DEC);
myFile.print(':');
myFile.print(now.second(), DEC);
myFile.print('\t');
Serial.println("Writing string to test.txt...");
myFile.println(cardID);
// close the file:
myFile.flush();
Serial.println("done.");
}
else
{
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
}
void initializeRTC()
{
// GND en VCC aansluiting via pin 18 en 19
pinMode(18, OUTPUT); // set pin to output
digitalWrite(18, LOW); // GND pin dus LOW
pinMode(19, OUTPUT); // set pin to output
digitalWrite(19, HIGH); // VCC pin dus HIGH
#ifdef AVR
Wire.begin();
#else
Wire1.begin(); // Shield I2C pins connect to alt I2C bus on Arduino Due
#endif
rtc.begin();
Serial.print("RTC Initialized: ");
DateTime now = rtc.now();
Serial.print(now.day(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.year(), DEC);
Serial.print(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
}
void initializeRFID()
{
rfid.begin(9600);
Serial.println("RFID initialized");
}
I think you are running out of RAM ,i have done a lot of data logging on SD card with Arduino and its a very resources taking job for the minial 2kb ram on the UNO (assuming u using UNO).
Try using MemoryFree() library before every place you see there might be problem to see if you are running outta memory?

Resources