Skip to content

Commit

Permalink
Example button handler code
Browse files Browse the repository at this point in the history
  • Loading branch information
FDelporte committed Jun 10, 2024
1 parent 32a18a8 commit 6e1661e
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import com.pi4j.context.Context;
import com.pi4j.io.gpio.digital.DigitalOutput;
import com.pi4j.io.gpio.digital.DigitalState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
Expand All @@ -13,12 +15,14 @@
@RequestMapping("/api/pi4j/")
public class Pi4JController {

private static final Logger logger = LoggerFactory.getLogger(Pi4JController.class);
private static final int PIN_LED = 22; // PIN 15 = BCM 22
private DigitalOutput led;
private final DigitalOutput led;

public Pi4JController(@Autowired Context pi4j) {
// LED example is based on https://www.pi4j.com/getting-started/minimal-example-application/
led = pi4j.digitalOutput().create(PIN_LED);
logger.info("LED initialized on pin {}", PIN_LED);
}

@GetMapping("/led/{status}")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.pi4j.spring.boot.sample.app.service;

import com.pi4j.context.Context;
import com.pi4j.io.gpio.digital.DigitalInput;
import com.pi4j.io.gpio.digital.DigitalStateChangeEvent;
import com.pi4j.io.gpio.digital.PullResistance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class Pi4JService {

private static final Logger logger = LoggerFactory.getLogger(Pi4JService.class);
private static final int PIN_BUTTON = 24; // PIN 18 = BCM 24

public Pi4JService(@Autowired Context pi4j) {
// Button example is based on https://www.pi4j.com/getting-started/minimal-example-application/
var buttonConfig = DigitalInput.newConfigBuilder(pi4j)
.id("button")
.name("Press button")
.address(PIN_BUTTON)
.pull(PullResistance.PULL_DOWN)
.debounce(3000L);
var button = pi4j.create(buttonConfig);
button.addListener(e -> handleButtonChange(e));
logger.info("Button initialized on pin {}", PIN_BUTTON);
}

private void handleButtonChange(DigitalStateChangeEvent e) {
logger.info("Button state changed to {}", e.state());
}
}

0 comments on commit 6e1661e

Please sign in to comment.