我想從 Java 程序接收 Arduino Uno 上的多個字節。arduino 收到數據后會立即處理,因此我不需要存儲它,我使用串行 RX 緩沖區作為臨時存儲,直到我真正讀取字節。完全實現后,每次將發送大約 150 個字節,但我已經修改了緩沖區大小以解決這個問題。我使用 jSerialComm 作為我的 java 串行庫我在下面放了一些 arduino 和 java 代碼。當我從 IDE 的串行監視器發送字節時,arduino 代碼可以完美運行,按預期點亮 LED。但是,一旦我嘗試使用 java 代碼發送字節,RX 板載 LED 就會閃爍,但黃色 LED 永遠不會亮起,并且 ExecuteMove() 不會觸發。我試圖在嘗試關閉端口之前放置一個 Thread.sleep() ,但這無濟于事。阿杜諾int GREEN = 4;int BLUE = 3;int YELLOW = 2;void setup() { pinMode(GREEN, OUTPUT); pinMode(BLUE, OUTPUT); pinMode(YELLOW, OUTPUT); Serial.begin(9600);}void loop() { byte rb = Serial.read(); if(rb != 255){ //Documentation says it sould be -1, but I'v tested it and it's 255 digitalWrite(YELLOW, HIGH); ExecuteMove(rb); delay(500); digitalWrite(YELLOW, LOW); }}void ExecuteMove(byte _move){ Lights up the green LED if _move == 65, blue if 66 (Works perfectly) }爪哇public static void main(String[] args) throws IOException, InterruptedException{ SerialPort sp = SerialPort.getCommPort("COM3"); sp.setComPortParameters(9600, 8, 1, 0); sp.setComPortTimeouts(SerialPort.TIMEOUT_WRITE_BLOCKING, 0, 0); if(sp.openPort()) { System.out.println("Port is open"); }else { System.out.println("Port failed to open"); return; } byte[] message = {65, 66, 65}; for(int i = 0; i < message.length; i++) { sp.getOutputStream().write(message[i]); //Sends the message sp.getOutputStream().flush(); } if(sp.closePort()) { System.out.println("Port is closed"); }else { System.out.println("Failed to close port"); return; } } 正如我已經說過的,arduino 代碼單獨與顯示器完美配合,但是當我使用 java 代碼發送字節時,只有 RX LED 亮起,但“我的”LED 都沒有
1 回答

Qyouu
TA貢獻1786條經驗 獲得超11個贊
對于任何偶然發現這篇文章并且接縫有類似問題的人來說,這是因為 Windows 在打開端口時向 arduino 發送了一個重置信號。因為它會立即發送數據,所以 Arduino 在重置時會將其從緩沖區中刪除,并且永遠無法讀取它。有兩種主要方法可以糾正這個問題,首先Thread.sleep(5000);
在打開端口和發送數據之間添加一個。您還可以在 RESET 和 GND 引腳之間添加一個 47μF 電容。
來源:https ://arduino.stackexchange.com/questions/22267/java-jssc-arduino-windows https://forum.arduino.cc/index.php?topic=96422.0
希望這可以幫助某人
添加回答
舉報
0/150
提交
取消