In the earlier post, I have discussed How to Use LDR with Arduino and also used map() function with the Arduino and LDR to scale the delay time from the Light Sensor Input. Similarly, in this article, I am going to show you how to control the pitch of a sound if you connect a small speaker to the Arduino.



To connect a speaker to your Arduino circuit, use the digital pin 9 through a resistor (fixed or variable) to the one terminal of the speaker. Connect the other terminal of your speaker to GND pin of the Arduino.

control sound with arduino ldr

Connections for a speaker with the LDR Arduino circuit.

To create sounds using digital pin 9 you need to increase the on / off rate to the pin. If you increase the on/off rate to pin 9 it will change frequency to the audio spectrum to that pin.

To achieve this you can decrease the min and max duration to digital pin 9 with the following code segments.

const int outputPin = 9;

// Speaker connected to digital pin 9
const int sensorPin = 0;

// connect sensor to analog input 0
const int minDuration = 1;

// 1ms on, 1ms off (500 Hz)
const int maxDuration = 10;

// 10ms on, 10ms off (50 hz)

void setup()
{
pinMode(outputPin, OUTPUT);

// enable output on the led pin
}
void loop()
{

int sensorReading = analogRead(sensorPin);

// read the analog input

int rate = map(sensorReading, 200,800,minDuration, maxDuration);

rate = constrain(rate, minDuration,maxDuration);

 

// constrain the value

digitalWrite(outputPin, HIGH);

 

// set the LED on

delay(rate);

// wait duration dependent on light level

digitalWrite(outputPin, LOW);

// set the LED off

delay(rate);
}

 

Read more about map() function