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> |
James Kuszmaul | 998d303 | 2018-09-08 15:41:41 -0700 | [diff] [blame] | 5 | #include <array> |
Brian Silverman | 8d3816a | 2017-07-03 18:52:15 -0700 | [diff] [blame] | 6 | |
| 7 | namespace frc971 { |
Brian Silverman | a96c1a4 | 2018-05-12 12:11:31 -0700 | [diff] [blame] | 8 | namespace motors { |
Brian Silverman | 8d3816a | 2017-07-03 18:52:15 -0700 | [diff] [blame] | 9 | |
| 10 | struct 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 | |
| 21 | struct 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. |
| 28 | BalancedReadings BalanceReadings(ReadingsToBalance to_balance); |
| 29 | |
James Kuszmaul | 998d303 | 2018-09-08 15:41:41 -0700 | [diff] [blame] | 30 | inline 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 Silverman | 6260c09 | 2018-01-14 15:21:36 -0800 | [diff] [blame] | 46 | inline 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 Silverman | a96c1a4 | 2018-05-12 12:11:31 -0700 | [diff] [blame] | 59 | } // namespace motors |
Brian Silverman | 8d3816a | 2017-07-03 18:52:15 -0700 | [diff] [blame] | 60 | } // namespace frc971 |
| 61 | |
| 62 | #endif // MOTORS_ALGORITHMS_H_ |