#include <SdFat.h>
#include <MD_MIDIFile.h>
#define SERIAL_RATE 31250 // Midi standard serial rate is 31250 baud
#define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0]))
// frequency counter using timer 1 and 2
volatile unsigned long totalCounts;
volatile bool nextCount;
volatile unsigned long Timer1overflowCounts;
volatile unsigned long overflowCounts;
unsigned int counter, countPeriod;
// MIDI off the SD
const byte SD_SELECT = 53; // Chip select for Sd card is pin 10
const char *loopfile = "MIDI_sample.MID"; // pointer to midi file on SD card
const int buttonPin = 7; // the number of the pushbutton pin
const int ledPin = 6; // the number of the LED pin
bool playFile = false; // boolean variable indicating if a file should be played
unsigned int timerTicks;
SDFAT SD;
MD_MIDIFile SMF; // create an instance of a midi file
// Called by the MIDIFile library when a file event needs to be processed
// thru the midi communications interface.
// This callback is set up in the setup() function.
void midiCallback(midi_event *pev){
if (pev->data[0] == 0x80){
// Serial.println("Note Off");
// Serial.println(pev->data[1]);
// Serial.println(pev->data[2]);
// Serial.println(pev->track);
// Serial.println(pev->channel);
digitalWrite(ledPin, LOW);
}
if (pev->data[0] == 0x90){
// Serial.println("Note On");
// Serial.println(pev->data[1]);
// Serial.println(pev->data[2]);
// Serial.println(pev->track);
// Serial.println(pev->channel);
digitalWrite(ledPin, HIGH);
}
if ((pev->data[0] >= 0x80) && (pev->data[0] <= 0xe0)){
//Serial.write(pev->data[0] | pev->channel);
//Serial.write(&pev->data[1], pev->size-1);
//Serial.println(pev->data[0]);
}
else {
//Serial.write(pev->data, pev->size);
}
}
void setup() {
pinMode(buttonPin, INPUT_PULLUP); // use built in pullup resistor with push button
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
Serial.begin(SERIAL_RATE);
// Initialize SD Card
if (!SD.begin(SD_SELECT, SPI_FULL_SPEED)){
while (true) ;
}
// Initialize MIDIFile
SMF.begin(&SD);
SMF.setMidiHandler(midiCallback);
SMF.looping(false);
TCNT1=0x00; //Reset Timer 1 Counter.
TCCR1A=0x00;
TCCR1B=0x07;
}
void loop() {
// Wait for pushbutton input
//int reading = digitalRead(buttonPin);
// If push button is depressed, load midi file and switch on LED
//if (reading == LOW) {
// playFile = true;
//digitalWrite(ledPin, HIGH); // Switch on LED
// SMF.load(loopfile);
// }
startCount(1000);
while(!nextCount){}
SMF.load(loopfile);
playFile = true;
// play the file if playFile is true
if(playFile == true){
// Play until end of file is reached
while (!SMF.isEOF()){
SMF.getNextEvent();
Serial.print("Timer: ");
Serial.println(TCCR1A);
}
}
// Once file is finished playing, close midi file and switch off LED
playFile = false;
//digitalWrite(ledPin, LOW);
SMF.close();
}