From 3febd09b8679d2f5f187a5a4c35bf520f8a6bd9c Mon Sep 17 00:00:00 2001
From: Hasin Israk Toaha <128958545+toaha63@users.noreply.github.com>
Date: Mon, 30 Dec 2024 13:46:42 +0600
Subject: [PATCH] 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
---
 cores/arduino/Tone.cpp | 43 ++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 43 insertions(+)

diff --git a/cores/arduino/Tone.cpp b/cores/arduino/Tone.cpp
index 1bfb3e379..52fec323a 100644
--- a/cores/arduino/Tone.cpp
+++ b/cores/arduino/Tone.cpp
@@ -32,6 +32,7 @@ Version Modified By Date     Comments
 0008    S Kanemoto  12/06/22 Fixed for Leonardo by @maris_HY
 0009    J Reucker   15/04/10 Issue #292 Fixed problems with ATmega8 (thanks to Pete62)
 0010    jipp        15/04/13 added additional define check #2923
+0011    Constant T  29/12/2024 added function melody()
 *************************************************/
 
 #include <avr/interrupt.h>
@@ -39,6 +40,8 @@ Version Modified By Date     Comments
 #include "Arduino.h"
 #include "pins_arduino.h"
 
+
+
 #if defined(__AVR_ATmega8__) || defined(__AVR_ATmega128__)
 #define TCCR2A TCCR2
 #define TCCR2B TCCR2
@@ -476,7 +479,47 @@ void disableTimer(uint8_t _timer)
   }
 }
 
+int melody(int pin, int notes[], int noteSize, int durations[], int durationSize)
+{
+    static int currentNoteIndex = 0;
+    static unsigned long noteStartTime = 0;
+    static bool isPlaying = false;
+
+    while((noteSize != durationSize) || (noteSize < durationSize) || (noteSize > durationSize))
+    {
+        return -1;
+    }
 
+    if (!isPlaying)
+    {
+        isPlaying = true;
+        currentNoteIndex = 0;
+        noteStartTime = millis();
+        tone(pin, notes[currentNoteIndex]);
+    }
+    else
+    {
+        unsigned long currentTime = millis();
+        if (currentTime - noteStartTime >= durations[currentNoteIndex])
+        {
+            noTone(pin);
+            currentNoteIndex++;
+            if (currentNoteIndex < noteSize)
+            {
+                tone(pin, notes[currentNoteIndex]);
+                noteStartTime = currentTime;
+            }
+            else
+            {
+                isPlaying = false;
+                currentNoteIndex = 0; 
+                return 0;
+            }
+        }
+    }
+
+    return 1;
+}
 void noTone(uint8_t _pin)
 {
   int8_t _timer = -1;