• <small id='Pfxm3'></small><noframes id='Pfxm3'>

  • <i id='Pfxm3'><tr id='Pfxm3'><dt id='Pfxm3'><q id='Pfxm3'><span id='Pfxm3'><b id='Pfxm3'><form id='Pfxm3'><ins id='Pfxm3'></ins><ul id='Pfxm3'></ul><sub id='Pfxm3'></sub></form><legend id='Pfxm3'></legend><bdo id='Pfxm3'><pre id='Pfxm3'><center id='Pfxm3'></center></pre></bdo></b><th id='Pfxm3'></th></span></q></dt></tr></i><div id='Pfxm3'><tfoot id='Pfxm3'></tfoot><dl id='Pfxm3'><fieldset id='Pfxm3'></fieldset></dl></div>

    1. <legend id='Pfxm3'><style id='Pfxm3'><dir id='Pfxm3'><q id='Pfxm3'></q></dir></style></legend><tfoot id='Pfxm3'></tfoot>
        • <bdo id='Pfxm3'></bdo><ul id='Pfxm3'></ul>

        Java/Arduino - 从串口读取数据

        Java/Arduino - Read data from the Serial Port(Java/Arduino - 从串口读取数据)

        <tfoot id='Ib35b'></tfoot>
        <i id='Ib35b'><tr id='Ib35b'><dt id='Ib35b'><q id='Ib35b'><span id='Ib35b'><b id='Ib35b'><form id='Ib35b'><ins id='Ib35b'></ins><ul id='Ib35b'></ul><sub id='Ib35b'></sub></form><legend id='Ib35b'></legend><bdo id='Ib35b'><pre id='Ib35b'><center id='Ib35b'></center></pre></bdo></b><th id='Ib35b'></th></span></q></dt></tr></i><div id='Ib35b'><tfoot id='Ib35b'></tfoot><dl id='Ib35b'><fieldset id='Ib35b'></fieldset></dl></div>
      1. <small id='Ib35b'></small><noframes id='Ib35b'>

            <tbody id='Ib35b'></tbody>

            <legend id='Ib35b'><style id='Ib35b'><dir id='Ib35b'><q id='Ib35b'></q></dir></style></legend>

                • <bdo id='Ib35b'></bdo><ul id='Ib35b'></ul>
                  本文介绍了Java/Arduino - 从串口读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  我有一个 Java 程序,我必须在其中读取 Arduino 发送的信息.我从 here 获取了 Java 代码.现在,我真的不明白它是如何工作的,但我尝试修改它并得到了这个:

                  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,然后我在需要时使用 Serial.readSerial.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 毫秒),但这并不意味着 Arduino 发送了一些东西.Arduino 仅在按下按钮时发送一个字节.因此,当 Java 代码运行时,它会在读取内容之前抛出n"异常,这会造成很大的延迟.

                  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.

                  如果你有一个有效的代码,如果你能把它给我,我会非常感激.我只需要两种方法,读和写,我不在乎代码是如何工作的: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

                  我更改了 Serial 类,现在它又像 apremalal 所说的那样具有这种方法

                  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 
                  }
                  

                  它正确打印值,但 data == "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?

                  好的解决了:

                  public void read(String data){
                  
                      serialRead = Integer.parseInt(data);
                  
                      if(serialRead == 255)
                          //code here 
                  }
                  

                  现在它的工作..不知道为什么我必须这样做...嗯,随便 :)

                  Now it's work..don't know why I had to do this... meh whatever :)

                  推荐答案

                  您不想专门编写一个读取函数,它已经存在于示例代码中.正如 TheMerovingian 指出的,您可以在读取之前检查输入缓冲区.这里是我在其中一个项目中使用的工作代码.

                  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 - 从串口读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                  相关文档推荐

                  How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
                  How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
                  Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
                  Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
                  How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
                  How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)
                  <tfoot id='kOu3N'></tfoot>
                • <small id='kOu3N'></small><noframes id='kOu3N'>

                        <tbody id='kOu3N'></tbody>
                      <legend id='kOu3N'><style id='kOu3N'><dir id='kOu3N'><q id='kOu3N'></q></dir></style></legend>

                          <bdo id='kOu3N'></bdo><ul id='kOu3N'></ul>

                            <i id='kOu3N'><tr id='kOu3N'><dt id='kOu3N'><q id='kOu3N'><span id='kOu3N'><b id='kOu3N'><form id='kOu3N'><ins id='kOu3N'></ins><ul id='kOu3N'></ul><sub id='kOu3N'></sub></form><legend id='kOu3N'></legend><bdo id='kOu3N'><pre id='kOu3N'><center id='kOu3N'></center></pre></bdo></b><th id='kOu3N'></th></span></q></dt></tr></i><div id='kOu3N'><tfoot id='kOu3N'></tfoot><dl id='kOu3N'><fieldset id='kOu3N'></fieldset></dl></div>