Teensy 4.0 Audio Shield - SD Card not initialising

UjjalD

Member
Hello,
I am working to make an audio guest book and struggling to get the SD card initialized. Please refer to the following pictures with hardware connections and errors I have been encountering. Any help to fix this would be highly appreciated.

IMG_1765.jpg
IMG_1766.jpg
SD ERRORS.JPG
 
The Rev C Audio Shield in your photos is not compatible with Teensy 4.x

See here

In particular, with regard to just the SD drive and flash memory if you've soldered it on, the 3.x Teensys needed to use the alternate SPI ports because the I2S ports for the audio stuff overlapped with some of the SPI pins. Unfortunately the Teensy 4.x systems don't support the alternate SPI pins that the Teensy 3.x systems did.
 
IMG_1809.jpg
IMG_1807.jpg
Hello, I have changed the board and cards but now getting only "Initializing SD card.." message with no further progress..
using codes form "C:\Program Files (x86)\Arduino\hardware\teensy\avr\libraries\SD\examples\listfiles" etc. but similar results

#include <SD.h>

// change this to match your SD shield or module;
// Teensy 2.0: pin 0
// Teensy++ 2.0: pin 20
// Wiz820+SD board: pin 4
// Teensy audio board: pin 10
// Teensy 3.5 & 3.6 & 4.1 on-board: BUILTIN_SDCARD
const int chipSelect = 10;

void setup()
{
//Uncomment these lines for Teensy 3.x Audio Shield (Rev C)
SPI.setMOSI(11); // Audio shield has MOSI on pin 7
SPI.setSCK(13); // Audio shield has SCK on pin 14

// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect.
}

Serial.print("Initializing SD card...");

if (!SD.begin(chipSelect)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");

File root = SD.open("/");

printDirectory(root, 0);

Serial.println("done!");
}

void loop()
{
// nothing happens after setup finishes.
}

void printDirectory(File dir, int numSpaces) {
while(true) {
File entry = dir.openNextFile();
if (! entry) {
//Serial.println("** no more files **");
break;
}
printSpaces(numSpaces);
Serial.print(entry.name());
if (entry.isDirectory()) {
Serial.println("/");
printDirectory(entry, numSpaces+2);
} else {
// files have sizes, directories do not
unsigned int n = log10(entry.size());
if (n > 10) n = 10;
printSpaces(50 - numSpaces - strlen(entry.name()) - n);
Serial.print(" ");
Serial.print(entry.size(), DEC);
DateTimeFields datetime;
if (entry.getModifyTime(datetime)) {
printSpaces(4);
printTime(datetime);
}
Serial.println();
}
entry.close();
}
}

void printSpaces(int num) {
for (int i=0; i < num; i++) {
Serial.print(" ");
}
}

void printTime(const DateTimeFields tm) {
const char *months[12] = {
"January","February","March","April","May","June",
"July","August","September","October","November","December"
};
if (tm.hour < 10) Serial.print('0');
Serial.print(tm.hour);
Serial.print(':');
if (tm.min < 10) Serial.print('0');
Serial.print(tm.min);
Serial.print(" ");
Serial.print(tm.mon < 12 ? months[tm.mon] : "???");
Serial.print(" ");
Serial.print(tm.mday);
Serial.print(", ");
Serial.print(tm.year + 1900);
}
 
Code:
#include <SD.h>

// change this to match your SD shield or module;
// Teensy 2.0: pin 0
// Teensy++ 2.0: pin 20
// Wiz820+SD board: pin 4
// Teensy audio board: pin 10
// Teensy 3.5 & 3.6 & 4.1 on-board: BUILTIN_SDCARD
const int chipSelect = 10;

void setup()
{
	//Uncomment these lines for Teensy 3.x Audio Shield (Rev C)
	SPI.setMOSI(11); // Audio shield has MOSI on pin 7
	SPI.setSCK(13); // Audio shield has SCK on pin 14

	// Open serial communications and wait for port to open:
	Serial.begin(9600);
	while (!Serial) {
		; // wait for serial port to connect.
	}

	Serial.print("Initializing SD card...");

	if (!SD.begin(chipSelect)) {
		Serial.println("initialization failed!");
		return;
	}
	Serial.println("initialization done.");

	File root = SD.open("/");

	printDirectory(root, 0);

	Serial.println("done!");
}

void loop()
{
	// nothing happens after setup finishes.
}

void printDirectory(File dir, int numSpaces) {
	while (true) {
		File entry = dir.openNextFile();
		if (!entry) {
			//Serial.println("** no more files **");
			break;
		}
		printSpaces(numSpaces);
		Serial.print(entry.name());
		if (entry.isDirectory()) {
			Serial.println("/");
			printDirectory(entry, numSpaces + 2);
		}
		else {
			// files have sizes, directories do not
			unsigned int n = log10(entry.size());
			if (n > 10) n = 10;
			printSpaces(50 - numSpaces - strlen(entry.name()) - n);
			Serial.print(" ");
			Serial.print(entry.size(), DEC);
			DateTimeFields datetime;
			if (entry.getModifyTime(datetime)) {
				printSpaces(4);
				printTime(datetime);
			}
			Serial.println();
		}
		entry.close();
	}
}

void printSpaces(int num) {
	for (int i = 0; i < num; i++) {
		Serial.print(" ");
	}
}

void printTime(const DateTimeFields tm) {
	const char* months[12] = {
	"January","February","March","April","May","Ju ne",
	"July","August","September","October","November"," December"
	};
	if (tm.hour < 10) Serial.print('0');
	Serial.print(tm.hour);
	Serial.print(':');
	if (tm.min < 10) Serial.print('0');
	Serial.print(tm.min);
	Serial.print(" ");
	Serial.print(tm.mon < 12 ? months[tm.mon] : "???");
	Serial.print(" ");
	Serial.print(tm.mday);
	Serial.print(", ");
	Serial.print(tm.year + 1900);
}
In future could you enclose your posted code between code tags using the # button, I think you will agree that it makes your code much easier to understand. This will make it more likely that someone will be able to help you.
Unfortunately I have no experience using the Audio card so I do not fall into that group.
 
I can't be 100% sure but don't think your pins are not aligned correctly between the T4 and the audio shield. See audio shield pinout vs your picture:
Picture2.jpg

Particularly note pins on the audio shield versus what's on the T4. YOu have the 5v/G/3.3v pins going to GND/0/1 pins on the audio shield. See this page for some mounting ideas:https://www.pjrc.com/store/teensy3_audio.html
 
I can't be 100% sure but don't think your pins are not aligned correctly between the T4 and the audio shield. See audio shield pinout vs your picture:
View attachment 28960

Particularly note pins on the audio shield versus what's on the T4. YOu have the 5v/G/3.3v pins going to GND/0/1 pins on the audio shield. See this page for some mounting ideas:https://www.pjrc.com/store/teensy3_audio.html

I think you are right. My quick look was that the Headphone jack was on the same side as USB connection. But did not notice that the board was logically upside down so The left hand side pins are on the right hand side...
 
Thanks for the help;)... I made those changes as suggested ... now it works, I can play the greeting.wav and record *.raw files and play back. However, while compiling I am receiving the following. Can anyone please suggest if the following indicating as errors? If so, how can I resolve?

C:\Users\dasau\OneDrive\80 AURICA\NICOLA\audio-guestbook\audio-guestbook.ino: In function 'void loop()':
C:\Users\dasau\OneDrive\80 AURICA\NICOLA\audio-guestbook\audio-guestbook.ino:131:9: warning: enumeration value 'Initialising' not handled in switch [-Wswitch]
switch(mode){
^
C:\Users\dasau\OneDrive\80 AURICA\NICOLA\audio-guestbook\audio-guestbook.ino: In function 'void playAllRecordings()':
C:\Users\dasau\OneDrive\80 AURICA\NICOLA\audio-guestbook\audio-guestbook.ino:265:36: warning: invalid conversion from 'const char*' to 'char*' [-fpermissive]
if (strstr(strlwr(entry.name() + (len - 4)), ".raw")) {
^
In file included from c:\program files (x86)\arduino\hardware\tools\arm\arm-none-eabi\include\stdlib.h:11:0,
from C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy4/WProgram.h:34,
from C:\Users\dasau\AppData\Local\Temp\arduino_build_780846\pch\Arduino.h:6:
c:\program files (x86)\arduino\hardware\tools\arm\arm-none-eabi\include\string.h:150:7: note: initializing argument 1 of 'char* strlwr(char*)'
char *_EXFUN(strlwr,(char *));
^
Opening Teensy Loader...
Memory Usage on Teensy 4.0:
FLASH: code:77604, data:10376, headers:8272 free for files:1935364
RAM1: variables:14688, code:75240, padding:23064 free for local variables:411296
RAM2: variables:29024 free for malloc/new:495264



Code:
/**
 * Audio Guestbook, Copyright (c) 2022 Playful Technology
 * 
 * Tested using a Teensy 4.0 with Teensy Audio Shield, although should work 
 * with minor modifications on other similar hardware
 * 
 * When handset is lifted, a pre-recorded greeting message is played, followed by a tone.
 * Then, recording starts, and continues until the handset is replaced.
 * Playback button allows all messages currently saved on SD card through earpiece 
 * 
 * Files are saved on SD card as 44.1kHz, 16-bit, mono signed integer RAW audio format
 * These can be loaded directly into Audacity (https://www.audacityteam.org/). Or else, converted to WAV/MP3 format using SOX (https://sourceforge.net/projects/sox/)
 * 
 **/

// INCLUDES
// The default "sketchbook" location in which Arduino IDE installs libraries is:
// C:\Users\alast\Documents\Arduino
// However, the TeensyDuino installer installs libraries in:
// C:\Program Files (x86)\Arduino\hardware\teensy\avr\libraries
// To ensure the correct libraries are used when targetting Teensy platform in Arduino IDE, go File->Preferences and change the sketchbook location to avoid conflicts with Arduino libraries.
// When targetting Arduino boards, change it back again to default
#include <Bounce.h>
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <TimeLib.h>

// DEFINES
// Define pins used by Teensy Audio Shield
#define SDCARD_CS_PIN    10
#define SDCARD_MOSI_PIN  7
#define SDCARD_SCK_PIN   14
// And those used for inputs
#define HOOK_PIN 0
#define PLAYBACK_BUTTON_PIN 1

// GLOBALS
// Audio initialisation code can be generated using the GUI interface at https://www.pjrc.com/teensy/gui/
// Inputs
AudioSynthWaveform      waveform1; // To create the "beep" sfx
AudioInputI2S           i2s2; // I2S input from microphone on audio shield
AudioPlaySdRaw          playRaw1; // Play .RAW audio files saved on SD card
AudioPlaySdWav          playWav1; // Play 44.1kHz 16-bit PCM greeting WAV file
// Outputs
AudioRecordQueue         queue1; // Creating an audio buffer in memory before saving to SD
AudioMixer4              mixer; // Allows merging several inputs to same output
AudioOutputI2S           i2s1; // I2S interface to Speaker/Line Out on Audio shield
// Connections
AudioConnection patchCord1(waveform1, 0, mixer, 0); // wave to mixer 
AudioConnection patchCord2(playRaw1, 0, mixer, 1); // raw audio to mixer
AudioConnection patchCord3(playWav1, 0, mixer, 2); // wav file playback mixer
AudioConnection patchCord4(mixer, 0, i2s1, 0); // mixer output to speaker (L)
AudioConnection patchCord5(i2s2, 0, queue1, 0); // mic input to queue (L)
AudioControlSGTL5000     sgtl5000_1;

// Filename to save audio recording on SD card
char filename[15];
// The file object itself
File frec;

// Use long 40ms debounce time on hook switch
Bounce buttonRecord = Bounce(HOOK_PIN, 40);
Bounce buttonPlay = Bounce(PLAYBACK_BUTTON_PIN, 8);

// Keep track of current state of the device
enum Mode {Initialising, Ready, Prompting, Recording, Playing};
Mode mode = Mode::Initialising;

void setup() {

  // Note that Serial.begin() is not required for Teensy - 
  // by default it initialises serial communication at full USB speed
  // See https://www.pjrc.com/teensy/td_serial.html
  // Serial.begin()
  Serial.println(__FILE__ __DATE__);
  
  // Configure the input pins
  pinMode(HOOK_PIN, INPUT_PULLUP);
  pinMode(PLAYBACK_BUTTON_PIN, INPUT_PULLUP);

  // Audio connections require memory, and the record queue
  // uses this memory to buffer incoming audio.
  AudioMemory(60);

  // Enable the audio shield, select input, and enable output
  sgtl5000_1.enable();
  // Define which input on the audio shield to use (AUDIO_INPUT_LINEIN / AUDIO_INPUT_MIC)
  sgtl5000_1.inputSelect(AUDIO_INPUT_MIC);
  sgtl5000_1.volume(0.5);

  // Play a beep to indicate system is online
  waveform1.begin(WAVEFORM_SINE);
  waveform1.frequency(440);
  waveform1.amplitude(0.9);
  wait(250);
  waveform1.amplitude(0);
  delay(1000);

  // Initialize the SD card
  SPI.setMOSI(SDCARD_MOSI_PIN);
  SPI.setSCK(SDCARD_SCK_PIN);
  if (!(SD.begin(SDCARD_CS_PIN))) {
    // stop here if no SD card, but print a message
    while (1) {
      Serial.println("Unable to access the SD card");
      delay(500);
    }
  }

  // Value in dB
  sgtl5000_1.micGain(15);

  // Synchronise the Time object used in the program code with the RTC time provider.
  // See https://github.com/PaulStoffregen/Time
  setSyncProvider(getTeensy3Time);
  
  // Define a callback that will assign the correct datetime for any file system operations
  // (i.e. saving a new audio recording onto the SD card)
  FsDateTime::setCallback(dateTime);

  mode = Mode::Ready;
}

void loop() {
  // First, read the buttons
  buttonRecord.update();
  buttonPlay.update();

  switch(mode){
    case Mode::Ready:
      // Rising edge occurs when the handset is lifted
      if (buttonRecord.fallingEdge()) {
        Serial.println("Handset lifted");
        mode = Mode::Prompting;
      }
      else if(buttonPlay.risingEdge()) {
        playAllRecordings();
      }
      break;

    case Mode::Prompting:
      // Wait a second for users to put the handset to their ear
      wait(1000);
      // Play the greeting inviting them to record their message
      playWav1.play("greeting.wav");    
      // Wait until the  message has finished playing
      while (playWav1.isPlaying()) {
        // Check whether the handset is replaced
        //  Serial.println("greeting playing");
        buttonRecord.update();
        // Handset is replaced
        if(buttonRecord.risingEdge()) {
          playWav1.stop();
          mode = Mode::Ready;
          return;
        }
      }
      // Debug message
      Serial.println("Starting Recording");
      // Play the tone sound effect
      waveform1.frequency(440);
      waveform1.amplitude(0.9);
      wait(250);
      waveform1.amplitude(0);
      // Start the recording function
      startRecording();
      break;

    case Mode::Recording:
      // Handset is replaced
      if(buttonRecord.risingEdge()){
        // Debug log
        Serial.println("Stopping Recording");
        // Stop recording
        stopRecording();
        // Play audio tone to confirm recording has ended
        waveform1.frequency(523.25);
        waveform1.amplitude(0.9);
        wait(50);
        waveform1.amplitude(0);
        wait(50);
        waveform1.amplitude(0.9);
        wait(50);
        waveform1.amplitude(0);
      }
      else {
        continueRecording();
      }
      break;

    case Mode::Playing:
      break;  
  }   
}

void startRecording() {
  // Find the first available file number
  for (uint8_t i=0; i<9999; i++) {
    // Format the counter as a five-digit number with leading zeroes, followed by file extension
    snprintf(filename, 11, " %05d.RAW", i);
    // Create if does not exist, do not open existing, write, sync after write
    if (!SD.exists(filename)) {
      break;
    }
  }
  frec = SD.open(filename, FILE_WRITE);
  if(frec) {
    Serial.print("Recording to ");
    Serial.println(filename);
    queue1.begin();
    mode = Mode::Recording;
  }
  else {
    Serial.println("Couldn't open file to record!");
  }
}

void continueRecording() {
  // Check if there is data in the queue
  if (queue1.available() >= 2) {
    byte buffer[512];
    // Fetch 2 blocks from the audio library and copy
    // into a 512 byte buffer.  The Arduino SD library
    // is most efficient when full 512 byte sector size
    // writes are used.
    memcpy(buffer, queue1.readBuffer(), 256);
    queue1.freeBuffer();
    memcpy(buffer+256, queue1.readBuffer(), 256);
    queue1.freeBuffer();
    // Write all 512 bytes to the SD card
    frec.write(buffer, 512);
  }
}

void stopRecording() {
  // Stop adding any new data to the queue
  queue1.end();
  // Flush all existing remaining data from the queue
  while (queue1.available() > 0) {
    // Save to open file
    frec.write((byte*)queue1.readBuffer(), 256);
    queue1.freeBuffer();
  }
  // Close the file
  frec.close();
  mode = Mode::Ready;
}


void playAllRecordings() {
  // Recording files are saved in the root directory
  File dir = SD.open("/");
  
  while (true) {
    File entry =  dir.openNextFile();
    if (!entry) {
      // no more files
      entry.close();
      break;
    }

    int8_t len = strlen(entry.name());
    if (strstr(strlwr(entry.name() + (len - 4)), ".raw")) {
      Serial.print("Now playing ");
      Serial.println(entry.name());
      // Play a short beep before each message
      waveform1.amplitude(0.5);
      wait(250);
      waveform1.amplitude(0);
      // Play the file
      playRaw1.play(entry.name());
      mode = Mode::Playing;
    }
    entry.close();

    while (playRaw1.isPlaying()) {
      buttonPlay.update();
      buttonRecord.update();
      // Button is pressed again
      if(buttonPlay.fallingEdge() || buttonRecord.risingEdge()) {
        playRaw1.stop();
        mode = Mode::Ready;
        return;
      }   
    }
  }
  // All files have been played
  mode = Mode::Ready;
}

// Retrieve the current time from Teensy built-in RTC
time_t getTeensy3Time(){
  return Teensy3Clock.get();
}

// Callback to assign timestamps for file system operations
void dateTime(uint16_t* date, uint16_t* time, uint8_t* ms10) {

  // Return date using FS_DATE macro to format fields.
  *date = FS_DATE(year(), month(), day());

  // Return time using FS_TIME macro to format fields.
  *time = FS_TIME(hour(), minute(), second());

  // Return low time bits in units of 10 ms.
  *ms10 = second() & 1 ? 100 : 0;
}

// Non-blocking delay, which pauses execution of main program logic,
// but while still listening for input 
void wait(unsigned int milliseconds) {
  elapsedMillis msec=0;

  while (msec <= milliseconds) {
    buttonRecord.update();
    buttonPlay.update();
    if (buttonRecord.risingEdge()) Serial.println("Button (pin 0) Press");
    if (buttonPlay.risingEdge()) Serial.println("Button (pin 1) Press");
    if (buttonRecord.fallingEdge()) Serial.println("Button (pin 0) Release");
    if (buttonPlay.fallingEdge()) Serial.println("Button (pin 1) Release");
  }
}
 
Hi, as far as i understand, there's 2 warning and 1 note, no errors, if theres an "opening teensy loader" line in your output, it usually means compiling went fine and you can upload the sketch. if it doesn't do so by itself, press the button on the teensy.
That said, i'm a bloody neewb myself, so take it with a grain of salt :)
 
Thanks for the help;)... I made those changes as suggested ... now it works, I can play the greeting.wav and record *.raw files and play back. However, while compiling I am receiving the following. Can anyone please suggest if the following indicating as errors? If so, how can I resolve?

As mentioned these are just compiler warnings. As to are they going to impact the program? Hard to say without looking at them.

C:\Users\dasau\OneDrive\80 AURICA\NICOLA\audio-guestbook\audio-guestbook.ino: In function 'void loop()':
C:\Users\dasau\OneDrive\80 AURICA\NICOLA\audio-guestbook\audio-guestbook.ino:131:9: warning: enumeration value 'Initialising' not handled in switch [-Wswitch]
switch(mode){

This one is saying: You are doing a switch on mode
Which is defined to have the following possible values: enum Mode {Initialising, Ready, Prompting, Recording, Playing};
And it is saying that you did not say anything about the possible state: Initialising
Ways around it: add case for it or add default:
These could be simply to then do: break;
So the compiler knows that it is handled...

^
C:\Users\dasau\OneDrive\80 AURICA\NICOLA\audio-guestbook\audio-guestbook.ino: In function 'void playAllRecordings()':
C:\Users\dasau\OneDrive\80 AURICA\NICOLA\audio-guestbook\audio-guestbook.ino:265:36: warning: invalid conversion from 'const char*' to 'char*' [-fpermissive]
if (strstr(strlwr(entry.name() + (len - 4)), ".raw")) {

^
In file included from c:\program files (x86)\arduino\hardware\tools\arm\arm-none-eabi\include\stdlib.h:11:0,
from C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy4/WProgram.h:34,
from C:\Users\dasau\AppData\Local\Temp\arduino_build_780846\pch\Arduino.h:6:
c:\program files (x86)\arduino\hardware\tools\arm\arm-none-eabi\include\string.h:150:7: note: initializing argument 1 of 'char* strlwr(char*)'
char *_EXFUN(strlwr,(char *));
^
This one is saying that you are passing entry.name() which is a (const char *) plus some offset to the function strlwr which takes a (char *)
Which is complaining that that function might try to change something that is marked const.

Two fixes: strlwr should really be marked as taking: const char * But that is library function so...
Or you tell the compiler that you want to pass it as char *
if (strstr(strlwr((char*)entry.name() + (len - 4)), ".raw")) {
 
This one is saying that you are passing entry.name() which is a (const char *) plus some offset to the function strlwr which takes a (char *)
Which is complaining that that function might try to change something that is marked const.

Two fixes: strlwr should really be marked as taking: const char * But that is library function so...
Or you tell the compiler that you want to pass it as char *
if (strstr(strlwr((char*)entry.name() + (len - 4)), ".raw")) {
This isn't quite correct, and could cause problems...

You are passing the result of a call to the function entry.name(), which returns a const char*: this tells you that you must not attempt to modify the data pointed to. Calling strlwr() with it as a parameter is such an attempt, because if there are upper-case characters in the filename then it will try to modify them in place, which is why strlwr() takes a char* parameter, and should absolutely not be "marked as taking const char*", because it doesn't!

EDIT: A better choice by the original author would have been to use strcasecmp(const char*, const char *), which does exactly what's wanted at this point...

I assume you've seen this thread, which addresses some of the other problems that this particular piece of code has.
 
Last edited:
Hi there! Sorry to interrupt this thread :)
Has anyone tried a Teensy 4.1 on this project (Audio Guestbook)? It looks to me it woulnd't need the SD+Audio shield as it seems to have this all built in

Thanks!
 
Or is there an audio-sd shield for 4.1?
Same Audio board for T4.0 and T4.1. If you use T4.1 you have the option of using the SD on the Audio Board or the one on the T4.1.
The T4.1 SD is faster than the Audio Board SD.
 
More audio shields are coming, but we don't have a precise date yet.

Production of another batch was held up by a shortage on the SD sockets. We got new (slightly different part) SD sockets, but that meant new PCBs needed to be made. They're being made now. Typically takes 2 weeks. Then manufacturing the PCBs usually takes 3 weeks. But everything this time of year gets disrupted to some degree by the holidays.

Best guess is first week or two of January the audio shield should be available again.
 
Ok, I see, anyway I realized that neither Teensy 4.0 neither 4.1 are available (at a reasonable price) shipped to my country right now
I will check again on Jan
Thanks everyone!
 
Back
Top