Ajuda - Código não salva dados no microSD

Sou novo no fórum e se estiver postando na área errada, me desculpem.

Estou realizando o TCC, onde o circuito basicamente varia a rotação de dois coolers conforme a temperatura do sensor, liga e desliga uma resistência por rele, mostra os valores no LCD e salva os dados no cartão SD.


A parte do código de variar a rotação do cooler, mostrar no LCD e controlar o rele está pronta e funcionando, porém não estou conseguindo salvar os valores de temperatura e humidade no cartão SD, que seria o último void ( void saveData() ).


#include <Robojax_L298N_DC_motor.h>
#include <LiquidCrystal_I2C.h>
#include <SD.h>
#include <SPI.h>
#include <Wire.h>
#include <Time.h>
#include “RTClib.h”

// Set the LCD address to 0x27 for a 20 chars and 4 line display
LiquidCrystal_I2C lcd(0x27,20,4);

// motor 1 settings
#define IN1 8
#define IN2 7
#define ENA 6 // this pin must be PWM enabled pin

// motor 2 settings
#define IN3 4
#define IN4 2
#define ENB 3 // this pin must be PWM enabled pin

const int CCW = 2; // do not change
const int CW = 1; // do not change

#define motor1 1 // do not change
#define motor2 2 // do not change

// use the line below for single motor
//Robojax_L298N_DC_motor motor(IN1, IN2, ENA, true);

// use the line below for two motors
Robojax_L298N_DC_motor motor(IN1, IN2, ENA, IN3, IN4, ENB, true);

// to control the FanSpeed
const float tempMin = 30.0; // tempMin in °C
const int speedMin =15; // speedMin in % from 0 to 100

const float tempMax = 65.0; // tempMin in °C
const int speedMax =50; // speedMin in % from 0 to 100

int motorSpeed; // variable holding motor speed

// to control heat transfer
int relayPin = 5; // relay pin
int relayOFF, relayON, NC, NO; // relay ON and OFF values for NC and NO Types conections
const int relayType = NC; // Set NC or NO according to you relay type
const float tempOFF = 40.0; // temperature in °C to control the relay, if tempOFF >50, the relay will be turn off

// to control data logger
const int chipSelect = 10;
RTC_DS1307 RTC;
File dataFile;
DateTime now;
uint32_t timer = 0;
int timeToSave = 120000;

#include “DHT.h”
#define DHTe_PIN A0 // define the pin of DHTe sensor
#define DHTji_PIN A1 // define the pin of DHTji sensor
#define DHTjf_PIN A2 // define the pin of DHTjf sensor
#define DHTs_PIN A3 // define the pin of DHTs sensor
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321

DHT dhte(DHTe_PIN, DHTTYPE); //for first DHT module and do the same for the oders
DHT dhtji(DHTji_PIN, DHTTYPE);
DHT dhtjf(DHTjf_PIN, DHTTYPE);
DHT dhts(DHTs_PIN, DHTTYPE);

void setup() {

pinMode(relayPin, OUTPUT);// set pin as output
if(relayType == NC){
relayON = HIGH;
relayOFF = LOW;
digitalWrite(relayPin, relayOFF); // set initial state OFF for high trigger relay
}
else{
relayON = LOW;
relayOFF = HIGH;
digitalWrite(relayPin, relayOFF); // set initial state OFF for low trigger relay
}

Serial.begin(115200);
motor.begin();
dhte.begin();
dhtji.begin();
dhtjf.begin();
dhts.begin();

lcd.begin(20,4); // define the numbers of chars x lines
lcd.init(); // start the LCD
lcd.backlight(); // start the blacklight
lcd.setCursor(2,1); // define the point on the begein position
lcd.print(“Ligando Sistema”);

delay(2000);
lcd.clear(); // clear display

// setup clock
Wire.begin();
if (! RTC.begin()){
Serial.print(“RTC nao encontrado!”);
while(1);
}

Serial.print(“RTC OK!”);
Serial.println(" ");

// following line sets the RTC to the date & time this sketch was compiled
RTC.adjust(DateTime(F(DATE), F(TIME)));
Serial.print(“Data e hora ajustadas”);
Serial.println(" ");
// this line sets the RTC with an explicit date & time, for example to set
// Formato: DateTime(ano, mes, dia, hora, minuto, segundo)
//rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));

if (! RTC.isrunning()){
Serial.println(“RTC nao operante!”);
}

// setup SD card
pinMode(chipSelect, OUTPUT);
if (!SD.begin(chipSelect)) {
Serial.println(“SD Card initialization failed!”);
return;
}
Serial.println(“SD Card OK.”);
Serial.println(" ");
}

void loop() {
delay(2000);

tempToSpeed();
saveData();

// writing date on serial
now = RTC.now();
Serial.print(now.hour(),DEC);
Serial.print(":");
Serial.print(now.minute(),DEC);
Serial.print(":");
Serial.print(now.second(),DEC);
Serial.println(" ");

Serial.print(“FanSpeed:”);
Serial.println(motorSpeed);

//motor.demo(1); // to test motor1
//motor.demo(2); // to test motor2

motor.rotate(motor1, motorSpeed, CW); //to start the motor1
motor.rotate(motor2, motorSpeed, CW); //to start the motor2

// show on display LCD the value of FanSpeed
lcd.setCursor(14,0);
lcd.print(“Fspeed”);
lcd.setCursor(16, 1);
lcd.print(motorSpeed);

//motor.brake(1); // use the line to brake the motor1 on test
//motor.brake(2); // use the line to brake the motor2 on test

delay(500);
}

void tempToSpeed() {
delay(2000);

float te = dhte.readTemperature(); // read the temperature in ° C of the sensor at the collector input
float tji = dhtji.readTemperature(); // read the temperature in ° C of the sensor at the collector junction
float tjf = dhtjf.readTemperature(); // read the temperature in ° C of the sensor at the collector junction
float ts = dhts.readTemperature(); // read the temperature in ° C of the sensor at the chamber output
float he = dhte.readHumidity(); // read humidity of the sensor at the collector input
float hji = dhtji.readHumidity(); // read humidity of the sensor at the collector junction
float hjf = dhtjf.readHumidity(); // read humidity of the sensor at the collector junction
float hs = dhts.readHumidity(); // read humidity of the sensor at the chamber output

// show on display LCD and serial the values of temperatures
Serial.print(“Te:”);
Serial.print(te,1);
Serial.println(" °C");
lcd.setCursor(0,0);
lcd.print(“Te =”);
lcd.print(te,0);
lcd.print(“C”);

Serial.print(“Tji:”);
Serial.print(tji,1);
Serial.println(" °C");
lcd.setCursor(0,1);
lcd.print(“Tji=”);
lcd.print(tji,0);
lcd.print(“C”);

Serial.print(“Tjf:”);
Serial.print(tjf,1);
Serial.println(" °C");
lcd.setCursor(0,2);
lcd.print(“Tjf=”);
lcd.print(tjf,0);
lcd.print(“C”);

Serial.print(“Ts:”);
Serial.print(ts,1);
Serial.println(" °C");
lcd.setCursor(0,3);
lcd.print(“Ts =”);
lcd.print(ts,0);
lcd.print(“C”);

Serial.print(“He:”);
Serial.print(he,1);
Serial.println(" %");
lcd.setCursor(8,0);
lcd.print(“H=”);
lcd.print(he,0);
lcd.print("%");

Serial.print(“Hji:”);
Serial.print(hji,1);
Serial.println(" %");
lcd.setCursor(8,1);
lcd.print(“H=”);
lcd.print(hji,0);
lcd.print("%");

Serial.print(“Hjf:”);
Serial.print(hjf,1);
Serial.println(" %");
lcd.setCursor(8,2);
lcd.print(“H=”);
lcd.print(hjf,0);
lcd.print("%");

Serial.print(“Hs:”);
Serial.print(hs,1);
Serial.println(" %");
lcd.setCursor(8,3);
lcd.print(“H=”);
lcd.print(hs,0);
lcd.print("%");

// to control fan speed
motorSpeed = map(tjf, tempMin, tempMax, speedMin,speedMax);
if(tjf <tempMin)
{
motorSpeed=0;
motor.brake(1);
motor.brake(2);
}

if(tjf >tempMax)
{
motorSpeed=100;
}

// to control relay
if(tji <tempOFF)
{
// turn relay ON
digitalWrite(relayPin, relayON);
Serial.println(“Resistência ON”);
lcd.setCursor(14,2);
lcd.print(“Resist”);
lcd.setCursor(16,3);
lcd.print(“ON”);
}

if(tji >tempOFF)
{
// turn relay OFF
digitalWrite(relayPin, relayOFF);
Serial.println(“Resistência OFF”);
lcd.setCursor(14,2);
lcd.print(“Resist”);
lcd.setCursor(16,3);
lcd.print(“OFF”);
}
}

void saveData(){
now = RTC.now();

// this one is used to save data from sensor at 5 in 5 minutes
if(now.minute() %5 == 0){

dataFile = SD.open(“teste.txt”,FILE_WRITE);

if (dataFile) {
dataFile.print(now.hour(),DEC);
dataFile.print(":");
dataFile.print(now.minute(),DEC);
dataFile.print(":");
dataFile.print(now.second(),DEC);
dataFile.print(te);
dataFile.print(",");
dataFile.print(tji);
dataFile.print(",");
dataFile.print(tjf);
dataFile.print(",");
dataFile.print(ts);
dataFile.print(",");
dataFile.print(he);
dataFile.print(",");
dataFile.print(hji);
dataFile.print(",");
dataFile.print(hjf);
dataFile.print(",");
dataFile.print(hs);
dataFile.print(motorSpeed);
dataFile.println();

dataFile.close();
// print to the serial port too:
Serial.println("Dado Salvo");

}
// if the file isn’t open, pop up an error:
else {
Serial.println(“Erro ao abrir datalog.txt”);
}
delay(5000);
}

delay(5000);
}

Falai @william blz cara, Te perguntar uma questão para podermos definir uma linha de raciocínio
1 - Vc não esta conseguindo escrever nada no cartão SD? ou
2 - Vc esta conseguindo escrever a Hora, minuto e segundo e os demais dados não são?

No aguardo
Abraços
Max

Caso seja a opção 2 acredito que o problema seja o escopo da variável que vc esta usando, ou seja, as variáveis te, tji, tjf, ts, he, hji, hjf, hs possuem validade somente dentro da função aonde elas foram criadas com exceção da motorSpeed que como foi definida fora do void setup e fora do void loop ela teria escopo global. Tecnicamente ela estaia sendo gravada no seu cartão SD.

Abraços
Max

Boa tarde @maxdesa, tudo bom?

Seria a segunda opção, eu consigo gravar os dados normalmente num outro código.

Fiz a alteração que sugeriu, mas parece que o arduino não entra no loop void saveData(). Tudo está funcionando ok agora, LCD, sensores, relé, mas ele não entra no loop que salva os dados.

Cara eu iria sugerir que vc comentasse o

if(now.minute() %5 == 0){

e a chave correspondente de fechamento do IF

e fazer um teste pois essa condição so habilita a gravação quando os minutos forem múltiplos de 5. Entao se seu teste demorar menos de 5 minutos ele não irá entrar nesse bloco e não irá gravar Comentando essa linha tecnicamente vai sempre entrar nesse bloco e poderá testar a funcionalidade de salvar os dados.

Abraços
Max

Como sou iniciante em arduino acredito que esteja errando em alguma lógica de programação, pois, mesmo assim ele não entra no loop. Vou repostar o código com as alterações que fiz.


#include <Robojax_L298N_DC_motor.h>
#include <LiquidCrystal_I2C.h>
#include <SD.h>
#include <SPI.h>
#include <Wire.h>
#include <Time.h>
#include “RTClib.h”

// Set the LCD address to 0x27 for a 20 chars and 4 line display
LiquidCrystal_I2C lcd(0x27,20,4);

// motor 1 settings
#define IN1 8
#define IN2 7
#define ENA 6 // this pin must be PWM enabled pin

// motor 2 settings
#define IN3 4
#define IN4 2
#define ENB 3 // this pin must be PWM enabled pin

const int CCW = 2; // do not change
const int CW = 1; // do not change

#define motor1 1 // do not change
#define motor2 2 // do not change

// use the line below for single motor
//Robojax_L298N_DC_motor motor(IN1, IN2, ENA, true);

// use the line below for two motors
Robojax_L298N_DC_motor motor(IN1, IN2, ENA, IN3, IN4, ENB, true);

// to control the FanSpeed
const float tempMin = 30.0; // tempMin in °C
const int speedMin =15; // speedMin in % from 0 to 100

const float tempMax = 65.0; // tempMin in °C
const int speedMax =50; // speedMin in % from 0 to 100

int motorSpeed; // variable holding motor speed

// to control heat transfer
int relayPin = 5; // relay pin
int relayOFF, relayON, NC, NO; // relay ON and OFF values for NC and NO Types conections
const int relayType = NC; // Set NC or NO according to you relay type
const float tempOFF = 40.0; // temperature in °C to control the relay, if tempOFF >50, the relay will be turn off

// to control data logger
const int chipSelect = 10;
RTC_DS1307 RTC;
File dataFile;
DateTime now;

#include “DHT.h”
#define DHTe_PIN A0 // define the pin of DHTe sensor
#define DHTji_PIN A1 // define the pin of DHTji sensor
#define DHTjf_PIN A2 // define the pin of DHTjf sensor
#define DHTs_PIN A3 // define the pin of DHTs sensor
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321

DHT dhte(DHTe_PIN, DHTTYPE); //for first DHT module and do the same for the oders
DHT dhtji(DHTji_PIN, DHTTYPE);
DHT dhtjf(DHTjf_PIN, DHTTYPE);
DHT dhts(DHTs_PIN, DHTTYPE);

float te;
float tji;
float tjf;
float ts;
float he;
float hji;
float hjf;
float hs;

void setup() {

pinMode(relayPin, OUTPUT);// set pin as output
if(relayType == NC){
relayON = HIGH;
relayOFF = LOW;
digitalWrite(relayPin, relayOFF); // set initial state OFF for high trigger relay
}
else{
relayON = LOW;
relayOFF = HIGH;
digitalWrite(relayPin, relayOFF); // set initial state OFF for low trigger relay
}

Serial.begin(115200);
motor.begin();
dhte.begin();
dhtji.begin();
dhtjf.begin();
dhts.begin();

lcd.begin(20,4); // define the numbers of chars x lines
lcd.init(); // start the LCD
lcd.backlight(); // start the blacklight
lcd.setCursor(2,1); // define the point on the begein position
lcd.print(“Ligando Sistema”);

delay(2000);
lcd.clear(); // clear display

// setup clock
Wire.begin();
if (! RTC.begin()){
Serial.print(“RTC nao encontrado!”);
while(1);
}

Serial.print(“RTC OK!”);
Serial.println(" ");

// following line sets the RTC to the date & time this sketch was compiled
RTC.adjust(DateTime(F(DATE), F(TIME)));
Serial.print(“Data e hora ajustadas”);
Serial.println(" ");
// this line sets the RTC with an explicit date & time, for example to set
// Formato: DateTime(ano, mes, dia, hora, minuto, segundo)
//rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));

if (! RTC.isrunning()){
Serial.println(“RTC nao operante!”);
}

// setup SD card
pinMode(chipSelect, OUTPUT);
if (!SD.begin(chipSelect)) {
Serial.println(“SD Card initialization failed!”);
return;
}
Serial.println(“SD Card OK.”);
Serial.println(" ");
}

void loop() {
delay(2000);

// writing date on serial
now = RTC.now();
Serial.print(now.hour(),DEC);
Serial.print(":");
Serial.print(now.minute(),DEC);
Serial.print(":");
Serial.print(now.second(),DEC);
Serial.println(" ");

Serial.print(“FanSpeed:”);
Serial.println(motorSpeed);

//motor.demo(1); // to test motor1
//motor.demo(2); // to test motor2

motor.rotate(motor1, motorSpeed, CW); //to start the motor1
motor.rotate(motor2, motorSpeed, CW); //to start the motor2

tempToSpeed();

// show on display LCD the value of FanSpeed
lcd.setCursor(14,0);
lcd.print(“Fspeed”);
lcd.setCursor(16, 1);
lcd.print(motorSpeed);

//motor.brake(1); // use the line to brake the motor1 on test
//motor.brake(2); // use the line to brake the motor2 on test
}

void tempToSpeed() {
delay(2000);

te = dhte.readTemperature(); // read the temperature in ° C of the sensor at the collector input
tji = dhtji.readTemperature(); // read the temperature in ° C of the sensor at the collector junction
tjf = dhtjf.readTemperature(); // read the temperature in ° C of the sensor at the collector junction
ts = dhts.readTemperature(); // read the temperature in ° C of the sensor at the chamber output
he = dhte.readHumidity(); // read humidity of the sensor at the collector input
hji = dhtji.readHumidity(); // read humidity of the sensor at the collector junction
hjf = dhtjf.readHumidity(); // read humidity of the sensor at the collector junction
hs = dhts.readHumidity(); // read humidity of the sensor at the chamber output

// show on display LCD and serial the values of temperatures
Serial.print(“Te:”);
Serial.print(te,1);
Serial.println(" °C");
lcd.setCursor(0,0);
lcd.print(“Te =”);
lcd.print(te,0);
lcd.print(“C”);

Serial.print(“Tji:”);
Serial.print(tji,1);
Serial.println(" °C");
lcd.setCursor(0,1);
lcd.print(“Tji=”);
lcd.print(tji,0);
lcd.print(“C”);

Serial.print(“Tjf:”);
Serial.print(tjf,1);
Serial.println(" °C");
lcd.setCursor(0,2);
lcd.print(“Tjf=”);
lcd.print(tjf,0);
lcd.print(“C”);

Serial.print(“Ts:”);
Serial.print(ts,1);
Serial.println(" °C");
lcd.setCursor(0,3);
lcd.print(“Ts =”);
lcd.print(ts,0);
lcd.print(“C”);

Serial.print(“He:”);
Serial.print(he,1);
Serial.println(" %");
lcd.setCursor(8,0);
lcd.print(“H=”);
lcd.print(he,0);
lcd.print("%");

Serial.print(“Hji:”);
Serial.print(hji,1);
Serial.println(" %");
lcd.setCursor(8,1);
lcd.print(“H=”);
lcd.print(hji,0);
lcd.print("%");

Serial.print(“Hjf:”);
Serial.print(hjf,1);
Serial.println(" %");
lcd.setCursor(8,2);
lcd.print(“H=”);
lcd.print(hjf,0);
lcd.print("%");

Serial.print(“Hs:”);
Serial.print(hs,1);
Serial.println(" %");
lcd.setCursor(8,3);
lcd.print(“H=”);
lcd.print(hs,0);
lcd.print("%");

// to control fan speed
motorSpeed = map(tjf, tempMin, tempMax, speedMin,speedMax);
if(tjf <tempMin)
{
motorSpeed=0;
motor.brake(1);
motor.brake(2);
}

if(tjf >tempMax)
{
motorSpeed=100;
}

// to control relay
if(tji <tempOFF)
{
// turn relay ON
digitalWrite(relayPin, relayON);
Serial.println(“Resistência ON”);
lcd.setCursor(14,2);
lcd.print(“Resist”);
lcd.setCursor(16,3);
lcd.print(“ON”);
}

if(tji >tempOFF)
{
// turn relay OFF
digitalWrite(relayPin, relayOFF);
Serial.println(“Resistência OFF”);
lcd.setCursor(14,2);
lcd.print(“Resist”);
lcd.setCursor(16,3);
lcd.print(“OFF”);
}
}

void saveData(){
now = RTC.now();

// this one is used to save data from sensor at 5 in 5 minutes
dataFile = SD.open(“teste.txt”,FILE_WRITE);

if (dataFile) {
dataFile.print(now.hour(),DEC);
dataFile.print(":");
dataFile.print(now.minute(),DEC);
dataFile.print(":");
dataFile.print(now.second(),DEC);
dataFile.print(te);
dataFile.print(",");
dataFile.print(tji);
dataFile.print(",");
dataFile.print(tjf);
dataFile.print(",");
dataFile.print(ts);
dataFile.print(",");
dataFile.print(he);
dataFile.print(",");
dataFile.print(hji);
dataFile.print(",");
dataFile.print(hjf);
dataFile.print(",");
dataFile.print(hs);
dataFile.print(motorSpeed);
dataFile.println();

dataFile.close();
// print to the serial port too:
Serial.println("Dado Salvo");

}
// if the file isn’t open, pop up an error:
else {
Serial.println(“Erro ao abrir teste.txt”);
}
delay(5000);
}