1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
use crate::{
mutex::MainCtx,
system::SysPeriph,
timer::{timer_get_large, LargeTimestamp, RelLargeTimestamp},
};
const HALFWAVE_DUR: RelLargeTimestamp = RelLargeTimestamp::from_millis(10);
#[derive(Clone)]
pub enum Phase {
Notsync,
PosHalfwave(LargeTimestamp),
NegHalfwave(LargeTimestamp),
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum PhaseUpdate {
NotChanged,
Changed,
}
pub struct Mains {
prev_vsense: bool,
phase: Phase,
}
impl Mains {
pub const fn new() -> Self {
Self {
prev_vsense: false,
phase: Phase::Notsync,
}
}
fn read_vsense(&self, _m: &MainCtx<'_>, sp: &SysPeriph) -> bool {
sp.PORTA.pina.read().pa1().bit()
}
pub fn run(&mut self, m: &MainCtx<'_>, sp: &SysPeriph) -> PhaseUpdate {
let vsense = self.read_vsense(m, sp);
let now = timer_get_large(m);
let mut ret = PhaseUpdate::NotChanged;
match self.phase {
Phase::Notsync | Phase::NegHalfwave(_) => {
if !self.prev_vsense && vsense {
self.phase = Phase::PosHalfwave(now);
ret = PhaseUpdate::Changed;
}
}
Phase::PosHalfwave(refstamp) => {
let nextref = refstamp + HALFWAVE_DUR;
if now >= nextref {
self.phase = Phase::NegHalfwave(nextref);
ret = PhaseUpdate::Changed;
}
}
}
self.prev_vsense = vsense;
ret
}
pub fn get_phase(&self) -> Phase {
self.phase.clone()
}
}
// vim: ts=4 sw=4 expandtab
|