Music with piezoelectric component
So far, we have controlled light, motion and electrons. Now let's turn on the sound. But sound is a similar phenomenon, how does our digital Arduino do it?
We will once again extract some of the incredible speed that makes it mimic analogue behaviour. To do this, we will connect the piezo component to one of the Arduino digital ports. The piezocomponent makes a sound click each time a current pulse is received. If we work at the desired frequency (for example, 440 times per second to create a do diese note), these clicks will work together to create notes.
COMPONENTS
- Piezocomponent.
- Connecting wire.
CIRCUIT DIAGRAM
CIRCUIT INSTALLATION
CODE
You can find this code in CIRC-06-code-beep.js.
var five = require("johnny-five");
five.Board().on("ready", function() {
var val = 0;
var piezoPin = 9;
// Mettre le port 9 en mode PWM (modulation de largeur d'impulsion)
this.pinMode(piezoPin, 3);
// bip continu
this.loop(200, function(){
if (val){
this.analogWrite(piezoPin, 20);
} else {
this.analogWrite(piezoPin, 0);
}
val = val ? 0 : 1;
});
});
Note: At the time of this writing, the Piezo object is disabled in Johnny-Five - we will also produce a PR signal directly to the port using board.analogWrite (9, value).
EMERGENCY REPAIR
No sound
Given the size and shape of the piezocomponent, it is easy to miss the corresponding holes on the prototyping card. Check its location.
I can't think when the notes are playing
Simply remove the piezocomponent while you think, run the program and try again. (This is a joke, NdT).
CODE EXTENSION
Look at piezo.js in the Johnny Five library directory for an example of how to write functions that work with key and duration, rather than communicating directly with material.
Common Creative license. Translation of the .fr textbook by Anna Gerber into English under the same license. Copying and modification is permitted provided that this notice, including the link on the original page, is retained.