Hello! I am having trouble pulling data from a pressure sensor and writing it to an SD card. It seems that I can either pull accurate data and NOT write to the card, or pull inaccurate data and successfully write to the card. This setup is SPI, using an Adafruit BMP280, an Adafruit SD SPI Card Breakout, and a Teensy 3.2.
When I comment out the following if-statement, the data is accurate but cannot write to the card:
if (!SD.begin(SD_CS_PIN)) {
Serial.println("initialization failed!");
return;
} else {
Serial.println("initialization done.");
}
I cannot understand how this if-statement affects the data and/or writing capability so significantly. I'm sure it's something silly. Here is the entirety of the code, please let me know if you can help!
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_BMP280.h>
#include <SdFatConfig.h>
#include <SdFat.h>
#define BMP_SCK (2)
#define BMP_MISO (12)
#define BMP_MOSI (11)
#define BMP_CS (A7)
#define SD_CS_PIN 10
//Adafruit_BMP280 bmp; // I2C
//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI
Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO, BMP_SCK);
#include "SdFat.h"
#include "SdFatConfig.h"
SdFat SD;
File myFile;
void setup() {
Serial.begin(9600);
Serial.println(F("BMP280 test"));
//if (!bmp.begin(BMP280_ADDRESS_ALT, BMP280_CHIPID)) {
if (!bmp.begin()) {
Serial.println(F("Could not find a valid BMP280 sensor, check wiring or "
"try a different address!"));
while (1) delay(10);
}
/* Default settings from datasheet. */
bmp.setSampling(Adafruit_BMP280::MODE_NORMAL, /* Operating Mode. */
Adafruit_BMP280::SAMPLING_X2, /* Temp. oversampling */
Adafruit_BMP280::SAMPLING_X16, /* Pressure oversampling */
Adafruit_BMP280::FILTER_X16, /* Filtering. */
Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */
// 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(SD_CS_PIN)) {
Serial.println("initialization failed!");
return;
} else {
Serial.println("initialization done.");
}
}
void loop() {
myFile = SD.open("test.txt", FILE_WRITE);
// if the file opened okay, write to it:
if (myFile) {
Serial.print("Writing to test.txt...");
myFile.print(bmp.readTemperature());
myFile.print('\t');
myFile.print(bmp.readPressure());
myFile.print('\t');
myFile.println(bmp.readAltitude(1013.25));
myFile.close();
// close the file:
Serial.println("done.");
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
Serial.print(F("Temperature = "));
Serial.print(bmp.readTemperature());
Serial.println(" *C");
Serial.print(F("Pressure = "));
Serial.print(bmp.readPressure());
Serial.println(" Pa");
Serial.print(F("Approx altitude = "));
Serial.print(bmp.readAltitude(1013.25)); /* Adjusted to local forecast! */
Serial.println(" m");
Serial.println();
delay(4000);
}