lunes, 22 de octubre de 2012

Comunicación Serie Ente Java y Arduino

Hoy veremos como realizar una comunicación serie entre el IDE Netbeans y Arduino. para la realizar de forma adecuada nuestro proyecto, tenemos que tener en cuenta la librería de conexión o comunicación entre estos dos entornos de programación, es una librería muy conocida llamada RXTX, Esta librería reemplazo a las extensiones API que anteriormente existían otra cosa que debemos tener muy en cuenta es que nosotros tenemos que ajustar la dirección del puerto COM de nuestra tarjeta arduino que en ese momento estemos utilizando para mi caso es el "COM36".

 Nuestro primer paso es el de llamar, incluir o agregar nuestra librería RXTX a nuestro IDE(Netbeans). después de haber descargado y descomprimido la librería, abrimos Netbeans Creamos un nuevo proyecto después de esto vamos a las propiedades de este, luego le damos clic en librerías, y por el momento le podemos dar clic en add/jar/folder y seleccionamos la librería RXTXcomm. La otra forma es agregando una librería para que cuando necesitemos esa misma librería no tengamos que hacer el paso anterior si no seleccionarla de las librerías principales de java.

el segundo paso para la comunicación es la configuración de arduino, para ello abrimos el entorno de programación de arduino,  y pegamos el siguiente código:

z
void setup () {
  Serial.begin (9600);  // Velocidad en la transferencia de los datos 9600 bauds
}

void loop () {
  Serial.println ("Hola mundo");  // imprimimos en el serial 
  delay (1000);         // hacemos un retardo de 1 segundo
}

el tercer paso es configurar el IDE de java o nuestro condigo principal para ello arduino nos brinda un código el cual es el mas básico para verificar la comunicación entre java y arduino que es el siguiente:

import java.io.InputStream;   //importamos las librerias
import java.io.OutputStream;
import gnu.io.CommPortIdentifier; 
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent; 
import gnu.io.SerialPortEventListener; 
import java.util.Enumeration;

public class SerialTest implements SerialPortEventListener {
 SerialPort serialPort;
        /** The port we're normally going to use. */
 private static final String PORT_NAMES[] = {  
//  muy importante esta parte ya que muchas personas se pierden en este paso y no// se realiza la comunicación como queremos podemos borrar las demas opciones dep//endiendo de cual sistemas operativo tengamos para mi caso solo dejo la de wind//ows y coloco "COM36".
   "/dev/tty.usbserial-A9007UX1", // Mac OS X
   "/dev/ttyUSB0", // Linux
   "COM3", // Windows
   };
 /** Buffered input stream from the port */
 private InputStream input;
 /** The output stream to the port */
 private OutputStream output;
 /** Milliseconds to block while waiting for port open */
 private static final int TIME_OUT = 2000;
 /** Default bits per second for COM port. */
 private static final int DATA_RATE = 9600; 
//velocidad de transferencia de datos y tiene q coincidir con la que tenemos con //arduino de lo contrario no se establece la comunicación.

 public void initialize() {
  CommPortIdentifier portId = null;
  Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

  // iterate through, looking for the port
  while (portEnum.hasMoreElements()) {
   CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
   for (String portName : PORT_NAMES) {
    if (currPortId.getName().equals(portName)) {
     portId = currPortId;
     break;
    }
   }
  }

  if (portId == null) {
   System.out.println("Could not find COM port.");
// en caso de arrojarnos could no find COM port debemos revisar la direccion del //puerto.
   return;
  }

  try {
   // open serial port, and use class name for the appName.
   serialPort = (SerialPort) portId.open(this.getClass().getName(),
     TIME_OUT);

   // set port parameters
   serialPort.setSerialPortParams(DATA_RATE,
     SerialPort.DATABITS_8,
     SerialPort.STOPBITS_1,
     SerialPort.PARITY_NONE);

   // open the streams
   input = serialPort.getInputStream();
   output = serialPort.getOutputStream();

   // add event listeners
   serialPort.addEventListener(this);
   serialPort.notifyOnDataAvailable(true);
  } catch (Exception e) {
   System.err.println(e.toString());
  }
 }

 /**
  * This should be called when you stop using the port.
  * This will prevent port locking on platforms like Linux.
  */
 public synchronized void close() {
  if (serialPort != null) {
   serialPort.removeEventListener();
   serialPort.close();
  }
 }

 /**
  * Handle an event on the serial port. Read the data and print it.
  */
 public synchronized void serialEvent(SerialPortEvent oEvent) {
  if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
   try {
    int available = input.available();
    byte chunk[] = new byte[available];
    input.read(chunk, 0, available);

    // Displayed results are codepage dependent
    System.out.print(new String(chunk));
   } catch (Exception e) {
    System.err.println(e.toString());
   }
  }
  // Ignore all the other eventTypes, but you should consider the other ones.
 }

 public static void main(String[] args) throws Exception {
  SerialTest main = new SerialTest();
  main.initialize();
  System.out.println("Started");
//Si todo la anterior esta bien entonces nos debe imprimir que el puerto esta ini//ciado y nos debe imprimir lo que tiene el arduio en el puerto seria osea el Hol//a Mundo
 }
}

para mas información visitar la pagina de arduino http://arduino.cc/playground/Interfacing/Java.

en internet se encuentra varios ejemplos de interactuar arduino y java de los cuales tome uno para hacer la prueba o verificación de esto en este caso realice la prueba del siguiente vídeo que encontré en internet:


cualquier duda me la hacen saber a través del los comentarios.



11 comentarios:

  1. Hola que tal, excelente el aporte, una pregunta ya realice todo al pie de la letra pero me marca este error

    java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path thrown while loading gnu.io.RXTXCommDriver
    Exception in thread "main" java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1860)
    at java.lang.Runtime.loadLibrary0(Runtime.java:845)
    at java.lang.System.loadLibrary(System.java:1084)
    at gnu.io.CommPortIdentifier.(CommPortIdentifier.java:83)
    at serialtest.SerialTest.initialize(SerialTest.java:45)
    at serialtest.SerialTest.main(SerialTest.java:145)
    Java Result: 1

    ya lo intente pero no puedo resolverlo me podrías ayudar ?

    otra pregunta hay algún problema con que este trabajando con un arduino uno r3?

    ResponderEliminar
    Respuestas
    1. Ok, mira tienes que revisar muy bien lo de la libreria. no lo especifique pero ya hare un nuevo post de eso para que entiendas mejor.

      Eliminar
    2. ami tambien me aparece el mismo error me podrias ayudar

      Eliminar
    3. Ese error sale por que no tienes las librerias completas. Debes copiar el serial.dll y el Parallel.dll en las carpetas de Java instaladas (jre\bin)
      Pasa por el sitio
      http://fizzed.com/oss/rxtx-for-java
      Ahi se encuentran las librerias completas

      Eliminar
  2. Oye amigo pasame el java tengo error en esta parte private static final String PORT_NAMES [ ] ="COM3"{


    };


    ME MARCA MAL TIENES TU PROGRAMA QUE ME PASE

    ResponderEliminar
    Respuestas
    1. el com3 va adentro de las llavas para indicar que es un array

      Eliminar
  3. el COM3 va adentro de las llaves rafaelmq_7

    ResponderEliminar
    Respuestas
    1. import java.io.BufferedReader;
      import java.io.InputStreamReader;
      import java.io.OutputStream;
      import gnu.io.CommPortIdentifier;
      import gnu.io.SerialPort;
      import gnu.io.SerialPortEvent;
      import gnu.io.SerialPortEventListener;
      import java.util.Enumeration;


      public class SerialTest implements SerialPortEventListener {
      SerialPort serialPort;
      /** The port we're normally going to use. */
      private static final String PORT_NAMES[] = {
      "/dev/tty.usbserial-A9007UX1", // Mac OS X
      "/dev/ttyACM0", // Raspberry Pi
      "/dev/ttyUSB0", // Linux
      "COM3", // Windows
      };
      /**
      * A BufferedReader which will be fed by a InputStreamReader
      * converting the bytes into characters
      * making the displayed results codepage independent
      */
      private BufferedReader input;
      /** The output stream to the port */
      private OutputStream output;
      /** Milliseconds to block while waiting for port open */
      private static final int TIME_OUT = 2000;
      /** Default bits per second for COM port. */
      private static final int DATA_RATE = 9600;

      public void initialize() {
      // the next line is for Raspberry Pi and
      // gets us into the while loop and was suggested here was suggested http://www.raspberrypi.org/phpBB3/viewtopic.php?f=81&t=32186
      System.setProperty("gnu.io.rxtx.SerialPorts", "/dev/ttyACM0");

      CommPortIdentifier portId = null;
      Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

      //First, Find an instance of serial port as set in PORT_NAMES.
      while (portEnum.hasMoreElements()) {
      CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
      for (String portName : PORT_NAMES) {
      if (currPortId.getName().equals(portName)) {
      portId = currPortId;
      break;
      }
      }
      }
      if (portId == null) {
      System.out.println("Could not find COM port.");
      return;
      }

      try {
      // open serial port, and use class name for the appName.
      serialPort = (SerialPort) portId.open(this.getClass().getName(),
      TIME_OUT);

      // set port parameters
      serialPort.setSerialPortParams(DATA_RATE,
      SerialPort.DATABITS_8,
      SerialPort.STOPBITS_1,
      SerialPort.PARITY_NONE);

      // open the streams
      input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
      output = serialPort.getOutputStream();

      // add event listeners
      serialPort.addEventListener(this);
      serialPort.notifyOnDataAvailable(true);
      } catch (Exception e) {
      System.err.println(e.toString());
      }
      }

      /**
      * This should be called when you stop using the port.
      * This will prevent port locking on platforms like Linux.
      */
      public synchronized void close() {
      if (serialPort != null) {
      serialPort.removeEventListener();
      serialPort.close();
      }
      }

      /**
      * Handle an event on the serial port. Read the data and print it.
      */
      public synchronized void serialEvent(SerialPortEvent oEvent) {
      if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
      try {
      String inputLine=input.readLine();
      System.out.println(inputLine);
      } catch (Exception e) {
      System.err.println(e.toString());
      }
      }
      // Ignore all the other eventTypes, but you should consider the other ones.
      }

      public static void main(String[] args) throws Exception {
      SerialTest main = new SerialTest();
      main.initialize();
      Thread t=new Thread() {
      public void run() {
      //the following line will keep this app alive for 1000 seconds,
      //waiting for events to occur and responding to them (printing incoming messages to console).
      try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
      }
      };
      t.start();
      System.out.println("Started");
      }
      }

      Eliminar
  4. Hola al desconectar el arduino y volverlo a conectar al puerto no pasa nada, puedes explicarme por que y que puedo hacer?

    ResponderEliminar
  5. oye lo que pasa es que al estar trabajando con el puerto serie y eviar varias datos por el puerto serial ahi perdida de ellos o no los alcanza a recuperar todos arduino y en mi caso que estoy trabajando con servos este ya no sabe que hacer.. intente hacer que arduino me manda un mensaje cundo aya terminado de procesar unos datos para pder volver a enviarle mas pero ese mensaje no me llega nunca

    ResponderEliminar
  6. Hola una duda, Yo tenia el problema de que conectaba correcto y todo pero si desconectaba el Arduino durante la ejecucion del programa me marca un error de software, una unknown software exception, necesito que al desconectar el arduino no se detenga si no que espere a que se reconecte el arduino y volver a trabajar. ¿Este codigo hace eso? Y si no ¿Sabes como se puede hacer?

    ResponderEliminar