martes, 30 de agosto de 2011

Connect Arduino to an Android Device using Bluetooth SPP

In this tutorial we’ll check out how to make a really quick and effective connection via bluetooth (using one Bluesmirf module) with one Arduino and one Android cellphone/tablet.
Bluesmirf is one Bluetooth device specially designed for use with microcontrollers via a UART connection, it’s a Serial device. It uses Bluetooth SPP(Serial Port Protocole) for communication, which is a Serial Port emulation via a Bluetooth Connection.
Programming in Arduino is one thing, but programming in Android is another... So, what do we do if we want to control our Arduino using one Android device, but without programming this device?, I found a solution: Blueterm, this Android app is a download free app, that emulates a serial port terminal via a Bluetooth connection, really simple to use, it only requires that our Android device is Bluetooth SPP capable. So... if we have one Bluetooth SPP device(Bluesmirf preferable), one Arduino and one Android Device we are ready to make a connection!
We’ll be using the next stuff:


Bluesmirf and Bluetooth Mate have different pinouts...

Blueterm is a terminal app, this means it will display characters sent and received via a bluetooth serial port connection. So... let’s download and install Blueterm on our android device, Blueterm can be downloaded freely via Android Market, no further settings required, should work on most Android devices, if encountering problems, please refer to manufacturer’s datasheet for bluetooth profiles installed.
Now, we have to prepare our hardware, we’ll make a really simple test program to see if Arduino is receiving data via a bluetooth connection. First, we have to connect our Rx/Tx pins to our bluetooth module, if using a Bluesmirf module make sure to power it with 5V. You can use a breadboard or male/female header cables for connections.
Here’s our Arduino test code:
void setup(){
  //make sure your bluesmirf module is
  //configured at 115200 baudrate setting
  Serial.begin(115200);
  //let's test arduino led
  pinMode(13, OUTPUT);
}
void loop(){
  if(Serial.available()){
    //read first characer received
    unsigned char charreceived = Serial.read();
    
    switch(charreceived){
      case 'a':
        digitalWrite(13, HIGH);
        Serial.println("Arduino Led On");
        break;
      case 'b':
        digitalWrite(13, LOW);
        Serial.println("Arduino Led Off");
        break;
      default:
        break;
    }
    
    //flush remaining characters
    //we only want first character
    Serial.flush();
  }
  delay(10);
}
After uploading our code to our Arduino, we are ready to proceed with the bluetooth connection. In our Android device, we must activate bluetooth connections and search for our bluesmirf and pair it, depending on our bluesmirf, it’s name will vary, usually it will be findable with the initials: RN-41 or RN-42, pair code is usually “1234”. I strongly recommend setting our bluetooth module to defaults, check here how to do so. Pairing should present no further problems after a reset.
Now it’s time to truly test it, after pairing we have to open our Blueterm app, in our Blueterm app we have to press an option button, and we’ll see one option called “Connect device”, press it, it should display all our bluetooth paired devices, click on the bluesmirf option (RN-41 or RN-42 usually) and after a couple of seconds we should see in our upper  right corner a message saying “Connected”, now we are able to send characters via our terminal, remember: if we press ‘a’ we’ll turn on Arduino’s led, and if we press ‘b’ we’ll turn it off. Note: remember that not all android devices are Bluetooth SPP compatible, please refer to manufacturer’s product specifications.
Once we are connected to our Bluetooth module, you'll see the green led turned on




Main View of Blueterm App (I used Asus EePad Transformer)

So, that’s it, without much effort, we have our Arduino+Bluesmirf paired and connected with our Android device, now it’s up to us to make more complex code for Arduino, for example: maybe adding more cases in our switch sentence for more leds control, maybe using characters for motor speed control, it’s up to our imagination. It’s pretty easy, we didn’t have to kill ourselves programming in android. Please refer to this page for further bluetooth programming stuff in android.

lunes, 8 de agosto de 2011

Sensor Ultrasónico Maxbotix LM-EZ1 con Arduino

Hoy veremos cómo usar el sensor ultrasónico Maxbotix LV-EZ1 con Arduino. Primero debemos ver el datasheet, para ver que pin corresponde a cada cosa:

Usaremos unos cables hembra-machos para conectar nuestro sensor con nuestro Arduino. El sensor posee varias formas de enviar datos:
  • Salida Serial - 9600bps
  • Salida Analógica - ~9.6mV/inch
  • Salida PWM - 147uS/inch
La manera más sencilla es usando la salida analógica, ya que con sólo conectar el pin AN del sensor a un pin analógico del Arduino y usar la función analogRead() podemos tener una lectura rápida del sensor. El Arduino tiene una resolución analógica de 10 bits(2^10), que es igual a 1023 posibles valores, de manera que como el Arduino trabaja a 5V tendremos que 5V/1023 da a 0.0048V(4.8mV) por unidad.
La salida analógica del sensor tiene una resolución de 9.6mV, entonces si el arduino tiene una resolución de 4.8mV podemos fácilmente inferir que por cada 9.6mV tendremos dos unidades en la lectura analógica, dos unidades equivaldrán a una pulgada. Un ejemplo rápido, hagamos de cuenta que logramos una lectura de 209, para convertir esta lectura a una medida en pulgadas sólo tendremos que dividirla entre dos. El sensor tiene un rango mínimo de 6 pulgadas, estos quiere decir que no detectará nada a menos de 6 pulgadas y siempre el valor mínimo será de 6 pulgadas. Recordemos que una pulgada es igual a 2.54 cm.
No hay que olvidarnos de alimentar al sensor con 5V. Aquí está el código:

//Creado por Henry Serrano 9/8/2011
//Taller Arduino FIUADY

void setup(){
  Serial.begin(9600);
}

void loop(){
  //conectamos el pin AN del sensor
  //al pin A0 del Arduino
  int a = analogRead(0);
  //dividimos entre 2 y nos aseguramos
  //que siga siendo un valor entero
  a = (int)(a/2);
 
  //para imprimir en pulgadas
  Serial.println(a);
 
  //para imprimir en centímetros
  //Serial.println(a*2.54);
 
  delay(80);
}


miércoles, 27 de julio de 2011

Arduino + JoystickShield + Processing = Shuriken



This project is pretty cool. It consists of using one Arduino with a Joystick Shield for sending data to the computer, and then reading that data from Processing to create a (sort of) Shuriken and move it with the joystick. This project is divided in two parts: arduino code and processing code.
Arduino Code
Hardware stuff needed: just one arduino with a joystick shield.
Joystick Shield consists of 4 big buttons and one pushable Joystick (another button), for this project we'll only be using the joystick. The joystick consists of two potentiometers, so we need to read them as normal potentiometers using the analogRead() function. Remember these values differ from 0 to 1023. With the joystick, the values we'll usually get from it when we are not touching it are near 500 (standard position). This means that when we read something really close to 500, we do not want our shuriken to move and it will keep its position on screen.
Communicating via a serial port with Arduino is pretty easy, we'll set BaudRate(9600) for this project. Through this serial port we'll be sending string packages, each package will include the two analog measurements from the joystick (x and y position). Processing sketch will later take care to unpack packages. But we'll only send this packages when we receive serial commands from the processing sketch (we'll be synchronous with the computer), this is a must do, in order to not overload computer's buffer and avoid lag in our sketch. Here the Arduino Sketch:
void setup(){
  Serial.begin(9600);
}

void loop(){
  //send package only when requested
  if(Serial.available() > 0){
    //data will be divided by a coma
    Serial.print(analogRead(0));
    Serial.print(",");
    Serial.println(analogRead(1));
    //little delay
    delay(2);
    //clean arduino buffer
    Serial.flush();
  }
}
Processing Code
Here's the tough part of the project. The shuriken is made by drawing and rotating several triangles, this figur, in order to be displayed around the screen, needs to be translated, we will use translate() function to do so, this function asks for two values, x coordinate and y coordinate, so we'll use the joystick coordinates, this way we'll see our shuriken moving.
In our setup function, we must set size screen (I set it with openGL render, you can also use P3D), after doing so we load a font for text drawing. Now we have to create our serialport object, at BaudRate of 9600bps. Our drawing function has already been explained, during this function we will be continuously asking the arduino for data, and we will be continuously mapping it, this mapping will consist of checking if our joystick coordinates are left,right, up or down of screen's center. This means, that if we move left our joystick it will make the shuriken horizontal counter to increase making it move left, opposite will happen for righ movement, same applies for vertical movement. It will be center aligned when coordinate values are near 500 (joystick standard position). Some extra-features are commented on the code, check them out:
//Arduino+JoystickShield+Processing=Shuriken
//Made by Henry Serrano 28/7/2011
//You can use/modify code in any way you like,
//support OpenSource community

import processing.opengl.*;
import processing.serial.*;

PFont a;
int k=0,j=0,e=50, xPos = 0, yPos = 0, positionx = 0, positiony = 0;
boolean flanders=true;
boolean flanders2=true;
int joystick[] = {0,0};
int joystick2[] = {0,0};
Serial myPort;

void setup(){
  //use if computer can't handle opengl
  //size(800, 500, P3D);
  size(800, 500, OPENGL);
  a = loadFont("ARDARLING-48.vlw");
  textFont(a,32);
  serialportconnect();
  smooth();
  noStroke();
}

void draw(){
  background(0);
  fill(255);
  text("Arduino+JoystickShield+Processing=Shuriken", width/8,25);
  //in case you want to use mouse coordinates:
  //translate(mouseX,mouseY);
  serialread();
  joystickmap();
  translate(positionx, positiony);
  //uncomment next lines for cool rotation
  //rotateX(frameCount*PI/60);
  //rotateY(frameCount*PI/60);
  rotate(frameCount*PI/60);
  text("H",-11,10);
  //here's the magic for the shuriken
  //we create one triangle then we rotate it
  //making lots of triangle and rotating forms a shuriken
  for (int i=0; i<20; i++){
    fill(i+200,j+146,k+89,e);
    triangle(20,20,100,100,40,100);
    rotate(TWO_PI/20);
 }
 //we make shuriken pieces to change color and opacity
 altercolors();
}

void altercolors(){
  if(flanders == true){
   k++;
   j++;
   if(k == 50){
     flanders=false;
   }
  }else{
   k--;
   j--;
   if(k==0){
     flanders = true;
   }
 }
 if(flanders2==true){
   e++;
   if(e==240){
     flanders2=false;
   }
 }else{
   e--;
   if(e==50){
     flanders2=true;
   }
 }
}
void joystickmap(){
  //here we process joystick data
  if(joystick[1]>508){
    joystick2[1]=10;
    positionx+=joystick2[1];
  }
  if(joystick[1]<498){
    joystick2[1]=-10;
    positionx+=joystick2[1];
  }
  if(joystick[0]>508){
    joystick2[0]=10;
    positiony+=joystick2[0];
  }
  if(joystick[0]<498){
    joystick2[0]=-10;
    positiony+=joystick2[0];
  }
  if(joystick[1]>=498 && joystick[1] <=508){
    joystick2[1]=0;
    positionx+=joystick2[1];
  }
  if(joystick[0]>=498 && joystick[0] <=508){
    joystick2[0]=0;
    positiony+=joystick2[0];
  }
  if(positionx>800){
    positionx=800;
  }
  if(positionx<0){
    positionx=0;
  }
  if(positiony>500){
    positiony=500;
  }
  if(positiony<0){
    positiony=0;
  }
}
void serialread(){
  //tell arduino to send data
  myPort.write("ok");
  String inString = myPort.readStringUntil('\n');
 
  if (inString != null) {
    //trim off any whitespace
    inString = trim(inString);
    //split data into joystick array
    joystick = int(split(inString, ','));
    print(joystick[0]);
    print(",");
    println(joystick[1]);
  }
  joystick2[0] = joystick[0];
  joystick2[1] = joystick[1];
}

void serialportconnect(){
  int excep=0;
  //print available serial ports access numbers
  println(Serial.list());
  //Serial.list()[n], n is the number assigned to arduino's port
  //check processing's console for port's number
  myPort = new Serial(this, Serial.list()[2], 9600);
}
Now you only need to upload code to your Arduino, and run the sketch.
I'll add both sketches here for download, for easier reading and testing. I'll also add one image of one cool expansion you could do with the code. I made one mini-game, which consists of killing flanders with the Shuriken and getting points racing against time.