Adam Snaider | c4b3c19 | 2015-02-01 01:30:39 +0000 | [diff] [blame^] | 1 | #include "frc971/zeroing/zeroing.h" |
| 2 | #include <math.h> |
| 3 | #include <vector> |
| 4 | |
| 5 | namespace frc971 { |
| 6 | namespace zeroing { |
| 7 | |
| 8 | ZeroingEstimator::ZeroingEstimator(double index_difference, |
| 9 | size_t max_sample_count) { |
| 10 | index_diff_ = index_difference; |
| 11 | samples_idx_ = 0; |
| 12 | max_sample_count_ = max_sample_count; |
| 13 | start_pos_samples_.reserve(max_sample_count); |
| 14 | } |
| 15 | |
| 16 | void ZeroingEstimator::UpdateEstimate(const ZeroingInfo & info) { |
| 17 | if (start_pos_samples_.size() < max_sample_count_) { |
| 18 | start_pos_samples_.push_back(info.pot - info.encoder); |
| 19 | } else { |
| 20 | start_pos_samples_[samples_idx_] = info.pot - info.encoder; |
| 21 | } |
| 22 | samples_idx_ = (samples_idx_ + 1) % max_sample_count_; |
| 23 | |
| 24 | double start_average = 0.0; |
| 25 | for (size_t i = 0; i < start_pos_samples_.size(); ++i) { |
| 26 | start_average += start_pos_samples_[i]; |
| 27 | } |
| 28 | |
| 29 | // Calculates the average of the starting position. |
| 30 | start_average = start_average / start_pos_samples_.size(); |
| 31 | /* If the index_encoder is invalid, then we use |
| 32 | * the average of the starting position to |
| 33 | * calculate the position. |
| 34 | */ |
| 35 | if (info.index_count == 0) { |
| 36 | pos_ = start_average + info.encoder; |
| 37 | } else { |
| 38 | // We calculate an aproximation of the value of the last index position. |
| 39 | double index_pos = start_average + info.index_encoder; |
| 40 | // We round index_pos to the closest valid value of the index. |
| 41 | double accurate_index_pos = (round(index_pos / index_diff_)) * index_diff_; |
| 42 | // We use accurate_index_pos to calculate the position. |
| 43 | pos_ = accurate_index_pos + info.encoder - info.index_encoder; |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | double ZeroingEstimator::getPosition() { return pos_; } |
| 48 | |
| 49 | } // namespace zeroing |
| 50 | } // namespace frc971 |