Saturday, April 30, 2016

Simple LED control with Xbee/Arduino and Processing

Goal: Turn a single LED on/off wirelessly though an Xbee chip connected to an Arduino using the control P5 library for Processing.

Materials: 
-LED
-330 Ohm resistor
-Xbee (2)
-Xbee shield for arduino
-Power Supply (4 AA battery holder)
-Arduino Uno

Assumption: 
-The Xbee is set up and configured
-The LED is connected to pin 13

Processing code:

//Turn on LED with button press using controlP5

import controlP5.*;
import processing.serial.*;

ControlP5 cp5;
Serial myPort;        // The serial port
int c2;

void setup() {
 
 // List all the available serial ports
 // if using Processing 2.1 or later, use Serial.printArray()
 println(Serial.list());

 // I know that the first port in the serial list on my mac
 // is always my  Arduino, so I open Serial.list()[0].
 // Open whatever port is the one you're using.
 myPort = new Serial(this, Serial.list()[0], 9600); 

 // don't generate a serialEvent() unless you get a newline character:
 myPort.bufferUntil('\n');
 
  size(400,600);
  noStroke();
  cp5 = new ControlP5(this);
 
 
   cp5.addButton("on")
     .setValue(0)
     .setPosition(100,100)
     .setSize(200,19)
     ;


  cp5.addButton("off")
     .setValue(100)
     .setPosition(100,120)
     .setSize(200,19)
     ;
        
}

void draw() {
  background(c2);
 

}

public void on(int theValue) {


   //if we clicked in the window
   myPort.write('1');         //send a 1
   println("1");  

}

public void off(int theValue) {
   myPort.write('0');         //send a 1
   println("0"); 

  c2 = color(#2408A5);
}


Arduino Code: 

#include  

char val;

SoftwareSerial XBee(2, 3); // Arduino RX, TX (XBee Dout, Din)

void setup() {
  //Serial Port begin
  Serial.begin (9600);
  XBee.begin(9600);
  pinMode(13,OUTPUT);
}

void loop()
{

  digitalWrite(13,HIGH);

   if (XBee.available())
   { // If data is available to read,
     val = XBee.read(); // read it and store it in val
   }
   if (val == '1')
   { // If 1 was received
     digitalWrite(13, HIGH); // turn the LED on
   } else {
     digitalWrite(13, LOW); // otherwise turn it off
   }
   delay(10); // Wait 10 milliseconds for next reading





How it works:
The button class of control P5 is activated on a button release event. When the button that says "on" is released, a value of '1' is written to the serial port that the XBee is connected to using the command myPort.write('value').

The Xbee (connected to the arduino) waits for data to become available (   if (XBee.available()) )and when the data is available , it reads the value (as a char value of "1" or "0" - if (val == '1') { ) and either turns and LED off or on.

Extending it:
The next step is to use a slider or a knob to send analog values to the arduino. The eventual goal is to be able to use sliders and dials to drive a robot while precisely controlling speed and turning radius. \

No comments:

Post a Comment