Baixe o app para aproveitar ainda mais
Esta é uma pré-visualização de arquivo. Entre para ver o arquivo original
/* * 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. */ package led; /** * * @author Kassandra */ public class Led { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here } } package Arduino; import ControlePorto.ControlePorta; import javax.swing.JButton; public class Arduino { private final ControlePorta arduino; /** * Construtor da classe Arduino */ public Arduino(){ arduino = new ControlePorta("COM3",9600);//Windows - porta e taxa de transmissão //arduino = new ControlePorta("/dev/ttyUSB0",9600);//Linux - porta e taxa de transmissão } /** * Envia o comando para a porta serial * @param button - Botão que é clicado na interface Java */ public void comunicacaoArduino(JButton button) { if(null != button.getActionCommand())switch (button.getActionCommand()) { case "Ligar": arduino.enviaDados(1); System.out.println(button.getText());//Imprime o nome do botão pressionado break; case "Desligar": arduino.enviaDados(2); System.out.println(button.getText()); break; default: arduino.close(); System.out.println(button.getText());//Imprime o nome do botão pressionado break; } } } /* * 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. */ package ControlePorto; import gnu.io.CommPortIdentifier; import gnu.io.NoSuchPortException; import gnu.io.SerialPort; import java.io.IOException; import java.io.OutputStream; import javax.swing.JOptionPane; public class ControlePorta { private OutputStream serialOut; private int taxa; private String portaCOM; /** * Construtor da classe ControlePorta * @param portaCOM - Porta COM que será utilizada para enviar os dados para o arduino * @param taxa - Taxa de transferência da porta serial geralmente é 9600 */ public ControlePorta(String portaCOM, int taxa){ this.portaCOM = portaCOM; this.taxa = taxa; this.initialize(); } /** * Médoto que verifica se a comunicação com a porta serial está ok */ private void initialize() { try { //Define uma variável portId do tipo CommPortIdentifier para realizar a comunicação serial CommPortIdentifier portId = null; try { //Tenta verificar se a porta COM informada existe portId = CommPortIdentifier.getPortIdentifier(this.portaCOM); } catch (NoSuchPortException npe) { //Caso a porta COM não exista será exibido um erro JOptionPane.showMessageDialog(null, "Porta COM não encontrada.", "Porta COM", JOptionPane.PLAIN_MESSAGE); } //Abre a porta COM SerialPort port = (SerialPort) portId.open("Comunicação serial", this.taxa); serialOut = port.getOutputStream(); port.setSerialPortParams(this.taxa, //taxa de transferência da porta serial SerialPort.DATABITS_8, //taxa de 10 bits 8 (envio) SerialPort.STOPBITS_1, //taxa de 10 bits 1 (recebimento) SerialPort.PARITY_NONE); //receber e enviar dados }catch (Exception e) { e.printStackTrace(); } } /** * Método que fecha a comunicação com a porta serial */ public void close() { try { serialOut.close(); }catch (IOException e) { JOptionPane.showMessageDialog(null, "Não foi possível fechar porta COM.", "Fechar porta COM", JOptionPane.PLAIN_MESSAGE); } } /** * @param opcao - Valor a ser enviado pela porta serial */ public void enviaDados(int opcao){ try { serialOut.write(opcao);//escreve o valor na porta serial para ser enviado } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Não foi possível enviar o dado. ", "Enviar dados", JOptionPane.PLAIN_MESSAGE); } } } /* * 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 Kassandra */ package JFInterface; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JButton; public class Led extends javax.swing.JFrame { Led conn = new Led(); public Led() { initComponents(); } /** * 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() { JBLedOn = new javax.swing.JButton(); JBLedOff = new javax.swing.JButton(); JBClose = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); JBLedOn.setText("Ligar"); JBLedOn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { JBLedOnMouseClicked(evt); } }); JBLedOff.setText("Desligar"); JBLedOff.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { JBLedOffMouseClicked(evt); } }); JBClose.setText("Sair"); JBClose.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { JBCloseMouseClicked(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(64, 64, 64) .addComponent(JBLedOn, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(48, 48, 48) .addComponent(JBLedOff)) .addGroup(layout.createSequentialGroup() .addGap(140, 140, 140) .addComponent(JBClose, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(66, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(55, 55, 55) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(JBLedOn, javax.swing.GroupLayout.DEFAULT_SIZE, 39, Short.MAX_VALUE) .addComponent(JBLedOff, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(18, 18, 18) .addComponent(JBClose, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(20, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void JBLedOnMouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: conn.comunicacaoLed(JBLedOn); } private void JBLedOffMouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: conn.comunicacaoLed(JBLedOff); } private void JBCloseMouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: conn.comunicacaoLed(JBClose); System.exit(0);//fecha aplicacao } /** * @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(Led.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Led.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Led.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Led.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 Led().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton JBClose; private javax.swing.JButton JBLedOff; private javax.swing.JButton JBLedOn; // End of variables declaration private void comunicacaoLed(JButton JBLedOn) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } } /* * 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. */ package led; /** * * @author Kassandra */ public class Led { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here } }
Compartilhar