Problem with setting time in internal RTC

RP2040 based microcontroller boards running MicroPython.
Target audience: MicroPython users with an RP2040 boards.
This does not include conventional Linux-based Raspberry Pi boards.
Post Reply
kjk
Posts: 2
Joined: Thu Feb 11, 2021 10:32 am

Problem with setting time in internal RTC

Post by kjk » Thu Feb 11, 2021 10:40 am

Hi,

I'm trying to write a library for internal RTC in Micropython on Rp2. And I've found a problem I can't deal with.
To setup the time I use a code:

Code: Select all

import uctypes
RTC_BASE        = 0x4005c000
RTC_SETUP_0     = 0x04  # RTC setup register 0
RTC_SETUP_1     = 0x08  # RTC setup register 1
RTC_CTRL        = 0x0c  # RTC Control and status

def setTimeDate(year, month, day, dow, hours, mins, secs=0):
	ctrl       = uctypes.bytearray_at(RTC_BASE + RTC_CTRL, 1)
	ctrl[0]    = 0 # stop RTC
	setup_0    = uctypes.bytearray_at(RTC_BASE + RTC_SETUP_0, 4)
	setup_0[0] = day     # 1..31
	setup_0[1] = month  + ((year<<4) & 0xF0)
	setup_0[2] = year >> 4        
	setup_1    = uctypes.bytearray_at(RTC_BASE + RTC_SETUP_1, 4)
	setup_1[0] = secs
	setup_1[1] = mins
	setup_1[2] = hours
	setup_1[3] = dow
	ctrl[0]    = 0x13 # load RTC registers, start RTC
When I run setTiemeDate() every byte of register RTC_BASE + RTC_SETUP_1 (or SETUP_0) contains last written byte (a value of dow).
I can't wite different values for every byte. For example, I want to set time to Monday, 12:30:00:

Code: Select all

setup_1    = uctypes.bytearray_at(RTC_BASE + RTC_SETUP_1, 4)
setup_1[0] = 00
setup_1[1] = 30
setup_1[2] = 12
setup_1[3] = 1
When I read the register by print(setup_1) I get: b'\x01\0x01\0x01\0x01'.
The last value I've written to SETUP_1 is setup_1[3] = 1.

Could someone help me?
Regards, kjk

fdufnews
Posts: 76
Joined: Mon Jul 25, 2016 11:31 am

Re: Problem with setting time in internal RTC

Post by fdufnews » Thu Feb 11, 2021 12:16 pm

This answer will not explain why your solution does not work butt there is a way to set the time here

Edit:
Maybe the answer is here. Adressing the registers using their base address only allows 32 bits access. Atomic access needs to use base address + 0x2000

kjk
Posts: 2
Joined: Thu Feb 11, 2021 10:32 am

Re: Problem with setting time in internal RTC

Post by kjk » Thu Feb 11, 2021 3:05 pm

Thank you!
I should have used machine.mem32 intstead of uctypes.bytes_at. Now all is working without problems!

Code: Select all

def setTimeDate(year, month, day, dow, hours, mins, secs=0):
        machine.mem32[RTC_BASE + RTC_CTRL]    = 0x0000_0000 # stop RTC
        machine.mem32[RTC_BASE + RTC_SETUP_0] = day + (month<<8) + (year<<12)
        machine.mem32[RTC_BASE + RTC_SETUP_1] = secs + (mins<<8) + (hours<<16) + (dow<<24)
        machine.mem32[RTC_BASE + RTC_CTRL]    = 0x0000_0013 # load RTC registers, start RTC
Regards, kjk

Post Reply