Source

ArduinoProjects / Experimental / MaryHadALittleLambRaveMachine.ino

Full commit
/*
  Melody
 
 Plays a melody 
 
 circuit:
 * 8-ohm speaker on digital pin 8
 
 created 21 Jan 2010
 modified 30 Aug 2011
 by Tom Igoe 

This example code is in the public domain.
 
 http://arduino.cc/en/Tutorial/Tone
 
 */
 #include "pitches.h"

// notes in the melody:
int melody[] = {
  NOTE_B4, NOTE_A4,NOTE_G4, NOTE_A4, NOTE_B4,NOTE_B4, NOTE_B4, 0, NOTE_A4, NOTE_A4, NOTE_A4, 0, NOTE_B4, NOTE_D5,  NOTE_D5, 0};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4};

int LDR = 0;       // select the input pin for the LDR
int RED = 11;
int GREEN = 12;
int BLUE = 13;

int redVal = 0;
int greenVal = 0;
int blueVal = 0;
  
void setup()
{
  pinMode(LDR, INPUT);       // declare the LDR as an INPUT
  
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
  pinMode(RED, OUTPUT);
  
  digitalWrite(GREEN, HIGH);
  digitalWrite(BLUE, HIGH);
  digitalWrite(RED, HIGH);
  
  analogWrite( RED, 255-redVal );
  analogWrite( GREEN, 255-greenVal );
  analogWrite( BLUE, 255-blueVal );
}

int thisNote = 0;

void loop()
{ 
  //MUSIC
  int LDRval = analogRead(LDR);       // read the value from the sensor
  
  // to calculate the note duration, take one second 
  // divided by the note type.
  //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
  int noteDuration = LDRval/noteDurations[thisNote];
  //noteDuration *= (LDRval)/8;
  
  int melodyNote = melody[thisNote];
  tone(8, melodyNote,noteDuration);
  
  // to distinguish the notes, set a minimum time between them.
  // the note's duration + 30% seems to work well:
  int pauseBetweenNotes = noteDuration * 1.30;
  delay(pauseBetweenNotes);
  // stop the tone playing:
  noTone(8);
  
  ++thisNote;
  if(thisNote == 16)
  {
    thisNote = 0;
  }
   
  //COLORS
  redVal += 5*(greenVal | blueVal);
  greenVal += 2;
  blueVal += 3*(greenVal | redVal);
  
  analogWrite( RED, 255-redVal );
  analogWrite( GREEN, 255-greenVal );
  analogWrite( BLUE, 255-blueVal );
}