first commit

This commit is contained in:
2025-11-10 18:05:25 +01:00
commit 85794d9f2f
10 changed files with 897 additions and 0 deletions
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""Alarm example for PyPCF8523 RTC driver.
This example demonstrates how to use the alarm functionality:
- Setting an alarm
- Checking alarm status
- Clearing an alarm
Hardware setup:
- Connect PCF8523 to Raspberry Pi I2C bus 1
- Optionally connect INT pin to a GPIO for interrupt handling
"""
import time
from pypcf8523 import PCF8523
def main():
print("PCF8523 Alarm Example")
print("=" * 50)
# Initialize the RTC
rtc = PCF8523(i2c_bus=1)
# Get current time
current = rtc.datetime
print(f"Current time: {current.tm_hour:02d}:{current.tm_min:02d}:{current.tm_sec:02d}")
# Set an alarm for 2 minutes from now
alarm_minute = (current.tm_min + 2) % 60
alarm_hour = current.tm_hour
if alarm_minute < current.tm_min: # Handle hour rollover
alarm_hour = (alarm_hour + 1) % 24
print(f"Setting alarm for: {alarm_hour:02d}:{alarm_minute:02d}")
rtc.set_alarm(minute=alarm_minute, hour=alarm_hour)
# Enable the alarm interrupt
rtc.alarm_interrupt = True
print("Alarm interrupt enabled")
# Clear any existing alarm status
rtc.alarm_status = False
print("\nWaiting for alarm... (Press Ctrl+C to stop)")
print("-" * 50)
try:
while True:
# Read current time
current = rtc.datetime
time_str = f"{current.tm_hour:02d}:{current.tm_min:02d}:{current.tm_sec:02d}"
# Check if alarm triggered
if rtc.alarm_status:
print(f"\n🔔 ALARM! Triggered at {time_str}")
# Clear the alarm
rtc.alarm_status = False
print("Alarm cleared")
# Optionally disable the alarm
# rtc.clear_alarm()
# print("Alarm disabled")
break
else:
print(f"Current time: {time_str} - Waiting for alarm...", end="\r")
time.sleep(1.0)
except KeyboardInterrupt:
print("\n\nExample stopped by user")
finally:
# Clean up
rtc.clear_alarm()
rtc.close()
print("Alarm cleared and RTC connection closed")
if __name__ == "__main__":
main()
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""Calibration example for PyPCF8523 RTC driver.
This example demonstrates how to calibrate the RTC for better accuracy:
- Reading calibration settings
- Adjusting calibration offset
- Setting calibration schedule
The PCF8523 can drift up to 2 seconds per day. Calibration helps
compensate for this drift.
Calibration offset range: -64 to +63
- Positive values speed up the clock
- Negative values slow it down
Calibration schedule:
- Per minute: 1 LSB = 4.069 ppm
- Per 2 hours: 1 LSB = 4.340 ppm
"""
import time
from pypcf8523 import PCF8523
def main():
print("PCF8523 Calibration Example")
print("=" * 50)
# Initialize the RTC
rtc = PCF8523(i2c_bus=1)
# Read current calibration settings
current_offset = rtc.calibration
per_minute = rtc.calibration_schedule_per_minute
print(f"Current calibration offset: {current_offset}")
print(f"Calibration schedule: {'Per minute' if per_minute else 'Per 2 hours'}")
# Calculate ppm (parts per million) offset
ppm_per_lsb = 4.069 if per_minute else 4.340
ppm_offset = current_offset * ppm_per_lsb
print(f"Approximate offset: {ppm_offset:.2f} ppm")
# Example: Set calibration
print("\n" + "-" * 50)
print("Example calibration adjustment:")
print("-" * 50)
# If your RTC is running fast (gaining time), use negative offset
# If your RTC is running slow (losing time), use positive offset
# Example: Clock gains 2 seconds per day
# 2 seconds / 86400 seconds = 23.15 ppm
# Offset needed: 23.15 / 4.069 ≈ -6 (per minute mode)
new_offset = 0 # Change this based on your measurements
print(f"\nTo set calibration offset to {new_offset}:")
print(f" rtc.calibration = {new_offset}")
if new_offset != 0:
print("\nUncomment the following lines to apply:")
print(" # rtc.calibration_schedule_per_minute = True")
print(f" # rtc.calibration = {new_offset}")
print(f" # This would give approximately {new_offset * 4.069:.2f} ppm offset")
# Uncomment to actually apply calibration:
# rtc.calibration_schedule_per_minute = True
# rtc.calibration = new_offset
# How to measure drift:
print("\n" + "=" * 50)
print("How to measure and calibrate your RTC:")
print("=" * 50)
print("1. Set the RTC to accurate time (sync with NTP)")
print("2. Wait 24-48 hours")
print("3. Compare RTC time with accurate time")
print("4. Calculate drift in seconds per day")
print("5. Convert to ppm: (drift_seconds / 86400) * 1,000,000")
print("6. Calculate offset: ppm / 4.069 (per minute mode)")
print("7. Apply opposite sign: if fast use negative, if slow use positive")
print("8. Set the calibration offset")
print("\nExample:")
print(" If RTC gains 2 seconds/day:")
print(" 2 / 86400 * 1000000 = 23.15 ppm")
print(" 23.15 / 4.069 = 5.69 ≈ 6")
print(" Use offset = -6 (negative because it's fast)")
# Check battery status
print("\n" + "-" * 50)
if rtc.battery_low:
print("⚠️ WARNING: Backup battery is low!")
else:
print("✓ Backup battery is OK")
# Clean up
rtc.close()
print("\nRTC connection closed")
if __name__ == "__main__":
main()
+75
View File
@@ -0,0 +1,75 @@
#!/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()