2012-04-19 70 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