I am a beginner java developer. I have a problem with reading from com port. Code:
public class Main {
private static SerialPort serialPort;
public static void main(String[] args) {
serialPort = new SerialPort("COM3");
try {
serialPort.openPort();
Thread.sleep(2000);
serialPort.setParams(SerialPort.BAUDRATE_57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
serialPort.writeBytes("Test".getBytes());
serialPort.setEventsMask(SerialPort.MASK_RXCHAR);
serialPort.addEventListener(new EventListener());
}
catch (SerialPortException | InterruptedException ex) {
System.out.println(ex);
}
}
private static class EventListener implements SerialPortEventListener {
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() == 8){
try {
byte[] buffer = serialPort.readBytes(8);
for(int i = 0; i < buffer.length; i++){
System.out.println("Output" + buffer[i]);
}
serialPort.closePort();
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
}
}
Nothing is displayed but I know that the data are written. Help, please.
What is the lib you are using for comm/serial stuff?
You may try add serialPort.addEventListener(new EventListener()); line before you send anything, this is possible that a receive event is sent before listener mapping.
Related
we are receiving data from controller using terminal software and as well as also java program ..
but think is that we get proper data on terminal software but java program can not show like terminal .. actually data come in ASCII and we convert to HEX terminal application show proper data but java program can not show terminal data.....
java program data
import java.io.*; // IOException
import java.util.*; // Scanner
import jssc.*;
/**
*
* #author Emiliarge
*/
public class ComPortSendReceive1 {
private static SerialPort serialPort;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String[] portNames = SerialPortList.getPortNames();
if (portNames.length == 0) {
System.out.println("There are no serial-ports :( You can use an emulator, such ad VSPE, to create a virtual serial port.");
System.out.println("Press Enter to exit...");
try {
System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
// выбор порта
System.out.println("Available com-ports:");
for (int i = 0; i < portNames.length; i++){
System.out.println(portNames[i]);
}
System.out.println("Type port name, which you want to use, and press Enter...");
Scanner in = new Scanner(System.in);
String portName = in.next();
// writing to port
serialPort = new SerialPort(portName);
try {
// opening port
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN |
SerialPort.FLOWCONTROL_RTSCTS_OUT);
serialPort.addEventListener(new PortReader(), SerialPort.MASK_RXCHAR);
// writing string to port
serialPort.writeString("Hurrah!!!");
System.out.println("String wrote to port, waiting for response..");
}
catch (SerialPortException ex) {
System.out.println("Error in writing data to port: " + ex);
}
}
// receiving response from port
private static class PortReader implements SerialPortEventListener {
#Override
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() > 0) {
try {
// получение ответа от порта
String receivedData = serialPort.readString(event.getEventValue());
for (char ch : receivedData.toCharArray()) {
System.out.format("%H ", ch);
} // prints "31 32 2E 30 31 33 "
}
catch (SerialPortException ex) {
System.out.println("Error in receiving response from port: " + ex);
}
}
}
}
}
I'm trying to read a String from my Sara g350 module. I'm using a serial port comunication. The code that I use is this one:
private static SerialPort serialPort;
public static void main(String[] args) {
String[] portNames = SerialPortList.getPortNames();
if (portNames.length == 0) {
System.out.println("There are no serial-ports :( You can use an emulator, such ad VSPE, to create a virtual serial port.");
System.out.println("Press Enter to exit...");
try {
System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
// OPEN PORT
System.out.println("Available com-ports:");
for (int i = 0; i < portNames.length; i++){
System.out.println(portNames[i]);
}
System.out.println("Type port name, which you want to use, and press Enter...");
Scanner in = new Scanner(System.in);
String portName = in.next();
// writing to port
serialPort = new SerialPort(portName);
try {
// opening port
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN |
SerialPort.FLOWCONTROL_RTSCTS_OUT);
serialPort.addEventListener(new PortReader(), SerialPort.MASK_RXCHAR);
// writing string to port
serialPort.writeString("AT+CMEE=2");
System.out.println("String wrote to port, waiting for response..");
}
catch (SerialPortException ex) {
System.out.println("Error in writing data to port: " + ex);
}
}
// receiving response from port
private static class PortReader implements SerialPortEventListener {
#Override
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() > 0) {
try {
// получение ответа от порта
String receivedData = serialPort.readString(event.getEventValue());
System.out.println("Received response from port: " + receivedData);
}
catch (SerialPortException ex) {
System.out.println("Error in receiving response from port: " + ex);
}
}
}
}
}
The Problem is that i read only the eco response and not all String.
I send "AT+CMEE=2" and the response could be:
AT+CMEE=2
OK
Can anyone help me? Thank you!
I'm writing a java program to read data from COM3 port. Data sent by Arduino [1]: https://imgur.com/a/MiNfTZN
But in Java Program (I'm using JSSC) it return � character. If I use RXTX, it return java.io.IOException: Underlying input stream returned zero bytes. I wonder how I can fix it?
This is my code
Using JSSC:
public class SerialTestJSSC {
private static SerialPort serialPort;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String[] portNames = SerialPortList.getPortNames();
if (portNames.length == 0) {
System.out.println("There are no serial-ports :( You can use an emulator, such ad VSPE, to create a virtual serial port.");
System.out.println("Press Enter to exit...");
try {
System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
// выбор порта
System.out.println("Available com-ports:");
for (int i = 0; i < portNames.length; i++){
System.out.println(portNames[i]);
}
System.out.println("Type port name, which you want to use, and press Enter...");
Scanner in = new Scanner(System.in);
String portName = in.next();
// writing to port
serialPort = new SerialPort(portName);
try {
// opening port
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN |
SerialPort.FLOWCONTROL_RTSCTS_OUT);
serialPort.addEventListener(new PortReader(), SerialPort.MASK_RXCHAR);
// writing string to port
serialPort.writeString("Hurrah!!!");
System.out.println("String wrote to port, waiting for response..");
}
catch (SerialPortException ex) {
System.out.println("Error in writing data to port: " + ex);
}
}
// receiving response from port
private static class PortReader implements SerialPortEventListener {
#Override
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() > 0) {
try {
// получение ответа от порта
String receivedData = serialPort.readString(event.getEventValue());
System.out.println("Received response from port: " + receivedData);
}
catch (SerialPortException ex) {
System.out.println("Error in receiving response from port: " + ex);
}
}
}
}
Using RXTX
public class SerialTest implements SerialPortEventListener {
SerialPort serialPort;
/** The port we're normally going to use. */
private static final String PORT_NAMES[] = {
"COM3", // Windows
};
/**
* A BufferedReader which will be fed by a InputStreamReader
* converting the bytes into characters
* making the displayed results codepage independent
*/
private static BufferedReader input;
/** The output stream to the port */
private OutputStream output;
/** Milliseconds to block while waiting for port open */
private static final int TIME_OUT = 2000;
/** Default bits per second for COM port. */
private static final int DATA_RATE = 9600;
public void initialize() {
// the next line is for Raspberry Pi and
// gets us into the while loop and was suggested here was suggested http://www.raspberrypi.org/phpBB3/viewtopic.php?f=81&t=32186
//System.setProperty("gnu.io.rxtx.SerialPorts", "/dev/ttyACM0");
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
//First, Find an instance of serial port as set in PORT_NAMES.
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
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 = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
output = serialPort.getOutputStream();
// add event listeners
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} 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();
}
}
/**
* Handle an event on the serial port. Read the data and print it.
*/
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
String inputLine=input.readLine();
System.out.println("System "+inputLine);
} catch (Exception e) {
System.err.println(e.toString());
}
}
// Ignore all the other eventTypes, but you should consider the other ones.
}
public static void main(String[] args) throws Exception {
SerialTest main = new SerialTest();
main.initialize();
Thread t=new Thread() {
public void run() {
try {
Thread.sleep(1000000);} catch (InterruptedException ie) {}
}
};
t.start();
System.out.println("Started");
}}
I've created a Java thread that reads data through serial port. The main parts of the code is given below:
public class dthread implements Runnable{
public dthread(CommPortIdentifier portId)implements SerialPortEventListener {
try {
serialPort = (SerialPort) portId.open(this.getClass().getName(),TIME_OUT);
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
// open the streams
input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {System.err.println(e.toString());}
}
public void serialEvent(SerialPortEvent oEvent){
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
String inputLine =null;
try {
// String inputLine=null;
if (input.ready()) {
inputLine = input.readLine();
System.out.println(inputLine);
}
} catch (Exception e) {System.err.println(e.toString());}
}
}
public void run() {}
}
portId - contains commportidentifier info. about the connected COM port; from another class.
public dthread(CommPortIdentifier portId)implements SerialPortEventListener { clearly, this is wrong. How should I implement SerialPortEvent in my code?
i want to send commands to to an embadded pc whihch connected to my pc through serial port ... here is the code that i use ...
public class Write {
static Enumeration portList;
static CommPortIdentifier portId;
static String messageString = "Hello, world!\n";
static SerialPort serialPort;
static OutputStream outputStream;
public static void main(String[] args) {
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM1")) {
try {
serialPort = (SerialPort) portId.open("SimpleWriteApp", 2000);
System.out.println("openning the port...");
} catch (PortInUseException e) {
}
try {
outputStream = serialPort.getOutputStream();
System.out.println("sending the command...");
} catch (IOException e) {
}
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
}
try {
outputStream.write(messageString.getBytes());
serialPort.close();
} catch (IOException e) {
}
}
}
}
}
}
is this code is correct, or there should be some modification to this code ....
If it works then there's nothing obviously wrong that I can see! The only thing I'd point out is that it's good practice to put close statements (such as when you're closing the serial port at the end) in finally blocks so they're always executed (VM termination aside.) At present if there's an exception thrown by outputStream.write(messageString.getBytes()); the close() method wouldn't be executed.
You also shouldn't ignore exceptions, at least do a printStackTrace() to make sure there's nothing happening.