Hello, I'm currently quite new with programming in Arduino, already have been programming for a year, but not able to crank this one out. I'm trying to detect the frequency (or period, then calculate the inverse of it for frequency) of a given audio signal coming from a guitar. I'm using an Arduino Mega 2560 (not able to buy or get another board, as it costed all of my life savings) and connecting it to a circuit that filters the guitar signal (between 800mV and 32mV), amplifies it (to about 1.55Vp) and mounts it on a direct voltage signal to get a voltage between 0 and 3V.
I've managed to built a program that allows me to write a custom frequency PWM signal between 0Hz and 4KHz from the amplitude of a 10K potentiometer (using PWM library), and another one that replicates the frequency of a sine wave through digitalWrite and delays. I tried to merge the two programs together, but to no luck at all, and the frequency detector one works really weirdly, as digitalWrite + delay doesn't keep a constant HIGH outpút, but a pulse train.
What I'm looking for is for a way to detect the frequency of an audio signal and paste it into the parameters of the PWM frequency generator function, or for a way that is better, more-efficient, quicker or just different, as I've been trying to get this working for a week and to no avail. The code for both programs is below, first the frequency generator, and second the frequency reader (which doesn't quite work sometimes).
#include <PWM.h>
void setup() {
InitTimersSafe();
pinMode(11, OUTPUT);
}
void loop()
{
int sV = analogRead(A3);
int32_t freq = sV * 3.91111;
SetPinFrequencySafe(11, freq);
pwmWrite(11, 128);
}
int ciclo = 0, i = 0, period = 0;
void setup() {
pinMode(A3, INPUT);
pinMode(11, OUTPUT);
analogReference(EXTERNAL);
}
void loop() {
while(analogRead(A3) >= 480){
ciclo++;
delayMicroseconds(1);
}
period = (0.000001 * ciclo);
period = 1000 * period;
digitalWrite(11, HIGH);
delay(period);
digitalWrite(11, LOW);
delay(period);
ciclo = 0;
period = 0;
}
