Making Sound In Arduino

Introduction

In this article, I'm going to explain about making sound in the Arduino, using the push button.
 
Parts Of Lists
  • Arduino Uno
  • Push Button
  • Buzzer
  • Bread Board
  • Hookup Wire. 
Connection
  • Push Button To Board:
  • Connect the 1st pin of the VCC of 5v to the Arduino Board
  • Connect the 2nd pin to the Gnd and any digital pin of the input side to the Board.
Buzzer to Board
  • Connect one side of the wire to the VCC
  • Connect the another side of the wire to the Gnd. 
Programming
  1. #include "pitches.h"  
  2. const int buttonPin = 2; // the number of the pushbutton pin    
  3. int note1 = NOTE_C4; // define note sound    
  4. // variables will change:    
  5. int buttonState = 0; // variable for reading the pushbutton status    
  6. void setup() {  
  7.     // initialize the pushbutton pin as an input:    
  8.     pinMode(buttonPin, INPUT);  
  9. }  
  10. void loop() {  
  11.     // read the state of the pushbutton value:    
  12.     buttonState = digitalRead(buttonPin);  
  13.     // check if the pushbutton is pressed.    
  14.     // if it is, the buttonState is HIGH:    
  15.     if (buttonState == HIGH) {  
  16.         // sound tone    
  17.         tone(8, note1);  
  18.     } else {  
  19.         //turn off sound    
  20.         noTone(8);  
  21.     }  
  22. }  
That's it. Now, when the button is pressed, it will automatically produce the sound.