Read an analog value using ADC

Dependencies:   mbed

main.cpp

Committer:
jose_23991
Date:
2014-12-29
Revision:
5:61fd7faf824b
Parent:
4:643030f4ac01

File content as of revision 5:61fd7faf824b:

/******************************************************************************************************/
/* Note: The STM32F401 has default 3.3V ADC pins                                                      */
/* Note: The STM32F401 has default 12 bits ADC but it is normalized to 16 bits (2^16 -> 65536 values) */
/******************************************************************************************************/

#include "mbed.h"

AnalogIn analog_sensor(A0);                      // Create the analog pin object

int main()
{
    uint16_t adc_value;                          // ADC value for analog read variable
    float voltage_value;                         // Voltage value for analog read variable
    float percent_value;                         // Percent value for analog read variable
    
    while(1)
    {
        adc_value = analog_sensor.read_u16();    // Read the ADC analog input value [0 to 65535]
        voltage_value = 3.3*adc_value/65535;     // Read and convert to voltage the analog input value [0.0 to 3.3]
        percent_value = analog_sensor.read();    // Read the percent analog input value [0.0 to 1.0]
        
        printf("\n");                            // Serial new line
        printf("Analog Read: ");                 // Show the text between " "
        printf("ADC [%d], ", adc_value);         // Show the voltage value [0 to 65535]
        printf("Voltage [%f], ", voltage_value); // Show the voltage value [0.0 to 3.3]
        printf("Percent [%f] ", percent_value);  // Show the percent value [0.0 to 1.0]
        
        wait_ms(1);                              // Wait 1ms between reads for stability
    }
}