rtc.now() works once then returns random dates and time - arduino

I am trying to read and print the RTC date and time to add an up-to-date time stamp to a file name. The sketch returns a correct time stamp once, then returns seemingly random dates and times. When I reset the board (Arduino Uno), it prints one correct time stamp followed by random dates and times. I would be grateful for any suggestion that could help me correct my mistakes. The sketch currently only creates and prints the time stamp.
#include <Wire.h>
#include <RTClib.h>
RTC_DS3231 rtc;
void setup () {
Serial.begin(9600);
while(!Serial); // wait for the Serial temnal to start
Wire.begin(); // sets up I2C
rtc.begin();
if(!rtc.begin()){
Serial.println("Coulnd't find the rtc");
}
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
void loop() {
DateTime nowDateTime = rtc.now();
char fmt[] = "YYYY/MM/DD-hh:mm:ss\n";
String timeStamp = nowDateTime.toString(fmt);
Serial.println(timeStamp);
delay(1000);
}
I have looked for similar problems and tried a few ideas but the problem remains the same. My current sketch is a bare bones attempt at simply getting the RTC time stamp to update and print to the Serial monitor. Many thanks for your suggestions.

Related

How to use Processing to store Arduinos serial output into a text file?

I have been trying to store data (real time, gas sensor data) into a .txt file so as to make graphs.
This is my arduino code:
const int gasPin = A0; //Gas sensor output pin to Arduino analog A0 pin
void setup()
{
Serial.begin(9600); //Initialize serial port - 9600 bps
}
void loop()
{
Serial.println(analogRead(gasPin));
delay(1000); // Print value every 1 sec.
}
And this is my Processing code:
import processing.serial.*;
Serial mySerial;
PrintWriter output;
void setup() {
mySerial = new Serial(this, "COM3", 9600);
output = createWriter( "data.txt" );
}
void draw() {
if (mySerial.available() > 0 ) {
String value = mySerial.readString();
if ( value != null ) {
output.println( value );
}
}
}
void keyPressed() {
output.flush();
output.close();
exit();
}
This doesn't work. I always get an empty data.txt file.
You should get into the habit of breaking your problem down into smaller steps and then taking those steps on one at a time.
For example, can you create a simple example sketch that stores a value in a file? Don't worry about Arduino yet. Just store a single value in a file.
Then make it so you store a bunch of values in the file. Maybe the value returned from millis(), or the mouse position. Again, don't worry about Arduino yet. Get this working perfectly before moving on.
Separately from that, can you make an Arduino program that sends values to a Processing sketch that simply prints those values to the console?
When you have those working separately, then you can combine them into a single program.
Right now, there's no way to know which part of your code is failing: is it the Arduino code? Is it the file storage? So you need to isolate those pieces so we (you) can test them by themselves.
If you still can't figure it out, then post a MCVE of just a single step in a new question post, and we'll go from there. Good luck.

Saving endless loop EKG data as .txt file

I am using Olimex EKG Shield with Arduino Uno.
void setup() {
// put your setup code here, to run once:
// initialize serial communication at 9600 bits per second:
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float value = sensorValue * (5.0 / 1023.0);
// print out the value you read:
Serial.println(value);
}
With this code provided here, I am getting a voltage value from 0-5V.
Since its a loop, the data keep shows in the serial monitor until it is disconnected.
So, what I am trying to do is that measure ECG for a certain amount of time (let's say 5 min) or data points (let's say a million points), and then save this data into a .txt file.
//From Arduino to Processing to Txt or cvs etc.
//import
import processing.serial.*;
//declare
PrintWriter output;
Serial udSerial;
void setup() {
udSerial = new Serial(this, Serial.list()[0], 115200);
output = createWriter ("data.txt");
}
void draw() {
if (udSerial.available() > 0) {
String SenVal = udSerial.readString();
if (SenVal != null) {
output.println(SenVal);
}
}
}
void keyPressed(){
output.flush();
output.close();
exit();
}
I found this processing code that imports data from Arduino serial monitor and saves as a .txt file, but it doesn's work somehow.
I think I need to make some change to the code on Arduino side and also on Processing side.
If anyone can help with me, I would really appreciate.
Thank you.
You need to be more specific than saying "it doesn't work somehow" - we have no idea what that means. What exactly did you expect this code to do? What exactly does it do instead?
You also need to split this up into smaller problems.
Can you create a simple example program that simply sends the values to Processing? Just print them to the console for now.
Can you create a separate example program that stores values in a text file? Just use hard-coded values or random values for now- don't worry about the arduino yet.
When you have both of those working perfectly, then you can think about combining them into one program that does both: sends values from the arduino and saves those values to a text file.
You can't just "find code" and expect it to work. You have to break your problem down and then approach each individual step by itself. Then if you get stuck on a specific step, you can post a MCVE and we can go from there. Good luck.

Arduino with RTC getting the wrong year

I am working on this Arduino test application as a part of a bigger project. I have connected my Arduino to a Grove RTC (Realtime clock DS1307) module which is now spitting out date and time in my serial monitor. However the year is wrong. As seen on the below picture it is showing the value 46 in the Year field.
Below is the two methods i am using to get date and time and then print it out. I get the year value from the Year field of the tmElements struct. The tmElements type is residing in the Time library.
// Gets date and time and prints out in "DD/MM/YYYY - HH:MM:SS" format.
void getTime(){
tmElements_t tm;
if (RTC.read(tm)){
getFormattedValue(tm.Day);
Serial.print("/");
getFormattedValue(tm.Month);
Serial.print("/");
Serial.print(tm.Year);
Serial.print(" - ");
getFormattedValue(tm.Hour);
Serial.print(":");
getFormattedValue(tm.Minute);
Serial.print(":");
getFormattedValue(tm.Second);
Serial.println();
}
}
// Formats the time value to two digits. Example: if hour is 7 it will be formatted as 07.
void getFormattedValue(int number) {
if (number >= 0 && number < 10) {
Serial.write('0');
}
Serial.print(number);
}
How come I am getting this wrong value? Can somebody please guide me in the right direction?
Ahh.. Already found the problem myself. The problem was that I didn't use the tmYearToCalendar() method.
So instead of:
Serial.print(tm.Year);
It had to be:
Serial.print(tmYearToCalendar(tm.Year));
Works like a charm now. Just thought I would share it with you all.

Make my arduino accomplish task at specific time

I'm a newbie to arduino. What I need is make him do something at specific time, and go to sleep, so that it doesn't work excessively.
Specific task is: I want him to start a mechanism for feeding my gold fish, so in vacation time arduino should work for 10 days or more (this is reason for sleep mode).
When researching this problem, I came up with time interrupts, but I don't think this is best solution, because I want him do something at specific time, not to to interrupt his task.
Thank you for any kind of help :)
I've read that the standard Arduino board doesn't save that much power, as the power regulator and USB port (if present) draws significant power. But given that you use an external clock to trigger the device to wakeup, there's a simple arduino library, Enerlib, that you can use.
Engblaze has a nice article on how to do it yourself, but if you're new to the arduino, you might not want to jump into AVR libraries.
you can try something easy like every 30 seconds starts an event of 20 seconds of duration :
#include <Wire.h>
#include "RTClib.h"
RTC_DS1307 rtc;
void setup () {
Serial.begin(57600);
#ifdef AVR
Wire.begin();
#else
Wire1.begin(); // Shield I2C pins connect to alt I2C bus on Arduino Due
#endif
rtc.begin();
if (! rtc.isrunning()) {
Serial.println("RTC is NOT running!");
}
}
boolean pumpOn = false;
void loop () {
DateTime now = rtc.now();
if(now.second()%30==0){ pumpOn=true;}
if(now.second()%50==0){ pumpOn=false;}
if(pumpOn)
Serial.println("on");
}
}
Use the millis() method. It will reset after 50 days but I don't think you will be traveling for so long...
unsigned long hours4nextFeeding = 8;
unsigned long lastTime = millis();
void loop() {
if(millis() > (lastTime + (hours4nextFeeding*3600*1000))) {
feedTheFish();
lastTime = millis();
}
delay(60000);
}
Also you can use a light sensor (supercheaper) and feed the fish once a day when the sun rises
The code I just wrote is untested but you should get the idea.
I like #Josh's solution of using the clock to reset the device, but here's another idea if your fish will die if they aren't fed on the millisecond.

GPS module stops working, is unable to setMode to on

I have been using the GPS module on waspmotes, and I have been able to get data off it. However on a fine day, with clear visible skies(which I don't think matters), I cannot be able to set the power mode on.
On calling GPS.setMode(GPS_ON), it fails to set the power mode on, and on freezes on subsequent call to: gpsConnected = GPS.check();
I have tried changing the GPS unit to no avail. I am using the following code. (NB: I have removed the unnecessary bits of code for the sake of brevity)
void setup()
{
ACC.ON();
USB.begin(); // Opening UART to show messages using 'Serial Monitor'
//Initialize the GPS module
GPS.ON(); // Turn GPS on
GPS.setMode(GPS_ON); // set GPS on
if(!GPS.pwrMode) USB.println("Was unable to set on the GPS internal power mode."); //this message gets printed.
if(!GPS.setCommMode(GPS_NMEA_GGA)) USB.println("Was unable to set the GPS communication mode.");
// Power up the Real Time Clock(RTC), init I2C bus and read initial values
RTC.ON();
........
}
void loop(){
//declare the variables
len, i, j = 0;
char degree[4] = "", minutes[8] = "", *latitude, *longitude, *altitude;
uint8_t temperature = 0;
int8_t fileFound = 0;
double latitude_dd, longitude_dd;
byte accOk;
//check if the GPS has connected to the satellite
GPS.begin(); // open the uart
GPS.init(); // Inits the GPS module
gpsConnected = GPS.check();
........
........
}
What might have happened???
Any help will be appreciated.
This was caused by using the RTC.setTime function. In the code, as can be seen here: http://pastebin.com/RmA98MkD, on line 195, RTC.setTimeFromGPS(), I was setting the boards time with the time that I received from GPS. This ended up screwing the GPS connection up and the code only looped once. You can see detailed conversations from here: http://www.libelium.com/forum/viewtopic.php?f=16&t=9861
You Need to simple test. First you ensure that you are giving TTl input to the Tx and rx pin . If you upload this program It will gives GPS output string.If you are using GPS module with Serial output of RS 232 out, As you said it wont work.IT expecting TTl input only
void setup()
{
Serial.begin();
}
void loop()
{
}

Resources