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