Autor Tema: Conexión μCtrol (ARDUINO, RASPBERRY- π, …) <-> JAVA(PC/LINUX/MAC) +GUI  (Leído 2426 veces)

0 Usuarios y 1 Visitante están viendo este tema.

Desconectado CompSystems

  • PIC18
  • ****
  • Mensajes: 488
    • Home Page
Hola, en este hilo comenzare a exponer mi experiencia sobre conexión JAVA(GUI) <-> arduino.
La GUI puede ser usada como una interfaz de control, similares a las que realiza LABVIEW, PROCESSING, PYTHON

biblioteca a usar: PanamaHitek_Arduino basada en RXTX library
http://panamahitek.com/libreria-panamahitek_arduino/
https://sourceforge.net/projects/arduinoyjava/?source=typ_redirect



video #1 enviar datos unidireccionalmente solo desde JAVA y capturado en el arduino TX(JAVA) -> RX(ARDUINO) usando la biblioteca PanamaHitek_Arduino

código JAVA del ejemplo anterior pero adaptado y mejorado para arduino mega 2560, este código solo contiene 2 botones para apagar o encender el led del pin 13, [Encender] envía "1" [Apagar]  transmite "0"

Código: Java
  1. package SERIAL;
  2.  
  3. import com.panamahitek.PanamaHitek_Arduino;
  4. import java.util.logging.Level;
  5. import java.util.logging.Logger;
  6.  
  7. public class GUI_conexion_JAVARDUINO extends javax.swing.JFrame {
  8.  
  9.     PanamaHitek_Arduino conexion_JAVARDUINO = new PanamaHitek_Arduino();
  10.  
  11.     public GUI_conexion_JAVARDUINO() {
  12.         initComponents();
  13.  
  14.         try {
  15.             //  arduinoTX, solo para enviar información a arduino
  16.             conexion_JAVARDUINO.arduinoTX("COM3", 9600);
  17.         } catch (Exception ex) {
  18.             Logger.getLogger(GUI_conexion_JAVARDUINO.class.getName()).log(Level.SEVERE, null, ex);
  19.         }
  20.     }
  21.  
  22.                      
  23.     private void initComponents() {
  24.  
  25.         btnEncenderLed = new javax.swing.JButton();
  26.         btnApagarLed = new javax.swing.JButton();
  27.  
  28.         setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  29.  
  30.         btnEncenderLed.setText("Encender Led");
  31.         btnEncenderLed.addActionListener(new java.awt.event.ActionListener() {
  32.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  33.                 btnEncenderLedActionPerformed(evt);
  34.             }
  35.         });
  36.  
  37.         btnApagarLed.setText("Apagar Led");
  38.         btnApagarLed.addActionListener(new java.awt.event.ActionListener() {
  39.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  40.                 btnApagarLedActionPerformed(evt);
  41.             }
  42.         });
  43.  
  44.         ....
  45.  
  46.         pack();
  47.     }                    
  48.  
  49.     private void btnApagarLedActionPerformed(java.awt.event.ActionEvent evt) {                                            
  50.         try {
  51.             conexion_JAVARDUINO.sendData("0");
  52.         } catch (Exception ex) {
  53.             Logger.getLogger(GUI_conexion_JAVARDUINO.class.getName()).log(Level.SEVERE, null, ex);
  54.         }
  55.  
  56.     }                                            
  57.  
  58.     private void btnEncenderLedActionPerformed(java.awt.event.ActionEvent evt) {                                              
  59.         try {
  60.             conexion_JAVARDUINO.sendData("1");
  61.         } catch (Exception ex) {
  62.             Logger.getLogger(GUI_conexion_JAVARDUINO.class.getName()).log(Level.SEVERE, null, ex);
  63.         }
  64.     }                                              
  65.  
  66.    
  67.     public static void main(String args[]) {
  68.        ...
  69.     }
  70.              
  71.     private javax.swing.JButton btnApagarLed;
  72.     private javax.swing.JButton btnEncenderLed;
  73.                  
  74. }

Código en arduino
Código: C++
  1. int input;
  2.  
  3. void setup() {
  4.   //"inicio de conexion JAVA ARDUINO"
  5.   Serial.begin(9600);
  6.   pinMode(13, OUTPUT);
  7.   delay(1000);
  8.  
  9.   // "prueba del led pin13"
  10.   Serial.println();
  11.   digitalWrite(13, LOW);
  12.   delay(500);
  13.   digitalWrite(13, HIGH);
  14.   delay(500);
  15. }
  16.  
  17. void loop() {
  18.   // Puerto serial disponible
  19.   if (Serial.available() >  0) {
  20.  
  21.     input = Serial.read();
  22.     Serial.println(input );
  23.     if (input == '1') {
  24.     //"encender"
  25.       digitalWrite(13, HIGH);
  26.     }
  27.     else if (input == '0') {
  28.       //"apagar"
  29.       digitalWrite(13, LOW);
  30.     }
  31.  
  32.   }
  33.  
  34. }
« Última modificación: 26 de Marzo de 2016, 13:50:33 por CompSystems »
Desde Colombia

Desconectado CompSystems

  • PIC18
  • ****
  • Mensajes: 488
    • Home Page
Re:Conexión μCtrol (ARDUINO, RASPBERRY- π, …) <-> JAVA(PC/LINUX/MAC) +GUI
« Respuesta #1 en: 10 de Marzo de 2016, 23:01:26 »
video #2 enviar datos bidireccionalmente entre JAVA y arduino TX/RX(JAVA) <->TX/RX(ARDUINO) usando la biblioteca PanamaHitek_Arduino y vídeo del mismo autor de la biblioteca


Codigo JAVA
Código: Java
  1. package SERIAL;
  2.  
  3. import com.panamahitek.PanamaHitek_Arduino;
  4. import gnu.io.SerialPortEvent;
  5. import gnu.io.SerialPortEventListener;
  6. import java.util.logging.Level;
  7. import java.util.logging.Logger;
  8.  
  9. public class GUI_conexion_JAVARDUINO extends javax.swing.JFrame {
  10.  
  11.     PanamaHitek_Arduino conexion_JAVARDUINO = new PanamaHitek_Arduino();
  12.    
  13. // evento para capturar datos enviados desde Arduino
  14.     SerialPortEventListener evento_de_recepcion_de_datos = new SerialPortEventListener() {
  15.         @Override
  16.         public void serialEvent(SerialPortEvent spe) {
  17.             // si se a terminado de recibir una cadena de caracteres
  18.             if (conexion_JAVARDUINO.MessageAvailable() == true) {
  19.                 // imprimir mensaje
  20.                 System.out.println(conexion_JAVARDUINO.printMessage());
  21.              }
  22.         }
  23.     };
  24.  
  25.     public GUI_conexion_JAVARDUINO() {
  26.         initComponents();
  27.  
  28.         try {
  29.             //  arduinoTXRX, solo para enviar y recibir información de un arduino
  30.             conexion_JAVARDUINO.ArduinoRXTX("COM3", 2000, 9600, evento_de_recepcion_de_datos);
  31.         } catch (Exception ex) {
  32.             Logger.getLogger(GUI_conexion_JAVARDUINO.class.getName()).log(Level.SEVERE, null, ex);
  33.         }
... el resto es igual al código anterior


Codigo en Arduino
Código: C++
  1. int input;
  2.  
  3. void setup() {
  4.   Serial.begin(9600);
  5.   pinMode(13, OUTPUT);
  6.   Serial.println("inicio de conexion JAVA ARDUINO");
  7.   delay(1000);
  8.  
  9.   Serial.println("prueba del led pin13");
  10.   digitalWrite(13, LOW);
  11.   delay(500);
  12.   digitalWrite(13, HIGH);
  13.   delay(500);
  14. }
  15.  
  16. void loop() {
  17.   // Puerto serial disponible
  18.   if (Serial.available() >  0) {
  19.  
  20.     input = Serial.read();
  21.     Serial.println(input );
  22.     if (input == '1') {
  23.       digitalWrite(13, HIGH);
  24.       Serial.println("encender");
  25.     }
  26.     else if (input == '0') {
  27.       digitalWrite(13, LOW);
  28.       Serial.println("apagar");
  29.     }
  30.  
  31.   }
  32.  
  33. }

Método para recibir carácter por caracter
Código: Java
  1. // evento para capturar datos enviados desde Arduino
  2.     SerialPortEventListener evento_de_recepcion_de_datos = new SerialPortEventListener() {
  3.         @Override
  4.         public void serialEvent(SerialPortEvent spe) {
  5.  
  6.             try {
  7.             // Imprima la conversion de valor numérico ASCII a Caracter
  8.             System.out.println((char)conexion_JAVARDUINO.receiveData());
  9.             } catch (Exception ex) {
  10.                 Logger.getLogger(GUI_conexion_JAVARDUINO.class.getName()).log(Level.SEVERE, null, ex);
  11.             }
  12.  
  13.         }
  14.     };
« Última modificación: 26 de Marzo de 2016, 13:50:52 por CompSystems »
Desde Colombia

Desconectado CompSystems

  • PIC18
  • ****
  • Mensajes: 488
    • Home Page
Re:Conexión μCtrol (ARDUINO, RASPBERRY- π, …) <-> JAVA(PC/LINUX/MAC) +GUI
« Respuesta #2 en: 11 de Marzo de 2016, 00:00:54 »
Vídeo #3 mas completo sobre el mismo ejemplo #1 y #2 usando la biblioteca PanamaHitek_Arduino y vídeo del mismo autor de la biblioteca



« Última modificación: 26 de Marzo de 2016, 13:51:04 por CompSystems »
Desde Colombia

Desconectado CompSystems

  • PIC18
  • ****
  • Mensajes: 488
    • Home Page
Re:Tema: Conexión ARDUINO <-> JAVA(PC/LINUX/MAC/RaspberryPI) + GUI
« Respuesta #3 en: 16 de Marzo de 2016, 11:43:00 »
vídeos #4 usando la biblioteca original "RXTX Java Library 2.1-7r2", en la cual se baso la biblioteca PanamaHitek_Arduino


Info: https://geekytheory.com/tutorial-java-arduino-javaduino/

Codigo Java
Código: Java
  1. import gnu.io.CommPortIdentifier;
  2. import gnu.io.SerialPort;
  3. import java.io.OutputStream;
  4. import java.util.Enumeration;
  5. import javax.swing.ImageIcon;
  6. import javax.swing.JOptionPane;
  7.  
  8. /*
  9.  * To change this license header, choose License Headers in Project Properties.
  10.  * To change this template file, choose Tools | Templates
  11.  * and open the template in the editor.
  12.  */
  13. /**
  14.  *
  15.  * @author  
  16.  */
  17. public class GUI_conexion_JAVARDUINO extends javax.swing.JFrame {
  18.  
  19.     /**
  20.      * Creates new form GUI_conexion_JAVARDUINO
  21.      */
  22.     private static final String YELLOW_LED_OFF = "0";
  23.     private static final String YELLOW_LED_ON = "1";
  24.     private static final String RED_LED_OFF = "1";
  25.     private static final String RED_LED_ON = "3";
  26.  
  27.     // IDs de conexion
  28.     // OutputStream es una clase abstracta de la que no pueden crearse objetos. No obstante, todos los objetos que se creen de clases derivadas dispondrán de algunas operaciones interesantes:
  29.     // que respectivamente escriben un byte, un array de bytes, o una zona de un vector de bytes.
  30.     private OutputStream output = null; // requiere: import java.io.OutputStream;
  31.     SerialPort serialPort; // requiere: import java.io.OutputStream;
  32.     private final String PUERTO = "COM4";
  33.     // Tiempo de espera (ms) mientras se abre el puerto serie
  34.     private static final int TIMEOUT = 2000;
  35.     private static final int DATA_RATE = 9600;
  36.  
  37.     public GUI_conexion_JAVARDUINO() {
  38.         initComponents();
  39.         inicializarConexion();
  40.         jLabel1.setIcon(new ImageIcon("src/RedLED_OFF_icon.png"));
  41.         jLabel2.setIcon(new ImageIcon("src/YellowLED_OFF_icon.png"));
  42.     }
  43.  
  44.     public void inicializarConexion() {
  45.         CommPortIdentifier puertoID = null; // requiere: import gnu.io.CommPortIdentifier;
  46.         // lista de puertos encontrados
  47.         Enumeration puertoEnum = CommPortIdentifier.getPortIdentifiers(); // requiere: import java.util.Enumeration;
  48.         // Mientras tenga mas elementos
  49.         while (puertoEnum.hasMoreElements()) {
  50.             CommPortIdentifier actualPuertoID = (CommPortIdentifier) puertoEnum.nextElement();
  51.             if (PUERTO.equals(actualPuertoID.getName())) {
  52.             }
  53.             puertoID = actualPuertoID;
  54.             break;
  55.         }
  56.         if (puertoID == null) {
  57.             mostrarError("No se puede conectar al puerto" + PUERTO);
  58.             System.exit(ERROR);
  59.         }
  60.  
  61.         try {
  62.             serialPort = (SerialPort) puertoID.open(this.getClass().getName(), TIMEOUT);
  63.             //parametros puerto serie
  64.             serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
  65.             // Flujo de datos
  66.             output = serialPort.getOutputStream();
  67.         } catch (Exception e) {
  68.             mostrarError(e.getMessage());
  69.             System.exit(ERROR);
  70.         }
  71.     }
  72.  
  73.     private void enviarDatos(String datos) {
  74.         try {
  75.             output.write(datos.getBytes());
  76.  
  77.         } catch (Exception e) {
  78.             mostrarError("ERROR ENVIAR");
  79.             System.exit(ERROR);
  80.         }
  81.     }
  82.  
  83.     private void mostrarError(String mensaje) {
  84.         JOptionPane.showMessageDialog(this, mensaje, "ERROR", JOptionPane.ERROR_MESSAGE);
  85.     }
  86.  
  87.     /**
  88.      * This method is called from within the constructor to initialize the form.
  89.      * WARNING: Do NOT modify this code. The content of this method is always
  90.      * regenerated by the Form Editor.
  91.      */
  92.     @SuppressWarnings("unchecked")
  93.     // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  94.     private void initComponents() {
  95.  
  96.         btnLED_ON = new javax.swing.JButton();
  97.         btnLED_OFF = new javax.swing.JButton();
  98.         jLabel1 = new javax.swing.JLabel();
  99.         jLabel2 = new javax.swing.JLabel();
  100.         radBtnRed = new javax.swing.JRadioButton();
  101.         radBtnYellow = new javax.swing.JRadioButton();
  102.  
  103.         setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  104.  
  105.         btnLED_ON.setText("LED OFF");
  106.         btnLED_ON.addActionListener(new java.awt.event.ActionListener() {
  107.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  108.                 btnLED_ONActionPerformed(evt);
  109.             }
  110.         });
  111.  
  112.         btnLED_OFF.setText("LED ON");
  113.  
  114.         jLabel1.setText("jLabel1");
  115.  
  116.         jLabel2.setText("jLabel1");
  117.  
  118.         radBtnRed.setText("LED ROJO");
  119.  
  120.         radBtnYellow.setText("LED AMARILLO");
  121.  
  122.         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  123.         getContentPane().setLayout(layout);
  124.         layout.setHorizontalGroup(
  125.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  126.             .addGroup(layout.createSequentialGroup()
  127.                 .addContainerGap()
  128.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  129.                     .addGroup(layout.createSequentialGroup()
  130.                         .addComponent(radBtnYellow)
  131.                         .addGap(0, 0, Short.MAX_VALUE))
  132.                     .addGroup(layout.createSequentialGroup()
  133.                         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  134.                             .addComponent(btnLED_ON)
  135.                             .addComponent(jLabel1))
  136.                         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 173, Short.MAX_VALUE)
  137.                         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  138.                             .addComponent(btnLED_OFF)
  139.                             .addComponent(jLabel2))
  140.                         .addGap(75, 75, 75))
  141.                     .addGroup(layout.createSequentialGroup()
  142.                         .addComponent(radBtnRed)
  143.                         .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
  144.         );
  145.         layout.setVerticalGroup(
  146.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  147.             .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  148.                 .addContainerGap()
  149.                 .addComponent(radBtnRed)
  150.                 .addGap(18, 18, 18)
  151.                 .addComponent(radBtnYellow)
  152.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 129, Short.MAX_VALUE)
  153.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  154.                     .addComponent(jLabel1)
  155.                     .addComponent(jLabel2))
  156.                 .addGap(18, 18, 18)
  157.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  158.                     .addComponent(btnLED_ON)
  159.                     .addComponent(btnLED_OFF))
  160.                 .addGap(45, 45, 45))
  161.         );
  162.  
  163.         pack();
  164.     }// </editor-fold>                        
  165.  
  166.     private void btnLED_ONActionPerformed(java.awt.event.ActionEvent evt) {                                          
  167.         // TODO add your handling code here:
  168.     }                                        
  169.  
  170.     /**
  171.      * @param args the command line arguments
  172.      */
  173.     public static void main(String args[]) {
  174.         /* Set the Nimbus look and feel */
  175.         //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  176.         /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  177.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
  178.          */
  179.         try {
  180.             for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  181.                 if ("Nimbus".equals(info.getName())) {
  182.                     javax.swing.UIManager.setLookAndFeel(info.getClassName());
  183.                     break;
  184.                 }
  185.             }
  186.         } catch (ClassNotFoundException ex) {
  187.             java.util.logging.Logger.getLogger(GUI_conexion_JAVARDUINO.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  188.         } catch (InstantiationException ex) {
  189.             java.util.logging.Logger.getLogger(GUI_conexion_JAVARDUINO.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  190.         } catch (IllegalAccessException ex) {
  191.             java.util.logging.Logger.getLogger(GUI_conexion_JAVARDUINO.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  192.         } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  193.             java.util.logging.Logger.getLogger(GUI_conexion_JAVARDUINO.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  194.         }
  195.         //</editor-fold>
  196.  
  197.         /* Create and display the form */
  198.         java.awt.EventQueue.invokeLater(new Runnable() {
  199.             public void run() {
  200.                 new GUI_conexion_JAVARDUINO().setVisible(true);
  201.             }
  202.         });
  203.     }
  204.  
  205.     // Variables declaration - do not modify                    
  206.     private javax.swing.JButton btnLED_OFF;
  207.     private javax.swing.JButton btnLED_ON;
  208.     private javax.swing.JLabel jLabel1;
  209.     private javax.swing.JLabel jLabel2;
  210.     private javax.swing.JRadioButton radBtnRed;
  211.     private javax.swing.JRadioButton radBtnYellow;
  212.     // End of variables declaration                  
  213. }
« Última modificación: 25 de Marzo de 2016, 11:10:22 por CompSystems »
Desde Colombia


 

anything