• Home
  • ExtropyNOW! - Courses
    • Mechatronics Engineering >
      • Mechatronics - 1st Tetramester >
        • ME-01-English I / Inglés I
        • ME-01-Values of the being / Valores del ser
        • ME-01-Metrology / Metrología >
          • Proteus Simulation Tutorial
        • ME-01-Electricity and magnetism / Electricidad y magnetismo
        • ME-01-AutoCAD / Dibujo para Ingeniería
        • ME-01-Differential and Integral Calculus >
          • II - Limits and continuity.
        • ME-01-Lineal Algebra / Álgebra lineal
      • Mechatronics - 2nd Tetramester >
        • ME-02-English II / Inglés II
        • ME-02-Emotional Intelligence / Intelligencia Emocional
        • ME-02-Static / Estática (Mechanical)
        • ME-02-Electronical Circuit Analysis / Análisis de Circuitos
        • ME-02-Structured Programming / Programación Estructurada (C)
        • ME-02-Vectorial Calculus / Cálculo Vectorial
        • ME-02-Normativity and Industrial Security / Normatividad y Seguridad Industrial
      • Mechatronics - 3rd Tetramester >
        • ME-03-English III / Inglés III
        • ME-03-Interpersonal Development / Desarrollo Interpersonal
        • ME-03-Dynamics / Dinámica (Mechanical)
        • ME-03-Analogic Electronics / Electrónica Analógica >
          • ME-03-Analog Electronics-Useful schematics
        • ME-03-Digital Electronics / Electrónica Digital >
          • N555 as timer.
        • ME-03-Probability and Statistics / Probabilidad y Estadística
        • ME-03-Maintenance Engineering
      • Mechatronics - 4th Tetramester >
        • ME-04-Thinking Abilities / Habilidades del Pensamiento
        • ME-04-Material's Resistance / Resistencia de los Materiales
        • ME-04-Power Electronics / Electrónica de Potencia
        • ME-04-Periphereal Programming / Programación de Periféricos (LabVIEW)
        • ME-04-Differential Equations / Ecuaciones Diferenciales
        • ME-04-First Internship / Estancia I
      • Mechatronics - 5th Tetramester >
        • ME-05-English V - Inglés V
        • ME-05-Organizational Abilities / Habilidades Organizacionales
        • ME-05-Engine's Analysis / Análisis de Mecanismos
        • ME-05-Sensor's and Signal Conditioning / Sensores y Acondicionamiento de Señales
        • ME-05-Microcontrollers / Microcontroladores (PIC)
        • ME-05-System's Modelling and Simulation
        • ME-05-Fluid Mechanics
      • Mechatronics - 6th Tetramester >
        • ME-06-English VI - Inglés VI
        • ME-06-Professional Ethics / Ética Profesional
        • ME-06-Mechanical Design / Diseño Mecánico
        • ME-06-Industrial Automation / Automatización Industrial (PLC's)
        • ME-06-Electric Machines / Máquinas Eléctricas
        • ME-06-Manufacturing Processes / Procesos de Manufactura
        • ME-06-Pneumatic and Hydraulic Systems / Sistemas Hidráulicos y Neumáticos
      • Mechatronics - 7th Tetramester >
        • ME-07-English VII / Inglés VII
        • ME-07-Signal Processing and Acquisition / Adquisición y Procesamiento de Señales (PDS)
        • ME-07-Computer Assisted Engineering / Ingeniería Asistida por Computadora
        • ME-07-Project's Engineering and Management / Administración e Ingeniería de Proyectos
        • ME-07-Economic Engineering / Ingeniería Económica
        • ME-07-Control Theory / Teoría de Control
        • ME-07-Second Internships / Estancias II
      • Mechatronics - 8th Tetramester >
        • ME-08-English VIII / Inglés VIII
        • ME-08-Termodynamics / Termodinámica
        • ME-08-CAM & CNC Systems / Sistemas CAM y CNC
        • ME-08-Mechatronic Design / Diseño Mecatrónico
        • ME-08-Kinematics of Robots / Cinemática de Robots
        • ME-08-Digital Control / Control Digital
        • ME-08-Mechanical Vibrations / Vibraciones Mecánicas
      • Mechatronics - 9th Tetramester. >
        • ME-09-English IX / Inglés IX
        • ME-09-Heat Transfer / Transferencia de Calor (Mechanical)
        • ME-09-Industrial Networks / Redes Industriales
        • ME-09-Mechatronics System's Integration / Integración de Sistemas Mecatrónicos (Matlab) >
          • AM Modulation - Simulation.
        • ME-09-Robot's Dynamics and Control
        • ME-09-Intelligent Control / Control Inteligente
        • ME-09-Quality and Technological Innovation. >
          • ME-09-Evidences Folder
        • A) Robotics and Control. >
          • I.-Robotics I / F. Kinematics. >
            • I.I.-An Introduction to Robotics
          • II.-Digital Control.
        • B) Computing and Programming. >
          • I.-Setting the Kinect on Ubuntu Linux (libfreenect).
          • II.-CNC Programming >
            • II.I.-An Introduction to CNC
            • II.II.-CNC Milling.
          • C) Electronics.
    • Master in Engineering with specialty on Information Technologies >
      • pcDuino
      • Artificial Intelligence >
        • Knowledge Representation >
          • Writing ontologies (RDFS and OWL)
          • RDFLib Python
          • My First Ontology in Protegé
          • My First Ontology in Protegé II
          • Making queries
          • Where to get ontologies
        • Neural Networks >
          • Perceptrons (Linear Functions)
          • One vs All Perceptron
          • Radial Networks
        • Genetic Programming >
          • Graph Colouring using GA
          • GA for function approximation >
            • String parsing
        • Scientific computing.
        • Cellular Automata
      • Machine Learning
      • Natural Language Processing >
        • AIML Language on Python
        • Machine translation
        • Markov Chatbot
        • Python Input Timeout Bot
      • Fundamentals of Information Systems >
        • Data structures >
          • Linked lists
          • Trees >
            • Implementation Binary Search Tree
          • Sparse Distributed Memory
          • Debugging with gdb
          • Finite State Machines
        • JavaFX
      • Electronics >
        • KiCAD - My First Project
        • KiCAD - Adding components
        • kiCAD - Creating Components
        • SPICE Tutorial II
        • SPICE Tutorial II - Part II
      • VHDL >
        • Programming VHDL Part I >
          • Programming VHDL Part II
          • Loading VHDL to FPGA - Part I
          • Loading VHDL to FPGA - Part II
          • VHDL - First Steps Alternative version
        • Loops
        • Switches and leds
        • UART
        • PicoBlaze uC + FPGA
        • ADC
      • Logic Programming
    • Computing. >
      • Adding subtitles to video files
      • Server Side Programming >
        • Webhosting >
          • WordPress
        • Online Storage
        • Apache/PHP >
          • MongoDB >
            • MongoDB in Python
        • Node.js >
          • NodeJS Client requests
          • MySQL with NodeJS
      • Hyperboria
      • Angular 4
      • Smartphones >
        • Rooting Samsung Galaxy Tab 2.7.0 Model P3110 >
          • Creating Nandroid Backup with Command Line
          • Installing Ubuntu Linux on Samsung Galaxy Tab 2.7.0
          • Porting Utopic Unicorn 14.10 to tablet P3110.
        • PhoneGap - Apache Cordova >
          • Debugging PhoneGap
          • PhoneGap - MyFirstApp
          • Phone Gap - My First App II
          • Improving Look and Feel with OnsenUI >
            • AngularJS + OnsenUI + Monaca
            • Angular2 + TypeScript + OnsenUI
          • Storage in Apache Cordova & Monaca
          • Maps in PhoneGap
          • Getting user location with PhoneGap
        • QT C++ >
          • Qt signals and slots
          • QT for Android
          • QT Deployment.
        • PyQt Threads
      • Computer vision >
        • OpenGL >
          • OpenGL-HelloWorld
        • Computer Vision with Matlab/Octave
        • JavaCV
        • OpenCV
      • LaTeX >
        • Citations with Zotero + LaTeX
      • Reddit
      • Video Game creation >
        • Unity3D
        • Live2D
        • Babylon JS
    • Biochemistry.
    • Humanities >
      • Cognitive Science
      • Learning
    • Economics. >
      • Accounting
      • III.-Mexican economics.
      • Patents
    • Philosophy >
      • II. The philosophical method.
      • III. Intuition as method for philosophy.
      • IV. Comes ontology.
      • V. & VI. Parménides metaphysics and Plato's realism.
      • Extropianism.
      • Extropianism II.
      • Extropianism III.
  • ExtropyNOW! - Projects
    • MacOS X on Virtual Box
    • TankSupervision System >
      • Programming
      • Programming 2 - RXTX
      • Designing the interface
      • RXTX - Functions.
      • Keybinding - Functions.
      • FAQ
    • Homemade Projector
    • Hospital Automation App >
      • Face Recognition Part I - The basics
      • Pressure and Temperature
    • The CHAMBER Project >
      • Brain Computer Interface
      • Building the Brain (AGI) >
        • OpenCog First Application
      • Server Side Programming >
        • Tornado
        • First Django Project
        • First Django Project II
      • HA Project
      • One DOF robotic arm controlled with MS Kinect. >
        • Setting Kinect+MatLAB+Processing
        • Setting communication between MatLAB and Processing.
        • The Bibliography.
    • Madoka: Superior
  • ExtropyNOW! - Interactive
    • ExtropyNOW! - Blog
    • ExtropyNOW! - Forums
  • ExtropyNOW! - Code repository...
    • ExtropyNOW! Code Repository Part II
    • ExtropyNOW! - School repository
    • ExtropyNOW! - School repository 2 >
      • School repository 3
    • ExtropyNOW! - Interesting WebPages.
  Extropy NOW!
Contact/Contacto:

RXTX - Useful functions.

As of today March-14-2014 I've stopped using the RXTX library because we acquired a PCDuino.
Its like a small computer or tablet capable of running an OS and acting like an embedded system at the same time. I'll be using the OTG library which is contained in the GPIO to access the ports directly from the application without having to worry about serial communication problems.

Still, I found the RXTX library useful for many projects before and given that not everybody has the chance or the resources to acquire a Raspberry, PcDuino, Beaglebone or similar, I'll leave the functions used in my applications so that they can be useful for those working with RXTX and Java.

NOTE: BTW they're not mine :P
/*
 * Class uses the RXTX Library for Serial Communication
 * to send, receive and encode Strings from an Arduino
 *
 * done by Laurid Meyer
 * 28.04.2012
 *
 * http://www.lauridmeyer.com
 */
 
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
 
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import org.jfree.ui.RefineryUtilities;
 
public class RXTX 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
                "COM11", // Windows
                };
        /** Buffered input stream from the port */
        private InputStream input;
        /** The output stream to the port */
        private OutputStream output;
        /** Milliseconds to block while waiting for port open */
        private static final int TIME_OUT = 2000;
        /** Default bits per second for COM port. */
        private static final int DATA_RATE = 9600;
 
        private String inputBuffer="";
        public String data="";
        
        
        
        
        public void initialize() {
            CommPortIdentifier portId = null;
            Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
 
            // iterate through, looking for the port
            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;
            }else{
                System.out.println("Found your Port");
            }
 
            try {
                // open serial port, and use class name for the appName.
                serialPort = (SerialPort) portId.open(this.getClass().getName(),TIME_OUT);
 
                // set port parameters
                serialPort.setSerialPortParams(DATA_RATE,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);
 
                // open the streams
                input = serialPort.getInputStream();
                output = serialPort.getOutputStream();
 
                // add event listeners
                serialPort.addEventListener(this);
                serialPort.notifyOnDataAvailable(true);
                
                
 
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
 
        /**
         * This should be called when you stop using the port.
         * This will prevent port locking on platforms like Linux.
         */
        public synchronized void close() {
            if (serialPort != null) {
                serialPort.removeEventListener();
                serialPort.close();
            }
        }
 
        /**
         * This Method can be called to print a String
         * to the serial connection
         */
        public synchronized void sendString(String msg){
            try {
                msg+='\n';//add a newline character
                output.write(msg.getBytes());//write it to the serial
                output.flush();//refresh the serial
                System.out.print("<- "+msg);//output for debugging
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
 
        /**
         * This Method is called when a command is recieved
         * and needs to be encoded
         */
        private synchronized void encodeCommand(String com){
            if(com.indexOf("s:")==0){//checks if the String starts with s for set
                String id=com.substring(com.indexOf("s:")+2, com.indexOf(","));//remove the s, and store the "p1"
                String value=com.substring(com.indexOf(",")+1, com.length());//store everything after the ","
                if(id.equals("p1") && !value.equals("")){//if it's my poti1 and it sends a value
                    String myValue="s:s1,"+value;//set the value to my servo1
                    sendString(myValue);//and send it via the serial
                }else{
                    System.out.println("not correct values");
                }
            }
        }
 
        /**
         * This Method is called when Serialdata is recieved
         */      
        public synchronized void serialEvent (SerialPortEvent oEvent) {
            /*if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                try {
                    int available = input.available();
                    for(int i=0;i<available;i++){//read all incoming characters
                        int receivedVal=input.read();//store it into an int (because of the input.read method
                        if(receivedVal!=10 && receivedVal!=13){//if the character is not a new line "\n" and not a carriage return
                            inputBuffer+=(char)receivedVal;//store the new character into a buffer
                        }else if(receivedVal==10){//if it's a new line character
                            data = inputBuffer;
                            encodeCommand(inputBuffer);//call the method to encode the recieved command
                            inputBuffer="";//clear the buffer
                        }
                    }
                } catch (Exception e) {
                    System.err.println(e.toString());
                }
            }*/
        }
        
        private class ReadThread implements Runnable {
        public void run() {
        while(true) {
            serialRead();
                    }
            }
        }
        
        public void setSerialListener() {
            new Thread(new ReadThread()).start();
        }
        
        public void                                                                                                                                 serialRead()
        {
            try {
                    int available = input.available();
                    for(int i=0;i<available;i++){//read all incoming characters
                        int receivedVal=input.read();//store it into an int (because of the input.read method
                        if(receivedVal!=10 && receivedVal!=13){//if the character is not a new line "\n" and not a carriage return
                            inputBuffer+=(char)receivedVal;//store the new character into a buffer
                        }else if(receivedVal==10){//if it's a new line character
                            System.out.println("SerialRead initiated.");
                            data = "";
                            data = inputBuffer;
                            
                            System.out.println(data);
                            encodeCommand(inputBuffer);//call the method to encode the recieved command
                            inputBuffer="";//clear the buffer
                        }
                    }
                } catch (Exception e) {
                    System.err.println(e.toString());
                }
        }
 
        public static void main(String[] args) throws Exception {
            RXTX main = new RXTX();
            main.initialize();
            System.out.println("Started");
        }
    }

Powered by
✕