5 * Devices 1 and 2 synchronize clocks using serial messages.
\r
7 * 1. Each serial message timestamped using the hardware timer capture
\r
8 * registers in both the sender and receiver.
\r
9 * 2. The sender transmits the send timestamp during the next time-sync
\r
11 * 3. The receiver then compares the senders timestamp with it's own
\r
12 * timestamp for the corresponding messages and calculates an offset.
\r
13 * 4. The offset is used to compensate the receivers local clock.
\r
15 * Time synchronization is performed in both directions.
\r
18 /***********************
\r
19 * Message Definitions *
\r
20 ***********************/
\r
22 #define MSG_HEADER 0x1234
\r
25 MSG_ID_SYNC, // Time synchronization
\r
26 MSG_ID_EVENT, // Event occurred
\r
30 uint32_t seconds; // Seconds since 1970 (without leap seconds)
\r
31 uint32_t nanosec; // Nanoseconds since 'seconds'
\r
35 uint16_t header; // Message Header
\r
36 uint16_t mesgid; // Message ID
\r
37 uint16_t length; // Body length
\r
38 uint16_t cksum; // Body checksum
\r
42 uint16_t seq; // Current sequence counter
\r
43 uint16_t prev; // Sequence of previous message
\r
44 ntime_t time; // Time of previous message
\r
48 uint16_t device; // Device ID
\r
49 uint16_t event; // Event ID
\r
50 ntime_t time; // Timestamp
\r
53 /*******************
\r
55 *******************/
\r
58 * Generate time stamp for an async event:
\r
59 * time: drift compensated wall-clock time
\r
60 * stamp: event timestamp from Timer/PWM Module
\r
62 void time_stamp(ntime_t *time, uint32_t stamp)
\r
68 * Compensate the Real-Time-Clock oscillator for
\r
69 * temperature and drift errors. Called at 1Hz and
\r
70 * synchronous to the RTC 1Hz output.
\r
72 void time_rtc_comp(void)
\r
78 * Synchronize the timer internal state with updates
\r
79 * from an external time sync message.
\r
80 * ours: our internal timestamp for the event
\r
81 * ref: reference timestamp from the other device
\r
83 void time_ext_sync(ntime_t *ours, ntime_t *ref)
\r
88 /************************
\r
89 * Serial I/O functions *
\r
90 ************************/
\r
93 * Output time sync message
\r
95 void serial_send_sync(void)
\r
100 * Output external event received message
\r
101 * event: id of the received event
\r
102 * time: compensated timestamp of the event
\r
104 void serial_send_event(uint16_t event, ntime_t *time)
\r
109 * Process serial receive messages
\r
111 void serial_receive(void)
\r
115 /********************
\r
116 * Data definitions *
\r
117 ********************/
\r
119 DigitalOut led1(LED1);
\r
120 DigitalOut led2(LED2);
\r
126 int main(int argc, char **argv)
\r
129 led1 = 1; led2 = 0; wait(0.1);
\r
130 led1 = 0; led2 = 1; wait(0.1);
\r