tof_control/device/
ad5675.rs

1#![allow(unused)]
2use libc::{ioctl, O_RDWR, STDOUT_FILENO};
3use std::fs::File;
4use std::os::fd::{AsRawFd, IntoRawFd, RawFd};
5use std::os::raw::{c_uint, c_ulong};
6
7use crate::constant::*;
8
9use i2c_linux_sys::*;
10
11const READBACK_ENABLE: u16 = 0x90;
12const POWER_DOWN_UP: u16 = 0x40;
13
14pub struct AD5675 {
15    fd: RawFd,
16    address: u16,
17}
18impl AD5675 {
19    pub fn new(address: u16) -> Self {
20        let fd = if let Ok(file) = File::open("/dev/i2c-0") {
21            file.into_raw_fd()
22        } else {
23            STDOUT_FILENO
24        };
25        Self { fd, address }
26    }
27    pub fn write_dac(&self, channel: u8, value: u16) {
28        unsafe { ioctl(self.fd, (I2C_SLAVE as c_ulong).try_into().unwrap(), 0x77) };
29        i2c_linux_sys::i2c_smbus_write_byte(self.fd, 0x04);
30        unsafe {
31            ioctl(
32                self.fd,
33                (I2C_SLAVE as c_ulong).try_into().unwrap(),
34                self.address as c_uint,
35            )
36        };
37        let mut buffer = (value & 0xFF00) >> 8;
38        buffer = buffer | (value & 0x00FF) << 8;
39        i2c_linux_sys::i2c_smbus_write_word_data(self.fd, 0x30 + channel, buffer);
40    }
41    // pub fn read_dac(&self, channel: u8) {
42    //     i2c_linux_sys::i2c_set_slave_address(self.fd, self.address, false);
43    //     // i2c_linux_sys::i2c_smbus_write_byte(self.fd, READBACK_ENABLE as u8);
44    //     // let mut buffer: [u8; 2] = [0, 0];
45    //     let mut reg: u8 = 0x10|channel;
46    //     // i2c_linux_sys::i2c_smbus_read_i2c_block_data(self.fd, channel, &mut buffer);
47    //     // i2c_linux_sys::i2c_smbus_read_i2c_block_data(self.fd, 0x30+channel, &mut buffer);
48    //     let mut i2c_msg_custom = i2c_linux_sys::i2c_msg {
49    //         addr: self.address,
50    //         flags: i2c_linux_sys::Flags::RD,
51    //         len: 2,
52    //         buf: &mut reg,
53    //     };
54    //     let mut i2c_rdwr_ioctl_data_custom = i2c_linux_sys::i2c_rdwr_ioctl_data {
55    //         msgs: &mut i2c_msg_custom,
56    //         nmsgs: 2,
57    //     };
58    //     let data = unsafe { i2c_linux_sys::ioctls::i2c_rdwr(self.fd, &mut i2c_rdwr_ioctl_data_custom) };
59    //     println!("{:?}", data);
60    // }
61}