2012-04-19 95 views
2

我想在我的java界面中製作應變計顯示數字。Java - 將串行端口字節數組轉換爲Int?

我有應變計電路工作,並將其電壓送入微控制器(PIC16F877A)程序進行模數轉換,然後在串口輸出數字。如果你有興趣,這裏是代碼:

unsigned short analog;   //Variable for analog voltage 
long tlong; 
unsigned char ch;     // 

void main() { 
    USART_Init(19200);    //set baude rate 

    ADCON1 = 0;      //All PORTA pins as analog, VDD as Vref 
    TRISA = 0xFF;     //All PORTA is input 

    do { 
    analog = ADC_Read(2) >> 2; //Read 10-bit ADC from AN2 and discard 2 LS bit 

    tlong = (long)analog * 5000; // Convert the result in millivolts 
    tlong = tlong/1023;   // 0..1023 -> 0-5000mV 
    ch = tlong/1000;   // Extract volts (thousands of millivolts) from result 

    USART_Write(48+ch);   // Write result in ASCII format 
    USART_Write('.'); 

    ch = (tlong/100) % 10;  // Extract hundreds of millivolts 
    USART_Write(48+ch);   // Write result in ASCII format 

    ch = (tlong/10) % 10;  // Extract tens of millivolts 
    USART_Write(48+ch);   // Write result in ASCII format 

    ch = tlong % 10;    // Extract digits for millivolts 
    USART_Write(48+ch);   // Write result in ASCII format 
    USART_Write(' '); 
    USART_Write(' '); 
    USART_Write(' '); 

    Delay_ms(1000); 
    } while (1); 
} 

這並不完美,因爲我動應變計,輸出數字不改變,他們應該的樣子。如果任何人有任何想法,它將非常感激。

但無論如何,我將這些數字發送到我的Java程序。我發現這個網上,並修改它適合我的設計:

import java.io.*; 
import java.util.*; 
import gnu.io.*; 


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

InputStream inputStream; 
SerialPort serialPort; 
Thread readThread; 
static byte[] readBuffer; 
public static int result2; 

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("COM4")) { 
       System.out.println("port identified is COM4.. " 
         + 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(19200, 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[500]; 

     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(); 
/* String one = new String(readBuffer); 
    char two = one.charAt(0); 
    System.out.println("Character at three: " + two);*/ 
} 

} 

它讀取同一範圍內的數字(一個串口,所以如果這是同樣的數字我不能測試)爲前面的代碼,雖然它有時會給我奇怪的數字,而不是.692,它會說320,然後下一個數字是43,那麼可能只是'。'。會出現,但很快就會恢復正常。我認爲這是一個緩衝區問題,它表示「readBuffer = new byte [500]」,其中我將大小更改爲500(最初爲8),並且稍微好一些。

我必須把輸出轉換成一個整數來與它做一些數學運算,作爲一個整數,我可以很容易地過濾出所有奇怪的數據。所以最終,我的問題是現在我會把這個輸出數據變成可用的整數嗎?主要的問題是我甚至不知道在我的Java程序中讀取串口號碼的位置。我假設這個變量是readBuffer,但是當我嘗試使用它時,我會遇到錯誤,通常是類型不匹配。

所以任何幫助將是偉大的,謝謝!

回答

0

我研究過你上面的代碼進一步,我想在上面的代碼流是:

<x.xxx >,所以如果你每次讀取,這將是一個數據輸入8個字節。如果您使用的InputStreamReader如果將字節轉換爲字符...

檢查http://docs.oracle.com/javase/1.4.2/docs/api/java/io/InputStreamReader.html

+0

這正是流應該是,通常它輸出0.200-1.000,但就像我說的,我偶爾自己變得怪異整數,甚至是小數。非常感謝你的建議,明天我會試着實現inputstreamreader! – 2012-04-20 01:31:33

0

這是很難從所提供的信息來猜測,但你說:

「讓我奇怪的號碼,如代替0.692,它會說320"

m個艾因的問題是,我什至不知道在哪裏我的Java程序它的讀取串口號

這在我看來是字節順序問題,如果你正試圖從接收的字節緩衝區中讀取整數。如果您嘗試從接收的字節緩衝區中讀取浮點數據,也可能是浮點類型的IEEE標準不匹配。但我建議不要使用浮點類型並只使用整數。

,如果你使用的是Java 5+使用的ByteBuffer類從NIO包,像這樣:

byte[] readBuffer = getBufferFromyourCode(); 
    ByteBuffer buffer = ByteBuffer.wrap(readBuffer); //wrap received byte buffer 
    buffer.order(ByteOrder.LITTLE_ENDIAN);//set correct endiannes 
    Integer version = buffer.getInt();// read first 4 bytes 
    Integer length = buffer.getInt(); // read next 4 bytes 
    byte[] rowMsg = new byte[length];// length = bytes to read 
    buffer.get(rowMsg); // copies 'length' bytes in rowMsg 
    String msg = new String(rowMsg); // convert to String 
    System.out.println("Version "+version+" message received"); 
    System.out.println("Length: "+length); 
    System.out.println("text: "+msg); 

注字節順序設置,嘗試既大又小端,看你從緩衝區中讀取值看起來正常。 查看更多關於字節序的位置:http://en.wikipedia.org/wiki/Endiannes