This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Compiler/TM4C123GH6PM: Build success but sprintf not working

Part Number: TM4C123GH6PM

Tool/software: TI C/C++ Compiler

Here is my code:


#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "driverlib/gpio.h"
#include "driverlib/pin_map.h"
#include "driverlib/rom.h"
#include "driverlib/sysctl.h"
#include "driverlib/uart.h"
#include "utils/uartstdio.h"
#include "driverlib/adc.h"

int a=100;
char buffer[10];
int length;
void UARTprint(char *cmd)
{
while(UARTBusy(UART0_BASE));
while(*cmd != '\0')
{
UARTCharPut(UART0_BASE, *cmd++);
}
//UARTCharPut(UART1_BASE, '\r'); //CR
//UARTCharPut(UART1_BASE, '\n'); //LF

}

void delayms(uint32_t time)
{
SysCtlDelay(time*(SysCtlClockGet()/3/1000));
}

int main(void) {

SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ);
SysCtlPeripheralEnable(SYSCTL_PERIPH_UART0);
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
GPIOPinConfigure(GPIO_PA0_U0RX);
GPIOPinConfigure(GPIO_PA1_U0TX);
GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);
UARTConfigSetExpClk(UART0_BASE, SysCtlClockGet(), 115200,(UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE | UART_CONFIG_PAR_NONE));

UARTCharPut(UART0_BASE, 't');
sprintf(buffer,"%d",a);
while (1)
{

UARTCharPut(UART0_BASE, buffer );
delayms(500);

}
}



when i run this code the output of UART only letter 't' and i cannot see the number 100 . Plz help me (sr for my bad English)

  • Try this:

    UARTCharPut(UART0_BASE, 't');
    sprintf(buffer,"%d",a);
    for (int i=0;i<strlen(buffer);i++)
    {
       UARTCharPut(UART0_BASE, buffer[i] );
       delayms(500);
    }
    
  • It not work. I used Watch Expressions and i see that the buffer value doesn't have any value inside
  • You might need to increase the heap. sprintf() is greedy.

    You can also adapt K&R's itoa() code:

    /* itoa:  convert n to characters in s */
     void itoa(int n, char s[])
     {
        . int i, sign;
     
         if ((sign = n) < 0)  /* record sign */
             n = -n;          /* make n positive */
         i = 0;
         do {       /* generate digits in reverse order */
             s[i++] = n % 10 + '0';   /* get next digit */
         } while ((n /= 10) > 0);     /* delete it */
         if (sign < 0)
             s[i++] = '-';
         s[i] = '\0';
         reverse(s);
     }
    
    
    #include <string.h>
     
     /* reverse:  reverse string s in place */
     void reverse(char s[])
     {
         int i, j;
         char c;
     
         for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
             c = s[i];
             s[i] = s[j];
             s[j] = c;
         }
     }