Java编程中GPIO解构函数的详细介绍
来源:爱站网时间:2022-10-24编辑:网友分享
爱站技术频道小编今天来大家分享下Java编程中GPIO解构函数内容,如果你在操作过程中刚好卡在这里不知道如何下手,那以下这篇文章或多或少能解决你的问题。
问题描述
我对编程世界是个新手。所以这是我的问题:
我正在构建一个简单的IRCBot(PIRCBot),它可以接收Turn on
和Turn off
之类的命令,这些命令会将树莓的引脚设置为high
或low
。当我终止应用程序或当应用程序崩溃时,引脚将保持active
。
所以我的问题是:当我用SIGINT
终止应用程序时,如何确保释放GPIO?(解决以下评论)
当应用程序崩溃时,如何确保释放GPIO?
我的代码MainBot:
public static void main(String[] args) throws Exception {
try(IRCBot bot = new IRCBot()) {
bot.setVerbose(true);
bot.connect("192.168.1.137", 6667, "somesecretpasswd");
bot.joinChannel("#test");
} catch (Exception e) {
System.out.println(e);
}
}
}
IRCBot类别:
public class IRCBot extends PircBot implements AutoCloseable {
private final static String[] ALLOWED_USER = {"USER1", "USER2", "IRCBot"};
private final static String TURN_LIGHT_ON = "Turn on";
private final static String TURN_LIGHT_OFF = "Turn off";
private final static String DISCO = "Disco";
private GPIOController gpio;
public IRCBot() {
this.gpio = new GPIOController();
this.setName("IRCBot");
}
///other stuff
@Override
public void close() throws Exception {
gpio.close();
}
GPIOController类
public class GPIOController implements AutoCloseable {
private final GpioController gpio = GpioFactory.getInstance();
private GpioPinDigitalOutput gpio20;
private GpioPinDigitalOutput gpio21;
private GpioPinDigitalOutput gpio26;
private boolean status = false;
Logger LOGGER = Logger.getLogger(GPIOController.class.getName());
public GPIOController() {
GpioFactory.setDefaultProvider(new RaspiGpioProvider(RaspiPinNumberingScheme.BROADCOM_PIN_NUMBERING));
gpio.setShutdownOptions(true, PinState.LOW, PinPullResistance.OFF);
gpio20 = gpio.provisionDigitalOutputPin(RaspiBcmPin.GPIO_20, "LED", PinState.HIGH);
gpio21 = gpio.provisionDigitalOutputPin(RaspiBcmPin.GPIO_21, "LED", PinState.HIGH);
gpio26 = gpio.provisionDigitalOutputPin(RaspiBcmPin.GPIO_26, "LED", PinState.HIGH);
}
///some other stuff
@Override
public void close() throws Exception {
gpio.shutdown();
LOGGER.info("Shuting down");
}
思路:
如果使类从java.lang.AutoCloseable接口继承,并在close方法中添加清除代码,则可以这样使用它:
try(MyClassThatNeedsCleanup x = new MyClassThatNeedsCleanup()){
// use the class here
}
退出范围时,它将自动调用close()。
小编分享的这篇Java编程中GPIO解构函数的详细内容都看明白了吧!只有熟悉这方面的流程操作,才能在日后工作中更快速的处理问题,不懂的问题记得来咨询爱站技术频道小编。