clock_trim_scan.c 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2021 IOsetting <iosetting(at)outlook.com>
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * Scan to find most close VRTRIM and IRTRIM for specified frequency.
  16. *
  17. * Change build_flags in platformio.ini
  18. * D__CONF_FOSC -> target frequency, e.g. 36864000UL
  19. * D__CONF_MCU_MODEL -> MCU type, e.g. MCU_MODEL_STC8H3K64S2
  20. * D__CONF_IRCBAND -> frequency band depending on the frequency
  21. * STC8H1K - 00:20MHz, 01:35MHz
  22. * STC8H3K,STC8H8K - 02:24MHz, 03:40MHz
  23. *
  24. * Connect UART at baud 115200 and read output, when the output is not garbled,
  25. * find the middle value of VRTRIM and IRTRIM, lower VRTRIM is preferred
  26. */
  27. #include "fw_hal.h"
  28. uint8_t readCode(uint8_t offset)
  29. {
  30. return (*(unsigned char volatile __CODE *)(__CID_ADDR + offset));
  31. }
  32. void main(void)
  33. {
  34. uint8_t i, j, vrtrim = 0x01, irtrim = 0;
  35. // Set system clock. Invoke it to set the frequency band
  36. SYS_SetClock();
  37. // UART1 configuration: baud 115200 with Timer2, 1T mode, no interrupt
  38. UART1_Config8bitUart(UART1_BaudSource_Timer2, HAL_State_ON, 115200);
  39. while(1)
  40. {
  41. // The upper limit of IRTRIM depends on VRTRIM, MCU becomes unstable if it goes
  42. // too high, set 0x30 to a lower value if scan stucks at beginning
  43. if (++irtrim == 0x30 + vrtrim)
  44. {
  45. irtrim = 0x00;
  46. // VRTRIM controls the voltage level, normally it won't exceed 0x40
  47. if (++vrtrim == 0x40)
  48. {
  49. vrtrim = 0x00;
  50. }
  51. }
  52. SYS_TrimClock(vrtrim, irtrim);
  53. UART1_TxString("ADDR: 0x");
  54. UART1_TxHex(__CID_ADDR >> 8);
  55. UART1_TxHex(__CID_ADDR & 0xFF);
  56. UART1_TxString("\r\n");
  57. UART1_TxString("MCUID: ");
  58. for (j = 0; j < 7; j++)
  59. {
  60. UART1_TxHex(readCode(18 + j));
  61. UART1_TxChar(' ');
  62. }
  63. UART1_TxString("\r\n");
  64. UART1_TxString("Current IRCBAND:");
  65. UART1_TxHex(IRCBAND);
  66. UART1_TxString(", VRTRIM:");
  67. UART1_TxHex(VRTRIM);
  68. UART1_TxString(", IRTRIM:");
  69. UART1_TxHex(IRTRIM);
  70. UART1_TxString(", LIRTRIM:");
  71. UART1_TxHex(LIRTRIM);
  72. UART1_TxString("\r\n\r\n");
  73. SYS_Delay(50);
  74. }
  75. }