-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fixes tonarino/portal#2666
- Loading branch information
Showing
4 changed files
with
38 additions
and
3 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,26 +1,51 @@ | ||
use hal::{prelude::*, qei::Qei, stm32::TIM1}; | ||
use hal::{ | ||
prelude::*, | ||
qei::Qei, | ||
stm32::TIM1, | ||
timer::{Instant, MonoTimer}, | ||
}; | ||
use stm32f4xx_hal as hal; | ||
|
||
const DETENT_RESET_TIMOUT_MS: u32 = 200; | ||
|
||
pub struct Counter<PINS> { | ||
qei: Qei<TIM1, PINS>, | ||
last_count: u16, | ||
timer: MonoTimer, | ||
last_update: Instant, | ||
} | ||
|
||
impl<PINS> Counter<PINS> { | ||
pub fn new(qei: Qei<TIM1, PINS>) -> Self { | ||
pub fn new(qei: Qei<TIM1, PINS>, timer: MonoTimer) -> Self { | ||
let last_count = qei.count(); | ||
Counter { qei, last_count } | ||
Counter { qei, last_count, last_update: timer.now(), timer } | ||
} | ||
|
||
pub fn poll(&mut self) -> Option<i8> { | ||
let count = self.qei.count(); | ||
let diff = count.wrapping_sub(self.last_count) as i16; | ||
|
||
// Sometimes it happens that last_count gets out of sync with the physical detents. | ||
// We require count to increment by 4 to fire a single tick but when last_count lands in between | ||
// detents we get backlash or missed ticks. | ||
// Assume that when the dial rests for more than DETENT_RESET_TIMOUT_MS it is aligned to a detent | ||
// and reset last_count to current position. | ||
if self.last_update.elapsed() > self.timer.frequency().0 * (DETENT_RESET_TIMOUT_MS / 1000) { | ||
self.last_count = count; | ||
} | ||
|
||
if diff != 0 { | ||
self.last_update = self.timer.now(); | ||
} | ||
if diff.abs() >= 4 { | ||
self.last_count = count; | ||
Some((diff / 4) as i8) | ||
} else { | ||
None | ||
} | ||
} | ||
|
||
pub fn current_count(&self) -> u16 { | ||
self.qei.count() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters