The AnalogIn Interface is used to read the voltage applied to an analog input pin.
Hello World!
Turn on a LED when AnalogIn goes above 0.3
#include "mbed.h"
AnalogIn ain(p20);
DigitalOut led(LED1);
int main() {
while (1){
if(ain > 0.3) {
led = 1;
} else {
led = 0;
}
}
}
API
API summary
| AnalogIn | An analog input, used for reading the voltage on a pin |
| Functions | |
| AnalogIn | Create an AnalogIn, connected to the specified pin |
| read | Read the input voltage, represented as a float in the range [0.0, 1.0] |
| read_u16 | Read the input voltage, represented as an unsigned short in the range [0x0, 0xFFFF] |
| operator float | An operator shorthand for read() |
Details
The AnalogIn Interface can be used on mbed pins p15-p20.
The 0.0v to 3.3v range of the AnalogIn is represented in software as a normalised floating point number from 0.0 to 1.0.
Examples
Control a R/C model servo with an analog input
#include "mbed.h"
AnalogIn position(p20);
PwmOut servo(p21);
int main() {
servo.period(0.020); // servo requires a 20ms period
while (1) {
servo.pulsewidth(0.001 + 0.001 * position); // servo position determined by a pulsewidth between 1-2ms
}
}
AnalogIn reading 16-bit samples
#include "mbed.h"
AnalogIn input(p20);
DigitalOut led1(LED1);
int main() {
unsigned short samples[1024];
for(int i=0; i<1024; i++) {
samples[i] = input.read_u16();
wait_ms(1);
}
printf("Results:\n");
for(int i=0; i<1024; i++) {
printf("%d, 0x%04X\n", i, samples[i]);
}
}
Code
#include "mbed.h"
AnalogIn ain(p20);
DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);
DigitalOut led4(LED4);
int main() {
while (1){
led1 = (ain > 0.2) ? 1 : 0;
led2 = (ain > 0.4) ? 1 : 0;
led3 = (ain > 0.6) ? 1 : 0;
led4 = (ain > 0.8) ? 1 : 0;
}
}
Last modified 21 Feb 2011, by
Simon Ford

No tags
|
30 comments
Is there any way to request an A/D conversion, then generate an interrupt to read the value once the conversion is complete? It looks like the thread waits for conversion during the read() function
is there a way to use those cycles more constructively?