我預期是用超音波感測,剛開始狀態是呼吸燈,當感應到有東西靠近時,可以撥放聲音跟led燈閃爍,但不知道為什麼一直卡再無法閃爍,但是燈有量的狀態下,小弟目前剛學而已,不是非常懂哪裡出了錯誤,想請教各為大神幫忙一下,不好意思
#include "D:/pitches.h"
const int trig = 13;
const int echo = 12;
const int inter_time = 20;
int time = 0;
int brightness = 0;
int fadeAmount = 5;
int delayDuration = 30;
int ledPin1 = 3;
int ledPin2 = 4;
int ledPin3 = 6;
int ledState = LOW;
long previousTime = 1;
long interval = 3000;
int melody[] = {
NOTE_G4, NOTE_G4 ,NOTE_E5, NOTE_D5, NOTE_C5, NOTE_G4,
NOTE_G4, NOTE_G4, NOTE_E5, NOTE_D5, NOTE_C5, NOTE_A4,
NOTE_A4, NOTE_A4, NOTE_F5, NOTE_E5, NOTE_D5, NOTE_A4,
NOTE_G5, NOTE_G5, NOTE_F5, NOTE_D5, NOTE_E5, NOTE_C5,
NOTE_G4, NOTE_G4, NOTE_E5, NOTE_D5, NOTE_C5, NOTE_G4,
NOTE_G4, NOTE_G4, NOTE_E5, NOTE_D5, NOTE_C5, NOTE_A4,
NOTE_A4, NOTE_F5, NOTE_E5, NOTE_D5, NOTE_G5, NOTE_G5, NOTE_G5, NOTE_G5,
NOTE_A5, NOTE_G5, NOTE_F5, NOTE_D5, NOTE_C5,
NOTE_E5, NOTE_E5, NOTE_E5, NOTE_E5, NOTE_E5, NOTE_E5,
NOTE_E5, NOTE_G5, NOTE_C5, NOTE_D5, NOTE_E5,
NOTE_F5, NOTE_F5, NOTE_F5, NOTE_F5, NOTE_E5, NOTE_E5, NOTE_E5, NOTE_E5,
NOTE_E5, NOTE_D5, NOTE_D5, NOTE_C5, NOTE_D5, NOTE_G5,
NOTE_E5, NOTE_E5, NOTE_E5, NOTE_E5, NOTE_E5, NOTE_E5,
NOTE_E5, NOTE_G5, NOTE_C5, NOTE_D5, NOTE_E5,
NOTE_F5, NOTE_F5, NOTE_F5, NOTE_F5, NOTE_E5, NOTE_E5, NOTE_E5, NOTE_E5,
NOTE_G5, NOTE_G5, NOTE_F5, NOTE_D5, NOTE_C5};
int duration[] = {
125,125,125,125,125,250,
125,125,125,125,125,250,
125,125,125,125,125,250,
125,125,125,125,125,750,
125,125,125,125,125,250,
125,125,125,125,125,250,
125,125,125,125,125,125,125,125,
125,125,125,125,250,
125,125,250,125,125,250,
125,125,125,125,250,
125,125,125,125,125,125,125,125,
125,125,125,125,250,250,
125,125,250,125,125,250,
125,125,125,125,250,
125,125,125,125,125,250,250,250,
125,125,125,125,500};
void setup() {
Serial.begin(9600);
pinMode (trig, OUTPUT);
pinMode (echo, INPUT);
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
}
void loop() {
float duration, distance;
digitalWrite(trig, HIGH);
delayMicroseconds(1000);
digitalWrite(trig, LOW);
duration = pulseIn (echo, HIGH);
distance = (duration/2)/29;
Serial.print("Data:");
Serial.print (time/30);
Serial.print(", d = ");
Serial.print(distance);
Serial.println(" cm");
time = time + inter_time;
delay(inter_time);
unsigned long currentTime = millis();
while(distance>0)
{
if(distance>=100)
{
digitalWrite(7,LOW);
analogWrite(3, brightness);
analogWrite(4, brightness);
analogWrite(6, brightness);
brightness = brightness + fadeAmount;
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount ;
}
delay(delayDuration);
break;
} else {
digitalWrite(7, HIGH);
for (int thisNote = 0; thisNote < 98; thisNote++) {
tone(8, melody[thisNote], 250);
delay(duration);
}
if(currentTime - previousTime > interval){
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(ledPin1, ledState);
digitalWrite(ledPin2, ledState);
digitalWrite(ledPin3, ledState);
previousTime = currentTime;
}
break;
}
}
} |