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

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAnitaRaj43
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 

Recently uploaded (20)

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

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/