March 19, 2008

Blink Project

For our first project we were supposed to combine analog & digital leading to some kind of LED blinking.

I have a simple On/Off switch, a flex sensor, and 3 LEDs. When the flex sensor is at rest (straight) the yellow LED blinks, bend it forward and it flashes green, bend it back and it flashes red. This also takes (via serial) to a Processing script which has a small rectangle that changes color to match the currently blinking LED.

Arduino Code:

/* Blink Project
/  by Ryan Galgon (due: 3/19/2008)
/
/  Demonstrate Analog and Digital techniques
/
*/

int redPin = 7;
int ylwPin = 6;
int grnPin = 5;
int switchPin = 2;
int switchVal = 0;
int flexPin = 5;
int flexVal = 0;


void setup() {
  Serial.begin(9600);

  pinMode(redPin, OUTPUT);
  pinMode(ylwPin, OUTPUT);
  pinMode(grnPin, OUTPUT);

  pinMode(switchPin, INPUT);
}


void blink(int aPin) {				// blink an LED
  digitalWrite(aPin, HIGH);
  delay(200);
  digitalWrite(aPin, LOW);
  delay(200);
}

void loop() {
  switchVal = digitalRead(switchPin); // is the switch on or off?
  if( switchVal == LOW) {	//we're ON
    flexVal = analogRead(flexPin);
    Serial.println(flexVal);
    if( flexVal > 600) {
      blink(grnPin);
    } 
    else if (flexVal > 500 ) {
      blink(ylwPin);
    } 
    else {
      blink(redPin);
    }
  } 
  else { 
    // we're off :-( 
  }
}

Processing Code:

import processing.serial.*;

int linefeed = 10;
Serial myPort;
int val = 0;

color c1 = #FF0000;

void setup() {
  //println(Serial.list());

  myPort = new Serial(this, Serial.list()[2], 9600);
  myPort.bufferUntil(linefeed); // read bytes until linefeed
}

void draw() {
  fill(c1);
  rect(0,0,100,100);
}

void serialEvent(Serial myPort) {
  // read serial buffer
  String myString = myPort.readStringUntil(linefeed);

  if (myString != null ) {
    myString = trim(myString);

    val = Integer.parseInt(myString);
    
    //println(val);

    if(val > 600) {
      c1 = #00FF00;  //green
    } 
    else if (val > 500) {
      c1 = #FFFF00;  // yellow
    } 
    else {
      c1 = #FF0000; // red
    }

  }
}

Pictures

Schematic:

schematic