cancel
Showing results for 
Search instead for 
Did you mean: 

STM32 internal ADC for reading temperature.

Kumar B
Associate II

0690X00000Arun6QAB.png0690X00000ArunFQAR.png

/*I want to read stm32 temperature using ADC1 with timer 2 configured.
I am getting temperature reading as 60 degrees when I configured 
ADC1->SQR3=16; 
and  -275 degrees when  ADC1->SQR3=18;  Is any thing wrong? */
 
#include "stm32f4xx.h"        // Device header
#include <stdio.h>
 
int UART2_write(int ch);
void UART2_Init(void);
void msdelay(unsigned int delay);
 
int data;
double voltage;
double celsius;
 
struct __FILE 
{
int handle;		
};
 
FILE __stdout ={1}; 
 
int fputc(int c, FILE *f)
{
	return UART2_write(c);
}	
 
int UART2_write(int ch)
{
 
		/*Wait till TX buffer is filled with data */
		while(!(USART2->SR & 0X0080));	
		USART2->DR = ch;
	  msdelay(100);
	  return ch;
}
void UART2_Init(void)
{
		/*Enable GPIO clock for Port A since USART2 connected to PA2*/ 
	RCC->AHB1ENR |=1;
	/*Enable bit 17 of RCC_APB1ENR for USART2 Clock  */
	RCC->APB1ENR |= 0X20000;
	/*USART2 connected to Alternate functin AF7 low register GPIOx_AFRL AF7(AFRL2) (PA2)=0111 = 0X0700 (doubt)*/ 
 
	//PA0 (0 to 3 bits)->0000, PA1 (4 TO 7 bits)-> 0000, PA2 (AFRL2)8 to 11 ->0111
	GPIOA->AFR[0]= 0x0700;  // 0000 0111 0000 0000 
 
	/*Set PA2 to alternate function*/
	GPIOA->MODER = 0X0020;
	/*set baud rate @9600*/
	USART2->BRR = 0X0683;
	/*Enable the USART2 module UE bit */
	USART2->CR1 |= 0x2000;
	/*Enable USART2 Transmitter TE bit */
	USART2->CR1 |= 0X0008;
}
int main(void)
{
 
RCC->AHB1ENR |=1;
RCC->APB1ENR|=1;
TIM2->PSC=1600-1;
TIM2->ARR=(10000)-1;
TIM2->CCMR1=0X6800;
TIM2->CCR2=50-1;
TIM2->CCER|=0x0010;
TIM2->CNT=0;
TIM2->CR1=1;
RCC->APB2ENR|= 0x100;
ADC->CCR&=~0x00400000 ;    //clear VBAT to disable
 ADC->CCR |=0x00800000  ;    //Temperature sensor and VREFINT enable
ADC1->SQR3=16;                  //select channel 16 for ADC1
 
 //Select a sampling time 100: 84 cycles 10us
 ADC1->SMPR1= 0x04000000;
 //1001: Timer 2 CC2 event for regular channels
 ADC1->CR2=0x13000000;	
 ADC1->CR2|=1;           //Start ADC 
 
UART2_Init();
printf("STM32 Temperature \r\n");
	
	while(1)
	{
		while(!(ADC1->SR)){};
			data=ADC1->DR;
			voltage=(double)data/4095*3.3;
			celsius=(voltage-0.76)/0.0025+25;
			
			printf("%d,%.2f\370C\r\n",data,celsius);
	}
 
}

10 REPLIES 10

Ok. Thanks