main.rs 13 KB

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