Created
August 17, 2019 14:12
-
-
Save gregorycollins/87dc660c095243dade9e62da175a4bcf to your computer and use it in GitHub Desktop.
Arduino frequency counter ring buffer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// we expect a timeslice to be 1024 micros | |
static constexpr uint32_t TIMESLICE_LEN_US = 1024; | |
struct ringbuf_counter { | |
// must be power of 2 | |
static constexpr int NDATA = 512; | |
uint16_t data[NDATA]; | |
int start = 0; | |
int idx = 0; | |
int n = 0; | |
uint32_t running_sum = 0; | |
void record_count(uint16_t x) { | |
if (n >= NDATA) running_sum -= data[idx]; | |
running_sum += x; | |
data[idx] = x; | |
idx = (idx + 1) & (NDATA - 1); | |
if (n < NDATA) ++n; | |
} | |
uint32_t get_sum() { | |
return running_sum; | |
} | |
uint32_t estimate_frequency() { | |
if (n == 0) return 0; | |
uint64_t sum = get_sum() * 1000000; | |
uint64_t interval_us = TIMESLICE_LEN_US * n; | |
uint64_t fudge = 1 + TIMESLICE_LEN_US / 2; // round the result | |
return (sum + fudge) / interval_us; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment