2 * Project: hid-custom-rq example
3 * Author: Christian Starkjohann
4 * Creation Date: 2008-04-07
6 * Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
7 * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
8 * This Revision: $Id: main.c 692 2008-11-07 15:07:40Z cs $
12 This example should run on most AVRs with only little changes. No special
13 hardware resources except INT0 are used. You may have to change usbconfig.h for
14 different I/O pins for USB. Please note that USB D+ must be the INT0 pin, or
15 at least be connected to INT0 as well.
16 We assume that an LED is connected to port B bit 0. If you connect it to a
17 different port or bit, change the macros below:
21 #define SIMPLE_COUNTER 1
29 #include <avr/eeprom.h>
30 #include <avr/interrupt.h> /* for sei() */
31 #include <util/delay.h> /* for _delay_ms() */
33 #include <avr/pgmspace.h> /* required by usbdrv.h */
35 #include "oddebug.h" /* This is also an example for using debug macros */
36 #include "requests.h" /* The custom request numbers we use */
41 #include "usb_keyboard_codes.h"
43 /* ------------------------------------------------------------------------- */
44 /* ----------------------------- USB interface ----------------------------- */
45 /* ------------------------------------------------------------------------- */
48 #define STATE_SEND_KEY 1
49 #define STATE_RELEASE_KEY 2
52 PROGMEM const char usbHidReportDescriptor[USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH] = {
53 0x05, 0x01, // USAGE_PAGE (Generic Desktop)
54 0x09, 0x06, // USAGE (Keyboard)
55 0xa1, 0x01, // COLLECTION (Application)
56 0x75, 0x01, // REPORT_SIZE (1)
57 0x95, 0x08, // REPORT_COUNT (8)
58 0x05, 0x07, // USAGE_PAGE (Keyboard)(Key Codes)
59 0x19, 0xe0, // USAGE_MINIMUM (Keyboard LeftControl)(224)
60 0x29, 0xe7, // USAGE_MAXIMUM (Keyboard Right GUI)(231)
61 0x15, 0x00, // LOGICAL_MINIMUM (0)
62 0x25, 0x01, // LOGICAL_MAXIMUM (1)
63 0x81, 0x02, // INPUT (Data,Var,Abs) ; Modifier byte
64 0x95, 0x01, // REPORT_COUNT (1)
65 0x75, 0x08, // REPORT_SIZE (8)
66 0x81, 0x03, // INPUT (Cnst,Var,Abs) ; Reserved byte
67 0x95, 0x05, // REPORT_COUNT (5)
68 0x75, 0x01, // REPORT_SIZE (1)
69 0x05, 0x08, // USAGE_PAGE (LEDs)
70 0x19, 0x01, // USAGE_MINIMUM (Num Lock)
71 0x29, 0x05, // USAGE_MAXIMUM (Kana)
72 0x91, 0x02, // OUTPUT (Data,Var,Abs) ; LED report
73 0x95, 0x01, // REPORT_COUNT (1)
74 0x75, 0x03, // REPORT_SIZE (3)
75 0x91, 0x03, // OUTPUT (Cnst,Var,Abs) ; LED report padding
76 0x95, 0x06, // REPORT_COUNT (6)
77 0x75, 0x08, // REPORT_SIZE (8)
78 0x15, 0x00, // LOGICAL_MINIMUM (0)
79 0x25, 0x65, // LOGICAL_MAXIMUM (101)
80 0x05, 0x07, // USAGE_PAGE (Keyboard)(Key Codes)
81 0x19, 0x00, // USAGE_MINIMUM (Reserved (no event indicated))(0)
82 0x29, 0x65, // USAGE_MAXIMUM (Keyboard Application)(101)
83 0x81, 0x00, // INPUT (Data,Ary,Abs)
84 0xc0 // END_COLLECTION
87 static uint16_t secret_length_ee EEMEM = 0;
88 static uint8_t secret_ee[32] EEMEM;
89 static uint8_t reset_counter_ee EEMEM = 0;
90 static uint8_t digits_ee EEMEM = 8;
93 static uint32_t counter_ee EEMEM = 0;
96 static uint8_t dbg_buffer[8];
97 static uint8_t secret[32];
98 static uint16_t secret_length_b;
99 static char token[10];
101 #define UNI_BUFFER_SIZE 16
103 static union __attribute__((packed)) {
104 uint8_t w8[UNI_BUFFER_SIZE];
105 uint16_t w16[UNI_BUFFER_SIZE/2];
106 uint32_t w32[UNI_BUFFER_SIZE/4];
107 void* ptr[UNI_BUFFER_SIZE/sizeof(void*)];
110 static uint8_t uni_buffer_fill;
111 static uint8_t current_command;
119 static keyboard_report_t keyboard_report; /* report sent to the host */
120 static uchar idleRate; /* in 4 ms units */
121 static uchar key_state = STATE_WAIT;
122 volatile static uchar LED_state = 0xff;
123 /* ------------------------------------------------------------------------- */
126 void memory_clean(void) {
127 memset(secret, 0, 32);
134 uint8_t secret_set(void){
142 const uint8_t length_B = (secret_length_b + 7) / 8;
145 eeprom_write_block(secret, secret_ee, length_B);
148 eeprom_read_block(read_back.w8, secret_ee, length_B);
149 r = memcmp(secret, read_back.w8, length_B);
151 memset(read_back.w8, 0, 32);
157 eeprom_write_word(&secret_length_ee, secret_length_b);
160 r = eeprom_read_word(&secret_length_ee) == secret_length_b;
174 void counter_inc(void){
178 t = eeprom_read_dword(&counter_ee);
180 eeprom_write_dword(&counter_ee, t + 1);
187 void counter_reset(void) {
188 uint8_t reset_counter;
190 reset_counter = eeprom_read_byte(&reset_counter_ee);
193 eeprom_write_dword(&counter_ee, 0);
198 eeprom_write_byte(&reset_counter_ee, reset_counter + 1);
202 void counter_init(void) {
205 if (eeprom_read_byte(&reset_counter_ee) == 0) {
213 void token_generate(void) {
216 eeprom_read_block(secret, secret_ee, 32);
219 hotp(token, secret, eeprom_read_word(&secret_length_ee), eeprom_read_dword(&counter_ee), eeprom_read_byte(&digits_ee));
221 hotp(token, secret, eeprom_read_word(&secret_length_ee), percnt_get(0), eeprom_read_byte(&digits_ee));
228 void buildReport(uchar send_key) {
229 keyboard_report.modifier = 0;
233 keyboard_report.modifier = MOD_SHIFT_LEFT;
234 keyboard_report.keycode[0] = KEY_A + (send_key-'A');
237 keyboard_report.keycode[0] = KEY_A + (send_key-'a');
240 keyboard_report.keycode[0] = KEY_1 + (send_key-'1');
243 keyboard_report.keycode[0] = KEY_0;
246 keyboard_report.keycode[0] = 0;
251 int8_t button_get_debounced(volatile uint8_t debounce_count) {
253 v = PINB & _BV(BUTTON_PIN);
254 while (debounce_count-- && v == (PINB & _BV(BUTTON_PIN))) {
257 if (debounce_count) {
263 usbMsgLen_t usbFunctionSetup(uchar data[8])
265 usbRequest_t *rq = (usbRequest_t *)data;
266 if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_CLASS) { /* class request type */
267 switch(rq->bRequest) {
268 case USBRQ_HID_GET_REPORT: // send "no keys pressed" if asked here
269 // wValue: ReportType (highbyte), ReportID (lowbyte)
270 usbMsgPtr = (void *)&keyboard_report; // we only have this one
271 keyboard_report.modifier = 0;
272 keyboard_report.keycode[0] = 0;
273 return sizeof(keyboard_report);
274 case USBRQ_HID_SET_REPORT: // if wLength == 1, should be LED state
275 if (rq->wLength.word == 1) {
276 current_command = LED_WRITE;
280 case USBRQ_HID_GET_IDLE: // send idle rate to PC as required by spec
281 usbMsgPtr = &idleRate;
283 case USBRQ_HID_SET_IDLE: // save idle rate as required by spec
284 idleRate = rq->wValue.bytes[1];
288 if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_VENDOR) {
289 current_command = rq->bRequest;
292 case CUSTOM_RQ_SET_SECRET:
293 secret_length_b = rq->wValue.word;
294 if (secret_length_b > 256) {
295 secret_length_b = 256;
297 uni_buffer.w8[0] = 0;
299 case CUSTOM_RQ_INC_COUNTER:
302 case CUSTOM_RQ_GET_COUNTER:
305 uni_buffer.w32[0] = eeprom_read_dword(&counter_ee);
307 uni_buffer.w32[0] = percnt_get(0);
309 usbMsgPtr = (usbMsgPtr_t)uni_buffer.w32;
311 case CUSTOM_RQ_RESET_COUNTER:
314 case CUSTOM_RQ_GET_RESET_COUNTER:
316 uni_buffer.w8[0] = eeprom_read_byte(&reset_counter_ee);
317 usbMsgPtr = uni_buffer.w8;
319 case CUSTOM_RQ_SET_DIGITS:
320 if (rq->wValue.bytes[0] > 9) {
321 rq->wValue.bytes[0] = 9;
324 eeprom_write_byte(&digits_ee, rq->wValue.bytes[0]);
326 case CUSTOM_RQ_GET_DIGITS:
328 uni_buffer.w8[0] = eeprom_read_byte(&digits_ee);
329 usbMsgPtr = uni_buffer.w8;
331 case CUSTOM_RQ_GET_TOKEN:
333 usbMsgPtr = (usbMsgPtr_t)token;
334 return strlen(token);
336 case CUSTOM_RQ_PRESS_BUTTON:
337 key_state = STATE_SEND_KEY;
339 case CUSTOM_RQ_CLR_DBG:
340 memset(dbg_buffer, 0, sizeof(dbg_buffer));
342 case CUSTOM_RQ_SET_DBG:
344 case CUSTOM_RQ_GET_DBG:{
346 if(len > rq->wLength.word){
347 len = rq->wLength.word;
349 usbMsgPtr = dbg_buffer;
352 case CUSTOM_RQ_RESET:
353 soft_reset((uint8_t)(rq->wValue.word));
355 case CUSTOM_RQ_READ_BUTTON:
356 uni_buffer.w8[0] = button_get_debounced(25);
357 usbMsgPtr = uni_buffer.w8;
362 return 0; /* default for not implemented requests: return no data back to host */
366 uchar usbFunctionWrite(uchar *data, uchar len)
368 switch(current_command){
371 if (data[0] != LED_state)
373 return 1; // Data read, not expecting more
374 case CUSTOM_RQ_SET_SECRET:
376 if (uni_buffer.w8[0] < (secret_length_b + 7) / 8) {
377 memcpy(&secret[uni_buffer.w8[0]], data, len);
378 uni_buffer.w8[0] += len;
380 if (uni_buffer.w8[0] >= (secret_length_b + 7) / 8) {
386 case CUSTOM_RQ_SET_DBG:
387 if(len > sizeof(dbg_buffer)){
388 len = sizeof(dbg_buffer);
390 memcpy(dbg_buffer, data, len);
397 uchar usbFunctionRead(uchar *data, uchar len){
401 static void calibrateOscillator(void)
404 uchar trialValue = 0, optimumValue;
405 int x, optimumDev, targetValue = (unsigned)(1499 * (double)F_CPU / 10.5e6 + 0.5);
407 /* do a binary search: */
409 OSCCAL = trialValue + step;
410 x = usbMeasureFrameLength(); // proportional to current real frequency
411 if(x < targetValue) // frequency still too low
415 /* We have a precision of +/- 1 for optimum OSCCAL here */
416 /* now do a neighborhood search for optimum value */
417 optimumValue = trialValue;
418 optimumDev = x; // this is certainly far away from optimum
419 for (OSCCAL = trialValue - 1; OSCCAL <= trialValue + 1; OSCCAL++){
420 x = usbMeasureFrameLength() - targetValue;
423 if (x < optimumDev) {
425 optimumValue = OSCCAL;
428 OSCCAL = optimumValue;
432 void usbEventResetReady(void)
434 cli(); // usbMeasureFrameLength() counts CPU cycles, so disable interrupts.
435 calibrateOscillator();
437 // we never read the value from eeprom so this causes only degradation of eeprom
438 // eeprom_write_byte(0, OSCCAL); // store the calibrated value in EEPROM
441 /* ------------------------------------------------------------------------- */
446 int8_t i = 0, last_stable_button_state = 0;
449 /* Even if you don't use the watchdog, turn it off here. On newer devices,
450 * the status of the watchdog (on/off, period) is PRESERVED OVER RESET!
452 /* RESET status: all port bits are inputs without pull-up.
453 * That's the way we need D+ and D-. Therefore we don't need any
454 * additional hardware initialization.
457 DDRB &= ~_BV(BUTTON_PIN); /* make button pin input */
458 PORTB |= _BV(BUTTON_PIN); /* turn on pull-up resistor */
461 usbDeviceDisconnect(); /* enforce re-enumeration, do this while interrupts are disabled! */
462 while(--i){ /* fake USB disconnect for ~512 ms */
470 for(;;){ /* main event loop */
474 i = button_get_debounced(25);
476 if (last_stable_button_state == 0 && i == 1) {
477 key_state = STATE_SEND_KEY;
479 last_stable_button_state = i;
482 if(usbInterruptIsReady() && key_state != STATE_WAIT){
485 buildReport(token[idx]);
486 key_state = STATE_RELEASE_KEY; // release next
488 case STATE_RELEASE_KEY:
491 if (token[idx] == '\0') {
493 key_state = STATE_WAIT;
495 key_state = STATE_SEND_KEY;
499 key_state = STATE_WAIT; // should not happen
502 usbSetInterrupt((void *)&keyboard_report, sizeof(keyboard_report));
510 /* ------------------------------------------------------------------------- */