Wrong output sprintf C51 8051 MCU embedded system

223 views Asked by At

I have the following fragment of C code for an AT89S52 microcontroller:

unsigned char x = 0x10;
unsigned char str[21];

sprintf(str, "%u", (x >> 4) );

sprintf function prototype in stdio.h:

extern int sprintf  (char *, const char *, ...);

Can someone tell me why does my string contain "256" instead of "1" ?, the x variable isn't even big enough to hold the 256 value.

I'm compiling with KEIL uVision 5, using the standard stdio.h library.

If I use:

void UlToStr(char *s, unsigned long bin, unsigned char n)
{
    s += n;
    *s = '\0';

    while (n--)
    {
        *--s = (bin % 10) + '0';
        bin /= 10;
    }
}

instead of sprintf the string holds a '1'.

Im verifying the content of the string printing it through a char-LCD 40x4 (KS 0066 compatible controller)

str_lecd1(str);

with the following functions:

void str_lcd1(unsigned char *a)
{
    int i;
    for(i=0;a[i]!='\0';i++)
     data_lcd1(a[i]);
    delay(10);
}

void data_lcd1(unsigned char x)
{
    P1 = x;
    rs = 1;
    en1 = 1;                
    delay(4);
    en1=0;
    delay(4);
}
0

There are 0 answers