#!/usr/bin/env python3 """Simple test example for PyPCF8523 RTC driver. This example demonstrates basic usage of the PCF8523 RTC: - Reading the current time - Setting the time - Checking power loss status Hardware setup: - Connect PCF8523 to Raspberry Pi I2C bus 1 - VCC -> 3.3V, GND -> GND, SDA -> GPIO2, SCL -> GPIO3 """ import time from pypcf8523 import PCF8523 # Days of the week for display DAYS = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") def main(): # Initialize the RTC on I2C bus 1 print("Initializing PCF8523 RTC...") rtc = PCF8523(i2c_bus=1) # Check if the RTC lost power if rtc.lost_power: print("WARNING: RTC lost power. Setting time to system time...") # Set the RTC to the current system time # In a real application, you might want to sync with NTP first current_time = time.localtime() rtc.datetime = current_time print(f"Time set to: {time.strftime('%Y-%m-%d %H:%M:%S', current_time)}") else: print("RTC power OK") # To manually set the time, uncomment and modify this section: # ================================================================ # import time # # Set to a specific time: 2025-11-09 15:30:00 (Saturday) # set_time = time.struct_time((2025, 11, 9, 15, 30, 0, 5, -1, -1)) # rtc.datetime = set_time # print(f"Time manually set to: {time.strftime('%Y-%m-%d %H:%M:%S', set_time)}") # ================================================================ print("\nReading time from RTC (Press Ctrl+C to stop):") print("-" * 50) try: while True: # Read the current time from the RTC current = rtc.datetime # Format and display the time day_name = DAYS[current.tm_wday] time_str = (f"{day_name} " f"{current.tm_year}/{current.tm_mon:02d}/{current.tm_mday:02d} " f"{current.tm_hour:02d}:{current.tm_min:02d}:{current.tm_sec:02d}") print(time_str) # Wait one second before next read time.sleep(1.0) except KeyboardInterrupt: print("\n\nTest stopped by user") finally: # Clean up rtc.close() print("RTC connection closed") if __name__ == "__main__": main()