點亮LED

      在〈點亮LED〉中尚無留言

GpioController

GpioController為GPIO的控制類別, 必需先取得此物件, 再由此物件控制各個針腳. 此物件不能使用new產生, 需由GpioFactory.getInstance()取得

GpioPinDigitalOutput

GpioPinDigitalOutput類別為控制每個針腳的動作, 由gpioController.provisionDigitalOutputPin()產生. 此方法有三個重載方法

gpioController.provisionDigitalOutputPin(RaspiPin.GPIO_00);
gpioController.provisionDigitalOutputPin(RaspiPin.GPIO_00, “LED”);
gpioController.provisionDigitalOutputPin(RaspiPin.GPIO_00, “LED”, PinState.HIGH);

針腳動作

gpioPin.setState(PinState.HIGH) : 輸出 3.3V
gpioPin.setState(PinState.LOW) : 輸出 0V
gpioPin.pulse(500) : 點亮500ms, 然後隨即滅掉
gpioPin.toggle() : 與上次一反向, 3.3 -> 0 ,  0->3.3
gpioPin.blink(1000, 10000)  : 亮1秒, 滅1秒, 持續10秒, 不用迴圈即可達成, 但執行緒要睡10秒, 再執行pin.setShutdownOptions(true, PinState.LOW);

程式範例

本程式會啟動GPIO 0,1,2三支針腳, 控制三個LED的狀態. 另本程式有另一個執行緒, 偵測t1, t2, t3是不是都完成了. 如果還沒完成, 就睡一秒鐘後再偵測. 如果三個執行緒都完成了, 就執行gpioControl.shutdown();

led1

MahalLed1.java如下

package mahalled1;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.Pin;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;
public class MahalLed1 {
    public static void main(String[] args) {
        GpioController gpioController=GpioFactory.getInstance();
        G.t1=new Led(gpioController, RaspiPin.GPIO_00, 100, 400, 100);
        G.t2=new Led(gpioController, RaspiPin.GPIO_01, 50, 600, 50);
        G.t3=new Led(gpioController, RaspiPin.GPIO_02, 40, 700, 10);       
        G.t1.start();
        G.t2.start();
        G.t3.start();
        new Thread(()->{
            while(G.t1.isAlive() || G.t2.isAlive() || G.t3.isAlive()){
                G.delay(1000);
            }
            gpioController.shutdown();
        }).start();
    }
}
class Led extends Thread{
    GpioController gpioController;
    Pin pin;
    int count, onTime, offTime;
    public Led(GpioController gpioController, Pin pin, int count, int onTime, int offTime){
        this.gpioController=gpioController;
        this.pin=pin;
        this.count=count;
        this.onTime=onTime;
        this.offTime=offTime;
    }
    @Override
    public void run(){
        GpioPinDigitalOutput gpioPin=gpioController.provisionDigitalOutputPin(pin, "Led");
        for (int i=0;i<count; i++){
            gpioPin.setState(PinState.HIGH);
            G.delay(onTime);
            gpioPin.setState(PinState.LOW);
            G.delay(offTime);
        }
    }
};

G.java如下

package mahalled1;
import com.pi4j.io.gpio.GpioController;
import java.util.logging.Level;
import java.util.logging.Logger;
public class G {
    public static Thread t1, t2, t3;
    public static void delay(int t){
        try {Thread.sleep(t);}
        catch (InterruptedException ex) {}
    }
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *