tone() is generating weird noises, not doing what told

Hey guys,

I'm programming a keyboard for a little school project. I've decided to use an arduino mega2560.
The pins 22-40 are being used as digital inputs from buttons under the keys.
Pin 10 is the speaker.
I have tried using an mp3 shield, but my lack of knowledge combined with the time limit is not allowing that.
I've settled for the simple tone() & noTone()

Problem is, I am getting only 1 frequency, no matter which button I press, it also seems to be a totally wrong frequency (e.g. I input 40Hz, it gives me 7000Hz). I've had no luck so far, any suggestions?


int speakerPin = 10;
int buttonPin1 = 22;
int buttonPin2 = 23;
int buttonPin3 = 24;
int buttonPin4 = 25;
int buttonPin5 = 26;
int buttonPin6 = 27;
int buttonPin7 = 30;
int buttonPin8 = 31;

#include "pitches.h";

void setup() {
  pinMode(buttonPin1, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
  pinMode(buttonPin3, INPUT_PULLUP);
  pinMode(buttonPin4, INPUT_PULLUP);
  pinMode(speakerPin, OUTPUT);  


void loop() {
  int val1 = digitalRead(buttonPin1);
  if (val1 == 0){
    tone(speakerPin, 1);
  else {

  int val2 = digitalRead(buttonPin2);

  if (val2 == 0){
    tone(speakerPin, 75000);
  else {

  int val3 = digitalRead(buttonPin3);

  if (val3 == 0){
    tone(speakerPin, NOTE_E2);
  else {

  int val4 = digitalRead(buttonPin4);

  if (val4 == 0){
    tone(speakerPin, NOTE_F2);
  else {


That string of ifs isn't going to work. You press buttonPin3 and it plays a tone, then instantly moves on to the next if, sees buttonPin4 isn't pressed so switches the tone back off etc. What you need is for tone to switch off only if NONE of the buttons are being pressed.

It's possible that switch/case may be useful here.


Yup, that solved it, many thanks!