Skip to content

Instantly share code, notes, and snippets.

@n8ebel
Created February 19, 2018 04:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n8ebel/2f0a16260c295709dcc672b359ba60d8 to your computer and use it in GitHub Desktop.
Save n8ebel/2f0a16260c295709dcc672b359ba60d8 to your computer and use it in GitHub Desktop.
Blink Rainbow HAT LED for Android Things
class MainActivity : Activity() {
private val TAG = MainActivity::class.java.simpleName
private val blinkHandler = Handler()
private var redLED: Gpio? = null
private val blinkRunnable = object : Runnable {
override fun run() {
redLED?.also {
runSafeIO {
it.value = !it.value // Update the GPIO state
// reschedule the update
blinkHandler.postDelayed(this, BLINK_DURATION_MILLIS)
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
runSafeIO {
redLED = RainbowHat.openLedRed()
blinkHandler.postDelayed(blinkRunnable, BLINK_DURATION_MILLIS)
}
}
override fun onDestroy() {
super.onDestroy()
// Remove pending blink Runnable from the handler.
blinkHandler.removeCallbacks(blinkRunnable)
runSafeIO { redLED?.close() }
}
/**
* Run the passed function in try/catch protecting against [IOException] that are
* thrown by the RainbowHAT driver methods
*/
private fun runSafeIO(ioOperation:() -> Unit) {
try {
ioOperation()
} catch (error: IOException) {
Log.e(TAG, "IO Error", error)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment