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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
//! A platform agnostic driver to interface with the HX711 (load cell amplifier and ADC)
//!
//! This driver was built using [`embedded-hal`] traits.
//!
//! [`embedded-hal`]: https://docs.rs/embedded-hal/0.2

#![deny(missing_docs)]
#![no_std]
#![cfg_attr(feature = "never_type", feature(never_type))]
#![cfg_attr(all(feature = "never_type", test), feature(unwrap_infallible))]

extern crate embedded_hal as hal;

extern crate nb;

use hal::blocking::delay::DelayUs;
use hal::digital::v2::InputPin;
use hal::digital::v2::OutputPin;

#[cfg(feature = "never_type")]
use core::convert::Infallible;

/// Maximum ADC value
pub const MAX_VALUE: i32 = (1 << 23) - 1;

/// Minimum ADC value
pub const MIN_VALUE: i32 = 1 << 23;

/// When PD_SCK pin changes from low to high and stays at high for logner than 60 us, HX711 enters power down mode. When PD_SCK returns low, the chip will reset and enter normal operation mode.
#[allow(dead_code)]
const TIME_TO_SLEEP: u32 = 70;

/// DOUT falling edge to PD_SCK rising edge (T1)
const TIME_BEFORE_READOUT: u32 = 1;

/// PD_SCK high time (T3)
const TIME_SCK_HIGH: u32 = 1;

/// PD_SCK low time (T4)
const TIME_SCK_LOW: u32 = 1;

/// HX711 driver
pub struct Hx711<D, IN, OUT> {
    delay: D,
    dout: IN,
    pd_sck: OUT,
    mode: Mode,
}

/// Error type for Input and Output errors on digital pins.
/// For some HALs, the digital input and output pins can never fail.
/// If you use the driver with such a crate, you can use `.into_ok()` on all results
/// instead of `.unwrap()` or `.expect()`.
#[derive(Debug)]
pub enum Error<EIN, EOUT> {
    /// Error while reading a digital pin
    Input(EIN),
    /// Error while writing a digital pin
    Output(EOUT),
}

/// For some hardware crates, the digital input and output pins can never fail.
/// This implementation enables the use of `.into_ok()`.
#[cfg(feature = "never_type")]
impl Into<!> for Error<!, !> {
    fn into(self) -> ! {
        panic!()
    }
}

/// For some hardware crates, the digital input and output pins can never fail.
/// This implementation enables the use of `.into_ok()`.
#[cfg(feature = "never_type")]
impl Into<!> for Error<Infallible, Infallible> {
    fn into(self) -> ! {
        panic!()
    }
}

impl<D, IN, OUT, EIN, EOUT> Hx711<D, IN, OUT>
where
    D: DelayUs<u32>,
    IN: InputPin<Error = EIN>,
    OUT: OutputPin<Error = EOUT>,
{
    /// Creates a new driver from Input and Outut pins
    pub fn new(delay: D, dout: IN, mut pd_sck: OUT) -> Result<Self, Error<EIN, EOUT>> {
        pd_sck.set_low().map_err(Error::Output)?;
        let mut hx711 = Hx711 {
            delay,
            dout,
            pd_sck,
            mode: Mode::ChAGain128,
        };
        hx711.reset()?;
        Ok(hx711)
    }

    /// Set the mode (channel and gain).
    pub fn set_mode(&mut self, mode: Mode) -> nb::Result<(), Error<EIN, EOUT>> {
        self.mode = mode;
        self.retrieve().and(Ok(()))
    }
    /// Put the chip in power down state.
    pub fn disable(&mut self) -> Result<(), Error<EIN, EOUT>> {
        self.pd_sck.set_high().map_err(Error::Output)?;
        self.delay.delay_us(TIME_TO_SLEEP);
        Ok(())
    }

    /// Wake the chip up and set mode.
    pub fn enable(&mut self) -> Result<(), Error<EIN, EOUT>> {
        self.pd_sck.set_low().map_err(Error::Output)?;
        self.delay.delay_us(TIME_SCK_LOW);
        nb::block! {self.set_mode(self.mode)}
    }

    /// Reset the chip.
    pub fn reset(&mut self) -> Result<(), Error<EIN, EOUT>> {
        self.disable()?;
        self.enable()
    }

    /// Retrieve the latest conversion value if available
    pub fn retrieve(&mut self) -> nb::Result<i32, Error<EIN, EOUT>> {
        self.pd_sck.set_low().map_err(Error::Output)?;
        if self.dout.is_high().map_err(Error::Input)? {
            // Conversion not ready yet
            return Err(nb::Error::WouldBlock);
        }
        self.delay.delay_us(TIME_BEFORE_READOUT);

        let mut count: i32 = 0;
        for _ in 0..24 {
            // Read 24 bits
            count <<= 1;
            self.pd_sck.set_high().map_err(Error::Output)?;
            self.delay.delay_us(TIME_SCK_HIGH);
            self.pd_sck.set_low().map_err(Error::Output)?;

            if self.dout.is_high().map_err(Error::Input)? {
                count += 1;
            }
            self.delay.delay_us(TIME_SCK_LOW);
        }

        // Continue to set mode for next conversion
        let n_reads = self.mode as u16;
        for _ in 0..n_reads {
            self.pd_sck.set_high().map_err(Error::Output)?;
            self.delay.delay_us(TIME_SCK_HIGH);
            self.pd_sck.set_low().map_err(Error::Output)?;
            self.delay.delay_us(TIME_SCK_LOW);
        }

        Ok(i24_to_i32(count))
    }
}

/// The HX711 can run in three modes:
#[derive(Copy, Clone)]
pub enum Mode {
    /// Chanel A with factor 128 gain
    ChAGain128 = 1,
    /// Chanel B with factor 64 gain
    ChBGain32 = 2,
    /// Chanel B with factor 32 gain
    ChBGain64 = 3,
}

/// Convert 24 bit signed integer to i32
fn i24_to_i32(x: i32) -> i32 {
    if x >= 0x800000 {
        x | !0xFFFFFF
    } else {
        x
    }
}

#[cfg(test)]
mod tests {
    use crate::*;

    #[cfg(feature = "never_type")]
    use core::convert::Infallible;

    #[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);
        assert_eq!(i24_to_i32(0xF00000), -1048576);
        assert_eq!(i24_to_i32(0x800000), -8388608);
        assert_eq!(i24_to_i32(0x7FFFFF), 8388607);
    }

    #[test]
    #[cfg(feature = "never_type")]
    fn infallible_into_ok() {
        let this_is_ok: Result<usize, Error<Infallible, Infallible>> = Ok(77);
        assert_eq!(this_is_ok.into_ok(), 77);
    }

    #[test]
    #[cfg(feature = "never_type")]
    fn never_fail_into_ok() {
        let this_is_ok: Result<usize, Error<!, !>> = Ok(77);
        assert_eq!(this_is_ok.into_ok(), 77);
    }
}