Controlled reading from serial port

I'm trying to establish a connection to an external device through the serial port. This is done in a while-loop which sends an association request tries to get a response if a response is not recieved a new rewuest is sent, etc. At the moment this procedure does not work. I am considering two explanations for this. The first is that the loop does not wait long enough for a response to come and simply keeps pumping out requests, the other is that there is something wrong with the reading algorithm, that doesn't let it properly take in information from the serial port.
Solved!
Go to Solution.
Attachments:
association_loop.GIF ‏5 KB
read_visa.GIF ‏8 KB

I made a new version of the read case. The old version was a while loop, the new version is a while loop which will go on until it encounters an EOF character. In this case it is
0xC1 or 'Á'. I thought the old version would break before getting any message. This doesnt get any signal either. I have probed it, and it doesn't get a string from which to take the length.
Attachments:
read_visa2.GIF ‏10 KB

Similar Messages

  • A problem about reading from serial port

    Hi,
       I just sent '0x03' from MCU to PC continuously, and then sent  '/n' as a stop character after every '0x03'. I use labview to read the data. The problem is when it get two '03' it get a '0', another two '03' and another a '0'. I don't know where is the '0' from?
      PS: Hyper terminal can display natrually.
       Thank you! 
    帖子被hengfo在08-08-2007 10:14 PM时编辑过了
    Attachments:
    serial read.vi ‏36 KB

    I think the problem may be the loop reading the serial port is running too fast.  There is no timing delay in the loop, so you are reading it as fast as you can, and probably faster than the device is sending data.  So sometimes the buffer is empty, and then the empty string gets converted to a numeric zero.  The way to know for sure is to put an indicator on the error wire coming out of the serial port read.  I bet you will see errors about the read buffer being empty.
    Put a wait timer in the loop to slow down the execution just slightly.  This is a good idea so that LV doesn't eat up all the CPU resources.  Look at the example for Basic Serial Write and Read.  You may want to have a loop ahead of the read that waits until there are a certain number of bytes at the port before it reads the serial port.  You may want to put a loop around the serial port that waits until a valid number is read in before it exits the loop and goes to the numeric conversion.
    Message Edited by Ravens Fan on 08-09-2007 08:50 AM

  • Computer freezes while reading from serial port

    My computer freezes when i tried to read from a serial port for a longer period of time such as 10 hours. I always close the serial port after reading. please, help me solve this problem

    I too experienced a similar problem twice on my machine and I have no idea how to stop it because it is so intermittent and I cannot replicate it.
    Perhaps I can offer some clues.
    The Labview screen cannot be stopped and some parts of Windows appears frozen. Oddly enough I can switch to the block diagram but thats about all I can do. The LV stop button will indicate a mouse click on it but the VI does not stop. iT also cannot be closed.
    Even the reset button and power button on the PC does not work. I am forced to power down the PC (pull the plug) to get back control.
    I believe it is related to a visa call to my serial Balance.
    ANyway no solution but hopefully some clues.
    Dell Optiplex GX260 w/ 500MB RAM
    Win2K 500.2195 w service pak 4,
    NI
    serial Hardware and NI serial ver1.45 (16 com ports)
    Labview 6.1 and 7

  • Efficient optimized way to read from serial port and GPS data display using map

    Hi,
    I have a custom h/w which reads the data from GPS Rx and after parsing send it to PC over RS232.
    Each second it sends 201 bytes to PC. I have developed a VI to read the GPS data and display it. Project file is attached.
    Fulctionality of different loops are as following:
    1. LOOP 1: 1.1 Reads the serial data from com port.
                   1.2 Synclonize the frame using start bytes "a" and "z".
                   1.3 Reads next 4 bytes containg receiving error information.
                   1.4 Reads next 195 bytes. in which initial 80 byes are GPS data. rest are others.
    2. LOOP 2: 2.1 Extarcts the GPS information and put them in an array.
                      2.2 Extarcts the receive error infor and counts the total error by incrimenting the variable using shift reg.
    3. LOOP 3:3: 3.1 Displays the GPS data in chart and log the data in a file.
    4. FLOW : Uses the GMAP .NET based API to creat a MAP and display.
    Problem statement:
    1. Functionality acheived.
    2. However in between data set is being missed by the programm. 
    Quesitions:
    1. Is the developed VI is efficient in terms of using queue loacl variables etc.
    2. What are the improvments I can do to solve the problem.
    Any other suggestions|
    Thank you
    jayant
    jayant
    Attachments:
    Telemetry_Receiver_v2.zip ‏3075 KB

    One of the most common problems in serial communication is the need for an adequate timing: how much time is expected your device to spend before answering? Have you put and adequate pause in your code before reading from the serial port?
    Hope this helps
    Roberto
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?

  • Plot more than one analog value to a waveform chart by reading from Serial Port

    I have 4 LDRs and I want to plot their values to a waveform chart by reading them from the serial port. I have looked around and found an example of a VI plotting one value to a waveform chart (attached below) but I am unsure about how to expand this for 4 different waveforms, mostly because I don't particularly understand the way is being read currently. If someone could either point me in the way of a relevant example or explain/show me a solution, or explain howthe current VI I have works, that would be greatly appreciated.
    Attachments:
    LDRread.vi ‏20 KB

    Since I assume each LDR (whatever that is) has its own serial connection, you will need to read from 4 different serial ports.  From there, just form an array of all the data and write to the chart.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions

  • Function for reading from serial port

    Hi experts,
    We are trying to read data from the serial port with the following function we got from internet.
    The problem is when creating the object with the sentence CREATE OBJECT o_obj '"MSCOMMLib.MSComm.1"'.
    This returns a sy-subrc = 2 and shows the exception NO_CREATE_OBJECT.
    We already copied the file MSCOMM32.OCX in c:\windows\system32 and we successfuly registered it, with regsvr32.exe.
    We tried it with Windows XP and Vista.
    Anybody has any idea?
    Thanks in advance
    FUNCTION ZSERIALCOM.
    ""Interfase local
    *"  IMPORTING
    *"     REFERENCE(MODE) TYPE  I DEFAULT 0
    *"     REFERENCE(COMMPORT) TYPE  I DEFAULT 1
    *"     REFERENCE(SETTINGS) TYPE  C DEFAULT '2400,N,8,1'
    *"     REFERENCE(OUTPUT) TYPE  C OPTIONAL
    *"  EXPORTING
    *"     REFERENCE(INPUT) TYPE  C
    *"  EXCEPTIONS
    *"      NO_CREATE_OBJECT
      TYPE-POOLS: sabc.
      INCLUDE ole2incl.
      PERFORM init.
      PERFORM open_port USING commport settings.
      IF mode = 0.
        PERFORM read_port
        CHANGING input.
      ENDIF.
      IF mode = 1.
        PERFORM write_port
        USING output
        CHANGING input.
      ENDIF.
      PERFORM final.
    ENDFUNCTION.
    DATA: o_obj TYPE ole2_object.
    *& Form Init
    text
    --> p1 text
    <-- p2 text
    FORM init.
    DATA:
    wa_repid LIKE sy-repid.
    wa_repid = sy-repid.
    CALL FUNCTION 'AUTHORITY_CHECK_OLE'
    EXPORTING
    program = wa_repid
    activity = sabc_act_call
    application = 'MSCOMMLib.MSComm.1'
    EXCEPTIONS
    no_authority = 1
    activity_unknown = 2
    OTHERS = 3.
    IF sy-subrc <> 0.
    MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
    WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
    ENDIF.
    CREATE OBJECT o_obj '"MSCOMMLib.MSComm.1"'.
    IF sy-subrc <> 0.
    RAISE no_create_object.
    ENDIF.
    ENDFORM. " Init
    FORM open_port *
    --> COMMPORT *
    --> SETTINGS *
    FORM open_port USING commport settings.
    SET PROPERTY OF o_obj 'CommPort' = commport.
    SET PROPERTY OF o_obj 'Settings' = settings.
    SET PROPERTY OF o_obj 'InputLen' = 0.
    SET PROPERTY OF o_obj 'PortOpen' = 1.
    ENDFORM. "open_port
    FORM read_port *
    --> INPUT *
    FORM read_port
    CHANGING input.
    DATA:
    wa_buffer TYPE i.
    DO 10 TIMES.
    GET PROPERTY OF o_obj 'InBufferCount' = wa_buffer.
    IF wa_buffer > 0.
    GET PROPERTY OF o_obj 'Input' = input.
    EXIT.
    ENDIF.
    ENDDO.
    ENDFORM. " read_port
    FORM write_port *
    --> OUTPUT *
    FORM write_port
    USING output
    CHANGING input.
    DATA:
    wa_buffer TYPE i.
    SET PROPERTY OF o_obj 'Output' = output.
    DO 10 TIMES.
    GET PROPERTY OF o_obj 'InBufferCount' = wa_buffer.
    IF wa_buffer > 0.
    GET PROPERTY OF o_obj 'Input' = input.
    EXIT.
    ENDIF.
    ENDDO.
    ENDFORM.
    *& Form final
    text
    --> p1 text
    <-- p2 text
    FORM final.
    SET PROPERTY OF o_obj 'PortOpen' = 0.
    FREE OBJECT o_obj.
    ENDFORM. " finalbligw

    Hi ,
    I want to read value form weigh bridge through COMM port. I have developed the FM and done the setting as mentioned in the below link
    Read COMM port using ABAP w/o third party software 
    but while executing the FM independently I am able to get the value from the COMM port,but when I call the FM from a program I am not able to get the output value from the FM.I am calling the FM from the report program.please find the code below.
    report test.
    data : lv_input TYPE c.
    CALL FUNCTION 'ZFM_WEIGHINTERFACE'
      EXPORTING
        MODE                         = 0
        COMMPORT               = 1
        SETTINGS                  = '1200,N,8,1'
        OUTPUT                     = ''
      IMPORTING
        INPUT                        = lv_input
      EXCEPTIONS
        NO_CREATE_OBJECT       = 1
        OTHERS                 = 2
    IF SY-SUBRC <> 0.
    * Implement suitable error handling here
    ENDIF.
    if I execute the FM independently the output is getting perfectly.but while calling from a program i am facing the issue..
    any suggestion is appreciated.
    Thanks
    Vivek

  • Reading from serial port

    HI,
    I need to read data from virtual serial (rfcomm - BT GPS receiver). I connect to my gps using system command:
    [root@localhost ~]# rfcomm connect /dev/rfcomm0 XX:XX:XX:XX:XX:XX
    and this creates port at /dev/rfcomm0, when I do :
    [root@localhost ~]# cat /dev/rfcomm0
    I get:
    M,0.0,0000*76
    $GPGSA,A,1,,,,,,,,,,,,,50.0,50.0,50.0*05
    $GPRMC,000009.999,V,0000.0000,N,00000.0000,E,,,101102,,*17
    $GPGGA,000010.999,0000.0000,N,00000.0000,E,0,00,50.0,0.0,M,0.0,M,0.0,0000*7E
    $GPGSA,A,1,,,,,,,,,,,,,50.0,50.0,50.0*05
    and the only problem is what to do to read this sequences via java application. I obtained package comm2.0.3.zip , but have no idea what next. I would be grateful for any help.
    best regards
    joshua

    I did everything described here:
    http://www.geeksville.com/~kevinh/linuxcomm.html
    got an example from:
    http://java.sun.com/developer/releases/javacomm/SimpleRead.java
    (the defaultPort = "/dev/term/a"
    replaced with
    defaultPort = "/dev/rfcomm0")
    i connect to my gps with:
    [root@localhost ~]# rfcomm connect /dev/rfcomm0 XX:XX:XX:XX:XX:XX
    start the application and get an error:
    java.io.IOException: Error instantiating class gnu.io.RXTXCommDriver
    gnu.io.RXTXCommDriver cannot be cast to javax.comm.CommDriver
    at javax.comm.CommPortIdentifier.loadDriver(CommPortIdentifier.java:239)
    at javax.comm.CommPortIdentifier.<clinit>(CommPortIdentifier.java:109)
    at comm.SimpleRead.main(SimpleRead.java:78)
    Exception in thread "main" java.lang.UnsatisfiedLinkError: com.sun.comm.SunrayInfo.isSessionActive()Z
    at com.sun.comm.SunrayInfo.isSessionActive(Native Method)
    at com.sun.comm.Portmapping.registerCommPorts(Portmapping.java:155)
    at com.sun.comm.Portmapping.refreshPortDatabase(Portmapping.java:100)
    at javax.comm.CommPortIdentifier.<clinit>(CommPortIdentifier.java:138)
    at comm.SimpleRead.main(SimpleRead.java:78)
    Java Result: 1
    i think i did everything about rxtx as described. could anyone help?
    best regards
    joshua

  • Problem while reading data from Serial Port

    Hi All,
    I am facing some problem while reading data from Serial Port.
    As per the requirement I am writing the data on Serial Port and waiting for response of that data.
    Notification for data availabilty is checked with method public void serialEvent(SerialPortEvent event) of javax.comm.SerialPortEventListener.
    When we are writing data on the port one thread i.e. "main" thread is generated and when data availability event occures another thread "Win32SerialPort Notification thread" is generated. This creates problem for me as we can't control thread processing.
    So can anybody pls explain me how to overcome this problem?
    Regards,
    Neha

    My Problem is:-
    I am simoultaneouly wrting data on port & reading data from port.
    First I write data on port using outputStream.write() method. Now when target side sends me response back for the request on serial port DATA_AVAILABLE of SerialPortEventListner event occured,we are reading data from serial port.Now till the time we didn't get the response from target next command can't be written on the serial port. When we are writing data on port main thread is executed.Now my problem starts when DATA_AVAILABLE event occured.At this point another thread is created.Due to this my program writes data of next command without reading response of previous command.To solve this prob. I have used wait() & notify() methods as follows.But again due to this my pc hangs after execution of 2 commands. (PC hang in while loop in a code provided below.)
    From SOPs I could figure it out that after 2 commands we are not able to write data on serial port so DATA_AVAILABLE event doesn't occure n pro. goes in wait state.
    Can anybody help me to solve this issue.
    Neha.
    Code:
    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:
                        try
                             dataThread = Thread.currentThread();
                             dataThread.setPriority(10);
                             dataAvailable = true;
                                                                                    byte[] tempArray=new byte[availableBytes];
                                        inputStream.read(tempArray);
                                                                       catch (IOException io)
                             SOP(io, "Error in serialEvent callback call for event DATA_AVAILABLE");
    public void  writetoPort(byte[] data) throws IOException
                             outputStream.write(data);
                              while(finalTimeOut >= actualTime)
                            if( ! dataAvailable)
                                    actualTime = System.currentTimeMillis();
                           else
              synchronized (mainThread)
                   mainThread = Thread.currentThread();
                   mainThread.wait();
    public  void sendDatatoUser(byte[] b) throws Exception, HWCCSystemFailure
              obj.returnData(b);
              synchronized(mainThread)
                   mainThread.notify();
                                                           

  • Read data from serial port or TCP port of frontend PC

    Hello Friends,
    I have requirement to read data from device connected to frontend PC which will provide meter reading data.
    Vendor has given me two option.
    1. Device can be connected to seiral port and data transfer will be done through MODBUS RTU protocol.In that case data need to capture from serial port.
    2. Device can be connected to TCP port and Socket program can be provided for data transfer. In that case SAP will act as client and communicate with TCP port.
    There will be multiple workstation with individual meters connected to them.
    I am aware of text file interfacing through front end tools using custom code using VB,JAVA or others.
    Is there any solution availble  to achieve above things using  ABAP other than text file , like direct communication?
    I am using ECC 6.0.

    Hello,
    Socket programming in not available on ABAP, but you may use RFC for the same.
    Use the below links for more details
    [Link 1|http://help.sap.com/printdocu/core/print46c/en/data/pdf/BCFESDE2/BCFESDE2.pdf]
    [Link 2|http://forums.sdn.sap.com/thread.jspa?threadID=1820233]
    Regards,
    Abhishek

  • 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 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 save a datas from serial port?

    How to save a datas from serial port?

    Hi
    I need some help about rs-232 communication. I want to make a vi witch can do this things:
    -read a txt file (to simulate a serial port like when the datas are coming)
    i will get 3 different data in serial port (like this: 121 213 135)
    i want to save in a txt file what datas get my vi
    so
    -write in a txt file or draw in a diagram (or both)
    so my problem is: read in serial port and save in a file and draw a diagram.
    if anybody can help pls HELP ME because im a beginner in this problem.
    I already do something but Im not sure that good.
    Thx for all.

  • Java program to receive byte from serial port

    hello everyone, i am recently working one a project which require communication between pic16f877 and PC. My pic continuiously measure a voltage and send the result (a byte ranging from 0 to 255) to the rs232 port. One the pc side, my java program keep reading the serial port and it works for values 0~127 and 160~255. But if the byte value is between 127 and 160, it cannot received correctly, i get something like 375,8224,or even 65532 etc(no obvious path but more likely to be 300+,700+,8000+ or 65500+). I have been trying very hard to solve this and i think the problem is due to the pc software. I am feeling so frustrated and any suggestion will be much appreciated.
    p.s. : i used Bufferedreader.read() in my program
    --mengyao                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    fumengyao wrote:
    hello everyone, i am recently working one a project which require communication between pic16f877 and PC. My pic continuiously measure a voltage and send the result (a byte ranging from 0 to 255) to the rs232 port. One the pc side, my java program keep reading the serial port and it works for values 0~127 and 160~255. But if the byte value is between 127 and 160, it cannot received correctly, i get something like 375,8224,or even 65532 etc(no obvious path but more likely to be 300+,700+,8000+ or 65500+). I have been trying very hard to solve this and i think the problem is due to the pc software. I am feeling so frustrated and any suggestion will be much appreciated.
    p.s. : i used Bufferedreader.read() in my program
    --mengyaothis may not matter in your case - but don't use a Reader, use a Stream (BufferedInputStream maybe)

  • Synchronise READ from Serial card when Counter on 6025 is incremented

    Hi!
    System description:
    I am using PXI-8423 (2-port RS-422) and PXI-6025 to measure the signal coming from 2 laser sensors mounted onto a mechanical stage with linear encoder.
    The laser sensors give RS-422 output (at 1KHz) and are connected to my serial card.
    The encoder gives quadrature output that I plan to connect to counters on my 6025 daqcard.
    Q:
    I want to read the laser data everytime the encoder gives a pulse signifying the mechanical stage has moved. How can I achieve this?
    We would be taking around 1000 serial reads (from each port) per second.
    Environment:
    We are using PXI-1031 chassis (4-slot) with PXI-8184 controller (850 MHz celeron). OS is Win2K prof. and LabVIEW 7.1
    Thanks,
    Gurdas
    [email protected]
    Gurdas Singh
    PhD. Candidate | Civil Engineering | NCSU.edu

    Hi Gurdas,
    We have some simple serial communication examples included in LabVIEW. Those example programs transmit any string of characters over the serial port. All you have to do is set which port you want to use, baud rate, stop bits, parity, etc. in the VI; this setting wil remain for each serial transfer while the program is running. Again, you can read/write any character string with the serial communication VI's. How the information is put into the character strings is up to you and the device you are communicating with. The serial communication is LSB before MSB.
    Regards,
    Salvador Santolucito
    Applications Engineering
    National Instruments
    Attachments:
    Basic_Serial_Write_and_Read.vi ‏66 KB
    Advanced_Serial_Write_and_Read.vi ‏105 KB

  • Count time between 2 readings from serial port... help!.

    Hi guys,
    I am using my application to get the readings sent by microcontroller from serial port. It works perfectly. But i have the problem, the pic uses 16bits counter, and sometimes i measure frequency lower than 15hz (65535-->16bits). Thats why I thought to measure the time between each pulse that it recieved in serial port. So i could multiply the reading about the time which spend in arrive to serial port. I know if any pulse spend more than 15hz, i should add 65535 to this reading.
    Then, the idea is count the time spent between each reading in serial port. SInce pics count and later send each turn.
    I dont know if it is possible, and exist any easy way.. Can ayone help me?.
    I would like to see any example of it, always it is possible.
    Regards, Fonsi.
    Attachments:
    capture.GIF ‏19 KB

    You're not going to be able to get even close to 1 usec resolution using the built-in time functions though I don't see any of those in your attachment. The windows clock is simply not that accurate. If you need to precisely time your serial reads you might want to look at using the timed loop. You can set the period of that to 1 msec.

Maybe you are looking for

  • Data pump import a table in to a different schema in 11g

    Hi All I have 11.2 Oracle database and i have a requirement to import few tables in to a new schema using my previous month export. I can not import whole schema as it is very large. I check REMAP_TABLE option but it just create the table in same sch

  • Mac Mini joining PC network

    hi, just got a mac mini with airport extreme wireless network capability. i run 2 W2K PC's through a Linksys Wireless G 2.4 GHz 54mpbs, model WRT54G-EU. the mac mini manual seems to indicate that i will need a base station also? is that right? tbh, i

  • Missing Points / $10 certificate from Preorder

    Hi BestBuy Community, Has anyone receive their $10 pre order bonus from the Assasins Creed Unity? It's been well over 30 days now and I see that points were given but it does not reflect the current balance. I have private messaged a MOD but no respo

  • Can see my contacts in imessage but not in 'contact'

    Hi there, I'm encountering I think, a weird issue. I change my iphone recently, and for some reasons, when I synced my new one, I got back everything but my recent contacts. When I go on Icloud online, same thing, I can see only my 'old contact'. BUT

  • Conditions in report (radiobutton : single char or combination of char)

    Hi friends, I have a got a doubt while writing conditions , could you please help me? Question : What is the use of "radiobutton: <u>single charateristics or combination of charateristics</u>" under  "Evaluate the conditions below" block. Points will