Brian Silverman | 8d3816a | 2017-07-03 18:52:15 -0700 | [diff] [blame] | 1 | #ifndef MOTORS_ALGORITHMS_H_ |
| 2 | #define MOTORS_ALGORITHMS_H_ |
| 3 | |
| 4 | #include <stdint.h> |
Philipp Schrader | 790cb54 | 2023-07-05 21:06:52 -0700 | [diff] [blame^] | 5 | |
James Kuszmaul | 998d303 | 2018-09-08 15:41:41 -0700 | [diff] [blame] | 6 | #include <array> |
Brian Silverman | 8d3816a | 2017-07-03 18:52:15 -0700 | [diff] [blame] | 7 | |
| 8 | namespace frc971 { |
Brian Silverman | a96c1a4 | 2018-05-12 12:11:31 -0700 | [diff] [blame] | 9 | namespace motors { |
Brian Silverman | 8d3816a | 2017-07-03 18:52:15 -0700 | [diff] [blame] | 10 | |
| 11 | struct 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 | |
| 22 | struct 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. |
| 29 | BalancedReadings BalanceReadings(ReadingsToBalance to_balance); |
| 30 | |
James Kuszmaul | 998d303 | 2018-09-08 15:41:41 -0700 | [diff] [blame] | 31 | inline 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 Silverman | 6260c09 | 2018-01-14 15:21:36 -0800 | [diff] [blame] | 47 | inline 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 Silverman | a96c1a4 | 2018-05-12 12:11:31 -0700 | [diff] [blame] | 60 | } // namespace motors |
Brian Silverman | 8d3816a | 2017-07-03 18:52:15 -0700 | [diff] [blame] | 61 | } // namespace frc971 |
| 62 | |
| 63 | #endif // MOTORS_ALGORITHMS_H_ |