OutputChangeHandler (thread function question)

C, C++, and Visual C++
rich
Phidgetly
Posts: 40
Joined: Sat Jul 02, 2011 2:47 pm
Contact:

OutputChangeHandler (thread function question)

Postby rich » Tue Sep 27, 2011 10:55 am

I know I'm not the first person to want this - and I've seen a lot of posts alluding to this, but I can't figure out how to get this to work. If anyone has any code segment they'd be willing to share it would be much appreciated.

On the SBC (or any Phidget 8/8/8) when the OutputChangeHandler picks up a change (eg; #2 sensor goes high) I'd like to wait for 12 seconds, and if the sensor does not get reset to low by another process, then I'd like to set that sensor back to low.

Obviously putting a "sleep" or "wait" in the OutputChangeHandler would not be a good idea because I don't want to hang the handler from processing other changes. But apparently I'm missing some important concept, because I just can't figure out how to properly code this. My guess is that I need to spawn a thread waiting for the change, signaled by the OutputChangeHandler, then have that thread "sleep" before setting the sensor back to low, allowing the OutputChangeHandler to keep working in the meantime. So, if anyone has actually done this and wouldn't mind sharing a code snippet, I'm sure quite a few people would really appreciate it.

Thanks in advance to anyone who can respond!

Rich.

User avatar
Patrick
Lead Developer
Posts: 3165
Joined: Mon Jun 20, 2005 8:46 am
Location: Canada
Contact:

Re: OutputChangeHandler (thread function question)

Postby Patrick » Tue Sep 27, 2011 11:31 am

You're right, just start a new thread from the event handler which simply sleeps for 12 seconds and then sets the output low.
very simply:

Code: Select all

pthread_t thread_handle;

int outputChangeHandler(CPhidgetInterfaceKitHandle phid, void *userPtr, int index, int state)
{
   if(index == 0 && state == 1)
      pthread_create(&thread_handle, NULL, thread_func, NULL);
}

void *thread_func(void *arg)
{
   sleep(12);
   CPhidgetInterfaceKit_setOutputState(0, false);
}

You'll probably want to add some logic to make sure there's only one instance of the thread running at a time, and to close it down when your app stop so you don't have a 12 second delay.

-Patrick

rich
Phidgetly
Posts: 40
Joined: Sat Jul 02, 2011 2:47 pm
Contact:

Re: OutputChangeHandler (thread function question)

Postby rich » Tue Sep 27, 2011 12:08 pm

Wow Patrick!!! Thank you!!!

The only change was adding the phidgethandle to the setoutput, and adding the pthread.h header up top - but otherwise it worked like a charm!!!

I _REALLY_ appreciate your quick response.

Rich.


Return to “C/C++”

Who is online

Users browsing this forum: No registered users and 6 guests