3874| 6
|
[常见问题] 如何获得音频的频率? |
唉,谁让我这么懒。 以arduino为例,一个麦克风来简单说一下怎么测声音频率。本人不才,误差大致是±5%,实际精度玩玩还行。输出的结果有:频率,占空比,周期,高电平时间,低电平时间。功能简单,基本满足你的需求可以用来粗略的调音,即只能测量单频,复合波形类似和弦就不行了。如果要提高效率,建议加入FFT库处理。 /* Arduino Frequency meter */ int divider[6] = {0, 1, 8, 64, 256, 1024}; int prescaler = 5; double count = 0; double middle = 0; char x = 0; ISR(TIMER1_OVF_vect) { if (prescaler < 4) { prescaler++; } } void interrupt() { if (!x) { count = TCNT1; TCNT1 = 0x000; TCCR1B = prescaler; attachInterrupt(0, interrupt, FALLING); } else { middle = TCNT1; attachInterrupt(0, interrupt, RISING); } x = ~x; } void setup() { Serial.begin(57600); TIMSK1 = 0x01; TCCR1A = 0x00; attachInterrupt(0, interrupt, RISING); } void loop() { Serial.print("Freq: "); Serial.print(16000000.0 / divider[prescaler] / count); Serial.print(" Hz Duty: "); Serial.print(middle / count * 100); Serial.print(" % Period: "); Serial.print(0.0000625 * divider[prescaler]*count); Serial.print(" ms H-time: "); Serial.print(0.0000625 * divider[prescaler]*middle); Serial.print(" ms L-time: "); Serial.print(0.0000625 * divider[prescaler]*(count - middle)); Serial.println(" ms"); if (prescaler > 1) { prescaler--; delay(200); } delay(100); } 麦克风接GND和D2口。 打开串口监视器,调波特率到57600,即可看到结果。因为没有任何防干扰措施,出现偏差特别大的结果请自行忽略。 |
© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed