|
-
Jul 27th, 2007, 04:29 AM
#1
Thread Starter
Junior Member
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
-
Jul 27th, 2007, 05:44 AM
#2
Re: Problems with COM ports
Try using my method here to send a files data using a binaryreader. See if it works better.
-
Jul 27th, 2007, 06:01 AM
#3
Thread Starter
Junior Member
Re: Problems with COM ports
 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.
-
Jul 27th, 2007, 07:04 AM
#4
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.
-
Jul 27th, 2007, 08:43 AM
#5
Thread Starter
Junior Member
Re: Problems with COM ports
 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
-
Jul 27th, 2007, 11:04 AM
#6
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.
-
Jul 27th, 2007, 05:44 PM
#7
Lively Member
Re: Problems with COM ports
Bosch CC220 requires 2 stop bits & RTS/CTS, flow control Xon/Xoff.
Microsoft Visual Basic 2008
-
Jul 28th, 2007, 04:21 AM
#8
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.
-
Jul 28th, 2007, 04:14 PM
#9
Lively Member
Re: Problems with COM ports
Microsoft Visual Basic 2008
-
Jul 30th, 2007, 02:53 AM
#10
Thread Starter
Junior Member
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.
-
Jul 30th, 2007, 04:26 AM
#11
Thread Starter
Junior Member
Re: Problems with COM ports
 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?
-
Jul 30th, 2007, 10:13 AM
#12
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.
-
Jul 31st, 2007, 02:54 AM
#13
Thread Starter
Junior Member
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
-
Jul 31st, 2007, 03:44 AM
#14
Re: Problems with COM ports
 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.
-
Jul 31st, 2007, 09:29 AM
#15
Thread Starter
Junior Member
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).
-
Jul 31st, 2007, 12:00 PM
#16
Re: Problems with COM ports
 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!
-
Aug 1st, 2007, 03:33 AM
#17
Thread Starter
Junior Member
Re: Problems with COM ports
 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
-
Aug 1st, 2007, 05:17 AM
#18
Thread Starter
Junior Member
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
-
Aug 1st, 2007, 12:22 PM
#19
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.
 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.
-
Aug 1st, 2007, 02:35 PM
#20
Thread Starter
Junior Member
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.
-
Aug 1st, 2007, 03:59 PM
#21
Re: Problems with COM ports
 Originally Posted by danweb
So I guess that it doesn't need before or after characters?
It would appear so, yes.
 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!
-
Aug 3rd, 2007, 02:33 AM
#22
Thread Starter
Junior Member
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...
-
Aug 3rd, 2007, 04:04 AM
#23
Thread Starter
Junior Member
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
-
Aug 3rd, 2007, 04:43 AM
#24
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!
-
Aug 6th, 2007, 04:02 AM
#25
Thread Starter
Junior Member
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...
-
Aug 6th, 2007, 06:25 AM
#26
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.
-
Aug 6th, 2007, 08:05 AM
#27
Thread Starter
Junior Member
Re: Problems with COM ports
Version 13 now out for testing
-
Aug 6th, 2007, 08:39 AM
#28
Thread Starter
Junior Member
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?
-
Aug 6th, 2007, 08:48 AM
#29
Re: Problems with COM ports
 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.
-
Aug 6th, 2007, 01:41 PM
#30
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:
' form level variables
Private filelines As List(Of String) = New List(Of String)
Private com As String = "COM3"
Private Sub btnTransmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTransmit.Click
' declare stream and streamreader
Dim fs As IO.FileStream = Nothing
Dim sr As IO.StreamReader = Nothing
' clear the List of strings
filelines.Clear()
' reset the Progress bar
ProgressBar1.Value = 0
Try
' displays the OpenFileDialog1 to the user
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
' defines sr as a FileStream and opens the filename from the OpenFileDialog1
fs = New IO.FileStream(OpenFileDialog1.FileName, IO.FileMode.Open)
' reads the sr filestream ino the stream reader (sr)
sr = New System.IO.StreamReader(fs)
' read each line of the file into the list of strings
Dim line As String
Do
line = sr.ReadLine
If line IsNot Nothing Then
filelines.Add(line)
End If
Loop Until line Is Nothing
' configure progressbar parameters
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = filelines.Count
' start background worker to perform COM port write operation
BackgroundWorker1.RunWorkerAsync()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
' close the stream and reader
sr.Close()
fs.Close()
End Try
End Sub
Private Sub btnCancelTransmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelTransmit.Click
' cancel transmit operation
If BackgroundWorker1.IsBusy Then
BackgroundWorker1.CancelAsync()
End If
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim worker As System.ComponentModel.BackgroundWorker = DirectCast(sender, System.ComponentModel.BackgroundWorker)
' sets up comPort as SerialPort and opens the port
Using comport As System.IO.Ports.SerialPort = My.Computer.Ports.OpenSerialPort(com)
' 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)
' set up counter variable
Dim i As Integer = 0
' writes each line of data to the comPort with pause after each block
For Each str As String In filelines
' check if operation has been cancelled
If worker.CancellationPending Then
e.Cancel = True
Exit For
Else
comport.WriteLine(str)
System.Threading.Thread.Sleep(20) ' 20 = 20 milliseconds
' increment counter for each line transmitted
i += 1
' report counter value to the ProgressChanged event
worker.ReportProgress(0, i)
End If
Next str
End Using
End Sub
Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
' update Progress bar with current reported value
Me.ProgressBar1.Value = DirectCast(e.UserState, Integer)
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
' reset the Progress bar
ProgressBar1.Value = 0
If (Not e.Error Is Nothing) Then
MessageBox.Show(e.Error.Message, "CNC transmission")
ElseIf e.Cancelled Then
MessageBox.Show("Cancelled!", "CNC transmission")
Else
MessageBox.Show("Completed!", "CNC transmission")
End If
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|