2014-10-08 29 views
0

我有一個beagle骨,想從我的程序中讀取gpio pin。該文件在任何時候都包含1或0。在我的C程序中,我有一個while循環,它永遠運行一個休眠函數,以防止在該引腳處於低電平時(0),並且當它處於高電平時(1),它將運行代碼。我覺得這是一個非常浪費資源。有沒有一種方法可以在這個文件是1的時候看到,然後運行代碼?我不喜歡投票,特別是當小獵犬骨頭要用電池供電時。如何在沒有輪詢的情況下查找文件中的更改?

回答

0

使用通知機制,例如通過利用libev

基本思想是,如果數據可用,則調用回調。

如果這不起作用,您可能需要使用其他API才能達到此目的,例如inotify。 libev文檔的

實施例提供:

// a single header file is required 
#include <ev.h> 

#include <stdio.h> // for puts 

// every watcher type has its own typedef'd struct 
// with the name ev_TYPE 
ev_io stdin_watcher; 
ev_timer timeout_watcher; 

// all watcher callbacks have a similar signature 
// this callback is called when data is readable on stdin 
static void 
stdin_cb (EV_P_ ev_io *w, int revents) 
{ 
puts ("stdin ready"); 
// for one-shot events, one must manually stop the watcher 
// with its corresponding stop function. 
ev_io_stop (EV_A_ w); 

// this causes all nested ev_run's to stop iterating 
ev_break (EV_A_ EVBREAK_ALL); 
} 

// another callback, this time for a time-out 
static void 
timeout_cb (EV_P_ ev_timer *w, int revents) 
{ 
puts ("timeout"); 
// this causes the innermost ev_run to stop iterating 
ev_break (EV_A_ EVBREAK_ONE); 
} 

int 
main (void) 
{ 
// use the default event loop unless you have special needs 
struct ev_loop *loop = EV_DEFAULT; 

// initialise an io watcher, then start it 
// this one will watch for stdin to become readable 
ev_io_init (&stdin_watcher, stdin_cb, /*STDIN_FILENO*/ 0, EV_READ); 
ev_io_start (loop, &stdin_watcher); 

// initialise a timer watcher, then start it 
// simple non-repeating 5.5 second timeout 
ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.); 
ev_timer_start (loop, &timeout_watcher); 

// now wait for events to arrive 
ev_run (loop, 0); 

// break was called, so exit 
return 0; 
} 
相關問題