Below the code is an example plot for the photoresistor sensor readout.
-----------------------------------------------------------------------------
int speakerPin = 9;
int sensorValue = 0; // value read from the pot
int outputValue = 0; // value output to the PWM (analog out)
int switchValue = 0; // switch to turn on or off the sound
const int analogInPin = 1; // Analog input pin that the potentiometer is attached to
const int digitalInPin = 22;// Digital input pin that the switch is connected to
int length = 15; // the number of notes
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
pinMode(speakerPin, OUTPUT);
}
void playTone(int tone) {
for (long i = 0; i < 1;) {
digitalWrite(speakerPin, HIGH);
delayMicroseconds(tone);
digitalWrite(speakerPin, LOW);
delayMicroseconds(tone);
if (digitalRead(digitalInPin) == 1){
i=1;
}
}
}
void playNote(char note) {
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]);
}
}
}
void loop() {
for (int i = 0; i < length; i++) {
sensorValue = analogRead(analogInPin);
// map it to the range of the analog out:
char note;
if (sensorValue < 600) {
note = 'C';
}
else if (sensorValue >=600 & sensorValue < 638) {
note = 'C';
}
else if (sensorValue >=638 & sensorValue < 676) {
note = 'b';
}
else if (sensorValue >=676 & sensorValue < 714) {
note = 'a';
}
else if (sensorValue >=714 & sensorValue < 752) {
note = 'g';
}
else if (sensorValue >=752 & sensorValue < 790) {
note = 'f';
}
else if (sensorValue >=790 & sensorValue < 828) {
note = 'e';
}
else if (sensorValue >=828 & sensorValue < 866) {
note = 'd';
}
else if (sensorValue >=866 & sensorValue < 900) {
note = 'c';
}
else if (sensorValue > 900) {
note = 'c';
}
if(digitalRead(digitalInPin) == 0) {
playNote(note);
}
Serial.print("sensor = " );
Serial.print(sensorValue);
Serial.print("\t output = ");
Serial.print(note);
Serial.print("\t switch = ");
Serial.println(digitalRead(digitalInPin));
}
}
-----------------------------------------------------------------------------
No comments:
Post a Comment