DS1302 Setup

How to set up current time and date (DS1302) in this code ?

#include <SD.h> // библиотека для SD Card.

#include <DS1302.h> // это скачанная библиотека для DS1302 Real Time Clock Module.

#include “DHT.h” // это скачанная библиотека для temperature sensors DHT11.

// ------------------------

// PINS для DS1302 Real Time Clock Module.

// ** RST - pin 2

// ** DAT - pin 3

// ** CLK - pin 4

// ! +5v не подключаем достаточно только “-” / землю.

DS1302 rtc(2, 3, 4);

// ------------------------

#define DHTPIN 7 // PIN №7 для датчика температуры и влажности DHT 11.

#define DHTTYPE AM2301 // DHT 11.

DHT dht(DHTPIN, DHTTYPE);

// ------------------------

File myFile; // SD card.

int SaveTemperature; // Для фиксации температуры.

// ------------------------

void setup()

{

Serial.begin(9600);

dht.begin(); // Включаем библиотеку “DHT”.

SaveTemperature = dht.readTemperature(); // Фиксируем текущую температуру.

// ----------------

// Тестируем SD card на работоспособность.

Serial.print(“Initializing SD card…”);

if (!SD.begin(10)) // Здесь можно изменить № pin ** CS - pin 10.

{

Serial.println(“initialization failed!”);

return;

}

Serial.println(“initialization done.”);

// ----------------

SDcardWrite(); // Запускаем функцию записи на SD card.

}

// ***************************************

void SDcardWrite() // Делаем функцию, для записи на SD card.

{

// open the file. note that only one file can be open at a time,

// so you have to close this one before opening another.

// Создаём новый, или открываем существующий файл на SD card,

// например с именем dimasens.txt

// максимум “8” символов может иметь имя файла 12345678.123

myFile = SD.open(“dimasens.txt”, FILE_WRITE);

// if the file opened okay, write to it:

if (myFile) {

Serial.print(“Writing to dimasens.txt…”);

// начинаем записывать на SD card, строку в файл dimasens.txt

myFile.print(rtc.getDateStr(FORMAT_SHORT, FORMAT_MIDDLEENDIAN, ‘/’)); // Текущую дату.

myFile.print(" – ");

myFile.print(rtc.getTimeStr()); // текущие время.

myFile.print(" – ");

myFile.print("Humidity: ");

myFile.print(dht.readHumidity()); // Значения влажности.

myFile.print(" %\t");

myFile.print("Temperature: ");

myFile.print(dht.readTemperature()); // Значения температуры.

myFile.println(" *C");

myFile.close(); // close the file:

Serial.println(“done.”);

}

else {

// if the file didn’t open, print an error:

Serial.println(“error opening dimasens.txt”);

}

}

// -------------------

// Делаем функцию для чтения с SD card и вывода в Serial монитор.

void SDcardRead()

{

// re-open the file for reading:

myFile = SD.open(“dimasens.txt”);

if (myFile) {

Serial.println(“dimasens.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 dimasens.txt”);

}

}

// ************************************

void loop()

{

// Для того чтоб бессмысленно не записывать на SD card данные с датчиков,

// сделаем проверку.

// Только если прошлое значение температуры не равно текущему значению,

// то есть произошло изменение температуры.

if (SaveTemperature != dht.readTemperature())

// Можно и по-другому, увеличивая порог, обнаружения изменения температуры.

// if (SaveTemperature >= (dht.readTemperature()+2) || SaveTemperature <= (dht.readTemperature()-2))

{

// Serial.println(rtc.getDateStr());

// Serial.println(dht.readHumidity());

// Serial.println(dht.readTemperature());

SDcardWrite(); // Запускаем функцию записи на SD card.

// Снова фиксируем текущее значение температуры.

SaveTemperature = dht.readTemperature();

}

// Для вывода в Serial монитор данных с SD card.

if (Serial.available() > 0) {

// Если отправляем через Serial монитор цифру 1

// запускаем функцию SDcardRead.

// То есть выводим в Serial монитор всё содержимое файла dimasens.txt

if (Serial.read()-48 == 1)SDcardRead();

}

}

here is the tutorial How to simply use DS1302 RTC module with Arduino board and LCD screen – SURTR TECHNOLOGY

Hi,

Thanks.

How many devices (ESP8266) can i add in Cayenne dashboard ?

currently there is no limit for the number of device that can be register to cayenne. just keep in mind about this Sending MQTT messages within rate limits

I think its not problem if i add 8 devices.

Do you have the code for ESP8266+ Cayenne+DS1302+AM2301+SD Card (6 pins) ?

no, i dont have one.

This code is working with Arduino+DS1302+AM2301+SD Card.

Can you help me to convert this code for ESP8266 and Cayenne ?

Arduino UNO PINS.

  • SD card attached to SPI bus as follows:

PINS SD Card Module.

** MOSI - pin 11

** MISO - pin 12

** CLK/SCK - pin 13

** CS - pin 10

*/

#include <SD.h> // SD Card.

#include <DS1302.h> // DS1302 Real Time Clock Module.

#include “DHT.h” // temperature sensors DHT11.

// ------------------------

// PINS для DS1302 Real Time Clock Module.

// ** RST - pin 2

// ** DAT - pin 3

// ** CLK - pin 4

// ! +5v

DS1302 rtc(2, 3, 4);

// ------------------------

#define DHTPIN 7 // PIN №7 DHT 11.

#define DHTTYPE AM2301 // DHT 11.

DHT dht(DHTPIN, DHTTYPE);

// ------------------------

File myFile; // SD card.

int SaveTemperature; //

// ------------------------

void setup()

{

Serial.begin(9600);

dht.begin(); // “DHT”.

SaveTemperature = dht.readTemperature(); // Фиксируем текущую температуру.

// ----------------

// Тестируем SD card на работоспособность.

Serial.print(“Initializing SD card…”);

if (!SD.begin(10)) // Здесь можно изменить № pin ** CS - pin 10.

{

Serial.println(“initialization failed!”);

return;

}

Serial.println(“initialization done.”);

// ----------------

SDcardWrite(); // Запускаем функцию записи на SD card.

}

// ***************************************

void SDcardWrite() // Делаем функцию, для записи на SD card.

{

// open the file. note that only one file can be open at a time,

// so you have to close this one before opening another.

// Создаём новый, или открываем существующий файл на SD card,

// например с именем dimasens.txt

// максимум “8” символов может иметь имя файла 12345678.123

myFile = SD.open(“dimasens.txt”, FILE_WRITE);

// if the file opened okay, write to it:

if (myFile) {

Serial.print(“Writing to dimasens.txt…”);

// начинаем записывать на SD card, строку в файл dimasens.txt

myFile.print(rtc.getDateStr(FORMAT_SHORT, FORMAT_MIDDLEENDIAN, ‘/’)); // Текущую дату.

myFile.print(" – ");

myFile.print(rtc.getTimeStr()); // текущие время.

myFile.print(" – ");

myFile.print("Humidity: ");

myFile.print(dht.readHumidity()); // Значения влажности.

myFile.print(" %\t");

myFile.print("Temperature: ");

myFile.print(dht.readTemperature()); // Значения температуры.

myFile.println(" *C");

myFile.close(); // close the file:

Serial.println(“done.”);

}

else {

// if the file didn’t open, print an error:

Serial.println(“error opening dimasens.txt”);

}

}

// -------------------

// Делаем функцию для чтения с SD card и вывода в Serial монитор.

void SDcardRead()

{

// re-open the file for reading:

myFile = SD.open(“dimasens.txt”);

if (myFile) {

Serial.println(“dimasens.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 dimasens.txt”);

}

}

// ************************************

void loop()

{

// Для того чтоб бессмысленно не записывать на SD card данные с датчиков,

// сделаем проверку.

// Только если прошлое значение температуры не равно текущему значению,

// то есть произошло изменение температуры.

if (SaveTemperature != dht.readTemperature())

// Можно и по-другому, увеличивая порог, обнаружения изменения температуры.

// if (SaveTemperature >= (dht.readTemperature()+2) || SaveTemperature <= (dht.readTemperature()-2))

{

// Serial.println(rtc.getDateStr());

// Serial.println(dht.readHumidity());

// Serial.println(dht.readTemperature());

SDcardWrite(); // Запускаем функцию записи на SD card.

// Снова фиксируем текущее значение температуры.

SaveTemperature = dht.readTemperature();

}

// Для вывода в Serial монитор данных с SD card.

if (Serial.available() > 0) {

// Если отправляем через Serial монитор цифру 1

// запускаем функцию SDcardRead.

// То есть выводим в Serial монитор всё содержимое файла dimasens.txt

if (Serial.read()-48 == 1)SDcardRead();

}

}

Shramik,

Will you help me ??

look at the pinout of nodemcu, and make the required changed in the code to get it working with nodemcu. Once done we can move to cayenne code.

Sir,

I am using thsese pins on ESP8266:

SD Card
cs-d8
sck-d5
mosi-d7
miso-d6

RTC
clk-d1
dat-d2
rst-d3

I have changed pins on the code, but its not working.

Can you help me with wiring and the code please?

I want to save data on SD Card and to show on Cayenne dashboard.

This is the code:

#include <SD.h>

#include <DS1302.h>

#include “DHT.h”

// ------------------------

// DS1302 Real Time Clock Module.

// ** RST - pin 0

// ** DAT - pin 4

// ** CLK - pin 5

// ! +5v

DS1302 rtc(0, 4, 5);

// ------------------------

#define DHTPIN 7 // .

#define DHTTYPE AM2301 // DHT 11.

DHT dht(DHTPIN, DHTTYPE);

// ------------------------

File myFile; // SD card.

int SaveTemperature;
// ------------------------

void setup()

{

Serial.begin(9600);

dht.begin();

SaveTemperature = dht.readTemperature();

// ----------------

Serial.print(“Initializing SD card…”);

if (!SD.begin(10)) //

{

Serial.println(“initialization failed!”);

return;

}

Serial.println(“initialization done.”);

// ----------------

SDcardWrite();
}

// ***************************************

void SDcardWrite()

{

// 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(“dimasens.txt”, FILE_WRITE);

// if the file opened okay, write to it:

if (myFile) {

Serial.print(“Writing to dimasens.txt…”);

myFile.print(rtc.getDateStr(FORMAT_SHORT, FORMAT_MIDDLEENDIAN, ‘/’));

myFile.print(" – ");

myFile.print(rtc.getTimeStr());

myFile.print(" – ");

myFile.print("Humidity: ");

myFile.print(dht.readHumidity());

myFile.print(" %\t");

myFile.print("Temperature: ");

myFile.print(dht.readTemperature());

myFile.println(" *C");

myFile.close(); // close the file:

Serial.println(“done.”);

}

else {

// if the file didn’t open, print an error:

Serial.println(“error opening dimasens.txt”);

}

}

// -------------------

void SDcardRead()

{

// re-open the file for reading:

myFile = SD.open(“dimasens.txt”);

if (myFile) {

Serial.println(“dimasens.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 dimasens.txt”);

}

}

// ************************************

void loop()

{

if (SaveTemperature != dht.readTemperature())

// if (SaveTemperature >= (dht.readTemperature()+2) || SaveTemperature <= (dht.readTemperature()-2))

{

// Serial.println(rtc.getDateStr());

// Serial.println(dht.readHumidity());

// Serial.println(dht.readTemperature());

SDcardWrite();

SaveTemperature = dht.readTemperature();

}

// Для вывода в Serial монитор данных с SD card.

if (Serial.available() > 0) {

if (Serial.read()-48 == 1)SDcardRead();

}

}

i already gave you a code for sd card in this topic Cayenne + am2301 (temp. sensor) + sd card - #44 by shramik_salgaonkar

Yes sir, but its not working.

I sent you my code. Its working with Arduino.

Can you help me to adapt this code for ESP8266 and Cayenne?

Its urgent, please.

do you understand the code or just copy-pasting? the code i gave is for esp and not arduino. Also it is esp + cayenne.

Sir,

I understand the code, but your code for ESP is not working.

can you atleast find out what is not working.

In serial monitor is shown this message:

15:51:47.741 → Initializing SD card…initialization failed. Things to check:
15:51:47.956 → 1. is a card inserted?
15:51:47.956 → 2. is your wiring correct?
15:51:47.956 → 3. did you change the chipSelect pin to match your shield or module?
15:51:47.956 → Note: press reset or reopen this serial monitor after fixing your issue!

Sensor data is not shown in dashboard and in serial monitor.

Maybe my wiring is incorrect.

lets do one thing at a time.
Connect only your SD card to your nodemcu and nothing else. The connection is as follows:-

SD CARD -----> NODEMCU
CLK ------> D5
MISO ------> D6
MOSI ------> D7
CS ------> D8

Is your SD card 5v or 3.3v. if it 5v you need to connect it to Vin pin of nodemcu. Upload the below code and see if the SD card is detected or not.

#include <SD.h>
#define CS_PIN  D8
File myFile;

void setup() {
  Serial.begin(9600);
  Serial.print("Initializing SD card...");

  if (!SD.begin(CS_PIN)) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("1. is a card inserted?");
    Serial.println("2. is your wiring correct?");
    Serial.println("3. did you change the chipSelect pin to match your shield or module?");
    Serial.println("Note: press reset or reopen this serial monitor after fixing your issue!");
    while (1);
  }

  Serial.println("initialization done.");

  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("temperature");
    myFile.print(" | ");
    myFile.println("humidity");

    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
}

Hi,

I have used this code and there is not any error.

This message is shown:

Leaving…
Hard resetting via RTS pin…
Invalid library found in C:\Program Files (x86)\Arduino\libraries\DS1302: no headers files (.h) found in C:\Program Files (x86)\Arduino\libraries\DS1302

But its not a problem.

In SD Card is created a test.txt.

that is the warning, you can look here no headers files (.h) found - IDE 1.x - Arduino Forum

Good that you have it working now. Now can you add the rtc to it and see if that works.

I have added the rtc module and i have included rtc module (ds1302) library in the code.

#include <SD.h>
#include <DS1302.h>

DS1302 rtc(2, 3, 4);

#define CS_PIN D8
File myFile;

void setup() {
Serial.begin(115200);
Serial.print(“Initializing SD card…”);

if (!SD.begin(CS_PIN)) {
Serial.println(“initialization failed. Things to check:”);
Serial.println(“1. is a card inserted?”);
Serial.println(“2. is your wiring correct?”);
Serial.println(“3. did you change the chipSelect pin to match your shield or module?”);
Serial.println(“Note: press reset or reopen this serial monitor after fixing your issue!”);
while (1);
}

Serial.println(“initialization done.”);

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(“temperature”);
myFile.print(" | ");
myFile.println(“humidity”);

myFile.print(rtc.getDateStr(FORMAT_SHORT, FORMAT_MIDDLEENDIAN, ‘/’)); // Текущую дату.

myFile.print(" – ");

myFile.print(rtc.getTimeStr()); // текущие время.

myFile.print(" – ");

// close the file:
myFile.close();
Serial.println("done.");

} else {
// if the file didn’t open, print an error:
Serial.println(“error opening test.txt”);
}
}

void loop() {
}

In serial monitor is shown nothing.
In SD CARD is created the file and is shown this:
temperature | humidity
85/85/@5 – 27:85:85 –

PINS
RTC - ESP8266
CLK ----> D1
DAT ----> D2
RST ----> D3

SD CARD - ESP8266
SCK ------> D5
MISO -----> D6
MOSI -----> D7
CS --------> D8