blob: 4cf44403f984701e39c500c20fcb7138b1d15562 [file] [log] [blame]
Brian Silvermanff7b3472015-01-26 17:53:04 -05001#include "frc971/wpilib/dma_edge_counting.h"
2
3#include "aos/common/logging/logging.h"
4
5namespace frc971 {
6namespace wpilib {
7
Brian Silverman552350b2015-08-02 18:23:34 -07008bool DMAEdgeCounter::ExtractValue(const DMASample &sample) const {
Brian Silverman03a00cf2015-08-29 19:26:54 -07009 return sample.Get(input_);
Brian Silvermanff7b3472015-01-26 17:53:04 -050010}
11
12void DMAEdgeCounter::UpdateFromSample(const DMASample &sample) {
Brian Silverman03a00cf2015-08-29 19:26:54 -070013 const bool previous_value =
Austin Schuhf83da152017-03-05 22:28:45 -080014 have_prev_sample_ ? ExtractValue(prev_sample_) : previous_polled_value_;
Brian Silverman03a00cf2015-08-29 19:26:54 -070015 have_prev_sample_ = true;
Brian Silvermanff7b3472015-01-26 17:53:04 -050016 prev_sample_ = sample;
Brian Silverman03a00cf2015-08-29 19:26:54 -070017
18 if (!previous_value && ExtractValue(sample)) {
19 pos_edge_count_++;
Brian Silverman03a00cf2015-08-29 19:26:54 -070020 pos_last_encoder_ = sample.GetRaw(encoder_);
21 } else if (previous_value && !ExtractValue(sample)) {
22 neg_edge_count_++;
Brian Silverman03a00cf2015-08-29 19:26:54 -070023 neg_last_encoder_ = sample.GetRaw(encoder_);
24 }
Brian Silvermanff7b3472015-01-26 17:53:04 -050025}
26
27void DMASynchronizer::CheckDMA() {
28 DMASample current_sample;
29
30 size_t remaining = 0;
31 while (true) {
32 switch (dma_->Read(&current_sample, 0, &remaining)) {
33 case DMA::STATUS_OK:
34 for (auto &c : handlers_) {
35 c->UpdateFromSample(current_sample);
36 }
37
38 if (remaining == 0) {
Austin Schuhf853bde2017-11-23 13:23:27 -080039 if (sample_time_ < static_cast<int64_t>(current_sample.GetTime())) {
Brian Silvermanff7b3472015-01-26 17:53:04 -050040 // If the latest DMA sample happened after we started polling, then
41 // just use the values from it because they're more recent.
42 for (auto &c : handlers_) {
43 c->PollFromSample(current_sample);
44 }
45 }
46 return;
47 }
48 case DMA::STATUS_TIMEOUT:
49 return;
50 case DMA::STATUS_ERROR:
51 LOG(WARNING, "DMA read failed\n");
52 break;
53 }
54 }
55}
56
57} // namespace wpilib
58} // namespace frc971