main_rtic.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. #![cfg_attr(test, allow(unused_imports))]
  2. #![cfg_attr(not(test), no_std)]
  3. #![cfg_attr(not(test), no_main)]
  4. #![feature(half_open_range_patterns)]
  5. #![feature(exclusive_range_pattern)]
  6. #![feature(destructuring_assignment)]
  7. #![allow(dead_code)]
  8. // custom panic handler
  9. #[cfg(not(test))]
  10. use core::panic::PanicInfo;
  11. use core::{cell::RefCell, ops::DerefMut};
  12. use cortex_m::interrupt::{Mutex, free};
  13. use stm32l4xx_hal::{delay::Delay, device::{I2C1, TIM2, TIM7}, gpio::{
  14. Alternate, Edge, Floating, Input, OpenDrain, Output, PullUp, PushPull, AF4, PA3, PB5, PC15,
  15. }, gpio::{State, PA10, PA9}, i2c::I2c, prelude::*, rcc, rng::Rng, timer::{Timer, Event}};
  16. mod ds3231;
  17. mod nixie;
  18. mod pca9685;
  19. mod tusb322;
  20. use nixie::*;
  21. type FaultLed = PC15<Output<PushPull>>;
  22. static FAULT_LED: Mutex<RefCell<Option<FaultLed>>> = Mutex::new(RefCell::new(None));
  23. #[rtic::app(device = stm32l4xx_hal::pac, peripherals = true)]
  24. const APP: () = {
  25. struct Resources {
  26. #[init(Clock::default())]
  27. clock: Clock,
  28. // Late initialized resources (shared peripherals)
  29. rtc_int: PB5<Input<Floating>>,
  30. fault_int: PA3<Input<PullUp>>,
  31. i2c: I2c<I2C1, (PA9<Alternate<AF4, Output<OpenDrain>>>,PA10<Alternate<AF4,Output<OpenDrain>>>)>,
  32. refresh_timer: Timer<TIM2>,
  33. cycle_timer: Timer<TIM7>,
  34. delay_timer: Delay,
  35. rng: Rng,
  36. }
  37. #[init(spawn = [start_cycle])]
  38. fn init(ctx: init::Context) -> init::LateResources {
  39. let mut dp = ctx.device;
  40. let cp = ctx.core;
  41. // Consume the raw peripheral and return a new object that implements a higher level API
  42. let mut flash = dp.FLASH.constrain();
  43. let mut rcc = dp.RCC.constrain();
  44. let mut pwr = dp.PWR.constrain(&mut rcc.apb1r1);
  45. // Configure clocks to run at maximum frequency off internal oscillator
  46. let clocks = rcc
  47. .cfgr
  48. .pll_source(rcc::PllSource::HSI16)
  49. .sysclk(64.mhz())
  50. .hclk(64.mhz())
  51. .pclk1(64.mhz())
  52. .pclk2(64.mhz())
  53. .hsi48(true)
  54. .freeze(&mut flash.acr, &mut pwr);
  55. // Configure delay timer that operates off systick timer
  56. let mut delay_timer = Delay::new(cp.SYST, clocks);
  57. // Split GPIO peripheral into independent pins and registers
  58. let mut gpioa = dp.GPIOA.split(&mut rcc.ahb2);
  59. let mut gpiob = dp.GPIOB.split(&mut rcc.ahb2);
  60. let mut gpioc = dp.GPIOC.split(&mut rcc.ahb2);
  61. // Configure high voltage PSU enable pin on PA2
  62. let mut hv_enable = gpioa.pa2.into_push_pull_output_with_state(&mut gpioa.moder, &mut gpioa.otyper, State::Low);
  63. // Configure serial port
  64. // let tx = gpiob.pb6.into_af7(&mut gpiob.moder, &mut gpiob.afrl);
  65. // let rx = gpiob.pb7.into_af7(&mut gpiob.moder, &mut gpiob.afrl);
  66. // let _serial = Serial::usart1(
  67. // dp.USART1,
  68. // (tx, rx),
  69. // Config::default().baudrate(115_200.bps()),
  70. // clocks,
  71. // &mut rcc.apb2,
  72. // );
  73. // Configure fault LED output on PC15
  74. let fault_led = gpioc.pc15.into_push_pull_output_with_state(&mut gpioc.moder, &mut gpioc.otyper, State::Low);
  75. // Store fault LED in static singleton so that it's accessible from anywhere
  76. free(|cs| {
  77. FAULT_LED.borrow(cs).replace(Some(fault_led));
  78. });
  79. // Configure fault input interrupt on PA3
  80. let mut fault_int = gpioa.pa3.into_pull_up_input(&mut gpioa.moder, &mut gpioa.pupdr);
  81. fault_int.make_interrupt_source(&mut dp.SYSCFG, &mut rcc.apb2);
  82. fault_int.enable_interrupt(&mut dp.EXTI);
  83. fault_int.trigger_on_edge(&mut dp.EXTI, Edge::FALLING);
  84. // Sanity check that fault pin isn't already set (active low)
  85. if fault_int.is_low().unwrap() {
  86. panic!();
  87. }
  88. // Enable RNG peripheral
  89. let rng = dp.RNG.enable(&mut rcc.ahb2, clocks);
  90. // Configure I2C SCL pin
  91. let scl = gpioa.pa9.into_open_drain_output(&mut gpioa.moder, &mut gpioa.otyper);
  92. let scl = scl.into_af4(&mut gpioa.moder, &mut gpioa.afrh);
  93. // Configure I2C SDA pin
  94. let sda = gpioa.pa10.into_open_drain_output(&mut gpioa.moder, &mut gpioa.otyper);
  95. let sda = sda.into_af4(&mut gpioa.moder, &mut gpioa.afrh);
  96. // Initialize I2C (configured for 1Mhz, but actually runs at 600kHz)
  97. let mut i2c = I2c::i2c1(dp.I2C1, (scl, sda), 1.mhz(), clocks, &mut rcc.apb1r1);
  98. // Initialize TUSB322 (USB Type-C configuration chip)
  99. tusb322::init(TUSB322_ADDR, &mut i2c);
  100. // Initialize DS3231 (RTC)
  101. ds3231::init(DS3231_ADDR, &mut i2c);
  102. // ds3231::set_date(DS3231_ADDR, &mut i2c, ds3231::Weekday::Wednesday, 15, 9, 21, 20);
  103. // ds3231::set_time(DS3231_ADDR, &mut i2c, 00, 37, 12);
  104. // Configure input interrupt pin from DS3231 on PB5
  105. // Interrupt is pulled high, with open drain on DS3231
  106. // Interrupt enable is automatically handled by RTIC's #[task]
  107. let mut rtc_int = gpiob.pb5.into_floating_input(&mut gpiob.moder, &mut gpiob.pupdr);
  108. rtc_int.make_interrupt_source(&mut dp.SYSCFG, &mut rcc.apb2);
  109. rtc_int.enable_interrupt(&mut dp.EXTI);
  110. rtc_int.trigger_on_edge(&mut dp.EXTI, Edge::FALLING);
  111. // Configure DAC AMP enable pin for AD8591 on PB1
  112. let mut _dac_enable = gpiob.pb1.into_push_pull_output_with_state(&mut gpiob.moder, &mut gpiob.otyper, State::High);
  113. // Configure DAC VIN for AD8591 on PA5
  114. // Note that this pin should actually be configured as analog output (for DAC)
  115. // but stm32l4xx_hal doesn't have support for the DAC as of now. We also currently
  116. // set the output to only the highest possible voltage, so the same functionality
  117. // can be achieved by configuring the pin as a digital output set to high.
  118. let mut _dac_output = gpioa.pa5.into_push_pull_output_with_state(&mut gpioa.moder, &mut gpioa.otyper, State::High);
  119. // Configure PWM enable pin (active low) for PCA9685 on PA7
  120. let mut pwm_enable = gpioa.pa7.into_push_pull_output_with_state(&mut gpioa.moder, &mut gpioa.otyper, State::High);
  121. // Initialize the PCA9685 display refresh timer
  122. // Interrupt enable is automatically handled by RTIC's #[task]
  123. let refresh_timer = Timer::tim2(dp.TIM2, nixie::DISPLAY_REFRESH_FPS.hz(), clocks, &mut rcc.apb1r1);
  124. // Initiaize display cycle timer
  125. // Interrupt enable is automatically handled by RTIC's #[task]
  126. let cycle_timer = Timer::tim7(dp.TIM7, (1000 / nixie::CYCLE_FADE_DURATION_MS).hz(), clocks, &mut rcc.apb1r1);
  127. // Small delay to ensure that PCA9685 is fully powered on before writing to it
  128. delay_timer.delay_us(10_u32);
  129. // Initialize PCA9685 (PWM driver)
  130. pca9685::init(PCA9685_ALL_CALL, &mut i2c);
  131. // Enable PWM output after PCA9685 has been initialized
  132. pwm_enable.set_low().unwrap();
  133. // Enable the high voltage power supply last
  134. hv_enable.set_high().unwrap();
  135. // Spawn tasks to cycle through all tubes on powerup
  136. ctx.spawn.start_cycle(0).unwrap();
  137. ctx.spawn.start_cycle(1).unwrap();
  138. ctx.spawn.start_cycle(2).unwrap();
  139. ctx.spawn.start_cycle(3).unwrap();
  140. init::LateResources { rtc_int, fault_int, i2c, refresh_timer, cycle_timer, delay_timer, rng }
  141. }
  142. #[idle(spawn = [start_cycle], resources = [delay_timer, rng])]
  143. fn idle(ctx: idle::Context) -> ! {
  144. let idle::Resources {delay_timer, rng} = ctx.resources;
  145. loop {
  146. // Delay before cycling digits to prevent cathode poisoning
  147. delay_timer.delay_ms(CYCLE_REFRESH_INTERVAL * 1000);
  148. // Choose a random tube to cycle
  149. let tube = (rng.get_random_data() % 4) as usize;
  150. ctx.spawn.start_cycle(tube).unwrap();
  151. }
  152. }
  153. // Interrupt handler for 1HZ signal from offchip RTC (DS3231)
  154. #[task(binds = EXTI9_5, priority = 1, resources = [clock, rtc_int, i2c, refresh_timer])]
  155. fn rtc_interrupt(ctx: rtc_interrupt::Context) {
  156. let rtc_interrupt::Resources {mut clock, rtc_int, mut i2c, mut refresh_timer} = ctx.resources;
  157. let (mut second, mut minute, mut hour) = (0, 0, 0);
  158. let (mut weekday, mut day, mut month) = (ds3231::Weekday::Sunday, 0, 0);
  159. // Lower priority task requires a critical section to access shared peripheral
  160. i2c.lock(|i2c| {
  161. // Read new time from DS3231
  162. (second, minute, hour) = ds3231::get_time(DS3231_ADDR, i2c);
  163. (weekday, day, month, ..) = ds3231::get_date(DS3231_ADDR, i2c);
  164. });
  165. // Calculate new values and account for DST
  166. let hour = if ds3231::in_dst(weekday, day, month, hour) { (hour + 1) % 12 } else { hour % 12 };
  167. let hour = if hour == 0 { 12 } else { hour };
  168. // Lower priority task requires a critical section to access shared peripheral
  169. clock.lock(|clock| {
  170. // Trigger the processing of a new time value
  171. clock.rtc_tick(second, minute, hour);
  172. });
  173. // Start the refresh timer to update the display
  174. // Lower priority task requires a critical section to access shared peripheral
  175. refresh_timer.lock(|refresh_timer| {
  176. refresh_timer.listen(Event::TimeOut);
  177. });
  178. // Clear the interrupt flag for the timer
  179. rtc_int.clear_interrupt_pending_bit();
  180. }
  181. // Interrupt handler for fault interrupt from USB monitor (TUSB322)
  182. // Configured as priority 4 for highest priority (pre-empts all other interrupts)
  183. #[task(binds = EXTI3, priority = 4, resources = [fault_int])]
  184. fn fault_interrupt(ctx: fault_interrupt::Context) {
  185. let fault_interrupt::Resources {fault_int} = ctx.resources;
  186. if fault_int.check_interrupt() {
  187. fault_int.clear_interrupt_pending_bit();
  188. panic!();
  189. }
  190. }
  191. // Interrupt handler for internal timer that drives display refresh rate
  192. #[task(binds = TIM2, priority = 3, resources = [clock, i2c, refresh_timer])]
  193. fn refresh_interrupt(ctx: refresh_interrupt::Context) {
  194. let refresh_interrupt::Resources {clock, refresh_timer, i2c} = ctx.resources;
  195. // Compute updates for non-static digits
  196. let updated = clock.fps_tick();
  197. // Write new values if values have changed, otherwise disable the refresh timer
  198. if updated {
  199. clock.write_i2c(i2c);
  200. refresh_timer.clear_interrupt(Event::TimeOut);
  201. } else {
  202. refresh_timer.unlisten(Event::TimeOut);
  203. }
  204. }
  205. // Interrupt handler for internal timer that drives individual digits within a cycle sequence
  206. #[task(binds = TIM7, priority = 2, resources = [clock, refresh_timer, cycle_timer])]
  207. fn cycle_interrupt(ctx: cycle_interrupt::Context) {
  208. let cycle_interrupt::Resources {mut clock, mut refresh_timer, cycle_timer} = ctx.resources;
  209. let mut cycle_ended = true;
  210. // Lower priority task requires a critical section to access shared data
  211. clock.lock(|clock| {
  212. cycle_ended = clock.cycle_tick();
  213. });
  214. // Trigger the next step in the cycling sequence
  215. if cycle_ended {
  216. cycle_timer.unlisten(Event::TimeOut);
  217. } else {
  218. cycle_timer.clear_interrupt(Event::TimeOut);
  219. }
  220. // Start the refresh timer to update the display
  221. // Lower priority task requires a critical section to access shared peripheral
  222. refresh_timer.lock(|refresh_timer| {
  223. refresh_timer.listen(Event::TimeOut);
  224. });
  225. }
  226. // Trigger the start of a new cycle sequence
  227. #[task(resources = [clock, cycle_timer], priority = 2, capacity = 4)]
  228. fn start_cycle(ctx: start_cycle::Context, tube: usize) {
  229. let start_cycle::Resources {mut clock, cycle_timer} = ctx.resources;
  230. // Lower priority task requires a critical section to access shared data
  231. clock.lock(|clock| {
  232. // Trigger the start of a cycling sequence
  233. clock.cycle_start(tube);
  234. });
  235. // Start the timer to cycle through individual digits
  236. cycle_timer.listen(Event::TimeOut);
  237. }
  238. // RTIC requires that unused interrupts are declared in an extern block when
  239. // using software tasks; these free interrupts will be used to dispatch the
  240. // software tasks.
  241. extern "C" {
  242. fn TSC();
  243. fn LCD();
  244. fn AES();
  245. }
  246. };
  247. // Helper function to set onboard LED state
  248. fn set_fault_led(state: State) {
  249. free(|cs| {
  250. let mut led_ref = FAULT_LED.borrow(cs).borrow_mut();
  251. if let Some(ref mut led) = led_ref.deref_mut() {
  252. match state {
  253. State::High => led.set_high().unwrap(),
  254. State::Low => led.set_low().unwrap(),
  255. };
  256. }
  257. });
  258. }
  259. // Custom panic handler
  260. #[panic_handler]
  261. #[cfg(not(test))]
  262. fn panic(_info: &PanicInfo) -> ! {
  263. set_fault_led(State::High);
  264. loop {
  265. continue;
  266. }
  267. }