Play Sound tone using Arduino and NodeJS

Play Sound tone using Arduino and NodeJS

In this tutorial, I will show you how to play sound tone using Arduino and NodeJS. This post will be part of the tutorial series on Javascript in Embedded electronics. I hope you enjoyed the last post on blink led using arduino and NodeJS.

With the tremedous rise of javascript and nodejs, it wasn’t a surprise seeing it heading into the world of electronics and IOT.

Lets make sure you have got all we need to accomplish this task:

  • Arduino board (I am making use of Arduino Mega but Uno will still serve)
  • Arduino IDE (You can download it here if you have not)
  • Push button
  • Piezo-buzzer
  • NodeJS (You can download yours from here)
  • Johnny-five (a JavaScript Robotics programming framework. Johnny-Five is open source and has growing developer communities. It can be install using the npm package manager)

 

Setting up the Arduino Board

  • Open your Arduino IDE, click on file ->  examples -> firmata -> StandardFirmata, then compile and upload.
  • Close the IDE except if you are using it for another thing. The board is ready.
  • You can also refer to the last post about these steps

 

Circuit diagram

 

Setting up the JavaScript file

  • From the folder of your choice, create a new folder and cd into the folder and install johnny-five framework:
npm install johnny-five

 

  • create a javascript file named btn1.js (you can named yours what you want). Paste this code inside the file:
var fiveLib = require("johnny-five");
var megaboard = new fiveLib.Board();

megaboard.on("ready", function() {

  // Create a new `button` hardware instance.
  var btn = new fiveLib.Button(2);
  var piezo = new fiveLib.Piezo(3);

  btn.on("hold", function() {
    console.log( "Button held" );
  });

  btn.on("press", function() {
    console.log( "Button pressed" );

    // Plays a song
    piezo.play({
    // song is composed by an array of pairs of notes and beats
    // The first argument is the note (null means "no note")
    // The second argument is the length of time (beat) of the note (or non-note)
    song: [
      ["C4", 1 / 4],
      ["D4", 1 / 4],
      ["F4", 1 / 4],
      ["D4", 1 / 4],
      ["A4", 1 / 4],
      [null, 1 / 4],
      ["A4", 1],
      ["G4", 1],
      [null, 1 / 2],
      ["C4", 1 / 4],
      ["D4", 1 / 4],
      ["F4", 1 / 4],
      ["D4", 1 / 4],
      ["G4", 1 / 4],
      [null, 1 / 4],
      ["G4", 1],
      ["F4", 1],
      [null, 1 / 2]
    ],
    tempo: 100
  });



  });

  btn.on("release", function() {
    console.log( "Button released" );
  });
});

 

Run the code with this command (i.e. from your project folder):

node btn1.js

 

console output
console output

 

 

Feel free to add your comments above this post and stay in-touch for the next post in this series.

Leave a Reply

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