Contents
This is my first Arduino project. In this project, the tempo (speed) of the rhythm produced changes when the resistance of the potentiometer changes. In this context, the resistance of the potentiometer will change as I rotate the knob the potentiometer. I’m using Arduino Uno in this project.
Parts
- Arduino Uno x 1
- Green LEDs x 2
- Red LED x 1
- Jumper Wires
- Potentiometer x 1
- Piezo Speaker x 1
How it works?
The range of the values output from the potentiometer will be from 0 – 1023, but I do not need such a large value. Therefore, I’ll be mapping the value from 0 – 1023 to 0 – 255. With a smaller value, I can use the new mapped values to set the brightness of the LED. Furthermore, the new "mapped" reading of the potentiometer, newVal, will determine the speed of the rhythm. When the reading of the potentiometer is more than 511, the second LED will be "On" to indicate that the potentiometer has been rotated by more than half.
When newVal = 0
, the red LED will be turned on and the rest of the LEDs will be off, as this will be the "off" state of the device. Below are some images of the project:
Demo
Schematics
Code
int sensorPin = 0; // select the input pin for the potentiometer
int ledPin = 11; // select the pin for the LED
int sensorValue = 0; // variable to store the value coming from the sensor
int newVal = 0;
int speakerPin = 9;
int length = 8; // the number of notes
char notes[] = "cdefgabC";// a space represents a rest
int beats[] = {1, 1, 1, 1, 1, 1, 1, 1};
void playTone(int tone, int duration ) {
for (long i = 0; i < duration * 1000L; i += tone * 2) {
digitalWrite(speakerPin, HIGH);
delayMicroseconds(tone);
digitalWrite(speakerPin, LOW);
delayMicroseconds(tone);
}
}
void playNote(char note, int duration) {
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };
// play the tone corresponding to the note name
for (int i = 0; i < 8; i++) {
if (names[i] == note) {
playTone(tones[i], duration);
}
}
}
void setup() {
pinMode(ledPin, OUTPUT); //declare the ledPin as an OUTPUT:
pinMode(speakerPin, OUTPUT);
pinMode(13, OUTPUT); //LED Pin to indicate >511 input value
pinMode(12, OUTPUT); //LED Pin to indicate 0 input value
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(sensorPin);// read the value from the sensor:
newVal = map(sensorValue, 0, 1023, 0, 255); //adjust the value 0 to 900 to
analogWrite(11 , newVal );
Serial.println(sensorValue);
for (int i = 0; i < length; i++) {
if (notes[i] == ' ') {
delay(beats[i] * newVal ); // rest
} else {
playNote(notes[i], beats[i] * newVal );
}
// pause between notes
delay(newVal/ 2);
}
if (sensorValue > 511){
digitalWrite(13, HIGH);
}
else {
digitalWrite(13, LOW);
}
if (sensorValue == 0){
digitalWrite(12, HIGH);
}
else {
digitalWrite(12, LOW);
}
}