# Using RTC DS1307 in multiple programs

I'm kinda new to electronics and programming, but I managed to make a DS1307 RTC functional when it is used by only one program (I'm using C code). Buf if I try to use it in multiple programs at the same time, it occasionally gives me some strange dates and times.

For example, I'm using these two programs:

• test.c
 #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "ABE_ExpanderPi.h"
void main() {
int i = 0;
while( i < 100 ) {
struct tm datetime;
char buffer[80];
if (strftime(buffer, sizeof buffer, "%Y/%m/%d;%H:%M:%S", &datetime)) {
}
else {
puts("strftime failed");
exit(1);
}
printf("%s\n", buffer);
i++;
usleep(10000);
}
}

• test2.c
 #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "ABE_ExpanderPi.h"
void main() {
int i = 0;
while( i < 100 ) {
struct tm datetime;
char buffer[80];
if (strftime(buffer, sizeof buffer, "%Y/%m/%d;%H:%M:%S", &datetime)) {
}
else {
puts("strftime failed");
exit(1);
}
printf("%s\n", buffer);
i++;
usleep(10000);
}
}


The DS1307 functions can be found in ABElectronics_C_Libraries.

When I run both at the same time, it shows me something like this:

...
2018/07/11;19:07:53
2018/80/40;05:06:92
2018/80/40;05:06:92
2018/07/11;19:07:53
2018/80/40;05:06:92
2018/07/11;19:07:53
2018/80/40;05:06:92
2018/07/11;19:07:53
2018/80/40;05:06:92
2018/07/11;19:07:53
2018/07/11;19:07:53
2018/07/11;19:07:53
2018/07/11;19:07:53
2018/07/11;19:07:53
2018/07/11;19:07:53
2018/80/40;05:06:92
2041/53/02;90:12:90
2018/07/11;19:07:53
2018/80/40;05:06:92
2018/07/11;19:07:53
2018/80/40;05:06:92
2018/07/11;19:07:53
2018/07/11;19:07:53
...


In my project I will be using the RTC more than twice at the same time. Can you help me, please?

• I imagine the correct way to do this is to have a single program that gets the time from the RTC, and then whenever another program needs the time, it calls that dedicated program, and ensures that theres only ever one instance of the RTC program running. – BeB00 Jul 11 '18 at 18:22
• Linux actually has a driver for the DS1307 built-in, so it would probably be best to just use that. – Jonathan S. Jul 11 '18 at 19:31
• Why read the time/date from the RTC when you can read it from the system. When you have an RTC the Linux driver will read it and set the system time/date. Any program (and multiples) can read from the OS without interference. – Jack Creasey Jul 11 '18 at 22:09

I would recommend looking into a shared memory solution. You would have a single process that is allowed to call rtc_read_date that places "messages" in a FIFO structure in shared memory. Then all the other processes that need date-time information could take the "messages" from the FIFO structure. This is not exactly trivial for a beginner but would be great to learn. Looking through this repository would be a good start.