Friday, August 19, 2011

Serial Communication

Onward with the projects! I have a few things on the go at the moment, working 9 to 5:30 breaks up my creative flow for outside projects, but I've gotten the Arduino and my computer conversing nicely using serial communication. First I used a potentiometer to control the screen background in Processing (thanks to Jeremy Blum for his fantastic arduino video tutorial series, I recommend it to absolutely anyone and everyone). Next came using Processing to control the Arduino, first with an LED on/off button approach, next using sliders to control PWM brightness. I used the controlP5 sliders, you can download the controlP5 library for free (google it).

Here are the sliders on my computer screen:
And here's the results as laid out on my new breadboard (from proto-pic, where I bought the original Arduino kit):

And a blurry dark photo to emphasise the different light levels:

I could not have done this without the help of Jeremy Blum's tutorials, Lucky Larry's tutorial on Arduino/Processing serial communication, and the ControlP5 slider example by Andreas Schlegel. The LEDs are on PWM-enabled pins 10 and 11.

I ended up with this Ardunio code:

int redPin = 10;
int yelPin = 11;
int buff[2];
//int
void setup()
{
  pinMode(redPin, OUTPUT);
  pinMode(yelPin, OUTPUT); 
  Serial.begin(9600);
}

void loop()
{
  if(Serial.available() >= 2 ){
    buff[0] = Serial.read();
    buff[1] = Serial.read();
    Serial.flush();
    analogWrite(redPin, buff[0]);
    analogWrite(yelPin, buff[1]);
  }
}



And this processing code:
import processing.serial.*;
import controlP5.*;
ControlP5 controlP5;
Serial port;

int redval = 0;
int yelval = 0;

void setup() {
  size(400,400);
  smooth();
  port = new Serial(this, "COM3", 9600);
  controlP5 = new ControlP5(this);
  controlP5.addSlider("red",0,255,128,200,180,100,10);
  controlP5.addSlider("yellow",0,255,128,200,210,100,10);
}
 
void draw() {
  background(0);
}

void red(float redi) {
  redval = round(redi);
  port.write(redval);
  port.write(yelval);
}

void yellow(float yeli) {
  yelval = round(yeli);
  port.write(redval);
  port.write(yelval);
}


Which, I'll be honest, was a lot easier and shorter than I thought it was going to be. There's probably a better way of doing this (leave a comment if you know one!) but I'm happy with it for a first try. Learning with Arduino always seems to be fast, and I'm constantly surprised how simple things are. The electronics have actually been the harder part of this experience, trying to catch up after 15 or so years.

Still, having fun!

No comments:

Post a Comment