a potentiometer to port A0
a speaker to port 2
the circuit
#include "pitches.h"
int speakerPin = 2;
int notes[] = {
0, NOTE_AS1,NOTE_A2,NOTE_GS3,NOTE_G4,NOTE_FS5,NOTE_F6,NOTE_E7,NOTE_DS8
};
void setup() {
pinMode(A0,INPUT);
pinMode(speakerPin,OUTPUT);
}
void loop() {
int sensor = analogRead(A0);
int S = map(sensor,0,1023,0,9);
int P = notes[S];
tone(speakerPin,P,100);
}
------------------------------
how to use this project:download the following code, then do the circuit and use the project!
------------------------------
the explanation for the code: #include "pitches.h"
"pitches.h" is a C Header file, it should be in the same folder with the project.
int notes[] = {
0, NOTE_AS1,NOTE_A2,NOTE_GS3,NOTE_G4,NOTE_FS5,NOTE_F6,NOTE_E7,NOTE_DS8
};
"notes[]" is an array that contains the notes to be played.
int sensor = analogRead(A0);
"sensor" is an integer contains the reading of the sensor.
int S = map(sensor,0,1023,0,9);
"S" is an integer contains "map()" function to make fewer cases for sensor reading.
int P = notes[S];
"p" is an integers shows which note should be played.
tone(speakerPin,P,100);
play the tone "int P" repeatedly.
Comments
Please log in or sign up to comment.