Reading temperature sensor built into STM32F103RB chips

Dependencies:   mbed

main.cpp

Committer:
hudakz
Date:
2016-03-27
Revision:
0:dfdf46225b14
Child:
1:09a5e83ea18f

File content as of revision 0:dfdf46225b14:

// Reading internal temperature sensor of STM32F103RB chip

#include "mbed.h"

// See STM32F103x datasheet, chapter 5.3.19 "Temperature sensor characteristics", Table 50. "TS characteristics"
const float         AVG_SLOPE   = 4.3E-03;
const float         V25         = 1.43;
const float         ACD_TO_VOLT = 3.3 / 4096;

Serial              pc(USBTX, USBRX);
DigitalOut          myled(LED1);
ADC_HandleTypeDef   hadc1;
float               temp;
uint16_t            adcValue;

/* ADC1 init function */
extern "C"
void MX_ADC1_Init(void) {
    ADC_ChannelConfTypeDef  sConfig;

    /**Common config
        */
    hadc1.Instance = ADC1;
    hadc1.Init.ScanConvMode = ADC_SCAN_DISABLE;
    hadc1.Init.ContinuousConvMode = DISABLE;
    hadc1.Init.DiscontinuousConvMode = DISABLE;
    hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
    hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
    hadc1.Init.NbrOfConversion = 1;
    HAL_ADC_Init(&hadc1);

    /**Configure Regular Channel
        */
    sConfig.Channel = ADC_CHANNEL_TEMPSENSOR;
    sConfig.Rank = 1;
    sConfig.SamplingTime = ADC_SAMPLETIME_239CYCLES_5;
    HAL_ADC_ConfigChannel(&hadc1, &sConfig);
}

int main() {
    MX_ADC1_Init();
    while(HAL_ADCEx_Calibration_Start(&hadc1) != HAL_OK);

    while(1) {        
        myled = !myled;
        HAL_ADC_Start(&hadc1);
        while(HAL_ADC_PollForConversion(&hadc1, 0) != HAL_OK);
        adcValue = HAL_ADC_GetValue(&hadc1);
        temp = (V25 - adcValue * ACD_TO_VOLT) / AVG_SLOPE + 25.0f;
        pc.printf("temp = %3.1f%cC\n", temp, 176);
        wait_ms(1000);
   }
}