PhotoresistorControlsTempoNicolasPdf.ino
Aller à la navigation
Aller à la recherche
/* sources: Sparkfun's Inventor's Guide on Arduino * CIRC06 et CIRC09 * un programme qui fait varier la restitution d'une mélodie * en fonction de l'intensité d'une lumière captée par une résistance photosensible * remière esquisse de @nicolasszilas * Avril 2012 * commentaires en français * le 15 avril 2012 * @atelierpdf.com */ // la fiche de la résistance photosensible int lightPin = 0; // cette fiche analogique n'est pas calibrée // elle ne retourne que des valeurs relatives // fiche de la DEL int ledPin = 9; // en utilisant la fiche 9 on exploite la (pulse width // modulation) permettant des transitions de valeur // la fiche du piézo/haut parleur int speakerPin = 11; // pour la sortie son int length = 15; // nombre de notes // notation anglaise (l'espace correspond à un silence) de ah vous dirai-je Maman? char notes[] = "ccggaagffeeddc "; int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 }; int tempo = 100; void setup() { Serial.begin( 9600 ); pinMode(ledPin, OUTPUT); // mise ne place des sorties pinMode(speakerPin, OUTPUT); } void loop() { // variante sans la fonction getLightLevel() // int lightLevel = analogRead(lightPin); //Read the // // lightlevel // // Serial.println( lightLevel ); // // // lightLevel = map(lightLevel, 0, 900, 0, 2000); // //adjust the value 0 to 900 to // //span 0 to 255 // lightLevel = constrain(lightLevel, 0, 255);//make sure the // //value is betwween // //0 and 255 // Serial.println( lightLevel ); // analogWrite(ledPin, lightLevel); //write the value // // tempo = lightLevel; int lightLevel = getLightLevel(); analogWrite(ledPin, lightLevel); //write the value //tempo = lightLevel; // son: for (int i = 0; i < length; i++) { tempo = getLightLevel(); if (notes[i] == ' ') { delay(beats[i] * tempo); // rest } else { playNote(notes[i], beats[i] * tempo); } // l'intervalle entre les notes delay(tempo / 8); } } // fonction pour chaque son void playTone(int tone, int duration) { for (long i = 0; i < duration * 1000L; i += tone * 2) { digitalWrite(speakerPin, HIGH); delayMicroseconds(tone); digitalWrite(speakerPin, LOW); delayMicroseconds(tone); } } // fonction captant le niveau de luminosité int getLightLevel() { int lightLevel = analogRead(lightPin); Serial.println(lightLevel); // affichage du niveau brut lightLevel = map(lightLevel, 0, 900, 0, 2000); // normalisation des valeurs de 0 to 900 sur 0 à 255 lightLevel = constrain(lightLevel, 0, 255); // fitre supplémentaire pour contraindre les limites Serial.println( lightLevel ); // affichage de la nouvelle valeur return lightLevel; } // fonction pour la mélodie void playNote(char note, int duration) { char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' }; int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 }; // play the tone corresponding to the note name for (int i = 0; i < 8; i++) { if (names[i] == note) { playTone(tones[i], duration); } } }