我正在使用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