AnalogIn

The AnalogIn Interface is used to read the voltage applied to an analog input pin.

Hello World!

» Import this program

#include "mbed.h"
 
AnalogIn ain(p19);
DigitalOut led(LED1);
 
int main() {
    while (1){
        if(ain > 0.3) {
            led = 1;
        } else {
            led = 0;
        }
    }
}

API

API summary

» Import latest build into a program

Public Member Functions

  AnalogIn (PinName pin)
  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()

Interface

/media/uploads/chris/pinout-thumbnails.jpg
See the Pinout page for more details

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



37 comments:

06 Dec 2010

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?

11 Jan 2011

Is there an easy way to speed up an A/D conversion by a factor of 2 or 4? For instance, for some microcontrollers it is possible to get A/D conversions with fewer bits of accuracy but in less time?

Thx.

21 Feb 2011

I think someone mess up with the code:

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

This doesn't make sense or compile

21 Feb 2011

I think what it meant to do was somethink like this, using the "Servo" Library http://mbed.org/cookbook/Servo

#include "mbed.h"
#include "Servo.h"

AnalogIn position(p20);
Servo myservo(p21);

int main (void)
{
   while(1)
   {
      float newPosition=position.read();     // The AnalogIn must be between 0v - 1v
      myservo = newPosition;                // or adapting it to this value 
   }
}
21 Feb 2011

All three examples now work; it was just three had become two smashed together.

Thanks! Simon

15 Apr 2011

hi i´m new with my mbed sorry for my engkish i´m from Ecuador, I need your help I work mith AnalogIn it work but when I put for example

AnalogIn volt(p15); PwmOut led(p21); and when i put

led=volt;

i have noise and the led blink the voltage i take from an potentiometer thank you

15 Apr 2011

user Juank Gutierrez wrote:

hi i´m new with my mbed sorry for my engkish i´m from Ecuador, I need your help I work mith AnalogIn it work but when I put for example

Hola Hombre!!

What's up dude!!

I'm from Ecuador too. I study in Ibarra, anyway about your question, you should post your code, or have a link to it.

You should try to visualize AnalogIn trough Serial port. like this

#include "mbed.h"

Serial pc( USBTX, USBRX);
AnalogIn Q14( p15 );
DigitalOut myled( LED1 );

int main() {
    while(1) {
        pc.printf("\n%f",Q14.read());
        wait_ms(100);
    }
}

And then figure out PWM. Maybe you get too many noise, or something.

15 Apr 2011

thank you for you answer, ok my code is

#include "mbed.h"
#include "TextLCD.h"
 TextLCD lcd(p5, p6, p7, p8, p9, p10); 

PwmOut out(p21);
AnalogIn vel(p16);

int main() {
    while(1) {
   
    out=vel.read();
    lcd.locate(0,1);
    lcd.printf("%0.3f   ",vel.read());
    wait(0.3);
       
    }
}

to probe i put the pin p16 to ground and in the lcd y can see 0.00 but it chages to 1.00 and obviously the led blink

15 Apr 2011

Help me please, i can´t solve the problem with the AnalogIn, when i try to use always have the value between 0,00 and 1.00 but repeatedly the value goes to 1.00 without change the input

Thanks

22 May 2011

.

06 Jun 2011

I have a similar problem. For several designs I use the analog input. One of them is a 4 led multimeter as one of mine example designs. Once in a while the LEDs blink at maximum although they should be not. Seem for a current measurement of an motor. Them maximum value of the current can never exceeds ( float ) 0.5 but somehow it measures 1. Seems like an compiler or chip problem to me...

Yes, I can use an low pass filter as a work-around but is there a solution to this problem?

Ben

16 Jun 2011

hi i have a question please what would happen if a negative voltage was inserted to the analogIN pin ( that is a sinusoidal voltage from the signal generator), how would it be interpreted in the teraterm( terminal application) , since only voltage is from 0.0 - 3.3 (0.0-1.0 normalised)? i would appreciate your response

16 Jun 2011

If you put a negative voltage on analog in, you'll break your mbed.

17 Jun 2011

I mean if I input a sinusoidal voltage that has a peak value of 2V for example , what values should i expect seeing in the terminal application ? because when i input a sinosoidal voltage , i see the values ranges from 0.0 to 1.00 so I just want to double check if that is right ? thanks in advance

27 Jun 2011

is the 3.3 volts that the analogIn interface can read rms or peak?

27 Jun 2011

yes, the read() function returns a float fro 0 to 1.0. Since the reference voltage is 3.3V, to get the actual voltage on the pin you multiply by 3.3

AnalogIn a(p20);
...
Vin= a.read()*3.3;
..

As Jeroen said, you must make sure you never input any negative voltage on a pin on the mbed. It's easy to forget when you measure AC voltages.

28 Jun 2011

thnx

03 Jul 2011

I think, this is AnalogIn bug. The code below just sends a few messages to my pc and then it stops (freezes)!
Please can you show me any solution, when I need to measure analog signal in high priority and measure other analog signals in lower priority "when a free time remains"?

#include "mbed.h"

AnalogIn a1(p17);
AnalogIn a2(p19);
Ticker t;
int a,b;

void measuring() {
    printf("mmm\n");
    a2.read();
    a++;
    if (a>10000) {
        printf("measuring is still running.");
        a=0;
    }
}

void main() {
    printf("starting.\n");
    t.attach(&measuring, 0.01);
    while(1) {
        printf("test1");
        for (int i=0;i<100;i++) a1.read();
        printf("test2");
        wait(0.1);
    }
}

starting.
test1test2mmm
mmm
mmm
mmm
mmm
mmm
mmm
mmm
mmm
mmm
test1mmm

now the sending messages to the pc stopped. I think, it is because one AD conversion was running and other AD conversion it interrupted. What to do?

19 Jul 2011

What is the input impedance of the Analog inputs?

19 Jul 2011

You need 1.7 bias and it has -05 to 5.1 v input so V = I R I don't know what 5V is in impedance..

ceri says 10 K. Possibly > 100K

http://mbed.org/forum/helloworld/topic/2292/?page=1#comment-11864

just search some of my theads... you may find something you may not.

23 Aug 2011

Hello, Someone knows the time it takes mbed taking a sample with the ADC?

12 Sep 2011

The ADC on the LPC1768 has a resolution of 12 bits, or 0x0000 - 0x0FFF. I understand why you might return a float of 0.0 to 1.0 as the "low to high" range. But I don't understand why the read_u16 function returns a 16 bit value from this 12 bit ADC. It seems like if you want the raw binary result, then that's what you want, not a bit shifted 16 bit result with (4096*15) missing codes.

It is certainly easy enough to accommodate this, but it means you had to shift it left in the lib and now I have to shift it right in the application. Seems like a bug.

03 Oct 2011

I realize that the MBED NXP 1768 supports multiple uses for many of its pins. For example, pin 15 can be configured as either a digital input, or as a digital output, or as an analog input.

What I'd like to know is if it is possible to use pin 15 as both a digital and as an analog input in a program. Basically, I'd like to create two variable (1 for digital input, and 1 for analog input) using the same pin. I plan on including another discrete digital input as a "deciding factor" that will enable either one of the variable (either digital or analog).

Can this be done? Can a pin be assigned to multiple variables? I tried, but I've run into some problems.

Thank you for your help.

03 Oct 2011

Can anyone tell me how many times per second the analog-in is sampled ?

04 Oct 2011

Direct from the user manual.

12-bit Analog-to-Digital Converter (ADC) with input multiplexing among eight pins, conversion rates up to 200 kHz, and multiple result registers. The 12-bit ADC can be used with the GPDMA controller.

Dave.

02 Dec 2011

Hi everyone, I would like to ask you which mbed pin no. is the one that is the voltage ground reference for analogin because I want to measure the voltage of a mini Wind Turbine Generator which is a lot higher than the mbed itself.

Thanks

04 Jan 2012

Happy new year to all of you...

I have a question. I want to design a sound-to-light controller by using the AIn. My idea was to read out a line signal (Upp- max 3,3V) from my cd-player. I build a low pass, and now i get frequencies under 100Hz (bass). If i lay the ground of my line signal on the mbeds ground an the signal on the AI ... Can I do that? My fear is because one of the older posts:"If you put a negative voltage on analog in, you'll break your mbed."

Thanks for your help

08 Jan 2012

user Thomas Burandt wrote:

"If you put a negative voltage on analog in, you'll break your mbed."

I believe using a capacitor like at least 0.1 ufd is series with AnalogIn will stop negative voltage from going below ground.

08 Jan 2012

Thomas, Don,

a series capacitor by itself will not protect the input from negative voltages. A capacitor can separate the mbed input from a DC level on the input signal. You should use a resistor voltage divider to raise the DC level of the mbed input pin to something like half the supply voltage of 3v3 and then connect your capacitor to that newly created DC level. Your mbed inputvoltage would then vary between 0v and 3v3 when the actual line voltage is 3v3 top-top. I would still add some additional protection diodes to make sure the mbed pin is always between 0 and 3v3.

Checkout http://mbed.org/forum/electronics/topic/2454/?page=1#comment-12647

14 Jan 2012

Dear all, I'm wondering about the adc conversion time. The microcontroller user manual specifies the sampling rate at 12 bit to be 200kS/s. Hence, the time between two samples should be 5 microseconds. I tested the time with the attached code. Apparently the time for one sample is up to 70 microseconds. Starting and stopping the timer prints values of only one microsecond. has anyone an idea how to speed up to the maximum sampling rate? Thanks a lot, Ralph

  1. include "mbed.h"

AnalogIn input(p20); LocalFileSystem local("local"); Timer t;

int main() { float samples;

FILE *fp = fopen("/local/out.txt", "w");

t.start(); samples=input.read(); t.stop();

fprintf(fp, "dt: %f sample: %f\n",float(t.read_us()),samples); fclose(fp); }

13 Aug 2012

I would also like to know the answer to Ralph's question. Is it possible to speed up the ADC somehow?

26 Aug 2012

Did Anyone find out how we can do to speed up the conversion?? I am getting a 20uS per sample and its still need to be faster there is a way to get to it?? Thanks a lot!

26 Aug 2012

The ADC conversion time on the mbed is set to about the slowest possible. You can find out how to speed it up in Chapter 14, Section 14.6.3 of our new book "Fast and Effective Embedded Systems Design - Applying the ARM mbed". This appears elsewhere in this site, and can be ordered from Amazon. This book is written to help you get a deeper understanding of what goes on in the mbed - we hope it works for you! Tim Wilmshurst (co-author)

11 Sep 2012

Deal all,

Using an mbed(or rather an lpc1768) to read some analogue potentiometers amongst other tasks and pass the values to an fpga via spi.

All working fine except analogue ins.

Using analogue.read() and expecting a float value between 0.0 and 1.0, However using a serial debug i'm finding the following values being returned(the pot was never moved as these readings were being taken): (-1610612736) (1610612736) (1610612736) (1610612736) (-2147483648) (-1073741824) (1610612736) (-1073741824) (1073741824) (536870912) (0) (0) (1610612736) (-2147483648) (0)

Readings taken 0.5 seconds apart.

Does anybody have any ideas as to why the readings are so random, This happens on all analogue ins.

Regards Richard.

11 Sep 2012

does your. code work on a real MBED. ?

have you defined the pins as analog in?

I believe a result of 0.0 to 1.0 is the full range.

also are you formatting your printf correctly? printf ("ADC = %f", analogValue);

if the above doesn't fix it then post your code.

from a hardware point of view :

have you an isolated voltage for ADC REF, hi and lo

and lots of decoupling caps I normally use : two of the following 1, 10, 100 nF SIX CAPACITORS as well as 10-47uF very close to LPC1768

hope that's usefull

Ceri

25 Oct 2012

According to the Analog input description, "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". But if I have an analog input with a 0.0 to 4.7 V range. What can I do?

Thank you.

Sergio

25 Oct 2012

Resistive voltage divider can work, although do take into account the mbeds ADC isnt allowed to see a resistance of more than 7.5kOhm (well thats official spec, depending on how much accuracy you need you probably can go a bit higher than that).

If for whatever reason you want to use larger resistors you need to use an opamp (or something else) as buffer.

Posting comments for this page has been disabled