2010年6月9日 星期三

使用計時訊息來控制LED


上篇提到如何利用計時器來更新UI內容,本篇將介紹它來控制LED,平台使用長高科技的6410XP,為了使模擬器能順利開啟執行畫面,我們把觸發硬體的控制命令放在按鈕的事件處理函式內。在此程式需要建立三個按鈕分別來控制閃爍、開啟驅動、關閉閃爍。其完整程式列表如下:
1. UpdateUIActivity.java

package tw.com.dmatek.dma6410xp.led;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class UpdateUIActivity extends Activity {
protected static final int led_on = 1;
private long mStartTime;
TextView mTimeLabel;
private int flag=0;
private int fd;
Button start,open,stop;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTimeLabel = (TextView) findViewById(R.id.timer);
mStartTime = System.currentTimeMillis();
mHandler.removeCallbacks(mUpdateTimeTask);
stop=(Button) findViewById(R.id.stop);
stop.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mHandler.removeCallbacks(mUpdateTimeTask);
}

});
start=(Button) findViewById(R.id.start);
start.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mStartTime = System.currentTimeMillis();

mHandler.postDelayed(mUpdateTimeTask, 100);
}

});
start.setEnabled(false);
open=(Button) findViewById(R.id.open);
open.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
fd = Linuxc.openled();

if (fd < 0){
setTitle("open device false!");

finish();
}
else {
setTitle("open device success!");
start.setEnabled(true);
open.setEnabled(false);
}
}

});

}
private Handler mHandler = new Handler();
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
final long start = mStartTime;
long millis = System.currentTimeMillis() - start;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
if (seconds < 10) {
mTimeLabel.setText("" + minutes + ":0" + seconds);
} else {
mTimeLabel.setText("" + minutes + ":" + seconds);
}
flag=1-flag;
Linuxc.send(2, flag+1);
mHandler.postDelayed(mUpdateTimeTask, 100);
}
};
}


2. Linuxc.java

package tw.com.dmatek.dma6410xp.led;

import android.util.Log;

public class Linuxc {
static {
try {
Log.i("JNI", "Trying to load libled.so");

System.loadLibrary("led");
}
catch (UnsatisfiedLinkError ule) {
Log.e("JNI", "WARNING: Could not load libled.so");
}}

public static native int openled();

public static native int closeled();

public static native int send(int led_num, int on_off);
}

沒有留言:

張貼留言