Recently changed pages
Debugging Debugging
mbed NXP LPC1768 mbed NXP LPC1768
Homepage Homepage
Compiler Tour Compiler Tour
Media Media
Serial Serial
Terminals Terminals
From the mbed microcontroller Handbook.

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

API summary

AnalogInAn analog input, used for reading the voltage on a pin
Functions
AnalogInCreate an AnalogIn, connected to the specified pin
readRead the input voltage, represented as a float in the range [0.0, 1.0]
read_u16Read the input voltage, represented as an unsigned short in the range [0x0, 0xFFFF]
operator floatAn operator shorthand for read()
class AnalogIn : public Base
An analog input, used for reading the voltage on a pin
AnalogIn(PinName pin,  
const char *name =  NULL)
Create an AnalogIn, connected to the specified pin
float read()
Read the input voltage, represented as a float in the range [0.0, 1.0]
unsigned short 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;
    }
}



calendar Page history
Last modified 21 Jul 2010, by user avatar Dan Ros   tag No tags | 0 replies     Share: Digg Tweet This

Please login to post comments.