How do I find the right SerialPort name? - java

I want to read out some information from a Arduino over the serial port.
I use the jSerialComm library.
Here's my code:
SerialPort serialPort = SerialPort.getCommPort("COM3");
serialPort.setComPortParameters(9600, 8, 1, 0);
if(serialPort.isOpen())
{
System.out.println("SerialPort is open");
}
else
{
System.out.println("SerialPort is not open");
}
Sadly, the program says that the port is closed, but I know it's not. I guess that I named it wrong here: SerialPort.getCommPort("COM3"); So how do I have to name it so it will work?

Not sure if any of this works (can't test atm), but I hope it does:
You could maybe look up the name in Device Manager -> Ports;
You can try running this and see what it says:
SerialPort[] list= SerialPort.getCommPorts();
if (list.length == 0) {
System.out.println("No ports found");
} else {
for (int i = 0; i < list.length; i++) {
System.out.println("Port " + i + ": " + list[i].getDescriptivePortName());
}
}
Or you could just try this and see what happens:
SerialPort serialPort = SerialPort.getCommPorts()[3];
Also, have a look at your baudrates, try with the Serial Monitor closed, and try an other USB cable.

Related

Can't read result after sending AT commands to GSM modem with java and jssc

I need to send AT commands to a concrete port and get the response
public static void main(String[] args) throws InterruptedException {
try {
String[] portNames = SerialPortList.getPortNames();
if (portNames.length < 1) {
System.out.println("No ports available");
System.exit(0);
} else {
serialPort = new SerialPort("COM25");
}
System.out.println("Port opened: " + serialPort.openPort());
System.out.println("Params set: " + serialPort.setParams(9600, 8, 1, 0));
serialPort.writeBytes("AT\r\n".getBytes());
serialPort.closePort();
} catch (SerialPortException ex) {
System.out.println(ex);
}
}
Code executes perfectly but all i have in console is:
As i understand this error is not crucial, but still i'm not getting and answer from port that i need. So the QUESTION IS: how can i get the answer on my request from concrete port on concrete AT command.

how to send sensor data from arduino as a server to a jsp on tomcat?

I have Arduino with an ethernet shield. I want to send readings from the ultrasonic sensor to be displayed on a JSP that is on tomcat on my local machine.
How can I do that?
Using the Serial Communication of the Arduino you need to use the Serial-Comm library for your java Code, below is the Maven dependency:
<dependency>
<groupId>com.fazecast</groupId>
<artifactId>jSerialComm</artifactId>
<version>[2.0.0,3.0.0)</version>
</dependency>
After that pack the data received in an Object and send it to your JSP using :
request.setAttribute("key",object);
and then loop through your object to display the data within This 2 LINKS below might help you do it:
http://classes.cec.wustl.edu/~SEAS-SVC-CSE132/weeks/6/studio/
http://fazecast.github.io/jSerialComm/
This Code will help you receiving data in your java code assuming that you know how to send data from Arduino code:
SerialPort[] ports = SerialPort.getCommPorts();
System.out.println("Select a port:");
int i = 1;
for(SerialPort port : ports)
System.out.println(i++ + ": " + port.getSystemPortName());
Scanner s = new Scanner(System.in);
int chosenPort = s.nextInt();
SerialPort serialPort = ports[chosenPort - 1];
if(serialPort.openPort())
System.out.println("Port opened successfully.");
else {
System.out.println("Unable to open the port.");
return;
}
serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING, 0, 0);
Scanner data = new Scanner(serialPort.getInputStream());
int value = 0;
while(data.hasNextLine()){
try{
value = Integer.parseInt(data.nextLine());
System.out.println(value);
}
catch(Exception e){}
}
System.out.println("Done.");

Parallel Port communication Rxtx or javax.comm

Currently I am trying to communicate with a Parallel port via Java, but this has proven to be troublesome. I am currently doing a brain research using EEG and I want to send simple "event markers" to the EEG system, which must happen via Parallel Port. I have used both javax.comm and RXTX but for some reason I cannot manage to write output to the port. The test-code is as follows:
import gnu.io.*; // RXTX
// import javax.comm.*; // javax.comm
public class PrlCom {
private String msg= "1";
private OutputStream outputStream;
private InputStream inputStream;
private ParallelPort parallelPort; // can be both Rxtx or javax.comm
private CommPortIdentifier port;
// CONSTANTS
public final String PARALLEL_PORT = "LPT1";
public final String[] PORT_TYPE = { "Serial Port", "Parallel Port" };
public static void main(String[] args) {
new PrlCom();
}
public PrlCom(){
openParPort();
}
public void openParPort() {
try {
// get the parallel port connected to the EEG-system (used to be printer)
port = CommPortIdentifier.getPortIdentifier(PARALLEL_PORT);
System.out.println("\nport.portType = " + port.getPortType());
System.out.println("port type = " + PORT_TYPE[port.getPortType() - 1]);
System.out.println("port.name = " + port.getName());
// open the parallel port -- open(App name, timeout)
parallelPort = (ParallelPort) port.open("CommTest", 50);
outputStream = parallelPort.getOutputStream();
inputStream = parallelPort.getInputStream();
System.out.println("Write...");
outputStream.write(toBytes(msg.toCharArray()));
System.out.println("Flush...");
outputStream.flush();
} catch (NoSuchPortException nspe) {
System.out.println("\nPrinter Port LPT1 not found : " + "NoSuchPortException.\nException:\n" + nspe + "\n");
} catch (PortInUseException piue) {
System.out.println("\nPrinter Port LPT1 is in use : " + "PortInUseException.\nException:\n" + piue + "\n");
} catch (IOException ioe) {
System.out.println("\nPrinter Port LPT1 failed to write : " + "IOException.\nException:\n" + ioe + "\n");
} catch (Exception e) {
System.out.println("\nFailed to open Printer Port LPT1 with exeception : " + e + "\n");
} finally {
if (port != null && port.isCurrentlyOwned()) {
parallelPort.close();
}
System.out.println("Closed all resources.\n");
}
}
I got the toBytes() function from Converting char[] to byte[] . I also directly tried spam.getBytes(), which made no difference.
After running this code with the javax.comm package, the parallel port is not recognized. If I run the code with RXTX(gnu.io), I get an IOException. The entire printed output is then as follows
Stable Library
=========================================
Native lib Version = RXTX-2.1-7
Java lib Version = RXTX-2.1-7
port.portType = 2
port type = Parallel Port
port.name = LPT1
Output stream opened
Write...
Printer Port LPT1 failed to write : IOException.
Exception:
java.io.IOException: The device is not connected.
in writeByte
Closed all resources.
With Rxtx, the code can make a connection with the Parallel Port thus. However, it is unable to write a byte to the output stream. Can someone please tell me how to resolve this?
I have read in many of the other topics how outdated a parallel port is and that I should use USB. However, I am working with an EEG-system (BioSemi ActiveTwo with ActiView software) to measure brain activity and, sadly, I don't have the possibility to change this. A Parallel port-USB converter is also no option. (Odd though, that something so technologically advanced uses such outdated hardware).
Thank you so much!
I have accepted that Rxtx and javax.comm do not work anymore. Instead, I found a workaround via Python. For the answer, see
Parallel Port Communication with jnpout32pkg / jnpout32reg

how to count Usb port using java?

I want to detect list of USB Ports which are free (not occupied) in system to while I checked with CommPortIdentifier.getPortIdentifiers() while this returns me Enumeration with 0 elements
I'd add librxtxcomm.jar too in classpath.
This should return each Port detail
Enumeration pList = CommPortIdentifier.getPortIdentifiers();
System.out.println(pList.hasMoreElements());
this returns 0 mean no List/Enumeration.
Rest Code :
public class CommPortLister{
/** Simple test program. */
public static void main(String[] ap) {
new CommPortLister().list();
}
/** Ask the Java Communications API * what ports it thinks it has. */
protected void list() {
// get list of ports available on this particular computer, by calling static method in CommPortIdentifier.
System.out.println("");
Enumeration pList = CommPortIdentifier.getPortIdentifiers();
System.out.println("Before While");
// CommPortIdentifier.getPortIdentifiers();
// Process the list.
System.out.println(pList.hasMoreElements());
while (pList.hasMoreElements()) {
System.out.println("While Loop");
CommPortIdentifier cpi = (CommPortIdentifier) pList.nextElement();
System.out.print("Port " + cpi.getName() + " ");
if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL) {
System.out.println("is a Serial Port: " + cpi);
} else if (cpi.getPortType() == CommPortIdentifier.PORT_PARALLEL) {
System.out.println("is a Parallel Port: " + cpi);
} else {
System.out.println("is an Unknown Port: " + cpi);
}
}
System.out.println("After While");
}
}
Code to detect USB port while i am unable to detect USB Port
Please try using ServerSocket(portNo). If there is an service running in the port, it will error so catch the exception and try the next port.
A port number is a 16-bit unsigned integer, thus ranging from 1 to 65535.
If you need to know which ports are occupied, you may call the system command "netstat" from java.
================Edited===========================
The above information is for transport layer logical ports.If you are looking for hardware ports for peripheral devices, then you need to check the COM ports. I found the following tutorial, maybe you can give it a try, so find another tutorial that suits your need.
http://www.java-samples.com/showtutorial.php?tutorialid=11
You will need javax.comm api for this. You can grab it from http://www.java2s.com/Code/Jar/c/Downloadcomm20jar.htm or http://www.oracle.com/technetwork/java/index-jsp-141752.html
Well here the thing using that u can have available ports u can scan it.
public class GettingAvaliable {
public static void main(String args[]) {
int startPortRange = 0;
int stopPortRange = 65365;
int usedport = 0;
int unusedports = 0;
for (int i = startPortRange; i <= stopPortRange; i++) {
try {
Socket ServerSok = new Socket("127.0.0.1", i);
System.out.println("Port in use: " + i);
usedport++;
ServerSok.close();
} catch (Exception e) {
//e.printStackTrace();
}
System.out.println("Port not in use: " + i);
unusedports++;
if (i == stopPortRange) {
System.out.println("Number of Used Ports In Your Machine: "+usedport);
System.out.println("Number of Unused Ports In Your Machine: "+unusedports);
}
}
}
}

java-simple-serial-connector read/write server

I have modified the example shown on https://code.google.com/p/java-simple-serial-connector/wiki/jSSC_examples to show read/write from java program. I can run the program, however the data I send using serialPort.writeString("HelloWorld"); does not seem to be read in the SerialPortReader event class. Could any one please point what the issue is ?
public class SerialReaderWriter {
static SerialPort serialPort;
public static void main(String[] args) {
serialPort = new SerialPort("COM1");
try {
serialPort.openPort();
serialPort.setParams(9600, 8, 1, 0);
//Preparing a mask. In a mask, we need to specify the types of events that we want to track.
//Well, for example, we need to know what came some data, thus in the mask must have the
//following value: MASK_RXCHAR. If we, for example, still need to know about changes in states
//of lines CTS and DSR, the mask has to look like this: SerialPort.MASK_RXCHAR + SerialPort.MASK_CTS + SerialPort.MASK_DSR
int mask = SerialPort.MASK_RXCHAR;
//Set the prepared mask
serialPort.setEventsMask(mask);
//Add an interface through which we will receive information about events
serialPort.addEventListener(new SerialPortReader());
serialPort.writeString("HelloWorld");
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
static class SerialPortReader implements SerialPortEventListener {
public void serialEvent(SerialPortEvent event) {
//Object type SerialPortEvent carries information about which event occurred and a value.
//For example, if the data came a method event.getEventValue() returns us the number of bytes in the input buffer.
System.out.println(event.getEventType());
if(event.isRXCHAR()){
if(event.getEventValue() == 10){
try {
String data= serialPort.readString();
System.out.println(data);
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
}
//If the CTS line status has changed, then the method event.getEventValue() returns 1 if the line is ON and 0 if it is OFF.
else if(event.isCTS()){
if(event.getEventValue() == 1){
System.out.println("CTS - ON");
}
else {
System.out.println("CTS - OFF");
}
}
else if(event.isDSR()){
if(event.getEventValue() == 1){
System.out.println("DSR - ON");
}
else {
System.out.println("DSR - OFF");
}
}
}
}
}
You can't read data from the same port where you write(COM1 here). I have followed the below steps for reading and writing using JSSC.
Fake your serial port with SerialPortMonitor.
Send data from COM2 from the SerialPortMonitor device installed.
Mode->Spy would show your written string "HelloWorld" and received String "OK"
Make the below modifications and check your code:
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN |
SerialPort.FLOWCONTROL_RTSCTS_OUT);
serialPort.writeBytes("HelloWorld");//Write data to port
PortReader portReader=new PortReader(serialPort)
serialPort.addEventListener(portReader, SerialPort.MASK_RXCHAR);
int[][] eventArray=serialPort.waitEvents()
for (int i = 0; i < eventArray.length; i++) {
if ((eventArray[i][0] > 0) ) {
serialPort.eventListener.serialEvent(new SerialPortEvent("COM1", eventArray[i][0], eventArray[i][1])); // wait for the listener event to complete
}
}
The port reader class: (You were missing the Override annotation and passing in the serial port)
public class PortReader implements SerialPortEventListener{
SerialPort serialPort
public PortReader(){}
public PortReader(SerialPort serialPort){this.serialPort=serialPort}
#Override
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() > 0) {
try {
String receivedData = this.serialPort.readString(event.getEventValue());
System.out.println("Received response: " + receivedData);
this.serialPort.closePort();//Close serial port
}
catch (SerialPortException ex) {
System.out.println("Error in receiving string from COM-port: " + ex);
this.serialPort.closePort();//Close serial port
}
}
}
}
The command
serialPort.writeString("HelloWorld");
sends the string
HelloWorld
from COM1. The SerialPortReader class that you are implementing causes COM1 to listen for the event type isRXCHAR (AKA when COM1 receives a char).
Do you have a serial cable connected to the serial port?
Unless you cross the RX and TX pins of COM1 or have a separate COM port (whose TX and RX is connected to COM1's RX and TX pins respectively), the SerialPortReader will never be activated.
if your device doesn't require RTS/CTS flow control
or you dont have a fully connected serial cable
( only RX, TX, GND)
you should switch off the data terminal ready (dtr)
signal for the serial communication
add this
serialPort.setRTS(false);
serialPort.setDTR(false);
after
serialPort.addEventListener(new SerialPortReader());

Categories

Resources