Processing

[English version] Processing + Arduino + touchOSC

3
OSCgui

Today we will see how to communicate your mobile device android / iphone / iphone / iphone with our PC, through a protocol known as OSC (Open Sound Control) , this protocol is commonly used to control luminaires and devices such as strobes, sequencers and other things used in the musical world, one could say that is the replacement of the MIDI. OSCinternet protocol uses UDP for communication, which is why we need a requirement that the devices are on the same network, know your IP address and open a communication port.

Need for the next act: processing , arduino , LED RGB device TouchOSC installed. But we’ll do exactly?? … We will create a custom template with TouchOSC editor, which we use as a control to vary the intensity of an RGB LED and color combinations to create, we will open a communication link between processing and TouchOSC, finally send all information received to an Arduino board connected to the serial port and see the result obtained in the RGB LED at the end of all this we have the following result:

For start, the first thing to do is create our template for the TouchOSC and charge it to the device, for this we use the TouchOSC Editor a tool created by Hexl that you can download from here , we will use three  fader controls with a resolution of one byte (0 – 255) to vary the intensity of the LED, for this follow the next steps in the video tutorial:

Now it’s time to open processing, but before you start throwing lines of code you need to install a specific library for communication with OSC, use the library oscP5 created by Andreas Schlegelwe can download it here, then decompress it and move its contents to documents / processing / libraries, once installed now open a new sketch.

We create a fader class that will be used as a control and to display the interaction with the mobile device, this control will be the closest thing to fader and with the same properties we use in our template, the final class for the Fader is as follows:

class Fader {

  int val, valMap;
  int px, py;
  final int h=300, w=70;
  color[] col;

  color[] red= {
    color(#DE1D2A), color(#131010), color(#501515)
  };
  color[] green= {
    color(#3B811C), color(#111410), color(#25451A)
  };
  color[] blue= {
    color(#1C2D81), color(#0D0D10), color(#0C1233)
  };  

  Fader(int px, int py, char c) {
    this.px=px;
    this.py=py;

    switch(c) {
    case 'R':
      col=red;
      break;
    case 'G':
      col=green;
      break;
    case 'B':
      col=blue;
      break;
    }
    setValue(0);
  }

  void draw() {
    strokeWeight(4);
    strokeJoin(ROUND);
    stroke(col[0]);
    fill(col[1]);
    rect(px, py, w, h);
    fill(col[2]);
    rect(px, py+(h-valMap), w, valMap);

    if (mousePressed && (mouseX>=px && mouseX< =px+w) && (mouseY>=py && mouseY< =py+h)) {
      setValue((int)map((h-(mouseY-py)), 0, h, 0, 255));
    }
  }

  void setValue(int val) {
    this.val=val;
    valMap=int(map(val, 0, 255, 0, h));
  }

  int getValue() {
    return val;
  }
}

After we create our custom template, for this we will use vectors with the addresses of each of our controls, these addresses are url type, we define this addresses in our template with the editor. The class of our template is as follows:

class RGBLayout {

  //Define the addresses
  //We defined it before in touchOSC Editor
  //Addresses are url type     /Page/Address
  String[] Addr= {
    "/RGB/fdrRed",
    "/RGB/fdrGreen",
    "/RGB/fdrBlue",
  };

  //create a vector to store recieved data
  //creates as many variables as addresses have our templete
  float[] Data= new float[Addr.length];

  //by default touchOSC use the "f" typetag  as identifier
  String Typetag="f";

  //this method check if the received data must be processed
  void check(OscMessage theOscMessage) {

    //for each address in our template
    for (int i = 0; i < Addr.length; i++) {
      //Check if the data sent matches an address
      if (theOscMessage.checkAddrPattern(Addr[i])==true) {
        //check if identifier matches
        if (theOscMessage.checkTypetag(Typetag)) {
          //Save the value in this address in variable Data
          Data[i] = theOscMessage.get(0).floatValue();
          //prints address and its new value
          println(Addr[i]+" = "+ Data[i]);
        }
      }
    }
    //if it doesn't match, ignore data
  }

  //prints data stored
  void printData() {
    println(Data);
  }

  //prints addresses url
  void printAddr() {
    println(Addr);
  }
}

And finally our main program, this must import the libraries netP5 and oscP5 to work properly, create objects of classes defined before and verify the received data for later send them to the Arduino trought the serial port, our main program is as follows:

//import nedded libraries
import oscP5.*;
import netP5.*;
import processing.serial.*; 

OscP5 oscP5;
Serial serial;
RGBLayout layout;

//create 3 fader objects
Fader fdrRed;
Fader fdrGreen;
Fader fdrBlue;

//variables for each color
int r, g, b;
//PImage logo;

void setup() {
  size(600, 320);
  smooth();

  //create OSC object to open the 8000 port
  oscP5 = new OscP5(this, 8000);
  //create our custom template
  layout= new RGBLayout();
  //try to open serial port
  try {
    serial = new Serial(this, Serial.list()[0], 9600);
  }
  //in case of exception produced
  catch(Exception e) {
    println("Can't open port...");
  }
  //print addresses name and its position in vector
  layout.printAddr();

  //create the faders
  fdrRed=new Fader(10, 10, 'R');//px, py, color
  fdrGreen=new Fader(90, 10, 'G');
  fdrBlue=new Fader(170, 10, 'B');

  //load watermark
  //logo=loadImage("watermark.png");
}

void draw() {
  //draw the faders
  fdrRed.draw();
  fdrGreen.draw();
  fdrBlue.draw();

  //save each fader value using get
  r=fdrRed.getValue();
  g=fdrGreen.getValue();
  b=fdrBlue.getValue();

  //try to write serial port
  try {
    //command for red color and its value
    serial.write(114);
    serial.write(r);
    //command for green color and its value
    serial.write(103);
    serial.write(g);
    //command for blue color and its value
    serial.write(98);
    serial.write(b);
  }
  //n case of error, handle the exceptio
  catch(Exception e) {
    println("Can't write serial port...");
  }

  //draw a rect with the mixed colors
  stroke(0);
  fill(color(r, g, b));
  rect(270, 10, 300, 300);

  //image(logo, 450, 240);
}

//This event happens every time we receive data over OSC
//theOSCMessage contains all data received
void oscEvent(OscMessage theOscMessage) {
  //check if data matches with our template
  layout.check(theOscMessage);

  //faders take the value received
  fdrRed.setValue((int) layout.Data[0]);
  fdrGreen.setValue((int)layout.Data[1]);
  fdrBlue.setValue((int) layout.Data[2]);
}

Now arduino board must process the data received, for it will create an algorithm that receives a byte and determine whether it is a command, after waiting for another command determines the value stored in the corresponding variable to vary the intensity the LED will use the arduino PWM pins using the analogOut() function.

//incoming data
int inByte = 0;
//leds pins
int led[]={
  6,5,3};
//current led to modify
int  currLed;
//data received flag
boolean commandFlag=0;
//command indicator
const int ledCom=13;  

void setup()
{
  //Red led output
  pinMode(led[0], OUTPUT);
  //Green led output
  pinMode(led[1], OUTPUT);
  //Blue led output
  pinMode(led[2], OUTPUT);
  //command indicator output
  pinMode(ledCom, OUTPUT); 

  //Initializes serial communication at 9600bps
  Serial.begin(9600);
  Serial.print("Connected...");
}

void loop()
{
  //if data is available in port buffer
  if (Serial.available() > 0) {
    //read incoming byte
    inByte = Serial.read();

    //if the command expects a value
    if (commandFlag){
      //modify current led intensity
      analogWrite(led[currLed],inByte);
      //reset the flag and led indicator
      commandFlag=false;
      digitalWrite(ledCom, LOW);
    }
    //if expects a command
    else
    {
      //select led to modify
      //then make the command flag true
      switch (inByte){
      case 114://r ascii
        currLed=0;
        digitalWrite(ledCom, HIGH);
        commandFlag=1;
        break;
      case 103://g ascii
        currLed=1;
        digitalWrite(ledCom, HIGH);
        commandFlag=1;
        break;
      case 98://b ascii
        currLed=2;
        digitalWrite(ledCom, HIGH);
        commandFlag=1;
        break;
      }
    }
  }
}

Post your comments and suggestions. ;)

Popularity: 13%

Processing + Arduino + touchOSC

4

OSCgui
Hoy veremos la forma de comunicar nuestro dispositivo móvil android/ipad/iphone/iphone con nuestra PC, por medio de un protocolo conocido como OSC (Open Sound Control), comúnmente este protocolo se utiliza para el control de luminaria y dispositivos como estrobos, secuenciadores y otras cosas usadas en el mundo musical, se podría decir que es el reemplazo del protocolo MIDI. OSC usa el protocolo de internet UDP para realizar la comunicación, por esa razón como requisito necesitamos que los dispositivos se encuentran en la misma red, conocer su dirección IP y abrir un puerto de comunicación.

Para el siguiente acto necesitaremos: processing, arduino, led RGB, dispositivo con touchOSC instalado. Pero que haremos exactamente??… Crearemos una plantilla personalizada con el touchOSC editor, la cual usaremos como control para variar la intensidad de un led RGB y poder crear combinaciones de colores, abriremos un enlace de comunicación entre processing y touchOSC, por ultimo mandaremos toda la informacion recibida a una placa arduino conectada por el puerto serie y veremos el resultado obtenido en el led RGB, al final de todo esto tendremos el siguiente resultado:

(más…)

Popularity: 11%

Realidad aumentada con Processing

1
canartutorial

La realidad aumentada (RA) es el término que se usa para definir una visión directa o indirecta de un entorno físico del mundo real, cuyos elementos se combinan con elementos virtuales para la creación de una realidad mixta en tiempo real. Consiste en un conjunto de dispositivos que añaden información virtual a la información física ya existente, es decir, añadir una parte sintética virtual a lo real. Esta es la principal diferencia con la realidad virtual, puesto que no sustituye la realidad física, sino que sobreimprime los datos informáticos al mundo real.

Con la ayuda de la tecnología (por ejemplo, añadiendo la visión por computador y reconocimiento de objetos) la información sobre el mundo real alrededor del usuario se convierte en interactiva y digital. La información artificial sobre el medio ambiente y los objetos pueden ser almacenada y recuperada como una capa de información en la parte superior de la visión del mundo real.

Wikipedia

Desde el sitio de Creative Applications Network nos sorprenden con un excelente tutorial sobre realidad aumentada, usando processing y una librería llama NyArToolkit podemos aumentar nuestra realidad y añadir objetos 3D. Para esta aplicacion se utiliza la camara web y tags para identificar donde agregar los objetos virtuales.

Enlace | Tutorial AR con processing (Ingles)

Popularity: 8%

[Tutorial Processing] Ciclos

0
headerfor

En esta ocasión veremos una herramienta muy poderosa y útil de la programación que nos ahorrara mucho tiempo y simplificara nuestros programas. Cuando tenemos una tarea repetitiva los mas fácil seria copiar y pegar el mismo código para que se ejecute varias veces, pero eso implica un mal aprovechamiento de los recursos ademas de que nuestro código se vuelve ineficiente, para estos casos usaremos los ciclos for, while y do while. Empezaremos por la sintaxis de los ciclos for.

(más…)

Popularity: 4%

Ir arriba