Skip to content

Instantly share code, notes, and snippets.

@rodolfo3
Created February 16, 2014 04:47
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 rodolfo3/d4282523758d35a1fb83 to your computer and use it in GitHub Desktop.
Save rodolfo3/d4282523758d35a1fb83 to your computer and use it in GitHub Desktop.
Minimum code to Arduino USB Keyboard using v-usb + Push button (from http://rodolfo3.wordpress.com)
// for Atmega328P
#define USB_INTR_VECTOR INT0_vect
#include "UsbKeyboard.h"
#define buttonPin 12
// To use USB, the interruption Timer0 is disabled,
// breaking the default delay function from Arduino
// Replacing by a new one
void delayMs(unsigned int ms) { // Safe delay helper function
for (int i = 0; i < ms; i++) {
delayMicroseconds(1000);
}
}
void setup() {
// Disable timer0 since it can mess with the USB timing. Note that
// this means some functions such as delay() will no longer work.
TIMSK0&=!(1<<TOIE0);
// Clear interrupts while performing time-critical operations
cli();
// Force re-enumeration so the host will detect us
usbDeviceDisconnect();
delayMs(250);
usbDeviceConnect();
// Set interrupts again
sei();
}
int current = LOW;
int previous = LOW;
void loop() {
UsbKeyboard.update();
current = digitalRead(buttonPin);
if (current == HIGH && previous == LOW) {
UsbKeyboard.sendKeyDown(KEY_H);
UsbKeyboard.waitReady();
} else if (current == LOW && previous == HIGH) {
UsbKeyboard.sendKeyUp(KEY_H);
UsbKeyboard.waitReady();
}
previous = current;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment