Finalement, j'ai un petit problème avec NodeJS.
J'ai branché un buzzer passif sur mon RPi Zero. J'arrive à le faire siffloter un morceau mais je suis persuadé que ce que j'ai écrit pourrait être plus propre, plus concis ... mieux, quoi !
Code : Tout sélectionner
var Gpio = require('pigpio').Gpio;
var buzz = new Gpio(21, {mode: Gpio.OUTPUT});
var button = new Gpio(7, {mode: Gpio.PUD_DOWN}); //use GPIO pin 7 as input for button
const delay = require('delay');
//FREQUENCIES
const cL=129;
const cLS=139;
const dL=146;
const dLS=156;
const eL=163;
const fL=173;
const fLS=185;
const gL=194;
const gLS=207;
const aL=219;
const aLS=228;
const bL=232;
const c=261;
const cS=277;
const d=294;
const dS=311;
const e=329;
const f=349;
const fS=370;
const g=391;
const gS=415;
const a=440;
const aS=455;
const b=466;
const cH=523;
const cHS=554;
const dH=587;
const dHS=622;
const eH=659;
const fH=698;
const fHS=740;
const gH=784;
const gHS=830;
const aH=880;
const aHS=910;
const bH=933;
const sleep = (milliseconds) => {
return new Promise(resolve => setTimeout(resolve, milliseconds))
}
function PlayNote(freq, duree)
{
buzz.pwmFrequency(freq);
const Sing = async () => {
await sleep(duree);
buzz.pwmWrite(200);
await sleep(duree);
buzz.pwmWrite(0);
}
Sing();
const Silence = async () => {
await sleep(200);
buzz.pwmWrite(0);
}
Silence();
}
console.log("Appuyez sur le bouton quand vous voulez.");
console.log("Ctrl+C pour sortir.");
async function loop()
{
while(true)
{
etat = button.digitalRead();
if ( etat == 1 )
{
PlayNote(a, 500); await delay(500);
PlayNote(a, 500); await delay(500);
PlayNote(f, 350); await delay(350);
PlayNote(cH, 150); await delay(150);
PlayNote( a, 500); await delay(500);
PlayNote( f, 350); await delay(350);
PlayNote( cH, 150); await delay(150);
PlayNote( a, 1000); await delay(1000);
PlayNote( eH, 500); await delay(500);
/* etc etc ... */
}
await delay(50);
}
}
loop();
Rien de bien transcendant, j'en suis sûr mais j'ai du mal à comprendre le fonctionnement des "await" ...
Les versions de NodeJS et npm (si ça peut être utile) :
Code : Tout sélectionner
pi@raspberrypi:~ $ node -v
v11.15.0
pi@raspberrypi:~ $ npm -v
6.14.4