Skip to content

Instantly share code, notes, and snippets.

@mikepyts
Last active November 4, 2018 23:17
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 mikepyts/eee7bfc55ce9c2a46a369aa8060981c9 to your computer and use it in GitHub Desktop.
Save mikepyts/eee7bfc55ce9c2a46a369aa8060981c9 to your computer and use it in GitHub Desktop.
Gist which demonstrate how to make blinking LED with peripheral manager and handler (Kotlin, Android Things)
package <package_name>
import android.app.Activity
import android.os.Bundle
import android.os.Handler
import android.util.Log
import com.google.android.things.pio.Gpio
import com.google.android.things.pio.PeripheralManager
import java.io.IOException
class BlinkingLED : Activity() {
// Variables
val TAG = "Blinking LED Activity"
val INTERVAL_BETWEEN_BLINKS_MS = 1000
val LED_PIN_NAME = <GPIO_pin>
val mHandler = Handler()
val manager = PeripheralManager.getInstance()
lateinit var mLedGpio: Gpio
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
try {
// Open GPIO connection
mLedGpio = manager.openGpio(LED_PIN_NAME)
// Configure as an output.
mLedGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_HIGH)
// Repeat using a handler.
mHandler.post(mBlinkRunnable)
} catch (e: IOException) {
Log.e(TAG, "Error on Peripheral IO API", e)
}
}
override fun onDestroy() {
super.onDestroy()
try {
// Remove handler events on close.
mHandler.removeCallbacks(mBlinkRunnable)
// Close the resource.
mLedGpio.close()
} catch (e: IOException) {
Log.e(TAG, "Error on PeripheralIO API", e)
}
}
private val mBlinkRunnable = object : Runnable {
override fun run() {
try {
// Toggle the LED state
Log.d(TAG, mLedGpio.value.toString())
mLedGpio.value = !mLedGpio.value
// Schedule another event after delay.
mHandler.postDelayed(this, INTERVAL_BETWEEN_BLINKS_MS.toLong())
} catch (e: IOException) {
Log.e(TAG, "Error on PeripheralIO API", e)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment