10 years, 8 months ago.

Sending data mbed to mbed lpc1768

Hi guys.

I'm trying to send an integer from one lpc1768 to another over serial. the approach i am trying to take is converting the int which is number between 0 and 256 into a char, i've writen a little routine to chop take the digits from the number one at a time to store them into a char[4] and then try to send the char all at once. I understand that using printf is not the best way because printf function is not buffered. i am trying to use putc/s the code thats in this listing is from testing with tera term. its slicing the digits, but not printing the contents of the char. Could any one of you great people point out to me where i am going wrong. I've searched it on the forum, there are many string on the topic. thanks a million

include the mbed library with this snippet


/*
*   Converting string to int
*
*/

#include "mbed.h"
#include "math.h"
//  creating objects
Serial pc(USBTX, USBRX);
// variable declaration

unsigned int val = 1234;
int a;
int store;
int b;
char box[4];
 
int main()
{
            
            for(int i = 0; i < 4 ; i++)             // 
            {
                store =  val % 10 ;                                 // read and save the last digit in the number
                pc.printf("  \n store  =  %d",store);  
                store = store + 48;                                 // adding 48 to match the ascii value of the number in store
                box[i]= store;
                                                    // copy the value in store into location i of box
                pc.printf("\n c =  %s",box);
                val /=10;                                           // getting rid of the last digit in the sequence 
                pc.printf("\n sliced  = %d", val);                      
                store = 0;
                
            }
        //    box = 'w';
           
}

1 Answer

10 years, 8 months ago.

printf() will find the end of the string by looking for a 'zero' value. So in your case you should make sure that 'box' has enough space (5 bytes) for the digits and the terminating 0 and you should do something like this to always have the zero at the end:

box[i]= store;
box[i+1]= 0;  //make sure string is terminated

Also note that the printed string will be reversed (4321) wrt to the input val because of the way you process and store the digits.