我写信给一个LCD,并已开发的驱动程序,以接受一个字符串输入的价值。我有一个叫做“循环”的变量,它是一个uint16。我需要将该值转换为字符串并将其写入显示器。我的字符串写函数原型如下:
void lcd_string(uint8_t column, uint8_t page, const uint8_t *font_address, const char *str)我显示该值的方法是将该值分解为单个数字,并将它们单独写入在适当位置的显示器上。
下面的代码适用于我想要做的事情,但如果可能的话,我想消除long if/else if语句。
loop = 0;
while (cycles_1 > 0) {
temp = cycles_1 % 10;
if (temp == 9) lcd_string(36 - (6 * loop),6,font_6x8_num,"9");
else if (temp == 8) lcd_string(36 - (6 * loop),6,font_6x8_num,"8");
else if (temp == 7) lcd_string(36 - (6 * loop),6,font_6x8_num,"7");
else if (temp == 6) lcd_string(36 - (6 * loop),6,font_6x8_num,"6");
else if (temp == 5) lcd_string(36 - (6 * loop),6,font_6x8_num,"5");
else if (temp == 4) lcd_string(36 - (6 * loop),6,font_6x8_num,"4");
else if (temp == 3) lcd_string(36 - (6 * loop),6,font_6x8_num,"3");
else if (temp == 2) lcd_string(36 - (6 * loop),6,font_6x8_num,"2");
else if (temp == 1) lcd_string(36 - (6 * loop),6,font_6x8_num,"1");
else if (temp == 0) lcd_string(36 - (6 * loop),6,font_6x8_num,"0");
cycles_1 /= 10;
loop++;
}我尝试了以下操作,但字符串并没有写入显示。
loop = 0;
while (cycles_1 > 0) {
temp = cycles_1 % 10;
lcd_string(36 - (6 * loop),6,font_6x8_num,{0x30 + temp, '\0'});
cycles_1 /= 10;
loop++;
}我认为将0x30添加到temp值会将其转换为ASCII号,然后使用空终止字符终止它,但这似乎不起作用。有什么我可以尝试的建议吗?
发布于 2022-11-21 18:49:29
如果在0到9之间有一个名为temp的数字,则可以使用以下代码将其转换为带有空终止符的1-字符C字符串:
char str[2] = { '0' + temp };没有必要对每一个数字都有单独的情况。
发布于 2022-11-22 11:54:40
当您标记问题avr时,您正在使用用于AVR的GNU工具,这些工具使用AVR作为它们的libc实现。它提供utoa,它将unsigned (即uint16_t)转换为字符串。注意,utoa是不标准的。
#include <stdlib.h>
#include <stdint.h>
...
uint16_t cycles_1 = 12345;
char buf[6];
utoa (cycles_1, buf, 10);
lcd_string (..., buf, ...);如果cycles_1是16位有符号类型,则有itoa.
utoa和itoa是在汇编中实现的,它们速度快,脚印小.他们不使用除法或模组。
如果您真的想单独输出每个字符,则可以
char buf[2], var = 3;
buf[1] = '\0';
buf[0] = '1'; lcd_string (..., buf, ...);
buf[0] = '2'; lcd_string (..., buf, ...);
buf[0] = '0' + var; lcd_string (..., buf, ...);
...或者,在您的代码中使用它:
uint8_t loop = 0;
while (cycles_1 > 0)
{
char temp = cycles_1 % 10;
char str[2] = { '0' + temp, 0 };
lcd_string (36 - loop, 6, font_6x8_num, str);
cycles_1 /= 10;
loop += 6;
}但是,请注意,这是缓慢和昂贵的,因为它需要除法(也许也是模块化)的每一个数字。
https://stackoverflow.com/questions/74523418
复制相似问题