main.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include "mbed.h"
  2. DigitalOut status_led(LED_BLUE);
  3. DigitalOut error_led(LED_RED);
  4. extern "C" void RTC_IRQHandler(void) {
  5. error_led = 0;
  6. }
  7. extern "C" void RTC_Seconds_IRQHandler(void) {
  8. error_led = 0;
  9. }
  10. extern "C" void HardFault_Handler(void) {
  11. error_led = 0;
  12. }
  13. extern "C" void NMI_Handler_Handler(void) {
  14. error_led = 0;
  15. }
  16. void rtc_init(void) {
  17. // enable the clock to SRTC module register space
  18. SIM->SCGC6 |= SIM_SCGC6_RTC_MASK;
  19. SIM->SOPT1 = (SIM->SOPT1 & ~SIM_SOPT1_OSC32KSEL_MASK) | SIM_SOPT1_OSC32KSEL(0);
  20. // disable interrupts
  21. NVIC_DisableIRQ(RTC_Seconds_IRQn);
  22. NVIC_DisableIRQ(RTC_IRQn);
  23. // Reset
  24. RTC->CR = RTC_CR_SWR_MASK;
  25. RTC->CR &= ~RTC_CR_SWR_MASK;
  26. // Allow write
  27. RTC->CR = RTC_CR_UM_MASK | RTC_CR_SUP_MASK;
  28. NVIC_EnableIRQ(RTC_Seconds_IRQn);
  29. NVIC_EnableIRQ(RTC_Seconds_IRQn);
  30. printf("LR: 0x%x\n", RTC->LR);
  31. printf("CR: 0x%x\n", RTC->CR);
  32. wait(1);
  33. if (RTC->SR & RTC_SR_TIF_MASK){
  34. RTC->TSR = 0;
  35. }
  36. RTC->TCR = 0;
  37. // After setting this bit, wait the oscillator startup time before enabling
  38. // the time counter to allow the clock time to stabilize
  39. RTC->CR |= RTC_CR_OSCE_MASK;
  40. for (volatile int i=0; i<0x600000; i++);
  41. //enable seconds interrupts
  42. RTC->IER |= RTC_IER_TSIE_MASK;
  43. // enable time counter
  44. RTC->SR |= RTC_SR_TCE_MASK;
  45. }
  46. int main() {
  47. error_led = 1;
  48. rtc_init();
  49. while (true) {
  50. wait(1);
  51. status_led = !status_led;
  52. printf("%u\n", RTC->TSR);
  53. }
  54. }