/* p7_3.c: LM34 Fahrenheit temperature sensor * * LM34 is a Fahrenheit temperature sensor with the output of * 10 mV/degreeF. The program assumes an LM34 connected to * pin PA4 (channel 4). The conversion result is displayed one * the console as degree Fahrenheit. * The console UART driver is from Program 4-5. * * This program was tested with Keil uVision v5.23 with DFP v2.0.0. */ #include "stm32f0xx.h" #include void USART2_init(void); int USART2_write(int c); void delayMs(int n); int main(void) { int result; double temp; /* set up pin PA4 for analog input */ RCC->AHBENR |= 0x00020000; /* enable GPIOA clock */ GPIOA->MODER |= 3<<8; /* PA4 analog */ /* setup ADC1 */ RCC->APB2ENR |= 0x00000200; /* enable ADC1 clock */ ADC1->CR = 0; /* SW trigger */ ADC1->CFGR1 = 0; ADC1->CFGR2 = 0; ADC1->CHSELR = 1 << 4; ADC1->CR |= 1; /* enable ADC1 */ /* initialize USART2 for output */ USART2_init(); printf("LM34 Temperature Sensor\r\n"); while (1) { ADC1->CR |= 4; /* start a conversion */ while (!(ADC1->ISR & 2)) { } /* wait for conv complete */ result = ADC1->DR; /* read conversion result */ temp = (double)result / 4095 * 330; printf("%d, %.2f\r\n", result, temp); delayMs(1000); } } /* initialize USART2 to transmit at 9600 Baud */ void USART2_init(void) { RCC->AHBENR |= 0x00020000; /* Enable GPIOA clock */ RCC->APB1ENR |= 0x00020000; /* Enable USART2 clock */ /* Configure PA2, PA3 for USART2 TX, RX */ GPIOA->AFR[0] &= ~0xFF00; GPIOA->AFR[0] |= 0x1100; /* alt1 for USART2 */ GPIOA->MODER &= ~0x00F0; GPIOA->MODER |= 0x00A0; /* enable alt. function for PA2, PA3 */ USART2->BRR = 0x0341; /* 9600 baud @ 8 MHz */ USART2->CR1 = 0x000C; /* enable Tx, Rx, 8-bit data */ USART2->CR2 = 0x0000; /* 1 stop bit */ USART2->CR3 = 0x0000; /* no flow control */ USART2->CR1 |= 0x0001; /* enable USART2 */ } /* Write a character to USART2 */ int USART2_write(int ch) { while (!(USART2->ISR & 0x0080)) { } // wait until Tx buffer empty USART2->TDR = (ch & 0xFF); return ch; } /* The code below is the interface to the C standard I/O library. * All the I/O are directed to the console, which is UART2. */ struct __FILE { int handle; }; FILE __stdout = { 1 }; /* Called by C library console/file output */ int fputc(int c, FILE *f) { return USART2_write(c); /* write the character to console */ } /* 8 MHz SYSCLK */ void delayMs(int n) { int i; for (; n > 0; n--) for (i = 0; i < 1142; i++); }