[英]Reading bytes from Arduino Uno
我正在使用RxTx庫在Arduino和Java應用程序之間進行通信。 我的Arduino鱈魚是:
void setup(){
Serial.begin(9600);
}
void loop(){
Serial.println("Hello world");
delay(1000);
}
如果您想查看我所有的java cods All 。 我有一種從arduino讀取字節的方法
public byte[] readBlocked(int num) throws IOException {
byte[] buff;
buff = new byte[num];
this.inputStream.readFully(buff, 0, num);
return buff;
}
在TestComunication類中,我打印接收數據
public class TestComunication {
private Connection connection;
//private CommPortIdentifier port;
private static final String PORT_NAMES[] = {
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyACM0", // Raspberry Pi
"/dev/ttyUSB0", // Linux
"COM3", // Windows
"/dev/tty.usbmodem621",
"/dev/tty.usbmodem411"
};
public TestComunication() throws IOException {
SerialClassConnection serialClassConnection = null;
CommPortIdentifier port = null;
serialClassConnection = SerialClassConnection.getInstance();
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
//First, Find an instance of serial port as set in PORT_NAMES.
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
port = currPortId;
break;
}
}
}
if (port == null) {
System.out.println("Could not find COM port.");
return;
}
System.out.println(port.getName());
serialClassConnection.openPort(port);
this.connection = serialClassConnection;
this.manageData(this.connection);
}
private void manageData(Connection conn) throws IOException {
Connection connection;
int availableBytes;
byte[] inBytes;
connection = conn;
// listen forever for incoming data
while (true) {
if (connection.isDataAvailable()) {
inBytes = connection.readBlocked(11);
String text = new String(inBytes, "UTF-8");
System.out.println(text);
}
}
}
public static void main(String[] args) throws IOException {
new TestComunication();
Thread t = new Thread() {
public void run() {
//the following line will keep this app alive for 1000 seconds,
//waiting for events to occur and responding to them (printing incoming messages to console).
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
}
}
};
t.start();
System.out.println("Started");
}
}
我正在發送字符串
你好,世界
來自Arduino Uno 在我的Java應用程序中,我正在以字符串形式讀取此字符串。 但是我收到的數據不連貫。 例:
Native lib Version = RXTX-2.1-7
Java lib Version = RXTX-2.1-7
/dev/tty.usbmodem621
Held
Hello
world
Hel
lo world
H
ello world
主要問題:字符串Hello World
轉換為ASCII是
072 101 108 108 111 032 119 111 114 108 100
但我不會每次都收到該序列。 我收到的示例:
072 108 101 108 111 032 119 111 114 108 100
101072108108111032111114108119100
101 072 108 111 032 114 108 111119 100 108
但是接收數據的長度是正確的11個字節
嗯什么返回this.inputStream.readFully(buff, 0, num);
檢查此方法,也許是錯誤的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.