How to sequence two coroutines to make a metronome?

I’m trying to build a simple metronome which will trigger a note on, then a note off message for some audio. I’ve been playing with Coroutines but not had any luck. What I would like to achieve is:

  1. When the user presses play (p), send a note on message (ADSRScript.Plugin_noteON():wink:
  2. Wait 20 seconds, then send a note off message (ADSRScript.Plugin_noteOFF():wink:
  3. Wait 20 seconds after step 2, then send a note on message.
  4. Repeat until the user presses stop (s).

This is what I have so far but it doesn’t work as planned. In the code ‘sixtyBPM’ is a constant WaitForSeconds previously declared.

	// Update is called once per frame
	void Update () {

		if (Input.GetKeyDown(KeyCode.P))
		{
			Debug.Log("P Pressed");
			play = true;
			StartCoroutine (coRoutineON());
			//ADSRScript.Plugin_noteON ();
		}
		else if (Input.GetKeyDown(KeyCode.S))
		{
			Debug.Log("S Pressed");
			play = false;
			ADSRScript.Plugin_noteOFF ();
			StopAllCoroutines ();
		}

	}

	IEnumerator coRoutineON(){
		while (play) {
			Debug.Log ("coroutine ON" + Time.time);
			ADSRScript.Plugin_noteON ();
			yield return sixtyBPM;
			StartCoroutine (coRoutineOFF ());
		}
	}
	IEnumerator coRoutineOFF(){
		while (play) {
			Debug.Log ("coroutine OFF" + Time.time);
			StopCoroutine (coRoutineON ());
			ADSRScript.Plugin_noteOFF ();
			yield return sixtyBPM;
			StartCoroutine (coRoutineON ());
		}
	}
}

The code results in something like this:

Any help would be greatly appreciated! Thanks

Here’s what I’ve come up with. I’ve not tested it, but it at least looks like it should work at first glance.

     void Update () {
         if (Input.GetKeyDown(KeyCode.P))
         {
             Debug.Log("P Pressed");
             play = true;
             StartCoroutine (coRoutineON());
         }
         else if (Input.GetKeyDown(KeyCode.S))
         {
             Debug.Log("S Pressed");
             play = false;
         }
     }
 
     IEnumerator coRoutineON(){
         while (play) {
             Debug.Log ("coroutine ON" + Time.time);
             ADSRScript.Plugin_noteON ();
             yield return sixtyBPM;
             ADSRScript.Plugin_noteOFF ();
             yield return sixtyBPM;
         }

         ADSRScript.Plugin_noteOFF ();
     }