Arduino unoで超音波距離センサを用いて観測をしたいです。しかし、下記のコードで試してみたのですがうまくSDカードにデータを記録できませんでした。
コード
#define trigPin 3 // Trigger Pin double Duration = 0; //受信した間隔 double Distance = 0; //距離 #include <SPI.h> #include <SD.h> File myFile; void setup() { Serial.begin( 9600 ); pinMode( 2, INPUT ); pinMode( 3, OUTPUT ); // 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(4)) { 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() { digitalWrite(3, LOW); delayMicroseconds(2); digitalWrite( 3, HIGH ); //超音波を出力 delayMicroseconds( 10 ); // digitalWrite( 3, LOW ); Duration = pulseIn( 2, HIGH ); //センサからの入力 if (Duration > 0) { Duration = Duration / 2; //往復距離を半分にする Distance = Duration * 340 * 100 / 1000000; // 音速を340m/sに設定 Serial.print("Distance:"); Serial.print(Distance); Serial.println(" cm"); } delay(500); }
確認ですが、「データをマイクロSDカードに記録」する方法(コード)が判らないので教えてほしい、という質問なのですよね?
そうです。お願いします。
「うまくSDカードにデータを記録できませんでした」との事ですが、シリアル通信から何が出力されますか? loop()の中は"delay(1000);"だけにして、setup()の中もSerialの初期化とSDカードの初期化、読み、書きだけにして、動作を追ってみることをお勧めします。
また、SDカードとArduino Unoとの接続はどうなっていますか? Arduino Uno自体にはSDカードスロットがついていないので、何らかの拡張ボード(シールド)か、ブレッドボードを使ってSDカードとつないでいると思うのですが。
WIRELESS SD SHIELDで接続しています。