Results 1 to 30 of 30

Thread: Problems with COM ports

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Jun 2007
    Posts
    17

    Problems with COM ports

    Brief Description
    I am trying to code a piece of software that will load a text file from a directory, then send that data out to a com port.
    The Problem
    I get an error on the machine that points to the BAUD rate being incorrect, yet I am confident that the BAUD is set correctly.

    Details
    I am sending the data via a Windows XP machine, running my software. It is connected to COM1. The PC is them directly connected via an RS232 cable to a Bosch CNC control (Model CC220).
    When I send my Data I get the following error;
    "Overflow Read Field" The error code it gives me is 2662.
    When I check the error codes, it tells me that Error 2662 is a "Loss of read-in data."
    It suggests that I check my BAUD rate, and it also points to problems with the interface or with the data iput device (the PC).
    I can rule out all but the BAUD rate, as I get the error wether I use my Laptop or the PC I have installed specifically for connecting to the CNC. I can also rule out interface errors, because we can communicate fine with the PC, using a DOS command to copy the file straight to the com port.

    The Code
    Code:
        Private Sub sendToLaser3()
            Try
                Using comPort As IO.Ports.SerialPort = My.Computer.Ports.OpenSerialPort(com)
                    If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
                        Dim fileReader As String
                        fileReader = My.Computer.FileSystem.ReadAllText(OpenFileDialog1.FileName)
                        comPort.DtrEnable = True
                        comPort.RtsEnable = True
                        comPort.Handshake = Ports.Handshake.None
                        comPort.BaudRate = 9600
                        comPort.Parity = Ports.Parity.Even
                        comPort.StopBits = Ports.StopBits.One
                        comPort.DataBits = 7
                        ' writes the fileBytes data to the comPort
                        comPort.WriteLine(fileReader)
                        comPort.Close()
                    End If
                End Using
            Catch ex As Exception
                MsgBox(com & " not found. Please try other com port(s)")
            End Try
            lblSending.Hide()
        End Sub
    I know this is quite specialised, but any help or ideas would be great,

    Fingers Crossed

    Dan
    Last edited by danweb; Jul 27th, 2007 at 04:30 AM. Reason: version vb.net

  2. #2
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: Problems with COM ports

    Try using my method here to send a files data using a binaryreader. See if it works better.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  3. #3

    Thread Starter
    Junior Member
    Join Date
    Jun 2007
    Posts
    17

    Re: Problems with COM ports

    Quote Originally Posted by Atheist
    Try using my method here to send a files data using a binaryreader. See if it works better.
    Thanks for the reply, but as you might see, I originated that thread, and I have the same problem if I try to use a binary reader unfortunately.

  4. #4
    PowerPoster stanav's Avatar
    Join Date
    Jul 2006
    Location
    Providence, RI - USA
    Posts
    9,290

    Re: Problems with COM ports

    Use comport.Write(string) instead of comPort.WriteLine(string) if your text file contains more than 1 line of text.

  5. #5

    Thread Starter
    Junior Member
    Join Date
    Jun 2007
    Posts
    17

    Re: Problems with COM ports

    Quote Originally Posted by stanav
    Use comport.Write(string) instead of comPort.WriteLine(string) if your text file contains more than 1 line of text.
    Unfortunately I have also tried this, and I get the same error. Incidentally I also seem to remember that if I send it a smaller file it doesn't seem to error, maybe this points to the problem, but I am not sure.

    For reference this code also does not work;
    Code:
        Private Sub sendToLaser1() ' main method for sending - revert to this one if working
            Try
                ' display Label to user informing them that job is transmitting to CNC
                lblSending.Show()
                lblSending.BringToFront()
                ' sets up comPort as SerialPort and opens the port
                Using comPort As Ports.SerialPort = My.Computer.Ports.OpenSerialPort(com)
                    ' displays the OpenFileDialog1 to the user
                    If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
                        ' defines sr as a FileStream and opens the filename from the OpenFileDialog1
                        Dim sr As New IO.FileStream(OpenFileDialog1.FileName, IO.FileMode.Open)
                        ' reads the sr filestream ino the binary reader (br)
                        Dim br As New IO.BinaryReader(sr)
                        ' reads the bytes into the fileBytes Byte
                        Dim fileBytes() As Byte = br.ReadBytes(CInt(br.BaseStream.Length))
                        ' close the readers
                        br.Close()
                        sr.Close()
                        ' setup the com ports
                        comPort.DtrEnable = True
                        comPort.RtsEnable = True
                        comPort.Handshake = Ports.Handshake.None
                        comPort.BaudRate = 9600
                        comPort.Parity = Ports.Parity.Even
                        comPort.StopBits = Ports.StopBits.One
                        comPort.DataBits = 7
                        ' writes the fileBytes data to the comPort
                        comPort.Write(fileBytes, 0, fileBytes.Length)
                    End If
                End Using
            Catch ex As Exception
                MsgBox(com & " not found. Please try other com port(s)")
            End Try
            lblSending.Hide()
        End Sub

  6. #6
    Fanatic Member Andy_P's Avatar
    Join Date
    May 2005
    Location
    Dunstable, England
    Posts
    669

    Re: Problems with COM ports

    I would suggest checking the cable you are using to comminicate with, and see if the handsahke lines are connected. Specifically the RTS/CTS lines, and the DTR/DSR lines.

    This is important, because if they are in use, then you should be using something other than 'Handshake.None' and setting the RTS line to 'RtsEnable = True'.

    I would reccomend leaving out the RtsEnable line altogether, and setting the handshake property to 'Ports.Handshake.RequestToSend'

    My guess is that the data you are sending is being sent continuously, and when the CNC machine at the other end basically says 'hang on a minute, I can't keep up', your program is ignoring that and keeps on transmitting, hence the loss of data.

    The key to this really, is how the comms lead is wired. Check the lead and post on here what the connections are.
    Using Windows XP Home sp3
    Mucking around with C# 2008 Express
    while ( this.deadHorse ) { flog( ); }


  7. #7
    Lively Member
    Join Date
    Apr 2006
    Location
    Local
    Posts
    112

    Re: Problems with COM ports

    Bosch CC220 requires 2 stop bits & RTS/CTS, flow control Xon/Xoff.
    Microsoft Visual Basic 2008

  8. #8
    Fanatic Member Andy_P's Avatar
    Join Date
    May 2005
    Location
    Dunstable, England
    Posts
    669

    Re: Problems with COM ports

    I have found this link that seems to indicate RTS/CTS flow control, and not Xon/Xoff.

    However, I have no experience with this unit, so how accurate the information is I cannot say.

    One thing is clear though, it appears that the RTS/CTS lines are required (which would indicate hardware flow control to me), which would mean the settings given by the original poster are indeed incorrect.
    Using Windows XP Home sp3
    Mucking around with C# 2008 Express
    while ( this.deadHorse ) { flog( ); }


  9. #9
    Lively Member
    Join Date
    Apr 2006
    Location
    Local
    Posts
    112

    Re: Problems with COM ports

    Sorry my mistake...
    Microsoft Visual Basic 2008

  10. #10

    Thread Starter
    Junior Member
    Join Date
    Jun 2007
    Posts
    17

    Re: Problems with COM ports

    Thanks for your input guys, I am going to try a few of these ideas.
    In particular 'Ports.Handshake.RequestToSend' as suggested by Andy P. I am also going to look at the RTS/CTS settings too.

    FYI this is how the DOS settings were setup, as I have taken a screen grab from that running program.

    Baud: 9600
    Parity: Even
    Data Bits: 7
    Stop Bits: 1
    Timeout: Off
    XON/XOFF: Off
    CTS Handshaking: Off
    DSR Handshaking: Off
    DSR Sensitivity: Off
    DTR Circuit: On
    RTS Circuit: On
    Last edited by danweb; Jul 30th, 2007 at 04:23 AM.

  11. #11

    Thread Starter
    Junior Member
    Join Date
    Jun 2007
    Posts
    17

    Re: Problems with COM ports

    Quote Originally Posted by Andy_P
    I would suggest checking the cable you are using to comminicate with, and see if the handsahke lines are connected. Specifically the RTS/CTS lines, and the DTR/DSR lines.

    The key to this really, is how the comms lead is wired. Check the lead and post on here what the connections are.
    I know little to nothing about pin designations in RS232, so wouldn't entirely know what I am looking at if I took the cable apart.

    I can check the manual though?

  12. #12
    Fanatic Member Andy_P's Avatar
    Join Date
    May 2005
    Location
    Dunstable, England
    Posts
    669

    Re: Problems with COM ports

    Well that's interesting, the settings you posted for the DOS program you use seem to match the settings you originally posted, so on the face of it, they look correct. It should say in the manual what comms parameters should be used.

    You mentioned that when you send a smaller file it works ok? This would definitely lead me to believe handshake or buffer size issuses to be the cause of the problems. It would be interesting to know the size of a file that does work, compared to a file that does not.

    Try setting the .WriteBufferSize properry of the com port to a larger number than the default od 2048.

    Code:
    comPort.WriteBufferSize = 4096 ' For example
    If the size of your files approach this value in size, then I would suspect the buffer is getting filled, which would require handshaking to be in operation to deal with it. It seems odd that in your DOS program, handshaking is disabled (the RTS and DTR lines are merely set to 'on'). Perhaps it creates a larger buffer by default and hence you are getting away with it.

    As far as taking the cable apart, it may be better to leave it at this stage, but if you feel like doing so, open up the end that plugs into the PC at detail any connections that are made. If the cable is a generic 'pin-to-pin' type, then it maybe necessary to dig out the manual and have a look in there.
    Using Windows XP Home sp3
    Mucking around with C# 2008 Express
    while ( this.deadHorse ) { flog( ); }


  13. #13

    Thread Starter
    Junior Member
    Join Date
    Jun 2007
    Posts
    17

    Re: Problems with COM ports

    I am convinced it is something to do with too much data getting sent to the port at once. I tried dropping the BAUD a few different values to see what happened. When I dropped it to 96(!) it didn't error upon receiving the data. But did (probably obviously) time out before it got all of the data.
    I tried a few others, but got UART and Parity errors.
    I will try the writebuffersize setting that you mentioned and see what happens.

    I took apart the cable, it looks like it's a purpose built cable as the soldering isn't the best I've seen.

    The pin connections are as follows;

    Pin-----Signal------------------------Connected
    1------Carrier Detect (DCD)-----------Pin 1 shorted to Pin 6
    2------Receive Data (RXD)------------Red
    3------Transmit Data (TXD)-----------Black
    4------Data Terminal Ready(DTR)------No
    5------Signal GND--------------------Green
    6------Data Set Ready (DSR)---------White
    7------Request To Send (RTS)--------Yellow
    8------Clear To Send (CTS)-----------Orange
    9------Ring Indicator (RI)-------------No

  14. #14
    Fanatic Member Andy_P's Avatar
    Join Date
    May 2005
    Location
    Dunstable, England
    Posts
    669

    Re: Problems with COM ports

    Quote Originally Posted by danweb
    I am convinced it is something to do with too much data getting sent to the port at once.
    That is the point of having Handshaking, so the transmitter can wait if the receiver cannot keep up with the data being sent.

    As the connections you have have the RTS and CTS pins connected, I would suggest that handshaking should be used.

    Another thing that springs to mind is the end of line characters, as you are sending text files. the link I posted above seems to indicate that a CR and LF (&H0d, &H0a) should be sent to the CNC machine. This is the default for the .Writeline method I think, but it's worth checking.
    Using Windows XP Home sp3
    Mucking around with C# 2008 Express
    while ( this.deadHorse ) { flog( ); }


  15. #15

    Thread Starter
    Junior Member
    Join Date
    Jun 2007
    Posts
    17

    Re: Problems with COM ports

    If I set the WriteBufferSize to 4096, it drops out to my Catch, and does not send the data.
    Code:
    Catch ex As Exception
                MsgBox(com & " not found. Please try other com port(s)")
    In the text files that it usually sends, there are no end of line characters. And to put these in would mean a re-write of lots of drivers in for the CAD software that we use. Which I am sure would put an end to this project.

    The file size that works was 51 bytes (Size on disk 4,096), ones that don't work are 3.11 KB (3,187 bytes) (size on disk 4,096).


  16. #16
    Fanatic Member Andy_P's Avatar
    Join Date
    May 2005
    Location
    Dunstable, England
    Posts
    669

    Re: Problems with COM ports

    Quote Originally Posted by danweb
    In the text files that it usually sends, there are no end of line characters.
    By end of line characters, I mean carriage returns or linefeeds. If when you view the file in Notepad for example, you can see each CNC command or whatever on a separate line, then it is fairly safe to assume there are some of those. If the file looks like one long line, then there might not be any, or perhaps only a termionator at the end.

    As long as it does not break any of your company rules, could you post (upload) an example of each file?

    It looks like you are trying to send it correctly with the .Write() method though, so this should stop any problems with incorrect carriage returns and line feeds that might happen with .WriteLine().

    The VB help says that by default, the .Write() method uses ASCII encoding, and that this "encodes all characters greater then 127 as (char)63 or '?'". Perhaps the files you have are a different encoding, maybe UTF8 or something.

    Maybe you could consider changing the Try..Catch arrangement to give you a more explicit error when it fails. At least change it to this for a test, so you know exactly what the exception is:
    Code:
    Catch ex As Exception
        Messagebox.Show(ex.Message)
    At the line the byte array gets filled from the binary reader, set a breakpoint to see if the array is filled with the amount of bytes you expect, for each file.

    Well, a few more things to look at there. Don't give up!
    Using Windows XP Home sp3
    Mucking around with C# 2008 Express
    while ( this.deadHorse ) { flog( ); }


  17. #17

    Thread Starter
    Junior Member
    Join Date
    Jun 2007
    Posts
    17

    Re: Problems with COM ports

    Quote Originally Posted by Andy_P
    Maybe you could consider changing the Try..Catch arrangement to give you a more explicit error when it fails. At least change it to this for a test, so you know exactly what the exception is:
    Code:
    Catch ex As Exception
        Messagebox.Show(ex.Message)
    I tried that and found out that I was trying to set the WriteBufferSize whilst the port was open, so I have closed it and re-opened before sending, and I can now set the buffer size!
    So I shall test it on the machine today to find out if it has worked.

    Also I have been testing another piece of software called DNC4U http://www.dnc4u.com/
    With the following settings the program works perfectly at sending my files.


    Here is an example of the files I am sending to the CNC (open in notepad or whatever)
    http://www.mediafire.com/download.php?fe4zntyz91j

  18. #18

    Thread Starter
    Junior Member
    Join Date
    Jun 2007
    Posts
    17

    Re: Problems with COM ports

    On the second tab of the DNC software it shows a buffer size of 8192, so I have tried this along with 4096.
    I have basically mirrored the exact settings as per the DNC software.

    But I cannot get it to send, I have checked the size of the array using a breakpoint, and it is exactly the same as the file size.....

    Any more ideas would be fantastic, I thank you for your patience and support

  19. #19
    Fanatic Member Andy_P's Avatar
    Join Date
    May 2005
    Location
    Dunstable, England
    Posts
    669

    Re: Problems with COM ports

    One things that stands out from looking at the docs for the DNC program, is that it says certain CNC machines require some characters to be sent before and after file transmission:

    From the docs:
    You can send a series of characters to your CNC both before and after file transmission. This is because many CNC need specific characters to "tell" it that comms is about to start or finish. dnc4U lets you setup these characters as a series of ASCII values (since many of these characters cannot be typed at the keyboard)

    What do you have set for all the parameters on the 'Send' tab of the DNC program? Maybe you require these bytes to be added to your byte array that you transmit.

    Quote Originally Posted by danweb
    The file size that works was 51 bytes
    Could you post an example of this file you say works?

    The DNC docs also make mention of sending by block and packet size, so if your CNC machine requires transmission like this, then your code will have to be modified. Maybe the 51 byte file works because it is below the size for one block and so can be sent all in one go.
    Using Windows XP Home sp3
    Mucking around with C# 2008 Express
    while ( this.deadHorse ) { flog( ); }


  20. #20

    Thread Starter
    Junior Member
    Join Date
    Jun 2007
    Posts
    17

    Re: Problems with COM ports

    I think I might have been confused about having one that worked....

    Here are the settings from the send tab of DNC;


    So I guess that it doesn't need before or after characters?

    As for sending as a block send (as per the DNC settings) I cannot see how I would enable that?

    Incidentally there is nothing set in the delays other than settings to wait after sending and an abort after inactivity setting.

  21. #21
    Fanatic Member Andy_P's Avatar
    Join Date
    May 2005
    Location
    Dunstable, England
    Posts
    669

    Re: Problems with COM ports

    Quote Originally Posted by danweb
    So I guess that it doesn't need before or after characters?
    It would appear so, yes.

    Quote Originally Posted by danweb
    As for sending as a block send (as per the DNC settings) I cannot see how I would enable that?
    Well, as each 'block' is simply a line in its own right, defined by the end of block code 'CR/LF' (carriage return/line feed), it should be fairly simple. It would mean sending one line at a time with a pause in between each line that is sent.

    Try this out:
    Code:
    ' sets up comPort as SerialPort and opens the port
    Using comport As System.IO.Ports.SerialPort = My.Computer.Ports.OpenSerialPort(com)
    
    ' displays the OpenFileDialog1 to the user
    If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
    
        ' defines sr as a FileStream and opens the filename from the OpenFileDialog1
        Dim fs As New IO.FileStream(OpenFileDialog1.FileName, IO.FileMode.Open)
    
        ' reads the sr filestream ino the stream reader (sr)
        Dim sr As New System.IO.StreamReader(fs)
    
        ' reads each line of the file into a list of strings
        Dim fileLines As List(Of String) = New List(Of String)
        Dim line As String
        Do
            line = sr.ReadLine
            If line IsNot Nothing Then
                fileLines.Add(line)
            End If
        Loop Until line Is Nothing
    
        ' close the readers
        sr.Close()
        fs.Close()
    
        ' setup the com ports
        comport.DtrEnable = True
        comport.RtsEnable = True
        comport.BaudRate = 9600
        comport.DataBits = 7
        comport.Parity = System.IO.Ports.Parity.Even
        comport.StopBits = System.IO.Ports.StopBits.One
        comport.Handshake = System.IO.Ports.Handshake.None
    
        ' explicitly set Carriage return and Line feed as the end of line terminator
        comport.NewLine = Convert.ToChar(&HD) & Convert.ToChar(&HA)
    
        ' writes each line of data to the comPort with pause after each block
        For Each str As String In fileLines
            comport.WriteLine(str)
            System.Threading.Thread.Sleep(10) ' 10 = 10 milliseconds
        Next str
    
        End If
    
    End Using
    Two things to note. Firstly, the end of line terminator is set explicitly to the correct value of a carriage return and line feed, to stop any confusion over whether it is or not. Also, after each line is sent, there is a pause, which can be set in milliseconds should you need it.

    As it stands, with this pause in place it may noticably make your UI a bit unresponsive, so should it prove to work, this would really need to be done another way, with the code running in another thread. But let's see if it works first!
    Using Windows XP Home sp3
    Mucking around with C# 2008 Express
    while ( this.deadHorse ) { flog( ); }


  22. #22

    Thread Starter
    Junior Member
    Join Date
    Jun 2007
    Posts
    17

    Re: Problems with COM ports

    Thanks Andy, I will try this code today, and see what happens.

    Thanks again for all your help

    Feedback to follow...

  23. #23

    Thread Starter
    Junior Member
    Join Date
    Jun 2007
    Posts
    17

    Re: Problems with COM ports

    Andy_P = Vb Guru!

    That's cracked it as far as I can tell. Wow you rock!

    I have picked through the code, and feel that I pretty much understand what you have done...

    The operator is going to run it for a bit and see how we get on.

    As for freezing up the GUI, it is, but no more than the previous incarnations.

    That was why I am displaying the label that tells the user "Sending to CNC"

    If all pans out okay, I hope to improve this by giving the user a progession bar.

    Thanks again Andy_P

  24. #24
    Fanatic Member Andy_P's Avatar
    Join Date
    May 2005
    Location
    Dunstable, England
    Posts
    669

    Re: Problems with COM ports

    Hardly a VB guru, just happen to know a little about RS232 that's all.

    Best to run it for a while in case anything crops up, but it sounds hopeful.

    Good luck!
    Using Windows XP Home sp3
    Mucking around with C# 2008 Express
    while ( this.deadHorse ) { flog( ); }


  25. #25

    Thread Starter
    Junior Member
    Join Date
    Jun 2007
    Posts
    17

    Re: Problems with COM ports

    I have just taken a call from the user, see what you make of this.

    The first job he sent through worked perfectly. The second job he sent through, ran on the CNC fine up until a point, then it errored with;
    "Invalid Character in the part program."
    The remedy to which is;
    "Read in program again"

    Because he didn't want to risk having the program fail on him again, he loaded it in using the DOS method and it worked okay.

    He noticed that the file sizes differed, the old version gave him 27,609 and the new version gave him 27,313.

    I am not sure if these are bytes, but I suspect they are...

  26. #26
    Fanatic Member Andy_P's Avatar
    Join Date
    May 2005
    Location
    Dunstable, England
    Posts
    669

    Re: Problems with COM ports

    I figured it was too good to be true!

    It doesn't sound like it is too far wrong though. Maybe a tweak of the delay between sending each line will fix the problem. My first guess would be to increase it by a small amount, as it appears to have struggled to send a large file.
    Using Windows XP Home sp3
    Mucking around with C# 2008 Express
    while ( this.deadHorse ) { flog( ); }


  27. #27

    Thread Starter
    Junior Member
    Join Date
    Jun 2007
    Posts
    17

    Re: Problems with COM ports

    Version 13 now out for testing

  28. #28

    Thread Starter
    Junior Member
    Join Date
    Jun 2007
    Posts
    17

    Re: Problems with COM ports

    I increased the delay to 20ms, and early signs are good!

    The operator was good enough to test the file that we had problems with, and it has now transmitted succesfully and without errors, and has the same byte size as the DOS version.

    I shall update if things change,

    Incidentally, when looking at providing a progress indicator, it seems apparent to me that it won't display as all of the processor is being used to transmit the data.

    Would this be achieved through threading the sending process and the progress indicator separately?

  29. #29
    Fanatic Member Andy_P's Avatar
    Join Date
    May 2005
    Location
    Dunstable, England
    Posts
    669

    Re: Problems with COM ports

    Quote Originally Posted by danweb
    Would this be achieved through threading the sending process and the progress indicator separately?
    The short answer to that is yes, but I will have to think about that, and unfortunately I can't right now. (Got work to do )

    In the meantime, have a look at the BackgroundWorker componet. There is a basic example in the codebank.
    Using Windows XP Home sp3
    Mucking around with C# 2008 Express
    while ( this.deadHorse ) { flog( ); }


  30. #30
    Fanatic Member Andy_P's Avatar
    Join Date
    May 2005
    Location
    Dunstable, England
    Posts
    669

    Re: Problems with COM ports

    Try this out...

    Add a ProgressBar and a BackgroundWorker component to your form. Set the .WorkerReportsProgress and .WorkerSupportsCancellation properties of the BackgroundWorker to 'True'.

    I have also used one button to start the transmit, and another to cancel.

    Add this code:

    vb.net Code:
    1. ' form level variables
    2. Private filelines As List(Of String) = New List(Of String)
    3. Private com As String = "COM3"
    4.  
    5. Private Sub btnTransmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTransmit.Click
    6.  
    7.         ' declare stream and streamreader
    8.         Dim fs As IO.FileStream = Nothing
    9.         Dim sr As IO.StreamReader = Nothing
    10.  
    11.         ' clear the List of strings
    12.         filelines.Clear()
    13.  
    14.         ' reset the Progress bar
    15.         ProgressBar1.Value = 0
    16.  
    17.         Try
    18.  
    19.             ' displays the OpenFileDialog1 to the user
    20.             If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
    21.  
    22.                 ' defines sr as a FileStream and opens the filename from the OpenFileDialog1
    23.                 fs = New IO.FileStream(OpenFileDialog1.FileName, IO.FileMode.Open)
    24.  
    25.                 ' reads the sr filestream ino the stream reader (sr)
    26.                 sr = New System.IO.StreamReader(fs)
    27.  
    28.                 ' read each line of the file into the list of strings
    29.                 Dim line As String
    30.                 Do
    31.                     line = sr.ReadLine
    32.                     If line IsNot Nothing Then
    33.                         filelines.Add(line)
    34.                     End If
    35.                 Loop Until line Is Nothing
    36.                
    37.                 ' configure progressbar parameters
    38.                 ProgressBar1.Minimum = 0
    39.                 ProgressBar1.Maximum = filelines.Count
    40.  
    41.                 ' start background worker to perform COM port write operation
    42.                 BackgroundWorker1.RunWorkerAsync()
    43.  
    44.             End If
    45.  
    46.         Catch ex As Exception
    47.  
    48.             MessageBox.Show(ex.Message)
    49.  
    50.         Finally
    51.  
    52.             ' close the stream and reader
    53.             sr.Close()
    54.             fs.Close()
    55.  
    56.         End Try
    57.  
    58. End Sub
    59.  
    60.  
    61. Private Sub btnCancelTransmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelTransmit.Click
    62.  
    63.         ' cancel transmit operation
    64.         If BackgroundWorker1.IsBusy Then
    65.             BackgroundWorker1.CancelAsync()
    66.         End If
    67.  
    68. End Sub
    69.  
    70.  
    71. Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    72.  
    73.         Dim worker As System.ComponentModel.BackgroundWorker = DirectCast(sender, System.ComponentModel.BackgroundWorker)
    74.  
    75.         ' sets up comPort as SerialPort and opens the port
    76.         Using comport As System.IO.Ports.SerialPort = My.Computer.Ports.OpenSerialPort(com)
    77.  
    78.             ' setup the com ports
    79.             comport.DtrEnable = True
    80.             comport.RtsEnable = True
    81.             comport.BaudRate = 9600
    82.             comport.DataBits = 7
    83.             comport.Parity = System.IO.Ports.Parity.Even
    84.             comport.StopBits = System.IO.Ports.StopBits.One
    85.             comport.Handshake = System.IO.Ports.Handshake.None
    86.  
    87.             ' explicitly set Carriage return and Line feed as the end of line terminator
    88.             comport.NewLine = Convert.ToChar(&HD) & Convert.ToChar(&HA)
    89.  
    90.             ' set up counter variable
    91.             Dim i As Integer = 0
    92.  
    93.             ' writes each line of data to the comPort with pause after each block
    94.             For Each str As String In filelines
    95.  
    96.                 ' check if operation has been cancelled
    97.                 If worker.CancellationPending Then
    98.                     e.Cancel = True
    99.                     Exit For
    100.  
    101.                 Else
    102.                     comport.WriteLine(str)
    103.                     System.Threading.Thread.Sleep(20) ' 20 = 20 milliseconds
    104.  
    105.                     ' increment counter for each line transmitted
    106.                     i += 1
    107.  
    108.                     ' report counter value to the ProgressChanged event
    109.                     worker.ReportProgress(0, i)
    110.  
    111.                 End If
    112.  
    113.             Next str
    114.  
    115.         End Using
    116.  
    117. End Sub
    118.  
    119.  
    120. Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
    121.  
    122.         ' update Progress bar with current reported value
    123.         Me.ProgressBar1.Value = DirectCast(e.UserState, Integer)
    124.        
    125. End Sub
    126.  
    127.  
    128. Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
    129.  
    130.         ' reset the Progress bar
    131.         ProgressBar1.Value = 0
    132.  
    133.         If (Not e.Error Is Nothing) Then
    134.             MessageBox.Show(e.Error.Message, "CNC transmission")
    135.         ElseIf e.Cancelled Then
    136.             MessageBox.Show("Cancelled!", "CNC transmission")
    137.         Else
    138.             MessageBox.Show("Completed!", "CNC transmission")
    139.         End If
    140.  
    141. End Sub

    This should keep the UI responsive, as all the transmission is being done in the background.

    Hope this helps.
    Last edited by Andy_P; Aug 6th, 2007 at 03:35 PM.
    Using Windows XP Home sp3
    Mucking around with C# 2008 Express
    while ( this.deadHorse ) { flog( ); }


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