简体   繁体   中英

Write from Serial Port to SD card

I am trying to write from the Serial Port to an SD Card in my Arduino Mega 2560, using a card module.

I want to be able to write in a txt file what I type in the serial com.

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

const int chipSelect = 4;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.print("This is a test and should be ignored");
   if (!SD.begin(chipSelect)) {
    Serial.println("\nCard failed, or not present");
    // don't do anything more:
    return;
  }
  else{
  Serial.println("\ncard initialized.");
}
}


void loop() {
  // put your main code here, to run repeatedly
File OpenFile = SD.open("test.txt", FILE_WRITE);
  if(OpenFile and Serial.available());
  {
    OpenFile.println(Serial1.read());
    OpenFile.close();
  }
}

However a continous line of "-1" and "1", without the ", is written to the SD.

Yes, I am able to write to the SD card through other methods...

Cheers, PoP

I notice you are checking Serial.available() but using Serial 1 to read from :)

As you have a Mega, you wouldn't get an error as there is Serial and Serial1 . I'd say this is your culprit!

The Stream read function will return -1 when there is no data. Also you could lessen the load on your Arduino and do the operation all at once (not open/close for each byte) and purge all available data ( Serial.read() only reads a single byte in case you did not know).

void loop() {

  File OpenFile = SD.open("test.txt", FILE_WRITE);

  if(OpenFile){
    while(Serial.available()){
      OpenFile.println(Serial.read());
    }
    OpenFile.close();
  }
}

You may want to check if the SD lib supports appending by default or a flag like FILE_APPEND as you will overwrite the file on the next loop if more data becomes available (Serial data isn't instant, your code may loop while receiving the rest of the data).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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