|
| 1 | +#![no_std] |
| 2 | +#![no_main] |
| 3 | + |
| 4 | +//! Example usage for ADC on STM32F303 |
| 5 | +
|
| 6 | +extern crate panic_semihosting; |
| 7 | + |
| 8 | +use cortex_m_rt::entry; |
| 9 | +use cortex_m_semihosting::hprintln; |
| 10 | + |
| 11 | +use stm32f3xx_hal::{adc, pac, prelude::*}; |
| 12 | + |
| 13 | +#[entry] |
| 14 | +/// Main Thread |
| 15 | +fn main() -> ! { |
| 16 | + // Get peripherals, clocks and freeze them |
| 17 | + let mut dp = pac::Peripherals::take().unwrap(); |
| 18 | + let mut rcc = dp.RCC.constrain(); |
| 19 | + let clocks = rcc.cfgr.freeze(&mut dp.FLASH.constrain().acr); |
| 20 | + |
| 21 | + // set up adc1 |
| 22 | + let mut adc1 = adc::Adc::adc1( |
| 23 | + dp.ADC1, // The ADC we are going to control |
| 24 | + // The following is only needed to make sure the clock signal for the ADC is set up |
| 25 | + // correctly. |
| 26 | + &mut dp.ADC1_2, |
| 27 | + &mut rcc.ahb, |
| 28 | + adc::CkMode::default(), |
| 29 | + clocks, |
| 30 | + ); |
| 31 | + |
| 32 | + // Set up pin PA0 as analog pin. |
| 33 | + // This pin is connected to the user button on the stm32f3discovery board. |
| 34 | + let mut gpio_a = dp.GPIOA.split(&mut rcc.ahb); |
| 35 | + let mut adc1_in1_pin = gpio_a.pa0.into_analog(&mut gpio_a.moder, &mut gpio_a.pupdr); |
| 36 | + |
| 37 | + // Be aware that the values in the table below depend on the input of VREF. |
| 38 | + // To have a stable VREF input, put a condensator and a volt limiting diode in front of it. |
| 39 | + // |
| 40 | + // Also know that integer division and the ADC hardware unit always round down. |
| 41 | + // To make up for those errors, see this forum entry: |
| 42 | + // [https://forum.allaboutcircuits.com/threads/why-adc-1024-is-correct-and-adc-1023-is-just-plain-wrong.80018/] |
| 43 | + hprintln!(" |
| 44 | + The ADC has a 12 bit resolution, i.e. if your reference Value is 3V: |
| 45 | + approx. ADC value | approx. volt value |
| 46 | + ==================+=================== |
| 47 | + 0 | 0 mV |
| 48 | + 2048 | 1500 mV |
| 49 | + 4095 | 3000 mV |
| 50 | +
|
| 51 | + If you are using a STM32F3Discovery, PA0 is connected to the User Button. |
| 52 | + Pressing it should connect the user Button to to HIGH and the value should change from 0 to 4095. |
| 53 | + ").expect("Error using hprintln."); |
| 54 | + |
| 55 | + loop { |
| 56 | + let adc1_in1_data: u16 = adc1.read(&mut adc1_in1_pin).expect("Error reading adc1."); |
| 57 | + hprintln!("PA0 reads {}", adc1_in1_data).ok(); |
| 58 | + } |
| 59 | +} |
0 commit comments