SFEMP3Shield.cpp 71.9 KB
Newer Older
papp's avatar
arduino  
papp committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
\file SFEMP3Shield.cpp

\brief Code file for the SFEMP3Shield library
\remarks comments are implemented with Doxygen Markdown format

*/

#include "SFEMP3Shield.h"
// inslude the SPI library:
#include "SPI.h"
//avr pgmspace library for storing the LUT in program flash instead of sram
#include <avr/pgmspace.h>

/**
 * \brief bitrate lookup table
 *
 * This is a table to decode the bitrate as per the MP3 file format,
 * as read by the SdCard
 *
 * <A HREF = "http://www.mp3-tech.org/programmer/frame_header.html" > www.mp3-tech.org </A>
 * \note PROGMEM macro forces to Flash space.
 * \warning This consums 190 bytes of flash
 */
PROGMEM const uint16_t bitrate_table[15][6] = {
                 { 0,   0,  0,  0,  0,  0}, //0000
                 { 32, 32, 32, 32,  8,  8}, //0001
                 { 64, 48, 40, 48, 16, 16}, //0010
                 { 96, 56, 48, 56, 24, 24}, //0011
                 {128, 64, 56, 64, 32, 32}, //0100
                 {160, 80, 64, 80, 40, 40}, //0101
                 {192, 96, 80, 96, 48, 48}, //0110
                 {224,112, 96,112, 56, 56}, //0111
                 {256,128,112,128, 64, 64}, //1000
                 {288,160,128,144, 80, 80}, //1001
                 {320,192,160,160, 96, 69}, //1010
                 {352,224,192,176,112,112}, //1011
                 {384,256,224,192,128,128}, //1100
                 {416,320,256,224,144,144}, //1101
                 {448,384,320,256,160,160}  //1110
               };

/*
 * Format of a MIDI file into a char arrar. Simply one note on and then off.
*/
// MIDI Event Specifics
#define MIDI_NOTE_ON             9
#define MIDI_NOTE_OFF            8

// MIDI File structure
// Header Chunk
#define MIDI_HDR_CHUNK_ID     0x4D, 0x54, 0x68, 0x64  // const for MIDI
#define MIDI_CHUNKSIZE           0,    0,    0,    6
#define MIDI_FORMAT              0,    0              // VSdsp only support Format 0!
#define MIDI_NUMBER_OF_TRACKS    0,    1              // ergo must be 1 track
#define MIDI_TIME_DIVISION       0,   96
// Track Chunk
#define MIDI_TRACK_CHUNK_ID   0x4D, 0x54, 0x72, 0x6B  // const for MIDI
#define MIDI_CHUNK_SIZE          0,    0,    0, sizeof(MIDI_EVENT_NOTE_ON) + sizeof(MIDI_EVENT_NOTE_OFF) + sizeof(MIDI_END_OF_TRACK) // hard coded with zero padded
// Events
#define MIDI_EVENT_NOTE_ON       0, (MIDI_NOTE_ON<<4) + MIDI_CHANNEL, MIDI_NOTE_NUMBER, MIDI_INTENSITY
#define MIDI_EVENT_NOTE_OFF   MIDI_NOTE_DURATION, (MIDI_NOTE_OFF<<4) + MIDI_CHANNEL, MIDI_NOTE_NUMBER, MIDI_INTENSITY
//
#define MIDI_END_OF_TRACK        0, 0xFF, 0x2F,    0

/**
 * \brief a MIDI File of one Note
 *
 * This is string containing a complete MIDI format 0 file of one Note ON and then Off.
 *
 * <A HREF = "http://www.sonicspot.com/guide/midifiles.html" > Description of MIDI file parsing </A>
 * \note PROGMEM macro forces to Flash space.
 * \warning This should consume 34 bytes of flash
 *
 *
 * An inline equation @f$ e^{\pi i}+1 = 0 @f$
 *
 * A displayed equation: @f[ e^{\pi i}+1 = 0 @f]
 *
 *
 */
PROGMEM const uint8_t SingleMIDInoteFile[] = {MIDI_HDR_CHUNK_ID, MIDI_CHUNKSIZE, MIDI_FORMAT, MIDI_NUMBER_OF_TRACKS, MIDI_TIME_DIVISION, MIDI_TRACK_CHUNK_ID, MIDI_CHUNK_SIZE, MIDI_EVENT_NOTE_ON, MIDI_EVENT_NOTE_OFF, MIDI_END_OF_TRACK};

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/* Initialize static classes and variables
 */

/**
 * \brief Initializer for the instance of the SdCard's static member.
 */
SdFile   SFEMP3Shield::track;

/**
 * \brief Initializer for the instance of the SdCard's static member.
 */
state_m  SFEMP3Shield::playing_state;

/**
 * \brief Initializer for the instance of the SdCard's static member.
 */
uint16_t SFEMP3Shield::spi_Read_Rate;
uint16_t SFEMP3Shield::spi_Write_Rate;

// only needed for specific means of refilling
#if defined(USE_MP3_REFILL_MEANS) && USE_MP3_REFILL_MEANS == USE_MP3_SimpleTimer
  SimpleTimer timer;
  int timerId_mp3;
#endif

//buffer for music
uint8_t  SFEMP3Shield::mp3DataBuffer[32];

//------------------------------------------------------------------------------
/**
 * \brief Initialize the MP3 Player shield.
 *
 * Execute this function before anything else, typically during setup().
 * It will bring the VS10xx out of reset, initialize the connected pins and
 * then ready the VSdsp for playback, with vs_init().
 *
 * \return Any Value other than zero indicates a problem occured.
 * where value indicates specific error
 *
 * \see
 * end() for low power mode
 * \see
 * \ref Error_Codes
 * \warning Will disrupt playback, if issued while playing back.
 * \note The \c SdFat::begin() function is required to be executed prior, as to
 * define the volume for the tracks (aka files) to be operated on.
 */
uint8_t  SFEMP3Shield::begin() {

/*
 This test is to assit in the migration from versions prior to 1.01.00.
 It is not really needed, simply prints an easy error, to better assist.
 If you are using SdFat objects other than "sd" the below may be omitted.
 or whant to save 222 bytes of Flash space.
 */
#if (1)
if (int8_t(sd.vol()->fatType()) == 0) {
  Serial.println(F("If you get this error, you likely do not have a sd.begin in the main sketch, See Trouble Shooting Guide!"));
  Serial.println(F("http://mpflaga.github.com/Sparkfun-MP3-Player-Shield-Arduino-Library/#Troubleshooting"));
}
#endif

  pinMode(MP3_DREQ, INPUT);
  pinMode(MP3_XCS, OUTPUT);
  pinMode(MP3_XDCS, OUTPUT);
  pinMode(MP3_RESET, OUTPUT);

#if PERF_MON_PIN != -1
  pinMode(PERF_MON_PIN, OUTPUT);
  digitalWrite(PERF_MON_PIN,HIGH);
#endif

  cs_high();  //MP3_XCS, Init Control Select to deselected
  dcs_high(); //MP3_XDCS, Init Data Select to deselected
  digitalWrite(MP3_RESET, LOW); //Put VS1053 into hardware reset

  playing_state = initialized;

  uint8_t result = vs_init();
  if(result) {
    return result;
  }

#if defined(USE_MP3_REFILL_MEANS) && USE_MP3_REFILL_MEANS == USE_MP3_Timer1
  Timer1.initialize(MP3_REFILL_PERIOD);
#elif defined(USE_MP3_REFILL_MEANS) && USE_MP3_REFILL_MEANS == USE_MP3_SimpleTimer
  timerId_mp3 = timer.setInterval(MP3_REFILL_PERIOD, refill);
  timer.disable(timerId_mp3);
#endif

  return 0;
}

/**
 * \brief Disables the MP3 Player shield.
 *
 * Places the VS10xx into low power hard reset, after polity closing files
 * after releasing interrupts and or timers.
 *
 * \warning Will stop any playing tracks. Check isPlaying() prior to executing, as not to stop on a track.
 * \note use begin() to reinitialize the VS10xx, for use.
 */
void SFEMP3Shield::end() {

  stopTrack(); // Stop and CLOSE any open tracks.
  disableRefill(); // shut down specific interrupts
  cs_high();  //MP3_XCS, Init Control Select to deselected
  dcs_high(); //MP3_XDCS, Init Data Select to deselected

  // most importantly...
  digitalWrite(MP3_RESET, LOW); //Put VS1053 into hardware reset

  playing_state = deactivated;
}

//------------------------------------------------------------------------------
/**
 * \brief Initialize the VS10xx Audio Decoder Chip.
 *
 * Reset and initialize the VS10xx chip's internal registers such as clock
 * for normal operation with the SFEMP3Shield class's members.
 * Along with uploading corresponding accumilative patch file, if present.
 *
 * \return Any Value other than zero indicates a problem occured.
 * - 0 indicates that upload was successful.
 * - 1 thru 3 are omitted, as not to overlap with other errors.
 * - 4 indicates other than default values were found in the SCI_MODE register.
 * - 5 indicates SCI_CLOCKF did not read back and verify the configured value.
 *
 * \note returned Error codes are typically passed and therefore need to avoid
 * overlap.
 *
 * \see
 * \ref Error_Codes
 */
uint8_t SFEMP3Shield::vs_init() {

  //Initialize VS1053 chip

  //Reset if not already
  delay(100); // keep clear of anything prior
  digitalWrite(MP3_RESET, LOW); //Shut down VS1053
  delay(100);

  //Bring out of reset
  digitalWrite(MP3_RESET, HIGH); //Bring up VS1053

  //From section 7.6 of datasheet, max SCI reads are CLKI/7.
  //Assuming CLKI = 12.288MgHz for Shield and 16.0MgHz for Arduino
  //The VS1053's internal clock multiplier SCI_CLOCKF:SC_MULT is 1.0x after power up.
  //For a maximum SPI rate of 1.8MgHz = (CLKI/7) = (12.288/7) the VS1053's default.

  //Warning:
  //Note that spi transfers interleave between SdCard and VS10xx.
  //Where Sd2Card.cpp sets SPCR & SPSR each and every transfer

  //The SDfatlib using SPI_FULL_SPEED results in an 8MHz spi clock rate,
  //faster than initial allowed spi rate of 1.8MgHz.

  // set initial mp3's spi to safe rate
  spi_Read_Rate  = SPI_CLOCK_DIV16;
  spi_Write_Rate = SPI_CLOCK_DIV16;
  delay(10);

   //Let's check the status of the VS1053
  int MP3Mode = Mp3ReadRegister(SCI_MODE);

/*
  Serial.print(F("SCI_Mode (0x4800) = 0x"));
  Serial.println(MP3Mode, HEX);

  int MP3Status = Mp3ReadRegister(SCI_Status);
  Serial.print(F("SCI_Status (0x48) = 0x"));
  Serial.println(MP3Status, HEX);

  int MP3Clock = Mp3ReadRegister(SCI_CLOCKF);
  Serial.print(F("SCI_ClockF = 0x"));
  Serial.println(MP3Clock, HEX);
  */

  if(MP3Mode != (SM_LINE1 | SM_SDINEW)) return 4;

  //Now that we have the VS1053 up and running, increase the internal clock multiplier and up our SPI rate
  Mp3WriteRegister(SCI_CLOCKF, 0x6000); //Set multiplier to 3.0x
  //Internal clock multiplier is now 3x.
  //Therefore, max SPI speed is 52MgHz.

#if (F_CPU == 16000000 )
  spi_Read_Rate  = SPI_CLOCK_DIV4; //use safe SPI rate of (16MHz / 4 = 4MHz)
  spi_Write_Rate = SPI_CLOCK_DIV2; //use safe SPI rate of (16MHz / 2 = 8MHz)
#else
  // must be 8000000
  spi_Read_Rate  = SPI_CLOCK_DIV2; //use safe SPI rate of (8MHz / 2 = 4MHz)
  spi_Write_Rate = SPI_CLOCK_DIV2; //use safe SPI rate of (8MHz / 2 = 4MHz)
#endif

  delay(10); // settle time

  //test reading after data rate change
  int MP3Clock = Mp3ReadRegister(SCI_CLOCKF);
  if(MP3Clock != 0x6000) return 5;

  setVolume(40, 40);
  // one would think the following patch would over write the volume.
  // But the SCI_VOL register space is not in the VSdsp's WRAM space.
  // Note to keep an eye on it for future patches.

  if(VSLoadUserCode("patches.053")) return 6;

  delay(100); // just a good idea to let settle.

  return 0; // indicating all was good.
}

//------------------------------------------------------------------------------
/**
 * \brief load VS1xxx with patch or plugin from file on SDcard.
 *
 * \param[out] fileName pointer of a char array (aka string), contianing the filename
 *
 * Loads the VX10xx with filename of the specified patch, if present.
 * This can be used to load various VSdsp apps, patches and plug-in's.
 * Providing many new features and updates not present on the default firmware.
 *
 * The file format of the plugin is raw binary, in VLSI's interleaved and RLE
 * compressed format, as extracted from the source plugin file (.plg).
 * A perl script \c vs_plg_to_bin.pl is provided to convert the .plg
 * file in to the binary filename.053. Where the extension of .053 is a
 * convention to indicate the VSdsp chip version.
 *
 * \note by default all plug-ins are expected to be in the root of the SdCard.
 *
 * \return Any Value other than zero indicates a problem occured.
 * - 0 indicates that upload was successful.
 * - 1 indicates the upload can not be performed while currently streaming music.
 * - 2 indicates that desired file was not found.
 * - 3 indicates that the VSdsp is in reset.
 *
 * \see
 * - \ref Error_Codes
 * - \ref Plug_Ins
 */
uint8_t SFEMP3Shield::VSLoadUserCode(char* fileName){

  union twobyte val;
  union twobyte addr;
  union twobyte n;

  if(!digitalRead(MP3_RESET)) return 3;
  if(isPlaying()) return 1;
  if(!digitalRead(MP3_RESET)) return 3;

  //Open the file in read mode.
  if(!track.open(fileName, O_READ)) return 2;
  //playing_state = loading;
  //while(i<size_of_Plugin/sizeof(Plugin[0])) {
  while(1) {
    //addr = Plugin[i++];
    if(!track.read(addr.byte, 2)) break;
    //n = Plugin[i++];
    if(!track.read(n.byte, 2)) break;
    if(n.word & 0x8000U) { /* RLE run, replicate n samples */
      n.word &= 0x7FFF;
      //val = Plugin[i++];
      if(!track.read(val.byte, 2)) break;
      while(n.word--) {
        Mp3WriteRegister(addr.word, val.word);
      }
    } else {           /* Copy run, copy n samples */
      while(n.word--) {
        //val = Plugin[i++];
        if(!track.read(val.byte, 2))   break;
        Mp3WriteRegister(addr.word, val.word);
      }
    }
  }
  track.close(); //Close out this track
  //playing_state = ready;
  return 0;
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// @{
// SelfTest_Group

//------------------------------------------------------------------------------
/**
 * \brief Generate Test Sine wave
 *
 * \param[in] freq specifies the output frequency sine wave.
 *
 * Enable and/or report the generation of Test Sine Wave as per specified.
 * As specified by Data Sheet Section 9.12.1
 *
 * \return
 * - -1 indicates the test can not be performed while currently streaming music
 *      or chip is reset.
 * - 1 indicates that test has begun successfully.
 * - 2 indicates that test is already in progress.
 *
 * \see
 * \ref Error_Codes
 * \note 9.12.5 New Sine and Sweep Tests was not implemented.
 */
uint8_t SFEMP3Shield::enableTestSineWave(uint8_t freq) {

  if(isPlaying() || !digitalRead(MP3_RESET)) {
    Serial.println(F("Warning Tests are not available."));
    return -1;
  }

  uint16_t MP3SCI_MODE = Mp3ReadRegister(SCI_MODE);
  if(MP3SCI_MODE & SM_TESTS) {
    return 2;
  }

  Mp3WriteRegister(SCI_MODE, MP3SCI_MODE | SM_TESTS);

  for(int y = 0 ; y <= 1 ; y++) { // need to do it twice if it was already done once before
    //Wait for DREQ to go high indicating IC is available
    while(!digitalRead(MP3_DREQ)) ;
    //Select control
    dcs_low();
    //SCI consists of instruction byte, address byte, and 16-bit data word.
    SPI.transfer(0x53);
    SPI.transfer(0xEF);
    SPI.transfer(0x6E);
    SPI.transfer(freq);
    SPI.transfer(0x00);
    SPI.transfer(0x00);
    SPI.transfer(0x00);
    SPI.transfer(0x00);
    while(!digitalRead(MP3_DREQ)) ; //Wait for DREQ to go high indicating command is complete
    dcs_high(); //Deselect Control
  }

  playing_state = testing_sinewave;
  return 1;
}

//------------------------------------------------------------------------------
/**
 * \brief Disable Test Sine wave
 *
 * Disable and report the generation of Test Sine Wave as per specified.
 * As specified by Data Sheet Section 9.12.1
 * \return
 * - -1 indicates the test can not be performed while currently streaming music
 *      or chip is reset.
 * - 0 indicates the test is not previously enabled and skipping disable.
 * - 1 indicates that test was disabled.
 *
 * \see
 * \ref Error_Codes
 */
uint8_t SFEMP3Shield::disableTestSineWave() {

  if(isPlaying() || !digitalRead(MP3_RESET)) {
    Serial.println(F("Warning Tests are not available."));
    return -1;
  }

  uint16_t MP3SCI_MODE = Mp3ReadRegister(SCI_MODE);
  if(!(MP3SCI_MODE & SM_TESTS)) {
    return 0;
  }

  //Wait for DREQ to go high indicating IC is available
  while(!digitalRead(MP3_DREQ)) ;

  //Select SPI Control channel
  dcs_low();

  //SDI consists of instruction byte, address byte, and 16-bit data word.
  SPI.transfer(0x45);
  SPI.transfer(0x78);
  SPI.transfer(0x69);
  SPI.transfer(0x74);
  SPI.transfer(0x00);
  SPI.transfer(0x00);
  SPI.transfer(0x00);
  SPI.transfer(0x00);
  while(!digitalRead(MP3_DREQ)) ; //Wait for DREQ to go high indicating command is complete

  //Deselect SPI Control channel
  dcs_high();

  // turn test mode bit off
  Mp3WriteRegister(SCI_MODE, Mp3ReadRegister(SCI_MODE) & ~SM_TESTS);

  playing_state = ready;
  return 0;
}

//------------------------------------------------------------------------------
/**
 * \brief Perform Memory Test
 *
 * Perform the internal memory test of the VSdsp core processor and resources.
 * As specified by Data Sheet Section 9.12.4
 *
 * \return
 * - -1 indicates the test can not be performed while currently streaming music
 *      or chip is reset.
 * - 1 indicates that test has begun successfully.
 * - 2 indicates that test is already in progress.
 *
 * \see
 * \ref Error_Codes
 */
uint16_t SFEMP3Shield::memoryTest() {

  if(isPlaying() || !digitalRead(MP3_RESET)) {
    Serial.println(F("Warning Tests are not available."));
    return -1;
  }

  playing_state = testing_memory;

  vs_init();

  uint16_t MP3SCI_MODE = Mp3ReadRegister(SCI_MODE);
  if(MP3SCI_MODE & SM_TESTS) {
    playing_state = ready;
    return 2;
  }

  Mp3WriteRegister(SCI_MODE, MP3SCI_MODE | SM_TESTS);

//  for(int y = 0 ; y <= 1 ; y++) { // need to do it twice if it was already done once before
    //Wait for DREQ to go high indicating IC is available
    while(!digitalRead(MP3_DREQ)) ;

    //Select SPI Control channel
    dcs_low();

    //SCI consists of instruction byte, address byte, and 16-bit data word.
    SPI.transfer(0x4D);
    SPI.transfer(0xEA);
    SPI.transfer(0x6D);
    SPI.transfer(0x54);
    SPI.transfer(0x00);
    SPI.transfer(0x00);
    SPI.transfer(0x00);
    SPI.transfer(0x00);
    while(!digitalRead(MP3_DREQ)) ; //Wait for DREQ to go high indicating command is complete

    //Deselect SPI Control channel
    dcs_high();
//  }
  delay(250);

  uint16_t MP3SCI_HDAT0 = Mp3ReadRegister(SCI_HDAT0);

  Mp3WriteRegister(SCI_MODE, Mp3ReadRegister(SCI_MODE) & ~SM_TESTS);

  vs_init();

  playing_state = ready;
  return MP3SCI_HDAT0;
}
// @}
// SelfTest_Group

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// @{
// Volume_Group

//------------------------------------------------------------------------------
/**
 * \brief Overload function of SFEMP3Shield::setVolume(leftchannel, rightchannel)
 *
 * \param[in] data packed with left and right master volume
 *
 * calls SFEMP3Shield::setVolume expecting the left channel in the upper byte
 * and right channel in the lower byte.
 *
 * As specified by Data Sheet Section 8.7.11
 */
void SFEMP3Shield::setVolume(uint16_t data) {
  union twobyte val;
  val.word = data;
  setVolume(val.byte[1], val.byte[0]);
}

//------------------------------------------------------------------------------
/**
 * \brief Overload function of SFEMP3Shield::setVolume(leftchannel, rightchannel)
 *
 * \param[in] uint8_t to be placed into both Left and Right
 *
 * calls SFEMP3Shield::setVolume placing the input into both the left channel
 * and right channels.
 *
 * As specified by Data Sheet Section 8.7.11
 */
void SFEMP3Shield::setVolume(uint8_t data) {
  setVolume(data, data);
}

//------------------------------------------------------------------------------
/**
 * \brief Store and Push member volume to VS10xx chip
 *
 * \param[in] leftchannel writes the left channel master volume
 * \param[in] rightchannel writes the right channel master volume
 *
 * Updates the VS10xx SCI_VOL register's left and right master volume level in
 * -0.5 dB Steps. Where maximum volume is 0x0000 and total silence is 0xFEFE.
 * As specified by Data Sheet Section 8.7.11
 *
 * \note input values are -1/2dB. e.g. 40 results in -20dB.
 */
void SFEMP3Shield::setVolume(uint8_t leftchannel, uint8_t rightchannel){

  VolL = leftchannel;
  VolR = rightchannel;
  Mp3WriteRegister(SCI_VOL, leftchannel, rightchannel);
}

//------------------------------------------------------------------------------
/**
 * \brief Get the current volume from the VS10xx chip
 *
 * Read the VS10xx SC_VOL register and return its results
 * As specified by Data Sheet Section 8.7.11
 *
 * \return uint16_t of both channels of master volume.
 * Where the left channel is in the upper byte and right channel is in the lower
 * byte.
 *
 * \note Input values are -1/2dB. e.g. 40 results in -20dB.
 * \note Cast the output to the union of twobyte.word to access individual
 * channels, with twobyte.byte[1] and [0].
 */
uint16_t SFEMP3Shield::getVolume() {
  uint16_t MP3SCI_VOL = Mp3ReadRegister(SCI_VOL);
  return MP3SCI_VOL;
}
// @}
// Volume_Group

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// @{
// Base_Treble_Group

//------------------------------------------------------------------------------
/**
 * \brief Get the current Treble Frequency limit from the VS10xx chip
 *
 * \return int16_t of frequency limit in Hertz.
 *
 */
uint16_t SFEMP3Shield::getTrebleFrequency()
{
  union sci_bass_m sci_base_value;
  sci_base_value.word = Mp3ReadRegister(SCI_BASS);
  return (sci_base_value.nibble.Treble_Freqlimt * 1000);
}

//------------------------------------------------------------------------------
/**
 * \brief Get the current Treble Amplitude from the VS10xx chip
 *
 * \return int16_t of amplitude (from -8 to 7).
 *
 */
int8_t SFEMP3Shield::getTrebleAmplitude()
{
  union sci_bass_m sci_base_value;
  sci_base_value.word = Mp3ReadRegister(SCI_BASS);
  return (sci_base_value.nibble.Treble_Amplitude);
}
//------------------------------------------------------------------------------
/**
 * \brief Get the current Bass Frequency limit from the VS10xx chip
 *
 * \return int16_t of bass frequency limit in Hertz.
 *
 */
uint16_t SFEMP3Shield::getBassFrequency()
{
  union sci_bass_m sci_base_value;
  sci_base_value.word = Mp3ReadRegister(SCI_BASS);
  return (sci_base_value.nibble.Bass_Freqlimt * 10);
}

//------------------------------------------------------------------------------
/**
 * \brief Get the current Bass boost amplitude from the VS10xx chip
 *
 * \return int16_t of bass bost amplitude in dB.
 *
 * \note Any value greater then zero enables the Bass Enhancer VSBE is a 
 * powerful bass boosting DSP algorithm, which tries to take the most out 
 * of the users earphones without causing clipping.
 *
 */
int8_t SFEMP3Shield::getBassAmplitude()
{
  union sci_bass_m sci_base_value;
  sci_base_value.word = Mp3ReadRegister(SCI_BASS);
  return (sci_base_value.nibble.Bass_Amplitude);
}
//------------------------------------------------------------------------------
/**
 * \brief Set the current treble frequency limit in VS10xx chip
 *
 * \param[in] Treble cutoff frequency limit in Hertz.
 *
 * \note The upper and lower limits of this parameter is checked.
 */
void SFEMP3Shield::setTrebleFrequency(uint16_t frequency)
{
  union sci_bass_m sci_base_value;

  frequency /= 1000;

  if(frequency < 1)
  {
      frequency = 1;
  }
  else if(frequency > 15)
  {
      frequency = 15;
  }
  
  sci_base_value.word = Mp3ReadRegister(SCI_BASS);
  sci_base_value.nibble.Treble_Freqlimt = frequency;
  Mp3WriteRegister(SCI_BASS, sci_base_value.word); 
}

//------------------------------------------------------------------------------
/**
 * \brief Set the current Treble Amplitude in VS10xx chip
 *
 * \param[in] Treble amplitude in dB from -8 to 7.
 *
 * \note The upper and lower limits of this parameter is checked. 
 */
void SFEMP3Shield::setTrebleAmplitude(int8_t amplitude)
{
  union sci_bass_m sci_base_value;


  if(amplitude < -8)
  {
      amplitude = -8;
  }
  else if(amplitude > 7)
  {
      amplitude = 7;
  }

  sci_base_value.word = Mp3ReadRegister(SCI_BASS);
  sci_base_value.nibble.Treble_Amplitude = amplitude;
  Mp3WriteRegister(SCI_BASS, sci_base_value.word); 
}

//------------------------------------------------------------------------------
/**
 * \brief Set the current Bass Boost Frequency limit cutoff in VS10xx chip
 *
 * \param[in] Bass Boost frequency cutoff limit in Hertz (20Hz to 150Hz).
 *
 * \note The upper and lower limits of this parameter is checked. 
 */
void SFEMP3Shield::setBassFrequency(uint16_t frequency)
{
  union sci_bass_m sci_base_value;

  frequency /= 10;

  if(frequency < 2)
  {
      frequency = 2;
  }
  else if(frequency > 15)
  {
      frequency = 15;
  }

  sci_base_value.word = Mp3ReadRegister(SCI_BASS);
  sci_base_value.nibble.Bass_Freqlimt = frequency;
  Mp3WriteRegister(SCI_BASS, sci_base_value.word); 
}

//------------------------------------------------------------------------------
/**
 * \brief Set the current Bass Boost amplitude in VS10xx chip
 *
 * \param[in] Bass Boost amplitude in dB (0dB to 15dB).
 *
 * \note Any value greater then zero enables the Bass Enhancer VSBE is a 
 * powerful bass boosting DSP algorithm, which tries to take the most out 
 * of the users earphones without causing clipping.
 *
 * \note The upper and lower limits of this parameter is checked. 
 */
void SFEMP3Shield::setBassAmplitude(uint8_t amplitude)
{
  union sci_bass_m sci_base_value;

  if(amplitude < 0)
  {
      amplitude = 0;
  }
  else if(amplitude > 15)
  {
      amplitude = 15;
  }

  sci_base_value.word = Mp3ReadRegister(SCI_BASS);
  sci_base_value.nibble.Bass_Amplitude = amplitude;
  Mp3WriteRegister(SCI_BASS, sci_base_value.word); 
}
// @}
// Base_Treble_Group

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// @{
// PlaySpeed_Group

//------------------------------------------------------------------------------
/**
 * \brief Get the current playSpeed from the VS10xx chip
 *
 * Read the VS10xx extra parameter memory for playSpeed register and return its
 * results.
 * As specified by Data Sheet Section 9.11.1
 *
 * \return multipler of current playspeed versus normal speed.
 * Where 0 and/or 1 are normal 1x speed.
 * e.g. 4 to playSpeed will play the song four times as fast as normal,
 * if you are able to feed the data with that speed.
 *
 * \warning Excessive playspeed beyond the ability to stream data between the
 * SdCard, Arduino and VS10xx may result in erratic behavior.
 */
uint16_t SFEMP3Shield::getPlaySpeed() {
  uint16_t MP3playspeed = Mp3ReadWRAM(para_playSpeed);
  return MP3playspeed;
}

//------------------------------------------------------------------------------
/**
 * \brief Set the current playSpeed of the VS10xx chip
 *
 * Write the VS10xx extra parameter memory for playSpeed register with the
 * desired multipler.
 *
 * Where 0 and/or 1 are normal 1x speed.
 * e.g. 4 to playSpeed will play the song four times as fast as normal,
 * if you are able to feed the data with that speed.
 * As specified by Data Sheet Section 9.11.1
 *
 * \warning Excessive playspeed beyond the ability to stream data between the
 * SdCard, Arduino and VS10xx may result in erratic behavior.
 */
void SFEMP3Shield::setPlaySpeed(uint16_t data) {
  Mp3WriteWRAM(para_playSpeed, data);
}
// @}
//PlaySpeed_Group

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// @{
// EarSpeaker_Group

//------------------------------------------------------------------------------
/**
 * \brief Get the current Spatial EarSpeaker setting from the VS10xx chip
 *
 * Read the VS10xx SCI_MODE register bits SM_EARSPEAKER_LO and SM_EARSPEAKER_HIGH
 * for current EarSpeaker and return its results as a composite integer.
 * As specified by Data Sheet Section 8.7.1 and 8.4
 *
 * \return result between 0 and 3. Where 0 is OFF and 3 is maximum.
 */
uint8_t SFEMP3Shield::getEarSpeaker() {
  uint8_t result = 0;
  uint16_t MP3SCI_MODE = Mp3ReadRegister(SCI_MODE);

  // SM_EARSPEAKER bits are not adjacent hence need to add them together
  if(MP3SCI_MODE & SM_EARSPEAKER_LO) {
    result += 0b01;
  }
  if(MP3SCI_MODE & SM_EARSPEAKER_HI) {
    result += 0b10;
  }
  return result;
}

//------------------------------------------------------------------------------
/**
 * \brief Set the current Spatial EarSpeaker setting of the VS10xx chip
 *
 * \param[in] EarSpeaker integer value between 0 and 3. Where 0 is OFF and 3 is maximum.
 *
 * The input value is mapped onto SM_EARSPEAKER_LO and SM_EARSPEAKER_HIGH bits
 * and written the VS10xx SCI_MODE register, preserving the remainder of SCI_MODE.
 * As specified by Data Sheet Section 8.7.1 and 8.4
 */
void SFEMP3Shield::setEarSpeaker(uint16_t EarSpeaker) {
  uint16_t MP3SCI_MODE = Mp3ReadRegister(SCI_MODE);

  // SM_EARSPEAKER bits are not adjacent hence need to add them individually
  if(EarSpeaker & 0b01) {
    MP3SCI_MODE |=  SM_EARSPEAKER_LO;
  } else {
    MP3SCI_MODE &= ~SM_EARSPEAKER_LO;
  }

  if(EarSpeaker & 0b10) {
    MP3SCI_MODE |=  SM_EARSPEAKER_HI;
  } else {
    MP3SCI_MODE &= ~SM_EARSPEAKER_HI;
  }
  Mp3WriteRegister(SCI_MODE, MP3SCI_MODE);
}
// @}
// EarSpeaker_Group

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// @{
// Differential_Output_Mode_Group

//------------------------------------------------------------------------------
/**
 * \brief Get the current SM_DIFF setting from the VS10xx chip
 *
 * Read the VS10xx SCI_MODE register bits SM_DIFF
 * for current SM_DIFF and return its results as a composite integer.
 * To indicate if the Left Channel is either normal or differential output.
 * As specified by Data Sheet Section 8.7.1
 *
 * \return 0 for Normal and 1 is Differential Output.
 * \return
 * - 0 Normal in-phase audio output of left and right speaker signals.
 * - 1 Left channel output is the invert of the right channel.
 *
 * \see setDifferentialOutput()
 */
uint8_t SFEMP3Shield::getDifferentialOutput() {
  uint8_t result = 0;
  uint16_t MP3SCI_MODE = Mp3ReadRegister(SCI_MODE);

  if(MP3SCI_MODE & SM_DIFF) {
    result = 1;
  }
  return result;
}

//------------------------------------------------------------------------------
/**
 * \brief Set the current SM_DIFF setting of the VS10xx chip
 *
 * \param[in] DiffMode integer value between 0 and 1.
 *
 * The input value is mapped onto the SM_DIFF of the SCI_MODE register,
 *  preserving the remainder of SCI_MODE. For stereo playback streams this
 * creates a virtual sound, and for mono streams this creates a differential
 * left/right output with a maximum output of 3V.

 * As specified by Data Sheet Section 8.7.1
 * \see getDifferentialOutput()
 */
void SFEMP3Shield::setDifferentialOutput(uint16_t DiffMode) {
  uint16_t MP3SCI_MODE = Mp3ReadRegister(SCI_MODE);

  if(DiffMode) {
    MP3SCI_MODE |=  SM_DIFF;
  } else {
    MP3SCI_MODE &= ~SM_DIFF;
  }
  Mp3WriteRegister(SCI_MODE, MP3SCI_MODE);
}
// @}
// Differential_Output_Mode_Group

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// @{
// Stereo_Group

//------------------------------------------------------------------------------
/**
 * \brief Get the current Stereo/Mono setting of the VS10xx output
 *
 * Read the VS10xx WRAMADDR bit 0 of para_MonoOutput] for the current Stereo/Mono and
 * return its results as a byte. As specified by VS1053B PATCHES AND FLAC
 * DECODER Data Sheet Section 1.2 Mono output mode.
 *
 * \return result between 0 and 3. Where 0 is OFF and 3 is maximum.
 *
 * \warning This feature is only available when composite patch 1.7 or higher
 * is loaded into the VSdsp.
 */
uint16_t SFEMP3Shield::getMonoMode() {
  uint16_t result = (Mp3ReadWRAM(para_MonoOutput) & 0x0001);
  return result;
}

//------------------------------------------------------------------------------
/**
 * \brief Set the current Stereo/Mono setting of the VS10xx output
 *
 * Write the VS10xx WRAMADDR para_MonoOutput bit 0 to configure the current
 * Stereo/Mono. As specified by VS1053B PATCHES AND FLAC DECODER Data Sheet
 * Section 1.2 Mono output mode. While preserving the other bits.
 *
 * \warning This feature is only available when composite patch 1.7 or higher
 * is loaded into the VSdsp.
 */
void SFEMP3Shield::setMonoMode(uint16_t StereoMode) {
  uint16_t data = (Mp3ReadWRAM(para_MonoOutput) & ~0x0001); // preserve other bits
  Mp3WriteWRAM(0x1e09, (StereoMode | (data & 0x0001)));
For faster browsing, not all history is shown. View entire blame