Friends of OpenJDK Today

Coroutines on the RaspberryPi (Pi4J-Kotlin)

April 01, 2023

Author(s)

  • Avatar photo
    Muhammad Hashim

    Senior Software Engineer at Instabug, FOSS Enthusiast, and a Writer.

If you didn’t know already, Pi4J has had a Kotlin DSL for quite some time now.

And I’m here to announce the latest release v2.4.0 with a sack of additions and to tell you about all the good stuff that’s been added since the first release.

1. Coroutines

If the pi4j { … } wasn’t good enough for ya, and you want to use coroutines instead of weaving fat threads on your precious precious Pi, you can now use the new pi4jAsync { … } block—It can do everything pi4j { … } does + you can run suspended functions within.

I know you guys just want to use coroutines so that you can call delay() instead of Thread::sleep. And I won’t disappoint you. Here’s a blinking LED example with coroutines:

pi4jAsync {
    digitalOutput(PIN_LED) {
        id(“led”)
        name(“LED Flasher”)
        shutdown(DigitalState.LOW)
        initial(DigitalState.LOW)
        piGpioProvider()
    }.run {
        while (true) {
            toggle()
            delay(500L)  // The most loved suspended function
        }
    }
}

Feel free to visit the docs on coroutines support, and the full example.

2. I²C DSL

This will add a little beauty to your life when dealing with I²C

i2c(1, 0x3f) {
    id(“TCA9534”)
    linuxFsI2CProvider()
}.use { tca9534Dev ->
  // use here. Will auto close
}

Feel free to visit the docs on I²C support, and the full example.

3. Serial DSL

I know I’m messing with “taboos” right now, but I’ve just made Serial look nice. You guessed it right, it’s as simple as just a serial { … } block

serial(“/dev/ttyS0”) {
    use_9600_N81()
    dataBits_8()
    parity(Parity.NONE)
    stopBits(StopBits._1)
    flowControl(FlowControl.NONE)
    piGpioSerialProvider()
}.open {
  // use here. 
}

You know the drill, feel free to visit the docs on Serial support, and the full example.

4. Misc

  • Updated Pi4J to v2.3.0
  • Updated docs and examples


If you want to share feedback, or report a bug, feel free to discuss and open issues on the Github Repo!

Topics:

Related Articles

View All

Author(s)

  • Avatar photo
    Muhammad Hashim

    Senior Software Engineer at Instabug, FOSS Enthusiast, and a Writer.

Comments (0)

Your email address will not be published. Required fields are marked *

Highlight your code snippets using [code lang="language name"] shortcode. Just insert your code between opening and closing tag: [code lang="java"] code [/code]. Or specify another language.

Save my name, email, and website in this browser for the next time I comment.

Subscribe to foojay updates:

https://foojay.io/feed/
Copied to the clipboard