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
//! *Microchip MCP4725 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 MCP4725 DAC over I2C.
//! To get started you can look at a short
//! [example](https://github.com/mendelt/bluepill-examples/blob/master/examples/01-bluepill_saw.rs)
//! on how to use this driver on an inexpensive blue pill STM32F103 board.
//!
//! The driver can be initialized by calling create and passing it an I2C interface.
//! ```rust, ignore
//! let mut dac = MCP4725::create(i2c);
//! ```
//!
//! A command can then be created and initialized with the device address and some data, and sent
//! the DAC.
//! ```rust, ignore
//! let mut dac_cmd = Command::default().address(0b111).data(14);
//! dac.send(dac_cmd);
//! ```
//!
//! New data can be sent using the existing command by just changing the data and re-sending.
//! ```rust, ignore
//! dac_cmd = dac_cmd.data(348);
//! dac.send(dac_cmd);
//! ```
//!
//! ## More information
//! - [MCP4725 datasheet](http://ww1.microchip.com/downloads/en/DeviceDoc/22039d.pdf)
//! - [API documentation] (https://docs.rs/mcp4725/)
//! - [Github repository](https://github.com/mendelt/mcp4725)
//! - [Crates.io](https://crates.io/crates/mcp4725)
//!

#![no_std]
#[warn(missing_debug_implementations, missing_docs)]
use embedded_hal::blocking::i2c::Write;

/// MCP4725 DAC driver. Wraps an I2C port and uses it to communicate to send commands to an MCP4725
pub struct MCP4725<I2C>
where
    I2C: Write,
{
    i2c: I2C,
}

impl<I2C> MCP4725<I2C>
where
    I2C: Write,
{
    pub fn create(i2c: I2C) -> Self {
        MCP4725 { i2c }
    }

    /// Send a command to the MCP4725
    pub fn send(&mut self, command: &Command) {
        self.i2c.write(command.address_byte, &command.bytes());
    }

    /// Send a fast command
    pub fn send_fast(&mut self, command: &FastCommand) {
        self.i2c.write(command.address_byte, &command.bytes());
    }
}

const DEVICE_ID: u8 = 0b1100;

/// Two bit flags indicating the power mode for the MCP4725
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[repr(u8)]
pub enum PowerMode {
    Normal = 0b00,
    Resistor1kOhm = 0b01,
    Resistor100kOhm = 0b10,
    Resistor500kOhm = 0b11,
}

/// The type of the command to send for a Command
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[repr(u8)]
pub enum CommandType {
    WriteDac = 0x40,
    WriteDacAndEEPROM = 0x60,
}

/// A Command to send to the MCP4725, using default() a default instance of this Command can be
/// created. Using the address(), command_type(), power_mode() and data() builder methods the
/// parameters for this command can be set. Commands can be sent using the send method on the
/// MCP4725 driver.
/// A command can (and should) be re-used. data() can be used to re-set the data while keeping other
/// parameters the same.
#[derive(Debug, Eq, PartialEq)]
pub struct Command {
    address_byte: u8,
    command_byte: u8,
    data_byte_0: u8,
    data_byte_1: u8,
}

impl Default for Command {
    /// Instantiate a command with sane defaults.
    fn default() -> Self {
        Self {
            address_byte: DEVICE_ID << 3,
            command_byte: CommandType::WriteDac as u8,
            data_byte_0: 0,
            data_byte_1: 0,
        }
    }
}

impl Command {
    /// Format data bytes to send to the DAC. At the moment only sending one sample at a time is
    /// supported.
    pub fn bytes(&self) -> [u8; 3] {
        [self.command_byte, self.data_byte_0, self.data_byte_1]
    }

    /// Set the data to send with this command. This data will be truncated to a 12 bit int
    pub fn data(mut self, data: u16) -> Self {
        self.data_byte_0 = (data >> 4) as u8;
        self.data_byte_1 = (data & 0x000f << 4) as u8;

        self
    }

    /// Set the 3 bit address
    /// TODO document where this address can be found for your chip.
    pub fn address(mut self, address: u8) -> Self {
        self.address_byte = (DEVICE_ID << 3) + (address & 0b00000111);
        self
    }

    /// Write the supplied values to the EEPROM as well as to the DAC
    pub fn command_type(mut self, command: CommandType) -> Self {
        self.command_byte = (self.command_byte & 0b00011111) | command as u8;
        self
    }

    /// Set the power mode
    pub fn power_mode(mut self, mode: PowerMode) -> Self {
        self.command_byte = (self.command_byte & 0b11111000) | ((mode as u8) << 1);
        self
    }
}

#[cfg(test)]
mod test_command {
    use super::*;

    #[test]
    fn should_encode_address_with_device_id() {
        let cmd = Command::default().address(0b111);

        assert_eq!(cmd.address_byte, 0b01100111);
    }

    #[test]
    fn should_ignore_adresses_with_more_than_3_bits() {
        let cmd = Command::default().address(0b11111010);

        assert_eq!(cmd.address_byte, 0b01100010);
    }

    #[test]
    fn should_encode_data_into_data_bytes() {
        let cmd = Command::default().data(0x0fff);

        assert_eq!(cmd.bytes(), [0b01000000, 0b11111111, 0b11110000])
    }

    #[test]
    fn should_encode_power_mode_into_data_bytes() {
        let cmd = Command::default().power_mode(PowerMode::Resistor1kOhm);

        assert_eq!(cmd.bytes(), [0b01000010, 0, 0])
    }

    #[test]
    fn should_encode_command_into_data_bytes() {
        let cmd = Command::default().command_type(CommandType::WriteDacAndEEPROM);

        assert_eq!(cmd.bytes(), [0b01100000, 0, 0])
    }
}

/// A FastCommand to send to the MCP4725, using default() a default instance of the FastCommand can
/// be created. Fast commands are special stripped down commands that can be used to send data to
/// an MCP4725 in only 2 bytes instead of 3. It can only be used to set the DAC register, not to
/// write the EEPROM that stores the default values.
/// As with the normal Command the address(), power_mode() and data() builder methods can be used to
/// set parameters. FastCommands can be sent using the send_fast method on the MCP4725 driver.
/// A FastCommand can (and should) be re-used. data() can be used to re-set the data while keeping
/// other parameters the same.
pub struct FastCommand {
    address_byte: u8,
    data_byte_0: u8,
    data_byte_1: u8,

    powermode: u8,
}

impl Default for FastCommand {
    fn default() -> Self {
        FastCommand {
            address_byte: DEVICE_ID << 3,
            powermode: 0,
            data_byte_0: 0,
            data_byte_1: 0,
        }
    }
}

impl FastCommand {
    pub fn bytes(&self) -> [u8; 2] {
        [self.data_byte_0, self.data_byte_1]
    }

    /// Set the 3 bit address
    /// TODO document where this address can be found for your chip.
    pub fn address(mut self, address: u8) -> Self {
        self.address_byte = (DEVICE_ID << 3) + (address & 0b00000111);
        self
    }

    /// Set the data to send with this command. This data will be truncated to a 12 bit int
    pub fn data(mut self, data: u16) -> Self {
        self.data_byte_0 = ((data >> 8) as u8) | self.powermode;
        self.data_byte_1 = data as u8;

        self
    }

    /// Set the power mode
    pub fn power_mode(mut self, mode: PowerMode) -> Self {
        self.powermode = (mode as u8) << 4;
        self.data_byte_0 = (self.data_byte_0 & 0x0f) | self.powermode;

        self
    }
}

#[cfg(test)]
mod test_fast_command {
    use super::*;

    #[test]
    fn should_encode_address_with_device_id() {
        let cmd = FastCommand::default().address(0b111);

        assert_eq!(cmd.address_byte, 0b01100111);
    }

    #[test]
    fn should_ignore_adresses_with_more_than_3_bits() {
        let cmd = FastCommand::default().address(0b11111010);

        assert_eq!(cmd.address_byte, 0b01100010);
    }

    #[test]
    fn should_encode_data_into_data_bytes() {
        let cmd = FastCommand::default().data(0x0fff);

        assert_eq!(cmd.bytes(), [0b00001111, 0b11111111])
    }

    #[test]
    fn should_encode_powermode_into_data_bytes() {
        let cmd = FastCommand::default().power_mode(PowerMode::Resistor500kOhm);

        assert_eq!(cmd.bytes(), [0b00110000, 0])
    }
}