//--- SPI code

#define DATAOUT     11      
#define DATAIN      12       //not used
#define SPICLOCK    13    
#define SLAVESELECT 10  
#define NOTEON      9

void SPIInitialize()
{
  byte clr;
  
  pinMode(DATAOUT, OUTPUT);
  pinMode(DATAIN, INPUT);
  pinMode(SPICLOCK,OUTPUT);
  pinMode(SLAVESELECT,OUTPUT);
  
  digitalWrite(SLAVESELECT,HIGH); //disable device
  
  SPCR = (1<<SPE)|(1<<MSTR);
  clr=SPSR;
  clr=SPDR;
  delay(10);
}

char SPITransfer(volatile char data)
{
  SPDR = data;                    // Start the transmission
  while (!(SPSR & (1<<SPIF)))     // Wait the end of the transmission
  {
  };
  return SPDR;                    // return the received byte
}


//--- MCP42100 code

byte SetPot(int address, int value)
{
  // Slave Select set low to allow commands
  digitalWrite(SLAVESELECT, LOW);

  // 2 byte command
  SPITransfer(0x10 + address);   // 0x10 = 'set pot' command
  SPITransfer(value);            // Value to set pot

  // Release chip, signal end transfer
  digitalWrite(SLAVESELECT, HIGH); 
}


//--- Sequencer code
//                    A   Bb  B   C   C#  D   Eb  E   F   Fb  G   G#  A   B    Bb   C    C#   D    Eb   E    F    F#   G    G#   A    Bb   B    C    C#   D    Eb   E    F    F#   G    G#
byte noteValues[] = { 11, 19, 26, 33, 40, 47, 54, 61, 68, 76, 83, 90, 98, 105, 112, 119, 126, 132, 139, 146, 153, 160, 167, 173, 180, 186, 193, 199, 206, 212, 218, 224, 231, 237, 243, 249  };

void NoteOn( int noteNum )
{
    SetPot(1, noteValues[noteNum]);   // Set the right level of resistance for the given note
    digitalWrite(NOTEON, HIGH);       // Then turn on the note to play through the synth
}

void NoteOff()
{
  digitalWrite(NOTEON, LOW);          // Turn off the noite
}


//--- Application code

void setup()
{
  pinMode(NOTEON, OUTPUT);  // Set up the NOTEON pin as an output
  SPIInitialize();          // Initialize the SPI interface

  NoteOff();                // Make sure we start with the note off
}


void loop()
{
  // run through each of the notes in ascending pitch
  for (int noteNum = 0; noteNum < 35; noteNum++)
  {
    // play the note for 650 ms
    NoteOn(noteNum); 
    delay(650);

    // turn off the note and wait 100 ms to rest 
    NoteOff();
    delay(100);
  }
}







