Þorkell Ragnar setti upp skemmtilega uppfærslu með hljóðum og ljósum í Arduino.Nam_forr3

Hér er kóðinn af þessu verkefni:

const int buzzerPin1 = 9;const int songLength = 30;

char notes[] = „EaEbEgaEcEdEbcEaEbEgaEcEdEbcEb“;

int beats[] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};

int tempo = 150;

void setup() {

pinMode(buzzerPin1, OUTPUT);

pinMode(3, INPUT);

pinMode(5, OUTPUT);

pinMode(2, OUTPUT);

pinMode(4, OUTPUT);

pinMode(7, OUTPUT);

pinMode(8, OUTPUT);

pinMode(12, OUTPUT);

Serial.begin(9600);

}

 

int lastButtonState = HIGH;

int noOfStateChanges = 0;

 

void loop() {

int buttonState = digitalRead(3);

if (buttonState != lastButtonState) {

noOfStateChanges++;

}

lastButtonState = buttonState;

if (noOfStateChanges == 2) {

// BUZZER

int i, duration;

 

for (i = 0; i < songLength; i++)

{

duration = beats[i] * tempo;

 

if (notes[i] == ‘ ‘)

{

delay(duration);

}

else

{

digitalWrite(5, LOW);

digitalWrite(2, LOW);

digitalWrite(4, LOW);

digitalWrite(7, LOW);

digitalWrite(8, LOW);

digitalWrite(12, LOW);

digitalWrite(light(notes[i]), HIGH);

tone(buzzerPin1, frequency(notes[i]), duration);

delay(duration);

}

delay(tempo/10);

}

}

 

if (noOfStateChanges == 4){

noOfStateChanges = 0;

Serial.println(„hahah“);

}

 

}

 

int light(char note) {

int i;

const int numNotes = 8;

char names[] = {‘E’,’g’, ‘a’, ‘b’, ‘c’, ‘d’};

int lights[] = {5, 2, 4, 7, 8, 12};

for (i = 0; i < numNotes; i++)

{

if (names[i] == note)

{

return(lights[i]);

}

}

return(0);

}

 

int frequency(char note)

{

int i;

const int numNotes = 8;

char names[] = {‘E’,’g’, ‘a’, ‘b’, ‘e’, ‘c’, ‘d’};

int frequencies[] = {330, 392, 440, 494, 659, 523, 587};

for (i = 0; i < numNotes; i++)

{

if (names[i] == note)

{

return(frequencies[i]);

}

}

return(0);

}