java arduino 串行通信
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25932964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java arduino serial communication
提问by Giu_ai
I am trying to set up a java-arduino serial communication. So far I downloaded the code from the Arduino page (http://playground.arduino.cc/interfacing/java) but I get an error. Code:
我正在尝试建立一个 java-arduino 串行通信。到目前为止,我从 Arduino 页面 ( http://playground.arduino.cc/interface/java)下载了代码,但出现错误。代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.Enumeration;
public class SerialTest implements SerialPortEventListener {
SerialPort serialPort;
/** The port we're normally going to use. */
private static final String PORT_NAMES[] = {
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyACM0", // Raspberry Pi
"/dev/ttyUSB0", // Linux
"COM3", // Windows
};
/**
* A BufferedReader which will be fed by a InputStreamReader
* converting the bytes into characters
* making the displayed results codepage independent
*/
private BufferedReader input;
/** The output stream to the port */
private OutputStream output;
/** Milliseconds to block while waiting for port open */
private static final int TIME_OUT = 2000;
/** Default bits per second for COM port. */
private static final int DATA_RATE = 9600;
public void initialize() {
// the next line is for Raspberry Pi and
// gets us into the while loop and was suggested here was suggested http://www.raspberrypi.org/phpBB3/viewtopic.php?f=81&t=32186
System.setProperty("gnu.io.rxtx.SerialPorts", "/dev/ttyACM0");
CommPortIdentifier portId = null;
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)) {
portId = currPortId;
break;
}
}
}
if (portId == null) {
System.out.println("Could not find COM port.");
return;
}
try {
// open serial port, and use class name for the appName.
serialPort = (SerialPort) portId.open(this.getClass().getName(),
TIME_OUT);
// set port parameters
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
// open the streams
input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
output = serialPort.getOutputStream();
// add event listeners
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
System.err.println(e.toString());
}
}
/**
* This should be called when you stop using the port.
* This will prevent port locking on platforms like Linux.
*/
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
/**
* Handle an event on the serial port. Read the data and print it.
*/
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
String inputLine=input.readLine();
System.out.println(inputLine);
} catch (Exception e) {
System.err.println(e.toString());
}
}
// Ignore all the other eventTypes, but you should consider the other ones.
}
public static void main(String[] args) throws Exception {
SerialTest main = new SerialTest();
main.initialize();
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(1000000);} catch (InterruptedException ie) {}
}
};
t.start();
System.out.println("Started");
}
}
That's the output i get:
这就是我得到的输出:
Stable Library ========================================= Native lib Version = RXTX-2.2pre2 Java lib Version = RXTX-2.1-7 WARNING: RXTX Version mismatch Jar version = RXTX-2.1-7 native lib Version = RXTX-2.2pre2
Could not find COM port. Started
稳定库 ========================================== 本机库版本 = RXTX-2.2 pre2 Java lib 版本 = RXTX-2.1-7 警告:RXTX 版本不匹配 Jar 版本 = RXTX-2.1-7 本机 lib 版本 = RXTX-2.2pre2
找不到 COM 端口。开始
I am using Linux. And I think the port is correct. Anyone could help?
我正在使用 Linux。我认为端口是正确的。任何人都可以帮忙吗?
回答by HirdayGupta
After seeing the problems and struggling with RXTX and JSSC for while, I developed the JAVA Arduino Communication Library.
在看到问题并在RXTX和JSSC上挣扎了一段时间后,我开发了JAVA Arduino通信库。
My library has (hopefullyy) great documentation(found on the SourceForge Wiki for the library) and tells you exactly how to install and use it. After downloading both JARs in the library and including them in your classpath, just include the following statement before your class definition:
我的图书馆(希望如此)有很棒的文档(在图书馆的 SourceForge Wiki 上找到)并告诉你如何安装和使用它。在库中下载两个 JAR 并将它们包含在类路径中后,只需在类定义之前包含以下语句:
import arduino.*;
Now, all you need is the following code snippet in your method, and you're good to go!
现在,您只需要方法中的以下代码片段,就可以开始了!
String ArduinoPort = ""; //Your port name here
int BAUD_RATE = 9600;
Arduino arduino = new Arduino(ArduinoPort, BAUD_RATE);
arduino.openConnection();
arduino.serialWrite('1'); //serialWrite is an overridden method, allowing both characters and strings.
arduino.serialWrite('1', 20); //its second parameter even allows delays. more details can be found in the documentation.
The library also comes with example codethat I thought would help speed along the process.
回答by appsdownload
it seems to be permission issue. try : sudo chmod 666 /dev/ttyACM0 (you usb ) and rerun the java code again.
这似乎是权限问题。尝试: sudo chmod 666 /dev/ttyACM0 (you usb ) 并再次重新运行 java 代码。
回答by Andrew
"Could Not Find Com Port" is the default error for when your Arduino can't interface with Arduino IDE.
“Could Not Find Com Port”是您的 Arduino 无法与 Arduino IDE 接口时的默认错误。
In this case though, the error isn't saying that the Arduino IDE can't see your Arduino - its saying that the RXTX library can't see the Arduino.
但在这种情况下,错误并不是说 Arduino IDE 看不到您的 Arduino——而是说 RXTX 库看不到 Arduino。
Your PC's driver may be an older version, and not yet support the com required by RXTX...
你电脑的驱动可能是旧版本,还不支持RXTX要求的com...
Here's my advice:
这是我的建议:
Plugin your Arduino Board
插入您的 Arduino 板
Go to Control Panel ---> System and Security ---> System ---> On the left pane Device Manger
转到控制面板 ---> 系统和安全 ---> 系统 ---> 在左窗格中的设备管理器
Expand Other Devices.
展开其他设备。
Under Other Devices you will notice a icon with a small yellow error graphic. (Unplug all your other devices attached to any Serial Port)
在其他设备下,您会注意到一个带有黄色小错误图形的图标。(拔下连接到任何串行端口的所有其他设备)
Right Click on that device ---> Update Driver Software
右键单击该设备 ---> 更新驱动程序软件
Select Browse my computer for Driver Software
选择浏览我的计算机以查找驱动程序软件
Click on Browse ---> Browse for the folder of Arduino Environment which you have downloaded from Arduino website. If not downloaded then http://arduino.cc/en/Main/Software
点击 Browse ---> Browse 找到您从 Arduino 网站下载的 Arduino Environment文件夹。如果未下载,则http://arduino.cc/en/Main/Software
After Browsing mark include subfolder.
浏览后标记包括子文件夹。
Click next ---> Your driver will be installed.
单击下一步 ---> 您的驱动程序将被安装。
Collapse Other Devices ---> Expand Port ( its in device manager only under other devices )
折叠其他设备 ---> 扩展端口(仅在其他设备下的设备管理器中)
You will see Arduino Written ---> Look for its COM PORT (close device manager)
你会看到 Arduino Written ---> Look for its COM PORT (close device manager)
Go to Arduino Environment ---> Tools ---> Serial Port ---> Select the COM PORT as mentioned in PORT in device manager. (If you are using any other Arduino Board instead of UNO then select the same in boards )
转到 Arduino Environment ---> Tools ---> Serial Port ---> 选择设备管理器中 PORT 中提到的 COM PORT。(如果您使用任何其他 Arduino 板而不是 UNO,则在板中选择相同的)
Some Reference Material: http://www.devfactor.net/2014/10/26/arduino-basics-serial-communication/
一些参考资料:http: //www.devfactor.net/2014/10/26/arduino-basics-serial-communication/