This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes I/O and Streams and the fly likes serial port problems Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "serial port problems" Watch "serial port problems" New topic
Author

serial port problems

Ellen Murphy
Greenhorn

Joined: Nov 17, 2004
Posts: 2
Hi, ive only just started programming in java. My FYP involves getting gps info over serial port and searching the data rxed for time etc. I've managed to get SImpleRead working for the GPS im using so it reads everything in fine. I have to search through the sentences (input) received now for the word $GPRMC and im having great difficulty. i cant see exactly what is my input in the code, is it inputStream or buffer??? can anyone help heres my code so far

****************************************************************************************
import java.io.*;
import java.util.*;
import javax.comm.*;

public class SerialRead implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;

InputStream inputStream;
SerialPort serialPort;
Thread readThread;
boolean portOpen;
BufferedInputStream in;

public static void main(String[] args) {
System.out.println("Starting....");
portList = CommPortIdentifier.getPortIdentifiers();

while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM1")) {
System.out.println("Found Serial Port!!!");
SerialRead reader = new SerialRead();
}
}
}
}

public SerialRead() {
System.out.println("Opening Serial......");
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
portOpen = true;
} catch (PortInUseException e) {}
try {
System.out.println("Getting input stream....");
inputStream = serialPort.getInputStream();
in = new BufferedInputStream(inputStream, 1024);
} catch (IOException e) {
serialPort.close();
System.out.println("Error opening i/o streams");}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(4800,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}

System.out.println("Parameters set");
readThread = new Thread(this);
readThread.start();
}

public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {}
}

public void serialEvent(SerialPortEvent event) {
// Create a StringBuffer and int to receive input data.
StringBuffer inputBuffer = new StringBuffer();
int newData = 0;

//Determine type of event
switch(event.getEventType()) {
case SerialPortEvent.BI:
System.out.println("\n--- BREAK RECEIVED ---\n");
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
while (newData != -1) {
try {
newData = inputStream.read();
if (newData == -1){
break;
}
if('\r' == (char)newData) {
inputBuffer.append('\n');
} else{

inputBuffer.append((char)newData);
//GetGPRMC();
System.out.print(new String(inputBuffer));
}
} catch (IOException ex) {
System.err.println(ex);
return;
}
}
}
}

// //Method to find GPRMC in buffer
// public void GetGPRMC()
// {
// int counter = 0;
//
// do{
// //search the i/p buffer to find GPRMC word
// if(inputBuffer.regionMatches(counter, GPRMC, 0, 5)){
//
// //store 127 characters starting at GPRMC
// String temp = inputBuffer.substring(counter, counter + 127);
// counter = 0;
//
// //Tokenize string with respect to commas
// StringTokenizer tokens = new StringTokenizer(temp, ",");
//
// while(tokens.hasMoreTokens() && (counter < 11))
// {
// gpsData[counter] = tokens.nextToken();
// }
// }
// }
//
// }



//Close connection method
public void CloseConnection()
{
if (!portOpen)
{
return; // if the port is already closed, do nothing
}
try {
inputStream.close(); //close inputstream
}
catch (IOException e) {
CloseConnection();
System.err.println(e);
}

serialPort.close(); // close port
}

}

*****************************************************************************************
i know its not an incredibly difficult thing to do but ive been puzzling over it for a while now and still cant see how to go about it. i know i could use regionMatches method but i dont know which string to use to call it.....

confused laela
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8914
    
    8

I/O in Java uses the concept of streams. You can augment one stream by "piping" it through another stream. For example, InputStream offers low-level reads. BufferedInputStream gives better performance by reading large chunks of data at one time, making one large request rather than thousands of small ones. To create a BufferedInputStream, we wrap an existing InputStream. You can see this in your code:

Your code has some interesting features, for example you start a thread, but it doesn't do anything:

And you have a serialEvent method, which is invoked when something happens on the serial port, but if you are receiving data you place it in the method-scope variable inputBuffer, so the data goes away when the method ends.
I strongly suggest that you start simple. Read the Java Tutorial. Learn the basics of the language and how to use it effectively, then read the Java Communications API User's Guide. That will help you understand the code you posted. It may take some time, but if you don't go through the tutorial it will take you far more time to post here about everything that is wrong with the above code.


"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
 
GeeCON Prague 2014
 
subject: serial port problems