无法在 Arduino 中uint8_t数组转换为无符号长整型数组



我正在尝试将uint8_t readData[10] = "123456789" ;转换为unsigned long,以便在Arduino中对此值进行一些数学运算。我正在使用strtoul函数。如果我自己定义上面的数组并且它成功地将该数组转换为unsigned long,strtoul工作正常。但是,如果我通过读取DS1307 NVRAM在此数组中输入一些值,则strtoul无法将数组转换为无符号长整型并给出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函数适用于一个数组而不是另一个数组。我搜索了许多论坛,但找不到任何解决方案。 任何人都可以,请看一下我的代码,并请向我建议解决方案。任何帮助将不胜感激。

似乎差异的原因可能是您的savedData数组以 null 结尾,但您的readData数组不是。strtoul要求数组以空值终止。

像这样更改代码

uint8_t readData[10] = "0"; // one extra byte for null terminator
...
rtc.readnvram(readData,9,2); //Read NVRAM from address 2 to 11.
readData[9] = '';          // add the null terminator

最新更新