Assignment 5.1

posted Aug 6, 2010, 8:39 PM by Unknown user   [ updated Aug 6, 2010, 8:44 PM ]

Arduino Code:

const int switchpin1 = 4; //sets the first button to pin 4
const int ledpin1 = 12; //sets the first led to pin 12
const int switchpin2 = 2; //sets the second button to pin 2
const int ledpin2 = 10; //sets the second button to pin 10
int val = 0;  // sets a variable for storing data

void setup() {
  //sets the buttons as outputs and the leds and inputs
  pinMode(switchpin1, INPUT);   
  pinMode(ledpin1, OUTPUT);
  pinMode(switchpin2, INPUT);
  pinMode(ledpin2, OUTPUT);
  Serial.begin(9600); //sets the serial communication to 9600 bps
}

void loop() 
    if (digitalRead(switchpin1) == HIGH && digitalRead(switchpin2) == LOW) // if button 1 is on and button 2 is off
    {                             
        val=1;        //creates situation 1
        digitalWrite(ledpin1, HIGH);//led 1 is turned on
        digitalWrite(ledpin2, LOW); //led 2 is turned off
    } 
    else if (digitalRead(switchpin1) == LOW && digitalRead(switchpin2) == HIGH) //if button 1 is off and button 2 is on
    {          
        val=2; // creates situation 2
        digitalWrite(ledpin1, LOW);//led 1 is turned off
        digitalWrite(ledpin2, HIGH);//led 2 is turned on
    } 
    else if (digitalRead(switchpin1) == HIGH && digitalRead(switchpin2) == HIGH) //if button 1 and 2 are on
    {    
        val=3; //creates situation 3
        digitalWrite(ledpin1, HIGH);//led 1 is turned on
        digitalWrite(ledpin2, HIGH);//led 2 is turned off
    } 
    else 
    { 
        val=0; // if the arduino recieves on data (i.e. both buttons are off)
        digitalWrite(ledpin1, LOW); //led 1 is turned off
        digitalWrite(ledpin2, LOW);// led 2 is turned off
    } 
}
  

Processing Code:

import processing.serial.*;

Serial myPort;  // Create object from Serial class
int val;      // Data received from the serial port

void setup() 
{
  size(200, 200);
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 9600);
}

void draw()
{
  if ( myPort.available() > 0) {  // If data is available,
    val = myPort.read();         // read it and store it in val
  }
  background(255);             // Set background to white
  if (val == 1) {              // In situation 1,
    fill(0, 0, 255);          // set fill to blue
  } 
  if (val == 2) {            // In situation 2,
    fill(0, 255, 0);          // set fill in green
  }
  if (val == 3) {             //In situation 3,
    fill(255, 255, 0);        // set fill to yellow
  }
  else {                       // If no buttons are pressed,
    fill(255, 0, 0);          // set fill to red
  }
  rect(50, 50, 100, 100);
}



Comments