Проблемы с записью файлов на SD-карту Arduino.C++

Программы на C++. Форум разработчиков
Ответить
Anonymous
 Проблемы с записью файлов на SD-карту Arduino.

Сообщение Anonymous »

Я хочу создать простую станцию ​​измерения температуры, которая добавляется в файл .csv. У меня отдельные детали работают, но все детали вместе демонстрируют странные проблемы:
  • Я проверил SD-карту с помощью простой программы проверки SD-карт с официального сайта. Документ arduino (https://docs.arduino.cc/learn/programming/sd-guide/), показывающий, что SD-карта работает и подключение правильное

    < li>Я использовал следующий код, чтобы убедиться, что мои датчики температуры, ЖК-дисплей и все остальное работает.

Код: Выделить всё

//Measurement with DHT11 and Thermistor

#include 
#define DHT_SENSOR_TYPE DHT_TYPE_11 //DH11

#include [*]

static const int DHT_SENSOR_PIN = 2;
DHT_nonblocking dht_Sensor(DHT_SENSOR_PIN, DHT_SENSOR_TYPE);

int tempPin = 0; //Thermistor

// NEW LCD PINS TO CHANGE:
// LCD Display pins
//                BS  E  D4  D5  D6  D7
LiquidCrystal lcd(3,4,5,6,7,8);

//setup
void setup()
{
Serial.begin(9600);
lcd.begin(16,2);
}

static bool measurement_environment(float *temperature, float *humidity)    //DH11
{
static unsigned long measurement_timestamp = millis();

/*Measure once every second */
if(millis()-measurement_timestamp > 10000ul)
{
if (dht_Sensor.measure(temperature, humidity) == true)
{
measurement_timestamp = millis();
return(true);
}
}
return(false);
}

void loop()
{
//Thermistor
int tempReading = analogRead(tempPin);
double tempK = log(10000.0 * ((1024.0 / tempReading -1)));
tempK = 1  / (0.001129148 + (0.000234125 + (0.0000000876741 * tempK * tempK )) * tempK ); //  Temp Kelvin
float tempC = tempK - 273.15;
float tempF = (tempC * 9.0)/ 5.0 + 32.0; // Convert Celcius to Fahrenheit

//DH11
float temperature;
float humidity;
if(measurement_environment(&temperature, &humidity) == true)
{

// Print a terminal
Serial.print( "DH11 " );
Serial.print( temperature, 1 );
Serial.print("  C, " );
Serial.print( humidity, 1 );
Serial.print(" %; Therm ");
Serial.print(tempC);
Serial.print(" C, ");
Serial.print(tempF);
Serial.println(" F");

//Display in LCD

//Thermistor
lcd.setCursor(0,0);
lcd.print("Therm        C  ");
lcd.setCursor(7,0);
lcd.print(tempC);

//DH11

lcd.setCursor(0,2);
lcd.print("DH11     C     %");
lcd.setCursor(5, 2);
lcd.print(temperature,1);

//Humidty

lcd.setCursor(11,2);
lcd.print(humidity,1);

delay(500);
}

}

//End

Затем я хотел добавить SD-карту и RTC (для абсолютных временных меток вместо относительных через millis() , но ЖК-дисплей мерцал и никогда ничего не показывал. Затем я отключил RTC и закомментировал некоторый код. Теперь он все еще может быть немного раздутым, но он должен работать. Последовательный монитор сообщает, что файл создан, но при доступе к файлу журнала произошла ошибка:
< /ul>

Код: Выделить всё

Directory created
Error opening log file!
DH11 20.0  C, 64.0 %; Therm 20.77 C, 69.38 F    Logfile not existing/accessible

Код: Выделить всё

// Measurement with DHT11 and Thermistor
#include 
#define DHT_SENSOR_TYPE DHT_TYPE_11 //DH11
#include 
#include  // Include the SD library
//#include  //RTC module
#include  // dependancy for RTC

static const int DHT_SENSOR_PIN = 2;
DHT_nonblocking dht_Sensor(DHT_SENSOR_PIN, DHT_SENSOR_TYPE);

int tempPin = 0; //Thermistor

//RTC_DS1307 rtc; //create RTC object

// //LCD Display pins
// //                BS  E D4  D5  D6  D7
// LiquidCrystal lcd(7,8,9,10,11,12);

// NEW LCD PINS TO CHANGE:
// LCD Display pins
//                BS  E  D4  D5  D6  D7
LiquidCrystal lcd(3,4,5,6,7,8);

const int chipSelect = 9; // Set the chip select pin for the SD card
File logFile; // Create a file object

//DateTime now = rtc.now();

void setup()
{
Serial.begin(9600);
lcd.begin(16,2);

// //Initialize RTC
// if (! rtc.begin())
// {
//   Serial.println("Couldn't find RTC");
//   while (1);
// }

// rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

SD.begin(chipSelect);

if (!SD.begin(chipSelect)) { // Initialize the SD card
Serial.println("Initialization failed!");
return;
}

//String logFileName = String(now.unixtime() + "_temp_log.csv");

String logFileName = String("_temp_log.csv");
String logFileDir = String("/TemperatureLogs/");

//check if logfile exists, if not create
if (!SD.exists(logFileDir+ logFileName))
{
SD.mkdir(logFileDir+logFileName);
Serial.println("Directory created");
}
else
{
Serial.println("Stuck in setup");
}

logFile = SD.open(logFileDir + logFileName, FILE_WRITE); // Open the log file
if (logFile)
{
logFile.println("Timestamp [date], Temperature Thermistor [°C],Temperature DH11 [°C], Humidity DH11 [%]");
}
else
{
Serial.println("Error opening log file!");
return;
}

}

void logMeasurement(float tempC, float temperature, float humidity) {
if (logFile) {
//    String dataString = String(now.unixtime()) + "," + String(tempC) + "," + String(temperature) + "," + String(humidity) + "\n";
//    logFile.print(dataString);

String dataString = String(millis()) + "," + String(tempC) + "," + String(temperature) + "," + String(humidity) + "\n";
logFile.print(dataString);
}
else
Serial.println("Logfile not existing/accessible");
}

static bool measurement_environment(float *temperature, float *humidity)    //DH11
{
static unsigned long measurement_timestamp = millis();

/*Measure once every second */
if(millis()-measurement_timestamp > 10000ul)
{
if (dht_Sensor.measure(temperature, humidity) == true)
{
measurement_timestamp = millis();
return(true);
}
}
return(false);
}

void loop()
{
//Thermistor
int tempReading = analogRead(tempPin);
double tempK = log(10000.0 * ((1024.0 / tempReading -1)));
tempK = 1  / (0.001129148 + (0.000234125 + (0.0000000876741 * tempK * tempK )) * tempK ); //  Temp Kelvin
float tempC = tempK - 273.15;
float tempF = (tempC * 9.0)/ 5.0 + 32.0; // Convert Celcius to Fahrenheit

//DH11
float temperature;
float humidity;
if(measurement_environment(&temperature, &humidity) == true)
{

// Print a terminal
Serial.print( "DH11 " );
Serial.print( temperature, 1 );
Serial.print("  C, " );
Serial.print( humidity, 1 );
Serial.print(" %; Therm ");
Serial.print(tempC);
Serial.print(" C, ");
Serial.print(tempF);
Serial.print("  F\
");

//Display in LCD

//Thermistor
lcd.setCursor(0,0);
lcd.print("Therm        C  ");
lcd.setCursor(7,0);
lcd.print(tempC);

//DH11

lcd.setCursor(0,2);
lcd.print("DH11     C     %");
lcd.setCursor(5, 2);
lcd.print(temperature,1);

//Humidty

lcd.setCursor(11,2);
lcd.print(humidity,1);

// Log the measurement
logMeasurement(tempC, temperature, humidity);
delay(500);
}
}

// End

Что мне здесь не хватает?


Подробнее здесь: https://stackoverflow.com/questions/791 ... to-sd-card
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C++»