【问题标题】:How do I write integers to a micro SD card on an Arduino如何将整数写入 Arduino 上的微型 SD 卡
【发布时间】:2017-03-04 23:14:40
【问题描述】:

当写入功能只接受整数时,如何让 Arduino 将测量数据写入 micro SD 卡?

#include <SD.h>
#include <SPI.h>

int CS_PIN = 10;
int ledPin = 13;
int EP =9;



File file;

void setup()
{

  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(EP, INPUT);

  initializeSD();



}


void loop(){
  long measurement =TP_init();
  delay(50);
 // Serial.print("measurment = ");
  Serial.println(measurement);

  createFile("test.txt");
  writeToFile(measurement);
  closeFile();
}



long TP_init(){
  delay(10);
  long measurement=pulseIn (EP, HIGH);  //wait for the pin to get HIGH and   returns measurement
  return  String(measurement);

}





void initializeSD()
{
  Serial.println("Initializing SD card...");
  pinMode(CS_PIN, OUTPUT);

  if (SD.begin())
  {
    Serial.println("SD card is ready to use.");
  } else
  {
    Serial.println("SD card initialization failed");
    return;
  }
}

int createFile(char filename[])
{
  file = SD.open(filename, FILE_WRITE);

  if (file)
  {
    Serial.println("File created successfully.");
    return 1;
  } else
  {
    Serial.println("Error while creating file.");
    return 0;
  }
}

int writeToFile(char text[])
{
  if (file)
  {
    file.println(text);
    Serial.println("Writing to file: ");
    Serial.println(text);
    return 1;
  } else
  {
    Serial.println("Couldn't write to file");
    return 0;
  }
}

void closeFile()
{
  if (file)
  {
    file.close();
    Serial.println("File closed");
  }
}

int openFile(char filename[])
{
  file = SD.open(filename);
  if (file)
  {
    Serial.println("File opened with success!");
    return 1;
  } else
  {
    Serial.println("Error opening file...");
    return 0;
  }
}

String readLine()
{
  String received = "";
  char ch;
  while (file.available())
  {
    ch = file.read();
    if (ch == '\n')
    {
      return String(received);
    }
    else
    {
      received += ch;
    }
  }
  return "";
}

【问题讨论】:

  • 为什么将TP_init() 的返回值声明为long 并在函数内部返回String (return String(measurement);)?

标签: arduino microcontroller arduino-uno arduino-ide


【解决方案1】:

您可以使用接受缓冲区和字节计数的write 函数的变体写入一个4 字节的long 值。只需传递您要写出的变量的地址和类型的大小:

long measurement;

file.write((byte*)&measurement, sizeof(long)); // write 4 bytes

你可以这样读:

file.read((byte*)&measurement, sizeof(long)); // read 4 bytes

【讨论】:

  • 你是什么意思,我会在写入文件功能中放入文件,写入内容吗?
  • writeToFile函数写入一串字符,所以不能放在那里。写另一个函数 writeLongToFile 或类似的
猜你喜欢
  • 1970-01-01
  • 2021-12-30
  • 2020-04-29
  • 2017-05-06
  • 2022-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多