miércoles, 12 de diciembre de 2012

LABORATORIO # 8

En este laboratorio  vamos controlar con el Arduino una la reproducción de una canción en un Piezo (Buzzer) o un Speaker la melodia (Inspector Gadget).



MATERIALES QUE SE USARON 

- 1 Piezo (Buzzer)

- Placa Arduino UNO



DIAGRAMA DEL LABORATORIO



ESQUEMA DEL LABORATORIO








CODIGO DEL LABORATORIO



 //     LA PANTERA ROSA
#define  c3    7634
#define  d3    6803
#define  e3    6061
#define  f3    5714
#define  g3    5102
#define  a3    4545
#define  b3    4049
#define  c4    3816    // 261 Hz
#define  c4s   3607    // 277,183 Hz
#define  d4    3401    // 294 Hz
#define  d4s   3214    // 311,127 Hz 
#define  e4    3030    // 329 Hz 
#define  f4    2865    // 349 Hz 
#define  f4s   2702    // 369 Hz 
#define  g4    2551    // 392 Hz
#define  g4s   2407    // 405 Hz
#define  a4    2272    // 440 Hz 
#define  a4s   2146
#define  b4    2028    // 493 Hz 
#define  c5    1912    // 523 Hz
#define  d5    1706
#define  d5s   1608
#define  e5    1517
#define  f5    1433
#define  g5    1276
#define  a5    1136
#define  a5s   1073
#define  b5    1012
#define  c6    955
    #define  R     0//defino el silencio
    int salida = 2;//pin de salida
    void setup() {
      pinMode(salida, OUTPUT);
    }
    //declaro la cancion en melodia con las notas y el tiempo de duracion
    //super mario
    int melody[] = {R,c4s,d4,d4s,e4,R,c4s,d4,d4s,e4,R,e4,d4s,d4,c4s,R,c4s,d4,d4s,e4,R,R,d4s,e4,R,f4s,g4,R,d4s,e4,f4s,g4,c5,b5,d4,g4,b4,a4s,R,a4s,b4,f4s,e4,f4s,R};
    int beats[] = {16,16,16,16,224,128,16,16,16,224,128,16,16,16,224,16,16,16,16,128,192,16,16,32,16,16,32,16,16,16,16,16,16,16,16,16,16,74,10,10,10,10,10,74,220};
     
    int tamanoTotal = 45; //tamaño  de la cancion
    long tiempo = 30000;//defino el tiempo para cada toque
    int pause = 1000; //el tiempo para volver a reproducir
    int rest_count = 10; // declaro variables para la reproduccion
    int toneM = 0;
    int beat = 0;
    long duration  = 0;
     
    //metodo que reproduce la cancion nota por nota
    void playTone() {
      long elapsed_time = 0;// el tiempo que va corriendo
      if (toneM > 0) {
        while (elapsed_time < duration) {//mientras que llegue al tiempo esperado
          digitalWrite(salida,HIGH);
          delayMicroseconds(toneM /5);
          digitalWrite(salida, LOW);
          delayMicroseconds(toneM /5);
     
          elapsed_time += (toneM);//sumo el tono o su frecuencia para el tiempo
        }
      }
      else {
        for (int j = 0; j < rest_count; j++) {
          delayMicroseconds(duration);  //cuando termine de reproducir la cancion espero unos segundos
        }                                
      }                                
    }
     
    void loop() {
      for (int i=0; i
        toneM = melody[i];//saco cada nota con su respectivo tiempo
        beat = beats[i];
        duration = beat * tiempo; // Set up timing
        playTone();
        delayMicroseconds(pause);
      }
    }


VIDEO DEL LABORATORIO








LABORATORIO # 7

En este laboratorio  vamos controlar con el Arduino un Motor DC usando un motor shield L293D , cambiando la direccion de giro  y un punto de detencion




MATERIALES QUE SE USARON


- 1  motor shield L293D

- Placa Arduino UNO

-1 Potenciometro 10 K

CODIGO DEL LABORATORIO


#include

AF_DCMotor motor(2, MOTOR12_64KHZ); // create motor #2, 64KHz pwm
int pot = A1;
int valpot =0;


// se ejecuta 1 sola vez, al iniciar el programa
void setup() {
    pinMode(pot, INPUT);
   
    
}

// se repite infinitamente mientras el arduino tenga corriente
void loop() {
  
  valpot= analogRead(pot);
  
  if( valpot >= 0  && valpot <401 font="font">
          {
             int indice = map(valpot,400,0,0,255 );
             motor.setSpeed(indice);     // set the speed to 200/255   
             motor.run(BACKWARD);    
            
            
          }      
          else if(valpot > 400  && valpot < 625)
          {
            int indice = map(valpot,401,624,0,255 );
             motor.run(RELEASE);      // stopped
            // the other way
                             
          }
          else if(valpot > 624  && valpot < 1024)
          {
            int indice = map(valpot,625,1023,0,255 );
            motor.run(FORWARD);
              
         }
  
  
  
  
  
  
}

FOTOS DEL MONTAJE






VIDEO DEL MONTAJE


ESQUEMA LABORATORIO


DIAGRAMA LABORATORIO


martes, 11 de diciembre de 2012

LABORATORIO # 6


 En este laboratorio se va hacer Igual al Laboratorio 4, pero usando un IC 74HC595 (Shift Register).


METARIALES QUE SE USARON

1 arduino

8 leds 

1 cable usb

1 protoboard

12 cables utp

8 resistencias

1 pc con el programa procesing

FOTOS DEL ENSAMBLAJE









VIDEO DEL MONTAJE


CODIGO QUE SE USO


Codigo fuente arduino:

//Pin connected to ST_CP of 74HC595
int latchPin = 8;
//Pin connected to SH_CP of 74HC595
int clockPin = 12;
////Pin connected to DS of 74HC595
int dataPin = 11;
// variable tipo char para obtener que slide se esta usando en el proccesing
char res;
//variables donde se guardan el valor que indica cada slide
int encendido=128, apagado=128;
const int MAXLED = 8;
// arreglo de 8 LEDs, desde el pin 2 hasta el pin 9
int led[MAXLED] = {1,2,4,8,16,32,64,128};
void setup() {
  //set pins to output so you can control the shift register
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
   for (int i=0; i   pinMode(led[i], OUTPUT);
   Serial.begin(9600);
}
void loop() {
  // count from 0 to 255 and display the number
  // on the LEDs
 
 for (int i=0; i    leerDatos();
   // take the latchPin low so
    // the LEDs don’t change while you’re sending in bits:
    digitalWrite(latchPin, LOW);
    delay(apagado);
 
 
    // shift out the bits:
    shiftOut(dataPin, clockPin, MSBFIRST,led[i]);
    //take the latch pin high so the LEDs will light up:
    digitalWrite(latchPin, HIGH);
    // pause before next value:
    delay(encendido);
 }

 for (int i=MAXLED-2; i>0; i–) {
   leerDatos();
    // take the latchPin low so
    // the LEDs don’t change while you’re sending in bits:
    digitalWrite(latchPin, LOW);
    delay(apagado);
    // shift out the bits:
    shiftOut(dataPin, clockPin, MSBFIRST,led[i]);
    //take the latch pin high so the LEDs will light up:
    digitalWrite(latchPin, HIGH);
    // pause before next value:
    delay(encendido);
 }

}

 void leerDatos(){
  if (Serial.available()>0) {
    res=Serial.read();
    if (res==’e') {
      encendido = Serial.read();
    }
    else if (res==’a') {
      apagado = Serial.read();
    }
  
  }
}

Codigo fuente processing:

import processing.serial.*;
import controlP5.*;
//se crea una variable port de tipo serial 
//para despues establecer la conexion 
Serial port;
//se crea una variable cp5 
//para despues establecer el control slide
ControlP5 cp5;
//se crea una variable
int valor=0; 
int valor_anterior=-1;
void setup() {
  //tamanho  de la ventana
  size(600, 200);
  
  noStroke();  
  //se crea la instancia del port y se le mandan atributos importantes 
  port = new Serial(this, Serial.list()[1], 9600);
  //se modifican los controles
  cp5 = new ControlP5(this);
  cp5.addSlider(“e”)
    .setPosition(40, 40)
    .setWidth(500)
    .setHeight(20)
    .setRange(0, 255)
    .setValue(128)
    .setSliderMode(Slider.FLEXIBLE);
    
  cp5.addSlider(“a”)
    .setPosition(40, 140)
    .setWidth(500)
    .setHeight(20)
    .setRange(0, 255)
    .setValue(128)
    .setSliderMode(Slider.FLEXIBLE);
}
void draw() {
  //color del fondo
  background(100);
}
//metodo para el control de eventos
public void controlEvent(ControlEvent theEvent) {
 //valido la condicion
  if(“e” == theEvent.getController().getName())
  {
      //mando por el serial la ‘e’
      port.write(‘e’);      
  }
  else if (“a” == theEvent.getController().getName())
  {
      //mando por el serial la ‘a’
      port.write(‘a’);
  }
    
  valor = int(theEvent.getController().getValue());
    if (valor != valor_anterior)  
    { 
      port.write(valor);
      valor_anterior = valor;
    }
 
}

DIAGRAMA DEL LABORATORIO





ESQUEMA DEL LABORATORIO


















LABORATORIO # 5

en este laboratorio se va  hacer Igual al Lab2, pero usando un IC 74HC595 (Shift Register).


MATERIALES QUE SE USARON






1 arduino


8 leds 

1 cable usb

1 protoboard

12 cables utp

8 resistencias

1 Potenciometro 10K

Shift Register

IMAGENES EN TIEMPO REAL DEL ENSAMBLAJE







VIDEOS EN TIEMPO REAL DEL FUNCIONAMIENTO




CODIGO QUE SE USO


const int MAXLED = 8;
//Pin connected to ST_CP of 74HC595 --- pin 12
int latchPin = 8;
//Pin connected to SH_CP of 74HC595 -- pin 11
int clockPin = 12;
////Pin connected to DS of 74HC595  --pin 14
int dataPin = 11;
//se asigna a una variable el puerto análogo del arduino 
int pot = A4;
// se guarda la lectura del potenciometro
int valpot =0;

// arreglo de 8 LEDs
int led[MAXLED] = {1,2,4,8,16,32,64,128};

//primera secuencia : arreglo de un led de por medio
int ledS1[14] = {1,2,4,8,4,2,1,16,32,64,128,64,32,16};


//segunda secuencia : arreglo de un leds de los extremos al medio
int ledS2[MAXLED] = {2,4,8,16,128,64,32,16};


//tercera secuencia
int ledS3[MAXLED] = {1,4,16,64,2,8,32,128};

//cuarta secuencia
int ledS4[MAXLED] = {2,4,128,64,8,16,32,1};




// se ejecuta 1 sola vez, al iniciar el programa
void setup() {
  //set pins to output so you can control the shift register
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(pot, INPUT);
}




// se repite infinitamente mientras el arduino tenga corriente
void loop() { 
// recorre desde el indice 0 hasta el 7   
for (int i=0; i
  
     digitalWrite(latchPin, LOW);
    delay(100);
    // shift out the bits:
    shiftOut(dataPin, clockPin, MSBFIRST,led[i]); 
    //take the latch pin high so the LEDs will light up:
    digitalWrite(latchPin, HIGH);
    // pause before next value:
    delay(100);
  
         
       
        //se hace una lectura del potenciometro
          valpot = analogRead(pot);
        //se evalua,  dependiendo del valor del potenciometro
        // se le asigna una secuencia   
          if( valpot > 0  && valpot <256 span="span">
          { secuenciaUno(); }      
          else if(valpot > 256  && valpot < 512)
          {  secuenciaDos();}
          else if(valpot > 512  && valpot < 768)
          {  secuenciaTres();}
         else if(valpot > 768  && valpot < 1024)
         {  secuenciaCuatro();}
         
 }

 // recorre desde el indice 6 hasta el 1, para no repetir los extremos 
 for (int i=MAXLED-2; i>0; i--) {
    // take the latchPin low so 
    // the LEDs don't change while you're sending in bits:
    digitalWrite(latchPin, LOW);
    delay(100);
    // shift out the bits:
    shiftOut(dataPin, clockPin, MSBFIRST,led[i]); 

    //take the latch pin high so the LEDs will light up:
    digitalWrite(latchPin, HIGH);
    // pause before next value:
    delay(100);
  }



}



// métodos propios --------------------------------------------

//secuencia I
void secuenciaUno(){
   uno:
  //recorre el arreglo donde se difinio la secuencia 
   for (int i=0; i<14 i="i" span="span">
     
     // take the latchPin low so 
  // the LEDs don't change while you're sending in bits:
  digitalWrite(latchPin, LOW);
  delay(500);
  // shift out the bits:
  shiftOut(dataPin, clockPin, MSBFIRST, ledS1[i]);  
  //take the latch pin high so the LEDs will light up:
  digitalWrite(latchPin, HIGH);
  delay(700);   
  }  

     //se hace una lectura previa para saber 
     //si todavia se esta ejecutando la secuencia actual
     valpot = analogRead(pot); 
     if( valpot > 0  && valpot <256 nbsp="nbsp" span="span">
     goto uno; }         
}



//secuencia II
void secuenciaDos(){  
   
   
  
  dos:  
 //recorro ciclo de los leds
 for (int i=0; i
  
   
   // take the latchPin low so 
  // the LEDs don't change while you're sending in bits:
  digitalWrite(latchPin, LOW);
  delay(100); 
  // shift out the bits:
  shiftOut(dataPin, clockPin, MSBFIRST, ledS2[i]);  
  //take the latch pin high so the LEDs will light up:    
   digitalWrite(latchPin, HIGH);
   delay(250);      
}

    //se hace una lectura previa para saber 
     //si todavia se esta ejecutando la secuencia actual                        
    valpot = analogRead(pot); 
    if(valpot > 256   && valpot < 512){    
    goto dos; }

}




//secuencia III
void secuenciaTres(){
tres:
//recorre el arreglo donde se difinio la secuencia 
for (int i=0; i
  
  
   // take the latchPin low so 
  // the LEDs don't change while you're sending in bits:
  digitalWrite(latchPin, LOW);
  delay(100);
  // shift out the bits:
  shiftOut(dataPin, clockPin, MSBFIRST, ledS3[i]);  
  //take the latch pin high so the LEDs will light up:
  digitalWrite(latchPin, HIGH);
  delay(700);  
          
}
    //se hace una lectura previa para saber 
     //si todavia se esta ejecutando la secuencia actual
    valpot = analogRead(pot); 
    if(valpot > 512  && valpot < 768){    
    goto tres; }
}




//secuencia IV
void secuenciaCuatro(){
 //var definir la posicion de los ultimos 4 leds
   int num = 0;

 cuatro:
//recorre el arreglo donde se difinio la secuencia 
for (int i=0; i
           
           
           
             // take the latchPin low so 
  // the LEDs don't change while you're sending in bits:
  digitalWrite(latchPin, LOW);
  delay(100);
  // shift out the bits:
  shiftOut(dataPin, clockPin, MSBFIRST, ledS4[i]);  
  //take the latch pin high so the LEDs will light up:
  digitalWrite(latchPin, HIGH);
  delay(250);  
}
    //se hace una lectura previa para saber 
     //si todavia se esta ejecutando la secuencia actual
    valpot = analogRead(pot); 
    if(valpot > 768  && valpot < 1024){    
    goto cuatro; }
}



DIAGRAMA DEL LABORATORIO



ESQUEMA DEL LABORATORIO






LABORATORIO # 4


Controlar con el Arduino un secuencia de 8 LEDS, con un LED encendido moviendose
de izquierda a derecha en forma automática, utilizando una interfaz en
Processing para
controlar (pueden usar los Sliders de ControlP5) para controlar el
tiempo de encendido
y el tiempo de apagado.



MATERIALES QUE SE USARON



1 arduino

8 leds 

1 cable usb

1 protoboard

12 cables utp

8 resistencias

1 pc con el programa procesing

IMGENES DEL ENSAMBLAJE








CODIGO QUE SE USO

const int MAXLED = 8;
// arreglo de 8 LEDs, desde el pin 2 hasta el pin 9
int led[MAXLED] = {
  2,3,4,5,6,7,8,9};
char res;
int encendido=128, apagado=128;
// se ejecuta 1 sola vez, al iniciar el programa
void setup() {
  for (int i=0; i    pinMode(led[i], OUTPUT);
 
}
// se repite infinitamente mientras el arduino tenga corriente
void loop() {
  // recorre desde el indice 0 hasta el 7
  for (int i=0; i    //entra en el metodo leer datos
    //para conocer el valor de encendido y apagado de los leds
    leerDatos(); 
    on(led[i], encendido);   
    off(led[i], apagado);
  }
  // recorre desde el indice 6 hasta el 1, para no repetir los extremos
  for (int i=MAXLED-2; i>0; i–) {
    //entra en el metodo leer datos
    //para conocer el valor de encendido y apagado de los leds
    leerDatos();
    on(led[i], encendido);   
    off(led[i], apagado);
  }
}  
// métodos propios ——————————————–
void leerDatos(){
  //valida si esta hay un flujo de datos
  if (Serial.available()>0) {
    //se lee el valor mandado por serial
    res=Serial.read();
    //se valida el tipo de respuesta esperada
    if (res==’e') {
      //se asigna  el valor  del slide a  la velocidad de encendido del led
      encendido = Serial.read();
    }
    else if (res==’a') {
      //se asigna  el valor  del slide a la velocidad de apagado del led
      apagado = Serial.read();
    }
 
  }
}
void on(int led, int ms) {
  digitalWrite(led, HIGH); // HIGH = +5V = prender
  delay(ms); // espera en milisegundos
}
void off(int led, int ms) {
  digitalWrite(led, LOW); // LOW = 0V = apagar
  delay(ms); // espera en milisegundos
}

Codigo fuente Processing:

import processing.serial.*;
import controlP5.*;
//se crea una variable port de tipo serial
//para despues establecer la conexion
Serial port;
//se crea una variable cp5
//para despues establecer el control slide
ControlP5 cp5;
//se crea una variable
int valor=0;
int valor_anterior=-1;
void setup() {
  //tamanho  de la ventana
  size(600, 200);
 
  noStroke();
  //se crea la instancia del port y se le mandan atributos importantes
  port = new Serial(this, Serial.list()[1], 9600);
  //se modifican los controles
  cp5 = new ControlP5(this);
  cp5.addSlider(“e”)
    .setPosition(40, 40)
    .setWidth(500)
    .setHeight(20)
    .setRange(0, 255)
    .setValue(128)
    .setSliderMode(Slider.FLEXIBLE);
  
  cp5.addSlider(“a”)
    .setPosition(40, 140)
    .setWidth(500)
    .setHeight(20)
    .setRange(0, 255)
    .setValue(128)
    .setSliderMode(Slider.FLEXIBLE);
}
void draw() {
  //color del fondo
  background(100);
}
//metodo para el control de eventos
public void controlEvent(ControlEvent theEvent) {

//valido la condicion
  if(“e” == theEvent.getController().getName())
  {
      //mando por el serial la ‘e’
      port.write(‘e’);    
  }
  else if (“a” == theEvent.getController().getName())
  {
      //mando por el serial la ‘a’
      port.write(‘a’);
  }
  
  valor = int(theEvent.getController().getValue());
    if (valor != valor_anterior)
    {
      port.write(valor);
      valor_anterior = valor;
    }

}

VIDEO EN TIEMPO REAL FUNCIONANDO

DIAGRAMA DEL LABORATORIO






ESQUEMA DEL LABORATORIO