logoTh!nk Again


Controlando led RGB al ritmo de la música

Posted in Arduino, Prácticas by admin on the March 19th, 2009

La idea principal del proyecto es armar una lámpara usando un led RGB. El color de la lámpara varía (verde, azul, rojo) dependiendo de la forma de la onda del sonido al reproducir un archivo mp3.

Por lo que dividimos el proyecto en 2 fases:

  • La primera fase consiste en cargar el archivo mp3, reproducirlo, obtener los valores de la onda y por último enviar el color en hexadecimal de forma serial al arduino.
  • En la segunda fase se trabaja sobre el arduino, se descompone el color (en R, G y B) se envían los valores a las salidas PWM (pines 9, 10 y 11).

Para más detalles de la segunda fase, consulten el capítulo 6 del siguiente libro, en la página 73:

ver capítulo 6. talking to the cloud, pág. 73

ver capítulo 6. talking to the cloud, pág. 73

Para la primera fase utilice la librería de audio Minim, consulten este ejemplo antes para comprender el funcionamiento: Examples->Library->Minim->LoadFile.

Motivación

Código aplicación en Processing

/*Dennys Regalado Díaz
  19/03/09
  Mapea onda de sonido a un color RGB y
  se lo envía por serial al Arduino Duemilanove
  Utiliza libreria Minim y parte del código de los ejemplos.
*/

import processing.serial.*;
import ddf.minim.*;

AudioPlayer player;
Minim minim;

Serial port;
int r,g,b,c,last_color=-1;
String cs;

void setup()
{
  size(512, 200,P3D);
  background(0);
  stroke(255);
  minim = new Minim(this);
  player = minim.loadFile("/home/dennys/Music/slipknot 2008/04. Psychosocial.mp3", 2048);
  player.play();
  //configura puerto serial
  println(Serial.list());
  port = new Serial(this, Serial.list()[0], 9600);
}

void draw()
{
  int sum=0;
  //Dibuja ondas de audio, tomado del ejemplo Libraries->Minim(Sound)->Load File
  for(int i = 0; i < player.left.size()-1; i++)
  {
    line(i, 50 + player.left.get(i)*50, i+1, 50 + player.left.get(i+1)*50);
    line(i, 150 + player.right.get(i)*50, i+1, 150 + player.right.get(i+1)*50);
    sum+=player.left.get(i)+player.right.get(i);
  }
  if(sum>10){
    r=255;
    g=b=0;
  }else if(sum>0){
    b=255;
    r=g=0;
  }
  else{
    g=255;
    r=b=0;
  }
  c = color(r,g,b);
 
  if(c!=last_color){
    cs = "#" + hex(c,6);
    port.write(cs);
    last_color=c;
  }
}


void stop()
{
  player.close();
  minim.stop()
  super.stop();
}

Código para el Arduino

/*Extracto del Ejemplo 6-1 Getting Started with Arduino,
http://www.makezine.com/getstartedarduino
Arduino networked lamp parts of the code
are inspired by a blog post by Tod E. Kurt (todbot.com)
*/

//puertos: 9,10,11 son por default salidas
#define R_LED 9
#define G_LED 10
#define B_LED 11
char buffer[7] ;
int pointer = 0;
byte inByte = 0;
byte r = 0;
byte g = 0;
byte b = 0;
void setup() {
  Serial.begin(9600); // open the serial port   
}
void loop() {
  // the serial port
  if (Serial.available() >0) {
    // read the incoming byte:
    inByte = Serial.read();
    // If the marker's found, next 6 characters are the colour
    if (inByte == '#') {
      while (pointer < 6) { // accumulate 6 chars
        buffer[pointer] = Serial.read(); // store in the buffer
        pointer++; // move the pointer forward by 1
      }
      // now we have the 3 numbers stored as hex numbers
      // we need to decode them into 3 bytes r, g and b
      r = hex2dec(buffer[1]) + hex2dec(buffer[0]) * 16;
      g = hex2dec(buffer[3]) + hex2dec(buffer[2]) * 16;
      b = hex2dec(buffer[5]) + hex2dec(buffer[4]) * 16;
      pointer = 0; // reset the pointer so we can reuse the buffer
    }
  }
  analogWrite(R_LED, r); // turn the leds on
  analogWrite(G_LED, g); // at the colour
  analogWrite(B_LED, b); // sent by the computer
  delay(10);              // wait 100ms between each send
}
int hex2dec(byte c) { // converts one HEX character into a number
  if (c >= '0' && c <= '9') {
    return c - '0';
  }
  else if (c >= 'A' && c <= 'F') {
    return c - 'A' + 10;
  }
}

Probando el servo motor

Posted in Arduino, Prácticas by admin on the March 15th, 2009

Sólo usé el código de ejemplo que incluye el IDE del arduino y listo!
Motivación

Materiales

Desarrollo
Así me quedó el circuito

Diagrama del circuito

Diagrama del circuito

Este es el código de ejemplo que viene con el IDE, Examples->Library-servo->Knob

// Controlling a servo position using a potentiometer (variable resistor)
// by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>

#include <Servo.h>
 
Servo myservo;  // create servo object to control a servo
 
int potpin = 0// analog pin used to connect the potentiometer
int val;    // variable to read the value from the analog pin
 
void setup()
{
  myservo.attach(9)// attaches the servo on pin 9 to the servo object
}
 
void loop()
{
  val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023)
  val = map(val, 0, 1023, 0, 179);     // scale it to use it with the servo (value between 0 and 180)
  myservo.write(val);                  // sets the servo position according to the scaled value
  delay(15);                           // waits for the servo to get there
}

Processing + Arduino

Posted in Arduino, Processing, Prácticas by admin on the March 15th, 2009

Introducción

Después de una semana de tener el Arduino Duemilinove, por fin me decidí a realizar una pequeña aplicación, la cuál consiste en interfazar el Arduino con un sketch de Processing.

Objetivos

Encender y apagar los segmentos de un display de ánodo común mediante una interfaz construida en Processing
Motivación

Materiales

DA05

DA05

tarjeta arduino

tarjeta arduino

Desarrollo

Lo dividí en dos fases:

  1. Interfaz en processing que permite establecer el estado de los segmentos (on/off) a través de un click, funciona como un toggle button.
  2. Programa para el arduino que recibe la configuración y actualiza el estado del display.

Este es el código en processing, creé una clase segmento para hacerlo más fácil.

class Segmento{
  float x,y,alto,ancho;
  int color_current;
  boolean over= false;
  boolean presionado = false;
  final int color_on=#FF0000,
            color_off=#999999,
            color_over=color(102,255,0,246);
  Segmento(float x, float y, float w, float h){
    this.x = x;
    this.y = y;
    alto = h;
    ancho = w;
    color_current = color_off;
  }
  void display(){
    stroke(color_current);
/*    if(presionado)
      fill(color_on);
    else
      fill(color_off);*/

    fill(color_current);
    rect(x,y,ancho,alto);
  }
  void update(){
    if(isOver()){
      color_current= color_over;
    }
    else if(presionado)
      color_current = color_on;
    else
      color_current= color_off;       
     
    if(mousePressed && isOver() && !locked){     
      presionado = !presionado;     
    }   

  }
  boolean encendido(){
    return presionado;
  }
  boolean pressed()
  {
    locked = over;
    return locked;
  }
 
  boolean isOver(){
    over = (mouseX>=x && mouseX<=x+ancho && mouseY>=y && mouseY<=y+alto);
    return over;
  }
}

y esté es el código del sketch principal

/*Test display DA05 usando Arduino Duemilanove
  por Dennys Regalado Díaz
  10/03/09
*/


import processing.serial.*;
 
Serial port;
boolean locked=false;
Segmento dis7seg[];
void setup(){
  size(200,250);
  smooth();
  background(0);
  dis7seg = new Segmento[7];
  dis7seg[0] = new Segmento(55,13.620,90,13); //a
  dis7seg[1]=new Segmento(145.036,26.659,13,90); //b
  dis7seg[2]=new Segmento(145,129.961,13,90); //c
  dis7seg[3]=new Segmento(55,220,90,13); //d
  dis7seg[4]=new Segmento(42.253,129.961,13,90); //e 
  dis7seg[5]=new Segmento(42.253,26.659,13,90);//f
  dis7seg[6]=new Segmento(55,116.712,90,13); //g

  println(Serial.list());
  port = new Serial(this, Serial.list()[0], 9600);


}
//escribe un número de segmento al puerto, si está encendido
void draw(){
  update();

  for(int i=0; i<7; i++){
    dis7seg[i].display();
    if(dis7seg[i].encendido()){
      port.write('L');
    }else
      port.write('H');
  }
 
}

void update(){
  int i;
  if(locked == false) {
    for(i=0; i< 7; i++){
      dis7seg[i].update();   
    }
  }
  else {
    locked = false;
  }

  if(mousePressed) {
    //raliza el bloqueo si se esta presionando un segmento
    for(i=0; i<7; i++){
      if(dis7seg[i].pressed()){
        break;
      }
    }
 
  }
}

Por último, el código para el arduino

int pins[] = { 2, 3, 4, 5, 6, 7, 8 }; // an array of pin numbers
int num_pins = 7;
int val,i;
void setup()
{
  Serial.begin(9600);
  for(i=0; i<num_pins; i++)
    pinMode(pins[i], OUTPUT);
}

void loop()
{
  while(Serial.available() ){
    i%=7;
      val = Serial.read();
      if(val=='L')
        digitalWrite(pins[i],LOW);
      else if(val=='H')
        digitalWrite(pins[i],HIGH);
      i++;   
  }
}