Skip to content
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
Cannot retrieve contributors at this time
title weight
Building an I/O Instance

A GPIO can be configured like in the following example:

var ledConfig = DigitalOutput.newConfigBuilder(pi4j)
    .name("My Digital Output")

newConfigBuilder parameters


The id field is used internally inside the Pi4J context/runtime to keep track of the instances. If you don't assign an id, Pi4J will create a unique ID string for the instance -- so its optional and only needed if you want to specify your own unique ID string.

Additionally, you can retrieve the I/O instance from the Pi4J context anywhere else in your program if needed by the id. This can help in some cases where you only need to pass around the single Pi4J context, and you can still gain access to the I/O instances without having to track and pass around your own variable references. So even if your variable reference to an I/O instance goes out of scope, Pi4J will maintain a reference to the I/O instance internally until it is shutdown().

// Three ways to get existing LED output instance
DigitalOutput led ="my-led");
var led = (DigitalOutput)"my-led");
var led ="my-led", DigitalOutput.class);

Internally the I/O instances are maintained by the Registry. You can gain access to the Registry via the context. There are additional methods in registry to interrogate/discover/enumerate the created I/O instances at runtime.

// Get the Pi4J I/O registry
Registry registry = pi4j.registry();

// Check to see if the LED output already exists (by id)
boolean myLedAlreadyExists = registry.exists("my-led");

// Get all digital output instances from the Pi4J I/O registry       
var outputs = registry.allByIoType(IOType.DIGITAL_OUTPUT);

name and description

Fields like name and description are entirely optional and not used by Pi4J internally except to print if performing a describe() or toString() operation on Pi4J objects.

// Create digital output I/O configuration
var config = DigitalOutput.newConfigBuilder(pi4j)
    .name("My Digital Output")

// Create digital output I/O instance using configuration
var output = pi4j.create(config);

// Print digital output object to system out


// > IO: "My Digital Output" {my-dout} <> {DOUT-26} 

Reuse the config

The config object can be reused to create multiple GPIOs by overriding the address (and id if used) for each I/O instance:

var config = DigitalOutput.newConfigBuilder(pi4j)

var pin0 = pi4j.create(config.address(0).id("my-led"));
var pin1 = pi4j.create(config.address(1).id("my-relay"));
var pin2 = pi4j.create(config.address(2).id("my-lock"));
var pin3 = pi4j.create(config.address(3).id("my-pump"));