Wenn du's unter Windows machst, probier einfach mal das, dann brauchst du nicht mal zusätzliche Bibliotheken:
Das öffnet den Seriellen Port 1 mit 4800 bps, keine Parität, 8 bits, 1 stop bit.Code:File serial = new File("com1:4800,n,8,1");
Wenn du mein Beispiel von oben benutzen möchtest, beachte die Installationsanweisungen.
Wichtig ist:
win32com.dll ins <JDK>/bin Verzeichnis kopieren
javax.comm.properties ins <JDK>/lib Verzeichnis kopieren
und natürlich die comm.jar in den classpath
Hier das Beispiel, das ich oben gepostet habe, zusätzlich für Windows (das Beispiel war nur für Linux):
Das Programm gibt dann die Bytes aus, die ein Gerät am seriellen Port sendet.....Code:package de.robot.communication; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.TooManyListenersException; import javax.comm.CommPortIdentifier; import javax.comm.PortInUseException; import javax.comm.SerialPort; import javax.comm.SerialPortEvent; import javax.comm.SerialPortEventListener; import javax.comm.UnsupportedCommOperationException; public class Simple implements Runnable, SerialPortEventListener { static CommPortIdentifier portId; static Enumeration portList; InputStream inputStream; SerialPort serialPort; Thread readThread; public Simple() { try { serialPort = (SerialPort) portId.open("SimpleReadApp", 2000); } catch (PortInUseException e) { } try { inputStream = serialPort.getInputStream(); } catch (IOException e) { } try { serialPort.addEventListener(this); } catch (TooManyListenersException e) { } serialPort.notifyOnDataAvailable(true); try { serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (UnsupportedCommOperationException e) { } readThread = new Thread(this); readThread.start(); } public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { } } 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[20]; try { while (inputStream.available() > 0) { int numBytes = inputStream.read(readBuffer); } System.out.println(new String(readBuffer)); } catch (IOException e) { } break; } } public static void main(String[] args) { System.out.println("listing ports..."); boolean portFound = false; portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) { portFound = true; portId = (CommPortIdentifier) portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { System.out.println("\tfound port: " + portId.getName()); Simple reader = new Simple(); } } if (!portFound) { System.out.println("no port found!"); } } }







Zitieren

Lesezeichen