sprintf() on the PIC 10/12/16 Series

19 June, 2009 (18:27) | PIC, Tutorials | By: Joshua

I mentioned sprintf() briefly in my post about communicating between your PIC and the computer but have since learned a couple things I think others could benefit from. So this is going to be a kinda hodge-podge post.

First, I threw together a quick function that will take any number, convert it to ASCII, and then send it out to the computer. It’s not fancy, like most of my programming, but it is functional if you just want an idea of where to start.


void transmit_comp(volatile unsigned int a) {
unsigned int i;
unsigned char a_ASCII[4];

sprintf(a_ASCII,"%d",a); // Convert it to ASCII

for (i = 0; i < 4; i++) // Loop to transmit each character
transmit(a_ASCII[i]);
}

void transmit(volatile unsigned int a) {
TXEN = 1; // Transmit enabled
TXREG = a; // Transmitting the requested character.
while (!TRMT) continue;
TXEN = 0;
return;
}

You are limited to printing out as many numbers (or characters) as the value of i in the above code. Setting i to a large number has no noticeable effect when looking at it in your console but it has two downsides. It uses up data space on your PIC and also each of those blank characters have to be transmitted, taking time. So be wise in your selection of i.

One obvious thing about the code above is that it only prints out integers. So what about longs and floats? What can we do? sprintf() is designed to be able to handle floats, doubles, and longs. However, what about those of us using the free compiler, either the PICC-lite or its replacement, the HI-TECH C PRO for the PIC10/12/16 MCU Family (whew! long name)? We are out of luck.

For some reason, any attempts to sprintf a float, it outputs the ASCII character “f”. I honestly don’t know why. This occurs in both compilers.

If you’re still using the PICC-lite, you can go to Properties->C/C++ Build->Tool Setting->Linker->Printf and set it so that it prints integers, longs, and floats. Doing this can create a new error saying that you need a library called “pcl40c-f.lib”. I never could find this file. This error will disappear if you switch to the newer HI-TECH C PRO compiler, but you will still only be creating the letter “f” as an output.

Screenshot of the Setup Screen

While I’m not positive, I believe this only applies to the smaller PICs. 18 series and above should be able to output floats.

Not a lot of help, but hopefully this will at least save time tearing your hair and trying to figure out why it’s not working.

Comments

Comment from Joshua
Time February 4, 2011 at 4:42 pm

Floats should actually be useable if you’re using the non-free compiler. For poor people such as myself, it may be little bit before I can afford an investment such as that.

Write a comment