Instantly share code, notes, and snippets.

Embed
What would you like to do?
package fr.xebia.androidthingskotlin
import android.app.Activity
import android.os.Bundle
import android.view.KeyEvent
import com.google.android.things.contrib.driver.button.Button
import com.google.android.things.contrib.driver.button.ButtonInputDriver
import com.google.android.things.pio.Gpio
import com.google.android.things.pio.PeripheralManagerService
class ButtonActivity : Activity() {
private lateinit var ledGpio: Gpio
private lateinit var buttonInputDriver: ButtonInputDriver
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val pioService = PeripheralManagerService()
ledGpio = pioService.openGpio(BoardDefaults.gpioForLED)
ledGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW)
buttonInputDriver = ButtonInputDriver(
BoardDefaults.gpioForButton,
Button.LogicState.PRESSED_WHEN_LOW,
KeyEvent.KEYCODE_SPACE)
buttonInputDriver.register()
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
when (keyCode) {
KeyEvent.KEYCODE_SPACE -> {
setLedValue(true)
return true
}
else -> return super.onKeyDown(keyCode, event)
}
}
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
when (keyCode) {
KeyEvent.KEYCODE_SPACE -> {
setLedValue(false)
return true
}
else -> return super.onKeyUp(keyCode, event)
}
}
private fun setLedValue(value: Boolean) {
ledGpio.value = value
}
override fun onDestroy() {
super.onDestroy()
buttonInputDriver.unregister()
buttonInputDriver.close()
ledGpio.close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment