Arduino从Txt读取整数
Arduino Read Integer From Txt
我正试图从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);
}
}
相关文章:
- 如何在c++中从文本文件中逐行读取整数
- Arduino从Txt读取整数
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 从二进制文件中读取整数数组
- 如何从字符串C++读取多个整数
- 使用字符串流读取整数并将它们相加
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 如何使用字符和整数C 读取文件
- 从文件到短 /长整数读取字节
- do整数读取需要受到关键部分的保护
- 此项目不会将整数读取为二进制并将其作为二进制输出到新文件
- 将连续字节作为一个整数读取
- 如何将文件中的整数读取到动态数组中
- 如何将字符串读取为字符串向量或将整数读取为整数向量
- 将文件中的间隔整数读取到C++数组中
- 将文件中的整数读取到C++中的向量中
- 如何在C++中将空格和换行符分隔的整数读取到2D数组中
- 将一组整数读取为C++中的字符串
- 我如何得到多行字符串和整数读取和输入文件,并在c++中显示
- 通过无符号整数读取无符号字符数组未定义,因此不安全