Created
February 19, 2018 04:24
-
-
Save n8ebel/2f0a16260c295709dcc672b359ba60d8 to your computer and use it in GitHub Desktop.
Blink Rainbow HAT LED for Android Things
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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