/* The MIT License (MIT) Copyright (c) 2023 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 core::fmt::Write; use arrayvec::ArrayString; use cortex_m_rt::ExceptionFrame; use cortex_m_semihosting::hprintln; use panic_semihosting as _; use stm32f1xx_hal::{ prelude::*, pac, pac::interrupt, i2c, gpio, gpio::PinState, timer::{CounterHz, Timer, Event}, qei::QeiOptions, }; use hd44780_driver::{Cursor, CursorBlink, Display, DisplayMode, HD44780}; pub mod ui; pub mod usb; pub mod feldhell_font; pub mod cw; pub mod state; pub mod si_clock; use state::*; // One WSPR symbol is 256/375s const WSPR_SYMBOL_TICKS : u32 = 256; // TIM2 runs at that rate, and increments TICK_COUNTER const TICKS_PER_SECOND : u32 = 375; // See README.md const WSPR_SYMBOLS : [u8; 162] = [ 1, 1, 2, 0, 0, 2, 2, 2, 1, 2, 0, 0, 3, 3, 1, 0, 2, 2, 3, 2, 0, 1, 0, 1, 3, 3, 1, 0, 2, 2, 0, 0, 2, 0, 3, 2, 0, 3, 0, 1, 2, 0, 2, 0, 2, 0, 3, 2, 1, 1, 0, 2, 3, 3, 0, 3, 0, 2, 2, 3, 1, 0, 3, 0, 2, 2, 0, 1, 3, 2, 3, 0, 3, 2, 3, 0, 1, 0, 0, 3, 0, 0, 1, 2, 1, 3, 0, 2, 2, 1, 3, 2, 3, 0, 3, 2, 0, 0, 3, 2, 0, 0, 0, 2, 3, 2, 0, 1, 2, 0, 1, 1, 1, 0, 3, 1, 2, 2, 1, 1, 0, 3, 2, 2, 2, 1, 1, 1, 0, 0, 2, 2, 2, 3, 0, 3, 2, 2, 3, 3, 0, 0, 2, 2, 2, 2, 0, 3, 3, 0, 1, 2, 1, 3, 0, 0, 0, 1, 1, 2, 2, 0]; struct SharedWithISR { state: State, last_sequence_state_change: u32, usb_data_transmit: usb::Transmit, cw_ptt_timestamp: u32, cw_key_out_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: gpio::gpiob::PB3>, seq_switch: gpio::gpiob::PB5>, led: gpio::gpiob::PB14>, wspr_symbol_ix: usize, wspr_symbol_duration_ticks: u32, } 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() }) } #[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 rcc = dp.RCC.constrain(); let mut afio = dp.AFIO.constrain(); let clocks = rcc.cfgr .use_hse(16.MHz()) .sysclk(48.MHz()) .pclk1(24.MHz()) .adcclk(2.MHz()) .freeze(&mut flash.acr); assert!(clocks.usbclk_valid()); let mut delay = cp.SYST.delay(&clocks); delay.delay_ms(200u16); let mut gpioa = dp.GPIOA.split(); let mut gpiob = dp.GPIOB.split(); let mut gpioc = dp.GPIOC.split(); let mut timer4 = Timer::new(dp.TIM4, &clocks).counter_hz(); timer4.start(usb::TIMER_FREQ_HZ.Hz()).unwrap(); timer4.listen(Event::Update); let usb_dm = gpioa.pa11; let usb_dp = gpioa.pa12.into_floating_input(&mut gpioa.crh); let mut usb = usb::USBData::new(timer4, dp.USB, usb_dm, usb_dp); usb::enable_interrupts(); // 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 pwm = dp.TIM1.pwm_hz(pa8, &mut afio.mapr, cw::SIDETONE_FREQ.Hz(), &clocks); let channel = pwm.split(); cw::CWPWM::new(channel) }; 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(); let (pa15, pb3, _pb4) = afio.mapr.disable_jtag(gpioa.pa15, gpiob.pb3, gpiob.pb4); let cw_key_out_n = pa15.into_push_pull_output_with_state(&mut gpioa.crh, PinState::High); let ptt_out = pb3.into_push_pull_output_with_state(&mut gpiob.crl, PinState::Low); let seq_switch = gpiob.pb5.into_push_pull_output_with_state(&mut gpiob.crl, PinState::Low); let c1 = gpioa.pa6; let c2 = gpioa.pa7; let qei = Timer::new(dp.TIM3, &clocks) .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, /* 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 TX 2023 ", &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, usb_data_transmit: usb::Transmit::None, cw_ptt_timestamp: 0, cw_key_out_n, ui, cw_pwm, cw_keyer: cw::Keyer::new(12, TICKS_PER_SECOND), cw_paddle_tip, cw_paddle_ring, ptt_out, seq_switch, led, wspr_symbol_ix: 0, wspr_symbol_duration_ticks: 0, }; si_clock::SiClock::new(i2c_busmanager.acquire_i2c(), 0, shared.state.vfo_display()) }; ui::update_disp(&mut lcd, unsafe { &(*SHARED.as_ptr()).state }, &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::new(dp.TIM2, &clocks).counter_hz(); timer.start(TICKS_PER_SECOND.Hz()).unwrap(); timer.listen(Event::Update); } unsafe { pac::NVIC::unmask(pac::Interrupt::TIM2); } let mut last_disp_update_counter = 1; let mut previous_vfo = 0; let mut previous_state = SequenceState::Rx; const MESSAGE_LEN: usize = 32; let mut usb_message: ArrayString:: = ArrayString::new(); loop { usb.handle(); let (state_copy, update_siclock_required) = cortex_m::interrupt::free(|_cs| { let shared = unsafe { &mut *SHARED.as_mut_ptr() }; if shared.wspr_symbol_ix == WSPR_SYMBOLS.len() && shared.wspr_symbol_duration_ticks == WSPR_SYMBOL_TICKS { usb.clear_transmit(); shared.wspr_symbol_ix = 0; shared.wspr_symbol_duration_ticks = 0; } let mut update_siclock_required = false; match shared.state.mode { Mode::CW(_) => { let vfo = shared.state.vfo_display(); if previous_vfo != vfo || previous_state != shared.state.sequence_state { shared.state.set_vfo(vfo); update_siclock_required = true; } previous_vfo = vfo; } Mode::FeldHell => { if let Some(f) = usb.take_frequency() { shared.state.set_vfo(f); update_siclock_required = true; } }, Mode::WSPR => { if let Some(f) = usb.take_frequency() { shared.state.set_vfo(f); update_siclock_required = true; } if shared.state.wspr_freq_offset_updated { update_siclock_required = true; } shared.state.wspr_freq_offset_updated = false; } }; shared.usb_data_transmit = usb.transmit(); (shared.state.clone(), update_siclock_required) }); if update_siclock_required { let f = state_copy.vfo_siclock() * 100 + match state_copy.sequence_state { SequenceState::Tx(SequenceMode::WSPR) => state_copy.wspr_freq_offset_centihz, _ => 0, }; usb_message.clear(); if write!(&mut usb_message, "F{}\n", f).is_ok() { usb.send_message(usb_message.as_bytes()); } siclock.set_vfo_centihertz(f); } previous_state = state_copy.sequence_state.clone(); let mut update_disp_required = update_siclock_required; 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) } }); update_disp_required = true; } match (previous_state.clone(), state_copy.sequence_state.clone()) { (SequenceState::Rx, SequenceState::Switching(_)) => usb.send_transmit(), (SequenceState::Switching(_), SequenceState::Rx) => usb.send_receive(), _ => (), } if last_disp_update_counter != state_copy.update_disp_counter { update_disp_required = true; last_disp_update_counter = state_copy.update_disp_counter; } if update_disp_required { ui::update_disp(&mut lcd, &state_copy, &mut delay); } last_encoder_count = encoder_count; cortex_m::asm::wfi(); } } #[allow(non_snake_case)] #[interrupt] fn TIM2() { let timer = unsafe { &mut *CLOCK_TIMER.as_mut_ptr() }; timer.clear_interrupt(Event::Update); 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(); let cw_paddle_ring_low = shared.cw_paddle_ring.is_low(); let cw_ptt_delay : u32 = TICKS_PER_SECOND * 800 / 1000; let 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 } }, Mode::FeldHell => { shared.usb_data_transmit == usb::Transmit::FELDHELL } Mode::WSPR => { if shared.usb_data_transmit == usb::Transmit::WSPR && shared.wspr_symbol_ix != WSPR_SYMBOLS.len() && shared.wspr_symbol_duration_ticks != WSPR_SYMBOL_TICKS { true } else { false } } }; 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), _ => false, }; let next_state = match shared.state.sequence_state { SequenceState::Rx => { shared.ptt_out.set_low(); shared.seq_switch.set_low(); if ptt { match shared.state.mode { state::Mode::WSPR => SequenceState::Switching(SequenceMode::WSPR), state::Mode::FeldHell => SequenceState::Switching(SequenceMode::FeldHell), state::Mode::CW(_) => SequenceState::Switching(SequenceMode::CW), } } else { SequenceState::Rx } }, SequenceState::Switching(m) => { shared.ptt_out.set_low(); shared.seq_switch.set_high(); if ptt { SequenceState::Tx(m) } else { SequenceState::Rx } }, SequenceState::Tx(m) => { shared.ptt_out.set_high(); shared.seq_switch.set_high(); if ptt { SequenceState::Tx(m) } else { SequenceState::Switching(m) } }, }; match shared.state.sequence_state { SequenceState::Tx(SequenceMode::CW) => { if cw_beep { shared.cw_pwm.on(); shared.cw_key_out_n.set_low(); shared.led.set_low(); } else { shared.cw_pwm.off(); shared.cw_key_out_n.set_high(); shared.led.set_high(); } }, SequenceState::Tx(SequenceMode::FeldHell) => { shared.led.set_low(); }, SequenceState::Tx(SequenceMode::WSPR) => { shared.cw_key_out_n.set_low(); shared.cw_pwm.off(); shared.led.set_low(); if shared.wspr_symbol_duration_ticks < WSPR_SYMBOL_TICKS { shared.wspr_symbol_duration_ticks += 1; } if shared.wspr_symbol_duration_ticks == WSPR_SYMBOL_TICKS { if shared.wspr_symbol_ix < WSPR_SYMBOLS.len() { shared.state.wspr_freq_offset_centihz = WSPR_SYMBOLS[shared.wspr_symbol_ix] as u32 * 100 * 375 / 256; shared.state.wspr_freq_offset_updated = true; shared.wspr_symbol_ix += 1; } else { shared.state.wspr_freq_offset_centihz = 0; } if shared.wspr_symbol_ix != WSPR_SYMBOLS.len() { shared.wspr_symbol_duration_ticks = 0; } } }, _ => { shared.led.set_high(); shared.cw_pwm.off(); shared.cw_key_out_n.set_high(); }, } const SWITCHING_DELAY : u32 = TICKS_PER_SECOND * 40 / 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; } } #[allow(non_snake_case)] #[cortex_m_rt::exception] unsafe 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()); cortex_m::asm::bkpt(); loop { } } #[allow(non_snake_case)] #[cortex_m_rt::exception] unsafe fn DefaultHandler(irqn: i16) { hprintln!("Unhandled exception (IRQn = {})", irqn); cortex_m::asm::bkpt(); loop { } }