forked from xfjx/TonUINO
-
Notifications
You must be signed in to change notification settings - Fork 40
/
tonuino.ino
2207 lines (2040 loc) · 82.5 KB
/
tonuino.ino
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
/*
basic button actions:
=====================
Button B0 (by default pin A0, middle button on the original TonUINO): play/pause
Button B1 (by default pin A1, right button on the original TonUINO): volume up
Button B2 (by default pin A2, left button on the original TonUINO): volume down
Button B3 (by default pin A3, optional): previous track
Button B4 (by default pin A4, optional): next track
additional button actions:
==========================
During idle:
------------
Hold B0 for 5 seconds - Enter parents menu
During playback:
----------------
Hold B0 for 5 seconds - Reset progress to track 1 (story book mode)
Hold B0 for 5 seconds - Single track repeat (all modes, except story book mode)
Hold B1 for 2 seconds - Skip to the next track ((v)album, (v)party and story book mode)
Hold B2 for 2 seconds - Skip to the previous track ((v)album, (v)party and story book mode)
During parents menu:
--------------------
Click B0 - Confirm selection
Click B1 - Next option
Click B2 - Previous option
Click B3 - Jump 10 options backwards
Click B4 - Jump 10 options forward
Double click B0 - Announce current option
Hold B0 for 2 seconds - Cancel parents menu or any submenu
Hold B1 for 2 seconds - Jump 10 options forward
Hold B2 for 2 seconds - Jump 10 options backwards
During nfc tag setup mode:
--------------------------
Click B0 - Confirm selection
Click B1 - Next folder, mode or track
Click B2 - Previous folder, mode or track
Click B3 - Jump 10 folders or tracks backwards
Click B4 - Jump 10 folders or tracks forward
Double click B0 - Announce current folder, mode or track number
Hold B0 for 2 seconds - Cancel nfc tag setup mode
Hold B1 for 2 seconds - Jump 10 folders or tracks forward
Hold B2 for 2 seconds - Jump 10 folders or tracks backwards
During power up:
----------------
Hold B0 + B1 + B2 - Erase all eeprom contents (resets stored progress and preferences)
ir remote:
==========
If an ir receiver (like TSOP38238 or similar) is connected to pin 5, you can also use
an ir remote to remote control TonUINO. The remote needs at least seven buttons to be
able to support all functions. This feature can be enabled by uncommenting the
'#define IRREMOTE' below.
Down below you can hard code (multiple sets of) code mappings for remotes which will
always be recognized. In addition to these hard coded remotes, you can learn in one
additional remote using the parents menu, which is then stored in EEPROM.
There is one function, currently only available with the ir remote: Box lock.
When TonUINO is locked, the buttons on TonUINO as well as the nfc reader are disabled
until TonUINO is unlocked again. Playback continues while TonUINO is locked and
you are still able to control TonUINO using the ir remote (great for parents).
During idle:
------------
center - toggle box lock
menu - enter parents menu
During playback:
----------------
center - toggle box lock
play/pause - toggle playback
up / down - volume up / down
left / right - previous / next track ((v)album, (v)party and story book mode)
menu - reset progress to track 1 (story book mode)
menu - single track repeat (all modes, except story book mode)
During parents menu:
--------------------
center - announce current option
play/pause - confirm selection
up / down - next / previous option
left / right - jump 10 options backwards / forward
menu - cancel
During nfc tag setup mode:
--------------------------
center - announce current folder, mode or track number
play/pause - confirm selection
up / down - next / previous folder, mode or track
left / right - jump 10 folders or tracks backwards / forward
menu - cancel
pin code:
=========
The complete erase of the eeprom contents (hold vol-, play/pause, vol+ during startup)
as well as the parents menu can be secured with a pin code of variable length. It is
defined (and can be changed) in the configuration section below, the default pin code is:
===> play/pause, vol-, vol+, play/pause <===
Once the pin code entry is triggered, you have (by default) 10s to enter the pin code
before it times out. It repeats when entered incorrectly. See status led section
for information about visual feedback. This feature can be enabled by uncommenting
the '#define PINCODE' below.
status led(s):
==============
There are two options for a status led (which are mutually exclusive!):
1) Connect a vanilla led to pin 6 and uncomment the '#define STATUSLED' below.
TonUINO will signal various status information, for example:
- Pulse slowly when TonUINO is idle.
- Solid when TonUINO is playing a title.
- Blink every 500ms when interactive in menus etc.
- Blink every 100ms if the LOWVOLTAGE feature is active and the battery is low.
- Burst 4 times when TonUINO is locked and 8 times when unlocked.
- Burst 4 times when repeat is activated and 8 times when deactivated.
There are some more signals, they try to be intuitive. You'll see.
2) Connect one (or even several) ws281x rgb led(s) to pin 6 and uncomment
the '#define STATUSLEDRGB' below. TonUINO will signal various status information
in different patterns and colors, for example:
- Pulse slowly green when TonUINO is idle.
- Solid green when TonUINO is playing a title.
- Blink yellow every 500ms when interactive in menus etc.
- Blink red every 100ms if the LOWVOLTAGE feature is active and the battery is low.
- Burst 4 times red when TonUINO is locked and 8 times green when unlocked.
- Burst 4 times white when repeat is activated and 8 times white when deactivated.
- Burst 8 times magenta when the track in story book mode is reset to 1.
There are some more signals, they try to be intuitive. You'll see.
For the vanilla led basically any 5V led will do, just don't forget to put an appropriate
resistor in series. For the ws281x led(s) you have several options. Stripes, single
neo pixels etc. The author did test the fuctionality with an 'addressable Through-Hole 5mm RGB LED'
from Pololu [1]. Please make sure you put a capacitor of at least 10 uF between the ground
and power lines of the led and consider adding a 100 to 1k ohm resistor between pin 6
and the led's data in. In general make sure you have enough current available (especially if
you plan more than one led - each takes up to 60mA!) and don't source the current for the led(s)
from the arduino power rail! Consult your ws281x led vendors documentation for guidance!
The ammount of ws281x led(s) as well as the max brightness can be set in the configuration
section below. The defaults are: One led and 20% brightness.
[1] https://www.pololu.com/product/2535
cubiekid:
=========
If you happen to have a CubieKid case and the CubieKid circuit board, this firmware
supports both shutdown methods. The inactivity shutdown timer is enabled by default,
the shutdown due to low battery voltage (which can be configured in the shutdown
section below) can be enabled by uncommenting the '#define LOWVOLTAGE' below.
The CubieKid case as well as the CubieKid circuit board, have been designed and developed
by Jens Hackel aka DB3JHF and can be found here: https://www.thingiverse.com/thing:3148200
pololu switch:
==============
If you want to use a pololu switch with this firmware the shutdown pin logic needs
to be flipped from HIGH (on) -> LOW (off) to LOW (on) -> HIGH (off). This can be done
by uncommenting the '#define POLOLUSWITCH' below.
data stored on the nfc tags:
============================
On MIFARE Classic (Mini, 1K & 4K) tags:
---------------------------------------
Up to 16 bytes of data are stored in sector 1 / block 4, of which the first 9 bytes
are currently in use:
13 37 B3 47 01 02 04 10 19 00 00 00 00 00 00 00
----------- -- -- -- -- --
| | | | | |
| | | | | +- end track (0x01-0xFF - in vstory (0x06), valbum (0x07) and vparty (0x08) modes)
| | | | +- single/start track (0x01-0xFF - in single (0x04), vstory (0x06), valbum (0x07) and vparty (0x08) modes)
| | | +- playback mode (0x01-0x08)
| | +- folder (0x01-0x63)
| +- version (currently always 0x01)
+- magic cookie to recognize that a card belongs to TonUINO (by default 0x13 0x37 0xb3 0x47)
On MIFARE Ultralight / Ultralight C and NTAG213/215/216 tags:
-------------------------------------------------------------
Up to 16 bytes of data are stored in pages 8-11, of which the first 9 bytes
are currently in use:
8 13 37 B3 47 - magic cookie to recognize that a card belongs to TonUINO (by default 0x13 0x37 0xb3 0x47)
9 01 02 04 10 - version, folder, playback mode, single track / start strack
10 19 00 00 00 - end track
11 00 00 00 00
additional non standard libraries used in this firmware:
========================================================
MFRC522.h - https://github.com/miguelbalboa/rfid
DFMiniMp3.h - https://github.com/Makuna/DFMiniMp3
AceButton.h - https://github.com/bxparks/AceButton
IRremote.h - https://github.com/z3t0/Arduino-IRremote
WS2812.h - https://github.com/cpldcpu/light_ws2812
Vcc.h - https://github.com/Yveaux/Arduino_Vcc
*/
// uncomment the below line to enable five button support
// #define FIVEBUTTONS
// uncomment the below line to enable ir remote support
// #define IRREMOTE
// uncomment the below line to enable pin code support
// #define PINCODE
// uncomment ONE OF THE BELOW TWO LINES to enable status led support
// the first enables support for a vanilla led
// the second enables support for ws281x led(s)
// #define STATUSLED
// #define STATUSLEDRGB
// uncomment the below line to enable low voltage shutdown support
// #define LOWVOLTAGE
// uncomment the below line to flip the shutdown pin logic
// #define POLOLUSWITCH
// include required libraries
#include <avr/sleep.h>
#include <SoftwareSerial.h>
#include <SPI.h>
#include <EEPROM.h>
#include <MFRC522.h>
#include <DFMiniMp3.h>
#include <AceButton.h>
using namespace ace_button;
// include additional library if ir remote support is enabled
#if defined IRREMOTE
#include <IRremote.h>
#endif
// include additional library if ws281x status led support is enabled
#if defined STATUSLED ^ defined STATUSLEDRGB
#if defined STATUSLEDRGB
#include <WS2812.h>
#endif
#endif
// include additional library if low voltage shutdown support is enabled
#if defined LOWVOLTAGE
#include <Vcc.h>
#endif
// playback modes
enum {NOMODE, STORY, ALBUM, PARTY, SINGLE, STORYBOOK, VSTORY, VALBUM, VPARTY};
// button actions
enum {NOP,
B0P, B1P, B2P, B3P, B4P,
B0H, B1H, B2H, B3H, B4H,
B0D, B1D, B2D, B3D, B4D,
IRU, IRD, IRL, IRR, IRC, IRM, IRP
};
// button modes
enum {INIT, PLAY, PAUSE, PIN, CONFIG};
// shutdown timer actions
enum {START, STOP, CHECK, SHUTDOWN};
// preference actions
enum {READ, WRITE, MIGRATE, RESET, RESET_PROGRESS};
// status led actions
enum {OFF, SOLID, PULSE, BLINK, BURST2, BURST4, BURST8};
// define general configuration constants
const uint8_t mp3SerialRxPin = 2; // mp3 serial rx, wired to tx pin of DFPlayer Mini
const uint8_t mp3SerialTxPin = 3; // mp3 serial tx, wired to rx pin of DFPlayer Mini
const uint8_t mp3BusyPin = 4; // reports play state of DFPlayer Mini (LOW = playing)
#if defined IRREMOTE
const uint8_t irReceiverPin = 5; // pin used for the ir receiver
#endif
#if defined STATUSLED ^ defined STATUSLEDRGB
const uint8_t statusLedPin = 6; // pin used for vanilla status led or ws281x status led(s)
const uint8_t statusLedCount = 1; // number of ws281x status led(s)
const uint8_t statusLedMaxBrightness = 20; // max brightness of ws281x status led(s) (in percent)
#endif
const uint8_t shutdownPin = 7; // pin used to shutdown the system
const uint8_t nfcResetPin = 9; // used for spi communication to nfc module
const uint8_t nfcSlaveSelectPin = 10; // used for spi communication to nfc module
const uint8_t button0Pin = A0; // middle button
const uint8_t button1Pin = A1; // right button
const uint8_t button2Pin = A2; // left button
#if defined FIVEBUTTONS
const uint8_t button3Pin = A3; // optional 4th button
const uint8_t button4Pin = A4; // optional 5th button
#endif
const uint16_t buttonClickDelay = 1000; // time during which a button press is still a click (in milliseconds)
const uint16_t buttonShortLongPressDelay = 2000; // time after which a button press is considered a long press (in milliseconds)
const uint16_t buttonLongLongPressDelay = 5000; // longer long press delay for special cases, i.e. to trigger the parents menu (in milliseconds)
const uint32_t debugConsoleSpeed = 9600; // speed for the debug console
// define magic cookie (by default 0x13 0x37 0xb3 0x47)
const uint8_t magicCookieHex[4] = {0x13, 0x37, 0xb3, 0x47};
#if defined PINCODE
// define pin code, allowed enums for pinCode[]: B0P, B1P, B2P (plus B3P & B4P if FIVEBUTTONS is enabled)
const uint8_t pinCode[] = {B0P, B2P, B1P, B0P}; // for example play/pause, vol-, vol+, play/pause
const uint8_t pinCodeLength = sizeof(pinCode);
const uint8_t pinCodeIrToButtonMapping[] = {B1P, B2P, B3P, B4P, NOP, IRM, B0P};
const uint64_t enterPinCodeTimeout = 10000; // time to enter the pin code (in milliseconds)
#endif
// default values for preferences
const uint8_t preferenceVersion = 1;
const uint8_t mp3StartVolumeDefault = 15;
const uint8_t mp3MaxVolumeDefault = 25;
const uint8_t mp3MenuVolumeDefault = 15;
const uint8_t mp3EqualizerDefault = 1;
const uint8_t shutdownMinutesDefault = 10;
const uint16_t irRemoteUserCodesDefault[7] = {};
/*
define hard coded (sets of) code mappings for ir remotes.
one remote per line with the following order of codes for: up, down, left, right, center, menu, play/pause
when adding multiple remotes, the array needs to look like this (watch the 'commas'!):
const uint16_t irRemoteCodes[][7] = {
{...},
{...},
{...}
};
*/
const uint16_t irRemoteCodes[][7] = {
{0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000} // example, replace 0x0000 with respective codes as per above
};
const uint8_t irRemoteCount = sizeof(irRemoteCodes) / 14;
const uint8_t irRemoteCodeCount = sizeof(irRemoteCodes) / (2 * irRemoteCount);
#if defined LOWVOLTAGE
// define constants for shutdown feature
const float shutdownMinVoltage = 4.4; // minimum expected voltage level (in volts)
const float shutdownWarnVoltage = 4.8; // warning voltage level (in volts)
const float shutdownMaxVoltage = 5.0; // maximum expected voltage level (in volts)
const float shutdownVoltageCorrection = 1.0 / 1.0; // voltage measured by multimeter divided by reported voltage
#endif
// define strings
const char *playbackModeName[] = {" ", "story", "album", "party", "single", "storybook", "vstory", "valbum", "vparty"};
const char *nfcStatusMessage[] = {" ", "read", "write", "ok", "failed"};
const char *mp3EqualizerName[] = {" ", "normal", "pop", "rock", "jazz", "classic", "bass"};
// this struct stores nfc tag data
struct nfcTagStruct {
uint32_t cookie = 0;
uint8_t version = 0;
uint8_t folder = 0;
uint8_t mode = 0;
uint8_t multiPurposeData1 = 0;
uint8_t multiPurposeData2 = 0;
};
// this struct stores playback state
struct playbackStruct {
bool isLocked = false;
bool isPlaying = false;
bool isFresh = true;
bool isRepeat = false;
bool playListMode = false;
uint8_t mp3CurrentVolume = 0;
uint8_t folderStartTrack = 0;
uint8_t folderEndTrack = 0;
uint8_t playList[255] = {};
uint8_t playListItem = 0;
uint8_t playListItemCount = 0;
nfcTagStruct currentTag;
};
// this struct stores preferences
struct preferenceStruct {
uint32_t cookie = 0;
uint8_t version = 0;
uint8_t mp3StartVolume = 0;
uint8_t mp3MaxVolume = 0;
uint8_t mp3MenuVolume = 0;
uint8_t mp3Equalizer = 0;
uint8_t shutdownMinutes = 0;
uint16_t irRemoteUserCodes[7] = {};
};
// global variables
uint8_t inputEvent = NOP;
uint32_t magicCookie = 0;
uint32_t preferenceCookie = 0;
playbackStruct playback;
preferenceStruct preference;
// ################################################################################################################################################################
// ############################################################### no configuration below this line ###############################################################
// ################################################################################################################################################################
// declare functions
void checkForInput();
void translateButtonInput(AceButton *button, uint8_t eventType, uint8_t /* buttonState */);
void switchButtonConfiguration(uint8_t buttonMode);
void waitPlaybackToFinish(uint8_t red, uint8_t green, uint8_t blue, uint16_t statusLedUpdateInterval);
void printModeFolderTrack(bool cr);
void playNextTrack(uint16_t globalTrack, bool directionForward, bool triggeredManually);
uint8_t readNfcTagData();
uint8_t writeNfcTagData(uint8_t nfcTagWriteBuffer[], uint8_t nfcTagWriteBufferSize);
void printNfcTagData(uint8_t dataBuffer[], uint8_t dataBufferSize, bool cr);
void printNfcTagType(MFRC522::PICC_Type nfcTagType);
void shutdownTimer(uint8_t timerAction);
void preferences(uint8_t preferenceAction);
uint8_t prompt(uint8_t promptOptions, uint16_t promptHeading, uint16_t promptOffset, uint8_t promptCurrent, uint8_t promptFolder, bool promptPreview, bool promptChangeVolume);
void parentsMenu();
#if defined PINCODE
bool enterPinCode();
#endif
#if defined STATUSLED ^ defined STATUSLEDRGB
void statusLedUpdate(uint8_t statusLedAction, uint8_t red, uint8_t green, uint8_t blue, uint16_t statusLedUpdateInterval);
void statusLedUpdateHal(uint8_t red, uint8_t green, uint8_t blue, int16_t brightness);
#endif
class Mp3Notify; // forward declare the notify class, just the name
SoftwareSerial mp3Serial(mp3SerialRxPin, mp3SerialTxPin); // create SoftwareSerial instance
typedef DFMiniMp3<SoftwareSerial, Mp3Notify> DfMp3; // define a type using serial and the notify class
DfMp3 mp3(mp3Serial); // create DfMp3 instance
MFRC522 mfrc522(nfcSlaveSelectPin, nfcResetPin); // create MFRC522 instance
ButtonConfig button0Config; // create ButtonConfig instance
ButtonConfig button1Config; // create ButtonConfig instance
ButtonConfig button2Config; // create ButtonConfig instance
AceButton button0(&button0Config); // create AceButton instance
AceButton button1(&button1Config); // create AceButton instance
AceButton button2(&button2Config); // create AceButton instance
#if defined FIVEBUTTONS
ButtonConfig button3Config; // create ButtonConfig instance
ButtonConfig button4Config; // create ButtonConfig instance
AceButton button3(&button3Config); // create AceButton instance
AceButton button4(&button4Config); // create AceButton instance
#endif
#if defined STATUSLED ^ defined STATUSLEDRGB
#if defined STATUSLEDRGB
WS2812 rgbLed(statusLedCount); // create WS2812 instance
#endif
#endif
#if defined LOWVOLTAGE
Vcc shutdownVoltage(shutdownVoltageCorrection); // create Vcc instance
#endif
// used by DFPlayer Mini library during callbacks
class Mp3Notify {
public:
static void OnError([[maybe_unused]] DfMp3& mp3, uint16_t returnValue) {
switch (returnValue) {
case DfMp3_Error_Busy: {
Serial.print(F("busy"));
break;
}
case DfMp3_Error_Sleeping: {
Serial.print(F("sleep"));
break;
}
case DfMp3_Error_SerialWrongStack: {
Serial.print(F("serial stack"));
break;
}
case DfMp3_Error_CheckSumNotMatch: {
Serial.print(F("checksum"));
break;
}
case DfMp3_Error_FileIndexOut: {
Serial.print(F("file index"));
break;
}
case DfMp3_Error_FileMismatch: {
Serial.print(F("file mismatch"));
break;
}
case DfMp3_Error_Advertise: {
Serial.print(F("advertise"));
break;
}
case DfMp3_Error_RxTimeout: {
Serial.print(F("rx timeout"));
break;
}
case DfMp3_Error_PacketSize: {
Serial.print(F("packet size"));
break;
}
case DfMp3_Error_PacketHeader: {
Serial.print(F("packet header"));
break;
}
case DfMp3_Error_PacketChecksum: {
Serial.print(F("packet checksum"));
break;
}
case DfMp3_Error_General: {
Serial.print(F("general"));
break;
}
default: {
Serial.print(F("unknown"));
break;
}
}
Serial.println(F(" error"));
}
static void PrintlnSourceAction(DfMp3_PlaySources source, const char* action) {
if (source & DfMp3_PlaySources_Sd) Serial.print("sd ");
if (source & DfMp3_PlaySources_Usb) Serial.print("usb ");
if (source & DfMp3_PlaySources_Flash) Serial.print("flash ");
Serial.println(action);
}
static void OnPlayFinished([[maybe_unused]] DfMp3& mp3, [[maybe_unused]] DfMp3_PlaySources source, uint16_t returnValue) {
playNextTrack(returnValue, true, false);
}
static void OnPlaySourceOnline([[maybe_unused]] DfMp3& mp3, DfMp3_PlaySources source) {
PrintlnSourceAction(source, "online");
}
static void OnPlaySourceInserted([[maybe_unused]] DfMp3& mp3, DfMp3_PlaySources source) {
PrintlnSourceAction(source, "in");
}
static void OnPlaySourceRemoved([[maybe_unused]] DfMp3& mp3, DfMp3_PlaySources source) {
PrintlnSourceAction(source, "out");
}
};
void setup() {
// things we need to do immediately on startup
pinMode(shutdownPin, OUTPUT);
#if defined POLOLUSWITCH
digitalWrite(shutdownPin, LOW);
#else
digitalWrite(shutdownPin, HIGH);
#endif
magicCookie = (uint32_t)magicCookieHex[0] << 24;
magicCookie += (uint32_t)magicCookieHex[1] << 16;
magicCookie += (uint32_t)magicCookieHex[2] << 8;
magicCookie += (uint32_t)magicCookieHex[3];
preferenceCookie = (uint32_t)magicCookieHex[2] << 24;
preferenceCookie += (uint32_t)magicCookieHex[3] << 16;
preferenceCookie += (uint32_t)magicCookieHex[0] << 8;
preferenceCookie += (uint32_t)magicCookieHex[1];
// start normal operation
Serial.begin(debugConsoleSpeed);
Serial.println(F("\n\nTonUINO JUKEBOX"));
Serial.println(F("by Thorsten Voß"));
Serial.println(F("Stephan Eisfeld"));
Serial.println(F("and many others"));
Serial.println(F("---------------"));
Serial.println(F("flashed"));
Serial.print(F(" "));
Serial.println(__DATE__);
Serial.print(F(" "));
Serial.println(__TIME__);
preferences(READ);
Serial.println(F("init nfc"));
SPI.begin();
mfrc522.PCD_Init();
mfrc522.PCD_DumpVersionToSerial();
Serial.println(F("init mp3"));
mp3.begin();
delay(2000);
Serial.print(F(" start "));
Serial.println(preference.mp3StartVolume);
mp3.setVolume(playback.mp3CurrentVolume = preference.mp3StartVolume);
Serial.print(F(" max "));
Serial.println(preference.mp3MaxVolume);
Serial.print(F(" menu "));
Serial.println(preference.mp3MenuVolume);
Serial.print(F(" eq "));
Serial.println(mp3EqualizerName[preference.mp3Equalizer]);
mp3.setEq((DfMp3_Eq)(preference.mp3Equalizer - 1));
Serial.print(F(" files "));
Serial.println(mp3.getTotalTrackCount(DfMp3_PlaySource_Sd));
pinMode(mp3BusyPin, INPUT);
Serial.print(F("init"));
pinMode(button0Pin, INPUT_PULLUP);
pinMode(button1Pin, INPUT_PULLUP);
pinMode(button2Pin, INPUT_PULLUP);
button0.init(button0Pin, HIGH, 0);
button1.init(button1Pin, HIGH, 1);
button2.init(button2Pin, HIGH, 2);
#if defined FIVEBUTTONS
pinMode(button3Pin, INPUT_PULLUP);
pinMode(button4Pin, INPUT_PULLUP);
button3.init(button3Pin, HIGH, 3);
button4.init(button4Pin, HIGH, 4);
Serial.print(F(" 5"));
#else
Serial.print(F(" 3"));
#endif
Serial.println(F(" buttons"));
switchButtonConfiguration(INIT);
Serial.print(F("init "));
Serial.print(preference.shutdownMinutes);
Serial.println(F("m timer"));
shutdownTimer(START);
#if defined IRREMOTE
Serial.println(F("init ir"));
IrReceiver.begin(irReceiverPin, DISABLE_LED_FEEDBACK);
#endif
#if defined STATUSLED ^ defined STATUSLEDRGB
#if defined STATUSLED
Serial.println(F("init led"));
pinMode(statusLedPin, OUTPUT);
#endif
#if defined STATUSLEDRGB
Serial.println(F("init ws281x"));
rgbLed.setOutput(statusLedPin);
rgbLed.setColorOrderRGB();
//rgbLed.setColorOrderBRG();
//rgbLed.setColorOrderGRB();
#endif
statusLedUpdate(SOLID, 0, 0, 0, 0);
#endif
#if defined LOWVOLTAGE
Serial.println(F("init lvm"));
Serial.print(F(" ex-"));
Serial.print(shutdownMaxVoltage);
Serial.print(F("V"));
Serial.print(F(" wa-"));
Serial.print(shutdownWarnVoltage);
Serial.print(F("V"));
Serial.print(F(" sh-"));
Serial.print(shutdownMinVoltage);
Serial.print(F("V"));
Serial.print(F(" cu-"));
Serial.print(shutdownVoltage.Read_Volts());
Serial.print(F("V ("));
Serial.print(shutdownVoltage.Read_Perc(shutdownMinVoltage, shutdownMaxVoltage));
Serial.println(F("%)"));
#endif
// hold down all three buttons while powering up: erase the eeprom contents
if (button0.isPressedRaw() && button1.isPressedRaw() && button2.isPressedRaw()) {
#if defined PINCODE
if (enterPinCode()) {
#endif
Serial.println(F("init eeprom"));
for (uint16_t i = 0; i < EEPROM.length(); i++) {
EEPROM.update(i, 0);
}
preferences(RESET);
mp3.setVolume(playback.mp3CurrentVolume = preference.mp3StartVolume);
mp3.setEq((DfMp3_Eq)(preference.mp3Equalizer - 1));
shutdownTimer(START);
mp3.playMp3FolderTrack(809);
waitPlaybackToFinish(0, 255, 0, 100);
#if defined PINCODE
}
#endif
}
switchButtonConfiguration(PAUSE);
mp3.playMp3FolderTrack(800);
Serial.println(F("ready"));
}
void loop() {
playback.isPlaying = !digitalRead(mp3BusyPin);
checkForInput();
shutdownTimer(CHECK);
#if defined LOWVOLTAGE
// if low voltage level is reached, store progress and shutdown
if (shutdownVoltage.Read_Volts() <= shutdownMinVoltage) {
if (playback.currentTag.mode == STORYBOOK) EEPROM.update(playback.currentTag.folder, playback.playList[playback.playListItem - 1]);
mp3.playMp3FolderTrack(808);
waitPlaybackToFinish(255, 0, 0, 100);
shutdownTimer(SHUTDOWN);
}
else if (shutdownVoltage.Read_Volts() <= shutdownWarnVoltage) {
#if defined STATUSLED ^ defined STATUSLEDRGB
statusLedUpdate(BLINK, 255, 0, 0, 100);
#endif
}
else {
#if defined STATUSLED ^ defined STATUSLEDRGB
if (playback.isPlaying) statusLedUpdate(SOLID, 0, 255, 0, 100);
else statusLedUpdate(PULSE, 0, 255, 0, 100);
#endif
}
#else
#if defined STATUSLED ^ defined STATUSLEDRGB
if (playback.isPlaying) statusLedUpdate(SOLID, 0, 255, 0, 100);
else statusLedUpdate(PULSE, 0, 255, 0, 100);
#endif
#endif
// ################################################################################
// # main code block, if nfc tag is detected and TonUINO is not locked do something
if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial() && !playback.isLocked) {
// if the current playback mode is story book mode, only while playing: store the current progress
if (playback.currentTag.mode == STORYBOOK && playback.isPlaying) {
Serial.print(F("save "));
printModeFolderTrack(true);
EEPROM.update(playback.currentTag.folder, playback.playList[playback.playListItem - 1]);
}
uint8_t readNfcTagStatus = readNfcTagData();
// ##############################
// # nfc tag is successfully read
if (readNfcTagStatus == 1) {
// #############################################################################
// # nfc tag has our magic cookie on it, use data from nfc tag to start playback
if (playback.currentTag.cookie == magicCookie) {
switchButtonConfiguration(PLAY);
shutdownTimer(STOP);
randomSeed(micros());
// prepare boundaries for playback
switch (playback.currentTag.mode) {
case STORY: {}
case ALBUM: {}
case PARTY: {}
case SINGLE: {}
case STORYBOOK: {
playback.folderStartTrack = 1;
playback.folderEndTrack = mp3.getFolderTrackCount(playback.currentTag.folder);
break;
}
case VSTORY: {}
case VALBUM: {}
case VPARTY: {
playback.folderStartTrack = playback.currentTag.multiPurposeData1;
playback.folderEndTrack = playback.currentTag.multiPurposeData2;
break;
}
default: {
break;
}
}
// prepare playlist for playback
for (uint8_t i = 0; i < 255; i++) playback.playList[i] = playback.folderStartTrack + i <= playback.folderEndTrack ? playback.folderStartTrack + i : 0;
playback.playListItemCount = playback.folderEndTrack - playback.folderStartTrack + 1;
// prepare first track for playback
switch (playback.currentTag.mode) {
case VSTORY: {}
case STORY: {
playback.playListItem = random(1, playback.playListItemCount + 1);
break;
}
case VALBUM: {}
case ALBUM: {
playback.playListItem = 1;
break;
}
case VPARTY: {}
case PARTY: {
playback.playListItem = 1;
// shuffle playlist
for (uint8_t i = 0; i < playback.playListItemCount; i++) {
uint8_t j = random(0, playback.playListItemCount);
uint8_t temp = playback.playList[i];
playback.playList[i] = playback.playList[j];
playback.playList[j] = temp;
}
break;
}
case SINGLE: {
playback.playListItem = playback.currentTag.multiPurposeData1;
break;
}
case STORYBOOK: {
uint8_t storedTrack = EEPROM.read(playback.currentTag.folder);
// don't resume from eeprom, play from the beginning
if (storedTrack == 0 || storedTrack > playback.folderEndTrack) playback.playListItem = 1;
// resume from eeprom
else {
playback.playListItem = storedTrack;
Serial.print(F("resume "));
}
break;
}
default: {
break;
}
}
playback.isFresh = true;
playback.isRepeat = false;
playback.playListMode = true;
printModeFolderTrack(true);
mp3.playFolderTrack(playback.currentTag.folder, playback.playList[playback.playListItem - 1]);
}
// # end - nfc tag has our magic cookie on it
// ##########################################
// #####################################################################################
// # nfc tag does not have our magic cookie on it, start setup to configure this nfc tag
else if (playback.currentTag.cookie == 0) {
nfcTagStruct newTag;
playback.playListMode = false;
// set volume to menu volume
mp3.setVolume(preference.mp3MenuVolume);
switchButtonConfiguration(CONFIG);
shutdownTimer(STOP);
while (true) {
Serial.println(F("setup tag"));
Serial.println(F("folder"));
newTag.folder = prompt(99, 801, 0, 0, 0, true, false);
if (newTag.folder == 0) {
mp3.playMp3FolderTrack(807);
waitPlaybackToFinish(255, 0, 0, 100);
break;
}
Serial.println(F("mode"));
newTag.mode = prompt(8, 820, 820, 0, 0, false, false);
if (newTag.mode == 0) {
mp3.playMp3FolderTrack(807);
waitPlaybackToFinish(255, 0, 0, 100);
break;
}
else if (newTag.mode == SINGLE) {
Serial.println(F("singletrack"));
newTag.multiPurposeData1 = prompt(mp3.getFolderTrackCount(newTag.folder), 802, 0, 0, newTag.folder, true, false);
newTag.multiPurposeData2 = 0;
if (newTag.multiPurposeData1 == 0) {
mp3.playMp3FolderTrack(807);
waitPlaybackToFinish(255, 0, 0, 100);
break;
}
}
else if (newTag.mode == VSTORY || newTag.mode == VALBUM || newTag.mode == VPARTY) {
Serial.println(F("starttrack"));
newTag.multiPurposeData1 = prompt(mp3.getFolderTrackCount(newTag.folder), 803, 0, 0, newTag.folder, true, false);
if (newTag.multiPurposeData1 == 0) {
mp3.playMp3FolderTrack(807);
waitPlaybackToFinish(255, 0, 0, 100);
break;
}
Serial.println(F("endtrack"));
newTag.multiPurposeData2 = prompt(mp3.getFolderTrackCount(newTag.folder), 804, 0, newTag.multiPurposeData1, newTag.folder, true, false);
newTag.multiPurposeData2 = max(newTag.multiPurposeData1, newTag.multiPurposeData2);
if (newTag.multiPurposeData2 == 0) {
mp3.playMp3FolderTrack(807);
waitPlaybackToFinish(255, 0, 0, 100);
break;
}
}
uint8_t bytesToWrite[] = {magicCookieHex[0], // 1st byte of magic cookie (by default 0x13)
magicCookieHex[1], // 2nd byte of magic cookie (by default 0x37)
magicCookieHex[2], // 3rd byte of magic cookie (by default 0xb3)
magicCookieHex[3], // 4th byte of magic cookie (by default 0x47)
0x01, // version 1
newTag.folder, // the folder selected by the user
newTag.mode, // the playback mode selected by the user
newTag.multiPurposeData1, // multi purpose data (ie. single track for mode 4 and start of vfolder)
newTag.multiPurposeData2, // multi purpose data (ie. end of vfolder, depending on mode)
0x00, 0x00, 0x00, // reserved for future use
0x00, 0x00, 0x00, 0x00 // reserved for future use
};
uint8_t writeNfcTagStatus = writeNfcTagData(bytesToWrite, sizeof(bytesToWrite));
if (writeNfcTagStatus == 1) {
mp3.playMp3FolderTrack(805);
waitPlaybackToFinish(0, 255, 0, 100);
}
else {
mp3.playMp3FolderTrack(806);
waitPlaybackToFinish(255, 0, 0, 100);
}
break;
}
mfrc522.PICC_HaltA();
mfrc522.PCD_StopCrypto1();
// restore playback volume, can't be higher than maximum volume
mp3.setVolume(playback.mp3CurrentVolume = min(playback.mp3CurrentVolume, preference.mp3MaxVolume));
switchButtonConfiguration(PAUSE);
shutdownTimer(START);
inputEvent = NOP;
}
// # end - nfc tag does not have our magic cookie on it
// ####################################################
}
// # end - nfc tag is successfully read
// ####################################
}
// # end - main code block
// #######################
// ##################################################################################
// # handle button and ir remote events during playback or while waiting for nfc tags
// ir remote center: toggle box lock
if (inputEvent == IRC) {
if ((playback.isLocked = !playback.isLocked)) {
Serial.println(F("lock"));
#if defined STATUSLED ^ defined STATUSLEDRGB
statusLedUpdate(BURST4, 255, 0, 0, 0);
#endif
}
else {
Serial.println(F("unlock"));
#if defined STATUSLED ^ defined STATUSLEDRGB
statusLedUpdate(BURST8, 0, 255, 0, 0);
#endif
}
}
// button 0 (middle) press or ir remote play/pause: toggle playback
else if ((inputEvent == B0P && !playback.isLocked) || inputEvent == IRP) {
if (playback.isPlaying) {
switchButtonConfiguration(PAUSE);
shutdownTimer(START);
Serial.println(F("pause"));
mp3.pause();
// if the current playback mode is story book mode: store the current progress
if (playback.currentTag.mode == STORYBOOK) {
Serial.print(F("save "));
printModeFolderTrack(true);
EEPROM.update(playback.currentTag.folder, playback.playList[playback.playListItem - 1]);
}
}
else {
if (playback.playListMode) {
switchButtonConfiguration(PLAY);
shutdownTimer(STOP);
Serial.println(F("play"));
mp3.start();
}
}
}
// button 1 (right) press or ir remote up while playing: increase volume
else if (((inputEvent == B1P && !playback.isLocked) || inputEvent == IRU) && playback.isPlaying) {
if (playback.mp3CurrentVolume < preference.mp3MaxVolume) {
mp3.setVolume(++playback.mp3CurrentVolume);
Serial.print(F("volume "));
Serial.println(playback.mp3CurrentVolume);
}
#if defined STATUSLED
else statusLedUpdate(BURST2, 255, 0, 0, 0);
#endif
}
// button 2 (left) press or ir remote down while playing: decrease volume
else if (((inputEvent == B2P && !playback.isLocked) || inputEvent == IRD) && playback.isPlaying) {
if (playback.mp3CurrentVolume > 1) {
mp3.setVolume(--playback.mp3CurrentVolume);
Serial.print(F("volume "));
Serial.println(playback.mp3CurrentVolume);
}
#if defined STATUSLED
else statusLedUpdate(BURST2, 255, 0, 0, 0);
#endif
}
// button 1 (right) hold for 2 sec or button 5 press or ir remote right, only during (v)album, (v)party and story book mode while playing: next track
else if ((((inputEvent == B1H || inputEvent == B4P) && !playback.isLocked) || inputEvent == IRR) && (playback.currentTag.mode == ALBUM || playback.currentTag.mode == PARTY || playback.currentTag.mode == STORYBOOK || playback.currentTag.mode == VALBUM || playback.currentTag.mode == VPARTY) && playback.isPlaying) {
Serial.println(F("next"));
playNextTrack(0, true, true);
}
// button 2 (left) hold for 2 sec or button 4 press or ir remote left, only during (v)album, (v)party and story book mode while playing: previous track
else if ((((inputEvent == B2H || inputEvent == B3P) && !playback.isLocked) || inputEvent == IRL) && (playback.currentTag.mode == ALBUM || playback.currentTag.mode == PARTY || playback.currentTag.mode == STORYBOOK || playback.currentTag.mode == VALBUM || playback.currentTag.mode == VPARTY) && playback.isPlaying) {
Serial.println(F("prev"));
playNextTrack(0, false, true);
}
// button 0 (middle) hold for 5 sec or ir remote menu, only during (v)story, (v)album, (v)party and single mode while playing: toggle single track repeat
else if (((inputEvent == B0H && !playback.isLocked) || inputEvent == IRM) && (playback.currentTag.mode == STORY || playback.currentTag.mode == ALBUM || playback.currentTag.mode == PARTY || playback.currentTag.mode == SINGLE || playback.currentTag.mode == VSTORY || playback.currentTag.mode == VALBUM || playback.currentTag.mode == VPARTY) && playback.isPlaying) {
Serial.print(F("repeat "));
if ((playback.isRepeat = !playback.isRepeat)) {
Serial.println(F("on"));
#if defined STATUSLED ^ defined STATUSLEDRGB
statusLedUpdate(BURST4, 255, 255, 255, 0);
#endif
}
else {