Hackster is hosting Hackster Holidays, Ep. 6: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Monday!Stream Hackster Holidays, Ep. 6 on Monday!
Laurent's Lab
Published © GPL3+

Simple USB Buttons Using an Adafruit Trinket M0

Ever needed to control a computer using big buttons? A simple project to get started with buttons, USB and the Arduino environment.

BeginnerFull instructions provided1.5 hours6,808
Simple USB Buttons Using an Adafruit Trinket M0

Things used in this project

Hardware components

Adafruit Trinket M0
Adafruit Trinket M0
×1
Serpac M4 - Black Enclosure
×1
Philmore Switch Push Button
×2

Hand tools and fabrication machines

Body Reamer

Story

Read more

Custom parts and enclosures

3D-printed enclosure

Schematics

USB_Button_M0

Code

USB_Button_M0

C/C++
#include <Keyboard.h>
 
#define PIN_BUTTON_YEL 0
#define PIN_BUTTON_RED 2
#define TIMEOUT 500 // 500 msec before restarting button
 
void setup()
{
  // Set button pins as inputs with pull-up resistors (when pressed, the buttons will drive the pins low)
  pinMode(PIN_BUTTON_YEL, INPUT_PULLUP);
  pinMode(PIN_BUTTON_RED, INPUT_PULLUP);
 
  // start USB keyboard
  Keyboard.begin();
}

int button_yel_pressed = 0;
unsigned long button_yel_timer = 0;

int button_red_pressed = 0;
unsigned long button_red_timer = 0;

void loop()
{
  if (button_yel_pressed) {
    if (millis() > button_yel_timer + TIMEOUT) {
      button_yel_pressed = 0;
    }
  } else {
    if (digitalRead(PIN_BUTTON_YEL) == LOW) {
      button_yel_pressed = 1;
      button_yel_timer = millis();
      Keyboard.press(KEY_LEFT_GUI); // "Windows" button on a PC
      Keyboard.press(KEY_F4);       // "Windows-F4" is the Skype shortcut to toggle mute on/off
      Keyboard.releaseAll();
    }
  }
 
  if (button_red_pressed) {
    if (millis() > button_red_timer + TIMEOUT) {
      button_red_pressed = 0;
    }
  } else {
    if (digitalRead(PIN_BUTTON_RED) == LOW) {
      button_red_pressed = 1;
      button_red_timer = millis();
      Keyboard.press(KEY_LEFT_GUI); // "Windows" button on a PC
      Keyboard.press('l');          // Windows-L is the Windows shortcut to lock the screen
      Keyboard.releaseAll();
    }
  }
}

Credits

Laurent's Lab

Laurent's Lab

3 projects • 4 followers

Comments