PORTS Forum

Ports and Interfaces => Serial Ports => Topic started by: btcomp on April 24, 2012, 05:23:46 pm

Title: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on April 24, 2012, 05:23:46 pm
I know this should be simple. But I haven't used serial ports in a while, but I bought a virtual RS-232 converter off Amazon, for a client connecting a moving machine, that moves in the x and y coordinates. Now I need to be able to write a text file that captures data that is transmitted when a sensor is activated and reads the x,y position of the movable flat machine.

I have created a loop back connector to the virtual port, now COM4. But I can't seem to get data into a VB variable so I can write it to a text file.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: Jan Axelson on April 24, 2012, 08:41:06 pm
If you just want to be able to read serial data from the machine, you could start with my COM port terminal application:

Lvr.com/serport.htm#my_example_code

Look at the DataReceived routine.

Jan
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on April 24, 2012, 10:39:02 pm
Thanks Jan,

I was looking at your code a few days ago, and I see that I could send the data to a text file in the DataReceived routine. I was looking at this program this afternoon, http://www.dreamincode.net/forums/topic/37361-serial-port-communication-in-vbnet/  too, which works also, but your DataReceived routine would be a good place to insert the text file write routine and you have shown where it could be added. Thanks.  :)
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on April 25, 2012, 10:10:55 pm
I put in the code for a simple text file:

Code: [Select]
Friend Sub DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs)

        Dim newReceivedData As String

        '*********************************************************BT-25Apr2012
        Dim FILE_NAME As String = "C:\RCMtools2012\rs232.txt"
        Dim objWriter As New System.IO.StreamWriter(FILE_NAME,true)
        '*********************************************************BT-25Apr2012
        Try
            ' Get data from the COM port.

            newReceivedData = selectedPort.ReadExisting

            ' Save the number of characters received.

            receivedDataLength += newReceivedData.Length

            RaiseEvent UserInterfaceData("AppendToMonitorTextBox", newReceivedData, Color.Black)

            '*********************************************************BT-25Apr2012
            objWriter.Write(newReceivedData)
            objWriter.Close()
            '*********************************************************BT-25Apr2012

This works great when I type in text. Now the Numerical Control Device will be hooked up instead of using the text box. I am thinking I need to modify the ProcessTextboxInput() procedure. As there isn't going to be any text input, just the text that is generated by the Numerical Control Device! I am not sure where I should be modifying the code!

Is there a way to send some test data through the RS232 cable and port?
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: Jan Axelson on April 26, 2012, 11:20:57 am
Make a copy of the ProcessTextboxInput routine and rename it, say, SendMyData.

Set userInput to the data you want to send.

Delete everything in the routine that has to do with the text box.

To send the data, call the routine.

Jan
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on April 26, 2012, 02:17:56 pm
Thanks Jan,

I have copied the procedure and will look at the userInput variable and see how to grab the RS-232 data.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on April 27, 2012, 08:40:28 pm
Jan, your program worked great at the company's shop today. I was pleasantly surprised that the data was just receiving, (in green) in the textbox. But the data was mostly gibberish with ? characters. Well the owner showed the man helping me what the settings were and then I discovered that I couldn't set a couple of parameters, just the baud rate and handshaking. So I did some programming while the man returned to his work and shortly had this.

                       
Code: [Select]
'**********************************************27Apr2012
                        ' The port parameters set here for RCMTools - to be sure they are correct.
                        SelectedPort.Parity = Parity.None
                        SelectedPort.DataBits = 7
                        SelectedPort.StopBits = StopBits.One
                        SelectedPort.Handshake = Handshake.None
                        '**********************************************27Apr2012

Then worked like a charm. Now this is hooked up to their Fadal CNC 88 controller which is connected to the Fadal VMC 4020 machine which position is being mapped and data sent through the RS-232 port and will be able to record the data nicely to a text file. The problem is the Fadal software on the same computer has to communicate through the same RS-232 port as Jan's program. There has to be a way for the Fadal program to let Jan's program know to turn off and vice versa. Jan's program ONLY needs to close it's port connection when the Fadal software on the computer is loading the program data into the CNC.

Note: I am not a Fadal programmer, though I would love to learn it, and if this project succeeds like it did today, I may be putting in more hours, here  ;D .

I am not sure if it is possible for the Fadal an Jan's program to communicate with each other. I am thinking perhaps something like a 'socket' which would allow communication between the two. I guess I am going to have to learn more about CNC programming?
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: Jan Axelson on April 28, 2012, 12:51:17 pm
Here is one article about sharing data between applications:

http://www.codeguru.com/csharp/csharp/cs_syntax/remoting/article.php/c6901/NET-Remoting-in-Visual-C.htm

I'm not an expert on this.

Jan
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on April 28, 2012, 01:32:48 pm
Thanks Jan, looks pretty complex, but will print out the text pages.  My local library has a couple of books on CNC which I am planning on picking up, so will review them to see if there is anything I can learn in the books that may help.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on May 05, 2012, 09:20:40 am
Well I am able to communicate with the CNC and I am thinking that I can upload the program code NC stuff, and your program has amazed me and the workers that it can talk to the CNC monitor. So I think that just using the Vb.Net may be the answer, then the RS-232 port can stay open all the time. I just have to learn more CNC and I got a bit familiar with uploading downloading and running the test program that is used to generate data for the text file. Crude yet, but I ordered your RS-232 book, even paid 3 dollars more on my Prime account to get it Monday. Well I'm at the shop on their dime so I will need to get busy, and brush up on my VB code and CNC code for this project! :)
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on May 09, 2012, 06:43:41 am
Well I am stuck with getting program code to be saved in the CNC controller. Normally a program called NCFadal is used. It is a serial communications program that you open the code (ex. below) and click 'to CNC' or 'from CNC' . I can get the code to show on the CNC screen but I can't get it to be saved as a program. Below is just the start and end code blocks. All programs start and end with a percent character. CR characters on each line.

The idea is to have the VB program sit on the desktop computer and whatever program the operator wants to use they choose it, the program uploads automatically and is ready to use at the CNC monitor. I could also have the VB program load the NCFadal program (and I already have that parameter in the line, but I can't find a way to get the CNC code (i.e. TestData.nc) as a paramter of the NCFadal program to then load into the CNC. That's the dilemma.

I seem to be missing some important serial communcication commands that are needed between the CNC and the desktop PC?

Code: [Select]
%
O1
(STOCK/BLOCK,0.000,0.000,0.000,-5.275,1.500,0.188)
( MILL: 4020_3 )
( 4.2530 Z HEIGHT OFF BED TO BOTTOM OF PART )
( 1.3750 PARALLEL HEIGHT )
( FRIDAY 4/27/12 11.05AM )
*
*PUT TOOL 500 IN SPINDLE
# SPRINT "POCKET-ID 1234"
# SPRINT "WALLS-PLUS-TOL 0.001"

,,,

#:END_WALL_SIZE_CHECK
G9
M5M9
* DONE *
T2M6
G52 X0 Y0 Z0
G00 H0 Z0
E0 X0 Y0
(POST UTILITY *8063*)
M02
%
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: Jan Axelson on May 09, 2012, 09:55:45 am
Unfortunately, I have no knowledge of NCFadal and thus no tips on how to save the program code.

Jan
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on May 09, 2012, 10:01:53 am
Thanks Jan,

I kind of figured this, being it was company specific. But I got a phone number to their technical support, so maybe I can get info that way. Will post if it is helpful here.  :)
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: Jan Axelson on May 09, 2012, 11:38:46 am
Good luck!

Jan
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on May 09, 2012, 11:40:55 am
Thanks Jan, I was thinking of this while on the treadmill this morning, maybe I can capture the RS-232 data coming out of the PC on com1 to the CNC88? I don't know if possible but will Google this?  :)
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on May 10, 2012, 03:47:08 pm
Okay, I made progress. I installed Serial Port Monitor 3.31 and found out interesting data on handshaking between the CNC 88 and the computer. I have tried to mimic the data. I will put down below the beginning part of the NCFadal listing followed by Jan's program that I have modified to send the test file. The beginning and ending parts are what are not the same. When the CNC is in command mode is when data transfer can occur. What starts is an 'A' or 41H sent from the computer. The CNC 88 returns an 'A'. When the CNC 88 sends the 'A' back then the PC starts it's transmission. Now when my program sends an 'A' the CNC 88 also sends back an 'A', BUT before my program can start sending it's data, the CNC 88 manages to sneak in a few more characters first. (See below)


This is the way it is supposed to go:  :)
Code: [Select]
Port opened by process "NCFadal.exe" (PID: 3536)

Request: 5/10/2012 3:14:36 PM.01864 (+27.0630 seconds)

 41                                                A               

Answer: 5/10/2012 3:14:36 PM.01864 (+0.0000 seconds)

 41                                                A               

Request: 5/10/2012 3:14:36 PM.01864 (+0.0000 seconds)

 40 0D 54 41 2C 31 0D 0A 25 0D 0A 4F 37 37 37 0D   @.TA,1..%..O777.
 0A 28 53 54 4F 43 4B 2F 42 4C 4F 43 4B 2C 30 2E   .(STOCK/BLOCK,0.
 30 30 30 2C 30 2E 30 30 30 2C 30 2E 30 30 30 2C   000,0.000,0.000,
Here is my program  :(
Code: [Select]
Port opened by process "COM Port Terminal.exe" (PID: 2596)

Request: 5/10/2012 3:12:27 PM.35964 (+60.0324 seconds)

 41                                                A               

Answer: 5/10/2012 3:12:27 PM.56264 (+0.2031 seconds)

 41 44 56 0D 0A 0D 0A                              ADV....         

Request: 5/10/2012 3:12:29 PM.67264 (+1.2344 seconds)

 40 0D 54 41 2C 31 0D 0A 25 0D 0A 4F 37 37 37 0D   @.TA,1..%..O777.
 0A 28 53 54 4F 43 4B 2F 42 4C 4F 43 4B 2C 30 2E   .(STOCK/BLOCK,0.
 30 30 30 2C 30 2E 30 30 30 2C 30 2E 30 30 30 2C   000,0.000,0.000,

And I am sending the block immediately after I send my 'A' (41H)
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: HDowns on May 24, 2012, 09:34:58 am
I would suggest to monitor a state of hardware flow control lines too (RTS/CTS). Usually CNC machines use these lines to control a data flow. I don't know can Serial Port Monitor 3.31 show it, but Advanced Serial Port Monitor 4 can.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on May 24, 2012, 11:18:31 am
Thanks HDowns. I see the free verison I have shows the green/red light at the bottom for RTS/CTS. But I don't see any data. How much is Advanced Serial Port Monitor 4 and is it downloadable? I
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on May 24, 2012, 02:44:34 pm
I found the Advanced Serial Port Monitor 4. I downloaded the free version, but it can't do anything. The advanced version is 60 dollars. I am wondering if there is a cheaper version that would do what we are looking for. This program has 'lots of bells and whistles' which is great, but it may be a bit overkill for the shop. It will be used a couple of times and then put aside.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: HDowns on May 25, 2012, 07:32:30 am
The trial version can also help you.
1. Switch it to the Spy mode.
2. In the program settings enable all system events.
3. Open the port
4. Start the NCFadal program

The monitor window should show you same as Serial Port Monitor, but will add some system events in red color.

It is possible it will help you.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on May 25, 2012, 10:44:31 am
Great, I will try it. Thanks. I will let you know.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on May 25, 2012, 03:23:58 pm
Below is the NCFadal.exe serial data. It 'Purge the serial port: RXABORT, RXCLEAR which my program doesn't do. So I am thinking that I have to do that in the code first. Will work on, only have an hour to figure this out today, but it's a start!

Code: [Select]
<20120525143207.458 SYS>
Purge the serial port: RXABORT, RXCLEAR
<20120525143207.880 TX>
% [len=1]
<20120525143207.880 TX>
<LF>O777 [len=5]
<20120525143207.880 TX>
<LF>(STOCK/BLOCK,0.000,0.000,0.000,-5.275,1.500,0.188) [len=51]
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on May 25, 2012, 05:29:43 pm
Okay, I am going to put in the successful NCFadal program start. The program: Purge the serial port: RXABORT, RXCLEAR, TXABORT, TXCLEAR

To send to Fadal CNC you type the TA,1 which you see near the end of the code, and the program code itself starts when you send a %

My program does not purge the ports nor turn on the DTR, it is the offstate in my code.
Code: [Select]
<20120525141323.189 SYS>
COM is open
<20120525141323.189 SYS>
In/out queue size 1024/512
<20120525141323.189 SYS>
Purge the serial port: RXABORT, RXCLEAR, TXABORT, TXCLEAR
<20120525141323.189 SYS>
Set timeouts: ReadInterval=-1, ReadTotalTimeoutMultiplier=0, ReadTotalTimeoutConstant=0, WriteTotalTimeoutMultiplier=0, WriteTotalTimeoutConstant=5000
<20120525141323.189 SYS>
Baud rate 9600
<20120525141323.189 SYS>
RTS off
<20120525141323.189 SYS>
DTR on
<20120525141323.189 SYS>
Data bits=7, Stop bits=1, Parity=Even
<20120525141323.189 SYS>
Set chars: Eof=0x1A, Error=0x3F, Break=0x3F, Event=0x00, Xon=0x11, Xoff=0x13
<20120525141323.189 SYS>
Handflow: ControlHandShake=(DTR_CONTROL), FlowReplace=(AUTO_TRANSMIT, AUTO_RECEIVE, ERROR_CHAR), XonLimit=256, XoffLimit=256
<20120525141323.189 SYS>
Purge the serial port: TXABORT, TXCLEAR
<20120525141323.189 TX>
A
<20120525141323.189 RX>
A
<20120525141323.189 SYS>
Purge the serial port: TXABORT, TXCLEAR
<20120525141323.189 TX>
@ [len=1]
<20120525141323.189 SYS>
Purge the serial port: RXABORT, RXCLEAR
<20120525141323.501 SYS>
Purge the serial port: RXABORT, RXCLEAR
<20120525141323.814 TX>
TA,1 [len=4]
<20120525141323.814 TX>
<LF>% [len=2]
<20120525141323.939 TX>
<LF>O777 [len=5]
<20120525141323.939 TX>

I hope I haven't confused everyone, but I see the advanced serial port program is valuable. I haven't figured out how to change my program, though I did add this to the ComPort module:

Code: [Select]
' PurgeComm function BT-25May2012

    Declare Function PurgeComm Lib "kernel32" (ByVal hFile As Integer, ByVal dwFlags As Integer) As Integer

Shop is closing, so I will send now, but monitoring.  :)
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: HDowns on May 26, 2012, 10:56:32 am
The DTR signal is important too, because it says the machine that it can send data.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on May 27, 2012, 10:19:22 pm
Yes, I will have to see if I can get the VB program to turn DTR on. Alternatively, if I could run another RS-232 program calling it from VB .Net, would be okay, in fact it may be the best way, loading the NC data program and also sending it on the RS-232 program. Then I can just use the VB program to list the different programming files to be used.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on June 01, 2012, 03:00:08 pm
Okay then all I would need to do is to:

Code: [Select]
SelectedPort.DtrEnable = True

Before I try communicating with CNC 88 controller?

I want to go into the shop, and be able to accomplish something. Or am I missing something. I think I tried this before I left last week, but haven't been able to get back there. I would like to go in Saturday morning and try this.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on June 02, 2012, 08:04:38 pm
The SelectedPort.DtrEnable = True works. In Jan's program it seems that it needs to be called inside the ComPorts.vb module. I will have to get inside the program more and see what is happening. For production I have hidden the buttons that allow you to change the parity, baud rate and other parameters, but made it visible again so I could see what is happening. One thing I had wrong was the parity was supposed to be even and I had none. That was a big mistake, duh! It should have Xon/Xoff as protocol for transferring data, and when I select it, and then go back it doesn't show that so will have to investigate.

The advanced serial port monitor program works great in showing the state of things. I am trying to use the statements:

       
Code: [Select]
ComPorts.PurgeComm(hFile:=1, dwFlags:=1)
        ComPorts.PurgeComm(hFile:=1, dwFlags:=4)

I am more upbeat on this. In fact I am thinking that somehow I sent a program to the CNC 88 controller, because my program called 777 is there. It's possible I did it with the NCFadal program but not sure. I have logged the data sent from my program in an appended file, so I grabbed it before leaving the shop.

I will be back on Monday, especially since I only have 6 more days to use the trial version of the software!  :)
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on June 04, 2012, 11:29:32 am
The DTR Enable works using the advanced monitor ports, but I can't seem to purge the ports. My code is below:

Code: [Select]
                        SelectedPort.DtrEnable = True
                                               
                        PurgeComm(hFile:=1, dwFlags:=2)
                        PurgeComm(hFile:=1, dwFlags:=8)
                        PurgeComm(hFile:=1, dwFlags:=1)
                        PurgeComm(hFile:=1, dwFlags:=4)
                       
I am wondering if I have the parameters wrong on the PurgeComm function)?
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on June 04, 2012, 02:16:13 pm
I am still puzzled about why I can't get the NC Fadal Code to go into the CNC 88. I made copies of both my attempt and the successful NCFadal.exe program. I have posted them on my website at:

My failed attemp: http://www.bdtcomp.com/rs232/bob4jun2012_131pm.html

NC Fadal successful program code transfer: http://www.bdtcomp.com/rs232/ncfadal4jun2012_135pm.html

The black text highlighted in yellow is from the Windows XP desktop. The black text is from the CNC 88

The red text is system events, as well as the greyed text which shows sys, Tx and Rx states.
 :)
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on June 04, 2012, 04:38:04 pm
As I finish up the day at the plant, I have been successful in uploading the programs, I removed two characters in the file, an 'A' and an '@' .  The reason I did this, is because the protocol instructions say nothing about these characters. Now you ask, WHY did I put them in to begin with? The reason was that I captured them with the port sniffing programs. So I am now able to get the code into the CNC 88 and they register as programs and appear to be good. There are two issues, one is that there is supposed to be one of two things that print on the CNC 88 screen when the program is loaded. If you run a Checksum (which I want to do at a future date) you get the message, 'TAPE IS GOOD', and without a checksum, which has been the norm here 'TAPE INPUT TERMINATED' . I don't get the message, rather the data stops near the end. I took some pictures with my phone, maybe I will upload these later.


2nd, I am not getting any characters in the port sniffing program now? I do get the red characters and I have put what I am getting on another web page:  http://www.bdtcomp.com/rs232/bob4jun2012_425pm.html

I have to consider that I have made progress, and I may have lost people here, but maybe their is a reincarnated Einstein that is seeing something here.  8)

I HAVE UPLOADED THE CNC 88 PICTURES!

[attachment deleted by admin]
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on June 12, 2012, 11:40:09 pm
I have SUCCESS! I was able to see the error of my ways, and I was able to get the protocol to properly start the upload to the CNC 88 and also to end. The start is TA,1 followed by line feed, carriage return then a %. The ending is a % followed by a line feed, carriage return. I also add BYE. I decided that the port must close between running the programs, and then using the OpenComPort method I can generate a unique file name to store probing data for each program. Pretty slick and thanks Jan.

Now I do have a problem in the ending. It seems that as long as the file uploaded is 3k or so, I get the whole program uploaded to the CNC and I get a proper termination message. But when the file is 7k, the formText variable is not sending the latter part of the file to the CNC 88 and then I don't get the proper termination, though the file will usually register as being loaded. Not sure I under formText as it seems to grab the datareceived data in chunks. I probably need to know more about RS-232 ports. I do have Jan's book so I will be studying it.

But just a happy success, because I did save three under 3k program files and I had success with the upload and with the datareceived from the probing part in the CNC.  8)
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on June 13, 2012, 07:29:53 am
I have been playing around with the program this morning, and wonder about the lines in ComPorts module. When I changed these values I was able to get more data read. I am going to try different values when at work, but I really need to understand what is going on here? This is in the OpenComPort method.

                       
Code: [Select]
SelectedPort.ReadTimeout = 5000
                        SelectedPort.WriteTimeout = 5000
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: Jan Axelson on June 13, 2012, 10:36:42 am
Start with Microsoft's documentation:

http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readtimeout
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.writetimeout

Jan
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on June 13, 2012, 10:45:38 am
Thanks Jan,

I'm in the shop and I was successful changing the WriteTimeout to 12000. I will read the documentation. The below is good for the demo I am going to do. It was driving me nuts yesterday until I realized that timing and real-world stuff has to be considered when working with computers!

Code: [Select]
SelectedPort.ReadTimeout = 5000
SelectedPort.WriteTimeout = 12000
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on June 21, 2012, 04:49:44 pm
After having success with the timeouts, I am now have another problem. You see the object of the program I'm using is to allow the VB.Net software to enable the old (yes old about 1985) CNC 88 to work with the PC, and currently it's connected to COM 1 of the XP Professional computer. For the most part this is fine, and the communications is at 9600 baud. Now CNC use what is called G-code, not an expert myself with this code. But what was possible in 1985 was the ability to send a new file, to the memory limited CNC 88. This is done directly by the path, (eg. C:\DATA\PROG1) which is easy. But I have been unsuccessful, getting errors and then also RS-232 errors. This led me to believe that for the path command to work, assumes the communication is at the command line of DOS.

So I am thinking that my program, (actually most is Jan's Serial Port Communication program, but which I have added and modified for this project. I have four forms now, having added a program listing form, though I don't think it's needed.

I have programmed at the command line in VB and C#, though it's not my favorite mode. Is it fairly easy to make a new VB.Net project and copy and paste most of the code. This has a good chance of working, though the CNC 88 manual does say that some Windows DOS may not work, in their 1999 legacy manual update.

I think with that I'm going to go home and think on this a bit and start writing a couple of small Console Applications to get used to using this type.

Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on July 16, 2012, 07:05:20 pm
I am now connecting to the CNC 88 controller (one of the company's oldest controllers) and able to send text data one line at a time, called 'drip-feed' which is probably the best way to work with the machine, and to be able to keep the machine running for hours.

Drip-feeding is as it sounds, think of an IV in someone to keep them alive, just continually adding fluid to a person. Now I am trying to turn on or off handshaking, as was suggested to me by a programmer of CNC controls. I was told to set handshaking to None when I got the Xoff signal

So I try something like this:

       
Code: [Select]
'Set a delay first and adjust the amt time needed. BT-14Jul2012
        Threading.Thread.Sleep(125)
        UserPort1.SelectedPort.Handshake = Handshake.XOnXOff

Below is what I found out on doing this, but this guy in Ohio, doesn't use .Net which my company wants to use. I don't know if this all makes sense. I wasn't really sure why you turn the handshake to None and then to Xon/Xoff?

Quote
Open your COM port and set the handshake property to "None".   This will let any Xon or Xoff characters pass through the serial port device driver, so you will be able to "see" the operator press the READ button.  Get your file ready to send, then wait for an Xon character to come in from the CNC.    As soon as you see an Xon, set the handshake property to "Xon/Xoff", then begin sending data.  Your software will send characters until your COM port control's output buffer is full, then it will stop until the buffer is near empty.  Your software will be perhaps several K-bytes ahead of where your CNC is during the transmission process.   Your software will finish sending the entire file well before the CNC gets the last of it, so DON'T CLOSE THE PORT when you're done sending until you're sure that the CNC has actually received the end of the program.  I usually watch the output buffer on the COM control and wait until there are zero characters left.   Closing the port before that time may interfere with the port's ability to handshake with the CNC.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: HDowns on July 17, 2012, 02:39:46 pm
If you'll set software flow control to XOn/XOff then a serial port driver will intercept Xon and Xoff characters and you'll not get in your code.

Software flow control is None - you can detect a time when an operator press the READ button

Software flow control is Enabled - the file will be sent to the machine in the drip-feed mode automatically and you will not need to control data flow manually by analyzing incoming data.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on July 17, 2012, 11:29:01 pm
HDowns, I believe I went and just turned on XOn/XOff completely. Now I can try that again, where I start with NONE and then change to XOn/XOff just before I start drip-feeding. By the way, I found a solution to the program stopping after one line. SPRINT sent drip-feed on CNC 88, mayber other machines too I don't know as of yet, causes program execution to go to the end on the CNC control, something I don't believe I want. SO I took out all SPRINT commands, and the machine danced perfectly, it did all the simulated probes. BUT no data to record. So, I believe Macros will help, not a perfect solution, but not a perfect world. I am going to try subprograms and I think this will work. But I will want to study the handshaking. I also may need to find a better insertion point for starting and stopping my data files. Presently when I want a new data file, I first close the port and then open it again. I do this though when no data is being sent. This may not be the best way of doing it, but at the time, I wasn't sure where else to do this. If I find a spot to do this that doesn't require the port to be closed I will move my routine there, I think that makes sense and I understand the ComPorts program a bit better than I did a month ago when I set that routine up. :-X
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: ydsjhb on July 23, 2012, 11:48:53 pm
If you just want to be able to read serial data from the machine, you could start with my COM port terminal application:

Lvr.com/serport.htm#my_example_code

Look at the DataReceived routine.

__________________

Sonnenbrille Ray Ban Damen (http://www.armanisonnenbrille.net/rayban-sonnenbrille-c-21.html)
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on July 24, 2012, 12:04:40 am
That's what I have done. And I succeeded. Now what I am not able to do in CNC Land, the land of computers in a real world of machines, is to read the SPRINT lines in DNC mode, or Direct Numerical Control, I believe. I am doing this using drip-feed method. You feed the cnc control with enough program code, to keep at least two lines of code visible on the monitor, analogy is the hospital patient on an IV.

What I discovered though is what is code G code, the data of CNC. The G31 command is a probing command. And you can use P1 P2 and P3 and you get back X Y Z data in these points. That works! Now I don't know if I can get the same measurements, but if I can then I can write the labels to match the P data.

If you are confused by this, so am I. But I intend to figure a way, because I can see data coming back in drip-feed and if so then it should be doable to both send instructions to the CNC as well as receive data back.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on July 26, 2012, 12:53:58 pm
Okay on the drip-feed method of DNC, I am able to get my data. The X, Y and Z coordinates of the location of a probe gives three dimensional information. The DataReceived method is working, (i.e. X1.45Y-2.5Z1.555T). The info is there, I just have to format it, no big deal. HOWEVER, in drip-feed as the name implies I am adding to the data going in. Now I want to either create a new file to store DataReceived when a new file is loaded and sent to the CNC controller or at least put in a statement separately the data.

Below is my code:
Code: [Select]
Friend Sub DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs)
        Dim newReceivedData As String
        '*********************************************************BT-25Apr2012
        ' Dim FILE_NAME As String = "C:\RCMTools2012\rs232" & TimeOfDay.Ticks.ToString & ".txt"
        Dim objWriter As New System.IO.StreamWriter(FileName, True)
        '*********************************************************BT-25Apr2012
        Try
            ' Get data from the COM port.s

            newReceivedData = SelectedPort.ReadExisting

            ' Save the number of characters received.

            ReceivedDataLength += newReceivedData.Length

            RaiseEvent UserInterfaceData("AppendToMonitorTextBox", newReceivedData, Color.Black)
       
            '*********************************************************BT-25Apr2012
            objWriter.Write(newReceivedData)

            objWriter.Close()
            '*********************************************************BT-25Apr2012
 
        Catch ex As Exception
            DisplayException(ModuleName, ex)
        End Try

    End Sub

I can't seem to figure how to add data to the open text file that is being written with data on the RS-232 port. I should also add that I create a new text file when I open the RS-232 port, COM 1. I had intended to close and open the port to create a new file. That isn't going to work here, as I will need to keep the port open during drip-feed.

The procedure is to Start the CNC controller by physically pressing the 'Green' start button. That is the only manual process. Once this happens, the process should continue, drip-feeding. When the 'Green' start button is pressed the port will be closed and opened and stay opened until the drip-feed is done, which may last just a few minutes, but more than likely will continue several hours.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on August 01, 2012, 08:08:10 pm
Wow, a lot of progress since I wrote just a few days ago. I have my data from the computer sending to an array the data sent to the CNC controller. Now the received data is coming and I also send it to an array in the ComPorts module. I access the ComPorts array and send the X, Y and Z coordinates values into a string variable from the array CNCX(200), CNCY(200) & CNCZ(200) as strX, strY and strZ. But the values are blank in my textfile. I am thinking that, actually know that the file is being written before I can get to the data, but tried to put a pause in the file I am writing to text and appending as the the data coming from DataReceived takes longer, by using  a While-End While loop. I tried checking for 'empty string', 'null' or 'nothing' but that isn't working. I get errors telling me

I may have to just write the file separately in the ComPorts module and then combine the two files later in time, when the cnc milling machine has caught up to the processed code! They let me stay here at the shop by myself, but going to go and get dinner and work on tomorrow. I think I am almost there, if I could just get my main program to slow down and smell the roses so to speak and wait for the DataReceived to catch up. :)

I put in some code belowl

Code: [Select]
'TESTING- SEND Array Data to a file.
        Dim strX As String  'Testing this. BT-1Aug2012
        Dim strY As String
        Dim strZ As String = ""

        Dim objArrayFile As New System.IO.StreamWriter("C:\DripFeed\files\array_trial1.txt", True)
        Dim Count As Integer
        For Count = 1 To no
            'This may have to be modified. I am going to try it tonight & if successful go home and research. BT-1Aug2012 in Romeo, MI
            '  While UserPort1.CNCZ(Count) = Nothing

            '  End While

            strX = UserPort1.CNCX(Count)
            strY = UserPort1.CNCY(Count)
            strZ = UserPort1.CNCZ(Count)

            While strY.Length <= 0
                strY = UserPort1.CNCY(Count)
            End While


            objArrayFile.Write("Probe No. = " & Count.ToString & " " & Prgm(Count) & vbCrLf & SprintTxt(Count) & vbCrLf & SprintD1(Count) & " " & strX _
                               & vbCrLf & SprintD2(Count) & strY & SprintD3(Count) & " " & strZ & vbCrLf & vbCrLf)





        Next

        objArrayFile.Close()
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on August 02, 2012, 05:15:35 pm
Okay, Progress! today! I finally got it. The CNC data is being sent to the CNC control and I'm getting back data from the DataReceived procedure and two things worked. One, my arrays though I could access the variables weren't loading with data. And I not only had to make them Public but also Shared. I will have to study the terminology more, but I tried this and it worked. Code below:


Code: [Select]
Dim PrgmNam As String = "M"
    Dim SubNo As Integer = 0
    Dim no As Integer = 0
    ' Dim RevCam(200, 200, 200, 200, 200, 200, 200) As String
    Public Shared Prgm(200) As String
    Public Shared SprintTxt(200) As String
    Public Shared SprintD1(200) As String
    Public Shared SprintD2(200) As String
    Public Shared SprintD3(200) As String

Now the other thing that was causing problem was the way I was trying to read the array! Think (http://forum.bdmoo.com/Smileys/default/turtle.gif) and the (http://forum.bdmoo.com/Smileys/default/053.gif) . I was trying to read both the data I sent, and receive when the computer was done, but the machine was way behind. So I reversed this, and created both sets of arrays but read them as the DataReceived came in. This of course had to be done in the raw form as the CNC 88 is not capable of sending any data back in what's called DNC or a direct line by line drip-feeding. Fortunately programmers design the software and hardware that runs these machines, who else! So I was able to do this. Now the work begins. I don't know if the firm knows how much, but I'm sure there is lots. And I still have to fine tune what I have already.

Thanks Jan for your serial port program, as it has been the workhorse making this work.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: Jan Axelson on August 02, 2012, 10:16:33 pm
Glad to hear of your success! Thank you for sharing what you learned.

Jan
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on September 06, 2012, 09:08:06 pm
Well I have been making progress with this program, and was able to actually change data sent to the RS-232 port after data has been flowing. But I believe this was done after I finished sending all the data I had to the CNC controller. The trick now is to be able to jump around in the program based on the data coming back from the CNC controller. I have been able to monitor the slow tortoise, milling machine as the fast hare PC sends it's data. So now I just take away the data after a analysis point is needed, and I'm trying to wait for the data to come back after reading all the data I send to the CNC controller.

The problem is the milling machine slows way down for me as I stop the data flow and compare the data number from the CNC controller, which is 15 for testing. The data sent to the CNC is stopped after data number 15 also is sent. I have been putting in message boxes to see what is happening, and I am getting numbers in the millions for the number of times the data is being compared to see if the CNC controller has sent back 15 data points.

One thing I am going to do, and have done, is try to slow the computer way down in sending just a few instructions more than the CNC needs. There needs to be at least a couple of data lines for the CNC controller to be happy theoretically. It's buffer of course can handle much more than that.

I am also finding that if I have message boxes in the program, when I click ok on them, the milling machine responds quicker and goes through it's motions faster. So I do believe I need to throttle the speed the data is going to the CNC.

But if there is anything that I might help in improving the communication to the serial port that would be helpful. That is the part of the program that is giving me some grief. And though I am trying to get the other people in the project to actually do some milling so I can get some real data, for the present time I have to be happy with just simulating the milling without actually cutting any steel.  :)
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on September 23, 2012, 11:15:12 am
I've been looking at the old posts on my thread and am thankful for your program Jan. I have been able to get data into the CNC milling machine, whether it be a straight file, or a bunch of files from a hard-drive or a network if need be (more a future part of this). I have had to put a while loop to possibly wait when control signals such as DC1 or DC3 are sent from the controller Xon/Xoff or ASCII 17 and ASCII 19 respectively. That's a must and will test this. I have been just partially successful in making an in process change. This has been tricky. And the guy working on the probe to test a milled hole has done very well on his probe. I have put in a routine to compare the RS-232 raw data as it comes in. This continues to be a painstaking adventure, since I am Regex, from a library book I borrowed. One new instance, for example is data that came in as .0000000E 9 [oops] didn't know the machine was capable of scientific notation. Not a biggie, but will have to add.

NOW, I am finding that I really didn't stop the text coming into MainForm, but rather just hide it. I like seeing the data in the RichTextBox for testing, and just hide it for now when I don't want to see it. BUT was is happening at the end is the text in the textbox is going into the AccessForm method, which I am just trying to get a feel for. I don't want that sent back to the CNC since it is the data that I wanted and not the what the machine needs.

So the first thing the machine sends me is a DNC which is the first thing I send for DripFeed which is what you have to do start DNC DripFeeding. So when the UpdateStatusLabel sends DNC after all the current data has been sent to the CNC controller, it starts to send what is in the RichTextBox. NOT what I want!

I suppose I could just delete the text in the textbox when the data sent to the CNC controller is presently done, but maybe just not sending data to the textbox at all is best! Not sure! I know this will make the company's day and Dakota who is the smart young man who has done the electronics on the probe happy. The routine to compare the data to a reference file I have spent a lot of time on and I am anxious to get this incorporated, so I can have the machine make the intelligent choice of 'what to do next'.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: Jan Axelson on September 23, 2012, 11:53:26 am
Just comment out the code that sends the text to the textbox.

It sounds like you've made a lot of progress in your project!
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on September 23, 2012, 12:09:55 pm
Thanks Jan. That will be the answer, I will put a toggle in so that for testing I can see the data otherwise just cancel.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on October 09, 2012, 09:09:50 pm
Lots of progress made on this project. And I do have the project working where the milling machine will do one of two things depending on the data received. This is cool. What I mean is two weeks ago I ran six points with the wireless probe made by Dakota, young college student. And I compared them to values with a reference file to within 0.001 inches. It checked and the machine sent a PRINT statement, "SUCCESS" and stopped the milling machine. Repeated the test and manually touched the probe with my hand during testing, effectively causing the run to fail, and it sent "DATA NOT WITHIN TOLERANCE" and it ran one more probe point.

Okay, hardcoding worked. But I can't get the MainForm to work. Code below.

What happens with the code is that it is ignored, because I don't think it has any values. I get this error message in the textbox of the MainForm.
'Exception: Object reference not set to an instance of an object Module ComPorts Method DripFeeedCNCDataParts

I commented out the direct WriteToComPort method. It will work if I put in local values, I just can't get it to work with the MainForm values I have in arrays!



 
Code: [Select]
'******************************************************************************************BT-25Sept2012********************************
            'MessageBox.Show(BoolMustBePerfect & " x = " & x & "UBound(file2Data) = " & UBound(file2Data))
            If BoolMustBePerfect = True And x = UBound(file2Data) - 1 Then
                '  MessageBox.Show("This should be what happens")
                WriteToComPort("#PRINT" & Chr(34) & "THIS IS BEGINNING TO BE A SUCCESS" & Chr(34) & vbCrLf)

                WriteToComPort("#PRINT" & Chr(34) & "JUMP TO NEXT PART OF THE PROGRAM" & Chr(34) & vbCrLf)

                ' WriteToComPort(MainForm.strStoreRestString) 'FOR TESTING ONLY!! BT-21Sept2012


                WriteToComPort("M02" & vbCrLf)

            ElseIf BoolMustBePerfect = False And x = UBound(file2Data) - 1 Then
                '  MessageBox.Show("Why did this happen?")
                WriteToComPort("#PRINT" & Chr(34) & "THE DATA WAS NOT WITHIN TOLERANCES!" & Chr(34) & vbCrLf)

                WriteToComPort("#PRINT" & Chr(34) & "RUN THE NEXT INCREMENT" & Chr(34) & vbCrLf)

                '  WriteToComPort("T2M6" & vbCrLf)

                '  WriteToComPort("G0 H99 Z0.100" & vbCrLf)
                ' WriteToComPort("G0 X1.8333 Y-1.5975" & vbCrLf)
                ' WriteToComPort("G01 Z-0.187 F30.0" & vbCrLf)
                ' WriteToComPort("G01 G31 F1.0 X1.8333 Y-1.7475 P1" & vbCrLf)
                ' WriteToComPort("G0 X1.8333 Y-1.5975" & vbCrLf)
                'WriteToComPort("T1M6" & vbCrLf)

                'WriteToComPort("M02" & vbCrLf)
             
               
                 Dim strProbeAgain As String = MainForm.DripFeedCNCDataParts(MainForm.strProbe(1, 1))
                strProbeAgain = MainForm.DripFeedCNCDataParts(MainForm.strProbe(1, 1))
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on October 18, 2012, 08:26:46 pm
I have found that XModem has been used by the company's software successfully. I looked into that option. Most say to use Xon/Xoff, but the parameters are given for both. Is it possible to do that with the SerialPort object?
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: Jan Axelson on October 18, 2012, 08:51:56 pm
Xmodem is a file-transfer protocol that adds error checking.

Xon/Xoff is a flow-control protocol to manage when the sender can send to the receiver.

You can use both together.

What line of code causes the Object reference not set to an instance of an object error?
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on October 18, 2012, 09:30:26 pm
In the case of the CNC I can use either but not both at the same time. I have been sending in Xon/Xoff but I don't think it would be too difficult to put in a separate module to do this in Xmodem and have both options. DNC is used for Xon/Xoff and DNCX is used for Xmodem. Most of the guys in the shop use the Xmodem, though the programmers have told me they mostly use Xon/Xoff. The problem is on the older CNC controller, I am working with one of the older ones from the 1990s I am thinking that it isn't working properly in Xon/Xoff, since I can't get the DC1/DC3 from the controller, only on rare occasion. The newer machines seem better able to handle both. The below was run on one of the newer CNC machines. I had the machinist run both Xon/Xoff so my port sniffer could take a look. Below is the Xmodem results.

Request: 10/16/2012 3:42:21 PM.39364 (+0.0000 seconds)


 40 0D 44 4E 43 58 2C 30 2C 30 2C 30 0D 0A         @.DNCX,0,0,0..  


Answer: 10/16/2012 3:42:23 PM.01864 (+2.0000 seconds)


 44 4E C3 D8 AC 30 AC 30 AC 30 8D 0A 15            DN秘񦏎0..   


Request: 10/16/2012 3:42:23 PM.01864 (+0.0000 seconds)


 01 01 FE 25 0D 0A 0D 0A 0D 0A 47 31 37 47 38 30   ..%......G17G80
 47 39 30 47 38 45 31 0D 0A 4F 32 28 44 45 54 5F   G90G8E1..O2(DET_
 30 36 30 32 29 0D 0A 28 54 4F 4F 4C 30 2E 31 38   0602)..(TOOL0.18
 37 35 44 49 41 30 2E 30 39 33 37 52 41 44 29 0D   75DIA0.0937RAD).
 0A 47 31 54 32 4D 36 46 31 30 30 2E 0D 0A 53 34   .G1T2M6F100...S4
 32 30 30 4D 33 0D 0A 47 34 33 48 32 5A 33 2E 37   200M3..G43H2Z3.7
 30 38 31 4D 38 0D 0A 47 31 58 2D 30 2E 33 37 35   081M8..G1X-0.375
 59 31 2E 38 37 35 46 31 30 30 2E 0D 0A 5A 33 2E   Y1.875F100...Z3.
 37 30 38 88                                       708ˆ           


Answer: 10/16/2012 3:42:23 PM.04964 (+0.0000 seconds)


 06                                                .               


Request: 10/16/2012 3:42:23 PM.04964 (+0.0000 seconds)


 01 02 FD 31 0D 0A 5A 33 2E 32 39 0D 0A 47 31 5A   ..1..Z3.29..G1Z
 33 2E 30 39 46 32 30 2E 0D 0A 47 31 58 2D 30 2E   3.09F20...G1X-0.
 33 35 34 33 46 33 30 2E 0D 0A 58 2D 30 2E 32 33   3543F30...X-0.23
 36 32 0D 0A 58 32 2E 38 37 35 0D 0A 47 31 59 31   62..X2.875..G1Y1
 2E 38 37 31 34 5A 33 2E 30 39 30 36 46 32 30 2E   .8714Z3.0906F20.
 0D 0A 58 32 2E 38 37 34 38 59 31 2E 38 36 37 38   ..X2.8748Y1.8678
 5A 33 2E 30 39 0D 0A 47 31 58 2D 30 2E 33 37 35   Z3.09..G1X-0.375
 46 33 30 2E 0D 0A 47 31 59 31 2E 38 36 34 32 5A   F30...G1Y1.8642Z
 33 2E 30 15                                       3.0.           


Answer: 10/16/2012 3:42:23 PM.08064 (+0.0000 seconds)


 06                                                .               
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on October 19, 2012, 11:01:21 am
Okay, thanks Jan. I guess what I need to do is write another module, so that my program can do both Xon/Xoff and add an XModem file-transfer protocol. I am at work today, so I am going to try to simulate the Xmodem on the old machine. One guy was running in DNC XModem, but unfortunately my port sniffer program wasn't on, otherwise I could have captured it. But I am going to try to do a dry run with it.

What line of code causes the Object reference not set to an instance of an object error?

Okay, I first have strProbeAgain setup here at the beginning of the ComPorts class.
 
Code: [Select]
[Public Class ComPorts
    Dim FileName As String  'Make this variable available to all the methods in this class. BT-12Jun2012
    Public Shared BoolMustBePerfect As Boolean = True
    Public strProbeAgain As String = ""

I think what is happening is in the code below is a variable scope problem. I really need to read up on Public, Friend Sharing. The strProbeAgain variable is supposed to have the Probe File data stored in an array in the MainForm Class and because the variable is not appearing to be defined. I have had this happen several times before and had to change the scope and placement of a string, decimal, integer or array variable Below is the code from the ComPorts module:
Code: [Select]
'Try this - Send the program to MainForm to do more data. If this doesn't work will have to copy the MainForm
                ' procedure into ComPorts. BT-6Oct2012
                ' MainForm.strFile = "Give this a value"
                'MainForm.DripFeedCNCDataParts()
                '  Dim strProbeAgain As String = MainForm.DripFeedCNCDataParts(MainForm.strProbe(1, 1))
                strProbeAgain = MainForm.DripFeedCNCDataParts(MainForm.strProbe(1, 1))

                WriteToComPort(strProbeAgain)
                ' MessageBox.Show(strProbeAgain)
                '  WriteToComPort(MainForm.DripFeedCNCDataParts(MainForm.strProbe(1, 1)))
                '  MainForm.DripFeedCNCDataParts(MainForm.strProbe(1, 1)) 'Hardcoded for testing on Tues. 9Oct2012
                ' MessageBox.Show(MainForm.DripFeedCNCDataParts(MainForm.strProbe(1, 1)))
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: Jan Axelson on October 19, 2012, 01:01:34 pm
In my ComPortTerminal example, take a look at the AccessFormMarshal routine and associated code, which passes data to a form for display.

http://www.lvr.com/serport.htm#my_example_code

Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on October 19, 2012, 02:07:31 pm
Thanks Jan, and I went out to the truck and grabbed my Murach's VB 2008 book on myBase and see some good info. As I said I have had this happen before, and often I will put messagebox.show statements in that just flat get ignored when I try to see what they say and the variables that I thought  :o should have the data I need, just aren't 'scoped' for it.  :)
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: Jan Axelson on October 19, 2012, 02:18:14 pm
Yes, it can take some research to get it right!
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on October 23, 2012, 11:53:37 am
Below are the variables that I have defined in MainForm.  I have them outside any sub or function, because they may and are used throughout running the program, so their values have to persist.

Code: [Select]
'Analyze the REVCAM parts and put them into appropriate arrays.
    Public Shared strProbe(50, 5) As String
    Public Shared strRef(50, 5) As String
    Public Shared strMill(50, 5) As String
    Public Shared FixAtt(50, 20) As String
    Public Shared strPrgmUpToFirstRevCam As String = ""
    Public Shared strPrgmLastLines As String = ""
    Public Shared PockNoCnt As Integer = 1


 In the ComPorts module I have only tried to use the strProbe(50,5) array for testing. So instead of returning string data in the strProbe in the array, instead of sending data to the WritetoComPort function, the function isn't run and hence I don't get a Message for the strProbeAgain value in strProbe(1,1) is 'not defined' since the array itself isn't defined while in ComPorts module.

Code: [Select]
strProbeAgain = MainForm.DripFeedCNCDataParts(MainForm.strProbe(1, 1))
WriteToComPort(strProbeAgain)
MessageBox.Show(strProbeAgain)

I am having a hard time understanding the scope of the variables.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on October 23, 2012, 03:33:45 pm
Good news and bad news, and the bad news isn't really bad. But the bad news is I don't understand all there is about variable scoping and the inheritance of using MyBase, polymorphism, MyClass ...

But the good news is I finally figured out the problem. So the code I had:
Code: [Select]
strProbeAgain = MainForm.DripFeedCNCDataParts(MainForm.strProbe(1, 1))
WriteToComPort(strProbeAgain)
MessageBox.Show(strProbeAgain

did not need to have the DripFeedCNCDataParts at all. I think I had a problem a couple weeks ago with a variable scope at the time and fixed that problem but didn't update the above code. So when I ran the below code the variable was Public Shared whereas above ONLY the MainForm.strProbe(1,1) was Public Shared, and DripFeedCNCDataParts was just Public.

An easy solution. Now I can work with the arrays, that I spent time building directly!

Thanks Jan for your help on this. I still want to learn more about OOP and Inheritance, but I am going to go home happier.
P.S. And even happier after the election is over, whomever wins too, not to be political!


               
Code: [Select]
strProbeAgain = MainForm.strProbe(1, 1)
                WriteToComPort(strProbeAgain)
                MessageBox.Show(strProbeAgain)
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on October 23, 2012, 04:18:02 pm
I still may need to use the MyBase on the procedure that filters the CNC data. I am going to test this in the next hour. As the data contains statements that are filtered in MainForm but I am calling it from ComPorts, and it is only Public. But it is just a procedure so I think I may get my hands dirty on MyBase anyway. Will post later if I can't get this to work today.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on October 23, 2012, 05:47:30 pm
Yep, I will have to do something. The array data is fine, but it has to be filtered and the MainForm class function DripFeedCNCDataParts takes the data that comes through each line and filters out lines that start with parenthesis ( or asterisk * ... and these lines are not sent to the CNC because they are not allowed in DNC mode.

I could just copy the procedure over to the ComPorts but that isn't the way to do it. So there is always another step.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: Jan Axelson on October 23, 2012, 10:19:49 pm
Here is a tutorial that covers marshaling data to a form:

http://www.codeguru.com/csharp/csharp/cs_syntax/threading/article.php/c10755/Safe-Multithreading-with-the-BackgroundWorker-Component.htm

And again, in my ComPortTerminal example, take a look at the AccessFormMarshal routine and associated code, which passes data to a form for display.

http://www.lvr.com/serport.htm#my_example_code
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on October 24, 2012, 12:21:33 am
Thanks Jan, I have printed the article and will look at your example again. I had trouble understanding the MyBase but I think with the extra resource you posted I should be able to make this work. The data is there, I see it in my messagebox, but in DripFeed mode, many of the machines are restricted to just the data, so my dripfeed method filters it.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on October 25, 2012, 11:42:35 am
I am going to put some breakpoints in your AccessFormMarshal method. I am still having a hard time understanding this. But I guess I need to know how to do this, so that I can call my 'filtering dripfeed routine that is the MainForm, because I am sending additional data on the RS232 port directly from the ComPorts module.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on October 25, 2012, 04:19:04 pm
I still must be doing things wrong. However, I haven't seen that I have an error showing. I just am not going to the DripFeedCNCDataParts routine or perhaps I am not getting out of the loop. I can't debug on the machine, and I haven't been able to get an old Windows 98 computer to communicate with my Laptop through an RS232 cable that connects the two, if I could do that I could probably test this part of the program at home, which would be ideal for me.

Below is the code that is supposed to trigger the RaiseEvent. I don't know if it does, but the line underneath, that shows a MessageBox, and lists the contents of the string does not show when the RaiseEvent line is added. Without the line it does.

Code: [Select]
ElseIf BoolMustBePerfect = False And x = UBound(file2Data) - 1 Then
                '  MessageBox.Show("Why did this happen?")
                WriteToComPort("#PRINT" & Chr(34) & "THE DATA WAS NOT WITHIN TOLERANCES!" & Chr(34) & vbCrLf)

                WriteToComPort("#PRINT" & Chr(34) & "RUN THE NEXT INCREMENT" & Chr(34) & vbCrLf)

                '  WriteToComPort("G0 H99 Z0.100" & vbCrLf)
                ' WriteToComPort("G0 X1.8333 Y-1.5975" & vbCrLf)
               
               
                strProbeAgain = MainForm.strProbe(1, 1)

                RaiseEvent FilterNCCode(strProbeAgain) 'BT-25Oct2012

               
                ' WriteToComPort(strProbeAgain)


                ' WriteToComPort(MainForm.DripFeedCNCDataParts(strProbeAgain))
                MessageBox.Show(strProbeAgain) 'Comment out again, so as not to be a

I posted four snapshots of where I added code so that I could run: RaiseEvent FilterNCCode(strProbeAgain) 'strProbeAgain should have the filtered data to send to the RS232 port. This routine also sends the data to the port, so I have commented the 'WriteToComPort here.

[attachment deleted by admin]
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on October 26, 2012, 03:50:48 pm
Okay it really is working. I had a mistake in my third image in my last post, as I had left out one line, so I have the fix below. ALSO, I changed my DripFeedCNCDataParts from a function to a sub, and the other parts also were of course changed to a sub, didn't really need this as a function. The data was processed and sent, though I do get an error on the CNC machine, but it really is sending and I assume doing some multithreading.

 
Code: [Select]
Private Sub AccessFormMarshal(ByVal action As String, ByVal formText As String, ByVal textColor As Color)

        AccessFormMarshalDelegate1 = New AccessFormMarshalDelegate(AddressOf AccessForm)
        Dim args() As Object = {action, formText, textColor}

        ' Call AccessForm, passing the parameters in args.

        MyBase.Invoke(AccessFormMarshalDelegate1, args)

    End Sub


    Private Sub DripFeedCNCDataPartsMarshal(ByVal strFile As String)
        DripFeedCNCDataPartsMarshalDelegate1 = New DripFeedCNCDataPartsMarshalDelegate(AddressOf DripFeedCNCDataParts) 'Added this BT-26Oct2012

        Dim args() As Object = {strFile}
        ' Call DripFeedCNCDataParts, passing it the one parameter
        MyBase.Invoke(DripFeedCNCDataPartsMarshalDelegate1, args)
    End Sub
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on October 27, 2012, 12:13:54 pm
At the shop this Saturday and I have fixed the error that occurs, on the CNC controller side. The multithreading is working great. The command I have setup is telling the controller to rerun the Probe data strProbe(1,1) and it is hard coded here for now. The first filtered data that goes into the RS232 port is supposed to be T2M6 followed by a VBCrLf. But the port sniffer showed the first character lopped off so that 2M6 only was sent. (For those that familiar with CNC Milling T1M6, T2M6, T3M6 ... tells the mill to get the tool in location 1, 2, 3 ...

The solution to this for now is to insert a blank line in front of the data being sent so that I am sending WriteToComPort("   " & VBCrLf)  or in my case, I may need to just put this line in whenever the program first sends data in my DripFeedCNCDataParts routine. I am going to add that.

Now I will have to see if my strRef(50,5) array data will parse correctly. I have been using a text file as my test, but this will not be hard, it's not rocket science.

Finally, I am thinking that I should put in an Xmodem method for this. The reason being is that I am thinking the older CNC machines will work better for extremely long runs, 10 or more hours or even days. So that is going to be a bit of a challenge. I know that 132 bytes are sent, with 128 used for data and the last four to work with the checksum. I have found an XModem module to look at, and I have sample port-sniffing data for this. The CNC controller sends back an 06Hex as my port-sniffing program has shown.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on October 28, 2012, 08:51:41 pm
The owner of the tool shop is concerned with the time taken on this project, and though I believe I have made lots of progress, you know time is money to people. Sometimes I think we programmers are not understood and I know the owner doesn't and I don't believe anyone in the shop knows, though Dakota working on the wireless probe for this project does. The owner seems to believe that the Xon/Xoff is not working and wants to know how long it will take to do this in XModem. And I am not going to try to explain to him the difference because he doesn't really understand all this. I am just a geeky guy and that is all he knows. The whole shop guys and a couple gals are a great bunch of people so I am not complaining, and times are tough I was happy to be employed on this project and I hope he doesn't think I am just wasting his money.

SO I am thinking that XModem with 128 bytes of data with 4 bytes for using for Checksum, though I am not sure how I am going to do this, but will research this. I think the program can easily be modified to add a routine to send the data piecemeal in 128 byte chunks, and this is after the initial coding DNCX 0,0,0 is sent. The parameters are optional. There is a mandatory 2 second delay, I have been adding about 2.5 seconds minimum myself. But since I have the program already setup to send line by line and now character by character I don't see any problem with 128 byte chunks, filling empty bytes with either zeros or spaces.

I am posting a sample that I captured off a newer CNC controller.
Quote
Port opened by process "NCFadal.exe" (PID: 57728)


Request: 10/16/2012 3:42:21 PM.39364


 41                                                A               


Answer: 10/16/2012 3:42:21 PM.39364 (+0.0000 seconds)


 41                                                A              


Request: 10/16/2012 3:42:21 PM.39364 (+0.0000 seconds)


 40 0D 44 4E 43 58 2C 30 2C 30 2C 30 0D 0A         @.DNCX,0,0,0..  


Answer: 10/16/2012 3:42:23 PM.01864 (+2.0000 seconds)


 44 4E C3 D8 AC 30 AC 30 AC 30 8D 0A 15            DN秘񦏎0..   


Request: 10/16/2012 3:42:23 PM.01864 (+0.0000 seconds)


 01 01 FE 25 0D 0A 0D 0A 0D 0A 47 31 37 47 38 30   ..%......G17G80
 47 39 30 47 38 45 31 0D 0A 4F 32 28 44 45 54 5F   G90G8E1..O2(DET_
 30 36 30 32 29 0D 0A 28 54 4F 4F 4C 30 2E 31 38   0602)..(TOOL0.18
 37 35 44 49 41 30 2E 30 39 33 37 52 41 44 29 0D   75DIA0.0937RAD).
 0A 47 31 54 32 4D 36 46 31 30 30 2E 0D 0A 53 34   .G1T2M6F100...S4
 32 30 30 4D 33 0D 0A 47 34 33 48 32 5A 33 2E 37   200M3..G43H2Z3.7
 30 38 31 4D 38 0D 0A 47 31 58 2D 30 2E 33 37 35   081M8..G1X-0.375
 59 31 2E 38 37 35 46 31 30 30 2E 0D 0A 5A 33 2E   Y1.875F100...Z3.
 37 30 38 88                                       708ˆ           


Answer: 10/16/2012 3:42:23 PM.04964 (+0.0000 seconds)


 06                                                .              


Request: 10/16/2012 3:42:23 PM.04964 (+0.0000 seconds)


 01 02 FD 31 0D 0A 5A 33 2E 32 39 0D 0A 47 31 5A   ..1..Z3.29..G1Z
 33 2E 30 39 46 32 30 2E 0D 0A 47 31 58 2D 30 2E   3.09F20...G1X-0.
 33 35 34 33 46 33 30 2E 0D 0A 58 2D 30 2E 32 33   3543F30...X-0.23
 36 32 0D 0A 58 32 2E 38 37 35 0D 0A 47 31 59 31   62..X2.875..G1Y1
 2E 38 37 31 34 5A 33 2E 30 39 30 36 46 32 30 2E   .8714Z3.0906F20.
 0D 0A 58 32 2E 38 37 34 38 59 31 2E 38 36 37 38   ..X2.8748Y1.8678
 5A 33 2E 30 39 0D 0A 47 31 58 2D 30 2E 33 37 35   Z3.09..G1X-0.375
 46 33 30 2E 0D 0A 47 31 59 31 2E 38 36 34 32 5A   F30...G1Y1.8642Z
 33 2E 30 15                                       3.0.           


Answer: 10/16/2012 3:42:23 PM.08064 (+0.0000 seconds)


 06                                                .               


Then this is the last block that was sent after several dozens of code sent for this 15 minute project.
Quote
Request: 10/16/2012 4:08:07 PM.38664 (+0.0000 seconds)


 01 95 6A 33 30 2E 0D 0A 47 31 59 2D 31 2E 33 36   .•j30...G1Y-1.36
 37 35 5A 33 2E 30 39 30 37 46 32 30 2E 0D 0A 59   75Z3.0907F20...Y
 2D 31 2E 33 37 31 31 5A 33 2E 30 39 0D 0A 47 31   -1.3711Z3.09..G1
 58 2D 30 2E 33 37 35 46 33 30 2E 0D 0A 47 31 5A   X-0.375F30...G1Z
 33 2E 37 30 38 31 46 31 30 30 2E 0D 0A 47 39 47   3.7081F100...G9G
 32 38 0D 0A 4D 32 0D 0A 0D 0A 0D 0A 25 0D 0A 00   28..M2......%...
 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00   ................
 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00   ................
 00 00 00 8D                                       ...           


Answer: 10/16/2012 4:08:09 PM.77764 (+1.3594 seconds)


 06                                                .               


Port closed


Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on November 05, 2012, 01:39:18 pm
Now I have been told to try and add XModem routine to the project. I have a class that has a couple of routines I can use, but in using XMODEM an ACK  06 is sent back, or NAK, etc.  This may work out better. But I have to turn of Xon/Xoff for this I believe.I am capturing data (see image). The DNC stands for Xon/Xoff Dripfeed, sending DNCX would cause the CNC controller to work in XMODEM. Will I be able to capture both the text XYZ data and the ACK, NAK ... control characters with no flow control?

The image shows the data which is received after the initial DNC handshake. Sometimes the probe data comes one probe point at a time, but often as many as 50 points at one time. With Xon/Xoff I don't see any other characters. The probe data starts with an X (or Y or Z if used),or an N or T occasionally. There is always one control character after each probe data point. (0Dhex)

[attachment deleted by admin]
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on December 09, 2012, 09:31:55 pm
An  update on XMODEM, I have it working, though you have to use NO flow control, that is keep Xon/Xoff to none. You depend on the receiver sending 06hex ACK and 15hex NAK. Now the routines I have work, but I'm thinking I have some communications problem I am going to have to single-step through in SendPacket and SendFiles routines of the modules I imported into Jan's program. These routines are in the MainForm in a routine I call DripFeedCNCDataParts which is the 'meat' of my program. I send all data through this routine and I use it with the Xon/Xoff method of data transfer and works okay. Now I needed to add XMODEM so I wanted to use the same DripFeedCNCDataParts routine. But it needs to be called from ComPorts module and I successfully setup this with RaiseEvent following Jan's method with the AccessFormMarshal routine. So in XMODEM with CRC checking I send 128 bytes of data, which is actually 132 bytes, the first three bytes are the numbering of bytes with 01 01 FE and then 01 02 FD ... and the last byte is the Checksum byte which is calculated and thanks to Dick G. for the modules I imported.

What happens is kind of strange. What I think Fadal with it's CNC controller is doing in XMODEM is sending ACK (06hex) is that it also will send a NAK (15hex) and keep doing this at short intervals, such as 1/2 second or so. This is followed by 11hex (DC1) and then again 15hexs. This repeats until the next XMODEM 132 byte packet is sent.

Well I may not have the communication perfect and/or timing. And putting in appropriate delays is important, but you don't too much delay. Ideally you want to have 06hex followed by a new packet or if you don't get a 06hex then you would get just the 15hex (NAK). Then you would resend the same packet.

Okay, I am getting some success, as the packets are going through and the machine is working, going through the motions of milling, probing, etc. BUT, I make a program change based on the probing data. This program change is not known until the probing is done. This is where the RaiseEvent works and I can send one of two data files depending on the probing data. This happens immediately and is sent. BUT, when I do this, the packets all get sent at one time, and then followed are the responses (all of them) at once!

I will attach a file of this, so it makes sense. I am wondering if  the fact that the SendPacket and SendFiles routines are in MainForm that I having this problem. Or maybe I have some delay in between running the different files that is causing this. I am going to keep working on this and report back what I find, I probably won't be back to the shop until Tuesday but I am going to single-step the SendPacket routine, because I still don't understand how it all works.

I have indicated in the image where the response is before I send the data with the RaiseEvent call. But using the RaiseEvent method does not give me a quick response but rather all the data is sent at the end. For a large amount of probing, I'm sure this would err.

I noticed that the SendPacket routine is Private, I am thinking that maybe it needs to be Public and or  Shared? I won't be back to the shop until Tuesday. but

[attachment deleted by admin]
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: Jan Axelson on December 10, 2012, 12:56:30 pm
The documentation for DataReceived says:

The DataReceived event is not guaranteed to be raised for every byte received.

http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx

This discussion might be helpful:

http://stackoverflow.com/questions/7808226/datareceived-event-sometimes-doesnt-fire
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on December 10, 2012, 01:12:35 pm
Thanks Jan. Just saw your  response and I will be looking at the  (ReadBufferSize and ReceivedBytesThreshold) and experimenting with this tomorrow. I am psyched up from this. I am also posting another image, as I want to show the data received in orange being delayed at the end, I see that my drawing clipped this. So the new image will show. NOTE, too that my data returned is mixed in with the control bytes of 06hex, 15hex ... This does not pose a problem since I know that all data for the CNC machines either will start with the first coordinate that is requested, in my case a Y but it could be X or Z and if nil or not data it will be either an N or a T . Kind of weird the T as I am thinking it means terminal or something where N means either nil or no data. I hope I haven't been confusing? But the data does come back consistently all data comes back with a 0Dhex which is my 'guiding light' to parse.

In the image notice the Y coordinates, my data, and the N for no data which just means I didn't generate a probe value so it is NIL, as well as 06hex 0Dhex which follows all data, and possibly 1 15hex or even a 11hex, though it may not be visible in this snapshot.

[attachment deleted by admin]
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on December 26, 2012, 11:31:46 am
I am getting the (attached image) System.NullReferenceException error in immediate window and InternalSubstringWithChecks with exception Length cannot be less than zero in my Xmodem run. This causes the CNC controller to send a 93Hex, which I believe is what they have programmed the controller to send when it cannot continue. These show up as ??? symbols in the textbox.

[attachment deleted by admin]
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on December 31, 2012, 11:10:23 am
Disclaimer, I am not Brad Pitt, but rather his better looking alter-ego!  ::)
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: Jan Axelson on December 31, 2012, 04:50:38 pm
Track down the source of the exception! This might help:

http://www.dotnetperls.com/nullreferenceexception
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on January 02, 2013, 11:43:12 am
Thanks Jan, I have bookmarked the link. It will come in handy for me. I am not sure I will be working more on this project. I believe this is the last day. I have an issue with a module in XModem from Dick G. program. I feel drained, as I have worked hard on this, the only programmer on the project, actually at the plant. But they can't seem to understand the need, or have the money for a full-time person and actually could benefit from two people. Anyway I am going to be busy with the PacketTimeout Method of Dick's. That is where I have some problems. It may not be solved today, but will be in my notes of what needs doing if the owner decides he wants me (or someone else) to coninue, and if I'm available, which is looking like I might not be. Unfortunate because the guys all love me here, and ditto from me.  :(

Will keep informed and I'm here for the next four hours at least!
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: Jan Axelson on January 02, 2013, 01:32:49 pm
I'm pretty sure this is the forum's longest thread (most responses)! I hope we've been of some help and/or moral support!
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on January 02, 2013, 01:50:58 pm
Jan, you sure have. I haven't solved all the issues, and currently the XModem solution has been the most intriguing. I personally think the project if continued may work better in XOn/XOff, even with no error checking. That is just IMHO as my late dad would say. You never know there may be a change of heart, or maybe money. I just checked the Dow Jones Stock Analysis and believe it, I think this is the stimulus us programmers needed in Michigan anyway. There was such a depressed feeling among the car industry people that I know, and they wouldn't verbally say anything, but I think they were ready to fall off the Fiscal Mountain, if Michigan had any big ones. There actually is one by the Ford Proving Grounds, one of two Ford plants, one about 1/2 mile from this plant the other 5 miles away. But I think there is a relief that more money will be flowing into the economy, even though the deal didn't really solve anything long term, but I don't think hiring would have kept up.
Title: Re: Simple VB.Net RS-232 program to capture serial port data to a text file
Post by: btcomp on January 02, 2013, 01:58:36 pm
Wow, I looked a the number of people that have looked at this thread 10,000, well I hope this has helped!