Skip to content

Commit 3febd09

Browse files
authored
Update Tone.cpp
Added a new function named melody() so that user can play melody tone by passing pin number,an array of notes and an array of duration in ms
1 parent c8c514c commit 3febd09

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Diff for: cores/arduino/Tone.cpp

+43
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,16 @@ Version Modified By Date Comments
3232
0008 S Kanemoto 12/06/22 Fixed for Leonardo by @maris_HY
3333
0009 J Reucker 15/04/10 Issue #292 Fixed problems with ATmega8 (thanks to Pete62)
3434
0010 jipp 15/04/13 added additional define check #2923
35+
0011 Constant T 29/12/2024 added function melody()
3536
*************************************************/
3637

3738
#include <avr/interrupt.h>
3839
#include <avr/pgmspace.h>
3940
#include "Arduino.h"
4041
#include "pins_arduino.h"
4142

43+
44+
4245
#if defined(__AVR_ATmega8__) || defined(__AVR_ATmega128__)
4346
#define TCCR2A TCCR2
4447
#define TCCR2B TCCR2
@@ -476,7 +479,47 @@ void disableTimer(uint8_t _timer)
476479
}
477480
}
478481

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+
}
479492

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+
}
480523
void noTone(uint8_t _pin)
481524
{
482525
int8_t _timer = -1;

0 commit comments

Comments
 (0)