c++ - 在TFT上显示日期而不使用char形式的数字数组

标签 c++ arduino arduino-c++

我正在尝试从DateTime实例将一个月的某天写入TFT显示。 DateTime实例的数据来自RTC。

基本上,我正在尝试这样做:

DateTime timenow;
timenow = rtc.now();                      // Get and store the current RTC data as DateTime.
tft.textWrite(timenow.day());             // This doesn't work (see below), but it shows the idea of what I am trying to do.
tft.textWrite接受char作为其参数,但是timenow.day()似乎输出int。我能够使它工作的唯一方法(显然,这不是一个好方法,正如您将看到的那样)是通过将从1到31的所有数字作为char组成一个巨大的数组:

const char days[31][3] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"};

然后我在代码中使用了数组:

DateTime timenow;
timenow = rtc.now();                      // Get and store the current RTC data as DateTime.
tft.textWrite(days[timenow.day() - 1]);

不幸的是,这一年我必须做同样的事情,而且我无法在可预见的将来将所有年份手动输入到数组中。这将占用内存,此外,这将不必要地耗时。

我的问题是,有人可以告诉我如何从int转换为char以便在此函数中使用,而无需庞大的数组?

我已经尝试了从String(timenow.day())char(timenow.day())char(String(timenow.day()))之类的所有东西,但它们似乎都不起作用。

最佳答案

您需要将整数转换为字符串。

    int day = timenow.day();
    char str[12];
    sprintf(str, "%d", day);
    tft.textWrite(str);

编辑:

代码说明:
  • 首先,我们将timenow.day()的整数值存储到day中;
  • 然后,我们在此处声明一个char数组,以存储int daychar. It will be used in the的转换sprintf()function call. This char array must be big enough to hold the conversion string. So that is why I used char str [12]`。因此,我们有12个字节来存储转换后的值。
  • sprintf(str, "%d", day)char *作为其存储转换的第一个参数。第二个参数是要获取的输出字符串的格式。然后,下一个参数是您传递的格式字符串所需的参数,在这种情况下,它是"%d",这意味着我们需要为其提供一个整数值。这就是为什么我们将day变量作为最后一个参数传递的原因。

  • 您可以通过在Linux终端中运行sprintf来获得man sprintf功能的更多详细信息。否则,您可以获得更多信息here

    关于c++ - 在TFT上显示日期而不使用char形式的数字数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61108757/

    相关文章:

    c++ - 追加到 std::array

    c++ - 中断创建arduino库

    c# - Arduino串口,数据未到达

    c++ - 错误消息 : Invalid operands of types 'float' and 'int' to binary 'operator%'

    C++ 从 'const char*' 到 'char*' 的无效转换 Arduino Uno

    c++ - 可以访问容器值/变量的子项(框和内容示例)

    c++ - 通过路径获取 Windows 可执行文件的显示名称

    c++ - 是否可以在 C++ 中构建没有依赖项的 DLL?

    c++ - AVR CTC 模式下的 16 位定时器

    c++ - 类内部的数组初始化器