我的Java代码如下:
import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.SerialPortList;
public class SerialPort1{
public static boolean sentBytes;
//public SerialPort serialPort;
public static void main(String[] args) {
// get computer serial ports names
String[] portNames = SerialPortList.getPortNames();
for (String port : portNames) {
System.out.println(port);
}
// inicialization with selecting port for communication
SerialPort serialPort = new SerialPort("/dev/ttyACM0");
try {
// open port for communication
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE,false,true);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
// byte data transfer
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
serialPort.writeInt(1);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(serialPort.readString());
// close port
serialPort.closePort();
} catch (SerialPortException ex) {
System.out.println(ex);
}
}
}
我能够从Arduino阅读。但是,我无法写任何东西给Arduino。如果有人帮助我这样做真的很棒。
我的arduino代码:
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println("Android");
delay(2000);
}
我从此处下载了JSSC库
import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.SerialPortList;
public class SerialPort1{
public static boolean sentBytes;
//public SerialPort serialPort;
public static void main(String[] args) {
// get computer serial ports names
String[] portNames = SerialPortList.getPortNames();
for (String port : portNames) {
System.out.println(port);
}
// initialization with selecting port for communication
SerialPort serialPort = new SerialPort("/dev/ttyACM0");
try {
// open port for communication
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE,false,true);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
// byte data transfer
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
serialPort.writeInt(1);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(serialPort.readString());
// close port
serialPort.closePort();
} catch (SerialPortException ex) {
System.out.println(ex);
}
}
}
我要做的就是在打开串行端口后增加2000毫秒的睡眠,然后在写入Arduino后加入200ms的睡眠。同样,Arduino代码的延迟减少到200ms。
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println("Android");
delay(200);
}