Pico Core
Loading...
Searching...
No Matches
harp_synchronizer.h
Go to the documentation of this file.
1#ifndef HARP_SYNCHRONIZER_H
2#define HARP_SYNCHRONIZER_H
3#include <stdint.h>
4#include <pico/stdlib.h>
5#include <hardware/uart.h>
6#include <hardware/irq.h>
7#include <hardware/sync.h>
8#include <hardware/structs/timer.h>
9
10#ifdef DEBUG
11#include <cstdio> // for printf
12#endif
13
14#define HARP_SYNC_BAUDRATE (100'000UL)
15#define HARP_SYNC_DATA_BITS (8)
16#define HARP_SYNC_STOP_BITS (1)
17#define HARP_SYNC_PARITY (UART_PARITY_NONE)
18
19#define HARP_SYNC_OFFSET_US (672 - 90) // time (in [us]) from the **end** of
20 // the last packet byte and the time
21 // specified in that packet.
22
23// Synchronizer that updates RP2040's timekeeping registers according to
24// specific uart input. Singleton.
25class HarpSynchronizer
26{
27public:
28 enum SyncState
29 {
30 RECEIVE_HEADER_0,
31 RECEIVE_HEADER_1,
32 RECEIVE_TIMESTAMP
33 };
34
35private:
36 // Make constructor/destructor private.
37 HarpSynchronizer(uart_inst_t* uart_id, uint8_t uart_rx_pin);
38 ~HarpSynchronizer();
39public:
40 // Disable default constructor, copy constructor, and assignment operator.
41 HarpSynchronizer() = delete;
42 HarpSynchronizer(HarpSynchronizer& other) = delete;
43 void operator=(const HarpSynchronizer& other) = delete;
44
48 static HarpSynchronizer& init(uart_inst_t* uart, uint8_t uart_rx_pin);
49
54 static HarpSynchronizer& instance(){return *self;}
55
64 static inline uint64_t system_to_harp_us_64(uint64_t system_time_us)
65 {return system_time_us - self->offset_us_64_;}
66
73 static inline void set_harp_time_us_64(uint64_t harp_time_us)
74 {self->offset_us_64_ = ::time_us_64() - harp_time_us;}
75
83 static inline uint64_t time_us_64()
84 {return system_to_harp_us_64(::time_us_64());}
85
91 static inline uint32_t time_us_32()
92 {return uint32_t(time_us_64());} // FIXME: this should execute faster
93 // but truncating for speed involves
94 // checking a bunch of edge cases.
95
103 static inline uint64_t harp_to_system_us_64(uint64_t harp_time_us)
104 {return harp_time_us + self->offset_us_64_;}
105
113 static inline uint32_t harp_to_system_us_32(uint64_t harp_time_us)
114 {return uint32_t(harp_to_system_us_64(harp_time_us));}
115
120 static inline bool is_synced()
121 {return self->has_synced_;}
122
123private:
128 static inline HarpSynchronizer* self = nullptr;
129
135 static void uart_rx_callback();
136
137 uart_inst_t* uart_id_;
138
139 // members edited within an ISR must be volatile.
140 volatile SyncState state_;
141 volatile uint8_t packet_index_;
142 volatile bool new_timestamp_;
143
144 volatile uint64_t offset_us_64_;
145
146 volatile bool has_synced_;
151 alignas(uint32_t) volatile uint8_t sync_data_[4];
152
158 friend class HarpCore;
159};
160
161#endif // HARP_SYNCHRONIZER_H
Harp Core that handles management of common bank registers. Implemented as a singleton to simplify at...
Definition harp_core.h:48