Hi,
I have a problem getting the SDcard, Ethernet and a real time clock DS1307 running concurrently on an Arduino Mega 2560 R3.
I know there are several posts regarding the SPI interface and using different CS for each device, but having read them, they haven't helped me solve my problem. Sometimes my code will return success with SD.begin(), most times it won't. I suspect my lack of understanding of SPI has made me write bad code - I would be very grateful if anyone can see the problem. Code below-
#include <SPI.h>
#include <SD.h>
#include <Ethernet.h>
#include <Wire.h>
#include <RTC_DS3234.h>
/* SD card attached to SPI bus as follows: (commented out definitions are defined in pins_arduino.h)*/
/* const int MOSI = 51;
const int MISO = 50;
const int SCLK = 52;
const int SS = 53;*/
const int CS_RTC = 7; //chip select pin for RTC
const int CS_SD = 4; //chip select for SD card
byte mac[] = {0x90, 0xA2, 0xDA, 0x0D, 0xAB, 0x8F}; // UNIT 2
File dataFile;
RTC_DS3234 RTC(CS_RTC);// Create an RTC instance, using the chip select pin it's connected to
void setup()
{
Serial.begin(9600);
SPI_Initialise();
SdCard_Initialise();
InitialiseEthernet();
Initialise_RTC();
}
void loop()
{
delay(3000);
PrintTime();
PrintTimeToFile();
}
void SPI_Initialise()
{
pinMode(SS, OUTPUT); //sets Mega in SPI master mode.
SPI.begin();
Serial.println("SPI Initialised.");
}
void SdCard_Initialise(){
if (!SD.begin(CS_SD)) {
Serial.println("SD Card failed");
return;
}
Serial.println("SD Card initialized");
}
void InitialiseEthernet()
{
if (Ethernet.begin(mac))
{
Serial.println("Ethernet Initialised.");
delay(2000);
Serial.print("My IP address is ");
Serial.println(Ethernet.localIP());
}
else
{
Serial.println("Ethernet failed to Initialise.");
}
}
void Initialise_RTC()
{
if ( RTC.begin())
{
Serial.println("RTC Initialised.");
}
else
{
Serial.println("RTC failed to Initialise.");
}
}
void PrintTimeToFile()
{
const int len = 32;
static char buf[len];
dataFile = SD.open("Time.txt", FILE_WRITE);
if (dataFile)
{
DateTime now = RTC.now();
dataFile.println(now.toString(buf,len));
dataFile.close();
}
else
{
Serial.println("SD failed to open!");
}
}
void PrintTime()
{
const int len = 32;
static char buf[len];
DateTime now = RTC.now();
Serial.println(now.toString(buf,len));
}
The output from the serial port is below:-
SPI Initialised.
SD Card failed
Ethernet Initialised.
My IP address is 172.16.205.195
RTC Initialised.
Sep 09 2013 17:26:11
SD failed to open!
Sep 09 2013 17:26:14
SD failed to open!
Sep 09 2013 17:26:17
SD failed to open!
Any help much appreciated,
Fin