Nucleo F303K8 AnalogIn does not work

I just picked up the Nucleo F303K8 dev board to test out the on board ADC found in the STM32 line and could use some help troubleshooting why I cannot get any valid reading from the pin.

The signal I am attempting to read is the output from a potentiometer connected to GND and VDD.

#include <mbed.h>

Serial pc(USBTX, USBRX);
DigitalOut led(LED1);
AnalogIn a1(A2);

int main() {

  while(1) {
    float val = a1.read();
    pc.printf("val: %d \r\n", a1.read());    // this spits out random Unsigned decimal integer
    if (val > 1) {
      led.write(1);
    } else {
      led.write(0);
    }
  }
}

Now what I expect this program to do when run is output the a1.read() value to the console, as well as turn on/off the onboard led, but what actually happens is the led does NOT get lit up, and the serial output is just a bunch of random “Unsigned decimal integers” like so:


val: 0 
val: 0 
val: 0 
val: 0 
val: -1073741824 
val: 536870912 
val: 536870912 
val: 0 
val: 0 
val: 0 
val: -536870912 
val: 0 
val: -2147483648 
val: 0 
val: 0 
val: 536870912 
val: 0 
val: 536870912 
val: -1610612736 

Hi Scott,
I checked your program with my F303K Mbed board and confirmed the output data.
I could reproduce problem.
Please modify your source code as follows.

pc.printf("val: %f\r\n", a1.read());

%d ->%f

Maybe you can read correct value from 0.0 to 1.0.

Kenji Arai

Hey Kenji, thanks for checking for me. It still doesn’t seem to work. Strange how yours is working and mine isn’t though…

ya so I think I misinterpretted what read() returns. Its actually a float between 0.0 and 1.0, so after updating my LED if statements I was able to toggle the LED on/off based on voltage being read, however I am still unable to see the float value in the console. I want to say it has something to do with this

Hi Scott,
please make a copy&paste followings.

#include <mbed.h>

DigitalOut led(LED1);
AnalogIn a2(A2);

int main() {
  while(1) {
    float val = a2.read();
    printf("val: %4.3f\r\n", val);
    if (val > 0.5f) {
      led = 1;
    } else {
      led = 0;
    }
    wait(0.2f);
  }
}

I slightly modified your code for better understanding.
Please make sure your mbed revision.
I’m using 20 Feb 2019, release version 165.


Just in case, I created bin file and save it into below.
It works on my F303K8 Mbed.
https://onedrive.live.com/?id=E726C1E354E854B2%211099537&cid=E726C1E354E854B2

Kenji Arai

Ahoj,

just for info, code like this already exist in examples and it is working (tested) -Nucleo_read_analog_value
In comments of that code you can found also a description.

BR, Jan