简体   繁体   English

Arduino 从 Txt 读取 Integer

[英]Arduino Read Integer From Txt

I'm trying to read my integer txt file from sd card.我正在尝试从 sd 卡读取我的 integer txt 文件。

My txt has these 2 lines (first line is 1, second is \n);我的 txt 有这两行(第一行是 1,第二行是 \n);

1

I did a reader code like;我做了一个阅读器代码,例如;

#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
}

It works but what I want is read my integer from txt file and sum with another integer (that is int total in my below code. I tried this but it doesn't work;它有效,但我想要的是从 txt 文件中读取我的 integer 并与另一个 integer 相加(在我的下面的代码中是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
}

What am I missing?我错过了什么? Can you fix my code?你能修复我的代码吗?

read() reads one character, so you have to convert the sequences of characters to integer value. read()读取一个字符,因此您必须将字符序列转换为 integer 值。

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

should be应该

    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);
      }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM