Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //#include "musicBox.h" //this is for our tones and is for reference.
- int knob = A4; //analog pin for the potentiometer
- int ledPin1 = 5;
- int ledPin2 = 6;
- int ledPin3 = 7;
- int speakerPin = 8;
- int length = 15; // the number of notes
- char notes[] = "ccggaagffeeddc "; // a space represents a rest
- int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
- int tempo = 300;
- int btn = 12; //pin for the button
- 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(speakerPin, OUTPUT);
- Serial.begin(57600); //start printing out to the serial port for processing to read from
- pinMode(knob, INPUT);//add a input for your potentiometer
- pinMode(btn, INPUT_PULLUP);//add an input for the button. We're using input pull up because otherwise, there'd be a short
- //you can also do this in hardware. I often do. See pull up resistor
- pinMode(ledPin1, OUTPUT);
- pinMode (ledPin2, OUTPUT);
- pinMode(ledPin3, OUTPUT);
- }
- void loop() {
- int data = analogRead(knob); //take an analog read on the knob to read resistance(0 to 1024)
- int btnState = digitalRead(btn); //digitally read the button (0 or 1)
- //Serial.println(btnState)
- ; //optional print line for testing
- data = map(data, 0, 1024, 65, 800);//using the map function, transform the range of the
- //tone that the resistor is in, 0 to 1024 to the range of tones we want to play.
- //turn on
- digitalWrite(ledPin1, HIGH);
- digitalWrite(ledPin2, HIGH);
- digitalWrite(ledPin3, HIGH);
- //wait 1 sec
- delay(1000);
- //turn off
- digitalWrite(ledPin1, LOW);
- digitalWrite(ledPin2, LOW);
- digitalWrite(ledPin3, LOW);
- //wait 1 sec
- delay(1000);
- if(btnState==0) // the button is pushed down
- {
- int pauseBetweenNotes = 2 * 1.30;//make a little pause to not overwhelm arduino
- tone(8, data,500); // play a tone on pin 8, at the mapped sound frequency for 500ms
- delay(pauseBetweenNotes); // a little pause
- Serial.println(data); // print it out
- noTone(8);//turn off the pad
- }else{ //the button is not pushed
- noTone(8); //make no noise
- }
- for (int i = 0; i < length; i++) {
- if (notes[i] == ' ') {
- delay(beats[i] * tempo); // rest
- } else {
- playNote(notes[i], beats[i] * tempo);
- }
- // pause between notes
- delay(tempo / 2);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement