第四个按钮二进制转换不起作用
Fourth button Binary Conversion Not working
我正在浏览 Sparkfun 的 Inventor's Kit,特别是关于 Digital Trumpet。为了扩展项目,我添加了第四个按钮并尝试将按下的按钮转换为二进制数,以便从 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 个按钮的行为外,这一切都很好。我试过移动按钮、切换引脚等,但它会继续工作,因此当按下第 4 个按钮而不是 1001
、1010
、1011
等值时,结果像 1002
和 1004
这里:
toneTot |= 10;
您没有按预期设置第 1 位。 10d 类似于 0b00001010,因此您正在设置 Bit3 和 Bit 1。将其切换为:
toneTot |= 0x02;
对 tonTot
中设置的另一个位也有同样的想法
我正在浏览 Sparkfun 的 Inventor's Kit,特别是关于 Digital Trumpet。为了扩展项目,我添加了第四个按钮并尝试将按下的按钮转换为二进制数,以便从 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 个按钮的行为外,这一切都很好。我试过移动按钮、切换引脚等,但它会继续工作,因此当按下第 4 个按钮而不是 1001
、1010
、1011
等值时,结果像 1002
和 1004
这里:
toneTot |= 10;
您没有按预期设置第 1 位。 10d 类似于 0b00001010,因此您正在设置 Bit3 和 Bit 1。将其切换为:
toneTot |= 0x02;
对 tonTot