Detect input signs at serial port

Hello,
It is posible using Lingo detect input signs at computer serial port??
Thanks for your help

This is certainly possible - check the Mile High Table for xtras that can help with serial communication

Similar Messages

  • Using a PS/2 keyboard on a Sparc workstation through the serial port

    We have recently migrated an application that used to run on a PC, to now run on a Sparc Workstation. This is a SunBlade 1500, running Solaris 8. The application is running in a dedicated console which has a fitted keyboard and trackerball that have PS/2 connectors and cannot be changed.
    We need a way of connecting the PS/2 keyboards to the serial ports of the Sparc workstation. We already have a piece of software that will read ascii values from the serial port so we definately want to go through the serial ports.
    Can someone please suggest what converters will be required to get the output of the keyboard and trackerball as ascii input to the serial port.

    Actually, that's not a bit perverse, at all.
    Jonathan's suggestion is a standard method of connecting to a server.
    (null cable between the computer serial ports)
    ... see the Solaris man pages.
    man tip
    TeraTerm and Hyperterminal are customarily used on a PC running some dialect of Windows.
    The 'tip' command is all that's necessary between Solaris systems.
    PS/2 is not a serial connection, but is a keyboard/mouse interface 'invented' by IBM when they offered their XT-class PS/2 line of desktop systems, back in the 1980's.
    I found this next link by using Google:
    http://members.chello.at/theodor.lauppert/computer/ps2/
    The smaller DIN ports were more compact than the AT-class keyboard ports and the mouse moved from a serial port to a dedicated mouse port.
    Serial communication devices are not keyboards, per se,
    and keyboards are not serial communication devices.
    You need other hardware in between to translate what the human being sends, and another computer is a common method to accomplish that translation.
    Having said all that ...
    Since you cannot change the dedicated console hardware,
    I suggest you go to the manufacturer of that console equipment
    and have them suggest some sort of serial-to-serial interface lash-up.

  • Connect Flash to Serial Port with Local Socket Connection

    Hey all,
    So, I am trying to connect a Flash movie to a serial port
    and have it react to the input coming in. Of course, Flash does not
    have this capability built in, so I need a workaround. I also
    program in Director, and there are easier ways to deal with this
    there, but since there hasn't been an update in years, and for
    other technical reasons, I would like to use a pure Flash program.
    I also need to take advantage of some of the new hardware
    acceleration improvements and horizontal sync issues that come with
    running the Flash player full screen. So, there are some tools out
    there that will let me stream the input from the serial port to a
    web address. I figure I could use the local address and assign a
    port number, then use Flash to create a local socket connection. I
    am having issues opening ports on my computer, and a few other
    things, but in theory, I think it should work. I know that I won't
    get all the answers here, but if anyone has done anything of the
    sort, or might know of some similar projects, it would really help.
    I am more of a Director/Flash programmer, and not so much one on
    the system level. So, opening local sockets, etc, while I am sure I
    can figure it out, is still a bit beyond me. Thanks all!
    - Bruce

    You may want to look into flash remoting, which would allow
    you to push content to the flash movie. You could then write a
    proxy between the source of your stream and flash the remoting
    server.

  • Reading a char array from Serial port

    Need help!
    Hi, I've got the following problem - I wanna read a input stream from serial port and I use at the moment the following method (reading bytewise):
    public String receiveText (){
          byte ch;
          fStrBuf.delete(0,fStrBuf.length()); //clearing the buffer
    try{
              do {
              ch = (byte) fPortInStream.read();
              fStrBuf.append( (char) ch);
            while ( (byte) ch != 0x03); //The end of frame byte
             }catch(IOException ioe) {};
          return fStrBuf.toString();It works pretty well, but disadvantage is that it's too slow to use it in the thread (at least I think so)
    How can I change it to read all available data from the port (or simply faste). I don't need event listeners, because it's a request-responde communication.
    I tried smth. like this
    byte[] readBuffer = new byte[20];
                try {
                    while (fPortInStream.available() > 0) {
                        int numBytes = inputStream.read(readBuffer);
                        fStrBuf.append(readBuffer);
                } catch (IOException e) {}
          return fStrBuf.toString();But it doesn't seem to work :-(

    May I suggest that you use StringBuilder rather than StringBuffer. It has less overhead because it is not threadsafe. I do synchronous serial port stuff with Opto 22, and i have no listeners enabled.
    Appending to the String(Builder/Buffer) directly from the byte buffer mangles it. So I use a string (ugh). With the Opto22 brain boards, i am looking for a carriage return as a term char. It either finds it or times out.
    This is the best i have come up with so far:
    StringBuilder response = new StringBuilder();
    String data = new String();
    long msTimeOut = 2000;
    public void getResponse () throws IOException {
            byte[] readBuff = {0};
            int charAvail;
            response.delete(0,response.length());
            long ts = Calendar.getInstance().getTimeInMillis();
            try {
                while ( readBuff[readBuff.length-1] != '\r' ) {
                    charAvail = inputStream.available();
                    if ( charAvail > 0 ) {
                        readBuff = new byte[charAvail];
                        inputStream.read(readBuff);
                        response.append(new String(readBuff));
                    if ( Calendar.getInstance().getTimeInMillis() > (ts + msTimeOut) ) {
                        response.delete(0,response.length());
                        response.append("TIMEOUT");
                        break;
            } catch (IOException e) { e.printStackTrace(); throw e; }        
            data = response.substring(0);
        } I just starting writing Java about 4 days ago, so caveat emptor.

  • How can detect the serial port is active

    I made a program. It can read datas via serial port. But the datas wont came all the time, so the other part of the program not need to run. I want to put before the "reading serial port" a detection about the serial port is get a data. So the reading is wont start before datas are not coming. Can anybody help me how can i solve this problem?

    Hi Zoyo, if you use the VISA- VIs, the functionyou need is "VISA Bytes at serial port". It shows, how many Bytes are available in the input buffer. You can find it here:
    greets, Dave
    Message Edited by daveTW on 11-22-2006 02:01 PM
    Greets, Dave
    Attachments:
    Bytes at serial port.png ‏20 KB

  • Java applets in a browser, and Serial port input

    I know that there is a special package for serial port input in java. (java.Comm.SerialPort)
    What I am trying to figure out before a final decision on design is made, is if there is anyway of reading serial port input into a java applet that is running inside of a browser.
    I have found lots of reference to Serial port input, but nothing that really goes in the direction that I am lookind for.
    Any little tid bits of information pertaining to this would be greatly appreciated.
    Cuervo

    You should also consider that applets are not allowed to access their client system's hardware without being signed; in other words, the user must agree (by clicking a button) to disable the applet security features. Why would you use an applet to do this? Applets are meant to be an extension of a website. You should use an application in this situation.

  • Serial port: Input/output signal errantly combined

    I am currently in the process of using LabView to replace another user interface for a scientific instrument.
    LabView is connected to this instrument through a serial port.  The instrument streams 25 bytes of binary data every second to the computer.  I can read the binary string (VISA Read) and save contiuously to disk using a while loop.  In addition, there are a few instructions I can send to the instrument that will do various functions (start logging, turn LEDs on/off, etc).  I can successfully send these instructions to the instrument using the previous interface, and in a stand-alone vi using VISA Write, but when I place the VISA Write function into the larger interface vi, signals go haywire.  Specifically, there are two separate LEDs that I can toggle with two different commands, but when in the larger interface vi, both commands toggle the same LED.  Also, it appears that the singal I send to the instrument (a single ASCII character) immediately bounces back to the computer into the 25 bytes of streaming binary data.  In other words, after I press the LED "on" key, one column of my streaming data changes when it is not supposed to (ex: after Binary to ASCII conversion, it changes from a single digit to a twenty digit value).
    Initially, I thought the problem was the sequence of VISA Read/Write.  In the current configuration, I read all data, then allow for Write commands.  Both the VISA functions are within the same While loop to continuously monitor the data.  Is it possible the Write signal output is not leaving the while loop and being read as input?  What would make the instrument read two different commands as the same one?  My goal is to run an interface that displays the streaming data as ASCII, and allows for a few different toggle options while the interface is running - is there are more efficient/elegant way than a while loop?
    ~Going Bananas
    Solved!
    Go to Solution.

    New replies now in gray.
    CodeMunkee wrote:
    1.  If you keep giving me good advice like this, I'll be tempted to change the background to Baltimore prison purple.
    I'll ignore this statement.
    2.  The buffer now lives outside the loop.  I understand clearly.  Part of the problem might be my instrument - when I cycle power the 19 digit number that was 'echoed' disappears.  Forget about that display stuff, it works properly - I accidentally removed the time delay when editing the vi.   But you do bring up an interesting point...
    Without the delay, the loop ran much faster.  If the bytes weren't at the port, the read statement would have returned nothing when it read zero bytes, thus blanking out the indicator rather quickly.
    Yes, Hexadecimal display shows 04 to indicate the end of the 25-byte data sample.
    Doing a bytes at port read is not always a good idea.  If not all the bytes had arrived yet when you ask for the read, you won't get all the data.  The remaining data being sent in that stream from the instrument will show up at the front of the buffer on the next read command. 
    While this isn't a common occurence, it does happen.  How can I prevent this from ever happening?
    Since you know each commands ends with a hex 04 (ASCII character for EOT), you could enable the termination character when you configure the serial port.  Set the termination character to be 4.  Then when you execute the VISA read, read a large number of bytes such as 25 or more.  The read will terminate at either the timeout, the requested number of bytes, or when the termination character is read.  With this setup, you could eliminate the wait statement and also not request the number of bytes as the port.  The VISA read will control the pacing of the loop.  Any extra bytes after the termination character are part of the next frame of data and will wait around until the next time you read the VISA port.
      3.  Implementing your ideas for the latch button works better.  I am still encountering issues with these commands however.  Attached is the new vi.  There are two commands I want to send, 't' turns on the LED light (they blink for 30 sec then time out), and the latch works perfectly for that, 'p' turns on the magnetometer light (an additional 'p' is required to turn it off), but I cannot get the command sent to the mag while the loop is running.  It turns on either at the beginning of the vi, or at the end of the vi (after Finish button is pressed).  This leads me to think the command 'p' is stuck inside the loop.  I tried adding another film strip (see attached vi) for the toggles to force the issue, but it didn't work. Additionally, the 'p' command effectively works as a 't' command, and the LED lights begin to blink when I press the 'p' button.  This isn't supposed to happen, and leads me to believe the 'p' command does in fact exit the loop but in the wrong manner.
    The "film strip" is another frame of a flat sequence structure.  It enforces the order of execution.  The next frame can't execute until everything in the prior frame has completed.  It isn't necessary in your case because the Error and VISA wires determine the order of execution with respect to the other VISA statements.  But it shouldn't hurt.
    There is no reason the "p" case structure should behave any differently than the "t" case structure.  Although you should wire the error wire through in the False case of the "p" structure like you did for the "t" structure.  There is no "exiting of the loop" in either case.  The loop runs until the stop button is pressed.  I would check the manual to see that t and p commands do what you think they should do.  Do they need a termination character of their own when they are sent?  Should they be upper case letters rather than lower case?  You can run NI Spy on your serial port and see the operations occurring with it and see the data coming in and what data is going out.  I would be suspicious that the device is not handling the command properly.
    Any ideas?  I think I've tried to put the toggle buttons outside the loop before, but then could only toggle once before the loop took over.  Ideally, these toggles would be available at any time while the data is streaming, so therefore inside the loop?
    The toggle buttons need to be within the loop so that they can be read on every iteration of the loop.  Outside the loop, as you discovered, they are only read once at the very beginning before the loop is started.
    4.  Thank you for the suggestion about the Selection Mode for the Open/Create File option.  It is annoying to create a file first.  I made the change, but I still get error messages when I use a file that does not yet exist.  LabView takes me to the first Open/Create/Replace vi when the error occurs.  Is there something else I must do?
    On the open file VI, there is an input that is Open as default when unwired.  Create a constant there and change to Replace or Create.
    Remember, if you have any questions about the way LabVIEW is handling something with serial ports, close the port within LabVIEW.  Open Hyperterminal and try the commands from there.
    Message Edited by Ravens Fan on 01-13-2009 03:55 PM

  • How to detect serial port

    CommPortIdentifier portId;
              Enumeration en = CommPortIdentifier.getPortIdentifiers();
              Vector v=new Vector();
              while (en.hasMoreElements())
                   portId = (CommPortIdentifier) en.nextElement();
                   if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
                             v.addElement(portId.getName());
              }

    refer this URL
    http://www.java2s.com/Code/Java/Development-Class/ReadfromaSerialportnotifyingwhendataarrives.htm
         * Project                     :
         * Class                     : GUIFrame.java
         * Purpose                    :
         * Date_Created               :
         * @ Version 1.0
    import javax.swing.JFrame;
    // import javax.swing.JPanel;
    import javax.swing.JMenuItem;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import java.awt.event.*;
    import javax.comm.*;
    import java.awt.*;
    import javax.swing.*;
    // import javax.swing.border.TitledBorder;     
    public class GUIFrame extends JFrame implements ActionListener
         JButton connectPort;
         JComboBox combo;     
         //JButton baudRate;
         //JComboBox baudRateCombo;     
         public JTextArea textArea;     
         JButton sendData;
         public SerialConnection serialConnection;
         public GUIFrame()
              setLayout(null);
              setTitle("First Frame");
              serialConnection = new SerialConnection();                    
              setJMenuBar(createMenuBar());
              combo = new JComboBox();
              combo.setBounds(50, 50, 80, 25);
              listPort();
              combo.addActionListener(this);
              connectPort = new JButton("Connect");
              connectPort.setBounds(150, 50, 100, 25);
              connectPort.addActionListener(this);
              sendData = new JButton("Send Data");
              sendData.setBounds(150, 150, 100, 25);
              sendData.addActionListener(this);
              textArea = new JTextArea();
              textArea.setBounds(300, 300, 400, 300);
              textArea.setFont(new Font("sansserif",0,18));
              add(connectPort);
              add(combo);
              add(sendData);
              add(textArea);;
              setSize(400, 300);
              setVisible(true);
              addWindowListener(new MainWindowAdapter());
         public static void main(String arg[])
              System.out.println("Hi");
              new GUIFrame();
         public JMenuBar createMenuBar()
              JMenuBar menuBar = new JMenuBar();
              JMenu fileMenu = new JMenu("File");
              JMenuItem connectMenuItem = new JMenuItem("Connect");
              connectMenuItem.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae){
                        try{
                             if(serialConnection.portName == null){
                                  serialConnection.portName = combo.getSelectedItem().toString();
                             serialConnection.openConnection();
                        catch(Exception ex)
              JMenuItem disconnectMenuItem = new JMenuItem("Disconnect");
              disconnectMenuItem.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae){
                        try{
                             serialConnection.closeConnection();
                        catch(Exception ex)
              fileMenu.add(connectMenuItem);
              fileMenu.add(disconnectMenuItem);
              menuBar.add(fileMenu);
              return menuBar;
         public void listPort()
              CommPortIdentifier portId;          
              java.util.Enumeration enumeration = CommPortIdentifier.getPortIdentifiers();
              while(enumeration.hasMoreElements())
                   portId = (CommPortIdentifier)enumeration.nextElement();
                   if(portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
                        if(!portId.isCurrentlyOwned())
                             combo.addItem(portId.getName());
         public void actionPerformed(ActionEvent ae)
              if(ae.getSource() == connectPort)
                   System.out.println("Connect is clicked");     
                   try
                        if(serialConnection.portName == null)
                             serialConnection.portName = combo.getSelectedItem().toString();
                        serialConnection.openConnection();
                   catch(Exception ex)
              if(ae.getSource() == combo)
                   System.out.print("Port Name = " + combo.getSelectedItem().toString());
                   serialConnection.portName = combo.getSelectedItem().toString();
              if(ae.getSource() == sendData)
                   byte b[] = new byte[5];
                   b[0] = (byte)0xaa;
                   b[1] = (byte)0xbb;
                   b[2] = (byte)0xcc;
                   b[3] = (byte)0xdd;
                   b[4] = (byte)0xee;     
                   try
                        serialConnection.getOutputStream().write(b);
                        display(b);
                   catch(Exception ex)
         public class MainWindowAdapter extends WindowAdapter
              public void windowClosing(WindowEvent win)
                   dispose();
                   System.exit(0);
         public void display(byte[] b)
              for(int i=0; i< b.length; i++)
                   textArea.append(Integer.toHexString (b[i] & 0xff) + " ");
              textArea.append("\n");
         * Project                     :
         * Class                     : SerialConnection.java
         * Purpose                    :
         * Date_Created               :
         * @ Version 1.0
    import javax.comm.*;
    import java.io.*;
    public class SerialConnection
         private OutputStream os;
         private InputStream is;
         private CommPortIdentifier portId;
         public SerialPort sPort;
         private boolean open;
         public String portName;
         SerialConnection serialConnection;
         public SerialConnection()
              serialConnection=this;
              PortHandler portHandler = new PortHandler(serialConnection);
              portHandler.init(serialConnection);
         public void setOutputStream(OutputStream os)
              this.os=os;
         public OutputStream getOutputStream()
              return os;
         public void setInputStream(InputStream is)
              this.is=is;
         public InputStream getInputStream()
              return is;
         * A Method to open the SerialConnection
    public void openConnection() throws Exception
              try
                   portId = CommPortIdentifier.getPortIdentifier(portName);
              catch (javax.comm.NoSuchPortException e)
                   System.out.println("noPort : "+e);
              try
                   sPort = (SerialPort)portId.open("port", 3000);               
                   open = true;
              catch (javax.comm.PortInUseException e)
                   throw new Exception();
              try
                   setOutputStream(sPort.getOutputStream());
                   setInputStream(sPort.getInputStream());               
                   System.out.println("IO stream is opened");
              catch (java.io.IOException e)
                   sPort.close();                    
         *A Method to Close the port and clean up associated elements.
         public void closeConnection()
              // If port is already closed just return.
              if (!open)
                   return;
              if (sPort != null)
                   try
                        this.os.close();
                        this.is.close();
                        System.out.println("IO stream is opened - CloseConnection");
                   catch (java.io.IOException e)
                        System.err.println(e);
                   sPort.close();
                   System.out.println("Port is closed");
              System.out.println("Flag Open - 1 : " + open );
              open = false;
              System.out.println("Flag Open - 2 : " + open);
         * Send a one second break signal.
         public void sendBreak()
              sPort.sendBreak(1000);
         * Reports the open status of the port.
         * @return true if port is open, false if port is closed.
         public boolean isOpen()
              return open;
         * A Method to add the event listener to the SerialPort
         public void addEventListener(java.util.EventListener listener)throws Exception
              System.out.println("Is not in opened state");
              if(isOpen())
                   System.out.println("Is in opened state");
                   try
                        sPort.addEventListener((javax.comm.SerialPortEventListener)listener);
                   catch (java.util.TooManyListenersException e)
                        sPort.close();               
                   // Set notifyOnDataAvailable to true to allow event driven input.
                   sPort.notifyOnDataAvailable(true);
                   // Set notifyOnBreakInterrup to allow event driven break handling.
                   sPort.notifyOnBreakInterrupt(true);
                   // Set receive timeout to allow breaking out of polling loop during
                   // input handling.
                   try
                   sPort.enableReceiveTimeout(50);
                   //sPort.enableReceiveTimeout(-1);
                   catch (javax.comm.UnsupportedCommOperationException e)
                        e.printStackTrace();
                   // Add ownership listener to allow ownership event handling.
                   portId.addPortOwnershipListener((javax.comm.CommPortOwnershipListener)listener);
         import javax.comm.*;
         public class PortHandler implements SerialPortEventListener,CommPortOwnershipListener{
              public SerialConnection serialConnection;
              public PortHandler(SerialConnection serialConnection)
                   this.serialConnection=serialConnection;
                   try{
                        serialConnection.addEventListener((SerialPortEventListener)this);
                        System.out.println("New Port Handler is called");
                   catch(Exception e)
                        System.out.println("Exception PortHandler(); " +e);
                        e.printStackTrace();
                   // Add this object as an event listener for the serial port.
                   System.out.println("PortHandler is initialised...");
              public SerialConnection getConnection(){
                   return serialConnection;
              public void setSerialConnection(SerialConnection serialConnection){
                   this.serialConnection = serialConnection;
              public void init(SerialConnection serialConnection){
                   setSerialConnection(serialConnection);
              public void serialEvent(SerialPortEvent e){
                   System.out.println("Event Initialised");
                   //Determine type of event.
                   switch (e.getEventType())
                        case SerialPortEvent.DATA_AVAILABLE:
                             try{
                                  readData();                              
                             catch(java.io.IOException e1)
                                  System.out.println("IO Excep "+e1.getMessage());
                                  e1.printStackTrace();
                             catch(Exception e1)
                                  System.out.println("Exception from Serial Event "+e1.getMessage());
                                  e1.printStackTrace();
                        break;
                        case SerialPortEvent.BI:
                        break;
              public void readData() throws java.io.IOException
                   byte b[]=new byte[8500];
                   int i=0,selectOption=0;
                   int newData=0;
                   int doubleLength=0;
                   int length=0;
                   // String mid="",strLen="";
                   while (newData != -1)
                        try     
                             System.out.println("getInputStream().available() : " + serialConnection.getInputStream().available());
                             newData = serialConnection.getInputStream().read();
                             System.out.println("newData\t"+newData);
                             if (newData == -1)
                                  System.out.println("\n End of the File\n");
                                  break;
                             if(i==0){
                                  b=(byte)newData;
                                  System.out.print("\n MSg ID \t= " + Integer.toString(newData&0xff,16)+"\n----------------------------");
                                  if(b[0] == (byte)0x00)
                                       i=-1;
                                       i++;
                                       continue;
                                  i++;
                                  //System.out.println("Method is called - selectOption : " + selectOption);
                                  continue;
                             if(i==1)
                                  b[i]=(byte)newData;
                                  System.out.print("\n Length =\t"+Integer.toString(newData&0xff,16)+"\n----------------------------");
                                  length=newData;
                                  if(length == 0)
                                       i=0;
                                       continue;
                                  i++;
                                  continue;
                             b[i]=(byte)newData;
                             if((b[0] == (byte)0x07) && (i == 2) || (b[0] == (byte)0xaf) && (i == 2) || (b[0] == (byte)0xec) && (i == 2)
                                  || (b[0] == (byte)0x5c) && (i == 2) || (b[0] == (byte)0xbe) && (i == 2) )
                                  String string = String.valueOf((byte)b[0]);
                                  String strLen = Integer.toString(b[2]&0xff,16) + Integer.toString(b[1]&0xff,16);
                                  System.out.println("\n\nLength String = " + strLen + "\n\n");
                                  java.math.BigInteger bi=new java.math.BigInteger(strLen,16);
                                  strLen = bi.toString();
                                  doubleLength = Integer.parseInt(strLen);
                                  System.out.println("\nLength int = " + doubleLength + "\n");
                                  //System.out.println("Method is called");
                             i++;
                             // Added by Siva on Jan 06
                             switch(selectOption)
                                  case 0:
                                       if(i>length+1)
                                            try
                                                 b[i]=(byte)newData;     
                                                 System.out.print("\nThe Last Byte =\t"+Integer.toString(newData&0xff,16)+"\n----------------------------");
                                                 System.out.print("\n"+i+" i Value =\t"+Integer.toString(newData&0xff,16));
                                                 System.out.println("\n----------------------- FINISHED------------------------------");
                                                 // service(b);     
                                                 System.out.println("\n----------------------- After Service------------------------------");
                                                 i=-1;
                                                 i++;               
                                                 continue;
                                            }catch (Exception e)
                                                 System.out.println("Exception in calling service 0:"+e.getMessage());
                                                 e.printStackTrace();
                                                 b[i]=(byte)newData;
                                       System.out.print("\nMSg ID \t= "+Integer.toString(newData&0xff,16)+"\n----------------------------");
                                       break;
                   }catch (java.io.IOException ex)     {
                        System.err.println("Abstarct Port handler Exception\t"+ex);
                   catch(Exception e1)
                        System.out.println("Exception from Read Data "+e1.getMessage());
                        e1.printStackTrace();
                   System.out.println("-----------------------------");
              public void ownershipChange(int type){
                   if (type == CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED){
              public void destroy()     
                   try{
                        serialConnection.closeConnection();     
                   }catch(Exception e){
                        System.out.println("Exception 2:"+e);     
                        e.printStackTrace();
              public void finalize(){
                   destroy();

  • Automatically detect a Printer plugged to a serial port?

    Hello, is there a way for me to automatically detect with java if a printer is plugged in to a serial port (and if so, which one) on my computer.
    I am using javax.comm, but there is no such feature in there.
    Thanks in advance.

    I am not very familiar with this area but I am 99% sure you wouldn't get a signal to tell you are printer had been plugged in to a serial port.
    Your best bet is to spawn a new thread that polls the serial port looking for a new printer.
    Not very pretty I admit but it shouldn't be to hard to do.

  • How to detect if my external device is connected to the Serial port

    Hi,
    If I remove the cable from the serial port in my pc or either remove the serial cable from my external device, then when I send a request to open the serial port from my program, it basically does nothing, it just sits there.
    I want to be able to show some sort of message or any other way of indicating to the user that they should check the cable.
    below is the bit of code to open and set serial port params:
         public void openPort() {
              // Initialise the drivers
              System.setSecurityManager(null);
              String driverName = "com.sun.comm.Win32Driver";
              try {
                   CommDriver commdriver = (CommDriver) Class.forName(driverName)
                             .newInstance();
                   commdriver.initialize();
              } catch (Exception e2) {
                   e2.printStackTrace();
              // port will be set in Store Operations.
              String wantedPortName = Configuration
                        .getParameter(ConfigSetting.EFT_COM_PORT);
              //System.out.println("wantedPortname : " + wantedPortName);
              Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers();
              CommPortIdentifier portId = null; // will be set if port found
              while (portIdentifiers.hasMoreElements()) {
                   System.out.println("counter");
                   CommPortIdentifier pid = (CommPortIdentifier) portIdentifiers
                             .nextElement();
                   System.out.println(pid.getName());
                   if (pid.getPortType() == CommPortIdentifier.PORT_SERIAL
                             && pid.getName().equals(wantedPortName)) {
                        portId = pid;
                        System.out.println("found a macth");
                        break;
              } // end of while
              if (portId == null) {
                   System.err.println("Could not find serial port " + wantedPortName);
                   //System.exit(1);
              try {
                   port = (SerialPort) portId.open("EFTDriver", // Name of the
                                                                               // application
                                                                               // asking for the
                                                                               // port
                             10000 // Wait max. 10 sec. to acquire port
              } catch (PortInUseException e) {
                   e.printStackTrace();
                   System.err.println("Port already in use: " + e);
                   //System.exit(1);
              // Now we are granted exclusive access to the particular serial
              // port. We can configure it and obtain input and output streams.
              try {
                        port.setSerialPortParams(9600, SerialPort.DATABITS_8,
                             SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
              } catch (UnsupportedCommOperationException usc) {
                   System.err.println("Unsupported operation" + usc);
              }Please advise what method can I use for this purpose.
    Thanks
    Abhi

    You mean it hangs in the open() method despite the timeout?

  • Serial port detection

    Ciao,
    is there somebody who can help me to solve this problem?
    I need to distribute an application (.exe) written by LabView7.1 which comunicates with an heating circulator by means of a serial (rs232) port, but I don't know what port will be used by the final user. I'm looking for a labview function or a VI that detects all the serial ports in the PC and add them to a list. Thank you for your co-operation. Bye

    Hi
    I think if you use the VISA Resource Name - Control, you get all available ports listed. I always used this and never had problems up to now.
    Just have a try.
    Hope this helps.
    Thomas
    Using LV8.0
    Don't be afraid to rate a good answer...
    Attachments:
    Visa.PNG ‏15 KB

  • Serial Port buffer is annoying.

    Hi, I'm having a hard time dealing with my serial port. When I send a command (for instance, 'Whello', which should display 'hello' on the instrument panel), it doesn't seem to actually send. If I send Whellowoiaydsociahncu4ynriausfaiu(insert at least 80 characters), the display will read "hellowoiayds" (the display is 12 characters wide).
    So how in the world do I tell the COM port to send the command without requiring all 80 characters? Note that I can have it send "W1234567890" and press send 8 times, and the command will be sent on the 10th attempt. I assume the buffer is being filled as I send the short command, and only actually sends after it is full. If I don't send something to the buffer within 2 seconds, the buffer is cleared.
    Is this a computer problem or programming thing? I've tried turning off FIFO, but it didn't help (maybe I have to reboot to make that setting work?)
    Thanks for your help,
    -James

    Have you tried to place a \n (linefeed) at the end of your buffer. Many serial instruments that I am familiar with (note that I am NOT an expert on serial instruments) typically use a line buffer for parsing and don't start to parse until they get a complete line (80 characters) or detect the end of input with a carraige return or linefeed (or both). So, you may consider sending "whello\n" or "whello\r\n".
    Good luck...

  • How do I process serial port strings as bits

    In response to my commands, my instrument is sending bytes to my serial
    port. In one instance, 2 bytes are received. I want to treat these 2 bytes
    as a group of 16 bits.
    The VISA and Compatibility Serial functions return these bytes from the
    serial port to Labview clearly labelled a "string".
    Everything I can find in the way of Labview functions and .vis don't want to
    do bit twiddling, bit swapping, and bit dropping, with "string" data.
    I thought "hex string to number" could be used here, but I can't find a way.
    The 2 Bytes in question can be represented as hex, but the data are not the
    ASCII codes for the hex representation of a binary number, they are the
    binary number. This "hex string to number" seems to want ASCII c
    odes.
    You can feed a hex number typed into a "control" box wired into "hex string
    to number" and you get a meaningful number. You can feed the 2 bytes from
    the serial port into an "indicator" set to read in hex and you get a hex
    number that is a correct representation. But that is Labview handing them
    around to itself. I need to get my "hands" on them.
    I can't feed those same bytes that show up as a correct hex representation
    in an indicator into the "hex string to number" or anything else, so far,
    and get a number that is useful for further processing.
    I thought "variant to data", but I can't find enough reference material to
    understand how to use it. A boolean array seems like a bit of a weird
    approach, so I thought I'd ask before I looked into that.
    I'm used to dealing directly with binary numbers on the processor stack, I
    call them whatever I want, and turn them into anything I feel like.
    I'm sure I'm staring the solution in the face, but I can't find any way to
    persuade
    Labview to treat this "string" data as 16 bits.
    I've got the 16 bits, which is better than not having them, but I don't have
    much hair left.

    duh, well I finally discovered the "Unflatten from String" function. A guy
    just feeds in the bytes he's collected from his serial port that Labview
    thinks are a "string", and out come lovely little unsigned 16 bit numbers,
    or whatever other type of number he wants to turn the bytes into. And there
    are great little bit twiddlers available after that, like "swap bytes", and
    you can mask out bits with the logic operators, why this is fun. There's
    nothing like being a moron...... fly me to the moon...................
    "David Lewis" wrote in message
    news:[email protected]..
    > The two bytes would come from a serial port read.vi in Labview, classed as
    a
    > string. For instance, D3 and 02. The output wou
    ld swap the two bytes,
    i.e.
    > to 02 and D3, consider the two swapped bytes as 16 bits, drop the six most
    > significant bits, and output the ten bits that are left as an integer
    > classed by Labview as some kind of number, not a string.
    >
    > Your example StringToBits_Converter.vi I found on the ni.com site
    > unfortunately gives an error message and refuses to open on my system
    saying
    > it comes from a newer version of Labview 6 than I am running. Mine says
    > 6.0.1b3. Thank you very much anyway.
    >
    > "FightOnSCTrojan" wrote in message
    > news:[email protected]..
    > > In another words, you want to create a VI in which the input is 2
    > > strings (i.e. AB) and the output is the converted array bits (e.g.
    > > 1010101010101010)?
    >
    >

  • "Example on reading combined signals from a serial port and separating them for display purposes". I am a beginner in Labview and would appreciate if anyone help with that

    I am working on a wireless vital sign monitor. I have 3 signals; heart rate and temperature. I filter and amplify the signals before converting them into digital form. I then pass them via MAX232 before passing them to RS232 serial cable.
    I am therefore working on a program to receive the combined signal and separate them.
    I have come across serial read and write examples on ni.com but am looking for one where I can actually separate combined signals and display them separately.

    Reading the serial port will give you a string. How you divide the channels depends on how the data was formatted before it was sent over the serial channel.
    If you are designing the instrument, as it seems from your query, then you can set up any form you wish. If your data is always floating point numeric, you could use space or tab characters to separate data words. You could use and XML format. If the instrument is provided by a vendor, contact them for the protocol.
    If tabs are used between words and returns between sets of readings, the resutlant string can be interpretted by the Spreadsheet String to Array function in LV.
    Things to avoid are characters often used by serial communications systems as control characters. Carraige returns are
    often used as command terminators by serial protocols, but may also be used by the port.
    Lynn

  • 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.

Maybe you are looking for