1 /*
2  * Copyright (c) 2024, Muhammad Waleed Badar
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <zephyr/device.h>
9 #include <zephyr/drivers/rtc.h>
10 #include <zephyr/sys/util.h>
11 
12 const struct device *const rtc = DEVICE_DT_GET(DT_ALIAS(rtc));
13 
set_date_time(const struct device * rtc)14 static int set_date_time(const struct device *rtc)
15 {
16 	int ret = 0;
17 	struct rtc_time tm = {
18 		.tm_year = 2024 - 1900,
19 		.tm_mon = 11 - 1,
20 		.tm_mday = 17,
21 		.tm_hour = 4,
22 		.tm_min = 19,
23 		.tm_sec = 0,
24 	};
25 
26 	ret = rtc_set_time(rtc, &tm);
27 	if (ret < 0) {
28 		printk("Cannot write date time: %d\n", ret);
29 		return ret;
30 	}
31 	return ret;
32 }
33 
get_date_time(const struct device * rtc)34 static int get_date_time(const struct device *rtc)
35 {
36 	int ret = 0;
37 	struct rtc_time tm;
38 
39 	ret = rtc_get_time(rtc, &tm);
40 	if (ret < 0) {
41 		printk("Cannot read date time: %d\n", ret);
42 		return ret;
43 	}
44 
45 	printk("RTC date and time: %04d-%02d-%02d %02d:%02d:%02d\n", tm.tm_year + 1900,
46 	       tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
47 
48 	return ret;
49 }
50 
main(void)51 int main(void)
52 {
53 	/* Check if the RTC is ready */
54 	if (!device_is_ready(rtc)) {
55 		printk("Device is not ready\n");
56 		return 0;
57 	}
58 
59 	set_date_time(rtc);
60 
61 	/* Continuously read the current date and time from the RTC */
62 	while (get_date_time(rtc) == 0) {
63 		k_sleep(K_MSEC(1000));
64 	};
65 	return 0;
66 }
67