-
Java Serial Communication using Javax.comm and saving variables into an array
Ok the idea is that i want to use serial communication in java, using javax.comm. What i want to do exactly is read a line though serial communication and save it in an array. For example every time i press a button on my external device, it will send a line of random numbers like "12345", if i press it again, should send another line of numbers. I want my java program to read that line save it into an array, then get ready to receive another line of numbers and save that in another array for late use. If there is any tip or someone can atleast help me getting connected with serial would be great. Thank You. So far i have the following, which finds ports.
HTML Code:
import java.util.Enumeration;
import javax.comm.CommPortIdentifier;
public class PortAccess {
CommPortIdentifier commPortIdentifier;
Enumeration enumeration;
public void fnListPorts() {
try {
enumeration = CommPortIdentifier.getPortIdentifiers();
} catch (Exception e) {
e.printStackTrace();
}
while (enumeration.hasMoreElements()) {
commPortIdentifier = (CommPortIdentifier) enumeration.nextElement();
System.out.println(commPortIdentifier.getName());
}
}
public static void main(String[] args) {
PortAccess portAccess = new PortAccess();
portAccess.fnListPorts();
}
}
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
Quote:
So far i have the following, which finds ports.
Does it work?
I've used javax.comm (and RXTX) a lot for communicating with mobile phones, LEGO RCX, oscilloscopes and various microcontroller projects, so the good news is that what you're trying to do will work eventually! I don't have javax.comm installed at the moment but I recall there were several demos included, including 'BlackBox' a pretty good serial port tool. Have a look through the source code of those demos and you'll be able to fund everything you need in there.
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
Yea the code works. Actually, i have managed to forge a code which does read serial bit's though a serial port in java. What i am using is a chip called HCS12, which is a small microcontroller. The microcontroller sends numbers to my serial port everytime i press a button on it. The code that i was maange to forge, receives the numbers 1 by 1, not by line, and also does not save it into an array. I am not too familiar with the functions in this code, im trying to learn it on my own. Heres the code.
import java.io.*;
import java.util.*; //import gnu.io.*;
import javax.comm.*;
public class SimpleRead implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
byte[] readBuffer;
public static void main(String[] args) {
portList = CommPortIdentifier.getPortIdentifiers();
System.out.println("portList... " + portList);
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
System.out.println("port identified is Serial.. "
+ portId.getPortType());
if (portId.getName().equals("COM6")) {
System.out.println("port identified is COM6.. "
+ portId.getName());
// if (portId.getName().equals("/dev/term/a")) {
SimpleRead reader = new SimpleRead();
} else {
System.out.println("unable to open port");
}
}
}
}
public SimpleRead() {
try {
System.out.println("In SimpleRead() contructor");
serialPort = (SerialPort) portId.open("SimpleReadApp1111",500);
System.out.println(" Serial Port.. " + serialPort);
} catch (PortInUseException e) {
System.out.println("Port in use Exception");
}
try {
inputStream = serialPort.getInputStream();
System.out.println(" Input Stream... " + inputStream);
} catch (IOException e) {
System.out.println("IO Exception");
}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
System.out.println("Tooo many Listener exception");
}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
// no handshaking or other flow control
serialPort.setFlowControlMode(SerialPort.FLOWCONTR OL_NONE);
// timer on any read of the serial port
serialPort.enableReceiveTimeout(500);
System.out.println("................");
} catch (UnsupportedCommOperationException e) {
System.out.println("UnSupported comm operation");
}
readThread = new Thread(this);
readThread.start();
}
public void run() {
try {
System.out.println("In run() function ");
Thread.sleep(500);
// System.out.println();
} catch (InterruptedException e) {
System.out.println("Interrupted Exception in run() method");
}
}
public void serialEvent(SerialPortEvent event) {
// System.out.println("In Serial Event function().. " + event +
// event.getEventType());
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:
readBuffer = new byte[8];
try {
while (inputStream.available()>0) {
int numBytes = inputStream.read(readBuffer);
// System.out.println("Number of bytes read " + numBytes);
}
System.out.print(new String(readBuffer + "i"));
} catch (IOException e) {
System.out.println("IO Exception in SerialEvent()");
}
break;
}
// System.out.println();
/* String one = new String(readBuffer);
char two = one.charAt(0);
System.out.println("Character at three: " + two);*/
}
}
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
So what happens when you run your code? (Next time you post code remember to wrap it in code tags)
Just to check - have you checked that your board works by testing it with a terminal emulator so that you can see the characters appearing on a console?
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
so i did test it in terminal, my board works fine, i make it send "12345" every 5 seconds on 1 line, so there is 1 line sending every 5 seconds saying "12345". When i run it with this code, im guessing because its waiting for 8 bits, it would show 12345 then 3 small boxes like waiting for 3 more numbers or so. What i want to do is modify this code to receive everything i throw at it from serial communication save it in a array for later use. my goal was to make a GUI application which displayed the numbers that are stored in the array, can be 5 or 8 numbers.
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
If you're sending human-readable lines of values (it's a good way to do it, in my opinion) terminated by a carriage return or a linefeed (or both) you may be able to use something like BufferedReader.readLine() to get your values in one shot. Watch out for InputStream.available(), a < 1 return value doesn't necessarily mean a value transfer has finished: only that you've emptied a buffer quicker than it is being filled - it's not the same thing. If you're sending the right EOL (End Of Line) from your board, BufferedReader will do correctly in one line what ten lines of byte-reading code might not do very well at all.
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
The program i have now is a bit too confusion for me, is it possible you can help me create a program which just reads variables from a port because im trying to shed some code from this code and i guess i am deleting some stuff which are necessary and them.
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
Quote:
When i run it with this code, im guessing because its waiting for 8 bits, it would show 12345 then 3 small boxes like waiting for 3 more numbers
There could be some confusion here. I assume that each number you send is a digit character that takes 8 bits. The 8 bits and 5 digits and 3 more numbers are not the right way to look at what is happening.
The read method get a byte, exactly 8 bits.
For testing I'd read the input byte by byte and print it out to see what the java program is receiving. Later you can convert the logic to make characters or Strings out of what is read.
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
Quote:
Originally Posted by
williamsant
The program i have now is a bit too confusion for me.
Do what Norm suggests. Don't try to maintain your own buffer (that byte array), it's a path of pain and probably not what you need to do long-term. Use InputStream.available() and InputStream.read() in your serialEvent method to get one byte at a time, printing it on the console. Get that working first, then post your code and a sample of your output showing the bytes received from your port.
BufferedReader would be a radically different solution, because those serial port events probably won't be synchronized with single lines emitted by your board. If you could use BufferedReader, you wouldn't bother with handling events at all.
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
I am gonna be working on this for the rest of the day ill post the program when i get to that step, thanks.
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
what i did, is read byte by byte, and the following came as a result:
1 and 7 squares
2 and 7 squares
3 and 7 squares
4 and 7 squares
5 and 7 squares
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
Could you show the code you used to read and to print with?
the read() method returns an int. The character '1' should print as 49
Don't use an array or convert the input to a String.
read and print the input byte by byte
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
The following code is my java code.
Code Java:
import java.io.*;
import java.util.*; //import gnu.io.*;
import javax.comm.*;
public class SimpleRead implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
byte[] readBuffer;
byte[] tempnum;
public static void main(String[] args) {
portList = CommPortIdentifier.getPortIdentifiers();
System.out.println("portList... " + portList);
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
System.out.println("port identified is Serial.. "
+ portId.getPortType());
if (portId.getName().equals("COM6")) {
System.out.println("port identified is COM6.. "
+ portId.getName());
// if (portId.getName().equals("/dev/term/a")) {
SimpleRead reader = new SimpleRead();
} else {
System.out.println("unable to open port");
}
}
}
}
public SimpleRead() {
try {
System.out.println("In SimpleRead() contructor");
serialPort = (SerialPort) portId.open("SimpleReadApp1111",500);
System.out.println(" Serial Port.. " + serialPort);
} catch (PortInUseException e) {
System.out.println("Port in use Exception");
}
try {
inputStream = serialPort.getInputStream();
System.out.println(" Input Stream... " + inputStream);
} catch (IOException e) {
System.out.println("IO Exception");
}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
System.out.println("Tooo many Listener exception");
}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
// no handshaking or other flow control
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
// timer on any read of the serial port
serialPort.enableReceiveTimeout(500);
System.out.println("................");
} catch (UnsupportedCommOperationException e) {
System.out.println("UnSupported comm operation");
}
readThread = new Thread(this);
readThread.start();
}
public void run() {
try {
System.out.println("In run() function ");
Thread.sleep(500);
// System.out.println();
} catch (InterruptedException e) {
System.out.println("Interrupted Exception in run() method");
}
}
public void serialEvent(SerialPortEvent event) {
// System.out.println("In Serial Event function().. " + event +
// event.getEventType());
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:
readBuffer = new byte[8];
try {
while (inputStream.available()>0) {
int numBytes = inputStream.read(readBuffer);
// System.out.println("Number of bytes read " + numBytes);
}
System.out.print(new String(readBuffer));
} catch (IOException e) {
System.out.println("IO Exception in SerialEvent()");
}
break;
}
// System.out.println();5
/* String one = new String(readBuffer);
char two = one.charAt(0);
System.out.println("Character at three: " + two);*/
}
}
This is the simple code i have written in C to send a char through serial port.
Code Java:
void main(void) {
PLL_init();
SCI0_init(9600);
while(1) {
outchar0('1');
ms_delay(500);
outchar0('2');
ms_delay(500);
outchar0('3');
ms_delay(500);
outchar0('4');
ms_delay(500);
outchar0('5');
ms_delay(500);
outchar0('6');
ms_delay(500);
outchar0('7');
ms_delay(500);
outchar0('8');
ms_delay(500);
}
}
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
What is printed if you use the read() method and print out what is read?
Code :
while (inputStream.available()>0) {
int aByte= inputStream.read(); // read a byte
System.out.println(aByte + " " + System.currentTimeMillis()); // print the byte with time
}
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
When i add this, it prints the following:
49
50
51
52
53
54
55
56
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
Those look like the characters 1 thru 8.
What is the next step?
When does the reading method decide it has all the bytes for a String so that it can create and return a String?
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
Have you got those hard-coded delays in your C code because your outchar0 doesn't block on a full transmit buffer (serial transmit buffers are usually only one byte on many microcontrollers)?
The way you're sending data from your micro means there's no 'end of message' mark that your Java code can use to distinguish where a pattern of digits starts and ends. You should really finish each string (sequence of numbers from your micro) with something like
which may allow you to read your serial port as a line-oriented stream once you get all the bugs ironed out.
edit: D'oh! answered Norm's question.
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
i tried sending 9 numbers and it displays the same as before but a 57 there. so im guessing it keeps reading the numbers but it does not store it anywhere. im guessing it erases the previous number it recorded before. what i want to do is save each number it received and store it in a separate variable that i can call it later on.
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
Before we go any further we need to know what it is that you're calling a 'number'. Your outchar0 appears to send a single 8-bit value. If you have an application which can communicate properly by exchanging only 8-bit values, your job is finished. If you need to be able to read things like "273", "open", "close", "alarm", "3.141", then the very first thing you need to do is to establish a protocol for terminating *strings*. I have always used (in simple micro apps) an EOL marker such as Carriage Return (CR) or Line Feed (LF) or even CRLF because they're common EOLs and you get free compatibility with lots of other software. Otherwise, how is your Java program going to know how to divide up:
?
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
Yeah, i guess you are right, i am done. By number i meant the "char" my c program is sending sorry for not being specific. My c program is just sending char by char, and i want my java to read char by char. all i need to do now is put it into an array when i read it for later use.
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
Define a large array and use an index to store the bytes into the array.
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
i got it, i didnt realize i was so close to completing =). Next step is include my GUI program that i have seperate. Thank you so much guys i got it from here, you guys helped clear things up for me.
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
Hey,
I have a similar need to the original post on this thread. I am using an arduino UNO to control a servo angle. At the moment I have coded the arduino to accept angular inputs from Hyper Terminal to move the servo. Now the next step i wish to take is to move the servo using a java GUI. I wish to have a 'connect' button to the COM3 serial port and preferably a slider that changed the angle of the servo from 0 to 180.
I am a novice in java programming and im unsure on a few things.
I am using netbeans IDE.
I got the following code from a website to get me started just with listing the ports in java:
************************************************** *************************
import java.util.Enumeration;
import javax.comm.CommPortIdentifier;
/** List all the ports available on the local machine. **/
public class ListPorts
{
public static void main (String args[])
{
Enumeration port_list = CommPortIdentifier.getPortIdentifiers();
while (port_list.hasMoreElements())
{
CommPortIdentifier port_id = (CommPortIdentifier)port_list.nextElement();
if (port_id.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
System.out.println ("Serial port: " + port_id.getName());
}
else if (port_id.getPortType() == CommPortIdentifier.PORT_PARALLEL)
{
System.out.println ("Parallel port: " + port_id.getName());
}
else
System.out.println ("Other port: " + port_id.getName());
}
} // main
} // class PortList
************************************************** ****************************
This should give me an output along the lines of:
C:\>javac ListPorts.java
C:\>java ListPorts
Serial port: COM7
Serial port: COM10
Serial port: COM3
Parallel port: LPT1
Parallel port: LPT2
However although the code builds with no errors there is no output :S if I put a simple System.out.println(“hello”); I get a ‘hello’ output so I don’t think it’s a problem with netbeans but im not sure.
Can anyone help?
Thank you in Advance
Steven
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
Ok so ive sorted the above problem, I needed to get the RXTX library and put the dll and jar files in the correct directories and then create a path for the jar files in netbeans. I now have the above code showing me where com3 is! Good times!
Now for the hard part, I want a code that allows me to send data to the com3 port so that i can tell the servo where to go, any tips? codes? any help is much appreciated!
Thanks Steven Blackburn
-
Re: Java Serial Communication using Javax.comm and saving variables into an array
Read the API doc for the classes in the javax.comm package.