Thread.Sleep in event handler

My problem is, I have a button connected to a cobra board that when depressed, turns on a motor through a motor controller, and when released turns off the motor. But I need the motor to run for an additional 300 milliseconds after the button is released. I tried sleeping the thread in the NotPressed event handler before turning the motor off, but after a few cycles all kinds of weird things start happening. What is the best way to accomplish what I need?

We could have an endless discussion of the “best way” to accomplish what you need. :slight_smile:

One of the first questions is how much of a latency can you allow between the time the button is press/released and when the motor is started/stopped?

The next question would be what else is going on in your program.

The first solution, that comes to mind, is having a separate thread for motor control. This thread would wait on a globally accessible AutoResetEvent object. There would also be a globally accessible boolean value which indicates whether the motor should be running. In the button event handler, the boolean value would be set to indicate the new state of the button, and then the AutoResetEvent would be set. The motor control thread would then wake up, and if the boolean value is true, start the motor running and then wait on the AutoResetEvent. If the boolean value was false, it would sleep for 300ms, and then stop the motor. It would then wait on the AutoResetEvent for the next button state change.

It would have been easier to just write the code to do this, but then you would be missing out on all the fun. :slight_smile:

@ hvelo - You could also start a timer with a callback in your button pressed event.

jasdev, can you point me to some sample code for starting a timer with a callback?

http://www.ghielectronics.com/docs/27/timers

Thanks. I’ll keep that handy. But the cobra seems barely able to keep up with these sequences as it is, it is slower than I expected (used to programming for hunky app servers), so I have found a physical solution that works just as well - I added a small piece of plastic to the button to hold it down longer… Works like a charm.

Thanks all!

I suggest you optimize your code. These system don’t tolerate programming practices that work with larger machines.

Well yes of course That’s what I have been doing.