Link Search Menu Expand Document

General Purpose Input / Output (GPIO)

Javadoc.

Key concepts:

Digital

Input

Key concepts:

  • The activeHigh property is optional; it will default to false if pud is set to pull-up, otherwise true.

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:

MCP3008 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, 3.3, 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);
	}
}