You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
2.7 KiB

3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
  1. #define _CRT_SECURE_NO_DEPRECATE
  2. #include <stdio.h>
  3. #include <stdint.h>
  4. #include <stdbool.h>
  5. typedef struct
  6. {
  7. int autoreload;
  8. int prescaler;
  9. float realfreq;
  10. } timer_config_t;
  11. bool compute_timer_parameter(timer_config_t* config, int timer_in_clk /*mhz*/, int infreq /*hz*/)
  12. {
  13. float psc_x_arr =(float) timer_in_clk * 1000 /*定时器模块时钟*/ * 1000 / infreq;
  14. uint32_t psc = 0;
  15. uint32_t arr = 65534;
  16. for (; arr > 2; arr--)
  17. {
  18. psc =(uint32_t)( psc_x_arr / arr);
  19. if (psc >= 1)
  20. {
  21. uint32_t tmparr = psc_x_arr / psc;
  22. if (tmparr >= 65534)
  23. continue;
  24. break;
  25. }
  26. }
  27. if (psc == 0)
  28. return false;
  29. if (arr <= 3)
  30. return false; //定时器一周期的分辨率太小了
  31. arr = psc_x_arr / psc;
  32. int psc_x_arr_real = arr * psc;
  33. float realfreq = timer_in_clk * 1000.0 /*定时器模块时钟*/ * 1000 / psc_x_arr_real;
  34. arr = arr - 1;
  35. psc = psc - 1;
  36. config->autoreload = arr;
  37. config->prescaler = psc;
  38. config->realfreq = realfreq;
  39. // config->compare = arr / 2;
  40. return false;
  41. }
  42. void dumpconfig_info(timer_config_t* config)
  43. {
  44. printf("* freq : %f \n", config->realfreq);
  45. printf("* prescaler : %d \n", config->prescaler);
  46. printf("* autoreload: %d \n", config->autoreload);
  47. }
  48. int main(int argc, char const* argv[])
  49. {
  50. if (argc != 3)
  51. {
  52. printf("%s timerInClk mhz expect_freq khz\n", argv[0]);
  53. return -1;
  54. }
  55. float expect_freq = 0;
  56. float timerInClk = 0;
  57. sscanf(argv[1], "%f", &timerInClk);
  58. sscanf(argv[2], "%f", &expect_freq);
  59. printf("******************************************************\n");
  60. printf("* author: zhaohe *\n");
  61. printf("* e-mail: h_zhaohe@163.com *\n");
  62. printf("******************************************************\n");
  63. printf("*\n");
  64. printf("* timerInClk : %f mhz\n", timerInClk);
  65. printf("* expect freq: %f khz\n", expect_freq);
  66. printf("*\n");
  67. int32_t infreq = (int32_t)(expect_freq * 1000);
  68. timer_config_t timerconfig_apb2;
  69. compute_timer_parameter(&timerconfig_apb2, timerInClk, infreq);
  70. printf("******************************************************\n");
  71. printf("*\n");
  72. printf("* timer_module_clk: %f mhz\n", timerInClk);
  73. printf("* freq : %f khz\n", timerconfig_apb2.realfreq / 1000.0);
  74. printf("* period : %f ms\n", (1.0 / timerconfig_apb2.realfreq * 1000));
  75. printf("* prescaler : %d \n", timerconfig_apb2.prescaler);
  76. printf("* autoreload : %d \n", timerconfig_apb2.autoreload);
  77. printf("*\n");
  78. return 0;
  79. }