openwch / arduino_core_ch32

Core library for CH32duino
269 stars 52 forks source link

Fix reading PADC_VREF #156

Open maxint-rd opened 1 month ago

maxint-rd commented 1 month ago

Silly workaround in analogInputToPinName(), since PADC_VREF mapped to PA_1 instead of just PADC_VREF. Don't know why the code is this convoluted, so this is just a quick fix that works on the CH32V003.

Note: this change was only tested with CH32V003. It requires ADC to be enabled in .../variants/CH32V00x/CH32V003F4/variant_CH32V003F4.h: #define ADC_MODULE_ENABLED

Example usage:

uint32_t _uVref=1200L; // Vref 1.17V-1.23V (avg 1.20V) according CH32V003 datasheet

uint32_t getVCC(uint32_t uMultiplier=100)
{ // return VCC in mV, based on internal 1.2V reference voltage and the supplied multiplier
  // multiplier is a percentage (100%=100), to be used for calibration
  uint32_t uVal=analogRead(PADC_VREF);  // Note: would be better to read an average after ADC gives stable readings
  uVal=(1024L*_uVref)/uVal;  // assume 1024 is full VCC, this applies to 10-bit ADC resolution
             // NOTE: 1024 works for CH32V003, others may need different values
  return((uVal * uMultiplier)/100);
}