[英]Receiving data from Terminal connected with USB->RS232
我正在開發一個Java應用程序,該應用程序需要與通過usb-to-rs232轉換器連接的終端進行通信!!
現在,我可以連接設備並發送數據了! 我可以確定終端接收到了發送的數據,因為當終端接收到某些東西時,LED會發光!
我正在使用JSSC (鏈接: https : //code.google.com/p/java-simple-serial-connector/wiki/jSSC_examples )...但是由於某些原因,我從來沒有從終端接收過任何數據。
我的代碼(JSSC代碼):
public class Main
{
static SerialPort serialPort;
public static void main(String[] args) throws InterruptedException
{
serialPort = new SerialPort("COM7");
try
{
serialPort.openPort();//Open port
serialPort.setParams(9600, 8, 1, 0);//Set params
int mask = SerialPort.MASK_RXCHAR + SerialPort.MASK_CTS + SerialPort.MASK_DSR;//Prepare mask
serialPort.setEventsMask(mask);//Set mask
serialPort.addEventListener(new SerialPortReader());//Add SerialPortEventListener
serialPort.writeByte( (byte)0x02 );
TimeUnit.SECONDS.sleep( 10 );
byte[] b = serialPort.readBytes();
System.out.println( "bytes " + b );
}
catch (SerialPortException ex)
{
System.out.println(ex);
}
}
/*
* In this class must implement the method serialEvent, through it we learn about
* events that happened to our port. But we will not report on all events but only
* those that we put in the mask. In this case the arrival of the data and change the
* status lines CTS and DSR
*/
static class SerialPortReader implements SerialPortEventListener
{
public void serialEvent(SerialPortEvent event)
{
System.out.println( "Event raised!" );
if(event.isRXCHAR())
{//If data is available
if(event.getEventValue() == 10)
{//Check bytes count in the input buffer
//Read data, if 10 bytes available
try
{
byte buffer[] = serialPort.readBytes(10);
}
catch (SerialPortException ex)
{
System.out.println(ex);
}
}
}
else if(event.isCTS())
{//If CTS line has changed state
if(event.getEventValue() == 1)
{//If line is ON
System.out.println("CTS - ON");
}
else
{
System.out.println("CTS - OFF");
}
}
else if(event.isDSR())
{///If DSR line has changed state
if(event.getEventValue() == 1)
{//If line is ON
System.out.println("DSR - ON");
}
else
{
System.out.println("DSR - OFF");
}
}
}
}
}
誰能幫我解決這個問題?
您打算將硬件流控制與USB-UART一起使用嗎? 如果是,請嘗試先設置DTR,再設置RTS。 這告訴第一端第二端已准備好進行通信。 此外,沒有接收到10個字節或根本沒有接收到數據。 還要考慮另一個串行端口通信庫,例如scm http://www.embeddedunveiled.com/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.