Notes About Working with Various Arduino & Netduino Microcontroller Boards

Saturday, January 5, 2013

Synchronizing a DeadOn Real Time Clock to an NTP Server with a Netduino Plus 2

A few days ago I shared an example of how to read the current date and time from a Sparkfun DeadOnRTC using a Netduino Plus 2. Today's example shows how to synchronize the DeadOnRTC with a public NTP server. I have not found a solution to the seconds problem in the previous post. You can set the seconds (apparently), but the Netduino only reads zeros when getting the value from the seconds register.

The code below uses an Ntp class by JayPM (based on work by Michael Schwarz). You will need to include Jay's Ntp class in your project.  You may wish to update the address of the NTP server and offset from GMT as appropriate for your location.

As noted in the previous post, the Sparkfun DeadOnRTC module uses a DS3234 chip and connects via SPI. Here are the connections for the Netduino: 


DeadOn RTC  Netduino Plus 2
GND         GND
VCC         3V3
CLK         D13
MISO        D12
MOSI        D11
SS          D10

This example assumes that you have the Netduino Plus 2's ethernet connection up and running. 


using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;

namespace DeadOnNTP
    public class Program
        public static void Main()
            byte[] WriteBuffer = new byte[8];
            SPI.Configuration Device1 = new SPI.Configuration(
                Pins.GPIO_PIN_D10, // SS-pin
                false,             // SS-pin active state - false = low
                0,                 // setup time for SS port
                0,                 // hold time for SS port
                true,              // idle state of clock
                true,              // sampling clock edge
                2000,              // SPI clock rate in KHz
                SPI_Devices.SPI1   // SPI bus used 
            SPI SPIBus = new SPI(Device1);

            Ntp.UpdateTimeFromNtpServer("", -6);
            int month = DateTime.Now.Month;
            int date = DateTime.Now.Day;
            int year = DateTime.Now.Year - 2000;
            int hour = DateTime.Now.Hour;
            int min = DateTime.Now.Minute;
            int sec = DateTime.Now.Second;
            WriteBuffer[0] = 0x80;
            WriteBuffer[1] = decToBcd(sec);
            WriteBuffer[2] = decToBcd(min);
            WriteBuffer[3] = decToBcd(hour);
            // Day of week not used in this example
            WriteBuffer[4] = decToBcd(0);
            WriteBuffer[5] = decToBcd(date);
            WriteBuffer[6] = decToBcd(month);
            WriteBuffer[7] = decToBcd(year);

        static byte decToBcd(int val)
            return Convert.ToByte(((val / 10 * 16) + (val % 10)).ToString());

No comments:

Post a Comment