我正试着用模拟传感器做一架阿迪诺钢琴作为钥匙。但是,所有的键都产生相同的音调,生成的音调在程序中不会出现在任何地方。当同时按下多个键时,所述音调在两个预期音调之间交替,而未定义的音调不产生。我检查了在触摸键时是否激活了其他命令,只有当按下相应的键时,它们才会激活。
#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);
}我知道数组的效率会更高,但我想先让它正常工作。我也是一个初级程序员,所以任何其他建议都将不胜感激。
发布于 2014-04-14 23:10:00
我怀疑问题是,每次在循环中,你都在激活和消除音调。我认为更好的方法是在特定输入被激活时启动音调,并一直播放到输入被停用为止。(不能同时使用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.
}这通过每个输入来检查它是否已被激活。如果是这样,如果目前没有其他音调,则开始播放相应的音符。如果输入不是活动的,但其相应的音符正在播放,则停止输入。
https://stackoverflow.com/questions/23069702
复制相似问题