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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#![deny(missing_docs)]
#![deny(warnings)]
#![no_std]
#![feature(never_type)]
extern crate embedded_hal as hal;
#[macro_use(block)]
extern crate nb;
use hal::digital::InputPin;
use hal::digital::OutputPin;
pub const MAX_VALUE: i32 = (1 << 23) - 1;
pub const MIN_VALUE: i32 = (1 << 23);
pub struct Hx711<IN, OUT> {
dout: IN,
pd_sck: OUT,
mode: Mode,
}
impl<IN, OUT> Hx711<IN, OUT>
where
IN: InputPin,
OUT: OutputPin,
{
pub fn new(dout: IN, mut pd_sck: OUT) -> Self {
pd_sck.set_low();
let mut hx711 = Hx711 {
dout,
pd_sck,
mode: Mode::ChAGain128,
};
hx711.reset();
hx711
}
pub fn set_mode(&mut self, mode: Mode) {
self.mode = mode;
block!(self.retrieve()).unwrap();
}
pub fn reset(&mut self) {
self.pd_sck.set_high();
for _ in 1..3 {
self.dout.is_high();
}
self.pd_sck.set_low();
}
pub fn retrieve(&mut self) -> nb::Result<i32, !> {
self.pd_sck.set_low();
if self.dout.is_high() {
return Err(nb::Error::WouldBlock);
}
let mut count: i32 = 0;
for _ in 0..24 {
count <<= 1;
self.pd_sck.set_high();
self.pd_sck.set_low();
if self.dout.is_high() {
count += 1;
}
}
let n_reads = self.mode as u16;
for _ in 0..n_reads {
self.pd_sck.set_high();
self.pd_sck.set_low();
}
Ok(i24_to_i32(count))
}
}
#[derive(Copy, Clone)]
pub enum Mode {
ChAGain128 = 1,
ChBGain32 = 2,
ChBGain64 = 3,
}
fn i24_to_i32(x: i32) -> i32 {
if x >= 0x800000 {
x | !0xFFFFFF
} else {
x
}
}
#[cfg(test)]
mod tests {
use crate::*;
#[test]
fn convert() {
assert_eq!(i24_to_i32(0x000001), 1);
assert_eq!(i24_to_i32(0x000002), 2);
assert_eq!(i24_to_i32(0xFFFFFF), -1);
assert_eq!(i24_to_i32(0xFFFFF3), -13);
}
}