I have a project where I am inputting 2 square waves into the Atmega 328, calculating the frequency of these two signals using the "pulseIn" function and some math, deciding which signal is the lowest frequency, and then outputting a new square wave signal at this lower frequency using the "tone" function. There is a summing amplifier on the output side of the circuit as well.
The program is doing what I ask it to do. However, the problem I am facing is I am getting some electrical interference between the input and output signals that is distorting all the square waves. I need some help to get rid of this interference.
Things I have tried: low pass filters/high pass filters, shielding wires with aluminum foil, twisting wires around each other, moving the input/output wires far away from each other, installing capacitors between power and ground on micro and op-amp, grounding unused pins on the microcontroller.
I have also just bought some shielded wire so I will be trying that soon.
Any ideas would be helpful. Thanks in advance
Here is my code:
int freqInputLeft = 4; //pin to read the new sensor wave at 0-5V (left wheel)
int freqInputRight = 6; //pin to read the new sensor wave at 0-5V (right wheel)
float pulseLengthLeft = 0; //initialize pulse length (left wheel)
float freqLeft = 0; //initialize frequency (left wheel)
float pulseLengthRight = 0; //initialize pulse length (right wheel)
float freqRight = 0; //initialize frequency (right wheel)
int FinalOutput = 12; //pin to output the modified square wave
void setup() {
//Serial.begin(9600); // setup serial
pinMode(freqInputLeft, INPUT);
pinMode(freqInputRight, INPUT);
pinMode(FinalOutput, OUTPUT);
}
void loop() {
pulseLengthLeft = pulseIn(freqInputLeft, HIGH, 15000); //measure the pulse length of the left sensor
freqLeft = 1/(2*pulseLengthLeft*.000001); //convert left pulse length to freq in Hz
pulseLengthRight = pulseIn(freqInputRight, HIGH,15000); //measure the pulse length of the right sensor
freqRight = 1/(2*pulseLengthRight*.000001); //convert right pulse length to freq in Hz
// if (pulseLengthRight > 0) {
// tone(FinalOutput, freqRight);
// //Serial.println(23);
// }
//
// else {
// noTone(FinalOutput);
// //Serial.println(10);
// }
//Serial.println("");
// Serial.println(freqLeft);
//Serial.println(freqRight);
// Serial.println("");
if (pulseLengthLeft && pulseLengthRight > 0) {
if (freqRight/freqLeft < .9) {
tone(FinalOutput, freqRight);
}
else{
tone(FinalOutput, freqLeft);
}
}
else {
noTone(FinalOutput);
}
}