Results 1 to 18 of 18

Thread: [RESOLVED] read string from COM1 without MSCOMM

  1. #1

    Thread Starter
    New Member
    Join Date
    Mar 2008
    Posts
    7

    Resolved [RESOLVED] read string from COM1 without MSCOMM

    Hello all VB masters,
    I'm a VERY VERY newbie in VB, but I got a very difficult task
    I need to read string from serial port (COM1), and for some reason, I can't use MSCOMM component . I already search the internet for the answer but still I stuck. Here is some code I've made :


    fCOM = FreeFile
    Dim LineText As String

    Open "COM6" For Input As #fCOM
    LineText = fCOM

    Close #fCOM
    Text1.Text = Text1.Text + LineText




    but what I've got is just "1" character on my text1 component. Any suggestion from masters?
    Thanks for read my post

  2. #2
    Cumbrian Milk's Avatar
    Join Date
    Jan 2007
    Location
    0xDEADBEEF
    Posts
    2,448

    Re: read string from COM1 without MSCOMM

    I don't know much about serial port communication but I'm pretty sure you can't access it as you are (Open Com is QBasic) Besides the reason why you just read a "1" is because that is the file number that FreeFile has returned, it is not coming from "COM6" which VB would interpret as a file name anyway.

    If you can't use the MSCOMM component then I think there are API's that will work.

    Here's some more info.
    Last edited by Milk; Mar 14th, 2008 at 06:20 AM.

  3. #3
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333

    Re: read string from COM1 without MSCOMM

    Welcome to the forums.
    Quote Originally Posted by dhell
    and for some reason, I can't use MSCOMM component
    Why not? Did you try and get errors?

  4. #4
    PowerPoster CDRIVE's Avatar
    Join Date
    Jul 2007
    Posts
    2,620

    Re: read string from COM1 without MSCOMM

    As far as I know MSComm was included in the Pro & Enterprise editions only. What VB version do you have?
    <--- Did someone help you? Please rate their post. The little green squares make us feel really smart!
    If topic has been resolved, please pull down the Thread Tools & mark it Resolved.


    Is VB consuming your life, and is that a bad thing??

  5. #5

    Thread Starter
    New Member
    Join Date
    Mar 2008
    Posts
    7

    Re: read string from COM1 without MSCOMM

    Thanks for all reply,
    milk : Thanks for the article and 780 pdf pages but I can't find any related topic there. Thanks anyway, I really apreciate it.
    hack : because the task has to do that way, I'm not allow to use any component for my code
    cdrive : I'm not sure which VB editions, but I can use MSCOMM component if I want to, the component available on my VB (but I have to do the code without any components )

    For additional information, I can send some string to my serial device with this code :
    vb Code:
    1. fCOM = FreeFile
    2.  
    3. Open "COM6" For Output As #fCOM
    4. Write #fCOM,"Hello World"
    5.  
    6. Close #fCOM

    Hope any one can help...

  6. #6
    PowerPoster CDRIVE's Avatar
    Join Date
    Jul 2007
    Posts
    2,620

    Re: read string from COM1 without MSCOMM

    Quote Originally Posted by dhell
    I'm not sure which VB editions, but I can use MSCOMM component if I want to, the component available on my VB (but I have to do the code without any components )
    This sounds like a school project but I can't make any sense of it. How can you write CommControl code without a CommControl on your Form? maybe I'm misunderstanding your statement? Is your instructor allowing CommControl but no other controls???
    <--- Did someone help you? Please rate their post. The little green squares make us feel really smart!
    If topic has been resolved, please pull down the Thread Tools & mark it Resolved.


    Is VB consuming your life, and is that a bad thing??

  7. #7

    Thread Starter
    New Member
    Join Date
    Mar 2008
    Posts
    7

    Re: read string from COM1 without MSCOMM

    thanks for reply cdrive,
    I'm not allowed even 1 component to do the code. but I think it is make sense because I can send "hello world" string to my serial device, the code is in my previous post. And it works 100 %.
    I'm sorry but correct me if I'm wrong, components are build from VB code too, right? so if it works with component, if I write the code (code to make the components) from the component manually, it sure will work too? correct?
    Thanks anyway, I'm still hoping someone could help me

  8. #8
    PowerPoster CDRIVE's Avatar
    Join Date
    Jul 2007
    Posts
    2,620

    Re: read string from COM1 without MSCOMM

    Quote Originally Posted by dhell
    thanks for reply cdrive,
    I'm not allowed even 1 component to do the code. but I think it is make sense because I can send "hello world" string to my serial device, the code is in my previous post. And it works 100 %.
    I'm sorry but correct me if I'm wrong, components are build from VB code too, right? so if it works with component, if I write the code (code to make the components) from the component manually, it sure will work too? correct?
    Thanks anyway, I'm still hoping someone could help me
    Well, I don't know why you think you're building controls with the code you posted. What you're doing is treating the serial port as a File. While your code does output data from the serial port I don't see how your going to have any flow control or any of the necessary properties required for practical serial com. I did find your code novel though. I don't find it very practical though, except as an exercise. Doogle has expertise with serial com. Perhaps he can help you. He usually answers comm questions.

    Btw, if it works 100% of the time then what is your problem?
    <--- Did someone help you? Please rate their post. The little green squares make us feel really smart!
    If topic has been resolved, please pull down the Thread Tools & mark it Resolved.


    Is VB consuming your life, and is that a bad thing??

  9. #9
    PowerPoster CDRIVE's Avatar
    Join Date
    Jul 2007
    Posts
    2,620

    Re: read string from COM1 without MSCOMM

    Quote Originally Posted by dhell
    For additional information, I can send some string to my serial device with this code :
    vb Code:
    1. fCOM = FreeFile
    2.  
    3. Open "COM6" For Output As #fCOM
    4. Write #fCOM,"Hello World"
    5.  
    6. Close #fCOM

    Hope any one can help...
    I ran your code last night and fed it back through a NullModem to another serial port. I then read the results in Hyper Terminal. Needless to say, "Hello World" was not what was displayed. What was displayed was non keyboard character sets. What is the serial device that you're sending your output to? Are both the TX & RX ports open when you read "1" on the RX port?
    <--- Did someone help you? Please rate their post. The little green squares make us feel really smart!
    If topic has been resolved, please pull down the Thread Tools & mark it Resolved.


    Is VB consuming your life, and is that a bad thing??

  10. #10

    Thread Starter
    New Member
    Join Date
    Mar 2008
    Posts
    7

    Re: read string from COM1 without MSCOMM

    thanks again cdrive,
    I think you got me wrong, what I posted is code for sending string, and my problem is to receive some string from serial port. I just want to prove that I can communicate through serial port without MSCOMM component(but I can only do the sending part )
    I tested the code using the Virtual Serial Port software, that's why in my code I use COM6, because the virtual port software create COM6 as virtual port.
    About TX and RX, I don't really understang about it, I just use the code and it works
    Btw, I've tried with hyper terminal too, but my application always show error when both my application and hyper terminal are activated. And just for additional information, HyperTerminal can communicate perfectly with Virtual Serial Port software.

    Doogle heeellllppp..........
    (hope he hear me )

  11. #11
    Cumbrian Milk's Avatar
    Join Date
    Jan 2007
    Location
    0xDEADBEEF
    Posts
    2,448

    Re: read string from COM1 without MSCOMM

    Quote Originally Posted by dhell
    <Re MSCOMM> I'm sorry but correct me if I'm wrong, components are build from VB code too, right?
    Although probably written in VB it's much more likely it acts as a wrapper for the Api functions as posted in #2 (VB examples for which are given from page 300 in the article, unfortunately truncated).
    However it does seem I was wrong and you can do what you want with the File Input/Output commands as per the old QBasic methods. There's apparently an example bas module that came with QBasic called Terminal.bas which demos this and should convert fairly easily to VB. And there's this at MSDN, see the first question in 'Hints and Suggestions', it's for QBasic but it still applies.

    It might also be worth your while researching working with text files in VB, you will find many examples of this which can be applied to you comm port.

  12. #12
    PowerPoster CDRIVE's Avatar
    Join Date
    Jul 2007
    Posts
    2,620

    Re: read string from COM1 without MSCOMM

    I don't know where to begin here. I still have QB4.5 on all my machines & I'm familiar with Terminal.BAS. QB used the PRINT not the Write statement to output to the comport. It also required the same arguments in the Open Comm command as VB except LEN. You can see this here.

    Code:
    ' Code from QB4.5 "TERMINAL.BAS"
    ' Open communications (1200 baud, no parity, 8-bit data,
    ' 1 stop bit, 256-byte input buffer):
    OPEN "COM1:1200,N,8,1" FOR RANDOM AS #1 LEN = 256
    
    PRINT #1, KeyInput$;    ' User pressed a key, send the character typed to the modem.

    As far as I'm concerned, I think VB has no idea that it's accessing a Comport. Like I said earlier, I suspect that VB thinks it's opening a file. In fact, if you put your code in the Form.Click event and Rem out 'Close #fCOM' I will guarantee you that clicking the Form more than once will return Run Time Error 55 "File Already Open". If VB knew it was communicating with a port you would receive Error 8005 "Port Already Open". I'm not an MSComm expert but I've used it enough to be familiar with the basics.

    Now I don't know if Milk is correct, that your code may be intended to be used with an API, or not, so I'm going to stay away from that discussion.
    <--- Did someone help you? Please rate their post. The little green squares make us feel really smart!
    If topic has been resolved, please pull down the Thread Tools & mark it Resolved.


    Is VB consuming your life, and is that a bad thing??

  13. #13

    Thread Starter
    New Member
    Join Date
    Mar 2008
    Posts
    7

    Re: read string from COM1 without MSCOMM

    You both are right, that command is usually use to dealing with textfile. I already tried my read command to read textfile before and it worked. That's why I don't think my code is wrong.

    vb Code:
    1. Open "C:\test.txt" For Input As #fCOM

    but when I change the textfile name to "COM6" you know what happened...

    cdrive: about the error message, you are absolutely right, that error message appear when 'Close #fCOM' is removed. I already try it before too

    That's why I join this forum, because I almost desperate hehehehe

  14. #14
    PowerPoster
    Join Date
    Jul 2006
    Location
    Maldon, Essex. UK
    Posts
    6,334

    Re: read string from COM1 without MSCOMM

    I've just found this thread, but I'm not going to be of much use. I've never heard of anyone ever trying to access the Comm ports using standard VB I/O, let alone a not-so-experienced programmer. As Cdrive has mentioned, there are a set of APIs available which the Comm control wraps up, including:

    CreateFile - to obtain a handle to the Comm Port
    GetCommState - to get the current settings of the Port
    SetCommState - to set the settings of the Port
    GetCommTimeouts - to get the current timeout values
    SetCommTimeouts - to set the timeout values
    WriteFile - to output to the Comm Port
    ReadFile - to read from the comm Port

    I doubt very much that your teacher or whoever is expecting this sort of code from you, I wouldn't expect a 'novice' programmer to be capable of doing this with APIs. It's difficult enough to create a reliable serial port communications program using the MSComm control. I think you should check back with whoever set you this challenge and ask them exactly how they expect you to complete it.

    Anyway, there's a reasonable example of using the APIs in .NET here: http://support.microsoft.com/kb/823179 which I have (hopefully) converted to VB. There may be some errors as I haven't got the facilities to test it. All I can say is that it does compile cleanly,

    Code:
    Option Explicit
    
    Private Type COMMTIMEOUTS
            ReadIntervalTimeout As Long
            ReadTotalTimeoutMultiplier As Long
            ReadTotalTimeoutConstant As Long
            WriteTotalTimeoutMultiplier As Long
            WriteTotalTimeoutConstant As Long
    End Type
    
    Private Type DCB
            DCBlength As Long
            BaudRate As Long
            fBitFields As Long 'See Comments in Win32API.Txt
            wReserved As Integer
            XonLim As Integer
            XoffLim As Integer
            ByteSize As Byte
            Parity As Byte
            StopBits As Byte
            XonChar As Byte
            XoffChar As Byte
            ErrorChar As Byte
            EofChar As Byte
            EvtChar As Byte
            wReserved1 As Integer 'Reserved; Do Not Use
    End Type
    
    Private Type SECURITY_ATTRIBUTES
            nLength As Long
            lpSecurityDescriptor As Long
            bInheritHandle As Long
    End Type
    
    Private Const GENERIC_READ As Long = &H80000000
    Private Const GENERIC_WRITE As Long = &H40000000
    Private Const OPEN_EXISTING As Long = 3
    Private Const FILE_ATTRIBUTE_NORMAL As Long = &H80
    Private Const NOPARITY As Long = 0
    Private Const ONESTOPBIT As Long = 0
    
    Private Declare Function CreateFile Lib "kernel32.dll" Alias "CreateFileA" _
                (ByVal lpFileName As String, ByVal dwDesiredAccess As Long, _
                 ByVal dwShareMode As Long, ByRef lpSecurityAttributes As SECURITY_ATTRIBUTES, _
                 ByVal dwCreationDisposition As Long, ByVal dwFlagsAndAttributes As Long, _
                 ByVal hTemplateFile As Long) As Long
    
    Private Declare Function GetCommState Lib "kernel32.dll" (ByVal nCid As Long, _
                ByRef lpDCB As DCB) As Boolean
    
    Private Declare Function SetCommState Lib "kernel32.dll" (ByVal nCid As Long, _
                ByRef lpDCB As DCB) As Boolean
    
    Private Declare Function GetCommTimeouts Lib "kernel32.dll" (ByVal hFile As Long, _
                ByRef lpCommTimeouts As COMMTIMEOUTS) As Boolean
    
    Private Declare Function SetCommTimeouts Lib "kernel32.dll" (ByVal hFile As Long, _
                ByRef lpCommTimeouts As COMMTIMEOUTS) As Boolean
    
    Private Declare Function WriteFile Lib "kernel32.dll" (ByVal hFile As Long, _
                ByVal lpBuffer As Any, ByVal nNumberOfBytesToWrite As Long, _
                ByRef lpNumberOfBytesWritten As Long, ByVal lpOverlapped As Long) As Boolean
    
    Private Declare Function ReadFile Lib "kernel32.dll" (ByVal hFile As Long, _
                ByVal lpBuffer As Any, ByVal nNumberOfBytesToRead As Long, _
                ByRef lpNumberOfBytesRead As Long, ByVal lpOverlapped As Long) As Boolean
    
    Private Declare Function CloseHandle Lib "kernel32.dll" (ByVal hObject As Long) As Boolean
    
    Private udtTimeOut As COMMTIMEOUTS
    Private udtDCB As DCB
    Private udtSec As SECURITY_ATTRIBUTES
    Private lngHandle As Long
    
    Private Sub cmdReceive_Click()
    Dim lngReturn As Long
    Dim strMessage As String
    Dim lngReceived As Long
    Dim lngMaxLen As Long
    '
    ' Maximum number of bytes to be received = 1024
    '
    lngMaxLen = 1024
    strMessage = Space(lngMaxLen)
    lngReceived = ReadFile(lngHandle, strMessage, lngMaxLen, lngReceived, 0&)
    If lngReceived <> 0 Then
        MsgBox (Left(strMessage, lngReceived))
    Else
        MsgBox "Unable to Read from Comm Port " & Err.LastDllError
    End If
    End Sub
    
    Private Sub cmdSend_Click()
    Dim lngReturn As Long
    Dim lngWritten As Long
    Dim strMessage As String
    strMessage = "This is going to be written to the Serial Port"
    lngReturn = WriteFile(lngHandle, strMessage, Len(strMessage), lngWritten, 0&)
    If lngReturn = 0 Then
        MsgBox "Unable to Write to Comm Port " & Err.LastDllError
    End If
    End Sub
    
    Private Sub Form_Load()
    Dim lngReturn As Long
    udtSec.nLength = Len(udtSec)
    '
    ' Open Comm Port 1
    '
    lngHandle = CreateFile("COM1", GENERIC_READ Or GENERIC_WRITE, 0, udtSec, _
                OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0&)
    If lngHandle <> 0 Then
        lngReturn = GetCommState(lngHandle, udtDCB)
        If lngReturn <> 0 Then
            '
            ' Port settings: (9600 Baud, No Parity, 8 Data Bits, 1 Stop Bit
            '
            udtDCB.BaudRate = 9600
            udtDCB.Parity = NOPARITY
            udtDCB.ByteSize = 8
            udtDCB.StopBits = ONESTOPBIT
            lngReturn = SetCommState(lngHandle, udtDCB)
            If lngReturn <> 0 Then
                lngReturn = GetCommTimeouts(lngHandle, udtTimeOut)
                If lngReturn <> 0 Then
                    '
                    ' All timeouts zero
                    '
                    udtTimeOut.ReadIntervalTimeout = 0
                    udtTimeOut.ReadTotalTimeoutConstant = 0
                    udtTimeOut.ReadTotalTimeoutMultiplier = 0
                    udtTimeOut.WriteTotalTimeoutConstant = 0
                    udtTimeOut.WriteTotalTimeoutMultiplier = 0
                    lngReturn = SetCommTimeouts(lngHandle, udtTimeOut)
                    If lngReturn <> 0 Then
                        '
                        ' If everything went Ok enable the commands
                        ' to send and receive
                        '
                        cmdSend.Enabled = True
                        cmdReceive.Enabled = True
                    Else
                        MsgBox "Unable to set Comm Port Timeouts " & Err.LastDllError
                    End If
                Else
                    MsgBox "Unable to Read Comm Port Timeouts " & Err.LastDllError
                End If
            Else
                MsgBox "Unable to set Comm Port Settings " & Err.LastDllError
            End If
        Else
            MsgBox "Unable to Read Comm Port Settings " & Err.LastDllError
        End If
    Else
        MsgBox "Unable to Access CommPort " & Err.LastDllError
    End If
    End Sub
    
    Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
    Dim lngReturn As Long
    lngReturn = CloseHandle(lngHandle)
    End Sub
    If you want to play with it, open a new project and on the form draw two CommandButtons (cmdSend & cmdReceive) set both their Enabled Properties to False.
    Copy and paste the above into the Declarations Section of the Form and run the code. Hopefully both CommandButtons will appear enabled. Clicking on cmdSend should send the text to the Comm port and clicking on receive will receive from the comm port and display a MessageBox containing what was sent. Note that the program will 'hang' until something is sent from the serial port to the program after you click on cmdReceive.
    Last edited by Doogle; Mar 18th, 2008 at 12:07 AM. Reason: Typos

  15. #15

    Thread Starter
    New Member
    Join Date
    Mar 2008
    Posts
    7

    Re: read string from COM1 without MSCOMM

    Hello doogle,
    wow,you're really expert in it. I tried your code and it worked. Although the application only receive the first character from the serial port, but that's a great help for me. I'll do the rest from here...
    Thanks to cdrive and milk too...
    Hope someday I will be someone who answer the threads hehehe

  16. #16
    New Member
    Join Date
    Jul 2012
    Posts
    1

    Re: [RESOLVED] read string from COM1 without MSCOMM

    Hi, I'm wondering If i can open up this thread again. I tried your code Doogle, but I keep hanging when I start to press and the cmdSend button. I have no idea why its hanging or even trying to do at that function 'WriteFile' Can I have some help?

    Also, I'm trying to close the port after it sends. It seems like I should use CloseHandler for this. Do you agree?

  17. #17
    New Member
    Join Date
    Jan 2013
    Posts
    1

    MSCOMM Issues

    I am trying to use MSCOMM to recieve Date and Time from a device. The code is:

    Code:
    Private Sub MSComm1_OnComm()
    
      Dim dummy As String
       dummy = MSComm1.Input
       Text1.Text = Text1.Text + dummy 'Obviously put this where you want
       
     
        
    End Sub
    but I would like also to print the data and time on label. How I can make it? I made the following:

    Code:
    label1.caption = dummy
    but only one character was being displayed.

  18. #18
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    14,206

    Re: [RESOLVED] read string from COM1 without MSCOMM

    Code:
    Label1.caption=Text1.Text & Now()

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width