How can I write a code that will simultaneously receive the data from the microphone sensor as sound from the speaker? So, I want to make something like a megaphone, but when I write the code, the sound only comes out as a crackling and incomprehensible sound.
İ use this code:
const int microphonePin = A6;
const int speakerPin = 5;
void setup() {
pinMode(speakerPin, OUTPUT);
}
void loop() {
int sensorValue = analogRead(microphonePin);
analogWrite(speakerPin, sensorValue / 4);
}
Sorry I cannot follow what you are asking. Using a microphone to listen to something it is sending to a speaker is prone to feedback (squealing is what you will hear). Post a simple block diagram explaining what you want to do. Realize the Arduino such as the UNO is not very good at working with sound.
Darkmour,
I've done some tests on your code from post #1, to try and explain why it doesn't work.
I modified your code slightly, as follows:
I used pin12 to monitor the frequency at which the ADC was taking samples.
I used direct port manipulation to change the state of pin 12, this hardly affects the sampling frequency.
Pin 12 goes high immediately before the ADC starts its conversion, and low again when the conversion has finished.
I changed the analogue pin to A0. This was simply for convenience, and has no effect on the results.
Here is the modified code:
const int microphonePin = A0;
const int speakerPin = 5;
const int monitorPin = 12;
void setup() {
pinMode(speakerPin, OUTPUT);
pinMode(monitorPin, OUTPUT);
}
void loop() {
PORTB = B00010000; // take pin12 high
int sensorValue = analogRead(microphonePin);
PORTB =B00000000; // take pin 12 low
analogWrite(speakerPin, sensorValue / 4);
}
I used a function generator to feed a 2kHz sinewave into the analogue pin A0.
I used an oscilloscope to monitor the signals going to and from the Arduino Uno R3.
Here is an oscilloscope trace showing what is happening:
The oscilloscope trace shows:-
The red trace shows the PWM output of pin 5. The PWM frequency is around 980Hz.
The green trace shows that the ADC is taking samples at a frequency of 8.9kHz.
When the green trace goes low the code is doing it's analogWrite().
This should change the pulse width of the red trace, but if the frequency of the PWM is only 980Hz, then you can't change the pulse width at a frequency of 8.9kHz.
The PWM signal just changes pulse width when it is able to, and so it is not a representation of the input signal.
After showing in post #15 that the PWM could not change fast enough to respond to a 2kHz signal, I did some further tests with lower frequency inputs.
Using a 20Hz signal, the PWM pulse width does in fact change fast enough to respond to the input.
I have included a fourth trace - Channel 3 (blue) which is the output of a low pass filter I have added to pin 5 output.
The filter consists of a 10kΩ resistor and 1µF capacitor.