我正在开发一个项目,我想通过组合不同的正弦波来生成(简单)声音。我使用的是 arduino mkrZero,因为它内置了 I2S 接口,并且似乎有足够的处理能力来满足我的需求。
I have wired my system exactly like in the tutorial for arduino I2S simpleTone:
And the tutorial https://www.arduino.cc/en/Tutorial/I2SSimpleTone代码工作得很好,我从扬声器中听到了简单的方波音。
现在我修改了代码来生成正弦波,有一个用于 sin 函数的查找表以使其足够快:
#include <I2S.h>
uint16_t isin16[] = {
0, 1144, 2287, 3430, 4571, 5712, 6850, 7987, 9121, 10252, 11380,
12505, 13625, 14742, 15854, 16962, 18064, 19161, 20251, 21336, 22414,
23486, 24550, 25607, 26655, 27696, 28729, 29752, 30767, 31772, 32768,
33753, 34728, 35693, 36647, 37589, 38521, 39440, 40347, 41243, 42125,
42995, 43851, 44695, 45524, 46340, 47142, 47929, 48702, 49460, 50203,
50930, 51642, 52339, 53019, 53683, 54331, 54962, 55577, 56174, 56755,
57318, 57864, 58392, 58902, 59395, 59869, 60325, 60763, 61182, 61583,
61965, 62327, 62671, 62996, 63302, 63588, 63855, 64103, 64331, 64539,
64728, 64897, 65047, 65176, 65286, 65375, 65445, 65495, 65525, 65535,
}; //0-90
const int sincount = 2;
int freqs[] = {50*360,51*360};
float amps[] ={0.1,0.1};
const int sampleRate = 8000; // sample rate in Hz
short sample = 0;
double t = 0;
double dt = 1.0/(1.0*sampleRate);
short LR[] = {0,0};
void setup() {
Serial.begin(115200);
// start I2S at the sample rate with 16-bits per sample
if (!I2S.begin(I2S_PHILIPS_MODE, sampleRate, 16)) {
while (1); // do nothing
}
}
void loop() {
sample = 0;
for(int n= 0;n<sincount;n++)
{
sample += fSin(freqs[n]*t)*amps[n];
}
t += dt;
LR[0] = sample;
LR[1] = sample;
I2S.write(LR[0]);//left channel
I2S.write(LR[1]);//right channel
}
float fSin(long x)
{
boolean pos = true; // positive - keeps an eye on the sign.
if (x < 0)
{
x = -x;
pos = false;
}
if (x >= 360) x %= 360;
if (x > 180)
{
x -= 180;
pos = !pos;
}
if (x > 90) x = 180 - x;
if (pos) return isin16[x]; // = /65535.0
return isin16[x];
}
这也很好用。
BUT!
如果我稍微改变一下代码然后写
I2S.write(LR,2);
代替
I2S.write(LR[0]);//left channel
I2S.write(LR[1]);//right channel
一切都崩溃了,扬声器发出的声音听起来就像是可怕的尖叫声 https://www.youtube.com/watch?v=_Eos0wg7QJU
来自 I2S 库参考:
描述
将二进制数据写入 I2S 接口。该数据作为样本发送
或一系列样品。
Syntax
I2S.write(val)
// 阻塞
I2S.write(buf, len)
// 不阻塞
参数
val:作为单个样本发送的值
buf:作为一系列样本发送的数组
len:缓冲区的长度
Returns
byte write() 将返回写入的字节数,尽管读取
该号码是可选的。
我想使用后一个版本的写入功能,因为它不会阻塞,并且我可以在播放以前的样本时生成新样本。
关于如何使缓冲版本也正常工作有什么想法吗?