Assignment 5.1

posted Jun 30, 2010, 1:03 PM by Unknown user   [ updated Jun 30, 2010, 3:17 PM ]
I figured this would be a good time to get some practice with bitwise operators and using as little code / memory as humanly possible.

Arduino Code

const int switch1 = 5;     //declare switch button pins
const int switch2 = 4;

void setup() {
  pinMode(switch1, INPUT);     // set switch pins to input   
  pinMode(switch2, INPUT);
  Serial.begin(9600);              // begin serial communication at 9600 bps
}

void loop() { 
byte msg = digitalRead(switch2);        //declare variable "msg" and set it to the value of digitalRead(switch1) (returns 1 if button is pushed, 0 if not
msg = msg<<1;                                //shift bits left (ex. 0000 0001 becomes 0000 0010)
msg = msg | digitalRead(switch1);      //use bitwise OR to combine the 2 (ex. 0000 0010 | 0000 0001 = 0000 0011)
Serial.print(msg);                              //prints 0 if neither are pressed, 3 if both, 2 for just switch2 and 1 for just switch1
delay(100);                                       //waits 1/10 second
}

Processing Code

import processing.serial.*;  //import all serial libraries
Serial serPort;              // Create object from Serial class
 
void setup() {
  size(200, 200);
  serPort = new Serial(this, Serial.list()[0], 9600);    //create serial port object at port 0 at 9600 bps (not sure what "this" is for though)
}

void draw() {
  if (serPort.available() == 0) {      //if no data available
    return;                                    //stop
  }
  switch (serPort.read()) {                   //begin switch-case with serial code
    default : background(0);                 //if nothing pressed, black background
              break;
    case 1  : background(255, 0, 0);      //switch1 pressed, red background
              break;
    case 2  : background(0, 0, 255);      //switch2 pressed, blue background
              break;
    case 3  : background(0, 255, 0);      //both pressed, green background
              break;
  }
}

Also I'm wondering if "serPort" would need to be released (deleted, dealloced, whatever) because of the use of the "new" command. Not sure though, I have very limited experience with Java.
Comments