Electronic – Sending integers via PIC’s USART

communicationmicrocontrollerpicserial

I need to send integers from my micro controller board (PIC16F877) to the PC. I'm using MAX232 for this. I need to use a code similar to this (coded using mikroc 8.2).

Please note that this is not correct (actually the line Usart_Write(count); will not work as intended). But it'll show what I'm trying to do.

#define BAUD_RATE 57600
#define DELAY 500
int count;

void interrupt(){
     if(INTCON.INTF == 1 ){
          count++;
          INTCON.INTF = 0;
     }
}

void setup(){
     INTCON = 0x90;
     TRISB = 0x01;
     Usart_Init(BAUD_RATE);
     count = 0;
}

void main() {
     setup();
     while(1){
        Usart_Write('>');
        Usart_Write(count);
        Usart_Write('<');
        count = 0;
        delay_ms(DELAY);
     }
}

The application is simple. The variable counter is incremented with PORTB0 interrupt and counter value is needed to be send to PC.

Can someone show me a correct (and simple) way to do this..

Best Answer

As I understand it, your problem is how to print a sequence of ASCII characters representing an integer.

You already have a function which can print a char, so you want something like the following:

char buf[16];
char *p;

sprintf(buf, "%d", count);
p = buf;
while(*p)
    Usart_Write(*p++);

If you don't have sprintf() in your C library, try itoa().

(Note for the pedants, snprintf() is safer, but not universally supported)