2010-04-30 64 views
1

所以我發現如何將Arduino連接到我的java程序。但是,使用串行連接不會提供任何有用的數據,無論是以錯誤的格式還是將其作爲一個盒子發送。我已經看過在這裏發佈的相關問題,但沒有一個提示似乎有幫助。那麼有誰知道如何使用串口在Arduino和計算機之間發送數據?Arduino無法發回串行數據

這是我正在使用的代碼,由此人提供: http://silveiraneto.net/2009/03/01/arduino-and-java/

package serialtalk; 

import gnu.io.CommPortIdentifier; 
import gnu.io.SerialPort; 
import java.io.InputStream; 
import java.io.OutputStream; 
import processing.app.Preferences; 

public class Main { 
    static InputStream input; 
    static OutputStream output; 

    public static void main(String[] args) throws Exception{ 
     Preferences.init(); 
     System.out.println("Using port: " + Preferences.get("serial.port")); 
     CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(
       Preferences.get("serial.port")); 

     SerialPort port = (SerialPort)portId.open("serial talk", 4000); 
     input = port.getInputStream(); 
     output = port.getOutputStream(); 
     port.setSerialPortParams(Preferences.getInteger("serial.debug_rate"), 
       SerialPort.DATABITS_8, 
       SerialPort.STOPBITS_1, 
       SerialPort.PARITY_NONE); 
     while(true){ 
      while(input.available()>0) { 
       System.out.print((char)(input.read())); 
      } 
     } 
    } 
} 

的Arduino是這樣的: http://www.arduino.cc/en/Main/ArduinoBoardDuemilanove

的代碼簡單地接收的數,並且確定哪個讀取模擬它應該從我的Arduino發回來。

+0

它是你的Java應用程序或其他東西的問題?你能用串口監視器發送文本到板子嗎? – 2010-04-30 14:40:00

+0

當我寫「Hello World!」時,我可以從arduino發送數據到Netbeans IDE。當我運行我的java程序時,arduino IDE中的串行監視器似乎沒有收到任何東西 – 2010-05-01 09:28:58

回答

1

當串行連接處理確保以下關鍵點:

  • 波特率匹配
  • DATABITS應符合
  • STOPBITS應符合
  • 奇偶應符合
  • 確保你正在使用正確的電纜(如果需要,爲空調制解調器)
  • 確保電纜不會太長

以上所有情況都可能導致奇怪的東西從Java端口出來。一旦你掌握了這一點,它變得更容易。

我個人最喜歡的圖書館here

+0

它最有可能是一個虛擬COM端口,並且電纜是USB電纜,除非arduino板很老。如果它是一個真正的RS232C連接,那麼也可以考慮握手的類型:) – 2010-04-30 14:56:06

+0

這是我使用的duemilanove,我已經使用導入到我使用的Netbeans IDE中的RXTX庫。我能夠將數據發送到NetBeans中的串行監視器,並接收從Arduino發送的數據,但我無法接收數據並干擾ardiuno,如使用If語句,也許我的數據發送錯誤? – 2010-04-30 17:55:10

+0

@Maciej H我已經用java和其他組件一起使用了arduino,我只是知道我必須調整這些參數才能讓所有的東西都玩得很好。 – 2010-04-30 18:31:16