想做一个arduino连接蜂鸣器,总共四个按键,前面三个按键按下发do,re,mi,后面一个按键按下放一首歌,但是现在写完实现不了前面三个按键的功能了,希望得到解答
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
#define NOTE_D0 -1
#define NOTE_D1 294
#define NOTE_D2 330
#define NOTE_D3 350
#define NOTE_D4 393
#define NOTE_D5 441
#define NOTE_D6 495
#define NOTE_D7 556
#define NOTE_DL1 147
#define NOTE_DL2 165
#define NOTE_DL3 175
#define NOTE_DL4 196
#define NOTE_DL5 221
#define NOTE_DL6 248
#define NOTE_DL7 278
#define NOTE_DH1 589
#define NOTE_DH2 661
#define NOTE_DH3 700
#define NOTE_DH4 786
#define NOTE_DH5 882
#define NOTE_DH6 990
#define NOTE_DH7 112/* 以上部分是定义是把每个音符和频率值对应起来 */
/********** 这部分是用英文对应了拍子 **********/
#define WHOLE 1
#define HALF 0.5
#define QUARTER 0.25
#define EIGHTH 0.25
#define SIXTEENTH 0.625
/* 这部分就是整首曲子的音符部分,用了一个序列定义为tune,整数 */
int tune[] = {
NOTE_D0,NOTE_D0,NOTE_D0,NOTE_D6,NOTE_D7,NOTE_DH1,NOTE_D7,NOTE_DH1,NOTE_DH3,NOTE_D7,NOTE_D7,NOTE_D7,NOTE_D3,NOTE_D3,
NOTE_D6,NOTE_D5,NOTE_D6,NOTE_DH1,NOTE_D5,NOTE_D5,NOTE_D5,NOTE_D3,NOTE_D4,NOTE_D3,NOTE_D4,NOTE_DH1,
NOTE_D3,NOTE_D3,NOTE_D0,NOTE_DH1,NOTE_DH1,NOTE_DH1,NOTE_D7,NOTE_D4,NOTE_D4,NOTE_D7,NOTE_D7,NOTE_D7,NOTE_D0,NOTE_D6,NOTE_D7,
NOTE_DH1,NOTE_D7,NOTE_DH1,NOTE_DH3,NOTE_D7,NOTE_D7,NOTE_D7,NOTE_D3,NOTE_D3,NOTE_D6,NOTE_D5,NOTE_D6,NOTE_DH1,
NOTE_D5,NOTE_D5,NOTE_D5,NOTE_D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 1,0.5,0.25,0.25,0.25,0.5, 0.5,0.5,0.5,0.25,0.5,1,
0.5,0.5,0.5,0.5,1,1, 1,1,1,0.5,0.5, 1+0.5,0.5,1,1,
1,1,1,0.5,0.5, 1.5,0.5,1,1, 1,1,1,1,
0.5,0.5,1,1,0.5,0.5, 1.5,0.25,0.5,1, 1,1,1,1,
1,1,1,1, 1,1,1,1, 0.5,0.5,1,1,0.5,0.5,
1,0.5,0.5,1,1, 1,1,1,1, 1,1,1,1,
0.5,0.5,1,1,0.5,0.5, 1,0.5,0.25,0.5,1, 1,1,1,0.5,0.5
};
/**********************************************************************************/
int length; /* 这里定义一个变量,后面用来表示共有多少个音符 */
int buttonPin = 5;//按键
boolean ledState = false;
LiquidCrystal lcd(0, 1, 8, 6, 10, 11); /// REGISTER SELECT PIN,ENABLE PIN,D4 PIN,D5 PIN, D6 PIN, D7 PIN
void setup()
{
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
pinMode(2,INPUT);//do
pinMode(3,INPUT);//re
pinMode(4,INPUT);//mi
pinMode(9,OUTPUT);
/* 这里用了一个sizeof函数, 可以查出tone序列里有多少个音符 */
length = sizeof(tune)/sizeof(tune[0]);
pinMode(buttonPin, INPUT_PULLUP);
lcd.clear();
}
int p;
void loop()
{
// set the cursor to column 0, line 1
lcd.setCursor(0, 0);
lcd.print("MUSIC PLAYER");//print name
//print name
delay(750);//delay of 0.75sec
// set the cursor to column 0, line1
noTone(9);
if(digitalRead(2)==HIGH)
{
tone(9,523);
lcd.setCursor(0, 1);
lcd.print("DO");
}
else if(digitalRead(3)==HIGH)
{
tone(9,587);
lcd.setCursor(0, 1);
lcd.print("RE");
}
else if(digitalRead(4)==HIGH)
{
tone(9,659);
lcd.setCursor(0, 1);
lcd.print("MI");
}
delay(5);
for (int x = 0; x < length; x++)
{
if (digitalRead(buttonPin) == HIGH) {//如果读取到按键被按压改变ledStart
ledState = !ledState ;
delay(500);//这个延迟是你按压按键的大概时间
p = x;//记录当前播放的音乐的位置
}
|