Hi,
I am trying to gradually increase volume while playing tracks from SD card.
Hardware setup: Arduino UNO R3 clone (Elegoo) + Sparkfun MP3 Player v15 shield + LED/resistor on PB5 (for troubleshooting).
I am using Timer2 overflow interrupts to increase the volume (also tried Timer1 CTC).
Problem: playing tracks from SD card seem to be interfering with the timer, i.e. timer overflow interrupt routine is not invoked.
#ifndef F_CPU
#define F_CPU 16000000UL
#endif
#include <avr/io.h>
#include <avr/interrupt.h>
#include <TrueRandom.h>
#include <SPI.h>
#include <SdFat.h>
#include <FreeStack.h>
#include <SFEMP3Shield.h>
#if defined(USE_MP3_REFILL_MEANS) && USE_MP3_REFILL_MEANS == USE_MP3_Timer1
#include <TimerOne.h>
#elif defined(USE_MP3_REFILL_MEANS) && USE_MP3_REFILL_MEANS == USE_MP3_SimpleTimer
#include <SimpleTimer.h>
#endif
volatile char vol = 48;
volatile uint16_t tmr_count = 0;
SFEMP3Shield MP3player;
SdFat sd;
int main(void)
{
DDRB |= (1 << 5); // Set LED on PB5 as output
uint8_t result; //result code from functions, to verify success
//Initialize the SdCard.
if(!sd.begin(SD_SEL, SPI_FULL_SPEED)) sd.initErrorHalt();
// depending upon your SdCard environment, SPI_HAVE_SPEED may work better.
if(!sd.chdir("/")) sd.errorHalt("sd.chdir");
result = MP3player.begin(); //test result here, if needed
//set initial volume
MP3player.setVolume(vol, vol);
//set mono mode
MP3player.setMonoMode(1);
result = sd.begin(SD_SEL, SPI_FULL_SPEED); //test result here, if needed
TCCR2B |= (1<<CS20) | (1<<CS21) | (1<<CS22); // PRESCALER 1024
TIMSK2 = (1<<TOIE2); //enable overflow interrupt
sei (); // Enable global interrupts
for (;;)
{
if ( !MP3player.isPlaying() ) {
play_tracks();
}
}
}
void play_tracks()
{
char filename[13];
int count = 0;
// count the files
SdFile file;
sd.chdir("/", true);
while (file.openNext(sd.vwd(), O_READ)) {
count += 1;
file.close();
}
// pick a random one
int r = TrueRandom.random(count + 1);
// loop over all the files agai - if our current
// index equals the random one - play it
sd.chdir("/", true);
count = 0;
while (file.openNext(sd.vwd(), O_READ)) {
if ( count == r )
{
file.getName(filename, sizeof(filename));
int8_t result = MP3player.playMP3(filename);
if (result != 0) {
//error - skip it
continue;
}
}
file.close();
count += 1;
}
}
ISR(TIMER2_OVF_vect)
{
if(tmr_count >= 50) // gives approx. 1 sec period
{
if(vol <= 2) // 2 is max volume
{
vol = 2;
} else {
vol -= 2; //decrementing vol actually increases volume
MP3player.setVolume(vol, vol);
}
tmr_count = 0;
PORTB ^= (1 << 5); // Toggle the LED
} else {
tmr_count++;
}
}
Actual result: volume does not increase, LED does not blink.
If I comment out the code that initializes SD, MP3player and play_tracks(), LED blinks as expected.
Any advice would be appreciated!