日期:2014-05-20  浏览次数:20858 次

串口问题,各位大虾帮帮忙
请问谁有关于关于串口通信的例子,让我研究一下阿,拜托

------解决方案--------------------

import java.util.Enumeration;

import javax.comm.CommPortIdentifier;
import javax.comm.NoSuchPortException;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;

public class RTS
{

CommPortIdentifier port;

SerialPort sp;

Enumeration en;

SerialParameters parameters;

/**
* @param args
*/
public static void main(String[] args)
{
RTS rtsTest = new RTS();


out( "comport: " + commPort);
rtsTest.listPort();
rtsTest.openPort( "COM1 ");

//set RTS true
rtsTest.getSp().setRTS(true);
//out( "rts is: " + rtsTest.getSp().isRTS());
//out( "baud rate is: " + rtsTest.getSp().getBaudRate());

try
{
// out( "before 0.5s time is: " + System.currentTimeMillis());
Thread.sleep(500);
// out( "after 0.5s time is: " + System.currentTimeMillis());
}
catch (InterruptedException e)
{
e.printStackTrace();
}

//set RTS false
rtsTest.getSp().setRTS(false);
//out( "rts is: " + rtsTest.getSp().isRTS());
//out( "baud rate is: " + rtsTest.getSp().getBaudRate());
//out( "port is owned: " + rtsTest.getPort().isCurrentlyOwned());

//close the port
out( "close the port: " + rtsTest.getSp().getName());
rtsTest.getSp().close();
//out( "port is owned: " + rtsTest.getPort().isCurrentlyOwned());
}

public static void out(Object o)
{
System.out.println(o);
}

public void openPort(String commPort)
{
this.parameters = new SerialParameters(commPort, 9600,
SerialPort.FLOWCONTROL_NONE, SerialPort.FLOWCONTROL_NONE,
SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);

try
{
this.port = CommPortIdentifier.getPortIdentifier(this.parameters
.getPortName());
out( "current opened port: " + this.parameters.getPortName());
}
catch (NoSuchPortException e1)
{
e1.printStackTrace();
}

try
{
this.sp = (SerialPort) this.port.open( "PvsClient ", 60);
}
catch (PortInUseException e)
{
e.printStackTrace();
}
}

public void listPort()
{
this.en = CommPortIdentifier.getPortIdentifiers();

out( "usable com port is: ");
while (this.en.hasMoreElements())
{
this.port = (CommPortIdentifier) this.en.nextElement();

if (this.port.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
System.out.println(this.port.getName());
}
}
}

public SerialPort getSp()
{
return this.sp;
}

public void setSp(SerialPort sp)
{
this.sp = sp;
}

public CommPortIdentifier getPort()