blob: 20dcbe89c162272df59e19ba7b1b2aecd67789f5 [file] [log] [blame]
Brian Silverman8d3816a2017-07-03 18:52:15 -07001#ifndef MOTORS_ALGORITHMS_H_
2#define MOTORS_ALGORITHMS_H_
3
4#include <stdint.h>
Philipp Schrader790cb542023-07-05 21:06:52 -07005
James Kuszmaul998d3032018-09-08 15:41:41 -07006#include <array>
Brian Silverman8d3816a2017-07-03 18:52:15 -07007
8namespace frc971 {
Brian Silvermana96c1a42018-05-12 12:11:31 -07009namespace motors {
Brian Silverman8d3816a2017-07-03 18:52:15 -070010
11struct ReadingsToBalance {
12 // Adds a single reading at index.
13 void Add(int index, int32_t value) {
14 sums[index] += value;
15 ++weights[index];
16 }
17
18 int32_t sums[3];
19 int weights[3];
20};
21
22struct BalancedReadings {
23 float readings[3];
24};
25
26// Returns three readings which add up to 0 and are the same distances apart as
27// the input ones (by weight). The distances between the averages of the inputs
28// and the corresponding outputs will be inversely proportional to the weights.
29BalancedReadings BalanceReadings(ReadingsToBalance to_balance);
30
James Kuszmaul998d3032018-09-08 15:41:41 -070031inline BalancedReadings BalanceSimpleReadings(
32 const ::std::array<float, 3> readings) {
33 float offset = 0;
34 for (int i = 0; i < 3; ++i) {
35 offset += readings[i];
36 }
37
38 offset = offset / 3.0f;
39
40 BalancedReadings r;
41 for (int i = 0; i < 3; ++i) {
42 r.readings[i] = static_cast<float>(readings[i]) - offset;
43 }
44 return r;
45}
46
Brian Silverman6260c092018-01-14 15:21:36 -080047inline BalancedReadings BalanceSimpleReadings(const uint16_t readings[3]) {
48 float offset = 0;
49 for (int i = 0; i < 3; ++i) {
50 offset += static_cast<float>(readings[i]);
51 }
52
53 BalancedReadings r;
54 for (int i = 0; i < 3; ++i) {
55 r.readings[i] = static_cast<float>(readings[i]) + offset / -3;
56 }
57 return r;
58}
59
Brian Silvermana96c1a42018-05-12 12:11:31 -070060} // namespace motors
Brian Silverman8d3816a2017-07-03 18:52:15 -070061} // namespace frc971
62
63#endif // MOTORS_ALGORITHMS_H_