Arduino从Txt读取整数

Arduino Read Integer From Txt

本文关键字:整数 读取 Txt Arduino      更新时间:2023-10-16

我正试图从sd卡中读取我的integer txt文件。

我的txt有这两行(第一行是1,第二行是\n(;

1

我做了一个读者代码类似;

#include <SD.h>
#include <SPI.h>
File myFile;
int pinCS = 53;
void setup() {

Serial.begin(9600);
pinMode(pinCS, OUTPUT);

// SD Card Initialization
if (SD.begin())
{
Serial.println("SD card is ready to use.");
} else
{
Serial.println("SD card initialization failed");
return;
}
// Reading the file
myFile = SD.open("test.txt", FILE_READ);
if (myFile) {
Serial.println("Read:");
// Reading the whole file
while (myFile.available()) {
Serial.write(myFile.read());
}
myFile.close();
}
else {
Serial.println("error opening test.txt");
}

}
void loop() {
// empty
}

它有效,但我想要的是从txt文件中读取我的整数,并与另一个整数求和(即我下面代码中的int total。我尝试过,但它不起作用;

#include <SD.h>
#include <SPI.h>
File myFile;
int pinCS = 53; // Pin 10 on Arduino Uno
int total = 3;
void setup() {

Serial.begin(9600);
pinMode(pinCS, OUTPUT);

// SD Card Initialization
if (SD.begin())
{
Serial.println("SD card is ready to use.");
} else
{
Serial.println("SD card initialization failed");
return;
}
// Reading the file
myFile = SD.open("test.txt", FILE_READ);
if (myFile) {
Serial.println("Read:");
// Reading the whole file
while (myFile.available()) {
total += myFile.read();
Serial.write(total);
}
myFile.close();
}
else {
Serial.println("error opening test.txt");
}

}
void loop() {
// empty
}

我错过了什么?你能修改我的代码吗?

read()读取一个字符,因此必须将字符序列转换为整数值。

while (myFile.available()) {
total += myFile.read();
Serial.write(total);
}

应该是

int current = 0;
while (myFile.available()) {
int c = myFile.read();
if ('0' <= c && c <= '9') {
current = current * 10 + (c - '0');
} else if (c == 'n') {
total += current;
current = 0;
Serial.write(total);
}
}