To simplify the work require, we will be using a potentiometer to simulate the change of resistor. A sample of potentiometer is this. By applying the potentiometer in a voltage divider circuit, we will be getting an output voltage that change when potentiometer resistor is changing.
Tutorial Setup
This tutorial will be reading performing ADC read at channel ADC_IN0 every seconds (using systick), then output it through USART interface(USART) into laptop hyperterminal.Below shown the setup require on ADC section
Using Vin=5V, R1=6.8K Ohm, potentiometer at R2 (with resisitance range of 0Ohm ~ 10K Ohm). The voltage output sample is shown in below:
R2 Resistance Vout
0 Ohm 0V
1K Ohm 0.64V
2K Ohm 1.13V
5K Ohm 2.11V
10K Ohm 2.98V
The Vout will be connect into PA0, correspond to ADC_IN0 pin.
Actual Setup |
The MCU is actually running at 3V, the ADC will give maximum reading of 0xFFF when input voltage is 3V.
Source Code Descriptions
SFR Settings Descriptions
The following SFR setup is require to enable ADC_IN0A) ADC function
Power up initialisation
- Enable GPIO-A block
- Change PA0 pin function to alternate function (ADC function)
- Enable ADC block
- Perform ADC calibration and wait for completion
- PowerUp ADC block and wait for completion
- Select ADC channel (in our case it would be ADC_IN0:Channel 0)
- Enable single conversion mode/
- Select conversion resolution (in our case we use 12 bits)
- Start ADC process and wait for completion
- Read the result
- Enable GPIO-A block
- Change PA9, PA10 pin function to alternate function( USART)
- Enable USART block
- USART settings on the following: 8 databit, 115200 baud rate, 1 stop bit
- USART transmit/receive enable
- Enable USART interrrupt receive
- Enable USART
- * For more detail on USART, refer to tutorial here.
- Set SysTick timer reload value
- Clear SysTick timer current value to 0
- Select SysTick timer clock source
- Enable timeout interrupt, SysTick timer
- *For more detail on SysTick, refer to this tutorial.
Tutorial Source Code
The tutorial source code can get clone from here.I have purposely combine the previous tutorial (USART, SysTick) to show how a source code can be 'expand' when more features is being added. Now each MCU peripheral will have its respective source file (e.g. gpio.c, systick.c, uart.c)
Even though we are using potentionmeter to simulate the voltage change, a real life example work similar way. For example, a temperature sensor of LM35, is giving out a voltage change base on temperature. And the above code can be use with some tweak on the ADC result, to translate the result into temperature.