We will create an application that reads the current time from the Real-Time Clock (RTC) connected to the Raspberry Pi board:
- In your ~/test working directory, create a subdirectory called rtc.
- Use your favorite text editor to create a rtc.cpp file in the rtc subdirectory.
- 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>
- 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);
}
};
- 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 ;
}
- 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++)
- Build your application and copy the resulting rtc binary to our Raspberry Pi emulator.