main.rs 13 KB

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