Read an analog value using ADC

Dependencies:   mbed

Revision:
3:152d8b330c08
Parent:
2:fc1b61adfc11
Child:
4:643030f4ac01
--- a/main.cpp	Sun Dec 28 23:59:30 2014 +0000
+++ b/main.cpp	Mon Dec 29 01:20:50 2014 +0000
@@ -1,16 +1,30 @@
-/**************************************************************************/
-/* Note: The STM32F401 has default 3.3V I/O pins (3.3V == 4096)           */    
-/**************************************************************************/
+/***********************************************************************************************/
+/* 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) */
+/***********************************************************************************************/
 
 #include "mbed.h"
 
-AnalogIn analog_sensor(A0);                                       // Create the analog pin object
+AnalogIn analog_sensor(A1);                      // 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)
-    {      
-        printf("\n Analog Read: %f", analog_sensor.read());       // Show the value
-        wait_ms(1);                                               // Wait 1ms between reads for stability
+    {
+        adc_value = analog_sensor.read_u16();    // Read the ADC analog input value [0 to 65536]
+        voltage_value = 3.3*adc_value/65536;     // 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 65536]
+        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
     }
 }