我正在使用Arduino Uno。我遇到與Serial.readbytes()
奇怪的行爲。 Arduino在COM4上通過USB進行供電和通信。我在64位Windows上運行Eclipse 7.通過USB從Java程序讀取時,Arduino遇到Serial.readbytes()問題
我目前的Arduino代碼如下所示:延遲是我可以啓動和停止Java服務並查看Arduino IDE中的串行窗口,inputBuffer是一個字符數組。
char inputBuffer[10]; // For incoming serial data
void setup() {
Serial.begin(9600); // Opens serial port, sets data rate to 9600 bit/s.
}
void GetTemp(){
int temp = 123;
Serial.print(temp);
}
void loop() {
if (Serial.available() > 0) {
Serial.readBytes(inputBuffer, Serial.available());
delay(5000);
Serial.print("I got this ->");
Serial.print(inputBuffer);
Serial.println("<-");
}
delay(5000);
Serial.println("delay");
Serial.println(inputBuffer[0], DEC);
}
這是我的Java端的代碼。我修改它從Two way communcation with the serial port。這只是在開始時發送一個字節的數組。
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.IOException;
import java.io.OutputStream;
public class TwoWaySerialComm
{
public TwoWaySerialComm()
{
super();
}
void connect (String portName) throws Exception
{
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned())
{
System.out.println("Error: Port is currently in use");
}
else
{
CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);
if (commPort instanceof SerialPort)
{
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
OutputStream out = serialPort.getOutputStream();
(new Thread(new SerialWriter(out))).start();
}
else
{
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
public static class SerialWriter implements Runnable
{
OutputStream out1;
public SerialWriter (OutputStream out)
{
this.out1 = out;
}
public void run()
{
try
{
byte[] test = ("H567").getBytes();//testing string to send
this.out1.write(test);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public static void main (String[] args)
{
try
{
(new TwoWaySerialComm()).connect("COM4");
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
當我運行它時,我的Arduino只是打印出一個空行。如果我首先使用串口窗口準備好「hiya」的Arduino,那麼當java被執行時,它將返回一個空行。
由於每次發送「H567 \ r \ n」,然後在串口窗口中鍵入發送「hiya」,額外的換行符仍在執行時,字符數組剛剛被覆蓋,所以我知道字符正在以某種方式存儲。
另一個測試是將最後的Serial.prinln()
更改爲Serial.println(inputBuffer[0], DEC)
。使用串行窗口,結果如預期的那樣,但是從Java只打印出「0」。從Arduino與Java代碼交談開始,串行通信就非常棒了,而不是從Java代碼到Arduino。我該如何解決這個問題?
根據建議,我嘗試閱讀Serial.available()
而不是固定的最大值10.沒有發生任何變化。
您正在使用哪種版本的RXTX?您使用的是哪個版本的Java? – Jeffrey 2013-04-08 00:55:51
你可以發佈你所有的Java代碼嗎?最好在[SSCCE](http://sscce.org)中包裝得好又整潔。 – Jeffrey 2013-04-08 00:57:50
你必須原諒我,但我在SSCCE遇到麻煩,我現在沒有多少睡眠。 – Mark 2013-04-08 01:22:59