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:
19 #define LED_PORT_DDR DDRB
20 #define LED_PORT_OUTPUT PORTB
32 #include <avr/eeprom.h>
33 #include <avr/interrupt.h> /* for sei() */
34 #include <util/delay.h> /* for _delay_ms() */
36 #include <avr/pgmspace.h> /* required by usbdrv.h */
38 #include "oddebug.h" /* This is also an example for using debug macros */
39 #include "requests.h" /* The custom request numbers we use */
40 #include "special_functions.h"
44 /* ------------------------------------------------------------------------- */
45 /* ----------------------------- USB interface ----------------------------- */
46 /* ------------------------------------------------------------------------- */
47 PROGMEM const char usbHidReportDescriptor[USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH] = {
48 0x05, 0x01, // USAGE_PAGE (Generic Desktop)
49 0x09, 0x06, // USAGE (Keyboard)
50 0xa1, 0x01, // COLLECTION (Application)
51 0x75, 0x01, // REPORT_SIZE (1)
52 0x95, 0x08, // REPORT_COUNT (8)
53 0x05, 0x07, // USAGE_PAGE (Keyboard)(Key Codes)
54 0x19, 0xe0, // USAGE_MINIMUM (Keyboard LeftControl)(224)
55 0x29, 0xe7, // USAGE_MAXIMUM (Keyboard Right GUI)(231)
56 0x15, 0x00, // LOGICAL_MINIMUM (0)
57 0x25, 0x01, // LOGICAL_MAXIMUM (1)
58 0x81, 0x02, // INPUT (Data,Var,Abs) ; Modifier byte
59 0x95, 0x01, // REPORT_COUNT (1)
60 0x75, 0x08, // REPORT_SIZE (8)
61 0x81, 0x03, // INPUT (Cnst,Var,Abs) ; Reserved byte
62 0x95, 0x05, // REPORT_COUNT (5)
63 0x75, 0x01, // REPORT_SIZE (1)
64 0x05, 0x08, // USAGE_PAGE (LEDs)
65 0x19, 0x01, // USAGE_MINIMUM (Num Lock)
66 0x29, 0x05, // USAGE_MAXIMUM (Kana)
67 0x91, 0x02, // OUTPUT (Data,Var,Abs) ; LED report
68 0x95, 0x01, // REPORT_COUNT (1)
69 0x75, 0x03, // REPORT_SIZE (3)
70 0x91, 0x03, // OUTPUT (Cnst,Var,Abs) ; LED report padding
71 0x95, 0x06, // REPORT_COUNT (6)
72 0x75, 0x08, // REPORT_SIZE (8)
73 0x15, 0x00, // LOGICAL_MINIMUM (0)
74 0x25, 0x65, // LOGICAL_MAXIMUM (101)
75 0x05, 0x07, // USAGE_PAGE (Keyboard)(Key Codes)
76 0x19, 0x00, // USAGE_MINIMUM (Reserved (no event indicated))(0)
77 0x29, 0x65, // USAGE_MAXIMUM (Keyboard Application)(101)
78 0x81, 0x00, // INPUT (Data,Ary,Abs)
79 0xc0 // END_COLLECTION
82 uint16_t secret_length_ee EEMEM = 0;
83 uint8_t secret_ee[32] EEMEM;
84 uint8_t reset_counter_ee EEMEM = 0;
85 uint8_t digits_ee EEMEM = 8;
87 /* Keyboard usage values, see usb.org's HID-usage-tables document, chapter
88 * 10 Keyboard/Keypad Page for more codes.
90 #define MOD_CONTROL_LEFT (1<<0)
91 #define MOD_SHIFT_LEFT (1<<1)
92 #define MOD_ALT_LEFT (1<<2)
93 #define MOD_GUI_LEFT (1<<3)
94 #define MOD_CONTROL_RIGHT (1<<4)
95 #define MOD_SHIFT_RIGHT (1<<5)
96 #define MOD_ALT_RIGHT (1<<6)
97 #define MOD_GUI_RIGHT (1<<7)
151 #define SCROLL_LOCK 4
153 static uint8_t dbg_buffer[8];
155 static uint8_t secret[32];
156 static uint16_t secret_length_b;
157 static char token[10];
160 #define UNI_BUFFER_SIZE 36
163 uint8_t w8[UNI_BUFFER_SIZE];
164 uint16_t w16[UNI_BUFFER_SIZE/2];
165 uint32_t w32[UNI_BUFFER_SIZE/4];
166 void* ptr[UNI_BUFFER_SIZE/sizeof(void*)];
169 static uint8_t uni_buffer_fill;
170 static uint8_t current_command;
179 #define STATE_SEND_KEY 1
180 #define STATE_RELEASE_KEY 2
184 static keyboard_report_t keyboard_report; // sent to PC
185 static uchar idleRate; /* in 4 ms units */
186 static uchar key_state = STATE_WAIT;
187 volatile static uchar LED_state = 0xff; // received from PC
188 /* ------------------------------------------------------------------------- */
190 void memory_clean(void) {
191 memset(secret, 0, 32);
195 uint8_t secret_set(void){
201 const uint8_t length_B = (secret_length_b + 7) / 8;
204 eeprom_write_block(secret, secret_ee, length_B);
206 eeprom_read_block(read_back.w8, secret_ee, length_B);
207 r = memcmp(secret, read_back.w8, length_B);
209 memset(read_back.w8, 0, 32);
214 eeprom_write_word(&secret_length_ee, secret_length_b);
216 r = eeprom_read_word(&secret_length_ee) == secret_length_b;
225 void token_generate(void) {
228 eeprom_read_block(secret, secret_ee, 32);
230 hotp(token, secret, eeprom_read_word(&secret_length_ee), percnt_get(0), eeprom_read_byte(&digits_ee));
234 void counter_reset(void) {
235 uint8_t reset_counter;
237 reset_counter = eeprom_read_byte(&reset_counter_ee);
240 eeprom_write_byte(&reset_counter_ee, reset_counter + 1);
243 void counter_init(void) {
245 if (eeprom_read_byte(&reset_counter_ee) == 0) {
251 void buildReport(uchar send_key) {
252 keyboard_report.modifier = 0;
256 keyboard_report.modifier = MOD_SHIFT_LEFT;
257 keyboard_report.keycode[0] = KEY_A + (send_key-'A');
260 keyboard_report.keycode[0] = KEY_A + (send_key-'a');
263 keyboard_report.keycode[0] = KEY_1 + (send_key-'1');
266 keyboard_report.keycode[0] = KEY_0;
269 keyboard_report.keycode[0] = 0;
274 int8_t button_get_debounced(uint8_t debounce_count) {
276 v = PINB & _BV(BUTTON_PIN);
277 while (debounce_count-- && v == (PINB & _BV(BUTTON_PIN))) {
280 if (debounce_count) {
286 void init_temperature_sensor(void){
291 uint16_t read_temperture_sensor(void){
298 usbMsgLen_t usbFunctionSetup(uchar data[8])
300 usbRequest_t *rq = (usbRequest_t *)data;
301 if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_CLASS) { /* class request type */
302 switch(rq->bRequest) {
303 case USBRQ_HID_GET_REPORT: // send "no keys pressed" if asked here
304 // wValue: ReportType (highbyte), ReportID (lowbyte)
305 usbMsgPtr = (void *)&keyboard_report; // we only have this one
306 keyboard_report.modifier = 0;
307 keyboard_report.keycode[0] = 0;
308 return sizeof(keyboard_report);
309 case USBRQ_HID_SET_REPORT: // if wLength == 1, should be LED state
310 if (rq->wLength.word == 1) {
311 current_command = LED_WRITE;
315 case USBRQ_HID_GET_IDLE: // send idle rate to PC as required by spec
316 usbMsgPtr = &idleRate;
318 case USBRQ_HID_SET_IDLE: // save idle rate as required by spec
319 idleRate = rq->wValue.bytes[1];
323 if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_VENDOR) {
324 current_command = rq->bRequest;
327 case CUSTOM_RQ_SET_SECRET:
328 secret_length_b = rq->wValue.word;
329 if (secret_length_b > 256) {
330 secret_length_b = 256;
332 uni_buffer.w8[0] = 0;
334 case CUSTOM_RQ_INC_COUNTER:
337 case CUSTOM_RQ_GET_COUNTER:
338 uni_buffer.w32[0] = percnt_get(0);
339 usbMsgPtr = (usbMsgPtr_t)uni_buffer.w32;
341 case CUSTOM_RQ_RESET_COUNTER:
344 case CUSTOM_RQ_GET_RESET_COUNTER:
346 uni_buffer.w8[0] = eeprom_read_byte(&reset_counter_ee);
347 usbMsgPtr = uni_buffer.w8;
349 case CUSTOM_RQ_SET_DIGITS:
350 if (rq->wValue.bytes[0] > 9) {
351 rq->wValue.bytes[0] = 9;
354 eeprom_write_byte(&digits_ee, rq->wValue.bytes[0]);
356 case CUSTOM_RQ_GET_DIGITS:
358 uni_buffer.w8[0] = eeprom_read_byte(&digits_ee);
359 usbMsgPtr = uni_buffer.w8;
361 case CUSTOM_RQ_GET_TOKEN:
363 usbMsgPtr = (usbMsgPtr_t)token;
364 return strlen(token);
366 case CUSTOM_RQ_PRESS_BUTTON:
367 key_state = STATE_SEND_KEY;
369 case CUSTOM_RQ_CLR_DBG:
370 memset(dbg_buffer, 0, sizeof(dbg_buffer));
372 case CUSTOM_RQ_SET_DBG:
374 case CUSTOM_RQ_GET_DBG:{
376 if(len > rq->wLength.word){
377 len = rq->wLength.word;
379 usbMsgPtr = dbg_buffer;
382 case CUSTOM_RQ_READ_MEM:
383 usbMsgPtr = (uchar*)rq->wValue.word;
384 return rq->wLength.word;
385 case CUSTOM_RQ_WRITE_MEM:
386 case CUSTOM_RQ_EXEC_SPM:
387 /* uni_buffer_fill = 4;
388 uni_buffer.w16[0] = rq->wValue.word;
389 uni_buffer.w16[1] = rq->wLength.word;
391 */ case CUSTOM_RQ_READ_FLASH:
392 uni_buffer.w16[0] = rq->wValue.word;
393 uni_buffer.w16[1] = rq->wLength.word;
396 case CUSTOM_RQ_RESET:
397 soft_reset((uint8_t)(rq->wValue.word));
399 case CUSTOM_RQ_READ_BUTTON:
400 uni_buffer.w8[0] = button_get_debounced(25);
401 usbMsgPtr = uni_buffer.w8;
403 case CUSTOM_RQ_READ_TMPSENS:
404 uni_buffer.w16[0] = read_temperture_sensor();
405 usbMsgPtr = uni_buffer.w8;
410 return 0; /* default for not implemented requests: return no data back to host */
414 uchar usbFunctionWrite(uchar *data, uchar len)
416 switch(current_command){
419 if (data[0] != LED_state)
421 return 1; // Data read, not expecting more
422 case CUSTOM_RQ_SET_SECRET:
424 if (uni_buffer.w8[0] < (secret_length_b + 7) / 8) {
425 memcpy(&secret[uni_buffer.w8[0]], data, len);
426 uni_buffer.w8[0] += len;
428 if (uni_buffer.w8[0] >= (secret_length_b + 7) / 8) {
434 case CUSTOM_RQ_SET_DBG:
435 if(len > sizeof(dbg_buffer)){
436 len = sizeof(dbg_buffer);
438 memcpy(dbg_buffer, data, len);
440 case CUSTOM_RQ_WRITE_MEM:
441 memcpy(uni_buffer.ptr[0], data, len);
442 uni_buffer.w16[0] += len;
443 return !(uni_buffer.w16[1] -= len);
444 case CUSTOM_RQ_EXEC_SPM:
445 if(uni_buffer_fill < 8){
446 uint8_t l = 8 - uni_buffer_fill;
450 memcpy(&(uni_buffer.w8[uni_buffer_fill]), data, len);
451 uni_buffer_fill += len;
454 uni_buffer.w16[1] -= len;
455 if (uni_buffer.w16[1] > 8) {
456 memcpy(uni_buffer.ptr[0], data, len);
457 uni_buffer.w16[0] += len;
460 memcpy(&(uni_buffer.w8[uni_buffer_fill]), data, len);
461 exec_spm(uni_buffer.w16[2], uni_buffer.w16[3], uni_buffer.ptr[0], data, len);
469 uchar usbFunctionRead(uchar *data, uchar len){
471 switch(current_command){
472 case CUSTOM_RQ_READ_FLASH:
474 *data++ = pgm_read_byte((uni_buffer.w16[0])++);
483 static void calibrateOscillator(void)
486 uchar trialValue = 0, optimumValue;
487 int x, optimumDev, targetValue = (unsigned)(1499 * (double)F_CPU / 10.5e6 + 0.5);
489 /* do a binary search: */
491 OSCCAL = trialValue + step;
492 x = usbMeasureFrameLength(); // proportional to current real frequency
493 if(x < targetValue) // frequency still too low
497 /* We have a precision of +/- 1 for optimum OSCCAL here */
498 /* now do a neighborhood search for optimum value */
499 optimumValue = trialValue;
500 optimumDev = x; // this is certainly far away from optimum
501 for (OSCCAL = trialValue - 1; OSCCAL <= trialValue + 1; OSCCAL++){
502 x = usbMeasureFrameLength() - targetValue;
505 if (x < optimumDev) {
507 optimumValue = OSCCAL;
510 OSCCAL = optimumValue;
514 void usbEventResetReady(void)
516 cli(); // usbMeasureFrameLength() counts CPU cycles, so disable interrupts.
517 calibrateOscillator();
519 // we never read the value from eeprom so this causes only degradation of eeprom
520 // eeprom_write_byte(0, OSCCAL); // store the calibrated value in EEPROM
523 /* ------------------------------------------------------------------------- */
528 int8_t i = 0, last_stable_button_state = 0;
531 /* Even if you don't use the watchdog, turn it off here. On newer devices,
532 * the status of the watchdog (on/off, period) is PRESERVED OVER RESET!
534 /* RESET status: all port bits are inputs without pull-up.
535 * That's the way we need D+ and D-. Therefore we don't need any
536 * additional hardware initialization.
539 DDRB &= ~_BV(BUTTON_PIN); /* make button pin input */
540 PORTB |= _BV(BUTTON_PIN); /* turn on pull-up resistor */
541 init_temperature_sensor();
543 usbDeviceDisconnect(); /* enforce re-enumeration, do this while interrupts are disabled! */
544 while(--i){ /* fake USB disconnect for ~512 ms */
552 for(;;){ /* main event loop */
556 i = button_get_debounced(25);
558 if (last_stable_button_state == 0 && i == 1) {
559 key_state = STATE_SEND_KEY;
561 last_stable_button_state = i;
564 if(usbInterruptIsReady() && key_state != STATE_WAIT){
567 buildReport(token[idx]);
568 key_state = STATE_RELEASE_KEY; // release next
570 case STATE_RELEASE_KEY:
573 if (token[idx] == '\0') {
575 key_state = STATE_WAIT;
577 key_state = STATE_SEND_KEY;
581 key_state = STATE_WAIT; // should not happen
584 usbSetInterrupt((void *)&keyboard_report, sizeof(keyboard_report));
592 /* ------------------------------------------------------------------------- */