我需要使用Java编程语言通过Linux Ubuntu上的COM端口将变量发送到Arduino UNO。使用库JSSC或RXTX。像:
String text = "turn_on";
write(text);
并且喜欢:
int num = 1;
write(num);
我的Arduino代码是这样的:
include <SoftwareSerial.h>
void setup() {
pinMode(9, OUTPUT);
Serial.begin(57600);
}
int st;
void loop() {
st = Serial.read();
if(st == 1){
digitalWrite(9, 1);
}
}
我试过这段代码:
import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;
public class Test {
private static SerialPort serialPort;
public static void main(String[] args) {
serialPort = new SerialPort("/dev/ttyUSB2");
try {
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_57600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN |
SerialPort.FLOWCONTROL_RTSCTS_OUT);
serialPort.addEventListener(new PortReader(), SerialPort.MASK_RXCHAR);
serialPort.writeInt(1);
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
private static class PortReader implements SerialPortEventListener {
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() > 0){
try {
String data = serialPort.readString(event.getEventValue());
serialPort.write(1);
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
}
}
}
怎么做?
答案 0 :(得分:0)
写入串口后尝试休眠。配置Arduino进行流量控制,首先看看正常读写是否正常然后移动到eventListener方法意味着如果java写入arduino,arduino能够读取然后从arduino和java端发送数据应该能够读取。这将消除许多可能性。进一步尝试其他一些并行的库,如SerialPundit或github上的fazecast。