我有一个变量应该转换成字符在LCD上显示,我的问题是当我用sprintf将这个整数转换为字符时,它显示错误的数字,超过4个长度的数字显示不正确,它只正确地显示长度4以下的数字。
我的微控制器是ATmega16a IDE是CodeVisionAVR,语言是C
unsigned long int username;
char show[20];
unsigned long int ScanKey(void)
{
unsigned long int num = 0;
_lcd_write_data(0x0F);
PORTC .2 = 1;
while (1)
{
PORTD .0 = 0;
PORTD .1 = 1;
PORTD .2 = 1;
delay_ms(5);
if (PIND .3 == 0)
{
while (PIND .3 == 0;
lcd_putchar('1');
num = (num * 10) + 1;
}
else if (PIND .4 == 0)
{
while (PIND .4 == 0);
lcd_putchar('4');
num = (num * 10) + 4;
}
else if (PIND .5 == 0)
{
while (PIND .5 == 0);
lcd_putchar('7');
num = (num * 10) + 7;
}
else if (PIND .6 == 0)
{
while (PIND .6 == 0);
_lcd_write_data(0x10);
lcd_putchar(' ');
_lcd_write_data(0x10);
num /= 10;
}
PORTD .0 = 1;
PORTD .1 = 0;
PORTD .2 = 1;
delay_ms(5);
if (PIND .3 == 0)
{
while (PIND .3 == 0);
lcd_putchar('2');
num = (num * 10) + 2;
}
else if (PIND .4 == 0)
{
while (PIND .4 == 0);
lcd_putchar('5');
num = (num * 10) + 5;
}
else if (PIND .5 == 0)
{
while (PIND .5 == 0)
;
lcd_putchar('8');
num = (num * 10) + 8;
}
else if (PIND .6 == 0)
{
while (PIND .6 == 0);
lcd_putchar('0');
num = (num * 10) + 0;
}
PORTD .0 = 1;
PORTD .1 = 1;
PORTD .2 = 0;
delay_ms(5);
if (PIND .3 == 0)
{
while (PIND .3 == 0);
lcd_putchar('3');
num = (num * 10) + 3;
}
else if (PIND .4 == 0)
{
while (PIND .4 == 0);
lcd_putchar('6');
num = (num * 10) + 6;
}
else if (PIND .5 == 0)
{
while (PIND .5 == 0);
lcd_putchar('9');
num = (num * 10) + 9;
}
else if (PIND .6 == 0)
{
while (PIND .6 == 0);
break;
}
}
PORTC .2 = 0;
_lcd_write_data(0x0C);
return num;
}
lcd_clear();
lcd_putsf("Enter Username:");
lcd_gotoxy(0, 1);
sprintf(show, "%lu", username);
lcd_puts(show);这不是我的全部代码,这是我有问题的部分。
我输入这个56321

输出如下

https://files.fm/f/qpwrmfs6h,这是视频。
我尝试了%ul和%lu,%ul有相同的问题,%lu输出是这样的


我的英语不太好,我很难补充细节。
发布于 2021-07-05 14:03:19
printf和scanf函数。它们是资源贪婪的,不太适合这种类型的micros.printf实现,而scanf实现是有限的,并且不支持许多formats.中尝试使用16位。
#define MASK32ULONG 1000000000UL
#define MASK16UINT 10000
char *toDecimal(char *buff, unsigned long val)
{
unsigned long mask = MASK32ULONG;
unsigned long remain;
char *wrk = buff;
do
{
int digit = val / mask;
if(digit || !val) *wrk++ = '0' + digit;
val %= mask;
mask /= 10;
}while(val);
*wrk = 0;
return buff;
}发布于 2022-06-08 06:59:23
使用%lu然后转到project->配置->c编译器,然后将printf更改为长、宽、精度。
https://stackoverflow.com/questions/68257239
复制相似问题