• 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 - Java Serial Communications Library.

Picture
Serial communication schematic using a microcontroller to interact with the computer. RS-232 protocol.
In order to get interaction between the contained world that is our application and the outside world that we want to control, for example in order for our application to control the movement and position of a motor, or in our case the turning on/off of a valve whenever there are leaks in the system.

From design, Java lacks support for this kind of interaction as the language was originally planned to work in a contained environment (the Java virtual machine) and have no contact with the outside world. Luckily, design limitations have never been a problem for programmers and several libraries that grant communication between the application running in the JVM (Java Virtual Machine) and the outside world have been developed.

Here, we'll deal with the RxTx library.

Serial Communication.

Serial communication is a peer-to-peer communication protocol, and one of the simplest and more widespread in actuality given the low costs of this type of communication and the ease of use. It makes use of the RS-232 protocol, which we won't deal with in this article, instead focusing on the programatically aspect of it, although for those looking for more information on this protocol, it can be seen in the Periphereal Programming course or the Industrial Networks one in the Mechatronics section.

The serial port consists of sending 0's and 1's through a copper wire from an emitter and interpreting them in a receiver. In our case the emitter can be either the computer or the microcontroller.

Installing the RxTx library.

1.-First of all, download the RxTx library from the official page, according to your Operative System.
http://rxtx.qbang.org/wiki/index.php/Download

In our case I downloaded the rxtx 2.1-7r2 (stable) file from the webpage and located it in a special directory I use for my libraries and applications called "My Applications".
2.-After that, we decompress the file and put it in a folder we don't plan to move. In my case, its in Desktop -> Files -> My Applications.
3.-We must move the serial files to the folder where our main Java files are located in the system. We must access the RxTx folder and copy-paste the files as follows:
c:\Program Files\Java\jdk1.6.0_01\

  • Copy rxtxParallel.dll to c:\Program Files\Java\jdk1.6.0_01\jre\bin\
  • Copy rxtxSerial.dll to c:\Program Files\Java\jdk1.6.0_01\jre\bin\
  • Copy RXTXcomm.jar to c:\Program Files\Java\jdk1.6.0_01\jre\lib\ext\

4.-Once that is finished, we must include the libraries in our NetBeans IDE. To do that, we go to Tools -> Ant Variables and add a New Library.
5.-The new library must be given a name, in our case we call it RxTx and leave it as a Java Class. We press OK.
6.-Afterwards, we press the Add JAR/Folder button and go to the location where we placed our RxTx folder, and select the RxTx-commons file. Press OK.
7.-Finally we add the library to the project by making right click in the libraries menu on the Project menu at the top left of the NetBeans application. We select the Add Library and we'll get a menu enumerating all libraries available in the system. We select the RxTx previously defined and make click in OK.
8.-Now to test the library we'll make use of an Arduino which is the preferred microcontroller platform to test prototypes. The Arduino has many special and powerful characteristics, but in this case, we will be using the serial port it directly provides to the computer along with the integrated led to test our application. To do so, load the following code in the Arduino:
ARDUINO CODE:


const int LED = 13; //LED connected to digital pin 13
int inByte = 0;
 
void setup(){
    Serial.begin(9600); //Open the serial port
    pinMode(LED, OUTPUT); //Set the digital pin as output
}
 
void loop(){
 
    if(Serial.available() > 0){
 
        inByte = Serial.read(); //read the incoming byte
 
        if(inByte == '1')
            digitalWrite(LED, HIGH); //turn the LED on
        else
            digitalWrite(LED, LOW); //turn the LED off
    }
}
JAVA CODE:


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
 
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
 
public class JPanelTurnOnOffLED extends JPanel
    implements ActionListener {
 
    private static final String ON = "On";
    private static final String OFF = "Off";
    private static final String TURN_ON = "1";
    private static final String TURN_OFF = "0";
 
    private JButton switchOnButton;
    private JButton switchOffButton;
    private JLabel label;
    private JFrame frame;
 
    /** The output stream to the port */
    private OutputStream output = null;
 
    SerialPort serialPort;
    private final String PORT_NAME = "/dev/cu.usbmodem1d11";
    /** 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;
 
    public JPanelTurnOnOffLED(){
        switchOnButton = new JButton(ON);
 
        switchOffButton = new JButton(OFF);
        switchOffButton.setEnabled(false);
 
        label = new JLabel("Turn On/Off LED:");
 
        switchOnButton.addActionListener(this);
        switchOffButton.addActionListener(this);
 
        add(label);
        add(switchOnButton);
        add(switchOffButton);
 
        initializeArduinoConnection();
    }
 
    public void initializeArduinoConnection(){
 
        CommPortIdentifier portId = null;
        Enumeration portEnum = CommPortIdentifier.
                                getPortIdentifiers();
 
        // iterate through, looking for the port
        while (portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId = (CommPortIdentifier)
                    portEnum.nextElement();
 
            if (PORT_NAME.equals(currPortId.getName())) {
                portId = currPortId;
                break;
            }
        }
 
        if (portId == null) {
            showError("Could not find COM port.");
            System.exit(ERROR);
            return;
        }
 
        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
            output = serialPort.getOutputStream();
 
        } catch (Exception e) {
            showError(e.getMessage());
            System.exit(ERROR);
        }
 
    }
 
    public static void createAndShowGUI(){
 
        JFrame frame = new JFrame("Turn On/Off LED example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        //Create and set up the content pane.
        JPanelTurnOnOffLED newContentPane = new JPanelTurnOnOffLED();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);
 
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
 
    public static void main(String args[]){
 
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
 
    }
 
    @Override
    public void actionPerformed(ActionEvent e) {
        if(ON.equals(e.getActionCommand())){
            switchOnButton.setEnabled(false);
            switchOffButton.setEnabled(true);
            sendData(TURN_ON);
 
        }else{
            switchOnButton.setEnabled(true);
            switchOffButton.setEnabled(false);
            sendData(TURN_OFF);
        }
 
    }
 
    private void sendData(String data){
 
        try {
            output.write(data.getBytes());
        } catch (IOException e) {
            showError("Error sending data");
            System.exit(ERROR);
        }
    }
 
    private void showError(String errorMessage){
        JOptionPane.showMessageDialog(frame,
                errorMessage,
                "Error",
                JOptionPane.ERROR_MESSAGE);
    }
 

}
If everything has worked well, you'll get the following menu which when pressed should turn on and off the LED contained in the Arduino.
Picture
SOURCES:

http://josedeveloper.com/2012/01/28/comunicacion-serial-java-y-arduino/

http://mdsaputra.wordpress.com/2012/01/24/java-com-programming-with-rxtx-in-windows-based-os/

Back
HOME
Next!
Powered by Create your own unique website with customizable templates.