提问者:小点点

无法将uint8_t数组转换为Arduino中的无符号长


我正在尝试将uint8_t readdata[10]=“123456789”;转换为unsigned long,以便在Arduino中对该值进行一些计算。 我在用strtoul函数。 如果我自己定义上面的数组,strtoul可以很好地工作,并且它成功地将这个数组转换为unsigned long。 但是如果我通过读取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函数只处理一个数组而不处理另一个数组。我搜索了很多论坛,但没有找到任何解决方案。 任何人都可以,请看看我的代码,并好心建议我的解决方案。 任何帮助都将不胜感激。


共1个答案

匿名用户

这一差异的原因可能是您的saveData数组是null erminated的,而readData数组不是null erminated的。 strtoul要求数组以空终止。