Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
10 years, 5 months ago.
AnalogIN andConvert the analog reading to a voltage (0 - 5V)
Hi to all, i am a newbie of embedded word i have a sensor and i write this simple code:
#include "mbed.h" Serial pc(SERIAL_TX, SERIAL_RX); AnalogIn ain(A0); int main() { while(1) { wait(10); float f=ain.read(); pc.printf("value is: %d \n",f); } }
all work well, but i want to convert this value in volt. If i use arduino i write this
arduino example
..... int sensorValue = analogRead(A0); // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V): float voltage = sensorValue * (5.0 / 1023.0);
but i think for st nulceo is differenty can you help me?
best regard. Antonio
2 Answers
10 years, 5 months ago.
Hello,
isn't nucleo 3.3v part, means ADC uses 3.3 as reference voltage? What's the ADc resolution for nucleo adc peripheral? 12bit, means that only 5.0 should be replaced by 3.3.
Regards,
0xc0170
10 years, 5 months ago.
ain.read() should return a value between 0 and 1, so simply multiply it with the reference voltage. (I really assume that is 3.3V also on the Nucleo, but if it is 5 then multiply it by 5). There is no need to divide it by 4096 since the library already does that. (Unless you use read_u16, but then you always get it as left-alligned 16-bit value, so in that case you need to divide it by 65xxx.
hi i write this:
Serial pc(SERIAL_TX, SERIAL_RX); AnalogIn ain(A0); DigitalOut myled(LED2); int main() { while(1) { wait(1); myled = !myled; float f=ain.read(); pc.printf("value f %d \n",f); float voltage =(f*(5.0/ 4096.0)); pc.printf("value voltage %d \n",voltage); } }
i see this value value f 536870912 value voltage 536870912 value f -1073741824 value voltage -1073741824 i don't know where is my error, can you help me?
posted by 04 Jun 2014Ah, I missed that in your post, thats why it is good to add what you see :).
The problem is that you use %d, that is used to print integers, not floating point values. Use %f for that (you should get a warning, currently it is printing the binary float value as an integer). See here for some more explanation: http://www.cplusplus.com/reference/cstdio/printf/
posted by 04 Jun 2014