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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
//! *Analog Devices AD5668 DAC Driver for Rust Embedded HAL*
//!
//! This is a driver crate for embedded Rust. It's built on top of the Rust
//! [embedded HAL](https://github.com/rust-embedded/embedded-hal)
//! It supports sending commands to a AD5668 DAC over SPI.
//!
//! First you create an instance of the driver wrapping the SPI port the DAC is connected to;
//! ```
//! # use embedded_hal_mock::{spi, pin};
//! # use ad5668::*;
//! # let mut spi = spi::Mock::new(&[]);
//! # let mut chip_select = pin::Mock::new(&[pin::Transaction::set(pin::State::High)]);
//! let mut dac = AD5668::new(spi, chip_select);
//! ```
//!
//! Now commands can be sent to the DAC, for example to set all outputs high
//! ```
//! # use embedded_hal_mock::{spi, pin};
//! # use ad5668::*;
//! # let mut spi = spi::Mock::new(&[spi::Transaction::write(vec![0x02, 0xff, 0xff, 0xf0]),]);
//! # let mut chip_select = pin::Mock::new(&[
//! #     pin::Transaction::set(pin::State::High),
//! #     pin::Transaction::set(pin::State::Low),
//! #     pin::Transaction::set(pin::State::High),
//! # ]);
//! # let mut dac = AD5668::new(spi, chip_select);
//! dac.write_input_register_update_all(Address::AllDacs, 0xffff);
//! ```
//!
//! ## More information
//! - [AD5668 datasheet](https://www.analog.com/media/en/technical-documentation/data-sheets/AD5628_5648_5668.pdf)
//! - [API documentation](https://docs.rs/ad5668)
//! - [Github repository](https://github.com/mendelt/ad5668)
//! - [Crates.io](https://crates.io/crates/ad5668)

#![no_std]
#[warn(missing_debug_implementations, missing_docs)]
use embedded_hal::{blocking::spi::Write, digital::v2::OutputPin};

/// AD5668 DAC driver. Wraps an I2C port to send commands to an AD5668
pub struct AD5668<SPI, CS> {
    spi: SPI,
    chip_select: CS,
}

impl<SPI, CS, E> AD5668<SPI, CS>
where
    SPI: Write<u8, Error = E>,
    CS: OutputPin,
{
    /// Construct a new AD5668 driver
    pub fn new(spi: SPI, mut chip_select: CS) -> Self {
        // Init chip select high
        chip_select.set_high().ok();

        Self { spi, chip_select }
    }

    /// Helper function that handles writing to the SPI bus while toggeling chip select
    fn write_spi(&mut self, data: &[u8]) -> Result<(), E> {
        self.chip_select.set_low().ok();
        let result = self.spi.write(data);
        self.chip_select.set_high().ok();
        result
    }

    /// Write input register for the dac at address with the value, does not update dac register yet
    pub fn write_input_register(&mut self, address: Address, value: u16) -> Result<(), E> {
        self.write_spi(&encode_update_command(
            Command::WriteInputRegister,
            address,
            value,
        ))
    }

    /// Update dac register for the dac at address
    /// TODO: Check if the data is written too or if this just updates data written earlier to the
    ///       dac
    pub fn update_dac_register(&mut self, address: Address, value: u16) -> Result<(), E> {
        self.write_spi(&encode_update_command(
            Command::UpdateDacRegister,
            address,
            value,
        ))
    }

    /// Write to a single input register, then update all dac channels. This can be used as the last
    /// command when updating multiple DACs. First stage values for all DACs then update them
    /// simultaniously by performing the last write using this command
    pub fn write_input_register_update_all(
        &mut self,
        address: Address,
        value: u16,
    ) -> Result<(), E> {
        self.write_spi(&encode_update_command(
            Command::WriteInputUpdateAll,
            address,
            value,
        ))
    }

    /// Write to input register and then update the dac register in one command.
    pub fn write_and_update_dac_channel(&mut self, address: Address, value: u16) -> Result<(), E> {
        self.write_spi(&encode_update_command(
            Command::WriteUpdateDacChannel,
            address,
            value,
        ))
    }

    /// Enable the internal reference
    pub fn enable_internal_ref(&mut self) -> Result<(), E> {
        self.write_spi(&[
            Command::SetInternalRefRegister as u8,
            0x00u8,
            0x00u8,
            InternalRef::Enabled as u8,
        ])
    }

    /// Disable the internal reference
    pub fn disable_internal_ref(&mut self) -> Result<(), E> {
        self.write_spi(&[
            Command::SetInternalRefRegister as u8,
            0x00u8,
            0x00u8,
            InternalRef::Disabled as u8,
        ])
    }

    /// Reset the DAC
    pub fn reset(&mut self) -> Result<(), E> {
        self.write_spi(&[Command::Reset as u8, 0x00u8, 0x00u8, 0x00u8])
    }

    /// Destroy the driver and return the wrapped SPI driver to be re-used
    pub fn destroy(mut self) -> (SPI, CS) {
        // Return chip select to low state
        self.chip_select.set_low().ok();

        (self.spi, self.chip_select)
    }
}

/// Encodes one of the commands that updates a 16 bit value
fn encode_update_command(command: Command, address: Address, value: u16) -> [u8; 4] {
    [
        command as u8,
        ((address as u8) << 4) + (value >> 12) as u8,
        (value >> 4) as u8,
        (value << 4) as u8,
    ]
}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[repr(u8)]
pub enum Address {
    DacA = 0b0000,
    DacB = 0b0001,
    DacC = 0b0010,
    DacD = 0b0011,
    DacE = 0b0100,
    DacF = 0b0101,
    DacG = 0b0110,
    DacH = 0b0111,
    AllDacs = 0b1111,
}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[repr(u8)]
pub enum InternalRef {
    Disabled = 0x00u8,
    Enabled = 0x01u8,
}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[repr(u8)]
enum Command {
    WriteInputRegister = 0b0000,
    UpdateDacRegister = 0b0001,
    WriteInputUpdateAll = 0b0010,
    WriteUpdateDacChannel = 0b0011,
    PowerDACUpDown = 0b0100,
    LoadClearCodeRegister = 0b0101,
    LoadLDACRegister = 0b0110,
    Reset = 0b0111,
    SetInternalRefRegister = 0b1000,
}

#[cfg(test)]
mod test {
    use super::*;
    use embedded_hal_mock::{pin, spi};

    extern crate std;
    use std::vec;

    #[test]
    pub fn should_encode_command() {
        assert_eq!(
            encode_update_command(Command::WriteUpdateDacChannel, Address::DacA, 0u16),
            [0b00000011, 0b00000000, 0b00000000, 0b00000000],
        )
    }

    #[test]
    pub fn should_encode_address() {
        assert_eq!(
            encode_update_command(Command::WriteInputRegister, Address::AllDacs, 0u16),
            [0b00000000, 0b11110000, 0b00000000, 0b00000000],
        )
    }

    #[test]
    pub fn should_encode_value() {
        assert_eq!(
            encode_update_command(Command::WriteInputRegister, Address::DacA, 0xffffu16),
            [0b00000000, 0b00001111, 0b11111111, 0b11110000],
        )
    }

    fn setup_mocks() -> (spi::Mock, pin::Mock) {
        let spi = spi::Mock::new(&[]);

        // Default cs expectations, new sets high, sending command toggles low, then high
        let chip_select = pin::Mock::new(&[
            pin::Transaction::set(pin::State::High),
            pin::Transaction::set(pin::State::Low),
            pin::Transaction::set(pin::State::High),
        ]);

        (spi, chip_select)
    }

    #[test]
    pub fn should_init_chip_select_high() {
        let (spi, mut chip_select) = setup_mocks();

        chip_select.expect(&[
            pin::Transaction::set(pin::State::High),
            pin::Transaction::set(pin::State::Low),
        ]);

        let dac = AD5668::new(spi, chip_select);
        let (_, mut chip_select) = dac.destroy();

        chip_select.done()
    }

    #[test]
    pub fn should_enable_internal_ref() {
        let (mut spi, chip_select) = setup_mocks();

        spi.expect(&[spi::Transaction::write(vec![
            0x08u8, 0x00u8, 0x00u8, 0x01u8,
        ])]);

        let mut dac = AD5668::new(spi, chip_select);

        dac.enable_internal_ref().unwrap();
    }

    #[test]
    pub fn should_disable_internal_ref() {
        let (mut spi, chip_select) = setup_mocks();

        spi.expect(&[spi::Transaction::write(vec![
            0x08u8, 0x00u8, 0x00u8, 0x00u8,
        ])]);

        let mut dac = AD5668::new(spi, chip_select);

        dac.disable_internal_ref().unwrap();
    }

    #[test]
    pub fn should_send_reset_command() {
        let (mut spi, chip_select) = setup_mocks();

        spi.expect(&[spi::Transaction::write(vec![
            0x07u8, 0x00u8, 0x00u8, 0x00u8,
        ])]);

        let mut dac = AD5668::new(spi, chip_select);

        dac.reset().unwrap();
    }
}