Change pin function on the fly, how?

03 Sep 2009 . Edited: 03 Sep 2009

Hi,

For my touchpad project I need to alternate the function of some pins between an analog input and a digital output. To do this I probably have to access the registers directly as I don't see how to do this using AnalogIn & DigitalOut (dynamic pin allocation?). The register names from the datasheet are not recognised by the compiler. Is there an "mbed way" to do this? Or am I supposed to provide my own definitions? Or is there an other way to achieve this? I don't want to use more pins.

Regards,

Clemens

03 Sep 2009

Hi Clemens,

For my touchpad project I need to alternate the function of some pins between an analog input and a digital output. To do this I probably have to access the registers directly as I don't see how to do this using AnalogIn & DigitalOut (dynamic pin allocation?).

The natural way in C++ is to dynamically create objects, either as local variables or using new/delete.

As an example using local variables (i.e. allocated on the stack), see:

http://mbed.org/users/simon/published/aadb7ad83d46450b9ea13e1c1282456d/AnalogInDigitalOut.zip

which basically does:

float do_something_analog() {
    AnalogIn x(p20);
    return x.read();
}

void do_something_digital() {
    DigitalOut x(p20);
    x = 1;
    wait(0.5);
    x = 0;
}
The constructor of objects (when you define e.g. AnalogIn) sets things up. The alternative would be to allocate on the heap using new/delete and pointers to the objects.

Not sure if this is ideal, but it should be enough to get you going. We can learn from there...

Simon

03 Sep 2009 . Edited: 03 Sep 2009

Oh, I see. I was under the impression that the pin declarations _had_ to be global.

Thanks,

Clemens

12 Jun 2019

After all these years, It seems that the AnalogOut doesn't allow changing the pin configuration from Analog to digital. Look at this code .. The digital part works only once .. but the analog parts works fine. This must be a bug..

#include "mbed.h"
//NUCLEO-L476RG
void do_something_analog() {
    AnalogOut x(PA_4);
    double g=0.0;
    while(g<0.5){
    x=g;
    g=g+0.1;
    wait_ms(50);
    }
}

void do_something_digital() {
    DigitalOut x(PA_4);
    for(int i=0;i<10;i++){
        x = 1;
       wait_ms(50);
        x = 0;
        wait_ms(50);
    }
}

int main()
{
    printf("\nAnalog/Digital loop example\n");
    while(1) {
    do_something_digital();
    do_something_analog();    
 }
}