Sunteți pe pagina 1din 48

DISERTANTES:

IEEE-UCSA 2015

Qu es processign?:
What is Processing?
From http://www.processing.org:
Processing is an open source programming language and environment for people
who want to program images, animation, and interactions.
It is used by students, artists, designers, researchers, and hobbyists for learning,
prototyping, and production.
It is created to teach fundamentals of computer programming within a visual
context and to serve as a software sketchbook and professional production tool.
Processing is developed by artists and designers as an alternative to proprietary
software tools in the same domain.

17/09/15

OBJETIVOS DE LA PRESENTACION: PODER UTILIZAR EL


SOFTWARE IDE + LEGUAJE PROCESSING PARA CONTROLAR LA
LOGICA DEL ARDUINO MEDIANTE EL PROTOCOLO FIRMATA.
Se necesitan para ello las libreras del Arduino del Estndar
Firmata y las libreras del Arduino para enviar los comando
que reconozcan el Arduino dentro del script Processing.
Siendo el processing parte del compilador Arduino.
Suena como trabalenguas, pero iremos viendo poco a poco.

17/09/15

ENTORNO DE PROGRAMACIN (IDE)

ENTORNO DE PROGRAMACIN (IDE)


Ejemplo: prog01_prueba.pde
Vamos a escribir un programa y lo vamos a
guardar con el nombre prog01_prueba.
ellipse(50, 50, 80, 80);

//ellipse(x,y,a,h);

http://processing.org/reference/ellipse_.html

Es un programa con una sola instruccin.


Otras primitivas bsicas de dibujo
- Punto
- Lnea

ENTORNO DE PROGRAMACIN (IDE)


Ejemplo: prog02_prueba.pde
Vamos a escribir un programa y lo vamos a
guardar con el nombre prog02_prueba.
void setup() {
size(480, 120);
}
void draw() {
if (mousePressed) {
fill(0);
} else {
fill(255);
}
ellipse(mouseX, mouseY,
80, 80);
}
6

ELEMENTOS DE PROGRAMACIN. SETUP()


Partes fundamentales de la estructura del
programa, son dos funciones: setup() y draw
().
1.- La funcin setup(). Esta funcin slo se
ejecuta unavoid
vez
setup() {
size(480, 120);
}

Esta funcin sirve para inicializar la aplicacin:


Definir el tamao del marco.
El color de fondo.

El color de relleno.

ELEMENTOS DE PROGRAMACIN. DRAW()


2.- La funcin draw().
Esta funcin se ejecuta continuamente
hasta que se produzca una parada. La
habitual es pulsar el icono de stop.
void draw() {
if (mousePressed) {
fill(0);
} else {
fill(255);
}
ellipse(mouseX, mouseY,
80, 80);
}

ELEMENTOS DE UN PROGRAMA. Resumen


- TIPOS DE DATOS (variables):
- int, long, float, char, boolean,
- array
- OPERADORES.
- Aritmticos, relacionales, lgicos,

ELEMENTOS DE UN PROGRAMA. Resumen


- ESTRUCTURAS DE CONTROL.
Delimitadores de bloque: { instrucciones; }
while:
while ( expr ) { instrucciones }
do { instrucciones } while ( expr )
for
for ( begin; end; inc ) {instrucciones }
if/else
if ( expr ) {instrucciones }
if ( expr ) {instrucciones } else { instrucciones }
switch
switch ( var ) { case val: instrucciones default: }
Saltos: break, continue, return
10

ELEMENTOS DE UN PROGRAMA. Resumen


- ESTRUCTURAS DE CONTROL.
Delimitadores de bloque: { instrucciones; }
while:
while ( test ) { instrucciones }
do { instrucciones } while ( test )
for
for ( begin; test; inc ) {instrucciones }
if/else
if ( test ) {instrucciones }
if ( test ) {instrucciones } else { instrucciones }
switch
switch ( val ) { case val_1: instrucciones default: }
Saltos: break, continue, return
11

PROCESSING 2D.
- SISTEMA DE COORDENADAS 2D.

El tamao de la ventana se establece con la funcin size(),


instruccin que se escribe en la funcin setup().
El (0,0), origen, se encuentra situado en la esquina superior
izquierda, donde las x son positivas hacia a la izquierda y las y
son positivas hacia abajo.

12

PROCESSING 2D.
- COLOR Y RELLENO.
El color de los trazos se determinan con la funcin stroke()
stroke(255) => RGB(255, 255, 255) especifica un valor
entre 0-256 niveles de gris.
stroke(128, 0, 128) => Cualquier valor RGB
El grosor de los trazos se puede caracterizar con
strokeWeight()
strokeWeight(5) => Grosor 5
El color de relleno de figuras 2D se especifica mediante la
funcin fill()
fill(128) => RGB(128, 128, 128)
fill(200, 120, 90) => RGB(200, 120, 90)

13

PROCESSING 2D.

background()
Borra la ventana con el color especificado
Ejemplos: background(0)
background(128, 100, 128)

noFill()
Las figuras 2D se dibujaran sin relleno

noStroke()
Las figuras 2D se dibujaran sin trazo (especialmente til en
figuras cerradas, pero afecta a todas, incluso a lneas)

14

PROCESSING 2D.
EJEMPLO SOBRE UNA LNEA
Escribimos un programa prog03_linea y vamos
aadiendo el siguiente cdigo.
size(100, 100);
background(0);
stroke(255);
strokeWeight(5);
line(0, 0, 99, 99);

//tamao de la ventana
//color de fondo
//color del trazo
//grosor del trazo

15

PROCESSING 2D.
EJEMPLO SOBRE UNA LNEA
Escribimos un programa prog04_linea y vamos
aadiendo el siguiente cdigo.
size(200, 200);
background(0);
//utilizamos una estructura de control repetitiva
for (int i=0; i<100; i++) {
stroke(random(255), random(255), random(255));
strokeWeight(random(10));
line(0, 0, random(200), random(200));
}

16

PROCESSING 2D.
ELIPSE Y CRCULOS

ellipse(x, y, ancho, alto)


Dibuja una elipse en las coordenadas (x, y) y el ancho y alto
suministrados

ellipseMode()
Cambia el modo en el que los parmetros de la elipse son
interpretados
ellipseMode(CENTER) => (x, y) es el centro de la elipse (es
elmodo por defecto).
ellipseMode(RADIUS) => igual que el anterior, pero ancho y
alto son radios y no dimetros
ellipseMode(CORNER) => (x, y) hace referencia a la esquina
superior izquierda del rectngulo envolvente de la elipse
ellipseMode(CORNERS) => los cuatro parmetros de la elipse
hacen referencia a dos puntos opuestos del rectngulo envolvente
de la elipse
17

PROCESSING 2D.
EJEMPLO DE ELIPSE Y CRCULOS
Escribimos un programa prog05_elipse y vamos
aadiendo el siguiente cdigo.
size(200, 200);
background(0);
stroke(255, 0, 0);
strokeWeight(5);
fill(0, 255, 0);

//color del trazo


//grosor

// (x, y) y dimetros
ellipse(100, 100, 100, 50);
// 2 esquinas opuestas
ellipseMode(CORNERS);
ellipse(0, 0, 50, 100);50);

18

PROCESSING 2D.
PRIMITIVAS DE 2D
Adems de las primitivas que hemos visto estn
tambin las siguientes:
Arcos
Rectngulos
Tringulos
Cuadrilteros
Curvas (Bzier y Catmull-Rom)
Shapes (formas libres)

19

MOVIMIENTO 2D.
float x=0; // coordenadas
float y=0;
float vy = 1; // velocidad eje X
float vx = 2; // velocidad eje y
void setup(){
size(300,300);
fill(255);
}
void draw(){
background(0);
x = x + vx;
y = y + vy;
ellipse(x,y,10,10);
}

20

Trabajaremos con el IDE Arduino y con el IDE Processing para Grficos en conjunto.
17/09/15

17/09/15

Metodos para controlar Arduino desde el IDE Processing:


Existen dos metodos para controlar Arduino dese processing:
1. Mediante la Librera Arduino para Processing
2. Mediante la lectura/escritura de datos a travs del puerto serie.

17/09/15

Firmata:
A generic protocol for communicating
with microcontrollers like the Arduino
from software on a host computer.
For the Arduino Library, it is included
in Arduino since version 0012, so see
the library reference page. For more
on the Firmata protocol, see
http://firmata.org.
17/09/15

Firmata is a generic protocol for communicating with


microcontrollers from software on a host computer. It is
intended to work with any host computer software package.
Right now there is a matching object in a number of
languages. It is easy to add objects for other software to use
this protocol. Basically, this firmware establishes a protocol
for talking to the Arduino from the host software. The aim is
to allow people to completely control the Arduino from
software on the host computer.
If you are interested, we can help you use this protocol with
any software whatsoever. The protocol is quite simple. We
will all benefit if we use a common firmware. Then
microcontroller boards become really cheap sensorboxes in
addition to all the rest of the stuff you can already do with
them. Check out the Examples page to see Firmata in action.
17/09/15

17/09/15

REFERENCIAS:
INFORMACIN PARA CONFIGURAR PROCESSING :
http://playground.arduino.cc/Interfacing/Processing
BAJAR EL PROCESSING:
https://processing.org/download/

17/09/15

CODIGO PROCESSING CON LIBRERIAS DE ARDUINO.


import processing.serial.*;
import cc.arduino.*;
Arduino arduino;
int ledPin = 13;
void setup()
{
//println(Arduino.list());
arduino = new Arduino(this, Arduino.list()[0], 57600);
arduino.pinMode(ledPin, Arduino.OUTPUT);
}
void draw()
{
arduino.digitalWrite(ledPin, Arduino.HIGH);
delay(1000);
arduino.digitalWrite(ledPin, Arduino.LOW);
delay(1000);
}17/09/15

Antes de nada debemos realizar los siguientes pasos para acondicionar el


entorno Processing:
a.CARGAR LA LIBRERIA ARDUINO EN EL IDE DE PROCESSING:
No debemos olvidarnos antes de nada de cargar el firmare correspondiente en
Arduino. El fichero de la librera Arduino para Processing esta en el archivo
processing-arduino o arduino-processing-e231 que se encuentra en la pgina de
arduino. Dentro de ellos hay una carpeta que se llama Arduino y contiene la
librera. (\processing-arduino\arduino o \arduino-processing-e231\arduino).
http://www.arduino.cc/playground/uploads/Interfacing/processing-arduino.zip
Para que Processing pueda trabajar con la librera de Arduino debemos incluir la
carpeta Arduino dentro de la carpeta libreras del IDE Processing:
\processing-0138\libraries
RESUMIENDO: A)DESCARGAR EL IDE PROCESSING 2 B) INSTALAR EL PLUG IN
ARDUINO DIRECTAMENTE DESDE EL IDE PROCESSING, MAS FACIL QUE
SEGUIR ESTOS PASOS DE LA REFERENCIA. Y LISTO. YA ESTA PREPARADO PARA
REALIZAR SUS PROGRAMAS DIRECTAMENTE DESDE EL PROCESSING 2.

17/09/15

b. CONFIGURAR ARDUINO PARA QUE PROCESSING PUEDA


DIALOGAR CON EL PROCESSING 2.
Para cargar el firmware en Arduino nos vamos a la librera
processign-arduino y en la carpeta
\arduino\firmware\Standard_Firmata se encuentra el
fichero
Standard_Firmata.pde
EDITAR EL PROGRAMA Y TRANSFERIRLO AL ARDUINO.

17/09/15

COPIAR EL SIGUIENTE CODIGO AL PROCESSING 2. Y EJECUTARLO.


import processing.serial.*;
import cc.arduino.*;
Arduino arduino;
int ledPin = 13;
void setup()
{
//println(Arduino.list());
arduino = new Arduino(this, Arduino.list()[0], 57600);
arduino.pinMode(ledPin, Arduino.OUTPUT);
}
void draw()
{
arduino.digitalWrite(ledPin, Arduino.HIGH);
delay(1000);
arduino.digitalWrite(ledPin, Arduino.LOW);
delay(1000);
}17/09/15

Su primera aplicacin con


processing 2 est realizada!!!

17/09/15

Referencia de las funciones de la librera Arduino para Processing 2:


Las siguientes funciones se encuentran en la Librera Arduino para
Processing y comunican (a partir de Processing) con un Arduino, una vez
que el Firmata se ha instalado en la tarjeta.
Arduino.list():devuelve una lista con los dispositivos serie (puertos serie)
disponibles. Su tarjeta Arduino est conectada a la computadora cuando
usted llama a esta funcin, su dispositivo estar en la lista.
Arduino(parent, name, rate): crea un objeto Arduino (objeto a nivel de
elemento de programacin). parent debe aparecer sin comillas; name es el
nombre del dispositivo serie (es decir, uno de los nombres devueltos por
Arduino.list ()); rate es la velocidad de la conexin (57600 para la versin
actual del de firmware).
pinMode(pin, mode): pin configura un pin digital como entrada (input) o
como salida (output) mode (Arduino.INPUT o Arduino.OUTPUT).

17/09/15

digitalRead(pin): devuelve el valor ledo de una de las entradas digitales,


Arduino.LOW o bien Arduino.HIGH (el pin debe estar configurado como
entrada).
digitalWrite(pin, value): escribe Arduino.LOW o Arduino.HIGH en un pin
digital.
analogRead(pin): devuelve el valor de una entrada analgica leda (de 0 a
1023).
analogWrite(pin, value): escribe un valor analgico (seal tipo PWM) en un
pin digital que soporta salida analgica (pines 3, 5, 6, 9, 10, y 11 para ATMEGA
168); valores debes estar comprendidos entre 0 (equivalente a off) y 255
(equivalente a on).

17/09/15

NOTA: OTRA FORMA DE PROCESAR CON EL ARDUINO CON EL PROCESSING 2:


Se puede controlar Arduino desde Processing sin necesidad de incluir la
libraria Arduino en processing, en este caso se trata de recoger datos del
puerto que la tarjeta Arduino envia al puerto serie.
Procedimiento:
1.- Se carga en la tarjeta Arduino el programa que se encargue de escribir en
el puerto el dato que despus leera Procesing y lo incorporara en el
programa que este ejecutando.
2.- Cargar y ejecutar el programa en el IDE Processing que recoger los datos
que Arduino le enva por el puerto serie.

17/09/15

EMPEZAREMOS A REALIZAR
UNA SERIE DE EJECICIOS
PRACTICOS

17/09/15

/*
* enciende el led cuando se presiona el botn del ratn
* apaga cuando levantamos el botn
*/
import processing.serial.*; //Importamos las libreras necesarias
import cc.arduino.*;
Arduino arduino; // Crea el objeto Arduino
int ledPin = 13; // Designa el numero de PIN para el LED
void setup() { //Configura el puerto y las seales con las que va a trabajar
size(200, 200);
arduino = new Arduino(this, Arduino.list()[0], 57600);
arduino.pinMode(ledPin, Arduino.OUTPUT); // Configura el PIN13 como salida
arduino.digitalWrite(ledPin, Arduino.HIGH); //Enciende el LED
}
void draw() { //Dibuja una ventana de interaccin
if (mousePressed == true) { //pregunta si se ha pulsado el botn del ratn
arduino.digitalWrite(13,Arduino.LOW); // Si se ha pulsado apaga el LED
} else {
arduino.digitalWrite(13,Arduino.HIGH); // Si no esta pulsado enciende el LED
}
}
17/09/15

/** Raton sin presionar-> LED off


**/
import processing.serial.*;
import cc.arduino.*;
Arduino arduino;
int ledPin = 13;
void setup() {
size(200, 200);
arduino = new Arduino(this, Arduino.list()[0], 57600);
arduino.pinMode(ledPin, Arduino.OUTPUT);
arduino.digitalWrite(ledPin, Arduino.HIGH);
}
void draw() {}
void mousePressed() { // Procedimiento para botn pulsado
arduino.digitalWrite(ledPin, Arduino.LOW);
}
void mouseReleased() { //Procedimiento para botn levantado
arduino.digitalWrite(ledPin, Arduino.HIGH);
}

17/09/15

/* * El led se enciende y apaga al cambiar el estado del ratn (conmutador on/off)


**/
import processing.serial.*;
import cc.arduino.*;
Arduino arduino;
int ledPin = 13;
boolean isLedOn = false;
void setup() {
size(200, 200);
arduino = new Arduino(this, Arduino.list()[0], 57600);
arduino.pinMode(ledPin, Arduino.OUTPUT);
arduino.digitalWrite(ledPin, Arduino.HIGH);
}
void draw() {}
void mousePressed()
{ //Procedimiento para testear el estado del ratn
if(isLedOn)
{arduino.digitalWrite(ledPin, Arduino.HIGH);}
else
{ arduino.digitalWrite(ledPin, Arduino.LOW); }
isLedOn = !isLedOn;
}
17/09/15

/*
* Al pulsar con el ratn de forma conmutada el LED parpadea
*/
import processing.serial.*;
import cc.arduino.*;
Arduino arduino;
int ledPin = 13;
boolean blinkLed = false; //Variable que indica si el LED esta parpadeando
void setup() {size(200, 200);
arduino = new Arduino(this, Arduino.list()[0], 57600);
arduino.pinMode(ledPin, Arduino.OUTPUT);
arduino.digitalWrite(ledPin, Arduino.LOW); }
void draw() {
if(blinkLed) {
arduino.digitalWrite(ledPin, Arduino.LOW);
delay(50);
arduino.digitalWrite(ledPin, Arduino.HIGH);
delay(50);
} else {arduino.digitalWrite(ledPin, Arduino.LOW);}
}
void mousePressed() { // Detecta si el ratn esta pulsado
blinkLed = !blinkLed;
}17/09/15

17/09/15

import processing.serial.*; import cc.arduino.*; Arduino arduino;


color off = color(4, 79, 111); // Definimos los colores del botn en estado off
color on = color(84, 145, 158); // Definimos los colores del botn en estado on
// designamos en un array de tamao 13 el estado de cada una de las entradas
int[] values = { Arduino.LOW, Arduino.LOW, Arduino.LOW, Arduino.LOW,
Arduino.LOW, Arduino.LOW, Arduino.LOW, Arduino.LOW, Arduino.LOW,
Arduino.LOW, Arduino.LOW, Arduino.LOW, Arduino.LOW, Arduino.LOW };
void setup() {size(470, 200); arduino = new Arduino(this, Arduino.list()[0], 57600);
for (int i = 0; i <= 13; i++){arduino.pinMode(i, Arduino.OUTPUT);}
void draw() {background(off); stroke(on);
for (int i = 0; i <= 13; i++) {
if (values[i] == Arduino.HIGH) fill(on); else fill(off);
rect(420 - i * 30, 30, 20, 20);}
}
// Procedimiento para detectar si el ratn se ha pulsado sobe uno de los botones
void mousePressed() { int pin = (450 - mouseX) / 30;
if (values[pin] == Arduino.LOW) {arduino.digitalWrite(pin, Arduino.HIGH);
values[pin] = Arduino.HIGH;} else {arduino.digitalWrite(pin, Arduino.LOW);
values[pin] = Arduino.LOW;}
}

17/09/15

/*
* encendido y apagado gradual de un LED - PWM */
import processing.serial.*; import cc.arduino.*; Arduino arduino;
int pwm=0; //Variable nivel de iluminacin del LED
int ledPin=9;
boolean rising=true; // indica si el encendido es hacia arriba de 0-255
void setup() {size(200, 200);
arduino = new Arduino(this, Arduino.list()[0], 57600);
arduino.pinMode(ledPin, Arduino.OUTPUT);
arduino.analogWrite(ledPin, pwm);
}
void draw() {
arduino.analogWrite(ledPin, pwm); // Escribe el valor pwm en la salida PIN9 del
LED
println(pwm); // Escribe en la ventana de datos el valor de la variable pwm
if(rising) { // contador ascendente hasta llegar a 255
pwm+=2;
if(pwm>=255) {
rising=false;
}}else {pwm-=2; // contador descendente hasta llegar a 0
if(pwm<=0) {rising=true;}}}
17/09/15

17/09/15

/*
* Gobierno del nivel de encendido de un led mediante un potencimetro
*/
import processing.serial.*;import cc.arduino.*;
Arduino arduino;int ledPin=9; int potPin=0;int val;
void setup() {size(200, 200);
arduino = new Arduino(this, Arduino.list()[0], 57600);
arduino.pinMode(ledPin, Arduino.OUTPUT);}
void draw() {
//lee la seal del potenciometro (0..1024), divide por cuatro (0..255)
val = arduino.analogRead(potPin)/4;
/envia al LED el valor leido y ajustado (0..255) seal PWM
arduino.analogWrite(ledPin, val);
//varia la intensidad del color de la ventana de processing
background(255-val,0,0);
}

17/09/15

Lectura de un sensor y representacin en


modo grafico
y texto del valor ledo.

17/09/15

/**
* Representacin de valor procedente de un sensor.
*/
import processing.serial.*;import cc.arduino.*; int[] xvals; // SAVE valores ledos
int val; // Valor ledo
int arrayindex = 0; // Puntero o ndice del array
Arduino arduino;
int potPin=0;
void setup(){size(256, 256);xvals = new int[width];
arduino = new Arduino(this, Arduino.list()[0], 57600);}
void draw(){background(0); // shift array left by one
for(int i=1; i<width; i++) {xvals[i-1] = xvals[i];}
// aade un nuevo valor al final del array - //lee la entrada analgica (0..1024),
divide su valor por 4 (0..255) // to stay within canvas drawing limits
val = arduino.analogRead(potPin);
xvals[width-1] = val/4;
// dibuja el array
for(int i=1; i<width; i++) {stroke(255);
point(i, 255-xvals[i]); //flip y coordinate so 0 is at bottom
}
textAlign(RIGHT);
text(val, 200, 30);
text(5.0*(xvals[width-1]/255.0)+"V",200,60);
}
17/09/15

17/09/15

S-ar putea să vă placă și