我有一段完整的旋律。如果我按下按钮,它将播放整首歌曲,但是如果我在delay
之后稍作休息,则只需重置i
。我如何才能使它仅在再次按下按钮后才能继续? (对于这个抱歉,我还是个新手,在此先感谢)
int buttonPin = 12;
void setup()
{
// put your setup code here, to run once:
pinMode(buttonPin, INPUT);
}
void loop()
{
// put your main code here, to run repeatedly:
int buttonState = digitalRead(buttonPin);
for(int i = 0; i < sizeof(mariomelody); i++)
{
if(buttonState == HIGH)
{
tone(8, mariomelody[i], 70);
delay();
}
}
}
答案 0 :(得分:2)
在仍然按住按钮的同时停止循环:
int buttonPin = 12;
void setup()
{
// put your setup code here, to run once:
pinMode(buttonPin, INPUT);
}
void loop()
{
// put your main code here, to run repeatedly:
int buttonState = digitalRead(buttonPin);
for(int i = 0; i < sizeof(mariomelody); i++)
{
if(buttonState == HIGH)
{
tone(8, mariomelody[i], 70);
delay();
}
while(digitalRead(buttonPin) == HIGH)
{
// wait until the button is released
}
while(digitalRead(buttonPin) == LOW)
{
//wait until the button is pressed again
}
}
}
答案 1 :(得分:1)
我猜您想在按下按钮时播放旋律,并在释放按钮时停止播放。
然后将是这样:
int i = 0;
void loop()
{
if(digitalRead(buttonPin) == HIGH)
{
tone(8, mariomelody[i], 70);
i = (i + 1) % sizeof(mariomelody);
delay();
}
}
为避免将位置重置为旋律的开始,您需要i
作为全局变量。
如果您希望按钮打开和关闭旋律,则需要另一个全局变量playing
:
bool playing = false;
void loop()
{
if(digitalRead(buttonPin) == HIGH)
{
playing = !playing;
while (digitalRead(buttonPin) == HIGH)
; //wait for release
}
if (playing) {
//the rest is the same
}
}