PDA

View Full Version : Teensy 3.0 SD Card + SPI Encoder



lucasdelevy
11-20-2013, 08:43 PM
Hi all!

This is my fist post, so I apologize if this is a repeated thread (I did check if the question had been asked before!)

I'm trying to use an SPI Encoder along with the SD adapter from PJRC. I'm using SD.h for SD communication and SPI.h for the encoder.

Turns out both of them work perfectly individually. However, when I try connecting both at the same time, there's no response from the SD, i.e. SD.begin(10) returns false. I'm using different pins for CS (9 for the encoder and 10 for the SD) and I set them as LOW/HIGH according to the one I'm using.

Has anyone ever tried to do something similar? SPI should work pretty straight-forward (which is what annoys me the most), but I don't know what I'm doing wrong.

- SD connections: MISO-12, MOSI-11, CS-10
- Encoder connections: MISO-12, MOSI-11, CS-09

As for the testing code, the setup is on these lines:


pinMode(CSB_SD,OUTPUT);
pinMode(CSB_ENC,OUTPUT);

// SD is ON, Encoder is OFF
digitalWrite(CSB_SD,HIGH);
digitalWrite(CSB_ENC,LOW);

// Check if the card is present and can be initialized
if (!SD.begin(CSB_SD))
{
Serial.println("Card failed or not present...");
}
else
Serial.println("Card initialized!");

SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);
SPI.setClockDivider(SPI_CLOCK_DIV32);
digitalWrite(CSB_SD,LOW);
digitalWrite(CSB_ENC,HIGH);
SPI.begin();

Serial.begin(9600);
delay(500);

And the loop is:



// SD is OFF, Encoder is ON
digitalWrite(CSB_SD,LOW);
digitalWrite(CSB_ENC,HIGH);

SPI.begin();

/*** Encoder communication starts ***/
// Encoder acquisition
for (int i=0; i <= 2; i++)
{
digitalWrite(CSB_ENC,LOW);
response[i] = SPI.transfer(0x10);
digitalWrite(CSB_ENC,HIGH);
delay(50);
}

/**Encoder data treatment here **/
float angle;

SPI.end();
/*** Encoder communication ends ***/

/*** SD communication starts ***/
// SD is ON, Encoder is OFF
digitalWrite(CSB_SD,HIGH);
digitalWrite(CSB_ENC,LOW);

File dataFile = SD.open("datalog.txt", FILE_WRITE);

if(dataFile)
{
dataFile.println(angle);
dataFile.close();

// Print to the serial port too
Serial.println(angle);
}
else // ERROR
Serial.println("Error opening datalog.txt...");

// SD is OFF, Encoder is ON
digitalWrite(CSB_SD,LOW);
digitalWrite(CSB_ENC,HIGH);

/*** SD communication ends ***/

Thank you!