General Purpose Input / Output (GPIO)
Key concepts:
- Use the provided Builder static classes rather than the constructors.
- Can be provisioned either via the GPIO number or a PinInfo object. A PinInfo object can be retrieved via one of the lookup methods in the BoardPinInfo instance that is returned from the device factory getBoardPinInfo() method.
- The GPIO or Analog Input device factory can be specified when using GPIO expansion boards such as the MCP3008, otherwise it defaults to the automatically detected host board.
Digital
Input
Key concepts:
- The
activeHigh
property is optional; it will default tofalse
ifpud
is set to pull-up, otherwisetrue
.
DigitalInputDevice Javadoc.
SmoothedInputDevice Javadoc.
Input and Output
A GPIO device that can be dynamically switched between input and output mode.
DigitalInputOutputDevice Javadoc.
Output
DigitalOutputDevice Javadoc.
PWM Output
PwmOutputDevice Javadoc.
Analog
Input
The AnalogInputDevice class provides the mechanism for interfacing with analog devices. This class provides access to unscaled (-1..1) as well as scaled (e.g. voltage, temperature, distance) readings. For scaled readings is important to set the ADC voltage range in the device constructor - all raw analog readings are normalised (i.e. -1..1).
Analog Device Support
A lot of boards, including the Raspberry Pi, do not natively support analog input devices, see expansion boards for connecting to analog-to-digital converters.
Example: Temperature readings using an MCP3008 and TMP36:
Code taken from TMP36Test:
try (McpAdc adc = new McpAdc(McpAdc.Type.MCP3008, chipSelect);
TMP36 tmp36 = new TMP36(adc, pin, vRef, tempOffset)) {
for (int i=0; i<ITERATIONS; i++) {
double tmp = tmp36.getTemperature();
Logger.info("Temperature: {}", String.format("%.2f", Double.valueOf(tmp)));
SleepUtil.sleepSeconds(.5);
}
}
Analog input devices also provide an event notification mechanism. To control the brightness of an LED based on ambient light levels:
try (McpAdc adc = new McpAdc(McpAdc.Type.MCP3008, 1);
LDR ldr = new LDR(adc, 1, 1000);
PwmLed led = new PwmLed(18)) {
// Detect variations of 10%, get values every 50ms (the default)
ldr.addListener(event -> led.setValue(1-event.getUnscaledValue()), .1f);
SleepUtil.sleepSeconds(20);
}
Output
The AnalogOutputDevice class provides support for analog output via an Digital to Analog Converter.
Example:
try (PCF8591 dac = new PCF8591();
AnalogOutputDevice aout = AnalogOutputDevice.Builder.builder(0).setDeviceFactory(dac).build()) {
for (float f = 0; f < 1; f += 0.1) {
aout.setValue(f);
SleepUtil.sleepMillis(100);
}
for (float f = 1; f >= 0; f -= 0.1) {
aout.setValue(f);
SleepUtil.sleepMillis(100);
}
}