Using a pin as both analog and digital

04 Oct 2011

Hi,

I was just asked if it is possible to use a pin as both an analog and a digital pin in different parts of the code.

The answer is yes, but it should be considered carefully if this is the best way to achieve the desired result.

Anyway, I wrote an example program that has two functions read_analog and read_digital, where each function has it's own local object (either analog or digital) which is created each time the function is called.

Not a particularly complex example, but it does enable you to measure the threshold voltage at which a DigitalIn starts reading the input as a '1'.

Import program

00001 #include "mbed.h"
00002 
00003 int read_digital(void) {
00004     DigitalIn mydigital(p20);
00005     return(mydigital.read());
00006 }
00007 
00008 float read_analog(void) {
00009     AnalogIn myanalog(p20);
00010     return(myanalog.read());
00011 }
00012 
00013 int main() {
00014     while(1) {
00015     
00016        printf("Digital reading : %d\n",read_digital());
00017        wait(1.0);
00018        printf("Analog reading : %.2f\n",read_analog());
00019        wait(1.0);
00020 
00021     }
00022 }