본문 바로가기
카테고리 없음

아두이노를 이용한 데이터 저장 -#5

by 오징어땅콩2 2020. 9. 3.
반응형

 

 

이전에 공부했던것을 잠시 복습하고 가자.

하지않고 가면 섭섭한 사람도 있을것 같아서 조금 다시 볻다면,

 

실제로 SD카드를 초기화 하고 파일에 쓰는 문장은 몇줄 되지 않는다.

파일을 열고, 파일에 쓰고, 파일을 닫고 이런식인데

이것은 모든 언어 공통이라고 이해하는것이 좋을것 같다.

우리도 일기를 적는다고 한다면 읽기장을 열고, 글을쓰고, 읽기장을 닫는다는 개념과 유사하다.

어렵게 생각해도 실제로 하는것은 단순하다.

물론 기본이라서 단순 할 수가 있지만, 실제로 단순하다.

그리고 단순하게 접근해야 한다.

만약 어렵게 접근하면 멀티 프로세스, 멀티 쓰레드같은 다중환경에서 100% 오류가 발생한다.

단순한 코딩이 최고의 코딩이다.

 

 
#include <SPI.h>
#include <SD.h>
 
File myFile;
volatile unsigned long previousMillis;
 
void setup() 
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) 
  {
    ; // wait for serial port to connect. Needed for native USB port only
  }
 
 
  Serial.print("Initializing SD card...");
 
  if (!SD.begin(10)) 
  {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");
  previousMillis = millis(); 
  
}
 
void loop() 
{
    unsigned long currentMillis = millis();
 
    if ((currentMillis-previousMillis)> 1000*1)
    {
        myFile = SD.open("test.txt", FILE_WRITE);
        // if the file opened okay, write to it:
        if (myFile) 
        {
              previousMillis = currentMillis;
              Serial.print("Writing to test.txt...");
                           
              char buf[100];
              sprintf(buf,"xxxxxxxxxxxxxxxxx!!");
              myFile.println(buf);            
              myFile.close();
              
              Serial.println("done.");
        } 
        else 
        {
              // if the file didn't open, print an error:
              Serial.println("error opening test.txt");
        }
    }
    delay(100);
}
 

댓글