homework for week 4: Little Piano

This is a little piano with 3 keys — red stands for C, green stands for E, and blue stands for G. Control the knock strength to change the key.

2014-09-26 08.45.04-1 拷貝

 

HW2_piano_bb

int sensorPin = 0;
int ledPinC = 2;
int ledPinE = 3;
int ledPinG = 4;
int threshold = 100;
int keyboard;

int speaker = 12;
int sensorValue = 0;

void setup() {
Serial.begin(9600);
pinMode(ledPinC, OUTPUT);
pinMode(ledPinE, OUTPUT);
pinMode(ledPinG, OUTPUT);
pinMode(speaker, OUTPUT);
}

void loop() {
int val = analogRead(sensorPin);

if (val >= threshold) {
sensorValue = map(val, 180, 400, 100, 500);

if(sensorValue >= 100 && sensorValue < 200) {
keyboard = 131;
tone(speaker, keyboard);
digitalWrite(ledPinC, HIGH);
delay(100);
digitalWrite(ledPinC, LOW);
noTone(speaker);
}
else if(sensorValue >= 200 && sensorValue < 300) {
keyboard = 330;
tone(speaker, keyboard);
digitalWrite(ledPinE, HIGH);
delay(100);
digitalWrite(ledPinE, LOW);
noTone(speaker);
}
else if(sensorValue >= 300 && sensorValue < 400) {
keyboard = 784;
tone(speaker, keyboard);
digitalWrite(ledPinG, HIGH);
delay(100);
digitalWrite(ledPinG, LOW);
noTone(speaker);
}
Serial.println(keyboard);
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *