A Real-Time Clock for the PICAXE-18X

IMPORTANT WARNING

The designs on this page are presented "as is" with no warranty or guarantee of operational correctness. The electronic design has not been built, tested nor proven, and there is no guarantee that the designs are sound or that damage will not occur when used with your own equipment. The software has not been tested, debugged and may not include the functionality described in this article. Anyone using the hardware and software designs or information related to them herein does so entirely at their own risk. No liability whatsoever is accepted by the author.

This project is a theoretical exercise and a work in progress and should be considered as an educational resource rather than as a completed or functional project.



The PICAXE doesn't include any Real-Time Clock, but elapsed time determination is easy to implement without any external hardware.



One problem with the PICAXE is its lack of an on-chip Real-Time Clock (RTC); without any RTC facility, it is difficult to execute program commands and keep track of elapsed time. This can cause problems in a variety of programs, and although the usually suggested solution is to use an external RTC chip, another, cheaper and software only, solution is to use a free-running timer within the PICAXE.

Providing that the free-running timer can be initialised, and its data read, the timer can be polled as part of the program's progress and elapsed time can be calculated. The only caveat is that the timer must be polled frequently enough that its value does not overflow, or accurate time measurement will be lost. The granularity affects how close to an actual elapse of time the elapsed time period is detected; with a high pre-scaler value, an overflow period of 524mS means that elapsed time will be within about half a second of what it really is and with a low pre-scale value, the elapsed time will be within a sixteenth of a second or so.

Assuming that timer reads are carried out expediently and within a time that is less than the overflow period; ignoring the granularity error, the accuracy of the RTC is maintained over long periods because the timer is tied to the PICAXE processor's internal oscillator, and is solely dependant upon the stability of the oscillator. For the PICAXE-28 range and the 40X, the resonator or crystal controlled oscillator should be extremely accurate, although for those which use an internal oscillator, the stability will vary depending upon frequency setting and operating voltage. Using the RTC to report elapsed time to a PC can be used to determine the stability of the PICAXE by comparing how it fares against the PC's own internal RTC.


In Practice

Once "Timer 1" has been enabled and is running, its value will increment from 0 to 65,535 at a rate determined by its prescaler value. When the prescaler value is set to zero ( ÷1 ), it counts every 1uS and overflows every 65,536uS. When it overflows it sets an Oveflow Flag.

Our Real-Time Clock program can run in a tight loop, waiting for the Overflow Flag to be set, clear the Overflow Flag, update its time and data, then wait for the next overflow ...

    Timer                  __ --.        __--.        __--.
    Value              __--     |    __--    |    __--    |
                   __--         |__--        |__--        |__
                                :            :
                                :            :
                                .----------. .----------. .--
    Overflow                    |          | |          | |
      Flag         -------------'          `-'          `-'
                                :            :          :
                                :        .-. :        .-.
    Timer Read      ---------------------| |----------| |-----
                                :        `-' :        `-'
                                :        :   :        :
    Timer Period                |<---------->|        :
                                         :            :
    Read Period                          |<---------->|

By counting the number of elapsed microseconds, we can determine when a second has elapsed; 1,000,000uS.

Both the overflow period ( 65,536uS ) and the number of microseconds in a second makes handling a counter rather difficult for a PICAXE which is limited to 16-bit words as its largest in-built variable size, however, our count does not have to be in microseconds, but can be divisions thereof.

By reducing the value of 'ticks' seen and how many 'ticks' make up a full second of elapsed time, we can bring the maths into a much more manageable range ...

    1,000,000      = 65,536 x K
      500,000 x 2  = 32,768 x K x 2
      250,000 x 4  = 16,384 x K x 4
      125,000 x 8  =  8,192 x K x 8
       62,500 x 16 =  4,096 x K x 16
       31,250 x 32 =  2,048 x K x 32
       15,625 x 64 =  1,024 x K x 64

If every time "Timer 1" overflows, we add 1,024 to a counter, when that counter exceeds 15,625 we know a second has elapsed. This is much more manageable using 16-bit words.

Because what we are counting does not match well with what elapsed time is in the real word ( the timer and counter use base-2 numbers and the real-world uses base-10 numbers ) after a second has elapsed the counter will usually contain a value which is greater than 15,625. If we discard this overflow our elapsed time will not include all elapsed ticks so the counter has 15,625 subtracted from it and the counter accumulates with what is left over.

Adding 1,024 to our counter every overflow works when the prescaler is zero, but if we use a larger pre-scaler the overflow will occur less frequently, and we need to correspondingly increase the value added to the counter on each overflow. Correspondingly, if we double the oscillator frequency then overflows will occur twice as frequently and we need to halve the value added to the counter on every overflow. An alternative is of course to adjust the value at which we consider a second to have occured, however it is impossible to accurately halve 15,625 using integer maths, and it is far easier to deal with changes to the smaller, powers-of-2 values, additions to the counter without seeing any overflow or loss of resolution.

The addition which need to made to the counter with various prescaler values and at various oscillator frequencies are as below ...

     Pre-Scaler   Divisor     4MHz         8MHz         16MHz

          0          1        1,024          512          256
          1          2        2,048        1,024          512
          2          4        4,096        2,048        1,024
          3          8        8,192        4,096        2,048

When the oscillator frequency is doubled, the frequency at which the overflow occurs is also doubled, and while our program code runs twice as fast, we can still only execute the same amount of code as at a lower oscillator frequency. increasing the oscillator frequency alone achieves nothing except that it can be used to increase the baud rate of serial communications.

To allow more program code to be executed before the timer overflows, the oscillator frequency has to be doubled and the pre-scaler increased.


Limitations on using Timer 1

The "Timer 1" will continue to operate no matter what the PICAXE is doing, and no matter how long it takes any PICAXE command or sequence takes to execution, but if the timer overflow is not read expediently, the elapsed time measurement will drift significantly.

In practical terms this means that any PICAXE commands which wait for an action can cause problems. The following commands should not be used when using the PICAXE "Timer 1" as a Real-Time Clock ...

  • INFRAIN and INFRAIN2
  • KEYIN
  • NAP
  • SERIN
  • SLEEP

A PAUSE which delays timer reading longer than the overflow period will also cause problems.

The RTC implementation also relies upon the fact that the PICAXE doesn't use "Timer 1" for its own purposes nor interfere with its operation in any way, and while that seems to be the case with the current range of PICAXE's it may not always remain so, and there is no gurantee that the PICAXE doesn't already interfere with the timer. Commands which rely on background timing ( SLEEP, NAP, PWMOUT, SERVO and those related to I2C ) plus "bit-banged" comamnds ( SERIN, SEROUT, SERTXD, SOUND, PLAY, PAUSE and so on ) appear to use either the Watchdog Timer, "Timer 2", or other timing sources rather than the timer we need to use for RTC, but that has not been confirmed by the PICAXE manufacturer.


A PICAXE-18X Real-Time Clock

The following project details a Real-Time Clock for the PICAXE-18X which sends the current date and time through its Serial Out Port for use by a PC or other serial device.

The serial could connect to another PICAXE to provide an LCD display and handle a keypad for setting the date, time and alarms, but this is beyond the scope of this article.

Hardware Circuit

        5V >---------------------------.------------------.--------.--
                                      .|.                .|.       |
                                  4K7 | |                | | 10K   |
                              22K     |_|   PICAXE-18X   |_|       |
        Run-Time              ___      |   .----..----.   |        |
           .-.   .-------.---|___|-----|---| A2    A1 |   |        |
        TX |O|---|---.---|-------------|---| SO    A0 |---{        |
        RX |O|---'   |   |     .-------|---| SI    I7 |   |        |
        0V |O|---.   |   |     |       `---| RST   I6 |   |        |
           `-'   |   |   |    .|.      .---| 0V    +V |---|--------'
                 |   |   |    | | 22K  |   | D0    D7 |   |
           .-.   |   |   |    |_|      |   | D1    D6 |   |
        SO |O|---|---'   |     |       |   | D2    D5 |   |
        SI |O|---|-------|-----{       |   | D3    D4 |   |
        0V |O|---{      .|.   .|.      |   `----------'   |
           `-'   |  10K | |   | | 10K  |                  O |_
        Download |      |_|   |_|      |                    |_| Synch
                 |       |     |       |                  O |
                 |       |     |       |                  |
        0V >-----^-------^-----^-------^------------------^-----------

                  Decoupling Capacitors not shown

Software

Because of the length of the software source code, the program is included as a separate file ...

  PICAXERT.BAS

The source code is quite large ( the largest program I've actually written for a PICAXE ) but could be condensed by using subroutines to handle the numerous number printing routines. The code provided has been written to run on the PICAXE-18X with Firmware 8.1 or earlier, which can only support 15 GOSUB commands, hence the reasoning for a lot of repeated in-line code.

Analysing the number of statements ( excluding labels, comments and blank lines ), it is interesting to compare this with the manufacturer's theoretical code estimate of 600 lines for the PICAE-18X. The source code here extrapolates out to about 450 lines of code; 75% of the predicted capacity.

The source code uses a lot of SERTXD commands which are notoriously program space hungry ( and, surprisingly, use no less program space than a SEROUT statement ) and there are a number of long LOOKUP statements which have an impact also. With SERTXD, LOOKUP and BRANCH statements removed, the extrapolated 18X capacity climbs above 500 lines.

Given the fairly complex maths in some places of the code, the 600 line estimate for source code lines in a 2048 program space seems to be in the right ballpark.

Functionality

The Real-Time Clock maintains a date and time as accurate as its oscillator will allow and delivers the date and time to a PC or other serial device through its Serial Out Line.

The Real-Time Clock handles all years between 2000 and 2255 without change and can be extended beyond then. It handles leap years and determines day of week automatically from the specified date. Automatic Daylight Saving Time is implemented for British Summer Time and for other locales. Multiple alarms are available, one for each day, and an additional 'every weekday' ( Monday to Friday ) alarm is included. Date and Time setting and Alarm programming is performed through a serial input, and a comprehensive 'date, time and alarm editor' is built-in.

Operation

The Real-Time Clock outputs a line of serial data at 4800 baud on every time increment in a long and short ( ISO 8601 style ) format, and every line will have the following format ...

    ddd, ddxx mmm yyyy hh:mm xm : yyyy-mm-dd hh:mm:ss

An active alarm is indicated by an appended "!" ( Weekday Alarm ) or "*" ( Daily Alarm ). An alarm indication is given during the entire minute at which the time matches the alarm time. A Weekday Alarm will take precedence over a Daily Alarm; if both are set at the same time, only the Weekday Alarm will be indicated.

Examples of the Real-Time Clock output is shown below ...

    Thu, 19th Aug 2004 01:30 PM : 2004-08-19 13:30:21

    Sat, 1st Jan 2005, 05:50 AM : 2005-01-01 05:50:15 *

    Wed, 23rd Feb 2005, 08:00 AM : 2005-02-23 08:00:02 !

    Sun, 30th Oct 2005, 01:59 AM : 2005-10-30 01:59:59
    Sun, 30th Oct 2005, 01:00 XM : 2005-10-30 01:00:00
    Sun, 30th Oct 2005, 02:00 AM : 2005-10-30 02:00:00

Note that the AM/PM indicator is set to "XM" during the repeated 01:00:00 to 01:59:59 period when leaving Daylight Saving Time ( BST in this case ).

Daylight Saving Time / British Summer Time

The Real-Time Clock will automatically adjust to handle Daylight Saving Time in accordance with the European Directive and UK legislation and guidelines in place, and will implement British Summer Time (BST) correctly.

At 01:00:00 on the last Sunday in March, BST will be entered and the time will automatically advance to 02:00:00, and at 02:00:00 on the last Sunday in October BST will finish and the time will automatically drop back to 01:00:00; the old, "Spring Forward, Fall Back", rule, applicable in Europe as well as America where the phrase originates, but entirely opposite to the scheme which is applicable in the Antipodes; Australia and New Zealand.

Note that the AM/PM indicator in the transmitted data is set to "XM" during the repeated 01:00:00 to 01:59:59 period when leaving Daylight Saving Time.

Daylight Saving Time as implemented is applicable to all continents, countries and regions which use it, providing that Daylight Saving Time starts and finishes on a consistently particular Sunday ( first, second, third, fourth or last ) and in the same months every year. The source code includes Daylight Saving Time definitions ( E&OE ) for Europe ( including the UK ), Australia, Tazmania, New Zealand, the USA, Canada, Mexico and Cuba. Other locales may be defined, and Daylight Saving Time can be disabled entirely.

Setting Date, Time and Alarms

More ...

    @yyyy-mm-dd hh:mm:ss Xh:Xm Mh:Mm Th:Tm Wh:Wm Hh:Hm Fh:Fm Sh:Sm Uh:Um
     YYYY
    =

The first line is the currently set date, time and alarm settings ( Weekday Alarm, then Monday through Sunday ). The second line is the edit field indicator which is positioned under the field which is selected for editing if using a display which uses fixe-width fonts. The third line is the prompt that the editor is ready to receive a command character.

Every character received is echoed back, and whenever a change is made to the date, time or alarms, or a new edit field is selected, the information is re-sent. The information will also be re-sent whenever a "?" character is issued.

The entity which is to be edited is selected by using the "<" and ">" ( or "," ) characters. The editing field indicators are as follows ...

    YYYY    Year                        2000 .. 2255
    MM      Month                       1 .. 12
    DD      Day                         1 .. 28/29/30/31
    HH      Hour                        0 .. 23
    NN      Minute                      0 .. 59
    SS      Second                      0 .. 59
    Xh      Weekday Alarm Hour          0 .. 23 or 99 ( disabled )
    Xm      Weekday Alam Minute         0 .. 59
    Mh      Monday Alarm Hour           0 .. 23 or 99 ( disabled )
    Mm      Monday Alarm Minute         0 .. 59
    Mh      Tuesday Alarm Hour          0 .. 23 or 99 ( disabled )
    Mm      Tuesday Alarm Minute        0 .. 59
    Th      Wednesday Alarm Hour        0 .. 23 or 99 ( disabled )
    Tm      Wednesday Alarm Minute      0 .. 59
    Wh      Thursday Alarm Hour         0 .. 23 or 99 ( disabled )
    Hm      Thursday Alarm Minute       0 .. 59
    Hh      Friday Alarm Hour           0 .. 23 or 99 ( disabled )
    Fm      Friday Alarm Minute         0 .. 59
    Sh      Saturday Alarm Hour         0 .. 23 or 99 ( disabled )
    Sm      Saturday Alarm Minute       0 .. 59
    Uh      Sunday Alarm Hour           0 .. 23 or 99 ( disabled )
    Um      Sunday Alarm Minute         0 .. 59

Note that the edit field indicator for minutes is "NN" while "MM" is used for the month field. There is no Day Of Week field as this is determined automatically from the date.

More ...

Elapsed Time Accuracy

The elapsed time is as accurate as the PICAXE's oscillator, which for the 18X is an internal oscillator which can be quite significantly inaccurate to its nominal frequency. Both changes in voltage and temperature will cause the on-chip oscillator to drift.

Drift caused by voltage change can be minimised by powering the PICAXE-18X from a well regulated supply using a voltage regulator which has good stabilisation and minimal ripple on its output line, but temperature is more difficult to solve.

Perhaps the easiest way to deal with temperature drift is to add or subtract a value to the overflow counter to keep the accumulated count in line with what it would be were it running at the correct speed. This could be achieved by either measuring a thermister value though an Analogue Input or by reading a Dallas DS18B20 temperature sensor and using an adjustment value which reflects the temperature read. Unfortunately such a scheme would require calibration for every PICAXE device and is beyond the scope of this article.

A far easier solution, if short-term drift can be tolerated, is to add a "Synchronise Time" button which forces the time to a particular value which can be used when an accurate time indicator is transmitted by a public broadcaster. Knowing that drift is relatively little, it would be possible to allow for a number of possible synchronisation times with the decision as to which it was based upon the current time; jumping to the nearest hour is undoubtedly the easiest to achieve and is supported in the provided code by pulling Input Pin 0 to ground.


PICAXE is a trademark of Revolution Education Ltd.





Associated Articles

  The PICAXE Processors
  PICAXE News
  PICAXE Questions & Answers
  PICAXE Comparisons
  PICAXE Pinouts
  PICAXE Serial Interfacing
  PICAXE Infra-Red Interfacing
  PICAXE Wireless Interfacing
  PICAXE LCD Interfacing
  PICAXE LCD Interfacing
  PICAXE Optimisations
  The PICAXE Birthday Box Project
  PICAXE Telephone Exchange Simulator
  The Brainf**ked PICAXE
  The PICAXE Extended Programming Interpreter
  Build Your Own Basic Stamp
  Tech Toys



Sites to Visit

  PICAXE Home Page
  Revolution Education Ltd

  Tech-Supplies Ltd



Site Navigation

  Home Page
  What's New
  Search
  Add Bookmark
  Have Your Say
  Guestbook




First published on Tuesday the 17th of August, 2004 at 15:46:53
Last upload was on Monday the 23rd of August, 2004 at 00:37:27