kirdy/src/laser_diode/current_sources.rs

74 lines
2.4 KiB
Rust

use cortex_m::prelude::_embedded_hal_blocking_delay_DelayMs;
use stm32f4xx_hal::{
gpio::{gpioa::*, gpiob::*, gpiod::*, Alternate, Output, PushPull, PD9},
hal::{blocking::spi::Write, digital::v2::OutputPin},
pac::SPI2,
spi::{NoMiso, Spi, TransferModeNormal},
};
pub trait CurrentSourcePhy {
type CurrentSourceLdoEn: OutputPin;
type CurrentSourceShort: OutputPin;
type Max5719Load: OutputPin;
type Max5719Cs: OutputPin;
type Max5719Spi: Write<u8>;
}
pub struct CurrentSourcePhyConstruct<C: CurrentSourcePhy> {
pub max5719_spi: C::Max5719Spi,
pub max5719_load: C::Max5719Load,
pub max5719_cs: C::Max5719Cs,
pub current_source_ldo_en: C::CurrentSourceLdoEn,
pub current_source_short: C::CurrentSourceShort,
}
pub struct CurrentSourceSettings {
pub output_current: f32,
}
pub struct CurrentSource<C: CurrentSourcePhy> {
pub phy: CurrentSourcePhyConstruct<C>,
pub setting: CurrentSourceSettings,
}
pub struct CurrentSourcePhyCh0;
impl CurrentSourcePhy for CurrentSourcePhyCh0 {
type CurrentSourceLdoEn = PD9<Output<PushPull>>;
type CurrentSourceShort = PA4<Output<PushPull>>;
type Max5719Load = PB14<Output<PushPull>>;
type Max5719Cs = PD8<Output<PushPull>>;
type Max5719Spi =
Spi<SPI2, (PB10<Alternate<5>>, NoMiso, PB15<Alternate<5>>), TransferModeNormal>;
}
use crate::device::delay;
impl<C: CurrentSourcePhy> CurrentSource<C> {
pub fn setup(&mut self, mut delay: delay::AsmDelay) {
let _ = self.phy.max5719_load.set_high();
let _ = self.phy.max5719_cs.set_high();
let _ = self.phy.current_source_ldo_en.set_high();
delay.delay_ms(10_u32);
let _ = self.phy.current_source_short.set_high();
delay.delay_ms(10_u32);
}
pub fn set_current(
&mut self,
current: f32,
) -> Result<(), <<C as CurrentSourcePhy>::Max5719Spi as Write<u8>>::Error> {
let _ = self.phy.max5719_load.set_high();
let _ = self.phy.max5719_cs.set_low();
self.setting.output_current = current * 10.0 / 0.75;
let word = (((self.setting.output_current / 4.096) * 1048576.0) as u32) << 4;
let mut buf = [
((word >> 16) & 0xFF) as u8,
((word >> 8) & 0xFF) as u8,
((word >> 0) & 0xFF) as u8,
];
self.phy.max5719_spi.write(&mut buf)?;
let _ = self.phy.max5719_cs.set_high();
let _ = self.phy.max5719_load.set_low();
Ok(())
}
}