PiicoDev Real Time Clock (RTC) RV-3028 - Getting Started Guide

Updated 08 July 2022

This guide will help you get started with a PiicoDev Real Time Clock. We'll set and read the time/date, observe the power-backup capability, and configure the RTC with an alarm.

A Real-Time Clock (RTC) is a timekeeping device that accurately tracks the passage of time. Most RTCs feature a calendar and alarm so they may be used to schedule actions. The PiicoDev Real-Time Clock is based on a low-power and very accurate RV-3028, factory calibrated to within 30 seconds per year. Power to the RTC is backed-up by a supercapacitor, capable of running the clock for up to a week without external power. When power is connected, the supercap is recharged. From dead-flat, it takes about three minutes to charge the supercap enough to sustain shorter power outages. A full charge takes about an hour.

 

Hardware and Connections

To follow along you'll need:

Plug your Pico into the expansion board. Make sure it is plugged in the correct orientation - Pin 0 on the expansion board should be to the left of the Pico's USB connector.

Connect your RTC to the expansion board with a PiicoDev Cable.

To follow along you'll need:

Mount the Adapter onto your Pi's GPIO. Make sure it is plugged in the correct orientation - An arrow on the Adapter will point to the Pi's Ethernet connector (on a Pi 3 the Ethernet connector and USB ports are swapped.)

Connect your RTC to the Adapter with a PiicoDev Cable.

To follow along you'll need:

Plug your micro:bit into the Adapter, making sure the buttons on the micro:bit are facing up.

Connect your RTC to the Adapter with a PiicoDev Cable.

Setup Thonny 

Select your dev board from the tabs above to get ready for programming with Thonny for the first time. 

If you have already programmed with PiicoDev modules before, there's probably no need to follow these steps again.

Let's get set up with scripting in Thonny for the Raspberry Pi Pico.

We'll install Thonny, configure for Pico and write our first script. To follow along you'll need:

Contents

 

Install Thonny

If you're working on a Raspberry Pi 4, you're in luck - Thonny comes pre-installed. For those on another operating system, download Thonny here and run the installer.

Once the installer finishes, run Thonny.

Set up Thonny

Hold the BOOTSEL button on your Pico, and connect your Pico to your computer via USB.

Go to Run > Select interpreter and choose MicroPython (Raspberry Pi Pico).

It's also a good idea to install or update firmware. This will update your Pico with the latest version of MicroPython, or install MicroPython if it wasn't already.

Select Interpreter

REPL interface (Shell)

We can immediately start executing code in the REPL - Enter this code in the shell tab: print("Hello, World!")

The command will be sent to your Pico, which will execute the command and display back the message.

We can also take control of the on-board LED by executing the following code:

from machine import Pin
led = Pin(25, Pin.OUT)
led.toggle()

This code will toggle the LED. If you keep executing led.toggle() the LED will keep changing state.

REPL Interface

LED On

Writing a Script

Create a new script with File > New and paste in the following code:

from machine import Pin
from time import sleep
led = Pin(25, Pin.OUT)
n = 0;
while True:
    led.toggle()
    print("13 x {} = {}".format(n, 13*n)) # print the thirteen-times table
    n = n + 1
    sleep(0.5)

Save the script - you will be prompted to save to your computer OR the pico. Select save to Pico and name the file main.py

Return to the REPL and press Ctrl+D (or use the Stop/Restart button) to restart your Pico. The LED should flash at a steady rate and the shell should begin printing multiples of thirteen.

Script Output

Installing a Package

Packages are reusable pieces of code that another programmer has written for a common task, such as interfacing with a specific piece of hardware. Thonny has support for installing micropython packages from the Python Package Index - aka 'PyPI' directly onto the Raspberry Pi Pico.

To install a package, ensure the Pico is plugged in and go to Tools > Manage Packages, which will show the Manage Packages dialog.

Enter the name of the package you would like to install into the search bar and click 'Search on PyPI'.

In the search results list, click the title of the package you would like to install. A title that's in bold simply indicates a direct search match on the text you entered in the search bar.

The Manage Packages dialog will show an overview of the package you have clicked. Click Install to install the package on your Pico.

You can confirm the package has been installed by checking the 'Raspberry Pi Pico' section of the File View in Thonny. The view should show a new folder named 'lib', and inside this folder will be one or more folders containing the metadata and source code of the library you just installed.

 

An example of installing the micropython-servo libraryAn example of installing the micropython-servo library
An example of installing the micropython-servo library

Conclusion

We've installed Thonny and uploaded scripts to our Raspberry Pi Pico - if you have any questions feel free to start the conversation below, or open a topic in our forums - we're full time makers and happy to help!

Good news! Thonny comes pre-installed with Raspberry Pi OS. However, to work with PiicoDev we need to enable I2C communications as follows:

  • Power on your Raspberry Pi.
  • Open the Preferences > Raspberry Pi Configuration, select the Interfaces tab
  • Ensure I2C is Enabled

You only need to do this step for your first PiicoDev project - from here on you probably won't have to repeat this step when using PiicoDev hardware.

Let's get set up with scripting in Thonny for the Micro:bit. We'll install Thonny, configure for Micro:bit, and write our first script.

All you'll need to follow along is a Micro:bit v2 GO kit

Contents

Install Thonny

Download Thonny here and run the installer.

Once the installer finishes, run Thonny.

Set up Thonny

Connect your Micro:bit V2 to your computer with the USB cable.

connect-microbit-to-computer-with-usb-cable

Open Thonny, and in the menu bar find Run > Select interpreter and choose MicroPython (BBC micro:bit)

It's also a good idea to install or update firmware. This will update your micro:bit with the latest version of MicroPython, or install MicroPython if it wasn't already.

select-microbit-interpreter-in-thonny

Make sure the Files pane and Plotter are visible by selecting them in View > Files, and View > Plotter.

REPL interface (Shell)

Click the red STOP button to restart the MicroPython on your micro:bit if necessary. The Shell tab should display a block of text that indicates MicroPython is running:

thonny-shell-restarted

We can immediately start executing code in the REPL - Enter this code in the shell tab: print("Hello, World!")

The command will be sent to your micro:bit, which will execute the command and display back the message - nice!

Next, we can also take control of the on-board speaker by executing the following code:

from microbit import *
import audio
audio.play(Sound.HAPPY)

This code will play a happy tone from the micro:bit's speaker! If you the LED. If you keep executing audio.play(Sound.HAPPY), the tone will repeat.

microbit-thonny-repl-play-audio

Writing a Script

The REPL is great for test-driving some new commands and performing short experiments - the real power is in scripting though.

Create a new script with File > New and paste in the following code:

from microbit import *
import audio

print("Hello!")

multiple = 1 # initialise the counter

while True:
    if button_a.was_pressed(): # get the next multiple of the thirteen
        result = multiple * 13 # Calculate the result
        print("13 times " + str(multiple) + " is " + str(result)) # print the multiplication
        multiple = multiple + 1 # increment the multiple
    
    if button_b.was_pressed(): # Say Hello
        display.show(Image.HAPPY)
        audio.play(Sound.HAPPY)
        display.clear()
        
    sleep(10) # a 10 millisecond delay

Save the script - you will be prompted to save to your computer OR the micro:bit. Select save to micro:bit and name the file main.py

Return to the REPL and press Ctrl+D to restart your micro:bit. If something went wrong, use the Stop/Restart button, then Ctrl+D. 

Now, when we press the A button, the Shell will print the next multiple of 13, or if we press the B-button, our micro:bit gives us a smile and a hello sound.

thonny-example-script-for-microbit

Notice the plot is also showing some lines, and they're colour-coded to numbers in the print statement! In my case:

  • The Blue line is the constant 13,
  • The Orange Line is the multiple variable that increases slowly, and
  • The Red line is the result variable, which increases really quickly.

Useful Tips

  • You can stop a running script by selecting the Shell window and pressing Ctrl+C. This is useful if we want to make changes to the file(s) stored on the micro:bit.
  • Reboot your micro:bit (or other MicroPython device) by selecting the Shell window and pressing Ctrl+D
  • If something goes wrong, you can always click the red STOP button in the menu bar

Uploading and Downloading Files

We've been working with a file stored directly on the micro:bit - if you'd like to keep a copy on your computer, right-click the main.py file and select the 'download' option. Similarly, you can always upload code to your micro:bit by right-clicking files on your computer and selecting the upload button.

download-script-from-microbit-to-computer

Conclusion

We've installed Thonny and uploaded our first script to our micro:bit. The script includes branches depending on which button is pressed and can generate audio tones and perform basic arithmetic. Now we can write scripts, move them between micro:bit and computer, or test code interactively using the REPL.

If you have any questions feel free to start the conversation below or open a topic in our forums - we're full-time makers and happy to help!

Download / Install PiicoDev Modules

To work with PiicoDev hardware, we need to download some drivers. The drivers provide all the functions to easily connect and communicate with PiicoDev hardware. Select your dev board from the options above.

We will need these files to easily drive the PiicoDev Real Time Clock:

  • Save the following files to your preferred coding directory - In this tutorial, we save to My Documents > PiicoDev.
  • Upload the files to your Pico. This process was covered in the Setup Thonny section.

The PiicoDev Unified Library is responsible for communicating with PiicoDev hardware, and the device module contains functions for driving specific PiicoDev devices.

 

We will now install/upgrade the PiicoDev python module for Thonny. This module contains all the drivers to work with all current PiicoDev hardware. Even if you have already installed the PiicoDev modules before, it's still worth upgrading to the latest version if one is available.

First, run Thonny by clicking the:

  1. Pi Start Menu
  2. Programming
  3. Thonny IDE

We need to set up a virtual environment to install the PiicoDev module into. This only needs to be done once as Thonny will remember an environment you have already made. If you are unsure if you have already set one up, you can always create a new one by following these steps.

To set up a virtual environment, click on run  > configure interpreter, to open up the interpreter tab.

In this window, we can create a new virtual environment in the bottom right. A notification window will first pop up, just click OK.

In this window, we are going to create a new empty folder in our Home Directory which will be the location of our virtual environment. To do so follow these steps:

  1. Select the Home tab on the left-hand side of the window.
  2. Click the Create Folder button in the top right.
  3. Enter the name of the new folder. You can call it what you want, but we will call ours "myenv". Once you have written the name, click Create next to it.
  4. Click OK in the bottom left.

Thonny will then set up your virtual environment and when it has finished, it will return to the Interpreter tab. Click OK, and you will have successfully set up the environment.

Note: the Python Executable path now points to the environment we just created.

Remember, you only need to do this once as the next time you open Thonny it will use this environment.

Next, open the package manager. From within Thonny click Tools > Manage Packages

Enter "piicodev" and click "Search on PyPI"

Finally, Install PiicoDev. If you already have PiicoDev installed, there may be an Upgrade button instead, to upgrade to a newer version.

 

With the PiicoDev module installed we are now ready to begin programming with PiicoDev hardware.

We will need these files to easily drive the PiicoDev Real Time Clock:

  • Save the following files to your preferred coding directory - In this tutorial, we save to My Documents > PiicoDev.
  • Upload the files to your micro:bit. This process was covered in the Setup Thonny section.

The PiicoDev Unified Library is responsible for communicating with PiicoDev hardware, and the device module contains functions for driving specific PiicoDev devices.

Set and Read the Time and Date

The following example shows how to set and read the time. The script initialises the RTC which enables charging the supercap. The date and time are set numerically, and the weekday is set with an integer between 0 and 6.

The setDateTime() method pushes the values we have set onto the RTC. Conversely, the getDateTime() method pulls the current date-time from the RTC and stores that data into the attributes (day, month, year, etc.). That means any time we want to get the current time, we must first call getDateTime().

We can query the name of the weekday by reading from the weekdayName property which contains a string ("Monday", "Tuesday" ... "Sunday"). weekdayName assumes that Monday is day zero. If you prefer, you can also set the weekday using weekdayName eg. rtc.weekdayName = "Monday"

timestamp() is a special method that first updates the current date-time, and then returns a string in the format YYYY-MM-DD HH:MM:SS. This is useful for printing timestamps to the shell or a log file.

# PiicoDev Real Time Clock RV-3028
# An example of how to set and read the date, time, and weekday

from PiicoDev_RV3028 import PiicoDev_RV3028
from PiicoDev_Unified import sleep_ms

rtc = PiicoDev_RV3028() # Initialise the RTC module, enable charging

# Set the time by assigning values to rtc's attributes
# Replace the following values with the current date/time
rtc.day = 6
rtc.month = 5
rtc.year = 2022
rtc.hour = 11
rtc.minute = 57
rtc.second = 00
rtc.ampm = '24' # 'AM','PM' or '24'. Defaults to 24-hr time
rtc.weekday = 4 # Rolls over at midnight, works independently of the calendar date
rtc.setDateTime() # Sets the time with the above values

# Get the current time
rtc.getDateTime()

# Print the current time, and today's name
# You can read from individual time attributes eg hour, minute, weekday.
print("The time is " + str(rtc.hour) + ":" + str(rtc.minute))
print("Today is " + str(rtc.weekdayName) + "\n") # weekdayName assumes counting from 0=Monday. 

while True:
    print(rtc.timestamp()) # timestamp() automatically updates time, and returns a pre-formatted string. Useful for printing and datalogging!
    sleep_ms(1000)

After running the script, you ought to see:

  • First, a message that reads "The time is..." and "Today is..." with the correct time and week day name.
  • Second, the current timestamp being printed every second.

 

Running on Backup Power

In the previous example, the PiicoDev RTC was automatically configured to charge the supercapacitor during initialisation. If your RTC has remained powered for a few minutes since running the example then the capacitor will have enough charge to withstand a power outage. Let's test it out!

  • Stop the example script if you haven't already
  • Disconnect the RTC for some time
  • Reconnect the RTC

Now we'll check if the clock has kept accurate time during the power outage. Run the following code - which is a stripped-down version of the previous example that just reads the timestamp. All going well, you should see accurate timestamps printing in the shell!

Be careful not to accidentally set the time again during this process! There should be no need to call setDateTime(), since we already set the correct time in the previous example.

# A simple example to read the date, timestamp and weekday from the PiicoDev RTC
from PiicoDev_RV3028 import PiicoDev_RV3028
from PiicoDev_Unified import sleep_ms

rtc = PiicoDev_RV3028()

while True:
    print(rtc.timestamp()) 
    sleep_ms(1000)

Advanced Examples

These examples use more advanced features of the RTC. As such, their documentation is a little more terse. Select a tab to see the example.

The following example checks whether the current time matches a pre-set scheduled time to perform an action. The action is only performed once. This can be used to create an alarm, or schedule events in the future. The alarmSetup() method accepts values for minutes, hours, and weekday (or date).

The status of the alarm can be checked with the checkAlarm() method, which returns True the first time it is called after an alarm has triggered. Subsequent calls to checkAlarm() will return False, until the alarm is triggered again. This means you don't have to query checkAlarm() at the exact time the alarm is set for.

By default, alarmSetup() will also configure the hardware interrupt pin (INT) to trigger on an alarm event.

# PiicoDev Real Time Clock RV-3028
# Some examples of how to set an alarm
# Alarms can trigger on a combination of minutes, hours, and weekday/date

from PiicoDev_RV3028 import PiicoDev_RV3028
from PiicoDev_Unified import sleep_ms
rtc = PiicoDev_RV3028() # Initialise the RTC module (24-hr mode by default), enable charging

### Trigger once per hour, at the start of the hour
rtc.alarmSetup(minutes=0)

### Trigger on the 3rd day of the week (count from zero) at 1:23 PM
# rtc.alarmSetup(weekday=2, hours=13, minutes=23)

### Trigger on the first day of the month
# rtc.alarmSetup(date=1)

while True:
    print(rtc.timestamp())
    if rtc.checkAlarm():
        print("Alarm Triggered")
        
    sleep_ms(2000)

The PiicoDev RTC features a clock output pin (CLK) that generates a square wave - the frequency is user configurable. Valid frequencies are: 0Hz (off, Low), 1, 32, 64, 1024, 8192 and 32,768Hz

# Set the CLK output pin frequency

from PiicoDev_RV3028 import PiicoDev_RV3028

rtc = PiicoDev_RV3028()
rtc.configClockOutput(1) # The frequency, in Hz, of the square wave on the CLK output pin. Valid values are: 32768, 8192, 1024, 64, 32, 1, and 0 (always low).

The PiicoDev RTC features a UNIX time register that can be set independently of the date-time. UNIX time is represented as the number of seconds since the last epoch. When reset to zero, this timer can be useful for keeping uptime or a mission-timer for data logging

from PiicoDev_RV3028 import PiicoDev_RV3028
from PiicoDev_Unified import sleep_ms

rtc = PiicoDev_RV3028() # Initialise the RTC module
rtc.setUnixTime(0) # reset UNIX time

while True:
    print(rtc.getUnixTime()) # display UNIX time
    sleep_ms(1500)

The PiicoDev RTC features an External Event Interrupt pin (EVI) and Time Stamp function that can capture the time of an external event. The example below configures the EVI pin to capture the timestamp of a falling edge. If multiple events occur before the event time is queried, only the most recent timestamp is returned.

# Read the EVI pin event time.
# The program will continue listening for an event until one is detected.
from PiicoDev_RV3028 import PiicoDev_RV3028
from PiicoDev_Unified import sleep_ms

rtc = PiicoDev_RV3028()

rtc.resetEventInterrupt(edge = 'falling')

rtc.getDateTime()
print('Monitoring started at: ' + rtc.timestamp())

while (rtc.getEventInterrupt() is False):
    print('Waiting for 10 seconds.  If there is a falling edge on EVI pin the time will be recorded.')
    sleep_ms(10000)
print('Event occurred at: ', end='')
rtc.getDateTime(eventTimestamp=True)
print(rtc.timestamp(eventTimestamp=True))


Technical Resources

Pin Description
GND Power Input, Ground
3V3 Power Input, 3.3V. Tolerant up to 5V (Note 1)
SDA I2C Communications - Data
SCL I2C Communications - Clock
INT Interrupt Output, Low when an interrupt occurs
EVI Event Input - pull to Ground to trigger an event interrupt
CLK

Clock output, square wave configurable from 1Hz to 32,768Hz

(Note 1) The RV-3028 RTC will operate down to Vcc of 1.2V however at this voltage the included supercapacitor will not hold sufficient charge to guarantee that time is kept through a power failure. Time is lost when the capacitor voltage drops below about 900 mV and it will typically only charge to Vcc-0.3V due to an internal Schottky diode. The RV-3028 works up to 5V, but this is only recommended for freestyle prototyping ie. not connected to any other PiicoDev hardware. PiicoDev is a 3.3V system.

License

You're welcome to reuse and remix this content for any NonCommercial purposes.

This content is distributed under CC BY-NC-SA 4.0:

You are free to Share (copy and redistribute the material in any medium or format); and Adapt (remix, transform, and build upon the material) so long as the purpose is NonCommercial. If you remix, transform, or build upon the material, you must distribute your contributions under the same license. Read the full license.
If you want to use this content for commercial purposes, send us an email to discuss.

 

Have a question? Ask the Author of this guide today!

Please enter minimum 20 characters

Your comment will be posted (automatically) on our Support Forum which is publicly accessible. Don't enter private information, such as your phone number.

Expect a quick reply during business hours, many of us check-in over the weekend as well.

Comments


Loading...
Feedback

Please continue if you would like to leave feedback for any of these topics:

  • Website features/issues
  • Content errors/improvements
  • Missing products/categories
  • Product assignments to categories
  • Search results relevance

For all other inquiries (orders status, stock levels, etc), please contact our support team for quick assistance.

Note: click continue and a draft email will be opened to edit. If you don't have an email client on your device, then send a message via the chat icon on the bottom left of our website.

Makers love reviews as much as you do, please follow this link to review the products you have purchased.