IMG_2035.jpg

Blog

Lab-Analog/digital input and pseudo analog output

force_button_led.png
// these constants won't change:
const int ledPin = 13;      // LED connected to digital pin 13
const int knockSensor = A0; // the piezo is connected to analog pin 0
//const int threshold = 100;  // threshold value to decide when the detected sound is a knock or not
const int buttonPin = 2;
int prev = LOW;
int redPin = 11;
int greenPin = 10;
int bluePin = 9;
int red, green, blue = 0;

// these variables will change:
int sensorReading = 0;      // variable to store the value read from the sensor pin
int ledState = LOW;         // variable used to store the last LED status, to toggle the light
int buttonState = 0;
int flag = 0;

void setup() {
  pinMode(redPin, OUTPUT); // declare the ledPin as as OUTPUT
  pinMode(greenPin, OUTPUT); // declare the ledPin as as OUTPUT
  pinMode(bluePin, OUTPUT); // declare the ledPin as as OUTPUT
  pinMode(buttonPin, INPUT);
  pinMode(knockSensor, INPUT);
  Serial.begin(9600);       // use the serial port
}

void loop() {
  sensorReading = analogRead(knockSensor);
  int current = digitalRead(buttonPin);
  int brightness = map(sensorReading, 0, 1023, 100, 255);
    switch(flag){
    case 0 :
      red =  brightness;green = 0;blue = 0;
      break;
    case 1 :
      green =  brightness;red = 0;blue = 0;
      break;
    case 2 :
      blue =  brightness;red = 0;green = 0;
      break;
    }
  if(prev != current){
      if(current  == HIGH){
          flag +=1;
      }else{
        flag %=3;
      }
    }
    setColor(red, green, blue);
    Serial.println(brightness);
    prev = current; 
    delay(100);  // delay to avoid overloading the serial port buffer
} 
void setColor(int red, int green, int blue)
{
  #ifdef COMMON_ANODE
  red = 255 - red;
  green = 255 - green;
  blue = 255 - blue;
  #endif
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);
}
YOU JIN CHUNG