Skip to content

Instantly share code, notes, and snippets.

@amitshekhariitbhu
Last active January 26, 2017 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save amitshekhariitbhu/29811ab1e44b6be4f5396a95189fadb5 to your computer and use it in GitHub Desktop.
Save amitshekhariitbhu/29811ab1e44b6be4f5396a95189fadb5 to your computer and use it in GitHub Desktop.
/**
* Example of using Button driver for toggling a LED.
*
* This activity initialize an InputDriver to emit key events when the button GPIO pin state change
* and flip the state of the LED GPIO pin.
*
* You need to connect an LED and a push button switch to pins specified in {@link BoardDefaults}
* according to the schematic provided above.
*/
public class ButtonActivity extends Activity {
private static final String TAG = ButtonActivity.class.getSimpleName();
private Gpio mLedGpio;
private ButtonInputDriver mButtonInputDriver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "Starting ButtonActivity");
PeripheralManagerService pioService = new PeripheralManagerService();
try {
Log.i(TAG, "Configuring GPIO pins");
mLedGpio = pioService.openGpio(BoardDefaults.getGPIOForLED());
mLedGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
Log.i(TAG, "Registering button driver");
// Initialize and register the InputDriver that will emit SPACE key events
// on GPIO state changes.
mButtonInputDriver = new ButtonInputDriver(
BoardDefaults.getGPIOForButton(),
Button.LogicState.PRESSED_WHEN_LOW,
KeyEvent.KEYCODE_SPACE);
mButtonInputDriver.register();
} catch (IOException e) {
Log.e(TAG, "Error configuring GPIO pins", e);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_SPACE) {
// Turn on the LED
setLedValue(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_SPACE) {
// Turn off the LED
setLedValue(false);
return true;
}
return super.onKeyUp(keyCode, event);
}
/**
* Update the value of the LED output.
*/
private void setLedValue(boolean value) {
try {
mLedGpio.setValue(value);
} catch (IOException e) {
Log.e(TAG, "Error updating GPIO value", e);
}
}
@Override
protected void onDestroy(){
super.onDestroy();
if (mButtonInputDriver != null) {
mButtonInputDriver.unregister();
try {
mButtonInputDriver.close();
} catch (IOException e) {
Log.e(TAG, "Error closing Button driver", e);
} finally{
mButtonInputDriver = null;
}
}
if (mLedGpio != null) {
try {
mLedGpio.close();
} catch (IOException e) {
Log.e(TAG, "Error closing LED GPIO", e);
} finally{
mLedGpio = null;
}
mLedGpio = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment