main.rs 12 KB

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