I'm going through the Inventor's Kit from Sparkfun, specifically around the Digital Trumpet. To expand on the project I'm adding a fourth button and trying to turn the buttons pressed into a binary number to give myself 16 notes from 4 buttons. Here's my code:
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));
}
In general this has worked perfectly fine, except for the behavior of the 4th button. I've tried moving buttons around, switching pins, etc, but it keeps on working so that when a 4th button is pressed instead of values like 1001
, 1010
, 1011
, etc, it comes out like 1002
and 1004
Here:
toneTot |= 10;
you are writing 10 decimal to toneTot
which means you are not only setting bit 1, as you expected. 10d is similar to 0b00001010, so you are setting bit 3 and bit 1. Switch it to:
toneTot |= 0x02;
or
toneTot |= 0b00000010;
to only set bit 1.
Same think for the other bits set in toneTot
.