how to send command to embedded pc connected by serial port - java

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.

Related

Arduino Uno in Proteus send � character

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");
}}

How to detect COM port connection loss(phsically) while application is running

i use RXTXcomm Library to connect COM port
if COM port connection is loss(physically) while application is running
I don't know whether Port is connect or not.
even the signal is still alive when the COM port is physically disconnected.
How i can detect COM port connection loss??
here my code
public class SerialSample implements SerialPortEventListener{
private InputStream in;
private OutputStream out;
public SerialSample() {
super();
}
void connect(String portName) throws Exception {
CommPortIdentifier portIdentifier = CommPortIdentifier
.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned()) {
} else {
CommPort commPort = portIdentifier.open(this.getClass().getName(),
2000);
if (commPort instanceof SerialPort) {
//System.out.println("connect");
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
in = serialPort.getInputStream();
out = serialPort.getOutputStream();
} else {
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
#Override
public synchronized void serialEvent(SerialPortEvent arg0) {
// TODO Auto-generated method stub
if (arg0.getEventType() == SerialPortEvent.DATA_AVAILABLE){
try{
int a = in.available();
byte chunk[] = new byte[a];
in.read(chunk, 0, a);
System.out.println(new String(chunk) + " , " + a);
inputSignal();
}catch(Exception e){
System.out.println(e.toString());
}
}
}

How to add an EventListener to a thread - Java

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?

sending a char to usb port by java coded in eclipse IDE

I have an arduino USB interfacing boarding which is already coded to glow an LED when it receives an "L" from usb port. I just want a java code. rxtx is already correctly setup.. test file run successfully.
here is my code:(I took help from internet)
import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
import java.io.*;
import java.util.*;
public class SimpleWrite {
#SuppressWarnings("rawtypes")
static Enumeration portList;
static CommPortIdentifier portId;
static String messageString = "L";
static SerialPort serialPort;
static OutputStream outputStream;
public static void main(String[] args) throws IOException{
portList = CommPortIdentifier.getPortIdentifiers();
int i;
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM12")) {
// if (portId.getName().equals("/dev/term/a")) {
while(( i=System.in.read()) != 13)
messageString += (char)i;
try {
serialPort = (SerialPort)
portId.open("SimpleWriteApp", 2000);
} catch (PortInUseException e) {System.out.println(e);}
try {
outputStream = serialPort.getOutputStream();
} catch (IOException e) {System.out.println(e);}
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {System.out.println(e);}
try { System.out.println(messageString);
outputStream.write(messageString.getBytes());
} catch (IOException e) {System.out.println(e);}
}
}
}
}
}
there is no warning no error shown in eclipse console. But LED remain in off stage. COM-PORT , BAUDRATE PARITY everything were checked by XCTU.
Where am I going wrong?

Read and write simultaneously on com port

My question is that isn't it possible to read and write simultaneously on one com port? This is just for demo purpose, I will only be reading a port once I press F5 key on the keyboard, but for demo purposes I was trying to read and write simultaneously but can't do it. It says that some other program is using the port.
UPDATE
package com_port;
import java.io.*;
import java.util.*;
import javax.comm.*;
public class simplerad implements Runnable, SerialPortEventListener
{
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
public static void main(String[] args) throws Exception
{
portList = CommPortIdentifier.getPortIdentifiers();
System.out.println("SimpleRead Started.");
while (portList.hasMoreElements())
{
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
System.out.println ("Found " + portId.getName());
if (portId.getName().equals("COM7"))
{
OutputStream outputStream;
SerialPort writePort = (SerialPort) portId.open("SimpleWriteApp", 2000);
writePort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
outputStream = writePort.getOutputStream();
outputStream.write("AT+CENG=2".getBytes());
System.out.println("write done");
writePort.close();
simplerad reader = new simplerad();
}
}
}
}
public simplerad()
{
try
{
System.out.println("1");
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
}
catch (PortInUseException e)
{
e.printStackTrace();
}
try
{
System.out.println("2");
inputStream = serialPort.getInputStream();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
System.out.println("3");
serialPort.addEventListener(this);
}
catch (TooManyListenersException e)
{
e.printStackTrace();
}
serialPort.notifyOnDataAvailable(true);
try
{
System.out.println("4");
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
}
catch (UnsupportedCommOperationException e)
{
e.printStackTrace();
}
readThread = new Thread(this);
readThread.start();
}
public void run()
{
System.out.println("5");
try
{
System.out.println("6");
Thread.sleep(200);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
public void serialEvent(SerialPortEvent event)
{
System.out.println("7");
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
{
System.out.println("8");
while (inputStream.available() > 0)
{
int numBytes = inputStream.read(readBuffer);
System.out.print(new String(readBuffer, 0, numBytes, "us-ascii"));
}
System.out.print(new String(readBuffer));
}
catch (IOException e)
{
e.printStackTrace();
}
break;
}
}
}
Why the serialEvent doesn't run?
The problem here is that you are trying to open the same COM port twice, and the answer is no, this will not work - at least the way that you are doing it here. The reason is that the underlying OS only allows one user mode handle per port.
But yes, as long as your COM port is bidirectional (most of them are) you can open a COM port and read/write to it at the same time - this is known as full duplex mode.
To get this behavior in your application you want to open your "COM7" port one time, then give your read thread access to this original object instead of trying to open it a second time. Another way is to just get your InputStream and OutputStream immediately after opening, then use these objects around the rest of your application.
I'm not sure exactly why your event listener is not firing, however your code seems a bit complex for what you are actually trying to do here. It's possible that opening/closing is causing you to miss an event notification.
Here is an example of what you should do on open, and this should be a more efficient solution than opening/closing the port in between reading and writing:
// Each of these could be object members so all your class methods have access
OutputStream outputStream;
InputStream inputStream;
SerialPort serialPort;
// Open the port one time, then init your settings
serialPort = (SerialPort)portId.open("SimpleWriteApp", 2000);
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
// Get the input/output streams for use in the application
outputStream = serialPort.getOutputStream();
inputStream = serialPort.getInputStream();
// Finally, add your event listener
serialPort.addEventListener(this);
NO,you cant read and write simultaneously on the same port.
Because to avoid deadlock condition.
i gone through your code and i found... in the while loop
while (portList.hasMoreElements())
{
}
the problem is with the while loop since portlist has no elememts to read.

Categories