From 2071c8485241e0b95de891e8855542d7c51915ab Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Sat, 20 Mar 2021 11:45:23 +0100 Subject: Create eval-clock-cw-tx sw --- sw/eval-clock-cw-tx/src/cw.rs | 200 ++++++++++++++++++++ sw/eval-clock-cw-tx/src/log10f.rs | 91 +++++++++ sw/eval-clock-cw-tx/src/main.rs | 367 ++++++++++++++++++++++++++++++++++++ sw/eval-clock-cw-tx/src/si_clock.rs | 132 +++++++++++++ sw/eval-clock-cw-tx/src/state.rs | 83 ++++++++ sw/eval-clock-cw-tx/src/ui.rs | 274 +++++++++++++++++++++++++++ 6 files changed, 1147 insertions(+) create mode 100644 sw/eval-clock-cw-tx/src/cw.rs create mode 100644 sw/eval-clock-cw-tx/src/log10f.rs create mode 100644 sw/eval-clock-cw-tx/src/main.rs create mode 100644 sw/eval-clock-cw-tx/src/si_clock.rs create mode 100644 sw/eval-clock-cw-tx/src/state.rs create mode 100644 sw/eval-clock-cw-tx/src/ui.rs (limited to 'sw/eval-clock-cw-tx/src') diff --git a/sw/eval-clock-cw-tx/src/cw.rs b/sw/eval-clock-cw-tx/src/cw.rs new file mode 100644 index 0000000..045ef15 --- /dev/null +++ b/sw/eval-clock-cw-tx/src/cw.rs @@ -0,0 +1,200 @@ +//! CW output using PWM on PA8, TIM1 CH1 + +use stm32f1xx_hal::{ + prelude::*, + timer, + pac::TIM1, + gpio::gpioa::*, + gpio::{Alternate, PushPull}, + afio::MAPR, + pwm, +}; + +pub struct CWPWM { + channel : pwm::PwmChannel, +} + +impl CWPWM { + pub fn new(pa8: PA8>, tim1: timer::Timer, mapr: &mut MAPR) -> Self { + let pwm = tim1.pwm(pa8, mapr, 400.hz()); + let mut channel = pwm.split(); + channel.enable(); + channel.set_duty(0); + CWPWM { channel } + } + + pub fn on(&mut self) { + let max = self.channel.get_max_duty(); + self.channel.set_duty(max / 2); + } + + pub fn off(&mut self) { + self.channel.set_duty(0); + } +} + +#[derive(PartialEq, Eq, Clone, Copy)] +enum MorseSign { + Dot, + Dash +} + +impl MorseSign { + fn length(&self) -> u32 { + match self { + Self::Dot => 1, + Self::Dash => 3, + } + } + + fn other(&self) -> Self { + match self { + Self::Dot => Self::Dash, + Self::Dash => Self::Dot, + } + } +} + +fn other_pressed(sign: MorseSign, dot_pressed: bool, dash_pressed: bool) -> bool { + match sign { + MorseSign::Dot => dash_pressed, + MorseSign::Dash => dot_pressed, + } +} + +#[derive(Eq, Clone, Copy)] +enum KeyerState { + Idle, + Beep{current: MorseSign, next: Option}, + Pause{current: MorseSign, next: Option}, + LastPause{next: Option}, +} + +impl PartialEq for KeyerState { + fn eq(&self, rhs: &Self) -> bool { + match (self, rhs) { + (Self::Idle, Self::Idle) => true, + (Self::Beep{current : c1, next : _}, Self::Beep{current : c2, next : _}) => c1 == c2, + (Self::Pause{current : c1, next : _}, Self::Pause{current : c2, next : _}) => c1 == c2, + (Self::LastPause{next : _}, Self::LastPause{next : _}) => true, + _ => false, + } + } +} + +pub struct Keyer { + // All durations are in ticks + dot_length : u32, + state : KeyerState, + time_last_state_change : u32, +} + +impl Keyer { + pub fn new(wpm : u32, ticks_per_s: u32) -> Keyer { + /* PARIS standard: 20 words per minute = dot length of 60 ms, inversely proportional: + * 1 wpm = 1200 ms, 2 wpm = 600 ms */ + + Keyer{ + dot_length : 1200 * ticks_per_s / (1000 * wpm), + state : KeyerState::Idle, + time_last_state_change : 0, + } + } + pub fn set_speed(&mut self, wpm : u32, ticks_per_s: u32) { self.dot_length = 1200 * ticks_per_s / (1000 * wpm) } + + pub fn tick(&mut self, ticks_now: u32, dot_pressed: bool, dash_pressed: bool) -> bool { + let mut transmit = false; + + let next_state = match self.state { + KeyerState::Idle => { + if dot_pressed { + transmit = true; + KeyerState::Beep{current: MorseSign::Dot, next: None} + } + else if dash_pressed { + transmit = true; + KeyerState::Beep{current: MorseSign::Dash, next: None} + } + else { + KeyerState::Idle + } + }, + KeyerState::Beep{current, next} => { + transmit = true; + + let next = if other_pressed(current, dot_pressed, dash_pressed) { + Some(current.other()) + } + else { + next + }; + + if self.time_last_state_change + self.dot_length * current.length() <= ticks_now { + KeyerState::Pause{current, next} + } + else { + KeyerState::Beep{current, next} + } + }, + KeyerState::Pause{current, next} => { + let next = if other_pressed(current, dot_pressed, dash_pressed) { + Some(current.other()) + } + else { + next + }; + + if self.time_last_state_change + self.dot_length <= ticks_now { + match next { + Some(state) => { + transmit = true; + KeyerState::Beep{current: state, next: None} + }, + None => KeyerState::LastPause{next: None} + } + } + else { + KeyerState::Pause{current, next} + } + }, + KeyerState::LastPause{next} => { + let next = if dot_pressed { + Some(MorseSign::Dot) + } + else if dash_pressed { + Some(MorseSign::Dash) + } + else { + next + }; + + if self.time_last_state_change + self.dot_length <= ticks_now { + KeyerState::LastPause{next} + } + else { + match next { + Some(MorseSign::Dot) => { + transmit = true; + KeyerState::Beep{current: MorseSign::Dot, next: None} + }, + Some(MorseSign::Dash) => { + transmit = true; + KeyerState::Beep{current: MorseSign::Dash, next: None} + }, + None => { + KeyerState::Idle + }, + } + } + }, + }; + + if next_state != self.state { + self.time_last_state_change = ticks_now; + } + self.state = next_state; + + transmit + } +} + diff --git a/sw/eval-clock-cw-tx/src/log10f.rs b/sw/eval-clock-cw-tx/src/log10f.rs new file mode 100644 index 0000000..108dfa8 --- /dev/null +++ b/sw/eval-clock-cw-tx/src/log10f.rs @@ -0,0 +1,91 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/e_log10f.c */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ +/* + * See comments in log10.c. + */ + +use core::f32; + +const IVLN10HI: f32 = 4.3432617188e-01; /* 0x3ede6000 */ +const IVLN10LO: f32 = -3.1689971365e-05; /* 0xb804ead9 */ +const LOG10_2HI: f32 = 3.0102920532e-01; /* 0x3e9a2080 */ +const LOG10_2LO: f32 = 7.9034151668e-07; /* 0x355427db */ +/* |(log(1+s)-log(1-s))/s - Lg(s)| < 2**-34.24 (~[-4.95e-11, 4.97e-11]). */ +const LG1: f32 = 0.66666662693; /* 0xaaaaaa.0p-24 */ +const LG2: f32 = 0.40000972152; /* 0xccce13.0p-25 */ +const LG3: f32 = 0.28498786688; /* 0x91e9ee.0p-25 */ +const LG4: f32 = 0.24279078841; /* 0xf89e26.0p-26 */ + +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +pub fn log10f(mut x: f32) -> f32 { + let x1p25f = f32::from_bits(0x4c000000); // 0x1p25f === 2 ^ 25 + + let mut ui: u32 = x.to_bits(); + let hfsq: f32; + let f: f32; + let s: f32; + let z: f32; + let r: f32; + let w: f32; + let t1: f32; + let t2: f32; + let dk: f32; + let mut hi: f32; + let lo: f32; + let mut ix: u32; + let mut k: i32; + + ix = ui; + k = 0; + if ix < 0x00800000 || (ix >> 31) > 0 { + /* x < 2**-126 */ + if ix << 1 == 0 { + return -1. / (x * x); /* log(+-0)=-inf */ + } + if (ix >> 31) > 0 { + return (x - x) / 0.0; /* log(-#) = NaN */ + } + /* subnormal number, scale up x */ + k -= 25; + x *= x1p25f; + ui = x.to_bits(); + ix = ui; + } else if ix >= 0x7f800000 { + return x; + } else if ix == 0x3f800000 { + return 0.; + } + + /* reduce x into [sqrt(2)/2, sqrt(2)] */ + ix += 0x3f800000 - 0x3f3504f3; + k += (ix >> 23) as i32 - 0x7f; + ix = (ix & 0x007fffff) + 0x3f3504f3; + ui = ix; + x = f32::from_bits(ui); + + f = x - 1.0; + s = f / (2.0 + f); + z = s * s; + w = z * z; + t1 = w * (LG2 + w * LG4); + t2 = z * (LG1 + w * LG3); + r = t2 + t1; + hfsq = 0.5 * f * f; + + hi = f - hfsq; + ui = hi.to_bits(); + ui &= 0xfffff000; + hi = f32::from_bits(ui); + lo = f - hi - hfsq + s * (hfsq + r); + dk = k as f32; + dk * LOG10_2LO + (lo + hi) * IVLN10LO + lo * IVLN10HI + hi * IVLN10HI + dk * LOG10_2HI +} diff --git a/sw/eval-clock-cw-tx/src/main.rs b/sw/eval-clock-cw-tx/src/main.rs new file mode 100644 index 0000000..4d2dae5 --- /dev/null +++ b/sw/eval-clock-cw-tx/src/main.rs @@ -0,0 +1,367 @@ +/* + The MIT License (MIT) + + Copyright (c) 2021 Matthias P. Braendli + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +#![no_main] +#![no_std] + +use core::mem::MaybeUninit; +use cortex_m_rt::ExceptionFrame; +use cortex_m_semihosting::hprintln; +use panic_semihosting as _; + +use stm32f1xx_hal::{ + prelude::*, + pac, + pac::interrupt, + i2c, + gpio, + delay::Delay, + timer::{CountDownTimer, Timer, Event}, + qei::QeiOptions, +}; + +use embedded_hal::digital::v2::OutputPin; +use embedded_hal::digital::v2::InputPin; +use hd44780_driver::{Cursor, CursorBlink, Display, DisplayMode, HD44780}; + +pub mod ui; +pub mod cw; +pub mod state; +pub mod si_clock; +pub mod log10f; + +use state::*; + +const TICKS_PER_SECOND : u32 = 100; + +struct SharedWithISR { + state : State, + last_sequence_state_change : u32, + cw_ptt_timestamp : u32, + cw_key_n : gpio::gpioa::PA15>, + ui : ui::UI, + cw_pwm: cw::CWPWM, + cw_keyer: cw::Keyer, + cw_paddle_tip: gpio::gpiob::PB8>, + cw_paddle_ring: gpio::gpiob::PB9>, + ptt_out_n: gpio::gpiob::PB3>, + led : gpio::gpiob::PB14>, +} + +static mut SHARED: MaybeUninit = MaybeUninit::uninit(); +static mut CLOCK_TIMER: MaybeUninit> = MaybeUninit::uninit(); +static mut TICK_COUNTER: MaybeUninit = MaybeUninit::uninit(); + +fn ticks_now() -> u32 { + cortex_m::interrupt::free(|_cs| unsafe { *TICK_COUNTER.as_ptr() }) +} + +fn get_state_copy() -> State { + cortex_m::interrupt::free(|_cs| unsafe { + (*SHARED.as_ptr()).state.clone() + }) +} + +#[cortex_m_rt::entry] +fn main() -> ! { + let cp = cortex_m::Peripherals::take().unwrap(); + let dp = pac::Peripherals::take().unwrap(); + + let mut flash = dp.FLASH.constrain(); + let mut rcc = dp.RCC.constrain(); + let mut afio = dp.AFIO.constrain(&mut rcc.apb2); + let clocks = rcc.cfgr + .adcclk(2.mhz()) + .freeze(&mut flash.acr); + let mut delay = Delay::new(cp.SYST, clocks); + + delay.delay_ms(200u16); + + let mut gpioa = dp.GPIOA.split(&mut rcc.apb2); + let mut gpiob = dp.GPIOB.split(&mut rcc.apb2); + let mut gpioc = dp.GPIOC.split(&mut rcc.apb2); + + // Buttons as analog inputs (multi-level) + let pb0 = gpiob.pb0.into_floating_input(&mut gpiob.crl); // BTN1 Button B, has external pullup + let pb1 = gpiob.pb1.into_floating_input(&mut gpiob.crl); // BTN0 Button A, has external pullup + let pb12 = gpiob.pb12.into_pull_up_input(&mut gpiob.crh); // BTN2 Button C + let pb13 = gpiob.pb13.into_pull_up_input(&mut gpiob.crh); // BTN3 Button D + let pc15 = gpioc.pc15.into_pull_up_input(&mut gpioc.crh); // Encoder button + let ui = ui::UI::new(pb0, pb1, pb12, pb13, pc15); + + let cw_pwm = { + let pa8 = gpioa.pa8.into_alternate_push_pull(&mut gpioa.crh); // CW PWM output using TIM1 Ch1 + let tim1 = Timer::tim1(dp.TIM1, &clocks, &mut rcc.apb2); + cw::CWPWM::new(pa8, tim1, &mut afio.mapr) + }; + + let cw_paddle_tip = gpiob.pb8.into_pull_up_input(&mut gpiob.crh); // CW paddle tip + let cw_paddle_ring = gpiob.pb9.into_pull_up_input(&mut gpiob.crh); // CW paddle ring + + // Configure PB14 as output. (LED) + let mut led = gpiob.pb14.into_push_pull_output(&mut gpiob.crh); + led.set_low().unwrap(); + + let (pa15, pb3, _pb4) = afio.mapr.disable_jtag(gpioa.pa15, gpiob.pb3, gpiob.pb4); + let cw_key_n = pa15.into_open_drain_output_with_state(&mut gpioa.crh, gpio::State::High); + let ptt_out_n = pb3.into_push_pull_output_with_state(&mut gpiob.crl, gpio::State::High); + + let c1 = gpioa.pa6; + let c2 = gpioa.pa7; + let qei = Timer::tim3(dp.TIM3, &clocks, &mut rcc.apb1) + .qei((c1, c2), &mut afio.mapr, QeiOptions::default()); + + // Configure I2C1 to be used for Si5351 and display + let scl = gpiob.pb6.into_alternate_open_drain(&mut gpiob.crl); + let sda = gpiob.pb7.into_alternate_open_drain(&mut gpiob.crl); + + let i2c = i2c::BlockingI2c::i2c1( + dp.I2C1, + (scl, sda), + &mut afio.mapr, + i2c::Mode::Standard { + frequency: 100_000.hz(), + }, + clocks, + &mut rcc.apb1, + /* start_timeout_us */ 1000, + /* start_retries */ 10, + /* addr_timeout_us */ 1000, + /* data_timeout_us */ 1000, + ); + let i2c_busmanager = shared_bus::BusManagerSimple::new(i2c); + + const I2C_ADDRESS: u8 = 0b010_0000; // MCP23008, depending on solder bridges + let mut lcd = match HD44780::new_i2c_mcp23008(i2c_busmanager.acquire_i2c(), I2C_ADDRESS, &mut delay) { + Ok(lcd) => lcd, + Err(_) => panic!("HD44780 init fail"), + }; + + lcd.reset(&mut delay).unwrap(); + lcd.clear(&mut delay).unwrap(); + lcd.set_display_mode( + DisplayMode { + display: Display::On, + cursor_visibility: Cursor::Invisible, + cursor_blink: CursorBlink::Off, + }, + &mut delay).unwrap(); + lcd.set_cursor_pos(0, &mut delay).unwrap(); + lcd.write_str(" HB9EGM ", &mut delay).unwrap(); + lcd.set_cursor_pos(40, &mut delay).unwrap(); + lcd.write_str(" 30m CW TX 2021 ", &mut delay).unwrap(); + delay.delay_ms(1_500u16); + + + let mut siclock = { + let shared = unsafe { &mut *SHARED.as_mut_ptr() }; + *shared = SharedWithISR { + state : State::new(), + last_sequence_state_change : 0, + cw_ptt_timestamp : 0, + cw_key_n, + ui, + cw_pwm, + cw_keyer : cw::Keyer::new(12, TICKS_PER_SECOND), + cw_paddle_tip, cw_paddle_ring, ptt_out_n, led + }; + + si_clock::SiClock::new(i2c_busmanager.acquire_i2c(), 0, shared.state.vfo()) + }; + + ui::update_disp(&mut lcd, &get_state_copy(), &mut delay); + + let mut last_encoder_count = qei.count(); + + { + let ticks = unsafe { &mut *TICK_COUNTER.as_mut_ptr() }; + *ticks = 0; + } + + { + let timer = unsafe { &mut *CLOCK_TIMER.as_mut_ptr() }; + *timer = Timer::tim2(dp.TIM2, &clocks, &mut rcc.apb1) + .start_count_down(TICKS_PER_SECOND.hz()); + timer.listen(Event::Update); + } + + unsafe { pac::NVIC::unmask(pac::Interrupt::TIM2); } + + let mut last_disp_update_counter = 1; + let mut previous_vfo = 0; + + loop { + let mut update_disp_required = false; + + let state = get_state_copy(); + + let encoder_count : u16 = qei.count(); + if encoder_count != last_encoder_count { + let delta = encoder_count.wrapping_sub(last_encoder_count); + let delta = if delta > 0x7FFF { delta as i32 - 0x10000 } else { delta as i32 }; + + cortex_m::interrupt::free(|_cs| { + let shared = unsafe { &mut *SHARED.as_mut_ptr() }; + shared.ui.update_encoder(&mut shared.state, delta); + if let Mode::CW(CWMode::Iambic) = shared.state.mode { + shared.cw_keyer.set_speed(shared.state.cw_wpm, TICKS_PER_SECOND) + } + }); + + siclock.set_vfo(state.vfo()); + update_disp_required = true; + } + + let vfo = state.vfo(); + if previous_vfo != vfo { + siclock.set_vfo(vfo); + } + previous_vfo = vfo; + + if last_disp_update_counter != state.update_disp_counter { + update_disp_required = true; + last_disp_update_counter = state.update_disp_counter; + } + + if update_disp_required { + ui::update_disp(&mut lcd, &state, &mut delay); + } + + last_encoder_count = encoder_count; + + cortex_m::asm::wfi(); + } +} + +#[interrupt] +fn TIM2() { + let timer = unsafe { &mut *CLOCK_TIMER.as_mut_ptr() }; + timer.clear_update_interrupt_flag(); + + let ticks = unsafe { &mut *TICK_COUNTER.as_mut_ptr() }; + *ticks += 1; + + let mut shared = unsafe { &mut *SHARED.as_mut_ptr() }; + let button_result = shared.ui.handle_buttons(&mut shared.state); + + if button_result.display_update { + shared.state.update_disp_counter += 1; + } + + let cw_paddle_tip_low = shared.cw_paddle_tip.is_low().unwrap(); + let cw_paddle_ring_low = shared.cw_paddle_ring.is_low().unwrap(); + + let cw_ptt_delay : u32 = TICKS_PER_SECOND * 800 / 1000; + let cw_ptt = match shared.state.mode { + Mode::CW(_) => { + if cw_paddle_tip_low || cw_paddle_ring_low { + shared.cw_ptt_timestamp = *ticks; + true + } + else { + shared.cw_ptt_timestamp + cw_ptt_delay > *ticks + } + } + }; + + let cw_beep = match shared.state.mode { + Mode::CW(CWMode::StraightKey) => cw_paddle_tip_low, + Mode::CW(CWMode::Iambic) => shared.cw_keyer.tick(*ticks, cw_paddle_tip_low, cw_paddle_ring_low), + }; + + let next_state = match shared.state.sequence_state { + SequenceState::Rx => { + shared.ptt_out_n.set_high().unwrap(); + if cw_ptt { + SequenceState::SwitchingCW + } + else { + SequenceState::Rx + } + }, + SequenceState::SwitchingCW => { + shared.ptt_out_n.set_low().unwrap(); + if cw_ptt { + SequenceState::TxCW + } + else { + SequenceState::Rx + } + }, + SequenceState::TxCW => { + shared.ptt_out_n.set_low().unwrap(); + if cw_ptt { + SequenceState::TxCW + } + else { + SequenceState::SwitchingCW + } + }, + }; + + match shared.state.sequence_state { + SequenceState::TxCW => { + if cw_beep { + shared.led.set_low().unwrap(); + shared.cw_pwm.on(); + shared.cw_key_n.set_low().unwrap(); + } + else { + shared.led.set_high().unwrap(); + shared.cw_pwm.off(); + shared.cw_key_n.set_high().unwrap(); + } + }, + _ => { + shared.led.set_high().unwrap(); + shared.cw_pwm.off(); + shared.cw_key_n.set_high().unwrap(); + }, + } + + const SWITCHING_DELAY : u32 = TICKS_PER_SECOND * 80 / 1000; + if shared.state.sequence_state != next_state && + shared.last_sequence_state_change + SWITCHING_DELAY <= *ticks { + shared.state.sequence_state = next_state; + shared.last_sequence_state_change = *ticks; + } +} + +#[cortex_m_rt::exception] +fn HardFault(ef: &ExceptionFrame) -> ! { + let periph = unsafe { cortex_m::Peripherals::steal() }; + let hfsr = periph.SCB.hfsr.read(); + let cfsr = periph.SCB.cfsr.read(); + + hprintln!("Hardfault {:x} {:x} at {:x}\n", hfsr, cfsr, ef.pc).unwrap(); + cortex_m::asm::bkpt(); + loop { } +} + +#[cortex_m_rt::exception] +fn DefaultHandler(irqn: i16) { + hprintln!("Unhandled exception (IRQn = {})", irqn).unwrap(); + cortex_m::asm::bkpt(); + loop { } +} diff --git a/sw/eval-clock-cw-tx/src/si_clock.rs b/sw/eval-clock-cw-tx/src/si_clock.rs new file mode 100644 index 0000000..a4b0e7a --- /dev/null +++ b/sw/eval-clock-cw-tx/src/si_clock.rs @@ -0,0 +1,132 @@ +/* + The MIT License (MIT) + + Copyright (c) 2020 Matthias P. Braendli + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ +use core::convert::TryInto; + +use si5351::{Si5351, Si5351Device}; +use embedded_hal::blocking::i2c::{WriteRead, Write}; + +const REF_CLOCK : u32 = 25_000_000; +const PLL_A_MULT : u32 = 32; + +fn gcd(x: u32, y: u32) -> u32 { + let mut x = x; + let mut y = y; + while y != 0 { + let t = y; + y = x % y; + x = t; + } + x +} + +fn clock_settings_for_pll(freq: u32, pll: u32) -> (u16, u32, u32) { + let a = pll / freq; + let b = pll - (a * freq); + let gcd = gcd(b, freq); + + let b = b / gcd; + let c = freq / gcd; + (a.try_into().unwrap(), b, c) +} + +fn clock_settings_with_pll_calculation(freq: u32) -> (u16, u8, u32, u32) { + let mut divider : u32 = 900_000_000 / freq; // Calculate the division ratio. 900,000,000 is the maximum internal + + if (divider % 2) == 1 { + divider -= 1 // Ensure an even integer division ratio + } + + let pll_freq = divider * freq; + // mult is an integer that must be in the range 15..90 + let mult = pll_freq / REF_CLOCK; + let l = pll_freq % REF_CLOCK; + + let denom = 1048575; + let num = f64::from(l) * f64::from(denom) / f64::from(REF_CLOCK); + + (divider.try_into().unwrap(), mult.try_into().unwrap(), num as u32, denom) +} + +fn set_bfo(siclock: &mut dyn Si5351, freq: u32) -> Result<(), si5351::Error> +{ + if freq == 0 { + siclock.set_clock_enabled(si5351::ClockOutput::Clk2, false); + } + else { + let (a, b, c) = clock_settings_for_pll(freq, PLL_A_MULT * REF_CLOCK); + siclock.setup_multisynth(si5351::Multisynth::MS2, a, b, c, si5351::OutputDivider::Div1)?; + siclock.select_clock_pll(si5351::ClockOutput::Clk2, si5351::PLL::A); + siclock.set_clock_enabled(si5351::ClockOutput::Clk2, true); + } + siclock.flush_clock_control(si5351::ClockOutput::Clk2) +} + +fn set_vfo(siclock: &mut dyn Si5351, freq: u32) +{ + let (div, mult, num, denom) = clock_settings_with_pll_calculation(freq); + + siclock.setup_pll(si5351::PLL::B, mult, num, denom).unwrap(); + siclock.setup_multisynth_int(si5351::Multisynth::MS0, div, si5351::OutputDivider::Div1).unwrap(); + siclock.select_clock_pll(si5351::ClockOutput::Clk0, si5351::PLL::B); + siclock.set_clock_enabled(si5351::ClockOutput::Clk0, true); + siclock.flush_clock_control(si5351::ClockOutput::Clk0).unwrap(); +} + +pub struct SiClock { + siclock : Si5351Device, +} + +impl SiClock + where + I2C: WriteRead + Write, +{ + pub fn new(i2c: I2C, bfo: u32, vfo: u32) -> SiClock { + let mut siclock = Si5351Device::new(i2c, false, REF_CLOCK); + siclock.init(si5351::CrystalLoad::_10).unwrap(); + + // See freqplan.py for Si5351 frequency plan + // CLK1 unused + siclock.setup_pll_int(si5351::PLL::A, 32).unwrap(); + + set_bfo(&mut siclock, bfo).unwrap(); + + siclock.reset_pll(si5351::PLL::A).unwrap(); + + set_vfo(&mut siclock, vfo); + + siclock.reset_pll(si5351::PLL::B).unwrap(); + + siclock.flush_output_enabled().unwrap(); + + SiClock{siclock} + } + + pub fn set_vfo(&mut self, freq: u32) { + set_vfo(&mut self.siclock, freq) + } + + pub fn set_bfo(&mut self, freq: u32) -> Result<(), si5351::Error> { + set_bfo(&mut self.siclock, freq) + } +} diff --git a/sw/eval-clock-cw-tx/src/state.rs b/sw/eval-clock-cw-tx/src/state.rs new file mode 100644 index 0000000..b3b0b7b --- /dev/null +++ b/sw/eval-clock-cw-tx/src/state.rs @@ -0,0 +1,83 @@ +const INITIAL_VFO : u32 = 10_100_000; + +// Defines which parameter is changed by the encoder +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum UISelection { + VFO, + Mode, +} + +#[derive(Clone, Copy)] +pub enum VFOSelection { + A, + B, +} + +#[derive(Clone)] +pub enum TuneSpeed { + Slow, + Mid, + Fast +} + +#[derive(PartialEq, Eq, Clone, Copy)] +pub enum CWMode { + StraightKey, + Iambic, +} + +#[derive(PartialEq, Eq, Clone, Copy)] +pub enum Mode { + CW(CWMode), +} + +#[derive(Clone, PartialEq, Eq)] +pub enum SequenceState { + Rx, + SwitchingCW, + TxCW, +} + +#[derive(Clone)] +pub struct State { + pub ui_sel : UISelection, + pub vfo_a : u32, + pub vfo_b : u32, + pub vfo_sel : VFOSelection, + pub mode : Mode, + pub tune_speed : TuneSpeed, + pub sequence_state : SequenceState, + pub update_disp_counter : u8, + pub cw_wpm : u32, +} + +impl State { + pub fn new() -> Self { + State { + ui_sel : UISelection::VFO, + mode : Mode::CW(CWMode::StraightKey), + vfo_sel : VFOSelection::A, + vfo_a : INITIAL_VFO, + vfo_b : INITIAL_VFO, + tune_speed : TuneSpeed::Mid, + sequence_state : SequenceState::Rx, + update_disp_counter : 0, + cw_wpm : 12, + } + } + + pub fn vfo(&self) -> u32 { + match self.vfo_sel { + VFOSelection::A => self.vfo_a, + VFOSelection::B => self.vfo_b, + } + } + + pub fn vfo_incr(&self) -> i32 { + match self.tune_speed { + TuneSpeed::Slow => 10, + TuneSpeed::Mid => 200, + TuneSpeed::Fast => 1000, + } + } +} diff --git a/sw/eval-clock-cw-tx/src/ui.rs b/sw/eval-clock-cw-tx/src/ui.rs new file mode 100644 index 0000000..564b7d1 --- /dev/null +++ b/sw/eval-clock-cw-tx/src/ui.rs @@ -0,0 +1,274 @@ +/* + The MIT License (MIT) + + Copyright (c) 2020 Matthias P. Braendli + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +use crate::state::*; + +use core::fmt; +use core::fmt::Write; + +use stm32f1xx_hal::{ + delay::Delay, + gpio::gpiob::*, + gpio::gpioc::*, + gpio::{Input, PullUp, Floating}, +}; + +use embedded_hal::digital::v2::InputPin; +use hd44780_driver::HD44780; + +#[derive(PartialEq, Eq, Clone, Copy)] +struct ButtonState { + pub a : bool, + pub b : bool, + pub c : bool, + pub d : bool, + pub e : bool, + pub enc : bool, +} + +impl ButtonState { + fn edge_detection(&self, old_state : &ButtonState) -> ButtonState { + ButtonState { + a : !old_state.a && self.a, + b : !old_state.b && self.b, + c : !old_state.c && self.c, + d : !old_state.d && self.d, + e : !old_state.e && self.e, + enc : !old_state.enc && self.enc, + } + } +} + +impl Default for ButtonState { + fn default() -> Self { + ButtonState { + a : false, + b : false, + c : false, + d : false, + e : false, + enc : false, + } + } +} + +impl fmt::Display for ButtonState { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}{}{}{}{}{}", + if self.a { "A" } else { "a" }, + if self.b { "B" } else { "b" }, + if self.c { "C" } else { "c" }, + if self.d { "D" } else { "d" }, + if self.e { "E" } else { "e" }, + if self.enc { "X" } else { "x" }) + } +} + +#[derive(Default)] +pub struct ButtonResult { + pub display_update : bool, +} + +pub struct UI { + btn0 : PB1>, + btn1 : PB0>, + + btn2 : PB12>, + btn3 : PB13>, + + btn_enc : PC15>, + + previous_button_state : ButtonState, +} + +impl UI { + pub fn new( + pb0: PB0>, + pb1: PB1>, + pb12: PB12>, + pb13: PB13>, + pc15 : PC15>) -> UI { + + UI { + btn0 : pb1, + btn1 : pb0, + btn2 : pb12, + btn3 : pb13, + btn_enc : pc15, + previous_button_state : ButtonState::default(), + } + } + + fn read_buttons(&mut self) -> ButtonState { + let mut buttons = ButtonState::default(); + + let b0_low = self.btn0.is_low().unwrap(); + let b1_low = self.btn1.is_low().unwrap(); + + if b0_low && b1_low { + buttons.e = true; + } + else if b0_low { + buttons.a = true; + } + else if b1_low { + buttons.b = true; + } + + if self.btn2.is_low().unwrap() { + buttons.c = true; + } + + if self.btn3.is_low().unwrap() { + buttons.d = true; + } + + if self.btn_enc.is_low().unwrap() { + buttons.enc = true; + } + + buttons + } + + pub fn handle_buttons(&mut self, state: &mut State) -> ButtonResult { + let mut result = ButtonResult::default(); + let button_state = self.read_buttons(); + let button_updates = button_state.edge_detection(&self.previous_button_state); + self.previous_button_state = button_state; + + if button_updates.a { + state.vfo_sel = match (state.ui_sel, state.vfo_sel) { + (UISelection::VFO, VFOSelection::A) => VFOSelection::B, + (UISelection::VFO, VFOSelection::B) => VFOSelection::A, + _ => state.vfo_sel.clone(), + }; + state.ui_sel = UISelection::VFO; + result.display_update = true; + } + + if button_updates.c { + let (new_ui_sel, new_filter_shift) = match (state.ui_sel, state.mode) { + (UISelection::Mode, Mode::CW(CWMode::StraightKey)) => (UISelection::Mode, Mode::CW(CWMode::Iambic)), + (UISelection::Mode, Mode::CW(CWMode::Iambic)) => (UISelection::Mode, Mode::CW(CWMode::StraightKey)), + (_, f) => (UISelection::Mode, f), + }; + + state.ui_sel = new_ui_sel; + state.mode = new_filter_shift; + + result.display_update = true; + } + + if button_updates.d { + state.tune_speed = match state.tune_speed { + TuneSpeed::Slow => TuneSpeed::Mid, + TuneSpeed::Mid => TuneSpeed::Fast, + TuneSpeed::Fast => TuneSpeed::Slow, + }; + result.display_update = true; + } + + if button_updates.enc { + match state.ui_sel { + UISelection::VFO => {}, + UISelection::Mode => { + state.mode = Mode::CW(CWMode::StraightKey); + }, + } + + result.display_update = true; + } + + result + } + + // Returns true if bfo must be reprogrammed + pub fn update_encoder(&mut self, state: &mut State, delta : i32) { + match state.ui_sel { + UISelection::VFO => { + match state.vfo_sel { + VFOSelection::A => { + state.vfo_a = (state.vfo_a as i32 + delta * state.vfo_incr()) as u32; + }, + VFOSelection::B => { + state.vfo_b = (state.vfo_b as i32 + delta * state.vfo_incr()) as u32; + }, + } + }, + UISelection::Mode => { + match state.mode { + Mode::CW(CWMode::Iambic) => { + let mut new_wpm = state.cw_wpm as i32 + delta / 4; + if new_wpm < 1 { + new_wpm = 1; + } + + let wpm = new_wpm as u32; + state.cw_wpm = wpm; + state.mode = Mode::CW(CWMode::Iambic); + }, + _ => { }, + } + }, + } + } +} + +pub fn update_disp(lcd: &mut HD44780, state: &State, delay: &mut Delay) +{ + let mut string = arrayvec::ArrayString::<[_; 16]>::new(); + + let disp_freq = state.vfo() as i32; + write!(string, "{:<05}.{:<03} ", disp_freq / 1000, disp_freq % 1000).unwrap(); + + write!(string, " CW{:<02}", state.cw_wpm).unwrap(); + + lcd.set_cursor_pos(0, delay).unwrap(); + lcd.write_str(&string, delay).unwrap(); + + string.clear(); + + match &state.vfo_sel { + VFOSelection::A => write!(string, "VFOa").unwrap(), + VFOSelection::B => write!(string, "VFOb").unwrap(), + } + + write!(string, " {}", if state.ui_sel == UISelection::Mode { ">" } else { " " }).unwrap(); + + let mode = match state.mode { + Mode::CW(CWMode::StraightKey) => "CWs", + Mode::CW(CWMode::Iambic) => "CWp", + }; + + let speed = match state.tune_speed { + TuneSpeed::Slow => "SLO", + TuneSpeed::Mid => "MID", + TuneSpeed::Fast => "FST", + }; + + write!(string, "{} {}", mode, speed).unwrap(); + + lcd.set_cursor_pos(40, delay).unwrap(); + lcd.write_str(&string, delay).unwrap(); +} -- cgit v1.2.3