aboutsummaryrefslogtreecommitdiffstats
path: root/sw/eval-clock-cw-tx/src/main.rs
blob: 2dce7bc778c7ea4ee98219c7165e1a63ae31d514 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
/*
    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 usb;
pub mod feldhell_font;
pub mod cw;
pub mod state;
pub mod si_clock;

use state::*;

const TICKS_PER_SECOND : u32 = 100;

struct SharedWithISR {
    state : State,
    last_sequence_state_change : u32,
    feldhell_ptt : bool,
    cw_ptt_timestamp : u32,
    cw_key_out_n : gpio::gpioa::PA15<gpio::Output<gpio::PushPull>>,
    ui : ui::UI,
    cw_pwm: cw::CWPWM,
    cw_keyer: cw::Keyer,
    cw_paddle_tip: gpio::gpiob::PB8<gpio::Input<gpio::PullUp>>,
    cw_paddle_ring: gpio::gpiob::PB9<gpio::Input<gpio::PullUp>>,
    ptt_out: gpio::gpiob::PB3<gpio::Output<gpio::PushPull>>,
    seq_switch: gpio::gpiob::PB5<gpio::Output<gpio::PushPull>>,
    led : gpio::gpiob::PB14<gpio::Output<gpio::PushPull>>,
}

static mut SHARED: MaybeUninit<SharedWithISR> = MaybeUninit::uninit();
static mut CLOCK_TIMER: MaybeUninit<CountDownTimer<pac::TIM2>> = MaybeUninit::uninit();
static mut TICK_COUNTER: MaybeUninit<u32> = 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 mut rcc = dp.RCC.constrain();
    let mut afio = dp.AFIO.constrain(&mut rcc.apb2);
    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 = 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);

    let mut timer4 = Timer::tim4(dp.TIM4, &clocks, &mut rcc.apb1)
        .start_count_down(usb::TIMER_FREQ_HZ.hz());
    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 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_out_n = pa15.into_push_pull_output_with_state(&mut gpioa.crh, gpio::State::High);
    let ptt_out = pb3.into_push_pull_output_with_state(&mut gpiob.crl, gpio::State::Low);
    let seq_switch = gpiob.pb5.into_push_pull_output_with_state(&mut gpiob.crl, gpio::State::Low);

    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,
            feldhell_ptt : false,
            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,
        };

        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::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_usb_freq = usb.frequency;
    let mut previous_vfo = 0;
    let mut previous_state = SequenceState::Rx;

    loop {
        let mut update_disp_required = false;

        usb.handle();

        if previous_usb_freq != usb.frequency {
            previous_usb_freq = usb.frequency;

            cortex_m::interrupt::free(|_cs| {
                let shared = unsafe { &mut *SHARED.as_mut_ptr() };
                shared.state.set_vfo(usb.frequency);
            });

            update_disp_required = true;
        }

        let state = cortex_m::interrupt::free(|_cs| unsafe {
            let shared = SHARED.as_mut_ptr();
            (*shared).feldhell_ptt = usb.is_transmit();
            (*shared).state.clone()
        });

        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.sequence_state.clone()) {
            (SequenceState::Rx, SequenceState::Switching(_)) => usb.send_transmit(),
            (SequenceState::Switching(_), SequenceState::Rx) => usb.send_receive(),
            _ => (),
        }

        let vfo = state.vfo_display();
        if previous_vfo != vfo || previous_state != state.sequence_state {
            siclock.set_vfo(state.vfo_siclock());
        }
        previous_vfo = vfo;
        previous_state = state.sequence_state.clone();

        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();
    }
}

#[allow(non_snake_case)]
#[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 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.feldhell_ptt
        }
    };

    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),
        Mode::FeldHell => false, // Done in usb.c
    };

    let next_state = match shared.state.sequence_state {
        SequenceState::Rx => {
            shared.ptt_out.set_low().unwrap();
            shared.seq_switch.set_low().unwrap();
            if ptt {
                if shared.state.mode == Mode::FeldHell {
                    SequenceState::Switching(SequenceMode::FeldHell)
                }
                else {
                    SequenceState::Switching(SequenceMode::CW)
                }
            }
            else {
                SequenceState::Rx
            }
        },
        SequenceState::Switching(m) => {
            shared.ptt_out.set_low().unwrap();
            shared.seq_switch.set_high().unwrap();
            if ptt {
                SequenceState::Tx(m)
            }
            else {
                SequenceState::Rx
            }
        },
        SequenceState::Tx(m) => {
            shared.ptt_out.set_high().unwrap();
            shared.seq_switch.set_high().unwrap();
            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().unwrap();
                shared.led.set_low().unwrap();
            }
            else {
                shared.cw_pwm.off();
                shared.cw_key_out_n.set_high().unwrap();
                shared.led.set_high().unwrap();
            }
        },
        SequenceState::Tx(SequenceMode::FeldHell) => {
            shared.led.set_low().unwrap();
        },
        _ => {
            shared.led.set_high().unwrap();
            shared.cw_pwm.off();
            shared.cw_key_out_n.set_high().unwrap();
        },
    }

    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]
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 { }
}

#[allow(non_snake_case)]
#[cortex_m_rt::exception]
fn DefaultHandler(irqn: i16) {
    hprintln!("Unhandled exception (IRQn = {})", irqn).unwrap();
    cortex_m::asm::bkpt();
    loop { }
}