Visualizzazione dei risultati da 1 a 5 su 5
  1. #1
    Utente di HTML.it
    Registrato dal
    Jun 2012
    Messaggi
    12

    RS232 - Scrittura con Jbutton e lettura

    Ciaoo a tutti,

    siccome sono alle prime armi con Java e devo sviluppare una GUI, ho il problema che non riesco a visualizzare le informazioni che invio tramite un bottone, collegamento seriale (RS232) ad una bilancia dal PC.

    In pratica la bilancia ha un comando specifico per la lettura del peso tramite seriale, e questo comando (chiamiamolo P) dovrebbe esser associato al Jbotton che ho creato, sotto forma di stringa nascosta.

    Sotto vi posto i 2 metodi di lettura e scrittura (con l'opzione JTexArea, nel codice della GUI, funzionano correttamente):

    codice:
    .....
    .....
    public void serialEvent(SerialPortEvent event) {
            switch (event.getEventType()) {
          case SerialPortEvent.BI:
          case SerialPortEvent.OE:
          case SerialPortEvent.FE:
          case SerialPortEvent.PE:
          case SerialPortEvent.CD:
          case SerialPortEvent.CTS:
          case SerialPortEvent.DSR:
          case SerialPortEvent.RI:
          case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
             break;
          case SerialPortEvent.DATA_AVAILABLE:
    
              byte[] readBuffer = new byte[64];
             try {
                    // read data
                    int numBytes = inputStream.read(readBuffer);
                    inputStream.close();
               
                    //send the received data to the GUI
                    String result = new String(readBuffer,0,numBytes);
                    gui.setjtaReceived(result);
                    
                    System.out.println(result);
                    
             }
             catch (IOException e) {exceptionReport(e);}
             break;
          }
        }   //end of serialEvent() method
    
    ....
    ....
       
        public void writetoport(String outString) {
       	 
          try { if(portOpen)
                    outputStream.write(outString.getBytes()); 
          			System.out.println(outString.getBytes());
          
          }
          catch (IOException e) {exceptionReport(e);}
    
         }
    ....
    ....
    Con l'opzione Jbutton per l'invio "nascosto" della stringa P, al click del bottone:

    codice:
    .......
    .......
            jbPesoP.setText("P");
            jbPesoP.setToolTipText("P");
            jbPesoP.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                	jbPesoPActionPerformed(evt);
                }
            });   
    
    private void jbPesoPActionPerformed(java.awt.event.ActionEvent evt){
        	 if(Bilancia.portOpen){	
       		 System.out.println("\n "+jbPesoP.getText());
        		 main.writetoport(jbPesoP.getText());
        		 jbPesoIP.setText("P");
        	 }   
        }
    
    ....
    ....
    Non riesco a leggere il peso, forse mi sfugge qualcosa.

    Spero di essere stato esaustivo.

    in ogni caso vi ringrazio anticipatamente.

  2. #2
    Utente di HTML.it
    Registrato dal
    Jun 2012
    Messaggi
    12
    Ciao,
    non c'è proprio nessuno disponibile a darmi una mano???

    Frimpa


  3. #3
    Utente di HTML.it
    Registrato dal
    Oct 2011
    Messaggi
    147
    Di solito, essendo le funzioni di lettura da uno stream bloccanti, è buona norma utilizzare un thread apposito che stia sempre in ascolto sulla porta attraverso cui arrivano le risposte ai tuoi comandi. Anche se probabilmente stai usando javax.comm dai un'occhiata al semplice codice di esempio di rxtx che permette collegamento, lettura e scrittura utilizzando una seriale:

    http://rxtx.qbang.org/wiki/index.php...he_serial_port

    Come vedi, sia la lettura che la scrittura avvengono in thread separati. Non dovrebbe essere molto difficile inserire un JButton con l'invio dei tuoi comandi.

  4. #4
    Utente di HTML.it
    Registrato dal
    Jun 2012
    Messaggi
    12
    Ciao watermark, grazie per l'info !!!

    Utilizzo pure quella libreria, la RxTx.

    Ho provato di nuovo a smanettare il codice, non vuole saperne proprio nulla di leggere il peso con Jbutton. La cosa strana è che con la JTextArea funziona correttamente.

    Ve lo posto, magari riuscite ad individuare il problema anche perchè non vorrei iniziare tutto daccapo visto che per far funzionare questo ho dovuto "sbattere" la testa ovunque.

    Se è proprio necessario tenterò la strada di utilizzare due thread appositi, per la lettura e scrittura.

    codice:
    import javax.swing.*;
    import gnu.io.*;
    import java.io.*;
    import java.util.*;
    @SuppressWarnings("serial")
    public class MainProva extends JFrame implements SerialPortEventListener
    {
    /*** My Variables ***********************************************************/
        GUIProva                     gui;                //class defining the graphical user interface
        SerialPort              serialPort;
        InputStream             inputStream;
        OutputStream            outputStream;
        CommPortIdentifier      portIdentifier;   
        boolean                 debug;              //true to print exception reports, false for release
        static String[]         portNames;    
        static boolean          portOpen;
        static int              baud,databits,parity,stopbits;
    
    /*** Constructor ************************************************************/
        public MainProva() 
    {          
            debug = false;                  //Activates exception reports used for debugging
            portOpen = false;               //flags whether a port is currently open
            portNames = new String[10];     //ports found on this computer, 10 maximum
            baud = 9600;                    //default baud setting
            databits = 8;                   //default databits setting
            parity = 0;                     //default parity setting
            stopbits = 1;                   //default stopbits setting
            findPorts();                    //this method populates the string[] portNames
        }
    
    /*** main method ************************************************************/
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    MainProva main=new MainProva();
                    main.init();      
                }
            });
        }
    
    /*** called by main() *******************************************************/
         private void init() {  
             gui=new GUIProva(this);
             gui.setVisible(true);
             initwritetoport();  
         }
         private void findPorts() {
             Enumeration<CommPortIdentifier> portEnum =
                    CommPortIdentifier.getPortIdentifiers();
            int portCount = 0;
            while ( portEnum.hasMoreElements() ) {
                portIdentifier = portEnum.nextElement();
                // populate the portNames array for display in gui.jcbPort
                //if the port is a serial port
                if(portCount < portNames.length &&
                        portIdentifier.getPortType() == portIdentifier.PORT_SERIAL)
                {
                    //put it in the array
                    portNames[portCount] = portIdentifier.getName();
                    portCount++;                
                }
            }        
         }
         public void RS232Setup(String portName) {
            Enumeration<CommPortIdentifier> portEnum =
                    CommPortIdentifier.getPortIdentifiers();
            if(portOpen) {                          //close any currently open port
                try {
                    inputStream.close();
                }
                catch(IOException e) {exceptionReport(e);}
                serialPort.notifyOnDataAvailable(false);
                serialPort.close();
                serialPort.removeEventListener();
            }
            portOpen = false;                   //clear the portOpen flag       
            while ( portEnum.hasMoreElements() ) {
                portIdentifier = portEnum.nextElement();
               if(portIdentifier.getName().equals(portName)
                        && portIdentifier.getPortType() == portIdentifier.PORT_SERIAL)
               {
                   gui.setjlStatus(portName + " found.");
                   try {    //try to open the port
                            serialPort = (SerialPort)portIdentifier.open("CommUtil", 2000);
                            portOpen = true;        //if successful, update the portOpen flag
                            break;
                   }
                   catch (PortInUseException e) {                   
                        gui.setjlStatus("Port "  + portIdentifier.getName() + " is in use.");
                    }
                   catch (Exception e) {                   
                       gui.setjlStatus("Failed to open port " +  portIdentifier.getName());
                    }
               }
            }   //end of while loop
            //if we succeeded in opening the port, set it up for operation
            if(portOpen) {
            try {
                     inputStream = serialPort.getInputStream();
            }
            catch (IOException e) {exceptionReport(e);}
            try {
                    serialPort.addEventListener(this);
            }
            catch (TooManyListenersException e) {exceptionReport(e);}
            // activate the DATA_AVAILABLE notifier
            serialPort.notifyOnDataAvailable(true);
            try {
                //set the port parameters
                serialPort.setSerialPortParams(baud, databits, stopbits, parity);
                //update to gui to display current status
                gui.setjlStatus(portName,
                                serialPort.getBaudRate(),
                                serialPort.getParity(),
                                serialPort.getDataBits(),
                                serialPort.getStopBits(),
                                portOpen);
                //update the gui open/close port button
                gui.setjbOpenClose(portOpen);
            }
            catch (UnsupportedCommOperationException e) {exceptionReport(e);}
            initwritetoport();
            }
        }   //end of RS232Setup() method   
        public void serialEvent(SerialPortEvent event) {
            switch (event.getEventType()) {
          case SerialPortEvent.BI:
          case SerialPortEvent.OE:
          case SerialPortEvent.FE:
          case SerialPortEvent.PE:
          case SerialPortEvent.CD:
          case SerialPortEvent.CTS:
          case SerialPortEvent.DSR:
          case SerialPortEvent.RI:
          case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
             break;
          case SerialPortEvent.DATA_AVAILABLE:
              byte[] readBuffer = new byte[64];
             try {
                    // read data
                    int numBytes = inputStream.read(readBuffer);
                    inputStream.close();         
                    //send the received data to the GUI
                    String result = new String(readBuffer,0,numBytes);
                    gui.setjtaReceived(result);             
                    System.out.println(result);             
             }
             catch (IOException e) {exceptionReport(e);}
             break;
          }
        }   //end of serialEvent() method  
         public void initwritetoport() {     
            if(portOpen) {
            try {
                // get the outputstream
                outputStream = serialPort.getOutputStream();
            } catch (IOException e) {exceptionReport(e);}
            try {
                // activate the OUTPUT_BUFFER_EMPTY notifier
                serialPort.notifyOnOutputEmpty(true);
            } catch (Exception e) {
                exceptionReport(e);
                System.exit(-1);
            }
          }
          }     //end of initwritetoport() method   
        public void writetoport(String outString) { 	 
          try { if(portOpen)
                    outputStream.write(outString.getBytes()); 
          			System.out.println(outString.getBytes());
          
          }
          catch (IOException e) {exceptionReport(e);}
         }     
    	public void exceptionReport(Exception e) {
            if(debug) {
                System.out.println(e.toString());
                e.printStackTrace();
            }
        }
    }

  5. #5
    Utente di HTML.it
    Registrato dal
    Jun 2012
    Messaggi
    12
    La GUI ha troppi caratteri per postarlo quì.

    Se avete altra soluzione fatemi sapere,

    grazie.

    Frimpa

    P.S. Scusatemi la lunghezza del codice.

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.