Coroutines on the RaspberryPi (Pi4J-Kotlin)
- April 01, 2023
- 4698 Unique Views
- 2 min read
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!
Don’t Forget to Share This Post!
Comments (0)
No comments yet. Be the first.