【发布时间】:2020-06-29 15:07:23
【问题描述】:
我正在尝试将 uint8_t readData[10] = "123456789" ; 转换为 unsigned long 以在 Arduino 中对此值进行一些数学运算。我正在使用 strtoul 功能。 strtoul 如果我自己定义了上面的数组并且它成功地将这个数组转换为unsigned long,则工作正常。 但是如果我通过读取 DS1307 NVRAM 将一些值放入这个数组,那么 strtoul 无法将数组转换为 unsigned long并给出 0 答案。我在读取 NVRAM 后使用 for 循环检查了 readData 数组中的值,发现这些值与我保存在 NVRAM 中的值相同。
我正在使用 NodeMCU 板和 DS1307。我的代码及其输出如下所示。
// Example of using the non-volatile RAM storage on the DS1307.
// You can write up to 56 bytes from address 0 to 55.
// Data will be persisted as long as the DS1307 has battery power.
#include "RTClib.h"
RTC_DS1307 rtc;
uint8_t readData[9] = "0"; //**this will store integer values from DS1307 NVRAM.
unsigned long convertedL1 = 0; //this will store converted value
uint8_t savedData[10] = "123456789"; //I have already filled this array for testing strtoul function.
unsigned long convertedL2 = 0; //this will store converted value of savedData array
void setup () {
Serial.begin(9600);
delay(3000);
#ifndef ESP8266
while (!Serial); // wait for serial port to connect. Needed for native USB
#endif
if (! rtc.begin()) {
Serial.println("Couldn't find RTC");
delay(3000);
while(1);
}
rtc.readnvram(readData,9,2); //Read NVRAM from address 2 to 11.
delay(20);
Serial.println("Prinitng values( using loop) stored in readData array, after reading NVRAM :");
for (int i = 0; i <9; i++) {
Serial.print(readData[i]);
}
Serial.println();
//Converting both arrays of same type using stroul
convertedL1 = (unsigned long)strtoul((char *)&readData[0],NULL,10);
convertedL2 = (unsigned long)strtoul((char *)&savedData[0],NULL,10);
Serial.print("converted value of readData array = ");
Serial.println(convertedL1);
Serial.println();
Serial.print("converted value of savedData array = ");
Serial.println(convertedL2);
}//setup end
void loop () {
// Do nothing in the loop.
}
串行监视器上的输出是:
Prinitng values( using loop) stored in readData array, after reading NVRAM :
123456789
converted value of readData array = 0
converted value of savedData array = 123456789
为什么 strtoul 函数适用于一个数组而不适用于其他数组。我搜索了许多论坛但找不到任何解决方案。 任何人都可以,请查看我的代码并建议我解决方案。任何帮助将不胜感激。
【问题讨论】:
-
strtoul需要一个字符串。readData是否有号码chars 并且NUL已终止? -
readData里面只有数字,但在被rtc.readnvram函数访问后,它并没有被NUL终止。我添加了'\0',它起作用了。