Formula Student Electronics & Software
The code for the embedded software
Loading...
Searching...
No Matches
utils.hpp
Go to the documentation of this file.
1#pragma once
2#include <cstdint>
3#include <deque>
4#include <numeric>
5
6void insert_value_queue(const int value, std::deque<int>& queue) {
7 queue.push_front(value);
8
9 if (queue.size() > 5) {
10 queue.pop_back();
11 }
12}
13
14int average_queue(const std::deque<int>& queue) {
15 int avg = 0;
16 if (!queue.empty()) {
17 const double sum = std::accumulate(queue.begin(), queue.end(), 0);
18 avg = static_cast<int>(sum / queue.size());
19 }
20 return avg;
21}
22
23bool check_sequence(const uint8_t* data, const std::array<uint8_t, 3>& expected) {
24 return (data[1] == expected[0] && data[2] == expected[1] && data[3] == expected[2]);
25}
26
28 int input;
29 char output[4];
30};
31
32void rpm_2_byte(const float rr_rpm, /* const */ char* rr_rpm_byte) {
33 float2bytes data;
34 /*
35 1st we multiply rpm by 100 to get a 2 decimal place value.
36 The roundf() function rounds rpm to the nearest integer value.
37 */
38 data.input = roundf(rr_rpm * 100);
39 /*
40 The order of the bytes in the output array depends on the endianness the system.
41 -> little-endian system, the least significant byte will be at output[0],
42 and the most significant byte will be at output[3].
43 -> big-endian system, it's the other way around.
44 */
45 std::copy(std::begin(data.output), std::end(data.output), rr_rpm_byte);
46
47 return;
48}
49
58void debounce(const bool new_value, bool& stored_value, unsigned int& counter,
59 const unsigned int counter_limit) {
60 if (new_value == stored_value) {
61 counter = 0;
62 } else {
63 counter++;
64 if (counter >= counter_limit) {
65 stored_value = new_value;
66 counter = 0;
67 }
68 }
69}
70
71void debounce(const bool new_value, bool& stored_value, unsigned int& counter) {
72 debounce(new_value, stored_value, counter, CHANGE_COUNTER_LIMIT);
73}
constexpr int CHANGE_COUNTER_LIMIT
char output[4]
Definition utils.hpp:29
int input
Definition utils.hpp:28
void rpm_2_byte(const float rr_rpm, char *rr_rpm_byte)
Definition utils.hpp:32
void debounce(const bool new_value, bool &stored_value, unsigned int &counter, const unsigned int counter_limit)
debounce function to avoid sporadic changes (and repeating the code everywhere)
Definition utils.hpp:58
bool check_sequence(const uint8_t *data, const std::array< uint8_t, 3 > &expected)
Definition utils.hpp:23
void insert_value_queue(const int value, std::deque< int > &queue)
Definition utils.hpp:6
int average_queue(const std::deque< int > &queue)
Definition utils.hpp:14