martes, 29 de noviembre de 2011

Peluche RFID

Me he puesto a hacer el proyecto "Charlie's Bear" de la revista MAKE número 28  he seguido las instrucciones paso por paso y ha funcionado a la primera.

El cacharro:

Un vídeo con el cacharro dentro de la vaca peluche:


Ya aparecieron los problemas:

Soluciones:
  • Añadirle un amplificador (el de velleman p.ej. en venta en todoelectronica y conectrol)
  • Utilizar un altavoz amplificado
  • Amplificar el volumen de los wavs, aunque parece que no ayuda mucho, debe ser lo más inmediato. Sí que es suficiente con  amplificar el wav con audicity.
Quiero hace un par de modificaciones al soft del proyecto:
  • Nombrar el fichero de sonido con los últimos 8 caracteres de la etiqueta rfid en vez de los 8 primeros. Coge bien los 8 últimos... pero luego dice que no puede reproducir el fichero... ¿por qué?
  • No reproducir un fichero hasta que no se haya terminado el actual (utilizando "while (wave.isplaying)" ). Esto funciona bien sin mayor problema. -> Hecho
  • Parar la reproducción si se acerca la tarjeta "silenciadora". -> Hecho
A nivel hard habría que hacer las siguientes modificaciones:
  • Añadir un interruptor. -> Añadido
El código me ha quedado así:

/ An interactive bear for Charlie -- RFID triggered sound responses

#include <FatReader.h>
#include <SdReader.h>
#include "WaveHC.h"
#include "WaveUtil.h"

SdReader memcard;
FatVolume vol;
FatReader root;
FatReader file;
WaveHC wave;

#define ENABLE 7      // Set the pin number for enabling the RFID reader. The Audio Shield uses pins 2-5.
#define STOPTAG "3D001EDA94" // Code of the TAG that stops any sound 


int  val = 0; 
char code[10];
int bytesread = 0; 

char filename[1][13];

void setup() { 
  //////// Set up RFID reader to collect tag information /////////////////////
  Serial.begin(2400);         // RFID reader SOUT pin connected to Serial RX pin at 2400bps 
  pinMode(ENABLE,OUTPUT);     // Set digital pin 7 as OUTPUT to connect it to the RFID /ENABLE pin 
  digitalWrite(ENABLE, LOW);  // Activate the RFID reader
  
  //////// Set the pins to output for driving the Audio Shield
  pinMode(2, OUTPUT); 
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  
  ////////// Set up the Audio Shield by initializing the memory card for reading ////////
  if (!memcard.init()) {
    // If something went wrong sdErrorCheck prints out the error check
    putstring_nl("Card init. failed!"); 
    cardErrorCheck();
    return;
  }
  
  //This will optimize the reading of the memory card -- remove it if it times out
  memcard.partialBlockRead(true);
  
  // Find a FAT formatted partition by looking in teh first five slots. Remember your memory card should be FAT16 or FAT32 formatted
  uint8_t partition;
  for (partition = 0; partition < 5; partition++) {
    if (vol.init(memcard, partition))
      break;
  }
  if (partition == 5)
  {
    putstring_nl("No valid FAT partition");
    cardErrorCheck();
    while(1); // This is a point of no return. Format your memory card properly and try again.
  }

  // Open the root directory for reading the files
  if (!root.openRoot(vol))
  {
    putstring_nl("Can't open root directory");
    while(1); // Something went wrong here so investigate the file system on your memory card.
  }
  
  // If you got this far then the card is ready to read
  /*Serial.println("STOP TAG is :  ");
  Serial.println(STOPTAG);
  putstring_nl("Ready to go");*/
}

// If we find an error, check what the error is and show it on the serial terminal
void cardErrorCheck(void)
{
  if(!memcard.errorCode()) return;
  putstring("\n\rSD I/O error:");
  Serial.print(memcard.errorCode());
  putstring(", ");
  Serial.print(memcard.errorData());
  while(1); // Stick here if there is an error
}

void loop() { 

  if(Serial.available() > 0) {          // if data available from reader  
    if((val = Serial.read()) == 10) {   // check for header 
      bytesread = 0; 
      while(bytesread<10) {              // read 10 digit code 
        if( Serial.available() > 0) { 
          val = Serial.read(); 
          if((val == 10)||(val == 13)) { // if header or stop bytes before the 10 digit reading 
            break;                       // stop reading 
          } 
          code[bytesread] = val;         // add the digit           
          bytesread++;                   // ready to read next digit  
        } 
      } 
      if(bytesread == 10) {              // if 10 digit read is complete 

        if(memcmp(code,STOPTAG,10) == 0  ){ // check if the TAG is the STOP TAG
           silence();                
           //Serial.println("STOP TAG ");
        } else if (! wave.isplaying){    // do nothing if a file is alredy playing
          playsound(code);
         // Serial.print("TAG code is: ");   // possibly a good TAG 
         // Serial.println(code);            // print the TAG code 
          Serial.flush();                  // Flush the serial buffer before trying to read a new code
        }
       
      } 
      bytesread = 0; 
    }
  }

} 

void playsound(char codetoplay[]) {
  
  Serial.print("File name is: ");   // possibly a good TAG 
  //for(int i = 2; i<10; i++) {    // Make a filename from the first 8 characters of the RFID tag number NOT WORKING
  for(int i = 0; i<8; i++) {    filename[0][i]=codetoplay[i];
    //Serial.print(codetoplay[i]);            // print the name code 
  }
  filename[0][8]='.';
  filename[0][9]='w';
  filename[0][10]='a';
  filename[0][11]='v';
  //Serial.println(".wav");            // print the name code 
  silence(); //shut down anything that is currently playing and close that file
  playfile(filename[0]);
  
}

void playfile(char *name) {
  
        
  if (!file.open(root, name)) {
      putstring_nl("Couldn't open file"); 
      return;
   }
   if (!wave.create(file)) {
     putstring_nl("Not a valid WAV"); 
     return;
   }
  wave.play();
  
}

void silence() {
  if(wave.isplaying) {
    wave.stop();
  }
}


Control universal para nanocópteros (¿y más?)

Otro de los proyectos es hacer un recptor/emisor de IR. ¿Para qué? Pues en 4 ó 5 años tengo 4 nanocópteros, cada unos con su mando no intercambiable. Cada mando utiliza 6 (6!!!) pilas AA. Así que si no quiero tener en "stock" 24 pilas (que además necesito para los juguetes de los niños) tengo que andar poniéndolas y quitándolas. Así que teniendo un receptor de IR para saber qué comando se envia a cada nanocóptero y un emisor para enviarlos podría utilizar un solo mando (además alimentado por USB o con una pila de 9 V) para todos los cacharros.

  • con el amicus18 un tipo ha hecho un receptor de IR para controlar aparatos de corriente continua. Además da como referencia una página qeu aclara todo lo referente a los mandos de IR.
  • Para Arduino hay información aquí y aquí. En esta página hay un tutorial bastante claro.
Después de mucho tiempo he retomado el asunto... y buscando el protocolo que tienen los juguetes he encontrado que en dangerous prototypes ya lo tienen montado y con un analizador todo por 20$... así que optaré por la solución fácil de la compra...

Ya llegó el analizador... a ver si juego con él un poco...

    domingo, 27 de noviembre de 2011

    Tortuga logo. Primer intento.

    Pues teniendo estos materiales:

    Me he puesto a intentar hacer una tortuga de logo:

    Los dos motores enganchados al arduino y funcionando

    Instalando uno de los motores en la tarrina.

    Una de las "ruedas", filtro de café
    El resultado es más tipo Igor que tortuga como puee apreciarse en el vídeo:



    Los elementos están mal ensamblados. Falta el microservo para subir y bajar el rotulador. El centro de gravedad está demasiado alto. Lo peor son las "ruedas". Tengo que encontrar otra solución. El material de los filtros de café es demasiado débil....

    El código que está corriendo sólo lo hace ir hacia adelante, girar a un lado, hacia atrás y girar a otro add infinitum:

    /* Stepper Bipolar Advanced
     * ------------------------
     *
     * Program to drive a stepper motor coming from a 5'25 disk drive
     * according to the documentation I found, this stepper: "[...] motor 
     * made by Copal Electronics, with 1.8 degrees per step and 96 ohms 
     * per winding, with center taps brought out to separate leads [...]"
     * [http://www.cs.uiowa.edu/~jones/step/example.html]
     *
     * It is a bipolar stepper motor with 5 wires:
     * 
     * - red: power connector, I have it at 5V and works fine
     * - orange and black: coil 1
     * - brown and yellow: coil 2
     *
     * (cleft) 2005 DojoDave for K3
     * http://www.0j0.org | http://arduino.berlios.de
     *
     * @author: David Cuartielles
     * @date: 20 Oct. 2005
     */
    
    int motor1Pins[] = {10, 11, 12,13};
    int motor2Pins[] = {5, 4, 3, 2};
    int count = 0;
    int count2 = 0;
    int countCambio = 0;
    int delayTime = 2;
    //int val = 0;
    
    void setup() {
      //pinMode(ledPin, OUTPUT);
      for (count = 0; count < 4; count++) {
        pinMode(motor1Pins[count], OUTPUT);
        pinMode(motor2Pins[count], OUTPUT);
      }
    }
    
    void moveForward() {
      if ((count2 == 0) || (count2 == 1)) {
        count2 = 16;
      }
      count2>>=1;
      for (count = 3; count >= 0; count--) {
        digitalWrite(motor1Pins[count], count2>>count&0x01);
        digitalWrite(motor2Pins[count], count2>>count&0x01);
      }
      delay(delayTime);
    }
    
    void moveBackward() {
      if ((count2 == 0) || (count2 == 1)) {
        count2 = 16;
      }
      count2>>=1;
      for (count = 3; count >= 0; count--) {
        digitalWrite(motor1Pins[3 - count], count2>>count&0x01);
        digitalWrite(motor2Pins[3 - count], count2>>count&0x01);
      }
      delay(delayTime);
    }
    
    void turnRight() {
      if ((count2 == 0) || (count2 == 1)) {
        count2 = 16;
      }
      count2>>=1;
      for (count = 3; count >= 0; count--) {
        digitalWrite(motor1Pins[count], count2>>count&0x01);
        digitalWrite(motor2Pins[3 - count], count2>>count&0x01);
      }
      delay(delayTime);
    }
    
    void turnLeft() {
      if ((count2 == 0) || (count2 == 1)) {
        count2 = 16;
      }
      count2>>=1;
      for (count = 3; count >= 0; count--) {
        digitalWrite(motor1Pins[3 - count], count2>>count&0x01);
        digitalWrite(motor2Pins[count], count2>>count&0x01);
      }
      delay(delayTime);
    }
    
    
    
    void loop() {
    
        if(countCambio <1000){
          moveForward();
        } else if (countCambio < 2000) {
          turnRight();
        }else if (countCambio < 3000) {
          moveBackward();
        }else if (countCambio < 4000) {
          turnLeft();
        } else {
         countCambio = 0;
        }
        countCambio++;
    }
    

    Si sigo con ello ya lo contaré.




    Lottie Lemon. Arduino se hizo robot.

    En colaboración con los chicos de complubot la gente de Arduino ha creado el Robot Educativo Lottie Lemon. 
    Dicen que lo pondrán a la venta a final de año... pero no lo encuentro todavía... :(  Que envidia de estos muchachos de compublot... con lo jovencitos que son!!!

    miércoles, 16 de noviembre de 2011

    Tortuga de logo

    Uno de los proyectos que pretendo hacer algún día de estos es una tortuga de logo.
    Un robot al que se le cargue un programita que hecho con logo y Pinte lo pinte en un papel en el suelo.
    Mirando por ahí he visto que hay bastante gente que ha pensado lo mismo:
    Es cuestión de ponerse un raaatooo...
    A través de Let's Make Robot he llegado al blog de txapuzas , el robot que hace tiene buena pinta.
    además en LMR hay una entrada de un robot que escribe, hecho con CD's... Para hacer el brazo qeu suba y baje el boli podría hacerse algo parecido a esto
    Otro interesante que dibuja en una pared colgando un boli de dos hilos movido por dos motores...