adc_interrupt_2ch.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. * STC8H3K64S2
  16. * AGrnd -> GND
  17. * AVcc -> VCC
  18. * AVref -> VCC
  19. * Vcc -> VCC
  20. * Gnd -> GND
  21. * ADC1 -> Test voltage
  22. *
  23. * STC8H1K08
  24. * AVref -> VCC
  25. * Vcc -> VCC
  26. * Gnd -> GND
  27. * ADC1 -> Test voltage
  28. */
  29. #include "fw_hal.h"
  30. uint8_t pos;
  31. uint16_t res[2];
  32. INTERRUPT(ADC_Routine, EXTI_VectADC)
  33. {
  34. ADC_ClearInterrupt();
  35. res[pos] = ADC_RESL;
  36. res[pos] |= (ADC_RES & 0x0F) << 8;
  37. // Restart ADC for continuous sampling
  38. pos = (pos+1) & 0x1;
  39. if (pos == 0)
  40. {
  41. /**
  42. * Uncomment these lines in high speed ADC
  43. GPIO_P1_SetMode(GPIO_Pin_1, GPIO_Mode_InOut_OD);
  44. GPIO_P1_SetMode(GPIO_Pin_1, GPIO_Mode_Input_HIP);
  45. */
  46. ADC_SetChannel(0x01);
  47. }
  48. else
  49. {
  50. /**
  51. * Uncomment these lines in high speed ADC
  52. GPIO_P1_SetMode(GPIO_Pin_2, GPIO_Mode_InOut_OD);
  53. GPIO_P1_SetMode(GPIO_Pin_2, GPIO_Mode_Input_HIP);
  54. */
  55. ADC_SetChannel(0x02);
  56. }
  57. ADC_Start();
  58. }
  59. void main(void)
  60. {
  61. SYS_SetClock();
  62. // For debug print
  63. UART1_Config8bitUart(UART1_BaudSource_Timer2, HAL_State_ON, 115200);
  64. // Channel: ADC1
  65. ADC_SetChannel(0x01);
  66. // ADC Clock = SYSCLK / 2 / (1+15) = SYSCLK / 32
  67. ADC_SetClockPrescaler(0x0F);
  68. // Right alignment, high 2-bit in ADC_RES, low 8-bit in ADC_RESL
  69. ADC_SetResultAlignmentRight();
  70. // Enable interrupts
  71. EXTI_Global_SetIntState(HAL_State_ON);
  72. EXTI_ADC_SetIntState(HAL_State_ON);
  73. // Turn on ADC power
  74. ADC_SetPowerState(HAL_State_ON);
  75. // Set ADC1(P1.1), ADC2(P1.2) HIP
  76. GPIO_P1_SetMode(GPIO_Pin_1|GPIO_Pin_2, GPIO_Mode_Input_HIP);
  77. // Start ADC
  78. ADC_Start();
  79. while(1)
  80. {
  81. UART1_TxString("Result: ");
  82. UART1_TxHex(res[0] >> 8);
  83. UART1_TxHex(res[0] & 0xFF);
  84. UART1_TxChar(' ');
  85. UART1_TxHex(res[1] >> 8);
  86. UART1_TxHex(res[1] & 0xFF);
  87. UART1_TxString("\r\n");
  88. SYS_Delay(100);
  89. }
  90. }