@@ -32,13 +32,16 @@ Version Modified By Date Comments
32
32
0008 S Kanemoto 12/06/22 Fixed for Leonardo by @maris_HY
33
33
0009 J Reucker 15/04/10 Issue #292 Fixed problems with ATmega8 (thanks to Pete62)
34
34
0010 jipp 15/04/13 added additional define check #2923
35
+ 0011 Constant T 29/12/2024 added function melody()
35
36
*************************************************/
36
37
37
38
#include < avr/interrupt.h>
38
39
#include < avr/pgmspace.h>
39
40
#include " Arduino.h"
40
41
#include " pins_arduino.h"
41
42
43
+
44
+
42
45
#if defined(__AVR_ATmega8__) || defined(__AVR_ATmega128__)
43
46
#define TCCR2A TCCR2
44
47
#define TCCR2B TCCR2
@@ -476,7 +479,47 @@ void disableTimer(uint8_t _timer)
476
479
}
477
480
}
478
481
482
+ int melody (int pin, int notes[], int noteSize, int durations[], int durationSize)
483
+ {
484
+ static int currentNoteIndex = 0 ;
485
+ static unsigned long noteStartTime = 0 ;
486
+ static bool isPlaying = false ;
487
+
488
+ while ((noteSize != durationSize) || (noteSize < durationSize) || (noteSize > durationSize))
489
+ {
490
+ return -1 ;
491
+ }
479
492
493
+ if (!isPlaying)
494
+ {
495
+ isPlaying = true ;
496
+ currentNoteIndex = 0 ;
497
+ noteStartTime = millis ();
498
+ tone (pin, notes[currentNoteIndex]);
499
+ }
500
+ else
501
+ {
502
+ unsigned long currentTime = millis ();
503
+ if (currentTime - noteStartTime >= durations[currentNoteIndex])
504
+ {
505
+ noTone (pin);
506
+ currentNoteIndex++;
507
+ if (currentNoteIndex < noteSize)
508
+ {
509
+ tone (pin, notes[currentNoteIndex]);
510
+ noteStartTime = currentTime;
511
+ }
512
+ else
513
+ {
514
+ isPlaying = false ;
515
+ currentNoteIndex = 0 ;
516
+ return 0 ;
517
+ }
518
+ }
519
+ }
520
+
521
+ return 1 ;
522
+ }
480
523
void noTone (uint8_t _pin)
481
524
{
482
525
int8_t _timer = -1 ;
0 commit comments