B4R Code Snippet Display the current time via DS1302 RTC

SubName: Displaying the current time on a 4 Bit 7 segment display from a battery backed up DS1302 RTC (Real Time Clock).
Description: You can use this basic code to read and display the stored current time from a DS1302 RTC IC onto a 4 Bit 7 segment display. Use the TimeNist code module posted by Erel to set the current time into the DS1302 RTC, then you can remove the TimeNist code module and all associated code from your project as you will no longer need it again and it takes up valuable memory space, the 3V battery keeps the RTC time correct. Now every time you plug in the power the correct time will automatically appear on your displayed (not unless you remove the battery or the battery dies).

I forgot to take a photo of the original breadboard project, so here it is wired directly into an Uno. Photo taken at 11:45AM...
IMG_20170303_114517_1.jpg

B4X:
'WIRE LEGEND
'Real Time Clock Pins
'VCC = 3.3V
'GND = GND
'CLK = 5
'DAT = 6
'RST = 7

'WIRE LEGEND
'4 Digit display Pins
'VCC = 5V
'GND = GND
'CLK = 13
'D10 = 10

Sub Process_Globals
    Public Serial1 As Serial
    Private RTC As DS1302
    Private Display As TM1637Display
    Private TmrCounter As Timer
    Private SetDots As Boolean = True
End Sub

Private Sub AppStart
    Serial1.Initialize(115200)
    Log("AppStart")

    RTC.Initialize(7, 6, 5) 'LOOK AT WIRE LEGEND ABOVE

    Display.Initialize(13, 10) 'LOOK AT WIRE LEGEND ABOVE
    Display.SetBrightness(0, True)

    TmrCounter.Initialize("TmrCounter_Tick", 500)
    TmrCounter.Enabled = True
End Sub

Sub TmrTime_Tick
    Dim RTCTime As Int = JoinStrings(Array As String(NumberFormat(RTC.CurrentTime.Hours, 2, 0), NumberFormat(RTC.CurrentTime.Minutes, 2, 0)))

    SetDots = Not(SetDots)
    Dim SwapDots() As Byte
    If SetDots Then SwapDots = Array As Byte(0xFF) Else SwapDots = Array As Byte(0x00) 'Swap the dots (the colon) from Off to On and vice versa
    Display.ShowNumberDec3(RTCTime, True, 4, 0, SwapDots(0)) 'Blink the dots (the colon) every 500 milliseconds

    If Not(SetDots) Then Return 'Dots are Off so Return
    Display.ShowNumberDec3(RTCTime, True, 4, 0, SwapDots(0)) 'Update the display every (2 x 500) milliseconds (1 second)

    Log("RTC Time = ", NumberFormat(RTC.CurrentTime.Hours, 2, 0), ":", NumberFormat(RTC.CurrentTime.Minutes, 2, 0), ":", NumberFormat(RTC.CurrentTime.Seconds, 2, 0)) 'Added just for a B4R visual log reference
End Sub

Tags: Time, Clock, Display, DS1302, Crystal, Battery

Note: The top rail is 5V and the bottom rail is 3V.
Display time with RTC_bb.png
 
Last edited:
Top