Read an analog value using ADC

Dependencies:   mbed

Committer:
jose_23991
Date:
Mon Dec 29 11:25:17 2014 +0000
Revision:
5:61fd7faf824b
Parent:
4:643030f4ac01
Version 1.4

Who changed what in which revision?

UserRevisionLine numberNew contents of line
jose_23991 5:61fd7faf824b 1 /******************************************************************************************************/
jose_23991 5:61fd7faf824b 2 /* Note: The STM32F401 has default 3.3V ADC pins */
jose_23991 5:61fd7faf824b 3 /* Note: The STM32F401 has default 12 bits ADC but it is normalized to 16 bits (2^16 -> 65536 values) */
jose_23991 5:61fd7faf824b 4 /******************************************************************************************************/
jose_23991 1:c501cf08e477 5
jose_23991 0:34080419f5c6 6 #include "mbed.h"
jose_23991 0:34080419f5c6 7
jose_23991 4:643030f4ac01 8 AnalogIn analog_sensor(A0); // Create the analog pin object
jose_23991 0:34080419f5c6 9
jose_23991 0:34080419f5c6 10 int main()
jose_23991 0:34080419f5c6 11 {
jose_23991 3:152d8b330c08 12 uint16_t adc_value; // ADC value for analog read variable
jose_23991 3:152d8b330c08 13 float voltage_value; // Voltage value for analog read variable
jose_23991 3:152d8b330c08 14 float percent_value; // Percent value for analog read variable
jose_23991 3:152d8b330c08 15
jose_23991 0:34080419f5c6 16 while(1)
jose_23991 3:152d8b330c08 17 {
jose_23991 5:61fd7faf824b 18 adc_value = analog_sensor.read_u16(); // Read the ADC analog input value [0 to 65535]
jose_23991 5:61fd7faf824b 19 voltage_value = 3.3*adc_value/65535; // Read and convert to voltage the analog input value [0.0 to 3.3]
jose_23991 3:152d8b330c08 20 percent_value = analog_sensor.read(); // Read the percent analog input value [0.0 to 1.0]
jose_23991 3:152d8b330c08 21
jose_23991 3:152d8b330c08 22 printf("\n"); // Serial new line
jose_23991 3:152d8b330c08 23 printf("Analog Read: "); // Show the text between " "
jose_23991 5:61fd7faf824b 24 printf("ADC [%d], ", adc_value); // Show the voltage value [0 to 65535]
jose_23991 3:152d8b330c08 25 printf("Voltage [%f], ", voltage_value); // Show the voltage value [0.0 to 3.3]
jose_23991 3:152d8b330c08 26 printf("Percent [%f] ", percent_value); // Show the percent value [0.0 to 1.0]
jose_23991 3:152d8b330c08 27
jose_23991 3:152d8b330c08 28 wait_ms(1); // Wait 1ms between reads for stability
jose_23991 0:34080419f5c6 29 }
jose_23991 0:34080419f5c6 30 }