forked from scream3r/java-simple-serial-connector
-
Notifications
You must be signed in to change notification settings - Fork 54
Examples
Tres Finocchiaro edited this page Apr 5, 2019
·
13 revisions
String[] ports = SerialPortList.getPortNames();
for(int i = 0; i < ports.length; i++) {
System.out.println(ports[i]);
}
import static jssc.SerialPort.*;
SerialPort port = new SerialPort("COM1");
port.openPort();
port.setParams(BAUDRATE_9600, DATABITS_8, STOPBITS_1, PARITY_NONE);
// port.setParams(9600, 8, 1, 0); // alternate technique
port.writeBytes("Testing serial from Java".getBytes());
port.closePort();
import static jssc.SerialPort.*;
SerialPort port = new SerialPort("COM1");
port.openPort();
port.setParams(BAUDRATE_9600, DATABITS_8, STOPBITS_1, PARITY_NONE);
// port.setParams(9600, 8, 1, 0); // alternate technique
byte[] buffer = port.readBytes(10 /* read first 10 bytes */);
serialPort.closePort();
Note: The mask is an additive quantity, thus to set a mask on the expectation of the arrival of Event Data (MASK_RXCHAR
) and change the status lines CTS
(MASK_CTS
), DSR
(MASK_DSR
) we just need to combine all three masks.
import static jssc.SerialPort.*;
SerialPort port = new SerialPort("COM1");
port.openPort();
port.setParams(BAUDRATE_9600, DATABITS_8, STOPBITS_1, PARITY_NONE);
// port.setParams(9600, 8, 1, 0); // alternate technique
int mask = SerialPort.MASK_RXCHAR + SerialPort.MASK_CTS + SerialPort.MASK_DSR;
port.setEventsMask(mask);
port.addEventListener(new SerialPortReader() /* defined below */);
/*
* In this class must implement the method serialEvent, through it we learn about
* events that happened to our port. But we will not report on all events but only
* those that we put in the mask. In this case the arrival of the data and change the
* status lines CTS and DSR
*/
static class SerialPortReader implements SerialPortEventListener {
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR()){//If data is available
if(event.getEventValue() == 10){ // Check bytes count in the input buffer
//Read data, if 10 bytes available
try {
byte buffer[] = serialPort.readBytes(10);
} catch (SerialPortException ex) {
System.out.println(ex);
}
}
}
else if(event.isCTS()){//If CTS line has changed state
if(event.getEventValue() == 1){ //If line is ON
System.out.println("CTS - ON");
} else {
System.out.println("CTS - OFF");
}
} else if(event.isDSR()){ ///If DSR line has changed state
if(event.getEventValue() == 1){ //If line is ON
System.out.println("DSR - ON");
} else {
System.out.println("DSR - OFF");
}
}
}
}