#define Button 0
#define LED 2
#define Microphone 15
#define ECHO_PIN 14
#define TRIG_PIN 12
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
delay(1000);
pinMode(Button, INPUT_PULLUP);
pinMode(LED, OUTPUT);
pinMode(Microphone, INPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
int lastState = HIGH;
int lastState2 = LOW;
bool isSpeaking = false;
int iniSample = 2048; //Microphone's flag
int cnt = 0;
void loop() {
// put your main code here, to run repeatedly:
button();
microphone();
distance();
}
void button(){
int value = digitalRead((Button));
if (lastState != value) {
lastState = value;
if (value == HIGH) {
cnt++;
Serial.println(" released");
//Serial.println(cnt%4);
}
if (value == LOW) {
cnt++;
Serial.println(" pressed");
//Serial.println(cnt%4);
}
}
led();
}
void microphone(){
int sample = analogRead(Microphone);
int delta = abs(sample - iniSample);
//Serial.println(delta);
if (delta > 50 && isSpeaking == false) {
cnt++;
Serial.println(" start speaking");
isSpeaking = true;
}
if (delta < 10 && isSpeaking == true) { //说话结束
cnt++;
isSpeaking = false;
Serial.println( "end speaking");
}
led();
//delay(1000);
}
void led(){
if (cnt%6 == 1){
analogWrite(LED, 64);
//Serial.println("On");
delay(500);
}
if (cnt%6 ==3){
analogWrite(LED, 1023);
delay(500);
}
if (cnt%6 == 5){
analogWrite(LED, 0);
delay(500);
}
}
float readDistanceCM() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int duration = pulseIn(ECHO_PIN, HIGH);
return duration * 0.034 / 2;
}
void distance(){
float distance = readDistanceCM();
int State = LOW;
if (distance < 100){
State = HIGH;
}
if (lastState2 == LOW && State == HIGH){
cnt++;
Serial.println(" near");
}
if (lastState2 == HIGH && State == LOW){
cnt++;
Serial.println(" far");
}
lastState2 = State;
led();
}