main.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. #include <stm32f10x.h>
  2. #include <stdio.h>
  3. #include <time.h>
  4. void initGPIO()
  5. {
  6. RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
  7. GPIO_InitTypeDef GPIO_Config;
  8. /* USART1 Tx */
  9. GPIO_Config.GPIO_Pin = GPIO_Pin_9;
  10. GPIO_Config.GPIO_Mode = GPIO_Mode_AF_PP;
  11. GPIO_Config.GPIO_Speed = GPIO_Speed_50MHz;
  12. GPIO_Init(GPIOA, &GPIO_Config);
  13. /* USART1 Rx */
  14. GPIO_Config.GPIO_Pin = GPIO_Pin_10;
  15. GPIO_Config.GPIO_Mode = GPIO_Mode_IN_FLOATING;
  16. GPIO_Config.GPIO_Speed = GPIO_Speed_50MHz;
  17. GPIO_Init(GPIOA, &GPIO_Config);
  18. }
  19. void initRTC()
  20. {
  21. RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);
  22. if (BKP_ReadBackupRegister(BKP_DR1) != 0xA5A5)
  23. {
  24. PWR_BackupAccessCmd(ENABLE);
  25. BKP_DeInit();
  26. RCC_LSEConfig(RCC_LSE_ON);
  27. while (RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET);
  28. RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);
  29. RCC_RTCCLKCmd(ENABLE);
  30. RTC_WaitForSynchro();
  31. RTC_WaitForLastTask();
  32. RTC_SetPrescaler(32767);
  33. RTC_WaitForLastTask();
  34. BKP_WriteBackupRegister(BKP_DR1, 0xA5A5);
  35. PWR_BackupAccessCmd(DISABLE);
  36. }
  37. RTC_WaitForSynchro();
  38. RTC_WaitForLastTask();
  39. }
  40. void initUSART()
  41. {
  42. RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
  43. USART_InitTypeDef USART_InitStructure;
  44. USART_InitStructure.USART_BaudRate = 115200;
  45. USART_InitStructure.USART_WordLength = USART_WordLength_8b;
  46. USART_InitStructure.USART_StopBits = USART_StopBits_1;
  47. USART_InitStructure.USART_Parity = USART_Parity_No;
  48. USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  49. USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
  50. USART_Init(USART1, &USART_InitStructure);
  51. USART_Cmd(USART1, ENABLE);
  52. }
  53. void setTime(uint32_t time)
  54. {
  55. PWR_BackupAccessCmd(ENABLE);
  56. RTC_WaitForLastTask();
  57. RTC_SetCounter(time);
  58. RTC_WaitForLastTask();
  59. PWR_BackupAccessCmd(DISABLE);
  60. }
  61. void initAll(void)
  62. {
  63. initRTC();
  64. initGPIO();
  65. initUSART();
  66. RCC_ClearFlag();
  67. }
  68. int main(void)
  69. {
  70. initAll();
  71. for (;;)
  72. {
  73. char c;
  74. time_t t;
  75. scanf("%c", &c);
  76. switch (c)
  77. {
  78. case 's':
  79. scanf("%d", &t);
  80. setTime(t);
  81. printf("Current time changed: %d - %s\r", t, ctime(&t));
  82. break;
  83. default:
  84. RTC_WaitForLastTask();
  85. t = time(0);
  86. printf("Current time: %d - %s\r", t, ctime(&t));
  87. break;
  88. }
  89. }
  90. return 0;
  91. }