Advertisement
hussamaldean

Untitled

Apr 6th, 2020
586
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.52 KB | None | 0 0
  1. // using timer to trigger adc and read the cpu temperature and display the temprature to serial monitor
  2.  
  3.  
  4. #include "stm32f4xx.h"                  // Device header
  5. #include "stdio.h"
  6. void USART2_Init(void);
  7. void Timer2_init(void);
  8. void ADC_Init(void);
  9. int temp;
  10. double voltage,degree;
  11. int main(void)
  12. {
  13. USART2_Init();
  14. Timer2_init();
  15. ADC_Init();
  16. printf("ADC Temperature\r\n");
  17. while(1){
  18. while(!(ADC1->SR)&ADC_SR_EOC){;}
  19. temp=ADC1->DR;
  20. voltage=(double)temp/4096*3.3;
  21. degree=(voltage-0.76)/0.0025+25;
  22. printf("%d,%.2f\370\r\n",temp,degree);
  23. }
  24. }
  25.  
  26. void USART2_Init(void){
  27. RCC->APB1ENR|=0x20000;
  28. RCC->AHB1ENR|=1;
  29. GPIOA->AFR[0]=0x0700;
  30. //GPIOA->AFR[1]=0x0700;
  31. GPIOA->MODER|=0x0020; //set PA2 as alternate mode  
  32. USART2->BRR  = 0x008B;    //9600 @16MHz
  33. USART2->CR1  |=0x2008; // enable tx
  34. //USART2->CR1  |=0x2000;   
  35. }
  36.  
  37. void Timer2_init(void){
  38. RCC->AHB1ENR|=RCC_AHB1ENR_GPIOAEN;
  39. RCC->APB1ENR|=RCC_APB1ENR_TIM2EN;
  40. TIM2->PSC=249;
  41. TIM2->ARR=63999;
  42. TIM2->CNT=0;
  43. TIM2->CCMR1|=0x6800;
  44. TIM2->CCER|=0x0010;
  45. TIM2->CCR2|=50-1;
  46. TIM2->CCR1|=1;
  47. }
  48. void ADC_Init(void){
  49. //RCC->AHB1ENR|=RCC_AHB1ENR_GPIOAEN; //enable gpio a clock
  50. RCC->APB2ENR|=RCC_APB2ENR_ADC1EN; //enable adc clock
  51. ADC->CCR=0;
  52. ADC->CCR=ADC_CCR_TSVREFE;
  53. //ADC->CCR&=~ADC_CCR_VBATE;
  54. ADC1->SMPR1|=0x1C0000;
  55. ADC1->SQR1|=1;
  56. ADC1->CR2=0x13000000;
  57. ADC1->CR2|=1;
  58. }
  59. int USART2_write(int ch ){
  60. while(!(USART2->SR)){;}
  61.     USART2->DR =(ch&0xFF);
  62.     return ch;
  63.    
  64. }
  65. struct __FILE{int handle;};
  66. FILE __stdout  ={1};
  67.  
  68. int fputc(int c, FILE *f){
  69. return USART2_write(c);
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement