RxtxSerial library multiple serial ports listener

Hello All,
I am using rxtxSerial library (import gnu.io.*; compatible with previousely available from Sun import javax.comm.*;) for my bridge application. Th example provided in the library's web site with nulltest.java employs only one serial port. It is powerful since it is threaded and detects incomming/outgoing streams.
However, I would like to bridge between servers so multiple ports will be employed. Do you heave any suggestion how to obtain multiple port handling (reading/writing) within the same class. The null test code is presented as follows. Simplest idea is to use arrays, but more details are required.
// derived from SUN's examples in the javax.comm package
import java.io.*;
import java.util.*;
//import javax.comm.*; // for SUN's serial/parallel port libraries
import gnu.io.*; // for rxtxSerial library
public class nulltest implements Runnable, SerialPortEventListener {
   static CommPortIdentifier portId;
   static CommPortIdentifier saveportId;
   static Enumeration        portList;
   InputStream           inputStream;
   SerialPort           serialPort;
   Thread           readThread;
   static String        messageString = "AT";
   static OutputStream      outputStream;
   static boolean        outputBufferEmptyFlag = false;
   public static void main(String[] args) {
      boolean           portFound = false;
      String           defaultPort;
      // determine the name of the serial port on several operating systems
      String osname = System.getProperty("os.name","").toLowerCase();
      if ( osname.startsWith("windows") ) {
         // windows
         defaultPort = "COM5";
      } else if (osname.startsWith("linux")) {
         // linux
        defaultPort = "/dev/ttyS0";
      } else if ( osname.startsWith("mac") ) {
         // mac
         defaultPort = "????";
      } else {
         System.out.println("Sorry, your operating system is not supported");
         return;
      if (args.length > 0) {
         defaultPort = args[0];
      System.out.println("Set default port to "+defaultPort);
          // parse ports and if the default port is found, initialized the reader
      portList = CommPortIdentifier.getPortIdentifiers();
      while (portList.hasMoreElements()) {
         portId = (CommPortIdentifier) portList.nextElement();
         if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            if (portId.getName().equals(defaultPort)) {
               System.out.println("Found port: "+defaultPort);
               portFound = true;
               // init reader thread
               nulltest reader = new nulltest();
      if (!portFound) {
         System.out.println("port " + defaultPort + " not found.");
   public void initwritetoport() {
      // initwritetoport() assumes that the port has already been opened and
      //    initialized by "public nulltest()"
      try {
         // get the outputstream
         outputStream = serialPort.getOutputStream();
      } catch (IOException e) {}
      try {
         // activate the OUTPUT_BUFFER_EMPTY notifier
         serialPort.notifyOnOutputEmpty(true);
      } catch (Exception e) {
         System.out.println("Error setting event notification");
         System.out.println(e.toString());
         System.exit(-1);
   public void writetoport() {
      System.out.println("Writing \""+messageString+"\" to "+serialPort.getName());
      try {
         // write string to serial port
         outputStream.write(messageString.getBytes());
      } catch (IOException e) {}
   public nulltest() {
      // initalize serial port
      try {
         serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
      } catch (PortInUseException e) {}
      try {
         inputStream = serialPort.getInputStream();
      } catch (IOException e) {}
      try {
         serialPort.addEventListener(this);
      } catch (TooManyListenersException e) {}
      // activate the DATA_AVAILABLE notifier
      serialPort.notifyOnDataAvailable(true);
      try {
         // set port parameters
         serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
                     SerialPort.STOPBITS_1,
                     SerialPort.PARITY_NONE);
      } catch (UnsupportedCommOperationException e) {}
      // start the read thread
      readThread = new Thread(this);
      readThread.start();
   public void run() {
      // first thing in the thread, we initialize the write operation
      initwritetoport();
      try {
         while (true) {
            // write string to port, the serialEvent will read it
            writetoport();
            Thread.sleep(1000);
      } catch (InterruptedException e) {}
   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:
         // we get here if data has been received
         byte[] readBuffer = new byte[20];
               int numBytes = 0;
         try {
            // read data
            while (inputStream.available() > 0) {
               numBytes = inputStream.read(readBuffer);
            // print data
            String result  = new String(readBuffer);
            System.out.println("Bytes read: "+numBytes+", Read contents: "+result);
         } catch (IOException e) {}
         break;
}Kujtim
Edited by: Kujtim on Jul 12, 2009 1:41 PM
Edited by: Kujtim on Jul 12, 2009 1:43 PM
Edited by: Kujtim on Jul 13, 2009 1:57 PM

As an off the wall suggestion, check the usb "power save settings" under "control Panelower Options:Edit Plan Settings:Advanced Settings:USB settings" You want the USB selective suspend setting to be Disabled. Another possible idagnostic tool might be to do  a    Power Efficiency Diagnostics Report  which we have found has occasionally pointed us to usb hanging issues. 
Using the same type usb-serial adapters doesn't guarantee anything, but I have run into issues where a vendor's driver was implemented incorrectly. It ended up being a wrapper around the FTDI driver, and the wrapper dll wasn't correctly made multi-threaded safe. I browbeat the vendor (I was working at a LARGE corporation, with a prospective LARGE purchase of the devices) into telling me what calls their wrapper made. I then used the FTDI dll directly, not using the "simplified interface" of the vendor's dll. FTDI's dll was thread safe, no more random lockups/BSOD.
Good Luck, these are incredibly painful!
Putnam
Certified LabVIEW Developer
Senior Test Engineer
Currently using LV 6.1-LabVIEW 2012, RT8.5
LabVIEW Champion

Similar Messages

  • Multiple serial port initialisation problem

    Good Morning All
    I have attached a vi which is giving me a problem that I can't solve, and would appreciate any help.
    The vi is supposed to intialise up to 7 serial ports (only using 5 at the moment), and I'm assuming this is a plausible way to do the initialisation (could be wrong). The serial ports are connected to a pc via a usb hub. The windows XP o/s does recognise the ports according to the device manager.
    The problem is that when the vi is run the following error is reported as shown in the attached word document.
    I have compared the port settings in the device manager properties for each port to the vi settings and they match. What more can I do?
    If somebody has a setup with mutliple serial ports could they try the vi and see if it works for them?
    Thanks and best regards
    Ray
    Solved!
    Go to Solution.
    Attachments:
    ax500 serial port init.vi ‏37 KB
    init error.docx ‏518 KB

    It has nothing to do with multiple serial ports.  It has to do with an invalid setting you are trying to use to configure any one of the serial ports.
    Look at the information in the error message.  Argument 4 of the property node in Configure Serial Port VI is the Stop Bits setting.  I see a coercion dot going into that VI, so that tells me the datatype you are wiring in doesn't quite match.
    You have an array of I32 values, and your values consist of 1's.  Disconnect that array and right click on the terminal of Configure Serial Port VI and pick Create Constant.  You'll see you get a ring data type.  It is a U16.  But if you look at the items in there, you'll see that stop bits 1.0 has a value of 10.  1.5 has a value of 15, 2.0 has a value of 20.  So the value of 1 has no meaning to that property node and you get an error.  You should be wiring in a value of 10.
    Delete that array.  Create an array of the ring constants.  Turn it into a control, and choose the correct ring value for each element of your array.
    You have several other coercion dots.  They may not be causing you problems, but I would consider disconnecting them, creating a constant of the correct datatype, and using that in the array you wire to the Configure subVI.
    I modified your VI and attached it.  See if it works for you.
    Attachments:
    ax500SerialPortInitMOD.vi ‏37 KB

  • Multiple serial ports reading from a shared USB port

    I have a program that reads from 4 flow controllers, which send data through RS232 serial ports. Because the computer is located pretty far away, the vendor suggested to use an Edgeport box to convert RS232 to USB, then convert to ethernet port using a SuperBooster converter. The signal travels long distance in ethernet cable to the computer and get converted back to USB, then to the computer. In MAX, I was able to see 8 com ports from the Edgeport box, and I was able to communicate with my flow controllers.
    The problem is, it will give me some error message occasionally. Sometime it's a VISA Read error, sometime it's a VISA framing error. Could this be caused by the way the signal is transmitted?
    In the program I have four parallel WHILE loops that constantly do READ and WRITE to the 4 flow controllers. Could this be causing the errors? If so, what is the best strategy to design this program?
    Thanks

    I agree with Mike, you will need an error handling strategy that accounts for these errors.  And retries the communications.  This can be a little tricky, but very doable.  I believe some sort of statemachine approach will work best for this. 
    As for your heated probe.  I would make some sort of hardware interlock that will shut it down in case of a coolant failure.  NEVER, EVER trust the computer to be running where safety is concerned, either for personal or hardware.  There are plenty of ICs that can monitor temperature, and have warning, and alarm outputs!  Another option is some sort of watchdog on the communications bus for the coolant control, but I think this is a bit more tricky. 
    Paul <--Always Learning!!!
    sense and simplicity.
    Browse my sample VIs?

  • Multiple serial ports streaming - BSOD/freezes - Hardware or Software problem?

    Hello all,
    I just joined the forums as I'm in dire need of some help with LV. I'm trying to hook up three lasers for an experiment. These are connected to my laptop via seperate RS232 cables with an adapter each to a COM port. I found an LV example that reads in one laser from the manufacturers site (something with .dll files and a C++ library). I'm a beginner with LV and I can't really say I have experience, especially not with custom libraries, so I just tried to make it work somehow. So what I did was basically copy it three times and reconnected some wires and changed the output format. I've added my program to this post; warning, you might get slightly sick by looking at it.
    Anyway, my main problem is; it works, but only for a limited time. After some time the VI will crash or my laptop will BSOD. Now, since my VI isn't very professional and probably has a very bad structure I'm not sure whether this is a problem with the VI or with the RS232 adapters/USB hub. I read some things on faulty RS232 adapters that conflict, but I can also imagine my VI can't deal with three data streams correctly, so I'm not sure where this is coming from.
    I was hoping that if any of you would take a glance at my VI, you could tell me whether it's my VI or not. I'd rather confirm this before I buy three new RS232 adapters.
    P.S. I'm running this on LV 2011 and LV 8.2.1 (my laptop with 2011 only recognises 2 COM ports simultaenously and my other laptop with 8.2.1 all three, but my laptop with 2011 can handle the crashes better)
    Thanks!
    Attachments:
    lv_RF603_Measure_3L_FORCE6.vi ‏120 KB
    library.7z ‏12 KB

    As an off the wall suggestion, check the usb "power save settings" under "control Panelower Options:Edit Plan Settings:Advanced Settings:USB settings" You want the USB selective suspend setting to be Disabled. Another possible idagnostic tool might be to do  a    Power Efficiency Diagnostics Report  which we have found has occasionally pointed us to usb hanging issues. 
    Using the same type usb-serial adapters doesn't guarantee anything, but I have run into issues where a vendor's driver was implemented incorrectly. It ended up being a wrapper around the FTDI driver, and the wrapper dll wasn't correctly made multi-threaded safe. I browbeat the vendor (I was working at a LARGE corporation, with a prospective LARGE purchase of the devices) into telling me what calls their wrapper made. I then used the FTDI dll directly, not using the "simplified interface" of the vendor's dll. FTDI's dll was thread safe, no more random lockups/BSOD.
    Good Luck, these are incredibly painful!
    Putnam
    Certified LabVIEW Developer
    Senior Test Engineer
    Currently using LV 6.1-LabVIEW 2012, RT8.5
    LabVIEW Champion

  • URGENT: Capturing data through serial port

    Hi,
    My problem is with the use of javax.comm API. I have an RFID tag reader connected to
    the serial port. It is a handheld reader and reads tags when its trigger is pulled. The
    data that is read is sent to the serial port. This is what I want to capture.
    I tried to test the reading operation by running the SimpleRead sample. What I see is
    that I pull the trigger once to read 1 tag, but that generates 3 DATA_AVAILABLE events.
    The tag ID that is read is 16 bytes, preceded by a 3 byte AIM Identifier (that declares
    the following data was read from an RFID tag, and not a barcode which has different
    AIM Identifiers for the different symbologies - but I digress.) By inserting some println's,
    I was able to see that the 19 bytes of data are read 8 bytes at a time. The first 8 bytes
    are read on the first DATA_AVAILABLE event, the next 8 are read on the second event
    and the last 3 bytes are read on the 3rd DATA_AVAILABLE event.
    This is strange & not good for me. How can my application know that the data read in
    these 3 separate DATA_AVAILABLE events is to be concatenated to form a single
    tag ID? Why is the single trigger-pull & tag read operation broken up into chunks of
    8 bytes? Is there some configuration setting that will give me the behavior I want?
    (I cannot rely on the length of the tag ID being 16 bytes always, because the same
    reader will also be reading barcodes where the data may have varying length)
    Thanks for any help. This is really urgent.
    - Ajoy

    please use the [ code ]and [code ] tags for code.
    I don't think you have a problem with the code, it's more like understanding how to make it work.
    to make the read method return.You do not have a read() method.
    The code is behaving as it should.
    You need to use the SimpleRead class as a thread, add and remove the Serial port listener as needed.
    You read all data available, then send it to a method to parse the buffer.
    You can count how much data was read so you know how much to parse.
    I never used receive threshhold.
    Here is example (sample)of my serial port reader
    //SerialIO
       public void serialEvent(SerialPortEvent event) {
            switch(event.getEventType()) {
                  case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                break;
            case SerialPortEvent.DATA_AVAILABLE:
                this.dataManager.readData();
    //DataManager
    public void readData() {
         String str;
         int     bytes = 0;
         long endTime, now;
         try {
              while (this.owner.isComPortOpen
                   && (SerialIO.inStream.available() > 0)) {
                   bytes = SerilIO.inStream.read(this.buffer);
                   if (bytes > 0) {
                   if (bytes > this.buffer.length) {
                        System.out.println( ": Input buffer overflow!");
         **Here is where you parse your buffer
                   sendDataToParser(bytes, buffer);
              } catch (IOException ex) {
                   System.out.println( ": Cannot read input stream");
          * Stops the serialEvent listener
         protected void stopSerialEvent() {
              SerialIO.serialPort.removeEventListener();
              try {
                   Thread.sleep(2000);
                   flushInputStream();
              } catch (InterruptedException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
          * Starts the Serial event listener
         protected void startSerialEvent() {
              // TODO Auto-generated method stub
              try {
                   SerialIO.serialPort.addEventListener(SerialIO);
              } catch (TooManyListenersException e) {
                   // TODO Auto-generated catch block
                   //System.out.println("startSerialEvent in dataManager");
                   e.printStackTrace();

  • Second serial port for CompactRIO

    I would like to reiterate the question posted here.
    Is it possible to add a second serial port to a CompactRIO chassis?
    Using the FPGA seems like it would not actually be transmitting at RS-232 levels, and using an Ethernet-to-Serial Port converter sounds more promising, but that means having the drivers loaded properly.  Are these the only options, and are they even feasible?  Having a multi serial port module seems like it would be a nice addition to the CompactRIO suite.

    Hi m3nth,
    The link involving using the FPGA and digital modules has been successful in the past with many people and like the tutorial says, a big part with this is converting to voltage using a voltage translator.  With respect to the ENET option, the link below can be used to direct you to the products that we have that you may want to try to implement multiple serial ports.  I've done some research and it appears that there shouldn't be an issue using the converters with a real-time system.  When using the ENET converters, keep in mind that it may cause some more latency in your network as opposed to regular serial transmission.  If you have any more questions, please let me know.  Thanks!
    http://sine.ni.com/nips/cds/view/p/lang/en/nid/10043
    Regards
    Noah R
    Applications Engineering
    National Instruments

  • Listen to serial port open by another applicatio​n

    I have a test setup where another application is communicating with a device over a serial port and I want my Labview gui to be able to listen to the communication. Since two applications cannot have the same serial port open I can't just open the port and do a visa read. Is there any way to do an unreserved open and only listen to communication on the serial port or do I physically have to break out the receive line in hardware and add a second serial port in order to do this?

    A better solution would be to have your reader post a message to a queue with the data. You can have a separate task that handles the UI updates. Depending on the type and amount of data you may not need to post all of the data.
    The answer to your specific question though is no, you cannot have two readers on the same connection.
    Mark Yedinak
    "Does anyone know where the love of God goes when the waves turn the minutes to hours?"
    Wreck of the Edmund Fitzgerald - Gordon Lightfoot

  • Getting error in call library node when establishing communication with MAX1452 on serial port using dll

    I want to communicate with MAX1452 in labview on PC serial port. Maxim provides dll file which has functions to communicate with device.It says first two functions should be findcom port and initialization sequence where findcom port returns PC's serial port address while initialization sequence helps device to learn baud rate.Iam not getting exception error in call library node.i have kept dll file in the same location as VI.

    Labview verison is 7.1 and os is win xp.
    The data types are according to the dll functions defined in functions definitions( attached previously).
    I'd put dll in the same directory where the code resides.
    Attachments:
    Code.vi ‏23 KB

  • To send multiple operation commands to serial port

    My AC power source is able to communicate to PC via serial port using LABView and I can perform any operation by giving commands in Hex individually, But when it comes to the parallel operation of all the commands or to put them in a particular sequence. I am failing to do so.

    You can only send 1 command at a time.  That is just bus communications 101.  But you can string together many VISA Writes to send the individual commands, one after the other.
    But since if sounds like you are doing this on a GUI based instance, what you want to do is configure the port before your loop and close the port after the loop.  Then inside your loop you just have an Event Structure to key off of the different controls changing values.  You just send the command you need to inside of each event case.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions

  • Send DAQ measurement results through serial ports

    Hi, All
    I use PCI-6034E for measurement. After DAQ gets data, I send them to another computer through serial port (com1). I write a Virtual C++ program, which calls NI-DAQ library functions to implement DAQ data sampling (multiple channel scan) and sends measurement data to another computer through serial port under request. DAQ data sampling and serial communication are implemented in two threads. They are running concurrently. They share a global memory for measurement data. The serial communication thread will do infinite wait and send data only when another computer sends a request through serial port.
    I met two problems. First, when I reduce the size of DAQ measurement buffers (piBuffer and halfpiBuffer, I us
    edouble buffer model), DAQ measurement is often interrupted by the message "[DAQ_DB_HalfReady] returned NI-DAQ warning 10846. Your application was unable to retrive data from the background acquisition buffer fast enough so the unretrieved data was overwritten with new data. ...". I want to get run time data so I need to reduce the buffers as small as possible. How can I solve it ? The second problem is that the serial port gets error data (nothing) from measurement computer sometimes, especially when DAQ initializes itself and finishes work. It looks like that there is a conflict between DAQ and serial port. Does anyone have similar experience about this? Any suggestion?
    Thank you in advance.
    Le Cai

    Le Cai,
    You are correct that the number of scans to read is equal to half of the buffer in double buffer mode. I was mistaken and referring to a standard (non double buffered) operation. However, you can increase the size of your buffer without affecting the period of your acquisition. A buffer of 60 is quite small and, as such, will be more prone to overflow errors. The rate is actually set through the DAQ_Rate() and DAQ_Start() functions. For more information on these functions and how to configure the scan rate, please see the NI-DAQ Function Reference Manual.
    NI-DAQ Function Reference Manual for PC Compatibles
    http://digital.ni.com/manuals.nsf/websearch/1630A0B68738B269862567C1007A2912?OpenDocument&node=132100_US
    A good place to start would be the example titled, "DAQdoubleBuf.c" which ships with the NI-DAQ driver. If you installed the examples for Visual C++ when you installed the NI-DAQ driver you should be able to find this example in the \Program Files\National Instruments\NI-DAQ\Examples\VisualC\AI folder on your computer. This example would be a good template as it is very close to what you are trying to do.
    If you observe that you only receive the overflow error when you are operating the two threads, thus ruling out the buffer size as being a potential problem, you may want to examine whether or not your second thread is placing a lengthy exclusion on your data buffer during the period when your first thread is trying to move the data. If your first thread has to wait during the half-buffer transfer this could easily cause the overflow, as the acquisition would be running but the transfer would be paused. Instead of placing a mutual exclusion around one piece of global memory you could try using a queue instead. A queue approach will allow you to pass the data from the first thread into a queue to be read, when convenient, by the second thread. In this method the first thread would never have to wait as the transfer would just be a handoff.
    Regards,
    Justin Britten
    Applications Engineer
    National Instruments

  • Two module I/O servers. one serial port

    is this possible? it's logical that you'd wan't to put multiple device on one serial network, in order to not have add extra ports to you controlller. I can't seem to find the answer. I ould think that the API handles sharing of the port behind the scenes, but who knows. Can I save myself some work and use the I/O server, or am I going to have to do this the old-fashioned way and use the modbus library?
    Solved!
    Go to Solution.

    As long as you are using a 485 port you should be able to communicate with multiple devices using Modbus over Serial.  It does look a bit strange because you need to have a different I/O server for each slave device but you can set them to all use the same serial port.
    Matt J
    Professional Googler and Kudo Addict
    National Instruments

  • Problem communicating via serial port in Linux

    Hello,
    I am trying to transfer data via serial port, in Linux.
    But it is impossible till now!
    I get Runtime exception.
    Here is my code:
    public class Main {
        public Main() {
        int num=5;
        int[] array = new int[5];
        public static void main(String args[])  {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    array[0]=1;
                    array[1]=2;
                    array[2]=3;
                    array[3]=4;
                    array[4]=5;
                    new ParallelCommunication(num,array);
    import java.io.*;
    import java.util.*;
    import javax.comm.*; // for SUN's serial/parallel port libraries
    //import gnu.io.*; // for rxtxSerial library
    public class ParallelCommunication implements Runnable, SerialPortEventListener {
       static CommPortIdentifier portId;
       static CommPortIdentifier saveportId;
       static Enumeration portList;
       InputStream inputStream;
       SerialPort serialPort;
       Thread readThread;
       static OutputStream outputStream;
       static boolean outputBufferEmptyFlag = false;
       int num;
       int[] array;
       public ParallelCommunication(int this_num,int[] this_array) {
          boolean portFound = false;
          String defaultPort;
          num = this_num;
         array=new int[this_array.length];     
          array = this_array;     
          // determine the name of the serial port on several operating systems
          String osname = System.getProperty("os.name","").toLowerCase();
          if ( osname.startsWith("windows") ) {
             // windows
             defaultPort = "COM1";
          } else if (osname.startsWith("linux")) {
             // linux
            defaultPort = "/dev/ttyS0";
          } else {
             System.out.println("Sorry, your operating system is not supported");
             return;
    //      if (args.length > 0) {
    //         defaultPort = args[0];
          System.out.println("Set default port to "+defaultPort);
          // parse ports and if the default port is found, initialized the reader
          portList = CommPortIdentifier.getPortIdentifiers();
          while (portList.hasMoreElements()) {
             portId = (CommPortIdentifier) portList.nextElement();
             if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                if (portId.getName().equals(defaultPort)) {
                   System.out.println("Found port: "+defaultPort);
                   portFound = true;
                   // init reader thread              
                   initialize();
                   break;
          if (!portFound) {
             System.out.println("port " + defaultPort + " not found.");
       public void initwritetoport() {
          // initwritetoport() assumes that the port has already been opened and
          //    initialized by "public void initialize()"
          try {
             // get the outputstream
             outputStream = serialPort.getOutputStream();
          } catch (IOException e) {}
          try {
             // activate the OUTPUT_BUFFER_EMPTY notifier
             serialPort.notifyOnOutputEmpty(true);
          } catch (Exception e) {
             System.out.println("Error setting event notification");
             System.out.println(e.toString());
             System.exit(-1);
       public void writetoport(int counter) {
          try {
             // write string to serial port
             outputStream.write(String.valueOf(array[counter]).getBytes());
          } catch (IOException e) {}
       public void initialize() {
          // initalize serial port
          try {
             serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
          } catch (PortInUseException e) {System.out.println("Port In Use.");}  //******Here is the Exception******
          try {
             inputStream = serialPort.getInputStream();
          } catch (IOException e) {}
          try {
             serialPort.addEventListener(this);
          } catch (TooManyListenersException e) {}
          // activate the DATA_AVAILABLE notifier
          serialPort.notifyOnDataAvailable(true);
          try {
             // set port parameters
             serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
                         SerialPort.STOPBITS_1,
                         SerialPort.PARITY_NONE);
          } catch (UnsupportedCommOperationException e) {}
          // start the read thread
          readThread = new Thread(this);
          readThread.start();
       public void run() {
          // first thing in the thread, we initialize the write operation
         initwritetoport();     
         for(int i=0; i<=num_of_inputs; i++) {
            // write string to port, the serialEvent will read it
            writetoport(i);
         serialPort.close();     
       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:
             // we get here if data has been received
             byte[] readBuffer = new byte[20];
             try {
                // read data
                while (inputStream.available() > 0) {
                   int numBytes = inputStream.read(readBuffer);
                // print data
                String result  = new String(readBuffer);
                System.out.println("Read: "+result);
             } catch (IOException e) {}
             break;
    }...and the outcome is :
    Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException:
    Error opening "/dev/ttyS0"
    tcgetattr(): Input/output error
    at com.sun.comm.LinuxDriver.getCommPort(LinuxDriver.java:66)
    at javax.comm.CommPortIdentifier.open(CommPortIdentifier.java:369)
    at ParallelCommunication.initialize(ParallelCommunication.java:128)
    I have searched a lot and I couldn't find a solution.
    Thank you.

    I'm having the same problem this helped somewhat debug the problem
    http://bloggerdigest.blogspot.com/2006/11/linux-serial-com-port-diagnostic-test.html
    I'm running Suse 10.3 and apparently it does not recognize my serial ports. So before
    you can test your Java code you have to figure out how to make linux see the ports.
    If I find a solution I'll let you know but if you find one first let me know. Thanks.

  • How to get data from serial port to GUI textArea

    From Serial Port.....
    Messages from base (always 5 bytes):
    0xAA, 0, 0, 0, 0xBB - IDLE Mode
    0xAA, 0, 0x80, 0x80, 0xBB - Question Mode
    messages from terminal (always 6 bytes):
    0xAA, a, b, c, chksum, 0xBB
    where chksum = a+b+c;
    a = address (0-250)
    the 2 MSB's of b represenet the answer:
    0 0 - A
    0 1 - B
    1 0 - C
    1 1 - D
    the 6LSB's of b and 8bits of c is the time for answer, in milliseconds.
    (0-16384 milliseconds)
    I have VB Code for that but I want the same thing in Java ...
    Can any one help me?
    Here's VB Code..
    VERSION 5.00
    Object = "{648A5603-2C6E-101B-82B6-000000000014}#1.1#0"; "MSCOMM32.OCX"
    Begin VB.Form Form1
       BorderStyle     =   1  'Fixed Single
       Caption         =   "Aakar GUI"
       ClientHeight    =   4665
       ClientLeft      =   60
       ClientTop       =   375
       ClientWidth     =   6105
       LinkTopic       =   "Form1"
       MaxButton       =   0   'False
       MinButton       =   0   'False
       ScaleHeight     =   311
       ScaleMode       =   3  'Pixel
       ScaleWidth      =   407
       StartUpPosition =   3  'Windows Default
       Begin VB.CommandButton cmdPort
          Caption         =   "Open Port"
          Height          =   375
          Left            =   120
          TabIndex        =   4
          Top             =   600
          Width           =   1455
       End
       Begin VB.ComboBox cmbPort
          Height          =   315
          ItemData        =   "Form1.frx":0000
          Left            =   120
          List            =   "Form1.frx":0016
          Style           =   2  'Dropdown List
          TabIndex        =   3
          Top             =   120
          Width           =   2895
       End
       Begin VB.CommandButton cmdEnd
          Caption         =   "End"
          Height          =   495
          Left            =   1560
          TabIndex        =   2
          Top             =   1320
          Width           =   1215
       End
       Begin VB.CommandButton cmdStart
          Caption         =   "Start"
          Height          =   495
          Left            =   120
          TabIndex        =   1
          Top             =   1320
          Width           =   1215
       End
       Begin VB.TextBox txtMessage
          Height          =   2040
          Left            =   119
          MultiLine       =   -1  'True
          ScrollBars      =   3  'Both
          TabIndex        =   0
          Top             =   2475
          Width           =   5848
       End
       Begin VB.Timer tmrRead
          Enabled         =   0   'False
          Interval        =   1
          Left            =   2040
          Top             =   600
       End
       Begin MSCommLib.MSComm MSComm1
          Left            =   3120
          Top             =   360
          _ExtentX        =   1164
          _ExtentY        =   1164
          _Version        =   393216
          DTREnable       =   0   'False
          ParityReplace   =   45
          SThreshold      =   1
       End
       Begin VB.Label Label5
          Caption         =   "Result Data:"
          Height          =   375
          Left            =   120
          TabIndex        =   5
          Top             =   2115
          Width           =   1320
       End
    End
    Attribute VB_Name = "Form1"
    Attribute VB_GlobalNameSpace = False
    Attribute VB_Creatable = False
    Attribute VB_PredeclaredId = True
    Attribute VB_Exposed = False
    Option Explicit
    Dim PortIsOpen As Boolean
    Dim Answers(4) As String
    Dim RejectKeystroke As Boolean
    Private Sub cmbPort_Change()
    Debug.Print cmbPort.ListIndex
    End Sub
    Private Sub cmbPort_Validate(Cancel As Boolean)
    'Cancel = True
    End Sub
    Private Sub cmdEnd_Click()
    MSComm1.Output = "e"
    txtMessage.Text = ""
    End Sub
    Private Sub cmdPort_Click()
    On Error GoTo ErrorHandler
    If cmbPort.ListIndex < 0 Then Exit Sub
    If PortIsOpen Then
        cmbPort.Enabled = True
        MSComm1.PortOpen = False
        PortIsOpen = False
        cmdPort.Caption = "Open Port"
        cmdStart.Enabled = False
        cmdEnd.Enabled = False
    Else
        MSComm1.CommPort = cmbPort.ListIndex + 1
        cmbPort.Enabled = False
        MSComm1.PortOpen = True
        PortIsOpen = True
        cmdPort.Caption = "Close Port"
        cmdStart.Enabled = True
        cmdEnd.Enabled = True
    End If
    Exit Sub
    ErrorHandler:
    Debug.Print Err.Number
    Debug.Print Err.Description
    MsgBox Err.Description, vbExclamation Or vbOKOnly, "Error opening port"
    cmbPort.Enabled = True
    PortIsOpen = False
    cmdPort.Caption = "Open Port"
    cmdStart.Enabled = False
    cmdEnd.Enabled = False
    End Sub
    Private Sub cmdStart_Click()
    MSComm1.Output = "s"
    txtMessage.Text = ""
    End Sub
    Private Sub Form_Initialize()
    Dim tmp As Variant
    tmp = InitCommonControls
    End Sub
    Private Sub Form_Load()
    Answers(0) = "A"
    Answers(1) = "B"
    Answers(2) = "C"
    Answers(3) = "D"
    'MSComm1.Settings = "9600,n,8,1"
    ''MSComm1.Settings = "115200,n,8,1"
    'MSComm1.PortOpen = True
    On Error GoTo ErrorHandler1
    MSComm1.CommPort = 1                    ' comm port 1
    MSComm1.RThreshold = 1                  ' use 'on comm' event processing
    MSComm1.Settings = "9600,n,8,1"         ' baud, parity, data bits, stop bits
    MSComm1.SThreshold = 1                  ' allows us to track Tx LED
    MSComm1.InputMode = comInputModeText    'comInputModeBinary  ' binary mode, you can also use
                                            ' comInputModeText for text only use
    PortIsOpen = False
    cmbPort.ListIndex = 0
    ' open the port
    MSComm1.PortOpen = True
    cmbPort.Enabled = False
    PortIsOpen = True
    cmdPort.Caption = "Close Port"
    cmdStart.Enabled = True
    cmdEnd.Enabled = True
    Exit Sub
    ErrorHandler1:
    Debug.Print Err.Description
    PortIsOpen = False
    cmbPort.Enabled = True
    cmdPort.Caption = "Open Port"
    cmdStart.Enabled = False
    cmdEnd.Enabled = False
    End Sub
    Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
    If MSComm1.PortOpen Then MSComm1.PortOpen = False
    End Sub
    Private Sub lblOption_Click()
    End Sub
    Private Sub MSComm1_OnComm()
    ' Synopsis:     Handle incoming characters, 'On Comm' Event
    ' Description:  By setting MSComm1.RThreshold = 1, this event will fire for
    '               each character that arrives in the comm controls input buffer.
    '               Set MSComm1.RThreshold = 0 if you want to poll the control
    '               yourself, either via a TImer or within program execution loop.
    '               In most cases, OnComm Event processing shown here is the prefered
    '               method of processing incoming characters.
        Dim i As Long
        Dim sBuff    As String           ' buffer for holding incoming characters
        Const MTC       As String = vbCrLf  ' message terminator characters (ususally vbCrLf)
        Const LenMTC    As Long = 2         ' number of terminator characters, must match MTC
        Dim iPtr        As Long             ' pointer to terminatior character
        ' OnComm fires for multiple Events
        ' so get the Event ID & process
        Select Case MSComm1.CommEvent
            ' Received RThreshold # of chars, in our case 1.
            Case comEvReceive
                ' read all of the characters from the input buffer
                ' StrConv() is required when using MSComm in binary mode,
                ' if you set MSComm1.InputMode = comInputModeText, it's not required
                'sBuff = sBuff & StrConv(MSComm1.Input, vbUnicode)
                'If Len(txtMessage.Text) > 4096 Then txtMessage.Text = ""
                sBuff = MSComm1.Input
                Dim ch As String
                Dim PacketStart As Boolean
                Dim PacketLength As Integer
                Dim Packet() As String
                PacketStart = False
                PacketLength = 0
                While (Len(sBuff) > 0)
                    ch = Left(sBuff, 1)
                    If (ch = Chr(&HAA)) Then PacketStart = True
                    If (ch = Chr(&HBB)) Then PacketStart = False
                    If (ch <> Chr(&HAA) And ch <> Chr(&HBB)) Then
                        PacketLength = PacketLength + 1
                        ReDim Preserve Packet(PacketLength)
                        Packet(PacketLength) = ch
                    End If
                    'txtMessage.Text = txtMessage.Text + Format(Hex(Asc(ch)), " @@")
                    sBuff = Right(sBuff, Len(sBuff) - 1)
                Wend
                If (PacketLength = 3) Then
                    Debug.Print "Command packet recieved"
                    'txtMessage.Text = txtMessage.Text + vbCrLf + "Address =" + Str(Asc(Packet(1)))
                    'txtMessage.Text = txtMessage.Text + vbCrLf + "Address =" + Str(Asc(Packet(2)))
                End If
                If (PacketLength = 4) Then
                    Debug.Print "Response packet recieved"
                    txtMessage.Text = txtMessage.Text + "Address =" + Str(Asc(Packet(1))) + _
                        " Answer = " + Answers((Asc(Packet(2)) And &HC0) / 64) + _
                        " Time =" + Str((Asc(Packet(2)) And &H3F) * 256 + (Asc(Packet(3)))) + "mS" + vbCrLf
                    'txtMessage.Text = txtMessage.Text + vbCrLf + "Address =" + Str(Asc(Packet(1)))
                    'txtMessage.Text = txtMessage.Text + vbCrLf + "Option =" + Str((Asc(Packet(2)) And &HC0) / 64)
                    'txtMessage.Text = txtMessage.Text + vbCrLf + "Time =" + Str((Asc(Packet(2)) And &H3F) * 256 + (Asc(Packet(3))))
                End If
                If (PacketLength <> 4 And PacketLength <> 3) Then Debug.Print "Unknown packet of length" + Str(PacketLength) + " recieved"
                txtMessage.Text = txtMessage.Text + vbCrLf
            ' An EOF charater was found in the input stream
            Case comEvEOF
                DoEvents
            ' There are SThreshold number of characters in the transmit  buffer.
            Case comEvSend
                DoEvents
            ' A Break was received.
            Case comEventBreak
                DoEvents
            ' Framing Error
            Case comEventFrame
                DoEvents
            ' Data Lost.
            Case comEventOverrun
                DoEvents
            ' Receive buffer overflow.
            Case comEventRxOver
                DoEvents
            ' Parity Error.
            Case comEventRxParity
                DoEvents
            ' Transmit buffer full.
            Case comEventTxFull
            ' Unexpected error retrieving DCB]
            Case comEventDCB
                DoEvents
        End Select
    End Sub
    Private Sub tmrRead_Timer()
    'MSComm1.Output = vbCrLf + vbCrLf
    'MSComm1.Output = Chr(128)
    End Sub
    Private Sub txtMessage_KeyDown(KeyCode As Integer, Shift As Integer)
    If Shift = 2 Or Shift = 4 Then RejectKeystroke = False Else RejectKeystroke = True
    End Sub
    Private Sub txtMessage_KeyPress(KeyAscii As Integer)
    If RejectKeystroke Then
        KeyAscii = 0
    End If
    End SubThanks in advance..

    I want to replicate the entire VB program as Java Program.
    This has to be included in my project which i am doing in java.

  • How to configure multiple listeners to listen for the same instance.

    Hello everyone,
    I am running oracle database 11g and I want information regarding how to configure multiple listeners to listen for the same database instance. Actually I know how to configure more than one listener but the main thing that I am confused about is when we create listener.ora file, do we have to statically register the database instance with both the listeners or the instance will register itself with both the listeners.
    According to my knowledge the instance will register with the listener specified by LOCAL_LISTENER parameter and we cannot have more than one value for this parameter.
    Please only give detailed answers with example as I am tired of simple answers with details that I already know.

    Hello,
    Yes, it can make sense to have several listener for one Oracle instance. For instance you may have one listener for the applications another listener for DBA administration tasks as well as one listener dedicated to dataguard broker. It is not possible to have several listeners listening on the same IP and Port.
    By default the database try to automatically register to a listener on port 1521. To instruct the instance to register to a specifc list of listeners you can add in the init.ora the local_listener parameter with an alias definition:
    i.e
    local_listener=MY_SET_OFF_LISTENERS
    in your tnsname.ora add an entry called:
    MY_SET_OFF_LISTENERS_LOCAL= (ADDRESS_LIST=
    (ADRESS=(PROTOCOL=TCP)(HOST=myhostname)(PORT=1530))
    (ADRESS=(PROTOCOL=TCP)(HOST=myhostname)(PORT=1531))
    (ADRESS=(PROTOCOL=TCP)(HOST=myhostname)(PORT=1532))
    In this sample your instance will register to three listeners listening on respectively port 1530, 1531 and 1532
    If you want your clients can be balanced over the 3 listeners

  • How to get a signal from the serial port to start a labview program?

    I need to synchronize the data obtained from a program (which is not in Labview)with the data collected with Labview on a different computer. I can send some data strings to the serial port of the computer running the Labview program when the other program starts. However, I need to be able to read the trigger in my Labview program. Do you know what I should do? Thanks.

    If you don't have any other programs listening on the COM port, you need to let a LV program run BEFORE the signal comes, otherwise you won't be able to read it. You can have the program wait in a slow timed loop so that it doesn't use up too much CPU time, and when the required "trigger" comes, to move into the main part of the program.
    You basically need a while loop waiting for a certain string in the serial buffer. Once the string is found the while loop is exited, and the data acqquisition or whatever else you require from the progam can be performed.
    In the example attached the program wait for ANY text to be sent to the COM port. Please note that you need to configure the VISA resource before using it. Once there is something at the COM port, the loop will exit and the rest of the program will be executed.
    Hope this helps
    Shane
    Using LV 6.1 and 8.2.1 on W2k (SP4) and WXP (SP2)
    Attachments:
    Wait for serisl message.vi ‏17 KB

Maybe you are looking for

  • How to copy Frame Above - FrameMaker 10

    My apologies if I don't use the correct terminology. I use InDesign, but I need to lightly edit a FrameMaker file that was created in 2003 on a Mac. I'm editing it on a PC because that's the only version available now (FrameMaker 10). I have been abl

  • Restart error status workflow

    Hello All, We have few workflow items with status error due some missing agents.  we have assigned the agents. Now user asking us to restart or retrigge the same workflow item . But when I tried to restart using SWIA getting message like ' Workflow c

  • Is it possible to combine two single line smartphone accounts?

    There is plenty of time on both contracts. Will there be fees?

  • Sales Order Exit : for defining the invalid Order reason.

    Hi all, I am looking for an exit that may cnotain code for defining invalid entries of order reason AUGRU. In VA01 , in my system, while creating order , we give order reason. But these reasons have been categorized as valid or invalid. Basically whe

  • 11r2 asm configuration on HACMP

    Hi ,I have already configured 11gr2 asm setup on my one server. Now i want to configure/convert this set up into hacmp ACTIVE PASIVE node . So do i have to again install grid and oracle on second node ? Requirement :Set up will look like : IBM aix 7.