2014-11-04 13 views
-6

任何人都可以帮我编写这个函数吗?我需要能够在两个不同的Piezo上一次播放两种不同的音调。我应该怎样改变我的代码?在C中编码多个Piezos#

void beep (unsigned char speakerPin, int freq1, int freq2, long timeInMilliseconds) 
{ 
    int x;  
    long delayAmount1 = (long)(1000000/freq1); 
    long delayAmount2 = (long)(1000000/freq2); 
    long loopTime = (long)((timeInMilliseconds*1000)/(delayAmount1*2)); 
    for (x=0;x<loopTime;x++)  
    {  
    digitalWrite(speakerPin1,HIGH); 
    digitalWrite(speakerPin2,HIGH); 
    delayMicroseconds(delayAmount2); 
    digitalWrite(speakerPin1,LOW); 
    digitalWrite(speakerPin2,LOW); 
    delayMicroseconds(delayAmount2); 

    } 
} 
+1

我们无法为您编写代码。首先要自己尝试一下,然后告诉我们。 – 2014-11-04 19:53:17

+1

这似乎是一个“压电”对此很重要。它是什么? – BradleyDotNET 2014-11-04 19:54:58

+0

我知道我可以使用移位寄存器编写代码,但我不想使用移位寄存器。我现在插入我的arduino的只是两个Piezos。这是我到目前为止所提出的。 – Entropular 2014-11-04 19:56:20

回答

0

您应该使用定时器和中断。他们将提供更准确的时间,并独立运行loop()

已经有一个Arduino功能,tone()一次播放一个音符,但它不能适应多个,因为它依赖于一个定时器的PWM。

相反,您需要编写一个中断服务程序,在正确的时间切换一个引脚,并设置下一个中断以便在将来适当的时候触发。你将需要使用attachInterrupt(),并有一些全球volatile变量来操纵音调。

这是一个标准的学生练习,网上应该有很多例子。

+0

你介意给我找个例子吗?我一直在寻找大约4个小时,但没有运气。 – Entropular 2014-11-04 20:22:23

+0

另外,是否可以运行移位寄存器呢?然后我可以同时运行扬声器? – Entropular 2014-11-04 20:23:34

+0

http://www.jeremyblum.com/2010/09/05/driving-5-speakers-simultaneously-with-an-arduino/是一个简单的,具有“足够好”的精度。必须有更多更精确的音调。但是代码确实告诉你如何设置中断处理程序并配置定时器来使用它。我刚刚搜索了“arduino定时器音调”,并忽略了使用'tone()'的命中。 – UncleO 2014-11-04 20:38:32