【问题标题】:Fourth button Binary Conversion Not working第四个按钮二进制转换不起作用
【发布时间】: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 个按钮而不是 100110101011 等值时,它会像 @987654325 @和1004

【问题讨论】:

  • 我没有使用二进制文字,但你使用的值不应该也是二进制的吗? toneTot |= 100; --> toneTot |= 0b100;?我测试得很快,|= 将接受任何整数,而不仅仅是二进制。

标签: c++ arduino binary-operators sparkfun


【解决方案1】:

这里:

  toneTot |= 10;

您没有像预期的那样设置位 1。 10d 与 0b00001010 类似,因此您正在设置 Bit3 和 Bit 1。将其切换为:

toneTot |= 0x02;

或者 toneTot |= 0b00000010;

对于 toneTot 中设置的其他位也有同样的想法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 2020-05-05
    • 2021-06-03
    • 1970-01-01
    • 2016-05-18
    • 2013-06-19
    • 2017-10-21
    相关资源
    最近更新 更多