问题描述
我有在Java程序在那里我有读取一个Arduino发送的信息。
我从。现在,我真的不明白它是如何工作的,但我试图修改它,我得到这样的:
I've got a program in Java where I have to read the information that an Arduino is sending.I took the Java code from here. Now, I didn't really understand how it works, but I tried to modify it and I got this:
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 Serial implements SerialPortEventListener {
SerialPort serialPort;
private static final String PORT_NAMES[] = {
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyUSB0", // Linux
"COM3", // Windows
};
private BufferedReader input;
private static OutputStream output;
private static final int TIME_OUT = 2000;
private static final int DATA_RATE = 115200;
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 = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
output = serialPort.getOutputStream();
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
}
catch (Exception e) {
System.err.println(e.toString());
}
}
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());
}
}
}
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
public Serial(String ncom){
if(Integer.parseInt(ncom)>=3 && Integer.parseInt(ncom)<=9)
PORT_NAMES[2] = "COM" + ncom;
initialize();
Thread t=new Thread() {
public void run() {
try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
}
};
t.start();
System.out.println("Serial Comms Started");
}
public synchronized void send(int b){
try{
output.write(b);
}
catch (Exception e) {
System.err.println(e.toString());
}
}
public synchronized int read(){
int b = 0;
try{
b = (int)input.read();
}
catch (Exception e) {
System.err.println(e.toString());
}
return b;
}
}
我创建我需要在主程序 COM端口串行对象,然后我用 Serial.read
和 Serial.write
当我需要它。
I create the object Serial with the COM port I need in the main program, then I use Serial.read
and Serial.write
when I need it.
Serial.write
的伟大工程,Arduino的获取数据并显示在LCD显示屏。问题是 Serial.read
。当程序运行时,它不断地读取串口(周围的每一个40 NBSP; MS),但是,这并不意味着Arduino的发送什么。 Arduino的发送仅当一个按钮被按下一个字节。因此,在Java code运行时,它抛出N异常之前读到的东西,这couses这么多的滞后。
Serial.write
works great, Arduino gets the data and show it in a LCD Display. The problem is Serial.read
. When the program is running, it keep read from serial port (around every 40 ms), but that doesn't mean Arduino sent something. Arduino sends a byte only when a button is pushed. So, when the Java code is running, it throws "n" Exception before read something, and this couses so much lag.
我知道我需要像 Serial.available()
,我试过 input.available()
,但这是行不通的。我不知道如何解决这个问题。
I know I need something like Serial.available()
, I tried input.available()
, but it doesn't work. I don't know how to solve this problem.
如果你有一个code,它的工作,我会是这么感激,如果你可以把它给我。我只需要两个方法,读,写,我不在乎code如何工作的:D
If you have a code that working, I'd be so much grateful if you could give it to me. I just need two methods, read and write, I don't care how the code works :D
编辑:
我改变了串行类,现在又有这种方法为premalal说
I changed the Serial class, now it has again this method as apremalal said
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
String inputLine=null;
if (input.ready()) {
inputLine = input.readLine();
panel.read(inputLine);
}
} catch (Exception e) {
System.err.println(e.toString());
}
}
}
和其他类(面板在这种情况下)我有这样的:
and in the other class (Panel in this case) I've got this:
public void read(String data){
System.out.println(data);
System.out.println(data == "255");
if(data == "255")
//code here
}
它正确打印值,但数据==255
永远是假的,即使我真的得到了255
....我试图做的Integer.parseInt
但没有改变。凭啥?
It print the values correctly but data == "255"
is always false, even if I really get a 255....I tried to do Integer.parseInt
but nothing changed. Why the hell?
编辑2:好解决:\\
EDIT 2: Ok solved :\
public void read(String data){
serialRead = Integer.parseInt(data);
if(serialRead == 255)
//code here
}
现在是work..don't知道为什么我不得不这样做......咩什么:)
Now it's work..don't know why I had to do this... meh whatever :)
推荐答案
您不想写专门的读取功能,它已经存在于样品code.As TheMerovingian指出,你可以检查前输入缓冲区reading.Here是工作code,我在我的一个项目已经使用。
You don't want to specifically write a read function it's already there in the sample code.As TheMerovingian pointed out you can check the input Buffer before reading.Here is the working code which I have used in one of my projects.
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/ttyUSB0", // Linux
"COM35", // Windows
};
private BufferedReader 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();
//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 {
serialPort = (SerialPort) portId.open(this.getClass().getName(),
TIME_OUT);
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();
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 {
String inputLine=null;
if (input.ready()) {
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");
}
}
编辑:的serialEvent函数负责读缓冲器
EDIT : serialEvent function is responsible for reading the buffer.
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
String inputLine=null;
if (input.ready()) {
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.
}
这篇关于的Java / Arduino的 - 从串口读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!