วันพุธที่ 22 กุมภาพันธ์ พ.ศ. 2560

การใช้งาน โมดูล Arduino SD Card module

การใช้งาน โมดูล Arduino SD Card module

ถ้าต้องการบันทึกข้อมูลการใช้งานต่าง ๆ เช่น Log File ค่าที่อ่านได้จากเซนเซอร์ ต่าง ๆ การใช้ความสามารถของ การบันทึกข้อมูลลงบน SD Card เป็นอีกทางเลือกที่เหมาะสม เพราะสามารถเก็บข้อมูลได้บริมาณมาก อุปกรณ์บันทึกข้อมูลมีราคาไม่แพง ต่อใช้งานง่าย
เราจะมาลองต่อใช้งาน Arduino SD Card Module กัน วิธีการใช้งานแบบรวดเร็ว

การต่อสายโมดูล Arduino SD Card module
2. เปิดดูโปรแกรมตัวอย่างวิธีใช้งาน ReadWrite.ino อัพโหลดลง บอร์ด Arduino

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

File myFile;

// change this to match your SD shield or module;
//     Arduino Ethernet shield: pin 4
//     Adafruit SD shields and modules: pin 10
//     Sparkfun SD shield: pin 8
const int chipSelect = 4;

void setup()
{
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }


  Serial.print("Initializing SD card...");
  // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
  // Note that even if it's not used as the CS pin, the hardware SS pin 
  // (10 on most Arduino boards, 53 on the Mega) must be left as an output 
  // or the SD library functions will not work. 
   pinMode(SS, OUTPUT);
   
  if (!SD.begin(chipSelect)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");
  
  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);
  
  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
// close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
  
  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");
    
    // read from the file until there's nothing else in it:
    while (myFile.available()) {
    Serial.write(myFile.read());
    }
    // close the file:
    myFile.close();
  } else {
  // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop()
{
// nothing happens after setup
}
3. ต่อวงจรจากโมดูล ไป Arduino Uno ดังนี้
3.3V -> 3.3V
Gnd -> Gnd
MISO -> 12
MOSI -> 11
SCLK -> 13
CS -> 4
4. ทดสอบการทำงานโดย เปิด Serial Monitor ใน Arduino IDE แล้วกดปุ่ม Reset บนบอร์ด Arduino ก็จะเห็น ข้อมูลการเขียน/อ่าน ไฟล์ที่เราต้องการ




ไม่มีความคิดเห็น:

แสดงความคิดเห็น