Menú

Mostrar Mensajes

Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.

Mostrar Mensajes Menú

Mensajes - Meta

#741
Ya me ejecuta, lo instaré todo a 32 bits.

https://www.youtube.com/watch?v=JAwCa4Uk6tA

Estoy haciendo un buen tutorial sobre puerto serie con Visual Studio y Java.



Si quieres te envío en pdf hasta donde he llegado.

Muchísimas gracias por la ayuda.
#742
Por lo que veo, mejor usar todo a 32 bits.

Lo instalaré todo a 32 bits por si acaso, a lo mejor es más cómodo y rápido.

http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

https://netbeans.org/downloads/8.0.1/

Desinstalé todo a 64 bits e instalé todo a 32 bits en Windows de 64 bits a ver que pasa. En este momento estoy descargando la última versión y a 32 bits, luego comento.

Saludos.
#743
Lo puse así:

Citar-Djava.library.path="C:\Program Files (x86)\Java\jre1.8.0_40\bin"

Me aparece esto:
Citarrun:
java.lang.UnsatisfiedLinkError: C:\Program Files (x86)\Java\jre1.8.0_40\bin\rxtxSerial.dll: Can't load IA 32-bit .dll on a AMD 64-bit platform thrown while loading gnu.io.RXTXCommDriver
Exception in thread "AWT-EventQueue-0" java.lang.UnsatisfiedLinkError: C:\Program Files (x86)\Java\jre1.8.0_40\bin\rxtxSerial.dll: Can't load IA 32-bit .dll on a AMD 64-bit platform

También puse esto:
Citar-Djava.library.path="C:\Program Files\Java\jre1.8.0_31\bin\rxtxSerial.dll"

Nombrando la dll y todo pero sigue con elmismo mensaje.
#744
Hola:

Uso netbeans 8.0.2 en español.

Mirando el código lo he hecho otra vez desde cero.
Código (java) [Seleccionar]

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.OutputStream;
import java.util.Enumeration;
import javax.swing.JOptionPane;

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author Meta
*/
public class JAVADUINO_Frame extends javax.swing.JFrame {

    /**
     * Creates new form JAVADUINO_Frame
     */
   
    private static final String L8on = "Led_8_ON";
    private static final String L8off = "Led_8_OFF";
   
    // Variables de conexión.
    private OutputStream output = null;
    SerialPort serialPort;
    private final String PUERTO = "COM4";
   
    private static final int TIMEOUT = 2000; // 2 segundos.
   
    private static final int DATA_RATE = 115200; // Baudios.
   
    public JAVADUINO_Frame() {
        initComponents();
        inicializarConexion();
    }
   
    public void inicializarConexion(){
        CommPortIdentifier puertoID = null;
        Enumeration puertoEnum = CommPortIdentifier.getPortIdentifiers();
       
        while (puertoEnum.hasMoreElements()){
            CommPortIdentifier actualPuertoID = (CommPortIdentifier) puertoEnum.nextElement();
            if (PUERTO.equals(actualPuertoID.getName())){
                puertoID = actualPuertoID;
                break;
            }
        }
       
        if (puertoID == null){
            mostrarError("No se puede conectar al puerto");
            System.exit(ERROR);
        }
       
        try{
            serialPort = (SerialPort) puertoID.open(this.getClass().getName(), TIMEOUT);
            // Parámatros puerto serie.
           
            serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);
           
            output = serialPort.getOutputStream();
        } catch (Exception e){
            mostrarError(e.getMessage());
            System.exit(ERROR);
        }
    }
   
    private void enviarDatos(String datos){
        try{
            output.write(datos.getBytes());
        } catch (Exception e){
            mostrarError("ERROR");
            System.exit(ERROR);
        }
    }
   
    public void mostrarError(String mensaje){
        JOptionPane.showMessageDialog(this, mensaje, "ERROR", JOptionPane.ERROR_MESSAGE);   
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("ON");

        jButton2.setText("OFF");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 99, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(92, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(26, 26, 26))
        );

        pack();
    }// </editor-fold>                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JAVADUINO_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JAVADUINO_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JAVADUINO_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JAVADUINO_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JAVADUINO_Frame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    // End of variables declaration                   
}



Uso Windows 7 de 64 bits.

Me sle este error.
Citarrun:
java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path thrown while loading gnu.io.RXTXCommDriver
Exception in thread "AWT-EventQueue-0" java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path
   at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1865)
   at java.lang.Runtime.loadLibrary0(Runtime.java:870)
   at java.lang.System.loadLibrary(System.java:1119)
   at gnu.io.CommPortIdentifier.<clinit>(CommPortIdentifier.java:83)
   at JAVADUINO_Frame.inicializarConexion(JAVADUINO_Frame.java:43)
   at JAVADUINO_Frame.<init>(JAVADUINO_Frame.java:38)
   at JAVADUINO_Frame$1.run(JAVADUINO_Frame.java:155)
   at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
   at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:749)
   at java.awt.EventQueue.access$500(EventQueue.java:97)
   at java.awt.EventQueue$3.run(EventQueue.java:702)
   at java.awt.EventQueue$3.run(EventQueue.java:696)
   at java.security.AccessController.doPrivileged(Native Method)
   at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
   at java.awt.EventQueue.dispatchEvent(EventQueue.java:719)
   at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
   at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
   at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
   at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
   at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
   at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

El que más me llama la ateción es este:
Citarjava.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path thrown while loading gnu.io.RXTXCommDriver
Exception in thread "AWT-EventQueue-0" java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path

Saludos.
#745
Hola:

Código (java) [Seleccionar]
/*
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.OutputStream;
import java.util.Enumeration;
import javax.swing.JOptionPane;
*/

import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.util.Enumeration;
import javax.swing.JOptionPane;

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author Meta
*/
public class JAVADUINO_JFrame extends javax.swing.JFrame {

    /**
     * Creates new form JAVADUINO_JFrame
     */
   
    private static final String L8ON = "Led_8_ON";
    private static final String L8OFF = "Led_8_OFF";
   
    // Variables de conexión.
    private final OutputStream output = null;
    SerialPort serialPort;
    private final String PUERTO = "COM4";
   
    private static final int TIMEOUT = 2000;
   
    private static final int DATA_RATE = 115200;
   
    public JAVADUINO_JFrame() {
        initComponents();
        inicializarConexion();
    }

    public final void inicializarConexion(){
        CommPortIdentifier puertoID = null;
        Enumeration puertoEnum = CommPortIdentifier.getPortIdentifiers();
       
        while(puertoEnum.hasMoreElements()){
            CommPortIdentifier actualPuertoID = (CommPortIdentifier) puertoEnum.nextElement();
            if (PUERTO.equals(actualPuertoID.getName())){
                puertoID = actualPuertoID;
                break;
            }
        }
       
            if (puertoID == null){
    mostrarError("No se puede conectar al puerto.");
    System.exit(ERROR);
}
   
    try{
        serialPort = (SerialPort) puertoID.open(this.getClass().getName(), TIMEOUT);
        // Parámetros puerto serie.
        serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);
        output = serialPort.getOutputStream();
}
    catch (Exception e){
    mostrarError(e.getMessage());
    System.exit(ERROR);
}
    }
   

    private void enviarDatos(String datos){
        try{
            output.write(datos.getBytes());
        }
        catch(Exception e){
            mostrarError("ERROR");
            System.exit(ERROR);
        }
    }
   
    public void mostrarError(String mensaje){
        JOptionPane.showMessageDialog(this, mensaje, "ERROR", JOptionPane.ERROR_MESSAGE);
       
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("ON");

        jButton2.setText("OFF");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 101, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addGap(45, 45, 45))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(250, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(27, 27, 27))
        );

        pack();
    }// </editor-fold>                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JAVADUINO_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JAVADUINO_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JAVADUINO_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JAVADUINO_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JAVADUINO_JFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    // End of variables declaration                   

    private void mostrarError(String no_se_puede_conectar_al_puerto) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}


Me sale este error.
Citarrun:
java.lang.ExceptionInInitializerError
Caused by: java.lang.RuntimeException: Uncompilable source code - method mostrarError(java.lang.String) is already defined in class JAVADUINO_JFrame
   at JAVADUINO_JFrame.<clinit>(JAVADUINO_JFrame.java:174)
Exception in thread "main" Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

Saludos.
#746
Hola:

Tengo un código medio hecho en el cual no se el motivo de los fallos. Se trata de encender y apagar un Led con Netbeans 8 en mi caso y Arduino.

Código (java) [Seleccionar]

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.OutputStream;
import java.util.Enumeration;
import javax.swing.JOptionPane;

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author Meta
*/
public class JAVADUINO_JFrame extends javax.swing.JFrame {

   /**
    * Creates new form JAVADUINO_JFrame
    */
   
   private static final String L8ON = "Led_8_ON";
   private static final String L8OFF = "Led_8_OFF";
   
   // Variables de conexión.
   private final OutputStream output = null;
   SerialPort serialPort;
   private final String PUERTO = "COM4";
   
   private static final int TIMEOUT = 2000;
   
   private static final int DATA_RATE = 115200;
   
   public JAVADUINO_JFrame() {
       initComponents();
       inicializarConexion();
   }

   public final void inicializarConexion(){
       CommPortIdentifier puertoID = null;
       Enumeration puertoEnum = CommPortIdentifier.getPortIdentifiers();
       
       while(puertoEnum.hasMoreElements()){
           CommPortIdentifier actualPuertoID = (CommPortIdentifier) puertoEnum.nextElement();
           if (PUERTO.equals(actualPuertoID.getName())){
               puertoID = actualPuertoID;
               break;
           }
       }
   }
   
   if (puertoID == null){
   mostrarError("No se puede conectar al puerto.");
   System.exit(ERROR);
}
   
   try{
       serialPort = (SerialPort) puertoID.open(this.getClass().getName(), TIMEOUT);
       // Parámetros puerto serie.
       serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);
       output = serialPort.getOutputStream();
}
   catch (Exception e){
   mostrarError(e.getMessage());
   System.exit(ERROR);
}

   private void enviarDatos(String datos){
       try{
           output.write(datos.getBytes());
       }
       catch(Exception e){
           mostrarError("ERROR");
           System.exit(ERROR);
       }
   }
   
   public void mostrarError(String mensaje){
       JOptionPane.showMessageDialog(this, mensaje, "ERROR", JOptionPane.ERROR_MESSAGE);
       
   }
   /**
    * This method is called from within the constructor to initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is always
    * regenerated by the Form Editor.
    */
   @SuppressWarnings("unchecked")
   // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
   private void initComponents() {

       jButton1 = new javax.swing.JButton();
       jButton2 = new javax.swing.JButton();

       setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

       jButton1.setText("ON");

       jButton2.setText("OFF");

       javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
       getContentPane().setLayout(layout);
       layout.setHorizontalGroup(
           layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
           .addGroup(layout.createSequentialGroup()
               .addGap(21, 21, 21)
               .addComponent(jButton1)
               .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 101, Short.MAX_VALUE)
               .addComponent(jButton2)
               .addGap(45, 45, 45))
       );
       layout.setVerticalGroup(
           layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
           .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
               .addContainerGap(250, Short.MAX_VALUE)
               .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                   .addComponent(jButton1)
                   .addComponent(jButton2))
               .addGap(27, 27, 27))
       );

       pack();
   }// </editor-fold>                        

   /**
    * @param args the command line arguments
    */
   public static void main(String args[]) {
       /* Set the Nimbus look and feel */
       //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
       /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
        * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
        */
       try {
           for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
               if ("Nimbus".equals(info.getName())) {
                   javax.swing.UIManager.setLookAndFeel(info.getClassName());
                   break;
               }
           }
       } catch (ClassNotFoundException ex) {
           java.util.logging.Logger.getLogger(JAVADUINO_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
       } catch (InstantiationException ex) {
           java.util.logging.Logger.getLogger(JAVADUINO_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
       } catch (IllegalAccessException ex) {
           java.util.logging.Logger.getLogger(JAVADUINO_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
       } catch (javax.swing.UnsupportedLookAndFeelException ex) {
           java.util.logging.Logger.getLogger(JAVADUINO_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
       }
       //</editor-fold>

       /* Create and display the form */
       java.awt.EventQueue.invokeLater(new Runnable() {
           public void run() {
               new JAVADUINO_JFrame().setVisible(true);
           }
       });
   }

   // Variables declaration - do not modify                    
   private javax.swing.JButton jButton1;
   private javax.swing.JButton jButton2;
   // End of variables declaration                  

   private void mostrarError(String no_se_puede_conectar_al_puerto) {
       throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
   }
}


Todavía no he programado los botones, hay que acabar con los fallos primero. Los mensajes que me dan son estos.
Citarrun:
java.lang.ClassFormatError: Duplicate field name&signature in class file JAVADUINO_JFrame
   at java.lang.ClassLoader.defineClass1(Native Method)
   at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
   at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
   at java.net.URLClassLoader.defineClass(URLClassLoader.java:455)
   at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
   at java.net.URLClassLoader$1.run(URLClassLoader.java:367)
   at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
   at java.security.AccessController.doPrivileged(Native Method)
   at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
   at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
   at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:495)
Exception in thread "main" Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

He segudio los tutoriales hasta el minuto 37':30" de este vídeo.
https://www.youtube.com/watch?v=4Hr_LZ62SdY

¿Alguna idea?

Saludos.
#747
Java / Re: Cargar librería en NetBeans 8
28 Febrero 2015, 05:09 AM
Muchas gracias.
#748
Java / Cargar librería en NetBeans 8
28 Febrero 2015, 03:47 AM
Hola a todos y a todas:

Descargué Netbeans 8.01 en español y JDK. Lo tengo instalado. Fui a la web
http://rxtx.qbang.org/wiki/index.php/Download

Y justo este enlace me descargué el rachivo en binario.

Estoy con Arduino y quiero desde Java encender y apagar un Led, que se puede hacer. El codigo de Arduino UNO r3 es este.


char caracter;
String comando;

void setup() {
 pinMode(8, OUTPUT); // Pin 8 la configuramos como salida.
 pinMode(13, OUTPUT);
 digitalWrite(8, HIGH); // Mantener relés del pin 8 apagado.
 digitalWrite(13, HIGH); // Mantener relés del pin 13 apagado.
 Serial.begin(115200); // Baudios a 115200.
}

void loop()
{
 /* Se lee carácter por carácter por el puerto serie, mientras, se va
 concatenando uno tras otro en una cadena. */
 while (Serial.available() > 0)
 {
   caracter = Serial.read();
   comando.concat(caracter);
   delay(10); // Este retardo muy corto es para no saturar el puerto
   // serie y que la concatenación se haga de forma ordenada.
 }

 if (comando.equals("Led_8_ON") == true) // Si la cadena o comando "Led_8_ON" es verdadero.
 {
   digitalWrite(8, !HIGH); // El Led 8 se enciende.
   Serial.println("Led 8 encendido."); // Envía mensaje por puerto serie.
 }

 if (comando.equals("Led_8_OFF") == true) // Si el comando "Led_8_OFF" es verdadero.
 {
   digitalWrite(8, !LOW); // Se apaga el Led 8.
   Serial.println("Led 8 apagado."); // Envía mensaje por puerto serie.
 }

 if (comando.equals("Led_13_ON") == true)
 {
   digitalWrite(13, !HIGH);
   Serial.println("Led 13 encendido.");
 }

 if (comando.equals("Led_13_OFF") == true)
 {
   digitalWrite(13, !LOW);
   Serial.println("Led 13 apagado.");
 }

 // Limpiamos la cadena para volver a recibir el siguiente comando.
 comando = "";
}


Lo que hace es recibir comandos por el puerto serie. Por ahora solo quiero saber como se prepara esa librería RXTX en el NMetBeans 8.xx, no para la 7.x.

Es de 64 bits el que tengo instalado bajo Windows 7.


Paso 1.
http://www.subeimagenes.com/img/fsdafasdfsad-1239041.png

Paso 2.
http://www.subeimagenes.com/img/fsdafasdfsad-1239044.png

Paso 3.
http://www.subeimagenes.com/img/fsdafasdfsad-1239046.png

Hasta aquí he lelgado y solo me falta cargar la librería RxTx que on se hacerlo y necesito ayuda. He estado viendo por internet con netbeans 7.x y parece ser que no es igual que l a8.

[youtube=640,360]https://www.youtube.com/watch?v=g7XPhDL6auA[/youtube]

Saludos.
#749
Hola:

Tengo este código con WPF C# 2013. Puedo enviar datos pero no recibirlos y se muestre en RichTextBox.
Código (vb) [Seleccionar]


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.IO.Ports; // No olvidar.
using System.Threading;

namespace WpfApplication1
{
    /// <summary>
    /// Lógica de interacción para MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        // Utilizaremos un string como buffer de recepción.
        string Recibidos;

        SerialPort serialPort1 = new SerialPort();

        public MainWindow()
        {
            InitializeComponent();

            serialPort1.BaudRate = 115200;
            serialPort1.PortName = "COM4";
            serialPort1.Parity = Parity.None;
            serialPort1.DataBits = 8;
            serialPort1.StopBits = StopBits.Two;

            // Abrir puerto mientras se ejecute la aplicación.
            if (!serialPort1.IsOpen)
            {
                try
                {
                    serialPort1.Open();
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }

            }

            // Ejecutar la función REcepción por disparo del Evento ¡DataReived'.
            //serialPort1.DataReceived += new SerialDataReceivedEventHandler(Recepcion);
        }

        private void Recepcion(object sender, SerialDataReceivedEventHandler e)
        {
            // Acumular los caracteres recibidos a nuestro 'buffer' (string).
            Recibidos += serialPort1.ReadExisting();

            // Invocar o llamar al proceso de tramas.
            //this.Invoke(new EventHandler(Actualizar));
             
        }


        // Procesar los datos recibidos en el buffer y estraer tramas completas.
        private void Actualizar(object s, EventArgs e)
        {
            // Asignar el valor de la trama al RichTextBox.
            RichTextBox_Mensajes.DataContext = Recibidos;
        }

        private void Button_Led_8_ON_Click(object sender, RoutedEventArgs e)
        {
            byte[] mBuffer = Encoding.ASCII.GetBytes("Led_8_ON");
            serialPort1.Write(mBuffer, 0, mBuffer.Length);
        }

        private void Button_Led_8_OFF_Click(object sender, RoutedEventArgs e)
        {
            byte[] mBuffer = Encoding.ASCII.GetBytes("Led_8_OFF");
            serialPort1.Write(mBuffer, 0, mBuffer.Length);
            RichTextBox_Mensajes.DataContext = "Hola";
        }

    }
}


Alguna solución donde está el problema.

Saludos.
#750


1)El programa espera la recepciòn de un ENQ(05 Hex) o STX(02 Hex)

2) Si recibo lo del paso 1 , le envìo un ACK(06 Hex)

3)Luego de enviado el ACK leo todo lo que me manda la maquina externa, si es distinto de cualquier caracter de control, lo muestro.

4) Si recibo un EOT(04 Hex) mando un enter en la pantalla de recepcion para diferenciar las lineas.

5) Si recibo un ETX(03 Hex) le respondo con un ACK.

Supongo que en este caso se podrìa hacer un if o un select preguntando lo recibido, el tema es que no se como leer de manera correcta y poder comparar que es lo que se recibio para poder ejecutar la tarea necesaria segun lo que llega.

Código (vbnet) [Seleccionar]
Imports System.IO.Ports
Imports System.Text

Public Class Form1
    Dim recibidos As String
    Dim stx As String = ASCIIEncoding.ASCII.GetString(New Byte() {2})
    Dim etx As String = ASCIIEncoding.ASCII.GetString(New Byte() {3})
    Dim eot As String = ASCIIEncoding.ASCII.GetString(New Byte() {4})
    Dim enq As String = ASCIIEncoding.ASCII.GetString(New Byte() {5})
    Dim ack As String = ASCIIEncoding.ASCII.GetString(New Byte() {6})


    Public Sub New()
        InitializeComponent()
        If Not SerialPort1.IsOpen Then
            Try
                SerialPort1.Open()
            Catch ex As Exception
                MessageBox.Show(ex.ToString)
            End Try
        End If
        AddHandler SerialPort1.DataReceived, AddressOf recepcion
    End Sub

    Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If SerialPort1.IsOpen Then
            SerialPort1.Close()
        End If
    End Sub

    Private Sub recepcion(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs)

        recibidos = Chr(SerialPort1.ReadChar)
        If recibidos = stx Or recibidos = enq Then
            SerialPort1.Write(ack)
        Else
            If recibidos <> stx And recibidos <> etx And recibidos <> enq And recibidos <> ack And recibidos <> eot Then
                Me.Invoke(New EventHandler(AddressOf actualizar))
            Else
                If recibidos = eot Then
                    Me.Invoke(New EventHandler(AddressOf actualizarenter))
                Else
                    If recibidos = etx Then
                        SerialPort1.Write(ack)
                    End If
                End If
            End If
        End If


    End Sub

    Private Sub actualizar(ByVal s As Object, ByVal e As EventArgs)
        textbox_visualizar_mensaje.Text = textbox_visualizar_mensaje.Text & recibidos
    End Sub

    Private Sub actualizarenter(ByVal s As Object, ByVal e As EventArgs)
        textbox_visualizar_mensaje.Text = textbox_visualizar_mensaje.Text & vbLf
    End Sub

    Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
        StatusStrip1.Items(0).Text = DateTime.Now.ToLongTimeString
    End Sub

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        SerialPort1.Encoding = System.Text.Encoding.Default
    End Sub
End Class