【发布时间】:2023-02-09 15:17:22
【问题描述】:
我正在浏览 Sparkfun 的 Inventor's Kit,特别是围绕数字小号。为了扩展项目,我添加了第四个按钮并尝试将按下的按钮转换为二进制数,以便从 4 个按钮中给自己 16 个音符。这是我的代码:
using namespace std;
//set the pins for the button and buzzer
int firstKeyPin = 2;
int secondKeyPin = 3;
int thirdKeyPin = 4;
int fourthKeyPin = 7;
int buzzerPin = 10;
void setup() {
Serial.begin(9600); //start a serial connection with the computer
//set the button pins as inputs
pinMode(firstKeyPin, INPUT_PULLUP);
pinMode(secondKeyPin, INPUT_PULLUP);
pinMode(thirdKeyPin, INPUT_PULLUP);
pinMode(fourthKeyPin, INPUT_PULLUP);
//set the buzzer pin as an output
pinMode(buzzerPin, OUTPUT);
}
void loop() {
auto toneTot = 0b0;
if (digitalRead(firstKeyPin) == LOW) {
tone(buzzerPin, 262); //play the frequency for c
toneTot |= 1;
}
if (digitalRead(secondKeyPin) == LOW) {
tone(buzzerPin, 330); //play the frequency for e
toneTot |= 10;
}
if (digitalRead(thirdKeyPin) == LOW) { //if the third key is pressed
tone(buzzerPin, 392); //play the frequency for g
toneTot |= 100;
}
if (digitalRead(fourthKeyPin) == LOW) { //if the fourth key is pressed
tone(buzzerPin, 494);
toneTot |= 1000;
}
Serial.println("Binary collected");
Serial.println(String(toneTot));
}
总的来说,除了第四个按钮的行为外,这工作得很好。我试过移动按钮、切换引脚等,但它会继续工作,因此当按下第 4 个按钮而不是 1001、1010、1011 等值时,它会像 @987654325 @和1004
【问题讨论】:
-
我没有使用二进制文字,但你使用的值不应该也是二进制的吗?
toneTot |= 100;-->toneTot |= 0b100;?我测试得很快,|=将接受任何整数,而不仅仅是二进制。
标签: c++ arduino binary-operators sparkfun