How to do it...

We will create an application that reads the current time from the Real-Time Clock (RTC) connected to the Raspberry Pi board:

  1. In your ~/test working directory, create a subdirectory called rtc.
  2. Use your favorite text editor to create a rtc.cpp file in the rtc subdirectory.
  3. Let's put the required include functions into the rtc.cpp file:
#include <iostream>
#include <system_error>

#include <time.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/rtc.h>
  1. Now, we define a class called Rtc that encapsulates the communication to the real-clock device:
class Rtc {
int fd;
public:
Rtc() {
fd = open("/dev/rtc", O_RDWR);
if (fd < 0) {
throw std::system_error(errno,
std::system_category(),
"Failed to open RTC device");
}
}

~Rtc() {
close(fd);
}

time_t GetTime(void) {
union {
struct rtc_time rtc;
struct tm tm;
} tm;
int ret = ioctl(fd, RTC_RD_TIME, &tm.rtc);
if (ret < 0) {
throw std::system_error(errno,
std::system_category(),
"ioctl failed");
}
return mktime(&tm.tm);
}
};
  1. Once the class is defined, we put a simple usage example into the main function: 
int main (void)
{
Rtc rtc;
time_t t = rtc.GetTime();
std::cout << "Current time is " << ctime(&t)
<< std::endl;

return 0 ;
}
  1. Create a CMakeLists.txt file containing the build rules for our program:
cmake_minimum_required(VERSION 3.5.1)
project(rtc)
add_executable(rtc rtc.cpp)

set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm)

set(CMAKE_CXX_COMPILER /usr/bin/arm-linux-gnueabi-g++)
  1. Build your application and copy the resulting rtc binary to our Raspberry Pi emulator.