Arduino运行一个简单的草图,简单地返回计算机发送的值:
void setup() {
Serial.begin(9600);
}
void loop() {
if(Serial.available())
Serial.println(Serial.read());
}
当我通过内置的串行监视器向它发送值时,它工作得很好。
我的Java代码似乎是问题所在,但我无法解决:
public static void main(String[] args){
SerialPort port = SerialPort.getCommPort("COM5");
port.setComPortParameters(9600,8,1,0);
port.setComPortTimeouts(SerialPort.TIMEOUT_NONBLOCKING,0,0);
System.out.println("Open port: " + port.openPort());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Scanner in = new Scanner(port.getInputStream());
PrintWriter out = new PrintWriter(port.getOutputStream(),true);
out.println('a');
out.flush();
System.out.println("> w");
while (in.hasNextLine())
System.out.println("return: " +in.nextLine());
}
谢谢你的回复。
package sample;
import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;
import java.io.PrintWriter;
import java.util.Scanner;
public class Test {
static boolean received;
public static void main(String[] args) {
SerialPort port = SerialPort.getCommPort("COM5");
port.setComPortParameters(9600,8,1,0);
port.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER,0,0);
System.out.println("Open port: " + port.openPort());
Scanner in = new Scanner(port.getInputStream());
PrintWriter out = new PrintWriter(port.getOutputStream(),true);
port.addDataListener(new SerialPortDataListener() {
@Override
public int getListeningEvents() {
return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
}
@Override
public void serialEvent(SerialPortEvent serialPortEvent) {
String input = "";
input = in.nextLine();
System.out.println("return: " + input);
received=true;
}
});
int counter =0;
while(!received) {
System.out.println(counter);
out.println(counter);
out.flush();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter++;
}
out.println('w');
System.out.println("w");
/* String input = in.nextLine();
System.out.println("return: "+input+input.isEmpty());*/
}
}
Arduino的密码:
void setup() {
Serial.begin(9600);
}
byte in;
int count=0;
void loop() {
if(Serial.available()){
Serial.print(Serial.parseInt());
Serial.print('\n');
}
}
开放端口:真
0
1
三
4
5
6
8
9
10
12
14
15
16
19
21
22
23
24
25
w
返回:0
这段代码应该立即返回计算机发送的值,但它没有。当我使用Arduino IDE中内置的串行监视器时,以及我尝试过的其他所有串行监视器时,它都能正常工作。