我有一个 Arduino,它从我的智能手机(通过蓝牙)接收包含 unix 时间戳的消息。现在,我正在尝试将我的 DS1307 与该时间戳同步。
但是,它不起作用,因此,我开始搜索并在将包含时间戳的 C 样式数组转换为浮点数时发现了一些奇怪的行为。
// Copy the time into "timeBuff"
int timeLength = siz - _CAT_LENGTH_;
char timeBuff[timeLength+1];
memcpy(timeBuff, &msg[_CAT_LENGTH_], timeLength);
timeBuff[timeLength] = '\0';
// For debugging
Serial.print(F("timeBuff: "));
Serial.println(timeBuff);
// Convert timeBuff string into a variable of type long
float deviceTime = atof(timeBuff);
// Now, deviceTime != what we printed above
Serial.print(F("Epoch time: "));
Serial.println(deviceTime);
前 5 行将消息的右侧部分复制到一个字符数组中,并添加终止零。
之后,我们打印 的内容timeBuff
并将其转换float
为存储在deviceTime
. 最后,我们打印deviceTime
.
这是我第一次测试的结果
timeBuff: 1476113620
Epoch time: 1476113664.00
这是第二个测试
timeBuff: 1476115510
Epoch time: 1476115456.00
为什么结果atof
与我们传递的字符串不同?