29 1 / 2014

I’ve been learning all about Xbee’s as part of a larger Arduino project and recenly “mastered” the art of sending some data from Processing through to an Arduino via two Xbee’s.

I won’t spend too much time talking about the setting up of Xbee’s althoug, I found it much harder than I initially expected (hint: make sure you know the baud rate and use ATND to check that the two Xbee’s can find each other) but there’s a great tutorial over here.

As for the Processing part, well that’s easy by comparison.

We’ll be generating a very straight forward boilerplate for serial communications between Processing and Arduino.

What you’ll need

  • Arduino Uno
  • RGB LED
  • Jumper Wires
  • 2x Xbees (I’m using Series 1 devices)
  • 2x Adafruit Xbee Adapters - you could swap this out for any sheild, but I found this super easy to get started with
  • 1x USB FTDI cable - for programming your Xbee’s

Sketch

The implementation consists of two parts, you have one Xbee connected to your computer via the FTDI cable, and the other mounted on a breadboard using this schematic: Xbee LED Control

Note: you can download the Fritzing file here.

Processing will use a software serial library to send messages via the Xbee to the Xbee connected to the Arduino. In this case, the message will be the RGB colour we want the LED to be.

One thing to take very clear notice of is the RX and TX pins on the Xbee - if you get this wrong the sketch won’t work.

Lets have a look at the code…

Arduino Code

#include <SoftwareSerial.h>
SoftwareSerial mySerial =  SoftwareSerial(2, 3);

// LED pins
int ledR = 11;
int ledG = 10;
int ledB =  9;

// RGB Calculated Values
int valueR, valueG, valueB;

// if we loose comms with the host, fade out after timeout_period
unsigned long timeout_period  = 1000.0;
unsigned long timeout_last_reset = millis();
boolean faded_out;

// set to true if you want to see action on the Serial output
boolean logging = true;

// setup
void setup() {
  // setup pins
  pinMode(ledR, OUTPUT);
  pinMode(ledG, OUTPUT);
  pinMode(ledB, OUTPUT);

  // test pattern
  testPattern();

  // setup serial comms
  if (logging) {
    Serial.begin(9600);
    Serial.println("Ready to recieve");
  }
  mySerial.begin(9600);
  mySerial.println("Ready");
}

// loop
void loop() {
  // if there's any serial available, read it:
  while (mySerial.available() > 0) {
    // look for the next valid integer in the incoming serial stream:
    valueR = mySerial.parseInt();
    valueG = mySerial.parseInt();
    valueB = mySerial.parseInt();

    // look for the newline. That's the end of your sentence:
    if (mySerial.read() == 'e') {
      // set the LEDs
      setLED(valueR, valueG, valueB);

      // reset the timeout manager
      timeout_last_reset = millis();
    }
  }

  // manage timeouts
  faded_out = (valueR + valueG + valueB) = 0;
  if (((timeout_last_reset + timeout_period) < millis()) && !faded_out) {
    if (logging) {
      Serial.println("We've reached the timeout");
    }

    // fade out & constrain
    valueR = constrain(valueR-1, 0, 255);
    valueG = constrain(valueG-1, 0, 255);
    valueB = constrain(valueB-1, 0, 255);

    // set the LEDs
    setLED(valueR, valueG, valueB);

    // slow down the fade
    delay(10);
  }
}

// test pattern
void testPattern() {
  setLED(255,0,0);
  delay(500);
  setLED(0,255,0);
  delay(500);
  setLED(0,0,255);
  delay(500);
  setLED(0,0,0);
}

// set the LED colours
void setLED(int r, int g, int b) {
  // My LEDs are common-cathode, so big number = low light
  analogWrite(ledR, map(r, 0, 255, 255, 0));
  analogWrite(ledG, map(g, 0, 255, 255, 0));
  analogWrite(ledB, map(b, 0, 255, 255, 0));

  // output the current versions
  if (logging) {
    Serial.print(valueR);
    Serial.print(", ");
    Serial.print(valueG);
    Serial.print(", ");
    Serial.println(valueB);
  }
}

Processing Code

import processing.serial.*;

Serial xBee;

void setup()  {
  size(255,255);
  try {
    String serialPort = serialIndexFor("tty.usbserial");
    xBee = new Serial(this, serialPort, 9600);
  } catch (Exception e) {
    println(e);
    exit();
  }
}

float r = 0;
float b = 0;
float g = 0;
int rData, gData, bData;

void draw() {
  r = r + 0.001;
  g = g + 0.002;
  b = b + 0.003;

  rData = (int)abs(sin(r)*255.0);
  gData = (int)abs(sin(g)*255.0);
  bData = (int)abs(sin(b)*255.0);

  xBee.write(rData + "," + gData + "," + bData + "e");

  delay(10);
}

String serialIndexFor(String name) throws Exception {
  for ( int i = 0; i < Serial.list().length; i ++ ) {
    String[] part = match(Serial.list()[i], name);
    if (part != null) {
      return Serial.list()[i];
    }
  }
  throw new Exception("Serial port named '" + name + "' could not be found");
}

Start by programming your Arduino, and remove it from your computer before running the Processing code against the FTDI cable - I had issues with my Mac recognising both at the same time for some reason, I didn’t look into the issue since simply disconecting it worked.

Obviously plug the Arduino up to a power source or another USB port (I used my iPhone wall charger).

On initial run the LED should cycle Red, Green & Blue to demonstrate correct wiring, then proceed to take the data from the Xbee.

If nothing happens, make sure the Processing code is running, and that it’s pushing data to the correct port. Secondly, check that the Arduino is actually accepting incoming data by looking at the serial monitor logs.

Lastly, if the Arduino doesn’t get data from the controller Xbee the LED will slowly fade to black. Which I thought was a nice touch :D

As always, you can find the code on my Github account.

28 1 / 2014

Couldn’t find the Fritzing part for Adafruit’s Xbee Adapter, so made my own. Download here.

26 1 / 2014

I’ve been playing around with serial ports a lot lately in both Processing and Arduino. I wrote this little function to automatically select the correct port if you’re not entirely aware of the ID or name (just a fragment).

Hope this makes life easier for someone else too:

import processing.serial.*;

Serial xBee;

void setup()  {
  try {
    String serialPort = serialIndexFor("tty.usbserial");
    xBee = new Serial(this, serialPort, 9600);
  } catch (Exception e) {
    println(e);
    exit();
  }
}

String serialIndexFor(String name) throws Exception {
  for ( int i = 0; i < Serial.list().length; i ++ ) {
    String[] part = match(Serial.list()[i], name);
    if (part != null) {
      return Serial.list()[i];
    }
  }
  throw new Exception("Serial port named '" + name + "' could not be found");
}

17 11 / 2013

Here’s a quick look at the software I’ve been building to go along with the LiveLights hardware demonstrated here.

You can checkout all the Processing code here: github.com/d2kagw/live-lights.

I’m yet to find a ADVC that plays nice with Processing, but as soon as I do, this project will be nearing completion.

17 11 / 2013

A few months ago I started working on a little project I’ve called ‘Live Lights’ (here’s my original post].

I thought I’d share with you the hardware aspect of the project which I finished a while back. Here’s a video of the construction:

What you see in the video is essentially two Pixel Strips from Adafruit plugged up to an Arduino. The Arduino is being sent Serial data from a Processing sketch running on my Mac.

I’ve been going through a complete redevelopment of the software used, but you can see the original implementation on Github here.

09 2 / 2013

I’ve been working on a bootstrap script for RaspberryPi that: - Updates the RaspberryPi OS and Firmware - Python, Ruby and all the hacking Essentials setup - Gets x11vnc running on boot (so you can VNC into the actual display) - Makes the Pi work with Apple’s Screen and File Sharing

Getting x11vnc setup and running on boot took forever to workout, so enjoy the end result :P

You can find the instructions here.

22 1 / 2013

Over the weekend I started playing around with the implementation of the LiveLight project I’m working on.

The most complex part of the project is the communication between the host system (running Processing) and the Arduino responsible for updating the colour/brightness of the LEDs.

I started hacking around with serial communications and quickly realised that sending complex data over serial communications isn’t as easy as I had hoped.

In this tutorial we’ll setup an Arduino with two buttons and two LEDs. The Arduino will send data (button presses) to Processing through the USB port, Processing will then take the data and return other data (LED on/off states) back to Arduino.

What you’ll need

  • Arduino Uno
  • Breadboard
  • 2x 10kΩ Resistors
  • 2x LEDs
  • A Computer with Processing installed & working.

Sketch

<project name>

Note: you can download the Fritzing file here.

Code

Because there’s we’re testing serial communication, there’s two parts to the code:

  1. The Arduino Code: sending inputs to the Processing code, and reading the response
  2. The Processing Code: retrieving output from the Arduino board, and returning actionable data

Arduino Code

// LEDs
int ledA = 10;
int ledB = 11;

// Buttons
int buttonA = 12;
int buttonB = 13;

int buttonStateA = 0;
int buttonStateB = 0;

int sloower = 1;

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

  pinMode(ledA, OUTPUT);
  pinMode(ledB, OUTPUT);

  pinMode(buttonA, INPUT);
  pinMode(buttonB, INPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // if we're setup to read data
  if (Serial.available()) {
    // read the response
    int rawSerial = Serial.read();

    // if the response == 500
    if (rawSerial==500) {
      // turn on the light
      digitalWrite(ledB, HIGH);
    } else {
      // otherwise, turn it off
      digitalWrite(ledB, LOW);
    }

    // fade the light based on the PWM value
    analogWrite(ledA, rawSerial);
  }

  // if the button is pressed
  buttonStateA = digitalRead(buttonA);
  if (buttonStateA == HIGH) {
    // send button state
    Serial.print("buttona,");
    Serial.println(buttonStateA);
    delay(sloower);
  };

  // if the button is pressed
  buttonStateB = digitalRead(buttonB);
  if (buttonStateB == HIGH) {
    // send button state
    Serial.print("buttonb,");
    Serial.println(buttonStateB);
    delay(sloower);
  };
}

Note: you can download the Arduino source code from here.

Processing Code

import processing.serial.*;

Serial serial;
int pwmValue;
int delta;

boolean redOn;

void setup() {
  frameRate(30);

  println(Serial.list());

  // XXXXX
  // You might need to update this port number
  int serialPortNumber = 6;
  String port = Serial.list()[serialPortNumber];
  serial = new Serial(this, port, 9600);
  serial.bufferUntil('\n');

  pwmValue = 0;
  delta = 10;

  redOn = false;
}

void draw() {
  pwmValue = pwmValue + delta;
  if (pwmValue<10) {
    delta = 10;
  }
  if (pwmValue>240) {
    delta = -10;
  }

  serial.write(pwmValue);

  if (redOn) {
    serial.write(500);
  };
}

void serialEvent(Serial port) {
  String inString = port.readStringUntil('\n');

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

    String actionKey = split(inString, ',')[0];
    int  actionValue = int(split(inString, ',')[1]);

    println("Arduino says: " + actionKey + " - " + actionValue);

    if (actionKey == "buttonb") {
      redOn != redOn;
    };
  }
}

Note: you can download the Processing source code from here.

How to get it running

One thing you’ll learn about Serial communications is that it can be really, really touchy.

Everything seems to be A-OK once you get things running, but if one small thing is out of place everything simply won’t work and there’ll be no explanation for it. So prepare for a fair amount of trial and error.

Firstly, send the code to the Arduino and start it up. At this point of time, nothing should happen.

Then, start the processing app.

IF everything is setup A-OK you should see one of your LED’s fade up and down indefinitely. If it’s not, then we need to slide into debug mode. First thing to check out is the port the processing code is sending data to.

Have a look at the processing code and look for this line int serialPortNumber = 6;. In the Processing log you should see a dump of all the available serial ports. Change that number to match the relevant port (hint: it’s the same as the Arduino IDE).

Once changed, try restarting the Processing app. If that doesn’t work, then unfortunately, there’s not much help I can offer here, just make sure you’ve followed the instructions above and run through the usual Arduino debug checklist of checking the pin numbers, etc. Then just hack away chunks of code until something works.

One thing that caught me off guard early in the process is the Arduino serial monitor. If you start throwing Serial.println() calls in your code to debug things the serial communication will cease - so keep that in mind.

Should the above sketches work for you then you should have ‘two-way’ communication between host and client.

What’s next?

I’ve come across two libraries that can help you pass data between host and client, they take a lot of this off your hands so you can worry about the implementation, but I always like understanding the inner-sanctum before relying on libraries.

  • CmdMessenger which is part of the Arduino Core
  • SerialCommand which looks really hot, but only handles one way communication (or so it seems)

My requirements only include simple data like button states to be passed through so this is essentially the extent of my research… for now!

22 1 / 2013

As per my earlier post, I’m trying to build a set of lights to sit behind my telly that light the room based on what’s on TV.

There’s loads of tutorials on the web of how to make them, but they all assume you’re either using XMBC as the media centre, or are for PC use only. I’m hoping to build something that can work across all our TV’s inputs, so the implementation is going to be different on the back-end.

I’m also planing on giving the project a few sexy features. Such as:

  • IR Remote control so you can adjust the brightness, turn it on & off and change it’s mode
  • Multiple modes:
    • Ambient TV Mode: Like the video
    • Plain Colour Mode: Have a single colour light the room - colour will be adjustable through the IR remote
    • Party Mode: Light the LEDs with predetermined animations and colours for a ‘party’ vibe
  • Build in a light detector to adjust the brightness based on how bright the room is (daylight vs. night-time)

Because of this, I’m going to need to use Processing to analyse the video input which will be fed into a computer I have sitting next to the TV. (TV will have a video capture device which takes in a Monitor output from the TV itself, allowing the LiveLight to work on any video source).

So, first up, it’s time to research Serial communication between the Arduino and Processing (running on our Mac Mini). Then, I’ll need to dive into Processing and learn how to get it to process the video and output the LED colours to the Arduino. After that, I’ll finally get onto the build stage!

Keep an eye out for a tutorial on how to get Serial comms working :)

21 1 / 2013

Hi all,

It’s been far too long since I’ve had time to dive into Arduino land, but I’m pretty excited about a new project I’ve just started working on.

The above video (you might have seen these screens already) show’s off the killer ambient lighting functionality of Philips screens. I’m hoping to recreate this using a heap of RGB LEDs and an Arduino.

I’ll post all the experiments & tests here as I go on.

Tags:

Permalink 5 notes

05 11 / 2011

I’ve shared my Fritzing files for the basic OpAmp used in the auto-beat detection project i’ve been working on.

Post can be found here.