我正在尝试用模拟传感器作为键来制作 Arduino Piano 。但是,所有键都产生相同的音调,所产生的音调不会出现在程序中的任何位置。当同时按下多个键时,音调在两个预期音调之间交替变化,并且不会产生未定义的音调。我检查了触摸按键时是否激活了其他命令,只有在按下相应的按键时它们才会激活。
#define Note_C 65.41 //Hz
#define Note_D 73.42 //Hz
#define Note_E 82.41 //Hz
#define Note_F 87.31 //Hz
#define Note_G 98 //Hz
#define Note_A 110 //Hz
#define threshold 1000
const int speaker=3;
const int B_1=A0; // pins A0-A5 have sensors attatched to them
const int B_2=A1; // pins 13-8 are being used to power each sensor
const int B_3=A2;
const int B_4=A3;
const int B_5=A4;
const int B_6=A5;
const int P_1=13;
const int P_2=12;
const int P_3=11;
const int P_4=10;
const int P_5=9;
const int P_6=8;
int val_1=0;
int val_2=0;
int val_3=0;
int val_4=0;
int val_5=0;
int val_6=0;
void setup()
{
Serial.begin(9600);
pinMode(P_1, OUTPUT);
digitalWrite(P_1, HIGH);
pinMode(P_2, OUTPUT);
digitalWrite(P_2, HIGH);
pinMode(P_3, OUTPUT);
digitalWrite(P_3, HIGH);
pinMode(P_4, OUTPUT);
digitalWrite(P_4, HIGH);
pinMode(P_5, OUTPUT);
digitalWrite(P_5, HIGH);
pinMode(P_6, OUTPUT);
digitalWrite(P_6, HIGH);
}
void loop()
{
analogRead(B_1); // checks each sensor value and stores it
delay(1); // each value must be checked twice with a
val_1=analogRead(B_1); // delay inbetween to provide consistant values
analogRead(B_2);
delay(1);
val_2=analogRead(B_2);
analogRead(B_3);
delay(1);
val_3=analogRead(B_3);
analogRead(B_4);
delay(1);
val_4=analogRead(B_4);
analogRead(B_5);
delay(1);
val_5=analogRead(B_5);
analogRead(B_6);
delay(1);
val_6=analogRead(B_6);
if (val_1 < threshold)
{
tone (speaker, Note_C);
Serial.println("1");
}
else
{
noTone (speaker);
}
if (val_2 < threshold)
{
Serial.println("2");
tone (speaker, Note_D);
}
else
{
noTone(speaker);
}
if (val_3 < threshold)
{
Serial.println("3");
tone (speaker, Note_E);
}
else
{
noTone (speaker);
}
if (val_4 < threshold)
{
Serial.println("4");
tone (speaker, Note_F);
}
else
{
noTone (speaker);
}
if (val_5 < threshold)
{
Serial.println("5");
tone (speaker, Note_G);
}
else
{
noTone (speaker);
}
if (val_6 < threshold)
{
Serial.println("6");
tone (speaker, Note_A);
}
else
{
noTone (speaker);
}
noTone(speaker);
}
我知道数组会更有效率,但我想先让它工作。我也是一名初学者,所以任何其他建议都会受到赞赏。
答案 0 :(得分:1)
我怀疑问题是你每次循环都在不断地激活和停用音调。我认为更好的方法是在激活特定输入时启动音调,并继续播放直到输入停用。 (您不能使用tone()
同时播放多个音符。)
您需要将当前播放音调的编号存储在变量中。这样的事情可能有用:
int currentTone = 0;
void loop()
{
// (take your analog readings here)
if (val_1 < threshold)
{
if (currentTone == 0)
{
tone(speaker, Note_C);
currentTone = 1;
}
}
else if (currentTone == 1)
{
noTone(speaker);
currentTone = 0;
}
if (val_2 < threshold)
{
if (currentTone == 0)
{
tone(speaker, Note_D);
currentTone = 2;
}
}
else if (currentTone == 2)
{
noTone(speaker);
currentTone = 0;
}
// etc.
}
通过每个输入来检查它是否已被激活。如果是,并且如果当前没有其他音调播放,它将开始播放相应的音符。如果输入未激活,但正在播放相应的音符,则会将其停止。