You are viewing an older revision! See the latest version

AnalogIn

/media/uploads/mbedofficial/analogin_interfaces.png

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

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]);
    }
}   

#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;
    }
}

All wikipages