Skip to content

Commit

Permalink
Example lcd code
Browse files Browse the repository at this point in the history
  • Loading branch information
FDelporte committed Jun 10, 2024
1 parent 6e1661e commit 9fca221
Show file tree
Hide file tree
Showing 5 changed files with 603 additions and 20 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
package com.pi4j.spring.boot.sample.app.controller;

import com.pi4j.context.Context;
import com.pi4j.io.gpio.digital.DigitalOutput;
import com.pi4j.io.gpio.digital.DigitalState;
import com.pi4j.spring.boot.sample.app.service.Pi4JService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -16,22 +15,24 @@
public class Pi4JController {

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

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);
public Pi4JController(@Autowired Pi4JService pi4JService) {
this.pi4JService = pi4JService;
}

@GetMapping("/led/{status}")
public String setLedStatus(@PathVariable Boolean status) {
try {
led.state(status ? DigitalState.HIGH : DigitalState.LOW);
return "LED status set to " + (status ? "ON" : "OFF");
} catch (Exception e) {
return "Error while changing the LED status: " + e.getMessage();
}
@GetMapping("/led/{state}")
public Boolean setLedStatus(@PathVariable Boolean state) {
return pi4JService.setLedState(state);
}

@GetMapping("/button")
public DigitalState setLedStatus() {
return pi4JService.getButtonState();
}

@GetMapping("/lcd/{line}/{text}")
public Boolean setLcdText(@PathVariable Integer line, @PathVariable String text) {
return pi4JService.setLcdText(line, text);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package com.pi4j.spring.boot.sample.app.lcd;

import java.time.Duration;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

public abstract class Component {
/**
* Logger instance
*/
private static final Logger logger = Logger.getLogger("Pi4J Components");

static {
Level appropriateLevel = Level.INFO;
//Level appropriateLevel = Level.FINE; //use if 'debug'

System.setProperty("java.util.logging.SimpleFormatter.format",
"%4$s: %5$s [%1$tl:%1$tM:%1$tS %1$Tp]%n");

logger.setLevel(appropriateLevel);
logger.setUseParentHandlers(false);
ConsoleHandler handler = new ConsoleHandler();
handler.setLevel(appropriateLevel);
logger.addHandler(handler);
}

protected Component() {
}

/**
* Override this method to clean up all used resources
*/
public void reset() {
//nothing to do by default
}

protected void logInfo(String msg, Object... args) {
logger.info(() -> String.format(msg, args));
}

protected void logError(String msg, Object... args) {
logger.severe(() -> String.format(msg, args));
}

protected void logDebug(String msg, Object... args) {
logger.fine(() -> String.format(msg, args));
}

protected void logException(String msg, Throwable exception) {
logger.log(Level.SEVERE, msg, exception);
}

/**
* Utility function to sleep for the specified amount of milliseconds.
* An {@link InterruptedException} will be caught and ignored while setting the interrupt flag again.
*
* @param duration Time to sleep
*/
protected void delay(Duration duration) {
try {
long nanos = duration.toNanos();
long millis = nanos / 1_000_000;
int remainingNanos = (int) (nanos % 1_000_000);
Thread.sleep(millis, remainingNanos);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}

protected <T> T asMock(Class<T> type, Object instance) {
return type.cast(instance);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package com.pi4j.spring.boot.sample.app.lcd;

import com.pi4j.context.Context;
import com.pi4j.io.i2c.I2C;
import com.pi4j.plugin.mock.provider.i2c.MockI2C;

import java.time.Duration;

public abstract class I2CDevice extends Component {

/**
* The Default BUS and Device Address.
* On the PI, you can look it up with the Command 'sudo i2cdetect -y 1'
*/
protected static final int DEFAULT_BUS = 0x01;

/**
* The PI4J I2C component
*/
private final I2C i2c;


protected I2CDevice(Context pi4j, int device, String name) {
i2c = pi4j.create(I2C.newConfigBuilder(pi4j)
.id("I2C-" + DEFAULT_BUS + "@" + device)
.name(name + "@" + device)
.bus(DEFAULT_BUS)
.device(device)
.build());
init(i2c);
logDebug("I2C device %s initialized", name);
}


/**
* send a single command to device
*/
protected void sendCommand(byte cmd) {
i2c.write(cmd);
delay(Duration.ofNanos(100_000));
}

protected int readRegister(int register) {
return i2c.readRegisterWord(register);
}

/**
* send custom configuration to device
*
* @param config custom configuration
*/
protected void writeRegister(int register, int config) {
i2c.writeRegisterWord(register, config);
}

/**
* send some data to device
*
* @param data
*/
protected void write(byte data) {
i2c.write(data);
}

/**
* Execute Display commands
*
* @param command Select the LCD Command
* @param data Setup command data
*/
protected void sendCommand(byte command, byte data) {
sendCommand((byte) (command | data));
}

protected abstract void init(I2C i2c);

// --------------- for testing --------------------

public MockI2C mock() {
return asMock(MockI2C.class, i2c);
}

}
Loading

0 comments on commit 9fca221

Please sign in to comment.