Compare commits

...

4 Commits

Author SHA1 Message Date
linuswck 30ab228b4b ld: Set default ld_current_limit in setup() fn 2024-02-20 16:22:13 +08:00
linuswck 88cca12a60 ld: Use Timer IRQ to ramp up/down output current
- Fixes possible watchdog timeout
- Improves ethernet response time & thermostat Pid update interval consistency
2024-02-20 16:18:06 +08:00
linuswck 8139ebdc1b ld_ctrl: set_dac() fn now returns the volt set
- before this fix, set_dac() just returns the inputted voltage
2024-02-20 12:30:00 +08:00
linuswck 5f83b73011 cmd: Add active report mode cmd 2024-02-19 15:08:00 +08:00
8 changed files with 256 additions and 56 deletions

View File

@ -8,6 +8,7 @@ use crate::net::net::ServerHandle;
use stm32_eth;
use fugit::ExtU32;
use log::{info, debug};
use stm32f4xx_hal::timer::TimerExt;
use stm32f4xx_hal::{
pac::{CorePeripherals, Peripherals},
rcc::RccExt,
@ -71,10 +72,9 @@ pub fn bootup(
debug!("Setting up Laser Driver");
let current_source = LdCtrl::new(current_source_phy);
let mut laser = LdDrive::new(current_source, perif.ADC2, pd_mon_phy);
let mut laser = LdDrive::new(current_source, perif.ADC2, perif.TIM2.counter(&clocks), pd_mon_phy);
laser.setup();
laser.ld_open();
laser.set_ld_drive_current_limit(ElectricCurrent::new::<ampere>(0.2));
laser.ld_set_i(ElectricCurrent::new::<ampere>(0.0));
laser.set_pd_i_limit(ElectricCurrent::new::<milliampere>(2.5));
laser.set_pd_mon_calibrated_vdda(thermostat.get_calibrated_vdda());

View File

@ -1,19 +1,20 @@
use miniconf::Tree;
use stm32f4xx_hal::pac::ADC2;
use stm32f4xx_hal::timer::CounterUs;
use stm32f4xx_hal::pac::{ADC2, TIM2};
use uom::si::electric_current::ampere;
use crate::laser_diode::ld_ctrl::{LdCtrl, Impedance};
use crate::laser_diode::ld_pwr_exc_protector::{LdPwrExcProtector, self};
use crate::laser_diode::pd_responsitivity;
use crate::laser_diode::ld_current_out_ctrl_timer::LdCurrentOutCtrlTimer;
use core::marker::PhantomData;
use crate::device::sys_timer::sleep;
use serde::{Deserialize, Serialize};
use uom::si::{
electric_current::milliampere,
f64::{ElectricPotential, ElectricCurrent, Power},
};
use num_traits::Float;
use uom::{si::{ISQ, SI, Quantity, ratio::ratio}, typenum::*};
use uom::{si::{ISQ, SI, Quantity}, typenum::*};
// Volt / Ampere
pub type TransimpedanceUnit = Quantity<ISQ<P2, P1, N3, N2, Z0, Z0, Z0>, SI<f64>, f64>;
@ -21,6 +22,11 @@ pub type TransimpedanceUnit = Quantity<ISQ<P2, P1, N3, N2, Z0, Z0, Z0>, SI<f64>,
type TransconductanceUnit = Quantity<ISQ<N2, N1, P3, P2, Z0, Z0, Z0>, SI<f64>, f64>;
impl Settings{
pub const LD_CURRENT_MAX: ElectricCurrent = ElectricCurrent {
dimension: PhantomData,
units: PhantomData,
value: 0.3,
};
pub const DAC_OUT_V_MAX: ElectricPotential = ElectricPotential {
dimension: PhantomData,
units: PhantomData,
@ -39,14 +45,6 @@ impl Settings{
units: PhantomData,
value: 10.0 / 0.75,
};
const LD_CURRENT_STEP_SIZE: ElectricCurrent = ElectricCurrent {
dimension: PhantomData,
units: PhantomData,
value: 0.0001,
};
const LD_CURRENT_TIME_STEP_MS: u32 = 1;
}
#[derive(Clone, Debug, Tree)]
@ -67,15 +65,26 @@ impl Default for Settings {
}
}
#[derive(Deserialize, Serialize, Copy, Clone, Debug, Tree)]
pub struct StatusReport {
pwr_engaged: bool,
pwr_excursion: bool,
ld_i_set: ElectricCurrent,
pd_i: ElectricCurrent,
pd_pwr: Power,
term_status: Impedance,
}
pub struct LdDrive{
ctrl: LdCtrl,
settings: Settings,
}
impl LdDrive{
pub fn new(current_source: LdCtrl, pins_adc: ADC2, phy: ld_pwr_exc_protector::LdPwrExcProtectorPhy)-> Self {
pub fn new(current_source: LdCtrl, pins_adc: ADC2, tim2: CounterUs<TIM2>, phy: ld_pwr_exc_protector::LdPwrExcProtectorPhy)-> Self {
LdPwrExcProtector::setup(pins_adc, phy);
LdCurrentOutCtrlTimer::setup(tim2);
LdDrive {
ctrl: current_source,
settings: Settings::default()
@ -84,7 +93,9 @@ impl LdDrive{
pub fn setup(&mut self) {
LdPwrExcProtector::pwr_off();
self.ld_set_i(ElectricCurrent::new::<milliampere>(0.0));
self.ctrl.set_i(ElectricCurrent::new::<milliampere>(0.0), Settings::LD_DRIVE_TRANSIMPEDANCE, Settings::DAC_OUT_V_MAX);
self.set_ld_drive_current_limit(Settings::LD_CURRENT_MAX);
LdCurrentOutCtrlTimer::reset();
self.ld_short();
}
@ -93,7 +104,7 @@ impl LdDrive{
}
pub fn set_ld_drive_current_limit(&mut self, i_limit: ElectricCurrent){
self.settings.ld_drive_current_limit = i_limit;
self.settings.ld_drive_current_limit = i_limit.min(Settings::LD_CURRENT_MAX);
}
pub fn ld_short(&mut self) {
@ -106,6 +117,7 @@ impl LdDrive{
pub fn power_up(&mut self){
let _ = self.ctrl.set_i(ElectricCurrent::new::<milliampere>(0.0), Settings::LD_DRIVE_TRANSIMPEDANCE, Settings::DAC_OUT_V_MAX);
LdCurrentOutCtrlTimer::reset();
LdPwrExcProtector::pwr_on_and_arm_protection();
// Wait for LD Power Supply to start up before driving current to laser diode
sleep(30);
@ -120,28 +132,26 @@ impl LdDrive{
LdPwrExcProtector::get_status().v * Settings::PD_MON_TRANSCONDUCTANCE
}
// Ramping up or down laser diode current according to preset current step size and time step.
pub fn ld_set_i(&mut self, i: ElectricCurrent) -> ElectricCurrent {
let mut prev_i_set = self.settings.ld_drive_current;
let final_i_set = i.min(self.settings.ld_drive_current_limit).max(ElectricCurrent::new::<ampere>(0.0));
let num_of_step = ((final_i_set - prev_i_set)/Settings::LD_CURRENT_STEP_SIZE).get::<ratio>().floor() as i32;
pub fn get_pd_pwr(&mut self) -> Power {
self.settings.pd_responsitivity.get_ld_pwr_from_ld_i(LdPwrExcProtector::get_status().v * Settings::PD_MON_TRANSCONDUCTANCE)
}
let current_step = if num_of_step.is_positive() {
Settings::LD_CURRENT_STEP_SIZE
} else {
-Settings::LD_CURRENT_STEP_SIZE
};
for _ in 0..num_of_step.abs() {
prev_i_set = prev_i_set + current_step;
let _ = self.ctrl.set_i(prev_i_set, Settings::LD_DRIVE_TRANSIMPEDANCE, Settings::DAC_OUT_V_MAX);
sleep(Settings::LD_CURRENT_TIME_STEP_MS);
pub fn ld_set_i(&mut self, i: ElectricCurrent){
LdCurrentOutCtrlTimer::set_target_i_and_listen_irq(i, self.settings.ld_drive_current);
}
pub fn poll_and_update_output_current(&mut self) -> ElectricCurrent {
match LdCurrentOutCtrlTimer::get_irq_status() {
Some(i_set) => {
let i_set = self.ctrl.set_i(i_set, Settings::LD_DRIVE_TRANSIMPEDANCE, Settings::DAC_OUT_V_MAX);
self.settings.ld_drive_current = i_set;
LdCurrentOutCtrlTimer::clear_alarm_and_resume_listening();
i_set
}
None => {
ElectricCurrent::new::<ampere>(0.0)
}
}
let prev_i_set = self.ctrl.set_i(final_i_set, Settings::LD_DRIVE_TRANSIMPEDANCE, Settings::DAC_OUT_V_MAX);
self.settings.ld_drive_current = prev_i_set;
prev_i_set
}
// Set the calibrated VDDA value obtained from ADC1 calibration
@ -178,4 +188,15 @@ impl LdDrive{
pub fn get_term_status(&mut self) -> Impedance {
self.ctrl.get_lf_mod_in_impedance()
}
pub fn get_status_report(&mut self) -> StatusReport {
StatusReport {
pwr_engaged: LdPwrExcProtector::get_status().pwr_engaged,
pwr_excursion: LdPwrExcProtector::get_status().pwr_excursion,
ld_i_set: self.settings.ld_drive_current,
pd_i: self.get_pd_i(),
pd_pwr: self.get_pd_pwr(),
term_status: self.get_term_status(),
}
}
}

View File

@ -1,3 +1,4 @@
use serde::{Deserialize, Serialize};
use stm32f4xx_hal::{
gpio::{gpioa::*, gpiob::*, gpiod::*, Alternate, Input, Output, PushPull},
hal::{blocking::spi::Transfer, digital::{v2::OutputPin, v2::InputPin}},
@ -13,7 +14,7 @@ use uom::si::{
use crate::laser_diode::max5719::{self, Dac};
use crate::laser_diode::laser_diode::TransimpedanceUnit;
#[derive(Debug)]
#[derive(Deserialize, Serialize, Debug, Clone, Copy)]
pub enum Impedance {
Is50Ohm,
Not50Ohm,
@ -80,7 +81,7 @@ impl LdCtrl {
let value = ((voltage / dac_out_v_max).get::<ratio>()
* (max5719::MAX_VALUE as f64)) as u32;
self.phy.dac.set(value).unwrap();
voltage
value as f64 * dac_out_v_max / max5719::MAX_VALUE as f64
}
pub fn set_i(&mut self, current: ElectricCurrent, transimpedance: TransimpedanceUnit, dac_out_v_max: ElectricPotential) -> ElectricCurrent {

View File

@ -0,0 +1,120 @@
use stm32f4xx_hal::timer::{CounterUs, Event};
use stm32f4xx_hal::pac::{interrupt, Interrupt, TIM2};
use uom::si::{f64::ElectricCurrent, electric_current::ampere};
use fugit::{TimerDurationU32, KilohertzU32};
use core::marker::PhantomData;
pub struct LdCurrentOutCtrlTimer {
target_i: ElectricCurrent,
now_i: ElectricCurrent,
timer: CounterUs<TIM2>,
timeout: bool,
}
static mut LD_CURRENT_OUT_CTRL_TIMER: Option<LdCurrentOutCtrlTimer> = None;
/// This timer notifies the main loop to set the correct output current so that ld output current can ramp up/down slowly.
/// The current output slope is guaranteed to be larger but not necessarily equal to than the preset value.
impl LdCurrentOutCtrlTimer {
const TIME_STEP_MS: TimerDurationU32<1000000> = TimerDurationU32::from_rate(KilohertzU32::from_raw(1));
const STEP_SIZE: ElectricCurrent = ElectricCurrent {
dimension: PhantomData,
units: PhantomData,
value: 0.0001,
};
pub fn setup(mut tim2: CounterUs<TIM2>) {
tim2.start(LdCurrentOutCtrlTimer::TIME_STEP_MS).unwrap();
unsafe {
cortex_m::peripheral::NVIC::unmask(Interrupt::TIM2);
}
unsafe {
LD_CURRENT_OUT_CTRL_TIMER = Some(
LdCurrentOutCtrlTimer {
target_i: ElectricCurrent::new::<ampere>(0.0),
now_i: ElectricCurrent::new::<ampere>(0.0),
timer: tim2,
timeout: false
}
);
}
}
fn get() -> Option<&'static mut Self> {
unsafe { LD_CURRENT_OUT_CTRL_TIMER.as_mut() }
}
pub fn reset() {
if let Some(ref mut ld_current_out_ctrl_timer ) = LdCurrentOutCtrlTimer::get() {
ld_current_out_ctrl_timer.target_i = ElectricCurrent::new::<ampere>(0.0);
ld_current_out_ctrl_timer.now_i = ElectricCurrent::new::<ampere>(0.0);
ld_current_out_ctrl_timer.timeout = false;
ld_current_out_ctrl_timer.timer.unlisten(Event::Update);
}
}
pub fn set_target_i_and_listen_irq(target: ElectricCurrent, now: ElectricCurrent) {
if let Some(ref mut ld_current_out_ctrl_timer ) = LdCurrentOutCtrlTimer::get() {
cortex_m::interrupt::free(|_| {
ld_current_out_ctrl_timer.target_i = target;
ld_current_out_ctrl_timer.now_i = now;
ld_current_out_ctrl_timer.timer.listen(Event::Update);
}
)
}
}
pub fn set_alarm() {
if let Some(ref mut ld_current_out_ctrl_timer ) = LdCurrentOutCtrlTimer::get() {
ld_current_out_ctrl_timer.timeout = true;
}
}
pub fn clear_alarm_and_resume_listening() {
if let Some(ref mut ld_current_out_ctrl_timer ) = LdCurrentOutCtrlTimer::get() {
ld_current_out_ctrl_timer.timeout = false;
ld_current_out_ctrl_timer.timer.listen(Event::Update);
}
}
pub fn get_irq_status() -> Option<ElectricCurrent> {
if let Some(ref mut ld_current_out_ctrl_timer ) = LdCurrentOutCtrlTimer::get() {
if ld_current_out_ctrl_timer.timeout {
return Some(ld_current_out_ctrl_timer.now_i);
}
}
None
}
pub fn clear_irq_flag() {
if let Some(ref mut ld_current_out_ctrl_timer ) = LdCurrentOutCtrlTimer::get() {
ld_current_out_ctrl_timer.timer.clear_interrupt(Event::Update);
}
}
pub fn update_next_i_set() -> bool {
if let Some(ref mut ld_current_out_ctrl_timer ) = LdCurrentOutCtrlTimer::get() {
let update = ld_current_out_ctrl_timer.now_i != ld_current_out_ctrl_timer.target_i;
if ld_current_out_ctrl_timer.target_i > ld_current_out_ctrl_timer.now_i {
ld_current_out_ctrl_timer.now_i = (ld_current_out_ctrl_timer.now_i + LdCurrentOutCtrlTimer::STEP_SIZE).min(ld_current_out_ctrl_timer.target_i);
}
else {
ld_current_out_ctrl_timer.now_i = (ld_current_out_ctrl_timer.now_i - LdCurrentOutCtrlTimer::STEP_SIZE).max(ld_current_out_ctrl_timer.target_i);
}
return update
}
false
}
pub fn stop_listening() {
if let Some(ref mut ld_current_out_ctrl_timer ) = LdCurrentOutCtrlTimer::get() {
ld_current_out_ctrl_timer.timer.unlisten(Event::Update);
}
}
}
#[interrupt]
fn TIM2(){
if LdCurrentOutCtrlTimer::update_next_i_set() {
LdCurrentOutCtrlTimer::set_alarm();
}
LdCurrentOutCtrlTimer::stop_listening();
LdCurrentOutCtrlTimer::clear_irq_flag();
}

View File

@ -2,4 +2,5 @@ pub mod ld_ctrl;
pub mod max5719;
pub mod laser_diode;
pub mod pd_responsitivity;
pub mod ld_pwr_exc_protector;
pub mod ld_pwr_exc_protector;
pub mod ld_current_out_ctrl_timer;

View File

@ -34,6 +34,10 @@ use panic_halt as _;
static mut ETH_DATA_BUFFER: [u8; 1024] = [0; 1024];
pub struct DeviceSettings{
report_readings: bool,
}
#[cfg(not(test))]
#[entry]
fn main() -> ! {
@ -80,12 +84,18 @@ fn main() -> ! {
let mut should_reset = false;
let mut device_settings = DeviceSettings {
report_readings: false,
};
loop {
wd.feed();
if !should_reset {
let mut eth_is_pending = false;
laser.poll_and_update_output_current();
if thermostat.poll_adc_and_update_pid() {
info!("curr_dac_vfb: {:?}", volt_fmt.with(thermostat.get_dac_vfb()));
info!("curr_vref: {:?}", volt_fmt.with(thermostat.get_vref()));
@ -98,6 +108,15 @@ fn main() -> ! {
info!("power_excursion: {:?}", laser.pd_mon_status().pwr_excursion);
info!("Termination Status: {:?}", laser.get_term_status());
if net::net::eth_is_socket_active() {
if device_settings.report_readings {
unsafe {
net::cmd_handler::send_ld_readings(&mut ETH_DATA_BUFFER, &mut laser);
net::cmd_handler::send_tec_readings(&mut ETH_DATA_BUFFER, &mut thermostat);
}
}
}
}
if net::net::eth_is_socket_active() {
@ -114,10 +133,13 @@ fn main() -> ! {
});
let bytes = net::net::eth_recv(&mut ETH_DATA_BUFFER);
debug!("Number of bytes recv: {:?}", bytes);
(laser, thermostat, should_reset) = net::cmd_handler::execute_cmd(&mut ETH_DATA_BUFFER, bytes, laser, thermostat);
(laser, thermostat, should_reset, device_settings) = net::cmd_handler::execute_cmd(&mut ETH_DATA_BUFFER, bytes, laser, thermostat, device_settings);
}
}
}
else {
device_settings.report_readings = false;
}
} else {
// Should reset, close all TCP sockets.
let mut any_socket_alive = false;

View File

@ -7,17 +7,24 @@ use uom::si::{
electrical_resistance::{ElectricalResistance, ohm},
f64::ThermodynamicTemperature, thermodynamic_temperature::degree_celsius
};
use crate::{laser_diode::laser_diode::LdDrive, net::net, thermostat::thermostat::StatusReport};
use crate::{laser_diode::laser_diode::{
LdDrive, StatusReport as LdStatusReport
},
net::net,
thermostat::thermostat::StatusReport as TecStatusReport
};
use crate::thermostat::thermostat::Thermostat;
use crate::thermostat::pid_state::PidSettings::*;
use crate::device::dfu;
use log::info;
use crate::DeviceSettings;
#[derive(Deserialize, Serialize, Copy, Clone, Default, Debug)]
enum DeviceCmd {
#[default]
Reserved,
Dfu
ReportStatus,
Dfu,
}
#[derive(Deserialize, Serialize, Copy, Clone, Default, Debug)]
@ -79,6 +86,7 @@ pub struct CmdJsonObj{
laser_diode_cmd: Option<LdCmdEnum>,
thermostat_cmd: Option<ThermostatCmdEnum>,
device_cmd: Option<DeviceCmd>,
data_bool: Option<bool>,
data_f32: Option<f32>,
data_f64: Option<f64>,
}
@ -87,12 +95,33 @@ pub struct Cmd {
json: CmdJsonObj
}
#[derive(Deserialize, Serialize, Copy, Clone, Debug, Default, Tree)]
pub struct StatusReportStruct {
json: StatusReport
#[derive(Deserialize, Serialize, Copy, Clone, Debug, Tree)]
pub struct TecStatusReportStruct {
json: TecStatusReport
}
pub fn execute_cmd(buffer: &mut [u8], buffer_size: usize, mut laser: LdDrive, mut tec: Thermostat)->(LdDrive, Thermostat, bool){
#[derive(Deserialize, Serialize, Copy, Clone, Debug, Tree)]
pub struct LaserStatusReportStruct {
json: LdStatusReport
}
pub fn send_ld_readings(buffer: &mut [u8], laser: &mut LdDrive){
let status_report = LaserStatusReportStruct {
json: laser.get_status_report()
};
let num_bytes = status_report.get_json("/json", buffer).unwrap();
net::eth_send(buffer, num_bytes);
}
pub fn send_tec_readings(buffer: &mut [u8], tec: &mut Thermostat){
let status_report = TecStatusReportStruct {
json: tec.get_status_report()
};
let num_bytes = status_report.get_json("/json", buffer).unwrap();
net::eth_send(buffer, num_bytes);
}
pub fn execute_cmd(buffer: &mut [u8], buffer_size: usize, mut laser: LdDrive, mut tec: Thermostat, mut device_settings: DeviceSettings)->(LdDrive, Thermostat, bool, DeviceSettings){
let mut should_reset = false;
let mut cmd = Cmd {
@ -111,6 +140,16 @@ pub fn execute_cmd(buffer: &mut [u8], buffer_size: usize, mut laser: LdDrive, mu
}
should_reset = true;
}
Some(DeviceCmd::ReportStatus) => {
match cmd.json.data_bool{
Some(val) => {
device_settings.report_readings = val;
}
None => {
info!("Wrong Data type is received")
}
}
}
None => { /* Do Nothing */}
_ => {
info!("Unimplemented Command")
@ -176,7 +215,7 @@ pub fn execute_cmd(buffer: &mut [u8], buffer_size: usize, mut laser: LdDrive, mu
info!("Not supported Yet")
}
Some(LdCmdEnum::GetLdStatus) => {
info!("Not supported Yet")
send_ld_readings(buffer, &mut laser);
}
Some(LdCmdEnum::GetAlramStatus) => {
info!("Not supported Yet")
@ -334,11 +373,7 @@ pub fn execute_cmd(buffer: &mut [u8], buffer_size: usize, mut laser: LdDrive, mu
}
}
Some(ThermostatCmdEnum::GetTecStatus) => {
let status_report = StatusReportStruct {
json: tec.get_status_report()
};
let num_bytes = status_report.get_json("/json", buffer).unwrap();
net::eth_send(buffer, num_bytes);
send_tec_readings(buffer, &mut tec);
}
Some(ThermostatCmdEnum::GetPidStatus) => {
info!("Not supported Yet")
@ -356,5 +391,5 @@ pub fn execute_cmd(buffer: &mut [u8], buffer_size: usize, mut laser: LdDrive, mu
info!("Invalid Command: {:?}", err);
}
}
(laser, tec, should_reset)
(laser, tec, should_reset, device_settings)
}

View File

@ -338,7 +338,7 @@ impl Thermostat{
}
}
#[derive(Deserialize, Serialize, Copy, Clone, Debug, Default, Tree)]
#[derive(Deserialize, Serialize, Copy, Clone, Debug, Tree)]
pub struct StatusReport {
ts: u32,
pid_engaged: bool,