Monday, March 19, 2012

It’s About Time

I happened to check the time on the WebCell the other day and noticed it was running about 4 minutes fast. Currently the WebCell clock only sets itself (using a network time server) when it powers on, so that error would have accumulated over the few months since the last winter power outage. I guess it’s time to change that.

Timekeeping on the WebCell originates with a 25 MHz crystal on the Ethernet chip. The Ethernet chip divides it by 4 to 6.25 MHz before sending it over to the AVR microcontroller.  The AVR multiplies it by 5 to 31.25 MHz, very close to its max clock speed of 32 MHz. A counter in the AVR divides this by 62,500 resulting in 500 Hz, which is then used for all internal timekeeping.

The crystal is supposed to be accurate to 50 parts per million, which can also viewed as one part per 20,000. Since there are 60 * 60 * 24 = 86,400 seconds per day, the crystal could have a max error of 86,400 / 20,000 = 4.32 seconds per day. Even resetting the time every day, that’s a little more error than I’d like to see.

The number 2^16 = 65536 is a bit special in programming, and I chose it as the interval in seconds between resetting the clock. This works out to about 18 hours. Not only that, but if the clock is off by one second or more when it gets reset, the counter that puts out the 500 Hz gets its divisor adjusted by one tick. So if the clock was running fast, the counter will be adjusted to divide by 62,501. If the clock continues to show an error at subsequent resets, the divisor will continue to be adjusted, one tick at a time. Given the accuracy of the crystal, this adjustment shouldn’t get larger than 3 or 4 ticks off the nominal 62,500, and I’ve set a limit of 20. This adjustment is maintained in the (non-volatile) EEPROM so it won’t be lost on power failure.

With that done, I decided to tackle another time issue that’s been bugging me. When I copy new web pages to the WebCell, the date/time stamp on the file is not copied with it. Instead, the new files are stamped with the current time. This can get pretty confusing when you look back and have to realize that a file time stamp on the WebCell that is after the file time stamp on the PC probably means they’re the same file.

Fixing this required hitting work items at several different levels. First, my implementation of the FAT file system did not yet support setting a file time stamp to an arbitrary date/time. Next, because these files are transferred using FTP, I had to implement the FTP extension MFMT, which sets the time stamp on a file. Finally, I had to have the FTP client in the CellScript simulator use that FTP extension when it copied files.

Fixing these time issues resolved all my immediate concerns for the WebCell itself, giving me some sense of completion.

No comments:

Post a Comment