Setting a Real Time Clock using a Pushbutton



' RTC_2.Bas
'
' Sets RTC using PutTime to 00:00:00.  Reads RTC using GetTime and 
' displays in HH:MM:SS format.
'
' Periodically look at pushbuttons on Pin3 (hours), Pin2 (minutes) and
' Pin1 (seconds).  If Pin3 is at zero, Hour is incremented (rolls over
' from 23 to 00).  If Pin2 is at zero, Minute is incremented (rolls over
' from 59 to 00).  If Pin1 is at zero, sets Second to 0.0.
'
' Thus provides a relatively simple technique to set the clock.
'
' If the time is in the range of 00:01:00 to 00:03:00 an LED is turned
' on.
'
' Compile with SerialPort.Bas
' 
' copyright, David Seebold, Baltimore, MD, Oct, '99

  
Sub Main()  

  Const zero as Byte = 0

  Dim Hour as Byte, Minute as Byte, Second as Single 
  Dim SecByte as Byte
  Dim str as String, initializing as String 

  Call OpenSerialPort(2, 9600)

  Hour = 0
  Minute = 0
  Second = 0.00

  initializing = "initializing..."
  Call PutPin(14,0)    ' turn LED off
  Call PutTime(Hour, Minute, Second)
  Call PutStr(initializing)
  Call NewLine()
  Call Sleep(0.5)

 Do
    Call GetTime(Hour, Minute, Second)
        ' fetch the date and time

    If(Hour < 10) Then	' display the time
	Call PutB(zero)
    End If

    Call PutB(Hour)
    str = ":"
    Call PutStr(str)     

   If(Minute < 10) Then
	Call PutB(zero)
   End If

   Call PutB(Minute)
   str = ":"
   Call PutStr(str)     

   SecByte = CByte(Second)
   If(SecByte < 10) Then
      Call PutB(zero)
   End If
   Call PutB(SecByte)     
   Call NewLine()

     ' check time and if in range, turn on LED
   If ((Hour = 0) AND (Minute >= 1) AND (Minute <=2)) then
      Call PutPin(14, 1)      ' turn on the LED
   Else
      Call PutPin(14, 0)      ' otherwise, turn it off
   End if

   Call Sleep(0.5)      

   Call Check_for_time_change(Minute, Hour, Second) 

 Loop

End Sub

Sub Check_for_time_change(ByRef Minute as Byte, ByRef Hour as Byte, _
                          ByRef Second as Single)

   Dim Pin3 as Byte, Pin2 as Byte, Pin1 as Byte
   Dim Change as Byte

   Change = 0

   Call PutPin(1, 3) ' configures pins 1, 2 & 3 as inputs 
   Call PutPin(2, 3) '  with input pullup resistors
   Call PutPin (3, 3)

   Pin1 = GetPin(1)		'reads the state of pin 1
   Pin2 = GetPin(2)		'reads the state of pin 2
   Pin3 = GetPin(3)

   If(Pin3 = 0) Then		' Hour increment
      Hour = Hour + 1
      Change = 1		' there was a change
   End If

   If(Pin2 = 0) Then		' Minute increment
      Minute = Minute + 1
      Change = 1
   End If

   If(Pin1 = 0) Then		' Zero the seconds
      Second = 0.0
      Change = 1      
   End If

   If (Change=1) Then
      If (Minute > 59) Then	' adjust the time as necessary
         Minute = 0
         Hour = Hour + 1
      End If

      Hour = Hour MOD 24
      
      Call PutTime(Hour, Minute, Second)   
   End If 

End Sub