SlideShare a Scribd company logo
1 of 4
###############################################################
## CETENE/LINCS - CampinaGrande/Recife - Paraíba/Pernambuco - Brasil ##
##   Dalton Cézane Gomes Valadares – Embedded Systems Developer      ##
##        Master's/Specialist/Bachelor in Computer Science-UFCG      ##
###############################################################

 How to communicate Java application via serial port on Beagleboard running
                               Angstrom

-Install Java on Angstrom
  opkg install openjdk-6-jre
-Install RxTx Library for serial communication
  opkg install librxtx-java librxtx-jni

-Create a class to open a serial connection and communicate with it:
package cetene.lincs.cg.bioquali;

import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;

/**
 * @author …
 */
public class SerialComm implements SerialPortEventListener {

  private static final String EMBEDDED_LINUX_PORT = "/dev/ttyS2";
      private static final String WINDOWS_PORT = "COM1";
      InputStream inputStream;

  public void execute() {
    String portName = getPortNameByOS();
    CommPortIdentifier portId = getPortIdentifier(portName);

    if(portId != null) {

       try {
             SerialPort serialPort = (SerialPort)
portId.open(this.getClass().getName(), 2000);
                           inputStream = serialPort.getInputStream();
             serialPort.addEventListener(this);
             serialPort.notifyOnDataAvailable(true);
serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
                                         SerialPort.PARITY_NONE);
       }
       catch (PortInUseException e) {}

        catch (IOException e) {}

        catch (UnsupportedCommOperationException e) {
          e.printStackTrace();
        }
        catch (TooManyListenersException e) {}

      } else {
         System.out.println("Porta Serial não disponível");
      }
  }

  /**
   * Get The port name
   **/
  private String getPortNameByOS() {

    String osname = System.getProperty("os.name","").toLowerCase();
    if ( osname.startsWith("windows") ) {
           // windows
           return WINDOWS_PORT;
    } else if (osname.startsWith("linux")) {
           // linux
           return EMBEDDED_LINUX_PORT; //Angstrom running on
Beagleboard...
    } else if ( osname.startsWith("mac") ) {
           // mac
           return "???";
    } else {
           System.out.println("Sorry, your operating system is not supported");
           System.exit(1);
           return null;
    }

  }
  /**
   *Get the Port Identifier
   **/
  private CommPortIdentifier getPortIdentifier(String portName) {
      Enumeration portList = CommPortIdentifier.getPortIdentifiers();
      Boolean portFound = false;
      while (portList.hasMoreElements()) {
       CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
System.out.println("Available port: " + portId.getName());
             if (portId.getName().equals(portName)) {
                  System.out.println("Found port: "+portName);
                 portFound = true;
                 return portId;
             }
           }
        }
        return null;
    }

    public void serialEvent(SerialPortEvent event) {

                 switch (event.getEventType()) {
                        case SerialPortEvent.BI:
                        case SerialPortEvent.OE:
                        case SerialPortEvent.FE:
                        case SerialPortEvent.PE:
                        case SerialPortEvent.CD:
                        case SerialPortEvent.CTS:
                        case SerialPortEvent.DSR:
                        case SerialPortEvent.RI:
                        case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                              break;
                        case SerialPortEvent.DATA_AVAILABLE:
                              byte[] readBuffer = new byte[20];
                              try {
                                      int numBytes = 0;
                                      int count = 0;
                                      while (inputStream.available() > 0 && count <
5) {
                                            numBytes =
inputStream.read(readBuffer);
                                             count++;
                                      }
                               String result = new String(readBuffer);
             result += result.substring(1, numBytes);
             System.out.println(result);
             // System.out.println(readBuffer);

                              } catch (IOException e) {}

                              break;
                 }
         }

}

-After compile, run the application as follow:
 java -cp .:/usr/share/java/RXTXcomm.jar
-Djava.library.path=/lib:/usr/lib/jni 
 -Dgnu.io.rxtx.SerialPorts=/dev/ttyACM0 SerialComm
/dev/ttyACM0

-In my case, adding other libs:
 java -cp ./EmbeddedBioquali/bin/.:./EmbeddedBioquali/lib/fluent-hc-
4.2.2.jar:./EmbeddedBioquali/lib/httpcore-
4.2.2.jar:./EmbeddedBioquali/lib/commons-codec-
1.6.jar:./EmbeddedBioquali/lib/httpclient-
4.2.2.jar:./EmbeddedBioquali/lib/httpmime-
4.2.2.jar:./EmbeddedBioquali/lib/commons-logging-
1.1.1.jar:./EmbeddedBioquali/lib/httpclient-cache-
4.2.2.jar:/usr/share/java/RXTXcomm.jar -Djava.library.path=/lib:/usr/lib/jni
-Dgnu.io.rxtx.SerialPorts=/dev/ttyS2 TestService /dev/ttyS2

Reference:
http://embeddedgeeks.wordpress.com/2012/02/26/arduino-beagleboard-serial-
communication-using-java-rxtx/

More Related Content

More from Dalton Valadares

Performance Evaluation of an IEEE 802.11g Network in an Industrial Environment
Performance Evaluation of an IEEE 802.11g Network in an Industrial EnvironmentPerformance Evaluation of an IEEE 802.11g Network in an Industrial Environment
Performance Evaluation of an IEEE 802.11g Network in an Industrial EnvironmentDalton Valadares
 
802.11g Signal Strength Evaluation in an Industrial Environment (Elsevier Int...
802.11g Signal Strength Evaluation in an Industrial Environment (Elsevier Int...802.11g Signal Strength Evaluation in an Industrial Environment (Elsevier Int...
802.11g Signal Strength Evaluation in an Industrial Environment (Elsevier Int...Dalton Valadares
 
Towards 802.11g Signal Strength Estimation in an Industrial Environment: a Pr...
Towards 802.11g Signal Strength Estimation in an Industrial Environment: a Pr...Towards 802.11g Signal Strength Estimation in an Industrial Environment: a Pr...
Towards 802.11g Signal Strength Estimation in an Industrial Environment: a Pr...Dalton Valadares
 
Towards 802.11g Signal Strength Estimation in an Industrial Environment: a Pr...
Towards 802.11g Signal Strength Estimation in an Industrial Environment: a Pr...Towards 802.11g Signal Strength Estimation in an Industrial Environment: a Pr...
Towards 802.11g Signal Strength Estimation in an Industrial Environment: a Pr...Dalton Valadares
 
Internet das Coisas e a Indústria 4.0
Internet das Coisas e a Indústria 4.0Internet das Coisas e a Indústria 4.0
Internet das Coisas e a Indústria 4.0Dalton Valadares
 
Achieving Data Dissemination with Security using FIWARE and Intel Software Gu...
Achieving Data Dissemination with Security using FIWARE and Intel Software Gu...Achieving Data Dissemination with Security using FIWARE and Intel Software Gu...
Achieving Data Dissemination with Security using FIWARE and Intel Software Gu...Dalton Valadares
 
Internet das Coisas com Edgex Foundry
Internet das Coisas com Edgex FoundryInternet das Coisas com Edgex Foundry
Internet das Coisas com Edgex FoundryDalton Valadares
 
OPTEE on QEMU - Build Tutorial
OPTEE on QEMU - Build TutorialOPTEE on QEMU - Build Tutorial
OPTEE on QEMU - Build TutorialDalton Valadares
 
Presentation of my paper in the IEEE Symposium on Computer and Communications...
Presentation of my paper in the IEEE Symposium on Computer and Communications...Presentation of my paper in the IEEE Symposium on Computer and Communications...
Presentation of my paper in the IEEE Symposium on Computer and Communications...Dalton Valadares
 
Avaliação de Desempenho de uma Rede 802.11g em uma Usina Termoelétrica
Avaliação de Desempenho de uma Rede 802.11g em uma Usina TermoelétricaAvaliação de Desempenho de uma Rede 802.11g em uma Usina Termoelétrica
Avaliação de Desempenho de uma Rede 802.11g em uma Usina TermoelétricaDalton Valadares
 
Apresentação sobre o modelo de segurança OPC UA
Apresentação sobre o modelo de segurança OPC UAApresentação sobre o modelo de segurança OPC UA
Apresentação sobre o modelo de segurança OPC UADalton Valadares
 
Modelo de segurança OPC UA
Modelo de segurança OPC UAModelo de segurança OPC UA
Modelo de segurança OPC UADalton Valadares
 
Introdução à Gestão de projetos
Introdução à Gestão de projetosIntrodução à Gestão de projetos
Introdução à Gestão de projetosDalton Valadares
 
Integrating Fiware Orion, Keyrock and Wilma
Integrating Fiware Orion, Keyrock and WilmaIntegrating Fiware Orion, Keyrock and Wilma
Integrating Fiware Orion, Keyrock and WilmaDalton Valadares
 
Desenvolvimento Web com JSF
Desenvolvimento Web com JSFDesenvolvimento Web com JSF
Desenvolvimento Web com JSFDalton Valadares
 
Comparison of signal smoothing techniques for use in embedded system for moni...
Comparison of signal smoothing techniques for use in embedded system for moni...Comparison of signal smoothing techniques for use in embedded system for moni...
Comparison of signal smoothing techniques for use in embedded system for moni...Dalton Valadares
 
Apresentação sobre artigo relacionado a Controle de Topologia em Redes de Sen...
Apresentação sobre artigo relacionado a Controle de Topologia em Redes de Sen...Apresentação sobre artigo relacionado a Controle de Topologia em Redes de Sen...
Apresentação sobre artigo relacionado a Controle de Topologia em Redes de Sen...Dalton Valadares
 

More from Dalton Valadares (20)

Performance Evaluation of an IEEE 802.11g Network in an Industrial Environment
Performance Evaluation of an IEEE 802.11g Network in an Industrial EnvironmentPerformance Evaluation of an IEEE 802.11g Network in an Industrial Environment
Performance Evaluation of an IEEE 802.11g Network in an Industrial Environment
 
802.11g Signal Strength Evaluation in an Industrial Environment (Elsevier Int...
802.11g Signal Strength Evaluation in an Industrial Environment (Elsevier Int...802.11g Signal Strength Evaluation in an Industrial Environment (Elsevier Int...
802.11g Signal Strength Evaluation in an Industrial Environment (Elsevier Int...
 
Towards 802.11g Signal Strength Estimation in an Industrial Environment: a Pr...
Towards 802.11g Signal Strength Estimation in an Industrial Environment: a Pr...Towards 802.11g Signal Strength Estimation in an Industrial Environment: a Pr...
Towards 802.11g Signal Strength Estimation in an Industrial Environment: a Pr...
 
Towards 802.11g Signal Strength Estimation in an Industrial Environment: a Pr...
Towards 802.11g Signal Strength Estimation in an Industrial Environment: a Pr...Towards 802.11g Signal Strength Estimation in an Industrial Environment: a Pr...
Towards 802.11g Signal Strength Estimation in an Industrial Environment: a Pr...
 
Internet das Coisas e a Indústria 4.0
Internet das Coisas e a Indústria 4.0Internet das Coisas e a Indústria 4.0
Internet das Coisas e a Indústria 4.0
 
Achieving Data Dissemination with Security using FIWARE and Intel Software Gu...
Achieving Data Dissemination with Security using FIWARE and Intel Software Gu...Achieving Data Dissemination with Security using FIWARE and Intel Software Gu...
Achieving Data Dissemination with Security using FIWARE and Intel Software Gu...
 
Internet das Coisas com Edgex Foundry
Internet das Coisas com Edgex FoundryInternet das Coisas com Edgex Foundry
Internet das Coisas com Edgex Foundry
 
OPTEE on QEMU - Build Tutorial
OPTEE on QEMU - Build TutorialOPTEE on QEMU - Build Tutorial
OPTEE on QEMU - Build Tutorial
 
Presentation of my paper in the IEEE Symposium on Computer and Communications...
Presentation of my paper in the IEEE Symposium on Computer and Communications...Presentation of my paper in the IEEE Symposium on Computer and Communications...
Presentation of my paper in the IEEE Symposium on Computer and Communications...
 
Avaliação de Desempenho de uma Rede 802.11g em uma Usina Termoelétrica
Avaliação de Desempenho de uma Rede 802.11g em uma Usina TermoelétricaAvaliação de Desempenho de uma Rede 802.11g em uma Usina Termoelétrica
Avaliação de Desempenho de uma Rede 802.11g em uma Usina Termoelétrica
 
Apresentação sobre o modelo de segurança OPC UA
Apresentação sobre o modelo de segurança OPC UAApresentação sobre o modelo de segurança OPC UA
Apresentação sobre o modelo de segurança OPC UA
 
Modelo de segurança OPC UA
Modelo de segurança OPC UAModelo de segurança OPC UA
Modelo de segurança OPC UA
 
Introdução à Gestão de projetos
Introdução à Gestão de projetosIntrodução à Gestão de projetos
Introdução à Gestão de projetos
 
Integrating Fiware Orion, Keyrock and Wilma
Integrating Fiware Orion, Keyrock and WilmaIntegrating Fiware Orion, Keyrock and Wilma
Integrating Fiware Orion, Keyrock and Wilma
 
Programação C - Aula 1
Programação C - Aula 1Programação C - Aula 1
Programação C - Aula 1
 
Programação C - Aula 3
Programação C - Aula 3Programação C - Aula 3
Programação C - Aula 3
 
Programação C - Aula 4
Programação C - Aula 4Programação C - Aula 4
Programação C - Aula 4
 
Desenvolvimento Web com JSF
Desenvolvimento Web com JSFDesenvolvimento Web com JSF
Desenvolvimento Web com JSF
 
Comparison of signal smoothing techniques for use in embedded system for moni...
Comparison of signal smoothing techniques for use in embedded system for moni...Comparison of signal smoothing techniques for use in embedded system for moni...
Comparison of signal smoothing techniques for use in embedded system for moni...
 
Apresentação sobre artigo relacionado a Controle de Topologia em Redes de Sen...
Apresentação sobre artigo relacionado a Controle de Topologia em Redes de Sen...Apresentação sobre artigo relacionado a Controle de Topologia em Redes de Sen...
Apresentação sobre artigo relacionado a Controle de Topologia em Redes de Sen...
 

Recently uploaded

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 

Recently uploaded (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 

How to communicate Java application via serial port on Beagleboard running Angstrom

  • 1. ############################################################### ## CETENE/LINCS - CampinaGrande/Recife - Paraíba/Pernambuco - Brasil ## ## Dalton Cézane Gomes Valadares – Embedded Systems Developer ## ## Master's/Specialist/Bachelor in Computer Science-UFCG ## ############################################################### How to communicate Java application via serial port on Beagleboard running Angstrom -Install Java on Angstrom opkg install openjdk-6-jre -Install RxTx Library for serial communication opkg install librxtx-java librxtx-jni -Create a class to open a serial connection and communicate with it: package cetene.lincs.cg.bioquali; import gnu.io.CommPortIdentifier; import gnu.io.PortInUseException; import gnu.io.SerialPort; import gnu.io.SerialPortEvent; import gnu.io.SerialPortEventListener; import gnu.io.UnsupportedCommOperationException; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.TooManyListenersException; /** * @author … */ public class SerialComm implements SerialPortEventListener { private static final String EMBEDDED_LINUX_PORT = "/dev/ttyS2"; private static final String WINDOWS_PORT = "COM1"; InputStream inputStream; public void execute() { String portName = getPortNameByOS(); CommPortIdentifier portId = getPortIdentifier(portName); if(portId != null) { try { SerialPort serialPort = (SerialPort) portId.open(this.getClass().getName(), 2000); inputStream = serialPort.getInputStream(); serialPort.addEventListener(this); serialPort.notifyOnDataAvailable(true);
  • 2. serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (PortInUseException e) {} catch (IOException e) {} catch (UnsupportedCommOperationException e) { e.printStackTrace(); } catch (TooManyListenersException e) {} } else { System.out.println("Porta Serial não disponível"); } } /** * Get The port name **/ private String getPortNameByOS() { String osname = System.getProperty("os.name","").toLowerCase(); if ( osname.startsWith("windows") ) { // windows return WINDOWS_PORT; } else if (osname.startsWith("linux")) { // linux return EMBEDDED_LINUX_PORT; //Angstrom running on Beagleboard... } else if ( osname.startsWith("mac") ) { // mac return "???"; } else { System.out.println("Sorry, your operating system is not supported"); System.exit(1); return null; } } /** *Get the Port Identifier **/ private CommPortIdentifier getPortIdentifier(String portName) { Enumeration portList = CommPortIdentifier.getPortIdentifiers(); Boolean portFound = false; while (portList.hasMoreElements()) { CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
  • 3. System.out.println("Available port: " + portId.getName()); if (portId.getName().equals(portName)) { System.out.println("Found port: "+portName); portFound = true; return portId; } } } return null; } public void serialEvent(SerialPortEvent event) { switch (event.getEventType()) { case SerialPortEvent.BI: case SerialPortEvent.OE: case SerialPortEvent.FE: case SerialPortEvent.PE: case SerialPortEvent.CD: case SerialPortEvent.CTS: case SerialPortEvent.DSR: case SerialPortEvent.RI: case SerialPortEvent.OUTPUT_BUFFER_EMPTY: break; case SerialPortEvent.DATA_AVAILABLE: byte[] readBuffer = new byte[20]; try { int numBytes = 0; int count = 0; while (inputStream.available() > 0 && count < 5) { numBytes = inputStream.read(readBuffer); count++; } String result = new String(readBuffer); result += result.substring(1, numBytes); System.out.println(result); // System.out.println(readBuffer); } catch (IOException e) {} break; } } } -After compile, run the application as follow: java -cp .:/usr/share/java/RXTXcomm.jar
  • 4. -Djava.library.path=/lib:/usr/lib/jni -Dgnu.io.rxtx.SerialPorts=/dev/ttyACM0 SerialComm /dev/ttyACM0 -In my case, adding other libs: java -cp ./EmbeddedBioquali/bin/.:./EmbeddedBioquali/lib/fluent-hc- 4.2.2.jar:./EmbeddedBioquali/lib/httpcore- 4.2.2.jar:./EmbeddedBioquali/lib/commons-codec- 1.6.jar:./EmbeddedBioquali/lib/httpclient- 4.2.2.jar:./EmbeddedBioquali/lib/httpmime- 4.2.2.jar:./EmbeddedBioquali/lib/commons-logging- 1.1.1.jar:./EmbeddedBioquali/lib/httpclient-cache- 4.2.2.jar:/usr/share/java/RXTXcomm.jar -Djava.library.path=/lib:/usr/lib/jni -Dgnu.io.rxtx.SerialPorts=/dev/ttyS2 TestService /dev/ttyS2 Reference: http://embeddedgeeks.wordpress.com/2012/02/26/arduino-beagleboard-serial- communication-using-java-rxtx/