[英]Arduino serial port communication
我正在尝试建立Java-Arduino串行通信。 所以我下载了谷歌搜索源代码。 但是我无法从Arduino向数据库(MySQL)发送正确的数据。
public class Serial implements SerialPortEventListener {
SerialPort serialPort;
private static final String PORT_NAMES[] = {
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyUSB0", // Linux
"COM3", // Windows
};
private InputStream input;
private OutputStream output;
private static final int TIME_OUT = 2000;
private static final int DATA_RATE = 9600;
public void initialize() {
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
if (portId == null) {
System.out.println("Could not find COM port.");
return;
}
try {
serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT);
serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
input = serialPort.getInputStream();
output = serialPort.getOutputStream();
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
System.err.println(e.toString());
}
}
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
int available = input.available();
byte chunk[] = new byte[available];
input.read(chunk, 0, available);
// print to console
System.out.print(new String(chunk));
Frequency frequnecy = new Frequency();
FrequencyDAO frequencyDAO = new FrequencyDAO();
frequencyDAO.insertFrequency(new String(chunk));
} catch (Exception e) {
System.err.println(e.toString());
}
}
}
}
和我得到的输出:
您想要将字段input
的类型更改为BufferedReader
并将其初始化,如下所示:
input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
使用缓冲的读取器,您可以一次读取一行,我想这就是您要存储在数据库中的内容。
然后相应地更新事件处理程序:
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
String line = input.readLine();
System.out.println(line);
FrequencyDAO frequencyDAO = new FrequencyDAO();
frequencyDAO.insertFrequency(line);
} catch (Exception e) {
System.err.println(e.toString());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.