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
6
7void insert_value_queue(const int value, std::deque<int>& queue, const unsigned int max_queue_size) {
8 queue.push_front(value);
9
10 if (queue.size() > max_queue_size) {
11 queue.pop_back();
12 }
13}
14void insert_value_queue(const int value, std::deque<int>& queue) {
15 insert_value_queue(value, queue, 5);
16}
17
18
19
20int average_queue(const std::deque<int>& queue) {
21 int avg = 0;
22 if (!queue.empty()) {
23 const double sum = std::accumulate(queue.begin(), queue.end(), 0);
24 avg = static_cast<int>(sum / queue.size());
25 }
26 return avg;
27}
28
29bool check_sequence(const uint8_t* data, const std::array<uint8_t, 3>& expected) {
30 return (data[1] == expected[0] && data[2] == expected[1] && data[3] == expected[2]);
31}
32
34 int input;
35 char output[4];
36};
37
38void rpm_2_byte(const float rr_rpm, /* const */ char* rr_rpm_byte) {
39 float2bytes data;
40 /*
41 1st we multiply rpm by 100 to get a 2 decimal place value.
42 The roundf() function rounds rpm to the nearest integer value.
43 */
44 data.input = roundf(rr_rpm * 100);
45 /*
46 The order of the bytes in the output array depends on the endianness the system.
47 -> little-endian system, the least significant byte will be at output[0],
48 and the most significant byte will be at output[3].
49 -> big-endian system, it's the other way around.
50 */
51 std::copy(std::begin(data.output), std::end(data.output), rr_rpm_byte);
52
53 return;
54}
55
64void debounce(const bool new_value, bool& stored_value, unsigned int& counter,
65 const unsigned int counter_limit) {
66 if (new_value == stored_value) {
67 counter = 0;
68 } else {
69 counter++;
70 if (counter >= counter_limit) {
71 stored_value = new_value;
72 counter = 0;
73 }
74 }
75}
76
77void debounce(const bool new_value, bool& stored_value, unsigned int& counter) {
78 debounce(new_value, stored_value, counter, 50);
79}
char output[4]
Definition utils.hpp:35
int input
Definition utils.hpp:34
void rpm_2_byte(const float rr_rpm, char *rr_rpm_byte)
Definition utils.hpp:38
void insert_value_queue(const int value, std::deque< int > &queue, const unsigned int max_queue_size)
Definition utils.hpp:7
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:64
bool check_sequence(const uint8_t *data, const std::array< uint8_t, 3 > &expected)
Definition utils.hpp:29
int average_queue(const std::deque< int > &queue)
Definition utils.hpp:20