serial write
Hi everyone
I have this piece of code that i am using to open COM1, write, and read from it.
Well the problem is I doubt if it actually writes to the port because when i run the program, it opens the port but there is no information to read at the port. I tested the port on hyperterminal and it works just fine. So how do I ensure that I am actually writing to the port? Can anyone help me?
Here is my code:
import java.util.*;
import javax.comm.*;
import java.io.*;
import java.awt.Toolkit;
publicclass Wavetronix
{
publicstaticfinalint BufferByteSize = 1440;
static CommPortIdentifier portID;
static Enumeration portlist;
static SerialPort serialport;
static InputStream inputstream;
static OutputStream outputstream;
static String cmdstring ="SB\r";
static DataOutputStream datafile;
staticbyte [] data;
static ByteArrayOutputStream buffer;
staticint datasize = BufferByteSize;
publicstaticvoid main(String args[])
{
portlist = portID.getPortIdentifiers();
while (portlist.hasMoreElements())
{
portID = (CommPortIdentifier) portlist.nextElement();
if (portID.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
System.out.println(portID.getName());
if(portID.getName().equals("COM1"))
{
//setting up ouput Stream;
try
{
datafile =new DataOutputStream(new FileOutputStream("dodger.txt"));
}catch(FileNotFoundException e){}
//setting up input stream;
try
{
serialport = (SerialPort) portID.open("WavetronixApp", 2000);
System.out.println("did portID.open return null?" + (serialport ==null));
}catch(PortInUseException e){System.out.println("unsuccessful open");}
try
{
outputstream = serialport.getOutputStream();
}catch (IOException e){}
try
{
serialport.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
}catch (UnsupportedCommOperationException e){}
try
{
//outputstream.flush();
outputstream.write(cmdstring.getBytes());
System.out.println("writing to port...");
}catch (IOException e){System.out.println("unsuccessful write");}
try
{
Thread.sleep(20000);
}catch(InterruptedException e){}
try
{
//inputstream.flush();
inputstream = serialport.getInputStream();
}catch (IOException e){}
try
{
buffer =new ByteArrayOutputStream();
/*
if( SerialPortEvent.OUTPUT_BUFFER_EMPTY == 2)
{
System.out.println("~Buffer Empty");
System.out.println(SerialPortEvent.OUTPUT_BUFFER_EMPTY);
} */
if( SerialPortEvent.DATA_AVAILABLE == 1)
{
int i = inputstream.available();
data =newbyte [datasize];
System.out.println(SerialPortEvent.DATA_AVAILABLE);
System.out.println(i);
while (i > 0)
{
inputstream.read(data, 0, i);
buffer.write(data, 0, i);
buffer.writeTo(datafile);
buffer.reset();
System.out.println("write to datafile complete");
System.out.println(SerialPortEvent.DATA_AVAILABLE);
}
}
}catch (IOException e){e.printStackTrace();}
}
}
}
}
}
Drake01

