【问题标题】:Arduino Java SerialEvent not being called未调用 Arduino Java SerialEvent
【发布时间】:2015-04-25 22:00:51
【问题描述】:

我正在关注一个简​​单的示例found here (example one),将 arduino 连接到 Raspberry Pi 并使用 Java 从 Pi 上的 arduino 读取一些数据。

问题是 SerialEvent 方法从未被调用,这意味着没有数据进入。但是,当我打开串行监视器时,我可以看到数据正在被正确读取。

也使用了正确的串口。

这里是 Java 代码。

    //This class:
// - Starts up the communication with the Arduino.
// - Reads the data coming in from the Arduino and
//   converts that data in to a useful form.
// - Closes communication with the Arduino.

//Code builds upon this great example:
//http://www.csc.kth.se/utbildning/kth/kurser/DH2400/interak06/SerialWork.java
//The addition being the conversion from incoming characters to numbers. 

//Load Libraries
import java.io.*;
import java.util.TooManyListenersException;

//Load RXTX Library
import gnu.io.*;

class ArduinoComm implements SerialPortEventListener
{

   //Used to in the process of converting the read in characters-
   //-first in to a string and then into a number.
   String rawStr="";

   //Declare serial port variable
   SerialPort mySerialPort;

   //Declare input steam
   InputStream in;

   boolean stop=false;

   public void start(String portName,int baudRate)
   {

      stop=false; 
      try 
      {
         //Finds and opens the port
         CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(portName);
         mySerialPort = (SerialPort)portId.open("my_java_serial" + portName, 2000);
         System.out.println("Serial port found and opened");

         //configure the port
         try 
         {
            mySerialPort.setSerialPortParams(baudRate,
            mySerialPort.DATABITS_8,
            mySerialPort.STOPBITS_1,
            mySerialPort.PARITY_NONE);
            System.out.println("Serial port params set: "+baudRate);
         } 
         catch (UnsupportedCommOperationException e)
         {
            System.out.println("Probably an unsupported Speed");
         }

         //establish stream for reading from the port
         try 
         {
            in = mySerialPort.getInputStream();
         } 
         catch (IOException e) 
         { 
            System.out.println("couldn't get streams");
         }

         // we could read from "in" in a separate thread, but the API gives us events
         try 
         {
            mySerialPort.addEventListener(this);
            mySerialPort.notifyOnDataAvailable(true);
            System.out.println("Event listener added");
         } 
         catch (TooManyListenersException e) 
         {
            System.out.println("couldn't add listener");
         }
      }
      catch (Exception e) 
      { 
         System.out.println("Port in Use: "+e);
      }
   }

   //Used to close the serial port
   public void closeSerialPort() 
   {
      try 
      {
         in.close();
         stop=true; 
         mySerialPort.close();
         System.out.println("Serial port closed");

      }
      catch (Exception e) 
      {
      System.out.println(e);
      }
   }

   //Reads the incoming data packets from Arduino. 
   public void serialEvent(SerialPortEvent event) 
   { 

      //Reads in data while data is available
      while (event.getEventType()== SerialPortEvent.DATA_AVAILABLE && stop==false) 
      {
         try 
         {
            //------------------------------------------------------------------- 

            //Read in the available character
            char ch = (char)in.read();

            //If the read character is a letter this means that we have found an identifier.
            if (Character.isLetter(ch)==true && rawStr!="")
            {
               //Convert the string containing all the characters since the last identifier into an integer
               int value = Integer.parseInt(rawStr);

               if (ch=='A')
               {
                  System.out.println("Value A is: "+value);
               }

               if (ch=='B')
               {
                  System.out.println("Value B is: "+value);
               }

               //Reset rawStr ready for the next reading
               rawStr = ("");
            } 
            else 
            {
               //Add incoming characters to a string.
               //Only add characters to the string if they are digits. 
               //When the arduino starts up the first characters it sends through are S-t-a-r-t- 
               //and so to avoid adding these characters we only add characters if they are digits.

               if (Character.isDigit(ch))
               {
                  rawStr = ( rawStr + Character.toString(ch));
               } 
               else 
               {
                  System.out.print(ch);
               } 
            }
         } 
         catch (IOException e) 
         {
         }
      }
   }

}

这是 Arduino 草图

    //Ardunio code for Part 01

//First we will define the values to be sent
//Note: The java code to go with this example reads-
//-in integers so values will have to be sent as integers
int valueA = 21;
int valueB = 534;

void setup()
{
   Serial.begin(115200);
   Serial.println("Start");
}

void loop()
{ 

   //We send the value coupled with an identifier character
   //that both marks the end of the value and what the value is.

   Serial.print(valueA);
   Serial.print("A");

   Serial.print(valueB);
   Serial.print("B");

   //A delay to slow the program down to human pace.
   delay(500);  

}

我已经读到将 Serial.print 更改为 Serial.write 是执行此操作的新方法,但更改它没有结果。

【问题讨论】:

    标签: java arduino raspberry-pi rxtx


    【解决方案1】:

    所以没有触发事件的原因是程序在它有机会之前退出并结束。

    为了解决这个问题,我在主线程内添加了一个带有循环的线程。

    public static void main(String[] args) throws Exception {
     ArduinoComm = new ArduinoComm ();
     main.start("/dev/ttyUSB0",115200);
     Thread t=new Thread() {
     public void run() {
     try {
     //Messy implementation but it works for this demo purpose
        while(true){
          //optional sleep  
          thread.Sleep(500);
        }
     } catch (InterruptedException ie) {}
     }
     };
     t.start();
     System.out.println("Started");
     }
    

    我有点疏忽。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-12
      • 1970-01-01
      • 2012-08-14
      • 1970-01-01
      相关资源
      最近更新 更多