MCC18 FAQ1,怎样将浮点数转成ASCII以便可以用printf之类显示
FAQ1: 在MCC18里,怎样将浮点数转成ASCII 以便可以用诸如printf之类的库函数显示?
:)方法:为了不使printf库函数代码过大,MCC18 printf不支持浮点(%f %g以及%h类型)输出。如果要printf支持
浮点输出,库函数代码大小将可能会加倍。那么,如何用printf来显示浮点数呢?我们知道printf支持定点数显示
,这样我们就可以用如下示例演示代码来用printf显示浮点数。仅供参考。
/***************************************************
* 以下代码用来演示用printf在USART上显示浮点数。 *
*注意:将要显示的浮点数转成两个变量,分别表示 *
*浮点数小数点左边部分和右边部分。小数点右边不 *
*需要的数据可按需要用适当的算法加以取舍。 *
****************************************************/
float fInput=356.9876; // Pick a number
long lWhole=0; // Stores digits left of decimal
unsigned long ulPart=0; // Stores digits right of decimal
#define MULTIPLIER 100 //(use 1 for no decimals, 10 for 1 place,
// 100 for 2 places, etc)
#include
#include // choose your device as needed
void main(void)
{
// Set up the USART for output (not required, but since printf sends to the USART, it makes the output readable in the
// output window). You also can use OpenUSART liabrary functions.
SPBRG=15;
TXSTA=0x24;
RCSTA=0x90;
//Alternative
//OpenUSART( USART_TX_INT_OFF &
USART_RX_INT_OFF &
USART_ASYNCH_MODE &
USART_EIGHT_BIT &
USART_CONT_RX &
USART_BRGH_HIGH,
129 ); //19.2K baud rate
//Convert number from float to fixed point for display.
//The number is converted to two parts.
lWhole=(long)((float)fInput);
ulPart=(long)((float)fInput*MULTIPLIER)-lWhole*MULTIPLIER;
printf((far char *)"The floating point number is: %li.%li\n",lWhole,ulPart);
while(1); // wait forever
}
//EOF
在上面示例代码里,使用100作为乘积因数,这样显示的精度就是小数点后两位。依次类推,1000 显示小数点后三位等等。
在软仿真环境里,可使能UART1 I/O。这样 MPLAB SIM 就会显示输出值到 OUTPUT 窗口 SIM Uart1视里。
显示结果是:The floating point number is: 356.98 。
[本帖最后由 bellstudio 于 2013-3-31 10:46 编辑]