Tuesday, December 28, 2010

Variable flashing LED with sound

This is 1 of the first Arduino projects I did and I must admit it felt great to achieve something.
It's quite a simple project doing the 'knightrider' lights with a beep when the light reaches the ends.

The speed of the LEDs is controlled by a potentiometer so it can be made faster and slower.


Below is the code.  Be aware I'm more about getting the Arduino to do something and so the code will be a bit rough around the edges.  It works but I definitely do not consider it best practise or even efficent code.
Use at your own risk.


// Create array for LED pins
byte ledPin[] = {4,5,6,7,8,9,10,11,12,13};
int ledDelay ; // delay between changes
int direction = 1;
int currentLED = 0;
unsigned long changeTime;
int potPin = 2; // select the input pin for the potentiometer

int speakerPin = 2;  // set the speakerPin to 2 for buzzer
int length = 25;  // the number of notes
char notes[] ="ccggaagffeeddc "; // a represents a rest
int beats[] = {1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
int tempo = 300;

void setup() {
  // set all pins to outputs
  for (int x=0; x<10; x++) {
    pinMode(ledPin[x], OUTPUT); }
    changeTime = millis();

pinMode(speakerPin, OUTPUT);  // set the speakerpin to OUTPUT
}

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 loop () {
//read the value from the pot
ledDelay = int(analogRead(potPin)/10);
  // if it has beenledDelay ms since last change
  if ((millis() - changeTime) > ledDelay) {
    changeLED();
    changeTime = millis();
  }
  }

void changeLED() {
// turn off all LEDs
for (int x=0;  x<10; x++) {
  digitalWrite(ledPin[x], LOW);
}
// turn om the current LED
digitalWrite(ledPin[currentLED], HIGH);

// play a tone when it gets to the end
if (currentLED == 9 || currentLED == 0) { playTone(1915, ledDelay);}

// increment by the direction value
currentLED += direction;
// change direction if we reach the end
if (currentLED == 9 || currentLED == 0) {  direction = direction *-1; }
}