Making the code work on any developer kit

As we mentioned before, the pin names of the Raspberry Pi and the iMX7D are different. You can take a look at the pinout diagrams in the Appendix, and I suggest that you print them out to have them at hand.

Have the pinout diagram of your developer kit at hand.

When we flipped the Rainbow HAT, we could see that the red LED was wired to BCM6, which is pin 31 of the board. While the pin position is the same, that pin on the iMX7D is called GPIO2_IO02.

However, if we look at the source code of the Rainbow HAT driver, which is in Java, we see that it is accessed using a function.

public static Gpio openLedRed() throws IOException {
return openLed(BOARD.getLedR());
}

This is a concept that is used frequently on examples when you want them to work on both devices. At the very minimum you should use a constant for the pin, so if someone has to change it, it is easy to find and update, but having an abstraction is better. This utility is normally called BoardDefaults.

We can identify the board using Build.DEVICE.

The value of Build.DEVICE will tell us which development board we are running in: rpi3 or imx7d_pico; then we can return the values of the pins based on that.

The Rainbow HAT driver uses an interface and then two implementations, one per board. That makes sense for the amount of pins it is using, but if our project uses just a few pins, it is simpler to wrap the logic into each method. Even more, when using Kotlin, we can get one step further and include that code into the get of the constant and use a when selector, like this:

object BoardDefaults {
private const val DEVICE_RPI3 = "rpi3"
private const val DEVICE_IMX7D_PICO = "imx7d_pico"

val ledR: String
get() = when (Build.DEVICE) {
DEVICE_RPI3 -> "BCM6"
DEVICE_IMX7D_PICO -> "GPIO2_IO02"
else -> throw IllegalStateException("Unknown Build.DEVICE
${Build.DEVICE}")
}
}

You can have this object as part of your class, but it is recommended to have it on its own file to separate hardware configuration from logic.

We will include a couple of examples of BoardDefaults throughout the chapter so you can get used to them, but ultimately they are kind of boilerplate code, so we will let them out for clarity.

Time to look at the usage of GPIO in detail.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.93.210