gpt4 book ai didi

c++ - 使用按钮为C++创建计数器

转载 作者:行者123 更新时间:2023-12-02 10:05:50 24 4
gpt4 key购买 nike

我试图将按钮按下计数器与我的氩气设备放在一起。我有几种声音要在它们之间交替,但无法获得用于改变歌曲A和B的计数器。我想将歌曲A设置为反偶数,将歌曲B设置为反偶数。我目前所剩无几,也不知道该从哪里去。不知道如何上传我当前的内容。

int button = A0;

int buzzer = A2;

// Defining Sound
int sound1[] = {1700,2500,2800,2000,2500,1500,2000,1800};

int sound2[] = {3800,3600,3400,3200,2400,2600,2800,3000};

//Defining Duration Of Notes

int Duration1[] = {4,2,4,2,4,2,4,2};

int Duration2[] = {2,4,2,4,2,2,4,2};

//Setting Button Count
int bcount = 0;
#define MAX 2

//Creates The Setup Of Code
void setup()
{
//Creates The Input Of Button Being Pressed
pinMode (button, INPUT);
//Creates The Output Of The Buzzer
pinMode (buzzer, OUTPUT);
}

void loop() {
//When Button Is Pressed
if (digitalRead(button) == 1) {
bcount = bcount + 1;
}
else if
(bcount = 0);
for (int i = 0; i < bcount; i++) {
digitalWrite(buzzer, 1);

if (bcount == MAX) {
bcount = 0;
break;
}
//Reads Notes
for (int Note = 0; Note < 8; Note++){
//Note Duration
int Duration = 1000/Duration1[Note];
//Sends Notes To Speaker
tone(buzzer, sound1[Note], Duration);
//Sets Delay Between Notes
int pauseBetweenNotes = Duration * 1.50;
//Delay Itself
delay(pauseBetweenNotes);
//Stop To The Sound
noTone(buzzer);
}
}
//When Button Is Pressed 2nd Time
if(digitalRead(button) == 2) {
//Reads Notes
for (int Note = 0; Note < 8; Note++){
//Note Duration
int Duration = 1000/Duration2[Note];
//Sends Notes To Speaker
tone(buzzer, sound2[Note], Duration);
//Sets Delay Between Notes
int pauseBetweenNotes = Duration * 1.50;
//Delay Itself
delay(pauseBetweenNotes);
//Stop To The Sound
noTone(buzzer);
}
}
}

最佳答案

试试这个:

int counter = 0;
void loop() {
if (digitalRead(button) == HIGH) {
counter = counter + 1;
if (counter % 2 == 1) {
// ... place your code for sound#1 here.
} else {
// ... place your code for sound#2 here.
}
}
}

这里发生的事情是:每次按下按钮,我们都会增加一个计数器。如果按下按钮的次数为奇数,则播放第一个声音,如果为偶数,则播放第二个声音。

将计数器存储在循环函数外部很重要,这样它就不会在循环调用之间丢失其值。

另外,请注意,如果按下按钮,digitalRead会返回HIGH,否则会返回LOW。数不清的打印机您都必须自己动手。

https://docs.particle.io/reference/device-os/firmware/argon/#digitalread-

关于c++ - 使用按钮为C++创建计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60242920/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com