首页 > 解决方案 > Arduino 从 Txt 读取整数

问题描述

我正在尝试从 sd 卡读取我的整数 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
}

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

标签: javac++arduinoreadfilesd-card

解决方案


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

推荐阅读