//Teste de lecture sur le port série int b = in.read(); System.out.println(in.read()); System.out.println(b); in.close();
package test_serial_port; import java.io.DataInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import javax.comm.CommPortIdentifier; import javax.comm.SerialPort; import com.sun.comm.Win32Driver; /** * This class allows opening, closing, reading and writing from and to a serial port * (using the RS232 protocol) on Windows plateform. * In order to work properly, the following procedure MUST already be done : * 1. Download the following content from this url : * {@link http://www.cs.uml.edu/~fredm/courses/91.305/software/JDK118-javaxcomm.zip} * 2. Copy and paste the file "win32com.dll" into the directory : C:\Windows\System32 * 3. Copy and paste the file "javax.comm.properties" into the directory C:\Program Files\Java\jre\lib * 4. Copy and paste the file "comm.jar" into the directory C:\Program Files\Java\jre\lib\ext * 5. Open Eclipse and add the "comm.jar" file (found in 4.) into the classPath * (right click on Java project > properties > Java Build Path > Libraries > Add external Jars...) * 6. Enjoy! * @author lionkid */ public class RS232 { private static final String appName = "Envoi"; // Application name that request opening the serial port. private static final int openTimeOut = 5000; // 5seconds. private CommPortIdentifier portId; private DataInputStream in; private PrintWriter out; private SerialPort serialPort; private static final int databits = SerialPort.DATABITS_8; // RS-232 configuration private static final int stopbit = SerialPort.STOPBITS_1; // RS-232 configuration private static final int parity = SerialPort.PARITY_NONE; // RS-232 configuration private static final int baudrate = 9600; // RS-232 configuration /** * Constructor * @param com the communication port to open * @author lionkid */ public RS232(String com, boolean listAvailablePorts) { Win32Driver w32Driver = new Win32Driver(); w32Driver.initialize(); try { // Listing or not available serial and parallel ports found... if(listAvailablePorts) System.out.println(availableSerialCommPorts()); // Opening com port... System.out.println("Trying to open serial port '" + com + "'..."); portId = CommPortIdentifier.getPortIdentifier(com); serialPort = (SerialPort) portId.open(appName, openTimeOut); System.out.println("Successfully opened serial port '" + serialPort.getName() + "'!"); // Setting the serial connection as requested... serialPort.setSerialPortParams(baudrate, databits, stopbit, parity); in = new DataInputStream(serialPort.getInputStream()); } catch(Exception e) { System.out.println(e.getMessage()); System.exit(1); // Exit application! Adapt if needed! } } /** * Read input stream through the RS-232 protocol * (from the serial or parallel communication port) * @return * @author lionkid */ public char read() { try { return in.readChar(); } catch (IOException e) { System.out.println("Error when trying to read! "+e.getMessage()); System.exit(1); // Exit application! Adapt if needed! } return '0'; // Returns the '0' char caracter if reading fails } /** * Send a message through the serial port * @param sendMsg * @author lionkid */ public void send(String sendMsg) { try { out.write(sendMsg); } catch(Exception e) { System.out.println("Is port available and opened?\n"+e.getMessage()); System.exit(1); // Exit application! Adapt if needed! } } /** * Close serial connection * @param none * @return * @author lionkid */ public void closeConnection() { try { in.close(); out.close(); } catch (IOException e) { System.out.println("Cannot open and / or close serial connection!Details:\n"+e.getMessage()); System.exit(1); // Exit application! Adapt if needed! } } /** * List all the available serial and parallel communication ports * @return the list of all available serial and parallel communication ports. */ public String availableSerialCommPorts() { System.err.println("Searching..."); String list = ""; Enumeration<Object> portList = CommPortIdentifier.getPortIdentifiers(); if (portList == null) // port(s) not found { System.err.println("No communication port detected!"); // notify it in the console return null; } else // port(s) found { System.err.println("Detected serial communication ports !\n"); while (portList.hasMoreElements()) { portId = (CommPortIdentifier) portList.nextElement(); // get the found port System.out.println("Found : "+portId.getName()); // notify it in the console list += portId.getName()+"\n"; // add it in the String list } return list; // Return the full list } } /** * Typical example of use of the RS232 class * @param args * @author lionkid */ public static void main(String args[]) { RS232 example = new RS232("COM1", true); // List all the available and found port com and try opening "COM1". example.send("Hello world!"); // Send the "Hello world!" string through the RS-232 System.out.println(example.read()); // Get the message sent by the remote device through the RS-232 protocol. example.closeConnection(); // Close the connection. } }
/** * Send a message through the serial port * @param sendMsg * @author lionkid */ public void send(String sendMsg) { try { out.write(sendMsg); out.flush(); } catch(Exception e) { System.out.println("Is port available and opened?\n"+e.getMessage()); System.exit(1); // Exit application! Adapt if needed! } }
Vous n’avez pas trouvé la réponse que vous recherchez ?
Posez votre questionpackage test_serial_port; import java.io.DataInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import javax.comm.CommPortIdentifier; import javax.comm.SerialPort; import com.sun.comm.Win32Driver; /** * This class allows opening, closing, reading and writing from and to a serial port * (using the RS232 protocol) on Windows plateform. * In order to work properly, the following procedure MUST already be done : * 1. Download the following content from this url : * {@link http://www.cs.uml.edu/~fredm/courses/91.305/software/JDK118-javaxcomm.zip} * 2. Copy and paste the file "win32com.dll" into the directory : C:\Windows\System32 * 3. Copy and paste the file "javax.comm.properties" into the directory C:\Program Files\Java\jre\lib * 4. Copy and paste the file "comm.jar" into the directory C:\Program Files\Java\jre\lib\ext * 5. Open Eclipse and add the "comm.jar" file (found in 4.) into the classPath * (right click on Java project > properties > Java Build Path > Libraries > Add external Jars...) * 6. Enjoy! * @author lionkid */ public class RS232 { private static final String appName = "Envoi"; // Application name that request opening the serial port. private static final int openTimeOut = 5000; // 5seconds. private CommPortIdentifier portId; private DataInputStream in; private PrintWriter out; private SerialPort serialPort; private static final int databits = SerialPort.DATABITS_8; // RS-232 configuration private static final int stopbit = SerialPort.STOPBITS_1; // RS-232 configuration private static final int parity = SerialPort.PARITY_NONE; // RS-232 configuration private static final int baudrate = 9600; // RS-232 configuration /** * Constructor * @param com the communication port to open * @author lionkid */ public RS232(String com, boolean listAvailablePorts) { Win32Driver w32Driver = new Win32Driver(); w32Driver.initialize(); try { // Listing or not available serial and parallel ports found... if(listAvailablePorts) System.out.println(availableSerialCommPorts()); // Opening com port... System.out.println("Trying to open serial port '" + com + "'..."); portId = CommPortIdentifier.getPortIdentifier(com); serialPort = (SerialPort) portId.open(appName, openTimeOut); System.out.println("Successfully opened serial port '" + serialPort.getName() + "'!"); // Setting the serial connection as requested... serialPort.setSerialPortParams(baudrate, databits, stopbit, parity); in = new DataInputStream(serialPort.getInputStream()); out = new PrintWriter(serialPort.getOutputStream()); } catch(Exception e) { System.out.println(e.getMessage()); System.exit(1); // Exit application! Adapt if needed! } } /** * Read input stream through the RS-232 protocol * (from the serial or parallel communication port) * @return * @author lionkid */ public char read() { try { return in.readChar(); } catch (IOException e) { System.out.println("Error when trying to read! "+e.getMessage()); System.exit(1); // Exit application! Adapt if needed! } return '0'; // Returns the '0' char caracter if reading fails } /** * Send a message through the serial port * @param sendMsg * @author lionkid */ public void send(String sendMsg) { try { out.write(sendMsg); out.flush(); } catch(Exception e) { System.out.println("Is port available and opened?\n"+e.getMessage()); System.exit(1); // Exit application! Adapt if needed! } } /** * Close serial connection * @param none * @return * @author lionkid */ public void closeConnection() { try { in.close(); out.close(); } catch (IOException e) { System.out.println("Cannot open and / or close serial connection!Details:\n"+e.getMessage()); System.exit(1); // Exit application! Adapt if needed! } } /** * List all the available serial and parallel communication ports * @return the list of all available serial and parallel communication ports. */ public String availableSerialCommPorts() { System.err.println("Searching..."); String list = ""; Enumeration<Object> portList = CommPortIdentifier.getPortIdentifiers(); if (portList == null) // port(s) not found { System.err.println("No communication port detected!"); // notify it in the console return null; } else // port(s) found { System.err.println("Detected serial communication ports !\nFound:\n"); while (portList.hasMoreElements()) { portId = (CommPortIdentifier) portList.nextElement(); // get the found port list += portId.getName()+"\n"; // add it in the String list } return list; // Return the full list } } /** * Typical example of use of the RS232 class * @param args * @author lionkid */ public static void main(String args[]) { RS232 example = new RS232("COM1", true); // List all the available and found port com and try opening "COM1". example.send("Hello world!"); // Send the "Hello world!" string through the RS-232 System.out.println("Received message = '"+example.read()+"'"); // Get the message sent by the remote device through the RS-232 protocol. example.closeConnection(); // Close the connection. } }
RS232 example = new RS232("COM1", true); example.send("0R0"); System.out.println("test ecriture OK"); System.out.println(example.read()); System.out.println("test lecture OK"); example.closeConnection();
while(in.available()>0) // Sors du while, lorsqu'il n'y a plus de données à lire { msg+=msg+in.read(); } return msg;
public byte[] readBytes() { try { byte buffer[] = new byte[1024]; int n=0, offset=0, i=0; while(true) { i = in.available(); n = in.read(buffer, offset, i); if (n<=0 || n == i) break; offset+=n; } return buffer; } catch (IOException e) { return null; } }
serialPort.notifyOnFramingError(false); serialPort.notifyOnOverrunError(false); serialPort.notifyOnParityError(false); // Set notifyOnDataAvailable to true to allow event driven input. serialPort.notifyOnDataAvailable(true); serialPort.notifyOnOutputEmpty(true); // Set notifyOnBreakInterrup to allow event driven break handling. serialPort.notifyOnBreakInterrupt(true); // Set receive timeout to allow breaking out of polling loop during // input handling. try { serialPort.enableReceiveTimeout(timeoutRx); // perso je place timeoutRx = 5000 } catch (javax.comm.UnsupportedCommOperationException e) { e.printStackTrace(); }
package RS232; import java.io.DataInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import javax.comm.CommPortIdentifier; import javax.comm.SerialPort; import com.sun.comm.Win32Driver; /** * This class allows opening, closing, reading and writing from and to a serial port * (using the RS232 protocol) on Windows plateform. * In order to work properly, the following procedure MUST already be done : * 1. Download the following content from this url : * {@link http://www.cs.uml.edu/~fredm/courses/91.305/software/JDK118-javaxcomm.zip} * 2. Copy and paste the file "win32com.dll" into the directory : C:\Windows\System32 * 3. Copy and paste the file "javax.comm.properties" into the directory C:\Program Files\Java\jre\lib * 4. Copy and paste the file "comm.jar" into the directory C:\Program Files\Java\jre\lib\ext * 5. Open Eclipse and add the "comm.jar" file (found in 4.) into the classPath * (right click on Java project > properties > Java Build Path > Libraries > Add external Jars...) * 6. Enjoy! * @author lionkid */ public class RS232 { private static final String appName = "Envoi"; // Application name that request opening the serial port. private static final int openTimeOut = 5000; // 5seconds. private CommPortIdentifier portId; private DataInputStream in; private PrintWriter out; private SerialPort serialPort; private static final int baudrate = 9600; // RS-232 configuration private static final int databits = SerialPort.DATABITS_8; // RS-232 configuration private static final int stopbit = SerialPort.STOPBITS_1; // RS-232 configuration private static final int parity = SerialPort.PARITY_NONE; // RS-232 configuration /** * Constructor * @param com the communication port to open * @author lionkid */ public RS232(String com, boolean listAvailablePorts) { Win32Driver w32Driver = new Win32Driver(); w32Driver.initialize(); try { // Listing or not available serial and parallel ports found... if(listAvailablePorts) System.out.println(availableSerialCommPorts()); // Opening com port... System.out.println("Trying to open serial port '" + com + "'..."); portId = CommPortIdentifier.getPortIdentifier(com); serialPort = (SerialPort) portId.open(appName, openTimeOut); System.out.println("Successfully opened serial port '" + serialPort.getName() + "'!"); // Setting the serial connection as requested... serialPort.setSerialPortParams(baudrate, databits, stopbit, parity); in = new DataInputStream(serialPort.getInputStream()); out = new PrintWriter(serialPort.getOutputStream()); } catch(Exception e) { System.out.println(e.getMessage()); System.exit(1); // Exit application! Adapt if needed! } } /** * Read input stream through the RS-232 protocol * (from the serial or parallel communication port) * @return * @author lionkid */ public char read() { try { return in.readChar(); } catch (IOException e) { System.out.println("Error when trying to read! "+e.getMessage()); System.exit(1); // Exit application! Adapt if needed! } return '0'; // Returns the '0' char caracter if reading fails } /** * Send a message through the serial port * @param sendMsg * @author lionkid */ public void send(String sendMsg) { try { out.write(sendMsg); } catch(Exception e) { System.out.println("Is port available and opened?\n"+e.getMessage()); System.exit(1); // Exit application! Adapt if needed! } } /** * Close serial connection * @param none * @return * @author lionkid */ public void closeConnection() { try { in.close(); out.close(); } catch (IOException e) { System.out.println("Cannot open and / or close serial connection!Details:\n"+e.getMessage()); System.exit(1); // Exit application! Adapt if needed! } } /** * List all the available serial and parallel communication ports * @return the list of all available serial and parallel communication ports. */ public String availableSerialCommPorts() { System.err.println("Searching..."); String list = ""; Enumeration<Object> portList = CommPortIdentifier.getPortIdentifiers(); if (portList == null) // port(s) not found { System.err.println("No communication port detected!"); // notify it in the console return null; } else // port(s) found { System.err.println("Detected serial communication ports !\n"); while (portList.hasMoreElements()) { portId = (CommPortIdentifier) portList.nextElement(); // get the found port System.out.println("Found : "+portId.getName()); // notify it in the console list += portId.getName()+"\n"; // add it in the String list } return list; // Return the full list } } public byte[] readBytes() { try { byte buffer[] = new byte[1024]; int n=0, offset=0, i=0; while(true) { i = in.available(); n = in.read(buffer, offset, i); if (n<=0 || n == i) break; offset+=n; } return buffer; } catch (IOException e) { return null; } } /** * Typical example of use of the RS232 class * @param args * @author lionkid */ public static void main(String args[]) { RS232 example = new RS232("COM1", true); // List all the available and found port com and try opening "COM1". example.send("0R0"); System.out.println("test ecriture OK");// Send the "Hello world!" string through the RS-232 //System.out.println(example.read()); System.out.println("test lecture OK");// Get the message sent by the remote device through the RS-232 protocol. example.closeConnection(); // Close the connection. } }
public static void main(String args[]) { RS232 example = new RS232("COM1", true); // List all the available and found port com and try opening "COM1". example.send("0R0"); System.out.println("test ecriture OK");// Send the "Hello world!" string through the RS-232 byte buffer = example.readBytes(); if(buffer == null) System.err.println("Read error, see the stack trace for more details..."); else { // on demande à java de transformer la chaîne bytes en String. // Attention il se peut que la chaîne contienne des données non affichables System.out.println(new String(b, 0, b.length); System.out.println("test lecture OK");// Get the message sent by the remote device through the RS-232 protocol. } example.closeConnection(); // Close the connection. }
while(in.available()>0) // while data is available, keep reading... { msg+=in.read(); } return msg;
//System.out.println(example.read());)
byte[] buffer, non?
private InputStreamReader in = new InputStreamReader(serialPort.getInputStream()); private BufferedReader data_in = new BufferedReader(in);
public String readString() { String msg = ""; try { while(data_in.available() > 0) { msg+=data_in.readLine(); } return msg; } catch(IOException ioe) { System.out.println("Reading error : "ioe.getMessage()); System.exit(1); } }
System.out.println(example.readString()); // :)
// Set notifyOnDataAvailable to true to allow event driven input. serialPort.notifyOnDataAvailable(true); serialPort.notifyOnOutputEmpty(true); // Set notifyOnBreakInterrup to allow event driven break handling. serialPort.notifyOnBreakInterrupt(true); // Set receive timeout to allow breaking out of polling loop during // input handling. try { serialPort.enableReceiveTimeout(timeoutRx); // perso je place timeoutRx = 5000 } catch (javax.comm.UnsupportedCommOperationException e) { e.printStackTrace(); }