Pololu Robotics & Electronics
Menu
My account Comments or questions? About Pololu Contact Ordering information Distributors

Pololu Forum

[Help] serial com--print float or int


#1

I attempted to use “sprintf” to convert float or int number to string, then use serial_send to send the message. It works ok with int, however when it comes to float the message received is just some weird signs like “?&*”. I am using the following code:

void printInt(int a)
{
	sprintf(send_buffer,"%d",a);
	//wait_for_sending_to_finish();
	serial_send_blocking(send_buffer,strlen(send_buffer));
}

void printIntln(int a)
{
	sprintf(send_buffer,"%d\r\n",a);
	//wait_for_sending_to_finish();
	serial_send_blocking(send_buffer,strlen(send_buffer));
}

void printFloat(double a)
{
	sprintf(send_buffer,"%.2f",a);
	//wait_for_sending_to_finish();
	serial_send_blocking(send_buffer,strlen(send_buffer));
}

void printFloatln(double a)
{
	sprintf(send_buffer,"%.2f\r\n",a);
	//wait_for_sending_to_finish();
	serial_send_blocking(send_buffer,strlen(send_buffer));
}

I tried to define the variable as double and float both. Yet no one worked. My question is, what is wrong with the sprintf, is there any alternative way?
Thanks for your concerns.


#2

You need to make sure that the floating point library versions of printf and sprintf are being linked, which is not the default with WinAVR, for example. What development system you are using?


LCD Screen
#3

Thanks for your hint. Sorry, I did not mention the IDE. I am using atmel studio 6. I got it. I need to modify the toolchain a little bit. Got details in another forum:http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&t=122686. (I assume it is ok to post the link. Hope this post can help others who got the similar problem.)

[quote]1) You need a -Wl,-u,vfprintf added to the linker options - it appears that’s what this new tick box in AS6 does. It appears to only cater for printf but not scanf.

  1. you need to add -lprintf_flt or -lscanf_flt to the linker options which is done by listing printf_flt as a library.

  2. you always need to have -lm if using float anyway (thankfully since mid AS5 Atmel have now been adding this as a default anyway). [/quote]


#4

How is send_buffer defined?


#5

The communication code I am using is modified from the example: https://www.pololu.com/docs/0J20/3.h.