Jared - Digital POT Test

/*Purpose:      Use pushbuttons to adjust brightness of light bulb through a digital POT
 *Date Created: 04/26/2011
 *Author:       Jared Morell
 */

#define CS 11     // chip select output to POT
#define SDI 10    // serial data output to POT
#define SHTD 12   // shutdown control on POT
#define CLK 13    // serial clock output to POT
#define down 4    // DOWN input
#define up 5      // UP input
#define rst 6     // reset output to POT
#define opt 7     // option for which pot to use - LOW = 1, HIGH = 2
#define rstin 8   // reset input

byte address = 0;    // specific POT address on digital POT
byte rstlevel = 128; // mid level of output voltage: (128/256)*Vdd
byte pot;            // current level of output voltage: (pot/256)*Vdd

int dbDelay = 50; // Debounce delay in ms

static unsigned long last_interrupt_time = 0;

void setup()
{
  pinMode(CS, OUTPUT);
  pinMode(SDI, OUTPUT);
  pinMode(CLK, OUTPUT);
  pinMode(rst, OUTPUT);

  pinMode(opt, INPUT);
  pinMode(up, INPUT);
  pinMode(down, INPUT);
  pinMode(rstin, INPUT);

  digitalWrite(SHTD, HIGH);

  // set pot to mid level and output to POT
  pot = rstlevel;
  sendLevel(pot);

  Serial.begin(9600);
}

// run infinite loop to check for inputs and act accordingly
void loop()
{  
  //Serial.println(digitalRead(pot), DEC);
 
  // Down
  if (digitalRead(down) == HIGH){
    if (debounce() == true){

      Serial.println("DOWN");

      // decrease pot value as long as min hasn't been reached
      if (pot > 0){
        pot--;
        sendLevel(pot);
        Serial.print("pot = ");
        Serial.println(pot, DEC);
      }
    }
  }
 
  // Up
  if (digitalRead(up) == HIGH){
    if (debounce() == true){
 
      Serial.println("UP");
        
      // increase pot value as long as max hasn't been reached  
      if (pot < 255){
        pot++;
        sendLevel(pot);
        Serial.print("pot = ");
        Serial.println(pot, DEC);
      }
    }
  }
 
//  // Reset
//  if (digitalRead(rstin) == HIGH){
//    if (debounce() == true){
//
//      Serial.println("RST");
//      pot = rstlevel;
//      sendLevel(pot);
//      Serial.print("pot = ");
//      Serial.println(pot, DEC);
//    }
//  }
//  delay(50);
}

// modified code from mikalhart on arduino.cc forums
// http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1223543716/
boolean debounce()
{
  unsigned long interrupt_time = millis();
  // If interrupts come faster than 200ms, assume it's a bounce and ignore
  if (interrupt_time - last_interrupt_time > dbDelay)
  {
    last_interrupt_time = interrupt_time;
    return true;
  }
  else{
    last_interrupt_time = interrupt_time;
    return false;
  }
}

// send information to POT
void sendLevel(byte val)
{
  byte address = digitalRead(opt);
  digitalWrite(CS, LOW);
  shiftOut(SDI, CLK, MSBFIRST, address);
  shiftOut(SDI, CLK, MSBFIRST, val);
  digitalWrite(CS, HIGH);
}