2012-08-14 4 views

Répondre

0

Ok, je vais modifier le même code pour vous aider à comprendre. (Je vais supprimer l'auditeur et ajouter une substitution, ce qui est bon. Vous devez utiliser l'écouteur)

import java.io.IOException; 
import java.io.InputStream; 
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; 
    private static final String PORT = "COM32"; 
    private InputStream input; 
    private OutputStream output; 
    private static final int TIME_OUT = 2000; 
    private static final int DATA_RATE = 9600; 

    public void initialize() { 
     CommPortIdentifier portId = null; 
     Enumeration portEnum = CommPortIdentifier.getPortIdentifiers(); 
     while (portEnum.hasMoreElements()) { 
      CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement(); 
      if (currPortId.getName().equals(PORT)) { 
       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 = serialPort.getInputStream(); 
      output = serialPort.getOutputStream(); 
     } 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(); 
     } 
    } 

    public static void main(String[] args) throws Exception { 
     SerialTest main = new SerialTest(); 
     main.start(); 
    } 

    public void start() throws IOException { 
     initialize(); 
     System.out.println("Started"); 
     byte[] readBuffer = new byte[400]; 
     while (true) { 
      int availableBytes = input.available(); 
      if (availableBytes > 0) { 
       // Read the serial port 
       input.read(readBuffer, 0, availableBytes); 
       // Print it out 
       System.out.print(new String(readBuffer, 0, availableBytes)); 
      } 
     } 
    } 
} 

Exécuter ce et la charge d'un code pour Arduino écrire à la série. Ensuite, ces valeurs seront affichées par le programme. (vous devrez peut-être changer le PORT en conséquence)

Questions connexes