D12的電阻是為了解決喇叭爆音的問題
#include <Ultrasonic.h>
#define TRIGGER_PIN 9
#define ECHO_PIN 8
Ultrasonic ultrasonic(TRIGGER_PIN, ECHO_PIN);
float cmMsec, inMsec;
long microsec;
#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"
DFRobotDFPlayerMini myDFPlayer;
SoftwareSerial mySoftwareSerial(11, 12); // RX, TX
int seq[] = {1,2,3,22};
const int interruptNumber = 0; // Interrupt 0 在 pin 2 上
const int buttonPin = 2; // 按鈕(pushbutton)
volatile int buttonState; // 用來儲存按鈕狀態
boolean jobStat = false;
#define DEBOUNCE_DELAY 200
static unsigned long lastDebounceTime;
void setup() {
mySoftwareSerial.begin(9600);
if!myDFPlayer.begin(mySoftwareSerial)) {
while(true)
;
}
myDFPlayer.setTimeOut(500);
myDFPlayer.volume(20); //Set volume value (0~30).
myDFPlayer.volumeUp(); //Volume Up
myDFPlayer.volumeDown(); //Volume Down
myDFPlayer.EQ(DFPLAYER_EQ_NORMAL);
myDFPlayer.outputDevice(DFPLAYER_DEVICE_SD);
myDFPlayer.play(23);
pinMode(ledPin, OUTPUT); // 把 ledPin 設置成 OUTPUT
pinMode(buttonPin, INPUT); // 把 buttonPin 設置成 INPUT
Serial.begin(9600);
// 把外部中斷(interrupt 0)連接到 buttonStateChanged() 函式
// CHANGE 是指當 pin 狀態改變時就觸發中斷,不管是從 HIGH 到 LOW 或從 LOW 到 HIGH
attachInterrupt(interruptNumber, buttonStateChanged, RISING);
}
void loop() {
if(jobStat){
microsec = ultrasonic.timing();
if(microsec<20000){
cmMsec = ultrasonic.convert(microsec, Ultrasonic::CM);
//Serial.println(cmMsec);
switch((int)cmMsec/100){
case 2:seq[0] = 1;break;
case 1:seq[0] = 2;break;
case 0:seq[0] = 3;break;
}
seq[1] = (int)((int)cmMsec%100)/10+3;
seq[2] = (int)cmMsec%10+12;
doPlaySeq();
}
jobStat = false;
}
}
// Interrupt 0 的中斷處理函式
// 讀取 buttonPin 的狀態,並反應到 ledPin 上
void buttonStateChanged() {
unsigned long currentTime = millis();
buttonState = digitalRead(buttonPin);
if(!jobStat & (currentTime - lastDebounceTime) > DEBOUNCE_DELAY){
jobStat = true;
lastDebounceTime = currentTime;
}
}
void doPlaySeq(){
for(int a=0;a<4;a++){
if((a==2&&seq[2]==12)||(a==0&&seq[0]==3)){
}else{
myDFPlayer.play(seq[a]); //Play the first mp3
delay(1500);
}
}
}