#![no_std]
#![deny(
missing_copy_implementations,
missing_debug_implementations,
missing_docs,
trivial_casts,
unstable_features,
unused_import_braces,
unused_qualifications,
warnings
)]
#![allow(dead_code)]
#![allow(clippy::uninit_assumed_init, clippy::upper_case_acronyms)]
extern crate cast;
extern crate embedded_hal as ehal;
extern crate generic_array;
extern crate nb;
use ehal::blocking::i2c::{Read, Write, WriteRead};
const WRITE_ADDRESS: u8 = 0x80;
const READ_ADDRESS: u8 = WRITE_ADDRESS >> 1;
#[allow(non_camel_case_types)]
#[derive(Copy, Clone, Debug)]
pub enum Register {
HOLD_BIT = 0x03,
MAXIMUM_EMITTING_PULSE_WIDTH = 0x13,
SPOT_SYMMETRY_THRESHOLD = 0x1C,
SIGNAL_INTENSITY_THRESHOLD = 0x2F,
MAXIMUM_SPOT_SIZE_THRESHOLD = 0x33,
MINIMUM_SPOT_SIZE_THRESHOLD = 0x34,
SHIFT_BIT = 0x35,
MEDIAN_FILTER = 0x3F,
SRAM_ACCESS = 0x4C,
DISTANCE_11_4 = 0x5E,
DISTANCE_3_0 = 0x5F,
AE_15_8 = 0x64,
AE_7_0 = 0x65,
AG_7_0 = 0x67,
COVER_COMPENSATION_5_0 = 0x8D,
COVER_COMPENSATION_10_6 = 0x8E,
COVER_COMPENSATION_ENABLE_BIT = 0x8F,
READ_OUT_IMAGE_SENSOR_DATA = 0x90,
SIGNAL_ACCUMULATION_NUMBER = 0xA8,
ENABLE_BIT_SIGNAL_INTENSITY = 0xBC,
ENABLE_BIT_MINIMUM_SPOT_SIZE = 0xBD,
ENABLE_BIT_MAXIMUM_SPOT_SIZE = 0xBE,
ENABLE_BIT_SPOT_SYMMETRY = 0xBF,
E_FUSE_TARGET_ADDRESS_READ_OUT_ENABLE_BIT = 0xC8,
E_FUSE_BIT_NUMBER_BANK_ASSIGN = 0xC9,
E_FUSE_PROGRAM_ENABLE_BIT = 0xCA,
E_FUSE_PROGRAM_DATA = 0xCD,
ACTIVE_STAND_BY_STATE_CONTROL = 0xE8,
CLOCK_SELECT = 0xEC,
SOFTWARE_RESET = 0xEE,
BANK_SELECT = 0xEF,
RIGHT_EDGE_COORDINATE = 0xF8,
LEFT_EDGE_COORDINATE = 0xF9,
PEAK_COORDINATE = 0xFA,
}
impl Register {
#[inline(always)]
pub fn addr(self) -> u8 {
self as u8
}
}
#[derive(Debug, Copy, Clone)]
pub struct GP2Y0E02B<I2C> {
com: I2C,
}
impl<I2C, E> GP2Y0E02B<I2C>
where
I2C: Write<Error = E> + Read<Error = E> + WriteRead<Error = E>,
E: core::fmt::Debug,
{
pub fn new(i2c: I2C) -> Result<GP2Y0E02B<I2C>, E> {
let chip = GP2Y0E02B { com: i2c };
Ok(chip)
}
pub fn read_register(&mut self, reg: Register) -> Result<u8, E> {
self.read_byte(reg as u8)
}
pub fn write_register(&mut self, reg: Register, byte: u8) -> Result<(), E> {
self.write_byte(reg as u8, byte)
}
pub fn read_distance(&mut self) -> Result<f32, E> {
let [high, low] = self.read_bytes(Register::DISTANCE_11_4.addr()).unwrap();
let shift = self.read_byte(Register::SHIFT_BIT.addr()).unwrap() as u32;
let v = (((high as f32 * 16.0) + low as f32) / 16.0) / (u16::pow(2, shift) as f32);
Ok(v)
}
fn read_byte(&mut self, reg: u8) -> Result<u8, E> {
let mut data: [u8; 1] = [0];
self.com.write_read(READ_ADDRESS, &[reg], &mut data)?;
Ok(data[0])
}
fn read_bytes(&mut self, reg: u8) -> Result<[u8; 2], E> {
let mut data: [u8; 2] = [0, 0];
self.com.write_read(READ_ADDRESS, &[reg], &mut data)?;
Ok(data)
}
fn write_byte(&mut self, reg: u8, byte: u8) -> Result<(), E> {
let mut buffer = [0];
self.com
.write_read(WRITE_ADDRESS, &[reg, byte], &mut buffer)
}
}