Play a Melody using the tone() function with Arduino

This example shows how to use the tone() command to generate notes. It plays a little melody you may have heard before.

Circuit

Arduino Play a Melody

image developed using Fritzing. For more circuit examples, see the Fritzing project page

Connect one terminal of your speaker to digital pin 8 through a 100 ohm resistor. Connect the other terminal to ground.

Schematic

Arduino Play a Melody Schematic

Code

The code below uses an extra file, pitches.h. This file contains all the pitch values for typical notes. For example, NOTE_C4 is middle C. NOTE_FS4 is F sharp, and so forth. This note table was originally written by Brett Hagman, on whose work the tone() command was based. You may find it useful for whenever you want to make musical notes.

The main sketch is as follows:

/*
Melody

Plays a melody

circuit:
* 8-ohm speaker on digital pin 8

created 21 Jan 2010
modified 30 Aug 2011
by Tom Igoe

This example code is in the public domain.

http://arduino.cc/en/Tutorial/Tone

*/
#include “pitches.h”

// notes in the melody:
int melody[] = {
NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3,0, NOTE_B3, NOTE_C4};

[box color=”#985D00″ bg=”#FFF8CB” font=”verdana” fontsize=”14 ” radius=”20 ” border=”#985D12″ float=”right” head=”Major Components in Project” headbg=”#FFEB70″ headcolor=”#985D00″]

Hardware Required

  • Arduino board
  • 8 ohm small speaker
  • 100 ohm resistor
  • hook-up wire

[/box]

For more detail: Play a Melody using the tone() function with Arduino


About The Author

Ibrar Ayyub

I am an experienced technical writer holding a Master's degree in computer science from BZU Multan, Pakistan University. With a background spanning various industries, particularly in home automation and engineering, I have honed my skills in crafting clear and concise content. Proficient in leveraging infographics and diagrams, I strive to simplify complex concepts for readers. My strength lies in thorough research and presenting information in a structured and logical format.

Follow Us:
LinkedinTwitter

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top