2017-02-19 55 views
1

我必須很快地將字符串發送到串行線。我目前只是調用一個簡單的shell腳本,但我覺得我應該可以在Java本身做到這一點。什麼是更好/更快/更乾淨的方式來做到這一點?代碼使用rapbian在Rpi上運行。在Java中寫入串口

Java代碼:

public static synchronized boolean sendString(String s){ 
    String target = "/home/pi/send.sh " + s; 
    Runtime rt = Runtime.getRuntime(); 
    try { 
     rt.exec(target); 
    } catch (Exception e) { 
     return false; 
    } 
    return true; 
} 

猛砸代碼:

echo "[email protected]" > /dev/ttyACM0 
+1

使用Pi4J :)我這樣做。它的偉大:) http://pi4j.com/ – slipperyseal

+0

http://pi4j.com/example/serial.html – slipperyseal

+0

我一定會檢查出pi4j!謝謝。 – woutwoot

回答

0

您可以打開/ dev/ttyACM0爲文件,並寫入。確保你有正確的訪問權限/ dev/ttyACM0,也許安裝一個udev規則給你適當的權限,