mcp7940 1.0
mcp7940 driver library
Loading...
Searching...
No Matches
mcp7940.c File Reference

Implementation of the MCP7940 driver functions. More...

#include "mcp7940.h"
Include dependency graph for mcp7940.c:

Functions

const char * mcp7940_weekday_string (unsigned char day)
 Returns a three-letter weekday abbreviation for a given day value.
void mcp7940_init (void)
 Initializes the MCP7940 RTC with battery backup, MFP mode, and oscillator settings.
MCP7940_Error mcp7940_trimming (MCP7940_Trim mode, unsigned char value)
 Configures the MCP7940 oscillator trimming value and verifies the write.
void mcp7940_oscillator (MCP7940_Mode mode)
 Enables or disables the MCP7940 RTC oscillator or external clock input.
MCP7940_Status mcp7940_status (void)
 Reads and returns the current MCP7940 status flags from the weekday register.
void mcp7940_mfp_output (MCP7940_Mode output)
 Controls the MCP7940 MFP pin when configured as a general-purpose output.
unsigned char mcp7940_weekday (MCP7940_Register data)
 Reads the weekday value from the MCP7940 for the selected timestamp register set.
void mcp7940_time (FORMAT_Time *time, MCP7940_Register reg)
 Reads hour, minute, and second fields from the MCP7940 into a FORMAT_Time structure.
void mcp7940_date (FORMAT_Date *date, MCP7940_Register reg)
 Reads day, month, and year fields from the MCP7940 into a FORMAT_Date structure.
void mcp7940_datetime (FORMAT_DateTime *datetime, MCP7940_Register reg)
 Reads both time and date from the MCP7940 into a FORMAT_DateTime structure.
MCP7940_LeapYear mcp7940_leapyear (void)
 Returns the current leap year status from the MCP7940 device.
MCP7940_Error mcp7940_setweekday (unsigned char weekday)
 Sets the MCP7940 weekday field in the RTCWKDAY register.
MCP7940_Error mcp7940_settime (const FORMAT_Time *time)
 Sets the current time of the MCP7940 RTC from a FORMAT_Time structure.
MCP7940_Error mcp7940_setdate (const FORMAT_Date *date)
 Sets the current calendar date of the MCP7940 RTC from a FORMAT_Date structure.
MCP7940_Error mcp7940_setdatetime (const FORMAT_DateTime *datetime)
 Sets the current MCP7940 date and time from a FORMAT_DateTime structure.

Variables

const char weeksdays [][4]

Detailed Description

Implementation of the MCP7940 driver functions.

This file contains the implementation of functions to initialize the MCP7940 device, write and read data from/to rtc. It utilizes TWI/I2C communication to interact with the MCP7940 hardware.

Author
g.raf
Date
2026-01-25
Version
1.0 Release
Note
This file is part of a larger project and subject to the license specified in the repository. For updates and the complete revision history, see the GitHub repository.
See also
https://github.com/0x007e/drivers-rtc-mcp7940 "MCP7940 RTC driver library"

Function Documentation

◆ mcp7940_date()

void mcp7940_date ( FORMAT_Date * date,
MCP7940_Register reg )

Reads day, month, and year fields from the MCP7940 into a FORMAT_Date structure.

Parameters
datePointer to a FORMAT_Date structure that will be populated with calendar information from the MCP7940 registers. On return:
  • date->day contains the decoded day-of-month value.
  • date->month contains the decoded month value.
  • date->year contains the decoded year value for current time, or 0 for power-up/power-down timestamp selections.
regSelects which MCP7940 register set to read, using a value from MCP7940_Register:

This function uses helper routines (mcp7940_day(), mcp7940_month(), and optionally mcp7940_year()) to extract the calendar date fields from the selected MCP7940 time or timestamp registers and write them into date. For the current time selection, the year field is read from the device via mcp7940_year(). For power-down and power-up timestamp registers, the year field is not read and date->year is set to 0, as this implementation does not associate a stored year with those timestamp records.

Here is the caller graph for this function:

◆ mcp7940_datetime()

void mcp7940_datetime ( FORMAT_DateTime * datetime,
MCP7940_Register reg )

Reads both time and date from the MCP7940 into a FORMAT_DateTime structure.

Parameters
datetimePointer to a FORMAT_DateTime structure that will be filled with the time and date fields obtained from the MCP7940 registers corresponding to reg. On return, datetime->time and datetime->date contain the decoded values.
regSelects which MCP7940 register set to read, using a value from MCP7940_Register:

This function is a convenience wrapper that combines mcp7940_time() and mcp7940_date() to populate a FORMAT_DateTime instance in a single call. It first reads the time portion into datetime->time, then reads the date portion into datetime->date, using the same reg selection for both operations to keep time and date information consistent.

Here is the call graph for this function:

◆ mcp7940_init()

void mcp7940_init ( void )

Initializes the MCP7940 RTC with battery backup, MFP mode, and oscillator settings.

This function configures the MCP7940 device according to the compile-time configuration macros. It first enables or disables the battery backup feature using mcp7940_battery() depending on MCP7940_BATTERY_BACKUP_EN. It then reads the current CONTROL register, preserves the EXTOSC bit, and updates control flags related to coarse trimming (MCP7940_CSTRIM_bm), square-wave output and prescaler (MCP7940_SQWEN_bm and MCP7940_MFP_SQUARE_WAVE_PRESCALER) or alarm mode (MCP7940_MFP_ALARM_MODE), depending on MCP7940_SQW_CRSTRIM_EN and MCP7940_MFP_MODE. Finally, it enables the RTC oscillator via mcp7940_oscillator(), allowing the device to begin timekeeping.

< Bit mask for the EXTOSC bit, selecting an external clock input instead of the crystal.

Here is the call graph for this function:

◆ mcp7940_leapyear()

MCP7940_LeapYear mcp7940_leapyear ( void )

Returns the current leap year status from the MCP7940 device.

Returns
A MCP7940_LeapYear value derived from the MCP7940 leap-year field:

This function reads the leap-year indicator bits from the MCP7940 and masks and shifts them into the MCP7940_LeapYear enumeration domain. The returned value reflects the RTC’s internal leap-year status, which influences how February 29 is handled in the device’s calendar logic.

< Bit mask for the leap-year indicator (LPYR) in the month register.

< Bit position of the leap-year indicator (LPYR) in the month register.

◆ mcp7940_mfp_output()

void mcp7940_mfp_output ( MCP7940_Mode output)

Controls the MCP7940 MFP pin when configured as a general-purpose output.

Parameters
outputDesired output mode for the MFP pin, using a value from MCP7940_Mode:

This function is available only when MCP7940_MFP_MODE is set to MCP7940_MFP_MODE_OUTPUT at compile time. In this mode, the MFP pin behaves as an open-drain general-purpose output controlled by the OUT bit in the CONTROL register. The function reads the current CONTROL value, sets or clears the OUT bit according to output, and writes the updated value back, preserving all other control bits.

< Bit mask for the OUT control bit, which drives the MFP output level in output mode.

< Bit mask for the OUT control bit, which drives the MFP output level in output mode.

◆ mcp7940_oscillator()

void mcp7940_oscillator ( MCP7940_Mode mode)

Enables or disables the MCP7940 RTC oscillator or external clock input.

Parameters
modeSelects the desired oscillator mode, using a value from MCP7940_Mode:

Depending on the compile-time configuration, this function controls either the external oscillator input (MCP7940_USE_EXTOSC defined) by setting or clearing the EXTOSC bit in the CONTROL register, or the internal RTC oscillator by setting or clearing the ST (start oscillator) bit in the seconds register RTCSEC. The corresponding register is read first and then updated with the appropriate bit set or cleared while preserving the other bits.

< Bit mask for the EXTOSC bit, selecting an external clock input instead of the crystal.

< Bit mask for the EXTOSC bit, selecting an external clock input instead of the crystal.

Here is the caller graph for this function:

◆ mcp7940_setdate()

MCP7940_Error mcp7940_setdate ( const FORMAT_Date * date)

Sets the current calendar date of the MCP7940 RTC from a FORMAT_Date structure.

Parameters
datePointer to a FORMAT_Date structure containing the date to be set. The following fields are used:
  • date->day (expected range: 1–31; only a basic range check is performed)
  • date->month (expected range: 1–12)
  • date->year (expected range: 0–99, interpreted as an application-defined offset)
Returns
Returns one of the following error codes:

This function first validates the date fields using validate_date(). If validation fails, it returns MCP7940_Error_Fail immediately. Otherwise, it writes the day, month, and year values to the MCP7940 RTCDATE, RTCMTH, and RTCYEAR registers via mcp7940_setdata(). The implementation assumes that any required conversion to the device’s register format (for example, BCD encoding and leap-year bit handling) is performed inside mcp7940_setdata() or the lower-level I2C access functions.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ mcp7940_setdatetime()

MCP7940_Error mcp7940_setdatetime ( const FORMAT_DateTime * datetime)

Sets the current MCP7940 date and time from a FORMAT_DateTime structure.

Parameters
datetimePointer to a FORMAT_DateTime structure containing both time and date components to be written to the MCP7940. The following subfields are used:
  • datetime->time.hour, datetime->time.minute, datetime->time.second
  • datetime->date.day, datetime->date.month, datetime->date.year
Returns
A combined MCP7940_Error value obtained by OR-ing the results of:

This function is a convenience wrapper that programs both the current time and calendar date of the MCP7940 in one call. It first calls mcp7940_settime() with datetime->time and then mcp7940_setdate() with datetime->date. The individual error codes are bitwise OR-combined and returned to the caller, allowing detection of failures in either step.

Here is the call graph for this function:

◆ mcp7940_settime()

MCP7940_Error mcp7940_settime ( const FORMAT_Time * time)

Sets the current time of the MCP7940 RTC from a FORMAT_Time structure.

Parameters
timePointer to a FORMAT_Time structure containing the time to be set. The following fields are used:
  • time->hour (expected range: 0–23)
  • time->minute (expected range: 0–59)
  • time->second (expected range: 0–59)
Returns
Returns one of the following error codes:

This function first validates the time fields using validate_time(). If validation fails, it returns MCP7940_Error_Fail immediately. Otherwise, it writes the hour, minute, and second values to the MCP7940 RTCHOUR, RTCMIN, and RTCSEC registers using mcp7940_setdata(), then enables the RTC oscillator via mcp7940_oscillator() so that timekeeping starts or continues from the new value. The implementation assumes that conversion to the device’s register format (for example BCD) is handled inside mcp7940_setdata().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ mcp7940_setweekday()

MCP7940_Error mcp7940_setweekday ( unsigned char weekday)

Sets the MCP7940 weekday field in the RTCWKDAY register.

Parameters
weekdayZero-based weekday index to be written to the device. Valid values are:
  • 0 for the first day of the week (mapped to device value 1),
  • 1 for the second day of the week (mapped to device value 2),
  • ...
  • 6 for the seventh day of the week (mapped to device value 7).

Values greater than or equal to 7 are rejected.

Returns
Returns one of the following error codes:

This function programs the weekday field of the MCP7940 RTCWKDAY register. The MCP7940 encodes weekday values in the range 1–7, so the provided zero-based weekday is incremented by 1 and masked with 0x07 before being written. The existing upper bits of RTCWKDAY (such as VBATEN, PWRFAIL, and OSCRUN) are preserved by masking with 0xF8 and OR-ing in the new weekday value.

◆ mcp7940_status()

MCP7940_Status mcp7940_status ( void )

Reads and returns the current MCP7940 status flags from the weekday register.

Returns
A MCP7940_Status value containing a bitwise combination of:

If none of these bits are set, the function returns MCP7940_Status_None.

This function reads the RTCWKDAY register of the MCP7940 and masks out the OSCRUN, PWRFAIL, and VBATEN bits to construct an MCP7940_Status value. The resulting status can be used by higher-level code to determine whether the RTC oscillator is running, whether a power failure has occurred, and whether battery backup is configured.

< Bit mask for the OSCRUN flag indicating that the oscillator is running.

< Bit mask for the PWRFAIL flag indicating that a power failure has occurred.

< Bit mask for the VBATEN flag enabling battery-backed timekeeping.

◆ mcp7940_time()

void mcp7940_time ( FORMAT_Time * time,
MCP7940_Register reg )

Reads hour, minute, and second fields from the MCP7940 into a FORMAT_Time structure.

Parameters
timePointer to a FORMAT_Time structure that will be populated with time information from the MCP7940 registers. On return:
  • time->hour contains the decoded hour value.
  • time->minute contains the decoded minute value.
  • time->second contains the decoded second value for current time, or 0 for power-up/power-down timestamp selections.
regSelects which MCP7940 register set to read, using a value from MCP7940_Register:

This function uses helper routines (mcp7940_hour(), mcp7940_minute(), and optionally mcp7940_second()) to extract the hour and minute from the selected MCP7940 time/timestamp registers and write them into time. For the current time selection, seconds are also read via mcp7940_second(). For power-down and power-up timestamp registers, the seconds field is not read and time->second is set to 0, since those registers do not store a separate seconds value in this implementation.

Here is the caller graph for this function:

◆ mcp7940_trimming()

MCP7940_Error mcp7940_trimming ( MCP7940_Trim mode,
unsigned char value )

Configures the MCP7940 oscillator trimming value and verifies the write.

Parameters
modeSelects the trim direction, using a value from MCP7940_Trim:
valueRaw trim magnitude to apply to the OSCTRIM register. Only the lower 7 bits (bit 6:0) are used as the trim value; bit 7 is set or cleared internally by this function according to mode to encode the sign of the adjustment. A value of 0 disables digital trimming.
Returns
Returns one of the following error codes:
  • MCP7940_Error_None if the OSCTRIM register was written successfully and a subsequent readback matches the programmed value.
  • MCP7940_Error_Fail if the readback of OSCTRIM does not match, indicating a possible I2C communication or device error.

This function masks value to seven bits, applies the sign bit according to the selected trim mode, and writes the resulting byte to the MCP7940 OSCTRIM register to adjust the RTC oscillator frequency. It then reads back the OSCTRIM register and compares it to the written value to confirm that the configuration was accepted by the device.

◆ mcp7940_weekday()

unsigned char mcp7940_weekday ( MCP7940_Register data)

Reads the weekday value from the MCP7940 for the selected timestamp register set.

Parameters
dataSelects which MCP7940 register block to read the weekday from, using a value from MCP7940_Register:
Returns
An unsigned 3-bit weekday value in the range 0–7, where the underlying MCP7940 encoding uses 1–7 for the day-of-week and 0 may be returned if the register contents are not yet initialized.

This function extracts the weekday field from the appropriate MCP7940 register depending on data. For the power-down and power-up timestamp registers, the weekday bits are located in the upper three bits of the month register (PWRDNMTH or PWRUPMTH) and are right-shifted by MCP7940_PWRWEEKDAY_bp after masking. For the current time, the weekday is read directly from the RTCWKDAY register and masked with 0x07 to return only the weekday bits.

< Bit position of the least significant bit of the weekday field in the power-fail timestamp month registers.

< Bit position of the least significant bit of the weekday field in the power-fail timestamp month registers.

◆ mcp7940_weekday_string()

const char * mcp7940_weekday_string ( unsigned char day)

Returns a three-letter weekday abbreviation for a given day value.

Parameters
dayEncoded weekday value in the MCP7940 format (1–7 expected), where:
  • 1 maps to "MON"
  • 2 maps to "TUE"
  • 3 maps to "WED"
  • 4 maps to "THU"
  • 5 maps to "FRI"
  • 6 maps to "SAT"
  • 7 maps to "SUN" Any other value is wrapped into this range and may yield the fallback "???".
Returns
Pointer to a constant, null-terminated string containing the three-letter weekday abbreviation corresponding to day.

This function converts the MCP7940 weekday encoding into a human-readable three-character abbreviation by masking and normalizing the input value into the index range of the internal weeksdays lookup table. The returned pointer refers to a static string and remains valid for the lifetime of the program.

Variable Documentation

◆ weeksdays

const char weeksdays[][4]
Initial value:
= {
"MON",
"TUE",
"WED",
"THU",
"FRI",
"SAT",
"SUN",
"???"
}