PyPCF8523/README.md
2025-11-10 18:05:25 +01:00

195 lines
5.0 KiB
Markdown

# PyPCF8523 - Python Driver for PCF8523 Real Time Clock
A Python 3.8+ driver for the PCF8523 Real Time Clock (RTC) chip, designed for Raspberry Pi and similar Linux boards with I2C support.
This library is a Python conversion of [Adafruit's CircuitPython PCF8523 library](https://github.com/adafruit/Adafruit_CircuitPython_PCF8523), adapted to work with standard Python and smbus2.
## Features
- **Battery-backed RTC**: Maintains accurate time even when main power is lost
- **Dual voltage support**: Works with 3.3V or 5V logic
- **Alarm functionality**: Set alarms with minute precision
- **Calibration support**: Adjust clock accuracy with offset calibration
- **Low battery detection**: Monitor backup battery status
- **Power management**: Configurable battery switchover modes
- **Python 3.8+ compatible**: Modern Python with type hints
## Hardware Requirements
- Raspberry Pi (any model with I2C) or compatible Linux board
- PCF8523 RTC module (e.g., Adafruit PCF8523 breakout)
- I2C connection to the RTC module
## Installation
### Prerequisites
Enable I2C on your Raspberry Pi:
```bash
sudo raspi-config
# Navigate to: Interface Options > I2C > Enable
```
### Install the package
```bash
pip install smbus2
pip install -e /path/to/PyPCF8523
```
Or install dependencies directly:
```bash
cd /path/to/PyPCF8523
pip install -r requirements.txt
pip install -e .
```
## Quick Start
### Basic Usage
```python
import time
from pypcf8523 import PCF8523
# Initialize RTC on I2C bus 1 (default for Raspberry Pi)
rtc = PCF8523(i2c_bus=1)
# Set the current time
current_time = time.localtime()
rtc.datetime = current_time
# Read the current time
dt = rtc.datetime
print(f"Current time: {dt.tm_year}-{dt.tm_mon:02d}-{dt.tm_mday:02d} "
f"{dt.tm_hour:02d}:{dt.tm_min:02d}:{dt.tm_sec:02d}")
```
### Using Context Manager
```python
from pypcf8523 import PCF8523
with PCF8523(1) as rtc:
print(f"RTC Time: {rtc.datetime}")
# Check if power was lost
if rtc.lost_power:
print("Warning: RTC lost power, time may be incorrect")
```
### Setting an Alarm
```python
from pypcf8523 import PCF8523
rtc = PCF8523(1)
# Set alarm for 8:30 AM every day
rtc.set_alarm(minute=30, hour=8)
# Enable alarm interrupt
rtc.alarm_interrupt = True
# Check if alarm triggered
if rtc.alarm_status:
print("Alarm triggered!")
rtc.alarm_status = False # Clear the alarm
```
### Calibration
```python
from pypcf8523 import PCF8523
rtc = PCF8523(1)
# Set calibration offset (-64 to +63)
# Positive values speed up the clock, negative values slow it down
rtc.calibration = 5
# Set calibration schedule
rtc.calibration_schedule_per_minute = True # Apply every minute
# or
rtc.calibration_schedule_per_minute = False # Apply every 2 hours
```
## API Reference
### PCF8523 Class
#### Constructor
```python
PCF8523(i2c_bus=1, address=0x68)
```
- `i2c_bus`: I2C bus number (default: 1)
- `address`: I2C device address (default: 0x68)
#### Properties
- **`datetime`** (struct_time): Get or set the current date and time
- **`lost_power`** (bool): True if device lost power since time was set
- **`power_management`** (int): Battery switchover mode (0-7)
- **`alarm_interrupt`** (bool): Enable/disable alarm interrupt output
- **`alarm_status`** (bool): Check if alarm triggered (write False to clear)
- **`battery_low`** (bool): True if backup battery is low (read-only)
- **`high_capacitance`** (bool): Oscillator capacitance mode
- **`calibration`** (int): Clock calibration offset (-64 to +63)
- **`calibration_schedule_per_minute`** (bool): Calibration schedule mode
#### Methods
- **`set_alarm(minute=None, hour=None, day=None, weekday=None)`**: Set alarm
- **`clear_alarm()`**: Disable and clear alarm
- **`close()`**: Close I2C bus connection
## Pin Connections (Raspberry Pi)
| PCF8523 | Raspberry Pi |
|---------|--------------|
| VCC | 3.3V (Pin 1) |
| GND | GND (Pin 6) |
| SDA | SDA (Pin 3) |
| SCL | SCL (Pin 5) |
## Troubleshooting
### I2C Device Not Found
Check if the device is detected:
```bash
i2cdetect -y 1
```
You should see `68` in the output grid.
### Permission Denied
Add your user to the i2c group:
```bash
sudo usermod -a -G i2c $USER
```
Then log out and back in.
### Accuracy Issues
The PCF8523 can drift up to 2 seconds per day. For critical timing applications:
1. Use the calibration feature to compensate for drift
2. Consider periodic synchronization with NTP
3. Monitor temperature (affects crystal oscillator)
## Credits
- **Original CircuitPython Library**: [Adafruit Industries](https://github.com/adafruit/Adafruit_CircuitPython_PCF8523)
- **Original Authors**: Philip R. Moyer and Radomir Dopieralski
- **Python Conversion**: Duncan Tourolle
## License
MIT License - See LICENSE file for details
## Contributing
This is a conversion of Adafruit's CircuitPython library. For core functionality improvements, please contribute to the [original repository](https://github.com/adafruit/Adafruit_CircuitPython_PCF8523).
For Python-specific issues or improvements, feel free to submit issues or pull requests.