Go Down

Topic: VB Comms Failure During Long Jobs (Read 8508 times) previous topic - next topic



I have cobbled together a 6-DOF pick 'n' place robot with a couple of lasers for etching and cutting etc. which works fine for short jobs, but sometimes stalls unexpectedly when performing tasks taking several hours. It's based on a UNO board and driven from a VB 2008 app on a laptop at 38400 baud. To minimize interference I use as short a USB lead as possible between the two, and have LAN and all other software disabled while running. As it often has these hiccups at night, I haven't been able to pin down exactly how long the job has run, in case it's some kind of overflow or at least time-based fault.

Here's the VB output from the last stall:

Code: [Select]

x7574y0l3o14s0c12g16i252o14                           ' VB->Arduino (command)

-> x=7574 y=0 z=0 l=3 o1=14 s=0 c=12 g=16 i=252 o2=14 ' Arduino->VB (variables parsed OK)

-> OK                                                 ' Arduino->VB (Done/Ready for next)

x-7574y1                                              ' VB->Arduino

-> x=-7574 y=1 z=0 l=0 o1=0 s=0 c=0 g=0 i=0 o2=0      ' Arduino->VB (variables parsed OK)

-> OK                                                 ' Arduino->VB (Done/Ready for next)

x7574y0l3o14s0c12g16i252o14                           ' VB->Arduino (command)

-> x=7574 y=0 z=0 l=3 o1=14 s=0 c=12 g=16 i=252 o2=14 ' Arduino->VB (variables parsed OK)

The last command was carried out successfully, but either the Arduino failed to send it's 'OK', or the VB app never saw it. When I tried to force a command to the machine, the VB app crashed with 'The Port is Closed'. When I arrived at the machine this morning it had been working for about 15 hours. Though I can't say for certain that this timing is consistent. Perhaps I should time-stamp my debugging output?

Anyone had this happen to them before, or have any ideas on how I can trace it?

Many Thanks,



Perhaps I should time-stamp my debugging output?

always a good idea.
for serious apps I recomment using a RealTime Clock(ds1307) , to be able to connect the error message of the arduino to the PC event log.

Can you post the whole Arduino code? (later we can check VB code too)
There might be an overflow involved if it is always around same time after startup.

Do you wrap your string send with tags to indicate begin of string and end of string? (like XML uses < and > )
This helps to synchronize longer packets of data.
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)


Are your VB code updating a text box or similar control with lots of data?

I had a problem with a program that worked perfectly for shorter runs but when running for say over 10 hours the textbox (displaying data recieved from Arduino) had so much text in it that it more or less made Windows stop working.

On the next crash you should start the task manager on your Windows machine and see if excessive memory or CPU usage is present.


Good points, thanks.


I have just ordered a ds1307, so hopefully I'll patch that in next week. Overflow does make sense, even though (I think) my Arduino code is free of counters. Perhaps something could be hidden in a library? When I started work on my machine I did use '<>' as start and end markers, but I still had the stalling problem after a few hours. I just use vbcrlf as line terminators now, which seems to work just as well. The lines never get any longer than the example I posted above. I am away from my Arduino sketch today (my Girlfriend has the laptop on a weekend course) but will post when I can.


That is very interesting indeed. I do have a lot of textboxes in my VB app, though none of them get updated during the run of the machine. I just set my parameters and press 'go'. I was running this from the IDE in debugging mode, I wonder if running the bare executable would behave differently? Also, you are very lucky to be living in CPH. It's one of my favourite cities, been there twice this year.


Lot's of textboxes should not be a problem. My problem was a single textbox with litteraly megabytes of text added over time.


I'm still bashing away at this fault, I have tried a lot of different fixes (including USB registry tweaks) but as none of them helped I won't bother listing them here. Here are the relevant bits of my code in case I'm doing something superdumb. Both programs (especially the VB side) are quite big, so I've only included the serial sections. Please bear in mind that the code works perfectly FOR A WHILE, anything between 1 and 16 hours, but not indefinitely. The machine stops 'randomly' after executing a command successfully, and fails to get the 'OK' back to VB. Then VB freezes, and on re-running the app I get 'Port is Closed'. Despite applying DisableSelectiveSuspend, the only way I can recover the connection is by un/re-plugging the USB cable. And yes, I have tried many different USB cables too!

Arduino side:
Code: [Select]

// tjn 16/10/2012
// Status: Working! Interleaves X, Y1, Y2 and Z(B)
// Note: 78 Steps/mm using B servo in Full-wave mode, slack = 36

#include <Wire.h>
#include <iox.h>

// Variables get declared...

void setup() {
 inStr.reserve(40);          // easily enough for longest command (ie.x7000y7000z1404o13s0c19g6i270o14)
 pinMode(xctrl1, OUTPUT);    // X stepper pin1
 pinMode(xctrl2, OUTPUT);    // X stepper pin2
 pinMode(yctrl1, OUTPUT);    // Y1 stepper pin1
 pinMode(yctrl2, OUTPUT);    // Y1 stepper pin2
 pinMode(y2ctrl1, OUTPUT);   // Y2 stepper pin1
 pinMode(y2ctrl2, OUTPUT);   // Y2 stepper pin2
 pinMode(lpower, OUTPUT);    // Laser power
 pinMode(xypower, OUTPUT);   // XY stepper power
 pinMode(xsensors, INPUT);   // X-buffer switches
 pinMode(ysensors, INPUT);   // Y-buffer switches
 digitalWrite(xypower, LOW); // Power-down XY motors
 digitalWrite(lpower,LOW);   // Power-down laser
 Wire.begin();               // Start 2-wire communications (Arduino as master device)
 IOX.device(0x74, 16);       // 0x74 is address for Servo A (Pitch)
 IOX.write(0x0080, CFGPORT); // P07=INPUT Set ports LOW to make them OUTPUTS
 IOX.write(0x0000, INVPORT); // Set slave device invert ports to all NON-INVERT
 IOX.write(0x000, OUTPORT);  // Power-down Lamp/Fan

//Wait for input string and parse it into usable chunks

void loop() {
 if (stringComplete) {
   if(inStr.indexOf("x") >=0) xSteps = inStr.substring(inStr.indexOf("x")+1,inStr.indexOf("y")).toInt();
   else xSteps = 0;  // X Transit
   if(inStr.indexOf("y") >=0) {
     if(inStr.indexOf("z") >=0) y1Steps = inStr.substring(inStr.indexOf("y")+1,inStr.indexOf("z")).toInt();
     else y1Steps = inStr.substring(inStr.indexOf("y")+1).toInt(); // Y Transit
   else y1Steps = 0;
   if(inStr.indexOf("z") >=0) {
     if(inStr.indexOf("l") >=0) zSteps = inStr.substring(inStr.indexOf("z")+1,inStr.indexOf("l")).toInt();
     else zSteps = inStr.substring(inStr.indexOf("z")+1).toInt(); // Z Transit
   else zSteps = 0;
   if(inStr.indexOf("l") >=0) laserTime = inStr.substring(inStr.indexOf("l")+1).toInt();
   else laserTime = 0;  // Laser On/Off
   if(inStr.indexOf("o") >=0){
     laserTime = inStr.substring(inStr.indexOf("l")+1,inStr.indexOf("o")).toInt();      // Laser On Time
     offset1 = inStr.substring(inStr.indexOf("o")+1,inStr.indexOf("s")).toInt();        // Offset1
     space = inStr.substring(inStr.indexOf("s")+1,inStr.indexOf("c")).toInt();          // Space
     cut = inStr.substring(inStr.indexOf("c")+1,inStr.indexOf("g")).toInt();            // Cut
     gap = inStr.substring(inStr.indexOf("g")+1,inStr.indexOf("i")).toInt();            // Gap
     iterations = inStr.substring(inStr.indexOf("i")+1,inStr.lastIndexOf("o")).toInt(); // Iterations
     offset2 = inStr.substring(inStr.lastIndexOf("o")+1).toInt();                       // Offset2
   else {
     offset1 = 0;
     space = 0;
     cut = 0;
     gap = 0;
     iterations = 0;
     offset2 = 0;

   // Show VB immediate window that variables are good

   Serial.print(" y=");
   Serial.print(" z=");
   Serial.print(" l=");
   Serial.print(" o1=");
   Serial.print(" s=");
   Serial.print(" c=");
   Serial.print(" g=");
   Serial.print(" i=");
   Serial.print(" o2=");

// Do various things with motors and lasers...

   Serial.println("OK"); // Reset ready to receive next command from vb    
   inStr = "";              // Clear input string
   stringComplete = false;
   oxDir = xDir;
   oyDir = yDir;
   ozDir = zDir;

VB (Express 2008) side:

Code: [Select]
   'setup form
   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
       If SerialPort1.IsOpen Then
       End If
           With SerialPort1
               .PortName = "Com7" 'check your ports!!! (AMD4400 = 5, Duemilanove = 4, UNO = 7)
               .BaudRate = 38400
               .Encoding = System.Text.Encoding.ASCII
           End With
           'Open the port and clear the input buffer
       Catch Ex As Exception
       End Try
   End Sub
    'release resources after form is closed
       Private Sub Form1_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
           If SerialPort1.IsOpen() Then
           End If
   End Sub
    'This sub gets called automatically when the COM port receives data
       Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
           rxBuffer = (SerialPort1.ReadLine) 'Move recieved data into the buffer
           If rxBuffer.StartsWith("OK") Then 'Allows diagnostic messages from Arduino without interfering with comms
               enableSend = True
           End If
           Debug.WriteLine("-> " + rxBuffer)
   End Sub
Private Function Output(ByVal CurrentImage As Bitmap) As Bitmap
        For i = 0 to Whatever ' 1 to 7000-ish
                ' Build outString        
               SerialPort1.Write(outString & vbCrLf)
               enableSend = False
               While enableSend = False
               End While
               outString = ""
        next i
End Function


if you use for example putty.exe to capture the output of arduino, does it fail after 16 hours too?

Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)


Nov 14, 2012, 09:44 pm Last Edit: Nov 14, 2012, 10:37 pm by aibonewt Reason: 1
I've had a number of monitors watching different jobs; Process Monitor, Comport Toolkit and Device Monitoring Studio. DMS was the most informative of the bunch, but only reflected exactly what VBs immediate window told me anyway. Arduino failed to send an 'OK', or the laptop never saw it. Process Monitor didn't really show anything strange, other than a double Thread Exit invoked in VB around the time of failure, but I'm not entirely convinced it was significant.

Currently running another test with Serial.flush() after the Arduino's 'OK' line. So far so good...


Nope, crashed after almost exactly 8hrs. Reset the Arduino and had to un/re-plug twice before VB would acknowledge it's existence again!


I think I'm starting to get to grips with this now (haha, famous last words!)

Running the VB straight from the .exe works MUCH better than within the IDE, and here's why...

To see what's going on behind the scenes Debug.Writeline is really handy, HOWEVER, dumping text into the immediate window really slows things down and seems to interfere with serial comms particularly badly, especially when there are lots of lines being returned in quick succession. The immediate window seems to insist on reporting everything as effectively as possible (which is fine in itself), but it seems to lend so many resources to printing and scrolling the outpouring of text that it will happily corrupt the transmission of serial comms and leave you wondering why something so simple often falls flat on its face.

I have now removed all of my Debug.Writeline command and now use StreamWriter to populate a text file with all of my event reports, and things are running so much better. I would like to say perfectly, but I'm still cautious (and the connection to my X-actuator has fatigued-away after performing over 140,000 transits over the last few days!)


You know, I'm seriously considering abandoning VB for this application.

I've been running the Debug Build so far, and thought things might be better using the Release Build. Freezes after sending one command, while the Debug would fail after a few thousand. ]:)


This thread has become somewhat of a soliloquy, but no matter. It's still useful for me to keep a record of what I'm trying, and much neater than the ever-thickening stack of sticky notes accumulating on the edge of my machine.

Not sure I can quite blame VB/MS just yet. I did a rebuild of my VB app using .Net Framework 2.0 as there are many reports going 'round that 3.5 is bad news for serial comms. The machine still froze after that, so I added a Try/Catch around the serial sending sub in the VB. Okay, it froze again after about 11 hours, but something unexpected happened. I had coded the serial exception to throw out messagebox with the error, but there was no box when the machine froze!

May be the Arduino misbehaving after all, but just to be sure I have started another test job with a camera watching the Tx/Rx lights on the Arduino. Hopefully, when it freezes again I will be able to play back the footage and see if that little Tx flashed before the machine stalled.



Okay, for those of you still reading, I now have photographic evidence that this is NOT a VB error, but an Arduino one! Here we go...

Job Start:

Logfile Entries (camera clock was a few seconds out of sync):
Code: [Select]
Start of Matrix Output...
13:53:35 <- z-412
13:53:37 -> OK
13:53:37 <- x0y1
13:53:37 -> OK
13:53:37 <- x7058y0l3o0s1c7g19i262o0
13:53:59 -> OK

Job End: (moved camera and switched to a lower resolution)

Code: [Select]
02:05:45 <- x-7058y1
02:05:54 -> OK
02:05:54 <- x7058y0l3o14s1c7g19i261o15
02:06:16 -> OK
02:06:16 <- x-7058y1
02:06:26 -> OK
02:06:26 <- x7058y0l3o14s1c7g19i261o15

I'm now trying another test at only 9600bps to see if that helps. If not I might try and restart this thread under a new guise, after all it is a different problem to the one I thought I had originally!


I now have photographic evidence that this is NOT a VB error, but an Arduino one!

Sounds like a conspiracy movie. I've never understood them because the photographic evidence that is supposed to prove something never does, to me.

Please explain what this photographic evidence is supposed to prove.
The art of getting good answers lies in asking good questions.


Hi Paul,

The shots were extracted from video of the UNO while my laser cutter was running. The serial transfer is a very simple polling scenario.

1) The VB app sends a command string, and waits for an 'OK' from the Arduino
2) Arduino catches the string and parses the variables <- RX flashes
3) Arduino carries out motor/laser commands
4) Arduino finishes and sends 'OK' back to the VB app <- TX flashes

And so on...

The photos show that the stalling is a fault with the Arduino or its code because the TX does not flash at the moment of stall (the last photo). Thus no 'OK' gets returned to VB. I had assumed for ages that VB/Windows was locking the port for some reason and not receiving the 'OK'.


The photos show that the stalling is a fault with the Arduino or its code because the TX does not flash at the moment of stall (the last photo).

You can see from this picture that the Arduino code failed because of what isn't here. OK. Got it.

You've, of course, posted ALL of your Arduino code, and I just missed it. Right?

Code: [Select]
  inStr.reserve(40);          // easily enough for longest command (ie.x7000y7000z1404o13s0c19g6i270o14)
In spite of all the warnings about problems with the String class, you are still using it. Here's a gun. Shoot your self in the foot. Go ahead and do it again. There's plenty of bullets, and I'll reload when you run out.
The art of getting good answers lies in asking good questions.

Go Up