]> git.cryptolib.org Git - labortage2013badge.git/blob - firmware/main.c
can send a keypress
[labortage2013badge.git] / firmware / main.c
1 /* Name: main.c
2  * Project: hid-custom-rq example
3  * Author: Christian Starkjohann
4  * Creation Date: 2008-04-07
5  * Tabsize: 4
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 $
9  */
10
11 /*
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:
18 */
19 #define LED_PORT_DDR        DDRB
20 #define LED_PORT_OUTPUT     PORTB
21 #define R_BIT            4
22 #define G_BIT            3
23 #define B_BIT            1
24 #define BUTTON_PIN 4
25
26 #include <stdint.h>
27 #include <string.h>
28 #include <stdbool.h>
29
30 #include <avr/io.h>
31 #include <avr/wdt.h>
32 #include <avr/eeprom.h>
33 #include <avr/interrupt.h>  /* for sei() */
34 #include <util/delay.h>     /* for _delay_ms() */
35
36 #include <avr/pgmspace.h>   /* required by usbdrv.h */
37 #include "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"
41
42 void update_pwm(void);
43
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
80 };
81
82 /* Keyboard usage values, see usb.org's HID-usage-tables document, chapter
83  * 10 Keyboard/Keypad Page for more codes.
84  */
85 #define MOD_CONTROL_LEFT    (1<<0)
86 #define MOD_SHIFT_LEFT      (1<<1)
87 #define MOD_ALT_LEFT        (1<<2)
88 #define MOD_GUI_LEFT        (1<<3)
89 #define MOD_CONTROL_RIGHT   (1<<4)
90 #define MOD_SHIFT_RIGHT     (1<<5)
91 #define MOD_ALT_RIGHT       (1<<6)
92 #define MOD_GUI_RIGHT       (1<<7)
93
94 #define KEY_A       4
95 #define KEY_B       5
96 #define KEY_C       6
97 #define KEY_D       7
98 #define KEY_E       8
99 #define KEY_F       9
100 #define KEY_G       10
101 #define KEY_H       11
102 #define KEY_I       12
103 #define KEY_J       13
104 #define KEY_K       14
105 #define KEY_L       15
106 #define KEY_M       16
107 #define KEY_N       17
108 #define KEY_O       18
109 #define KEY_P       19
110 #define KEY_Q       20
111 #define KEY_R       21
112 #define KEY_S       22
113 #define KEY_T       23
114 #define KEY_U       24
115 #define KEY_V       25
116 #define KEY_W       26
117 #define KEY_X       27
118 #define KEY_Y       28
119 #define KEY_Z       29
120 #define KEY_1       30
121 #define KEY_2       31
122 #define KEY_3       32
123 #define KEY_4       33
124 #define KEY_5       34
125 #define KEY_6       35
126 #define KEY_7       36
127 #define KEY_8       37
128 #define KEY_9       38
129 #define KEY_0       39
130
131 #define KEY_F1      58
132 #define KEY_F2      59
133 #define KEY_F3      60
134 #define KEY_F4      61
135 #define KEY_F5      62
136 #define KEY_F6      63
137 #define KEY_F7      64
138 #define KEY_F8      65
139 #define KEY_F9      66
140 #define KEY_F10     67
141 #define KEY_F11     68
142 #define KEY_F12     69
143
144 #define NUM_LOCK 1
145 #define CAPS_LOCK 2
146 #define SCROLL_LOCK 4
147
148 union {
149         struct {
150                 uint16_t red;
151                 uint16_t green;
152                 uint16_t blue;
153         } name;
154         uint16_t idx[3];
155 } color;
156
157 #define UNI_BUFFER_SIZE 16
158
159 static union {
160         uint8_t  w8[UNI_BUFFER_SIZE];
161         uint16_t w16[UNI_BUFFER_SIZE/2];
162         uint32_t w32[UNI_BUFFER_SIZE/4];
163         void*    ptr[UNI_BUFFER_SIZE/sizeof(void*)];
164 } uni_buffer;
165
166 static uint8_t uni_buffer_fill;
167 static uint8_t current_command;
168
169 typedef struct {
170     uint8_t modifier;
171     uint8_t reserved;
172     uint8_t keycode[6];
173 } keyboard_report_t;
174
175 #define STATE_WAIT 0
176 #define STATE_SEND_KEY 1
177 #define STATE_RELEASE_KEY 2
178
179
180 static keyboard_report_t keyboard_report; // sent to PC
181 static uchar idleRate;           /* in 4 ms units */
182 static uchar key_state = STATE_WAIT;
183 volatile static uchar LED_state = 0xff; // received from PC
184 /* ------------------------------------------------------------------------- */
185
186 void buildReport(uchar send_key) {
187     keyboard_report.modifier = 0;
188
189     if(send_key >= 'a' && send_key <= 'z')
190         keyboard_report.keycode[0] = 4 + (send_key - 'a');
191     else
192         keyboard_report.keycode[0] = 0;
193 }
194
195 uint8_t read_button(void){
196         uint8_t t,v=0;
197         t = DDRB;
198         DDRB &= ~(1<<BUTTON_PIN);
199         PORTB |= 1<<BUTTON_PIN;
200         PORTB &= ~(1<<BUTTON_PIN);
201         v |= PINB;
202         DDRB |= t&(1<<BUTTON_PIN);
203         PORTB &= ~(t&(1<<BUTTON_PIN));
204         v >>= BUTTON_PIN;
205         v &= 1;
206         v ^= 1;
207         return v;
208 }
209
210 void init_temperature_sensor(void){
211         ADMUX = 0x8F;
212         ADCSRA = 0x87;
213 }
214
215 uint16_t read_temperture_sensor(void){
216         ADCSRA |= 0x40;
217         while(ADCSRA & 0x40)
218                 ;
219         return ADC;
220 }
221
222 #if 0
223 uchar   usbFunctionSetup(uchar data[8])
224 {
225 usbRequest_t    *rq = (void *)data;
226
227     usbMsgPtr = reportBuffer;
228     if((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_CLASS){    /* class request type */
229         if(rq->bRequest == USBRQ_HID_GET_REPORT){  /* wValue: ReportType (highbyte), ReportID (lowbyte) */
230             /* we only have one report type, so don't look at wValue */
231             buildReport(keyPressed());
232             return sizeof(reportBuffer);
233         }else if(rq->bRequest == USBRQ_HID_GET_IDLE){
234             usbMsgPtr = &idleRate;
235             return 1;
236         }else if(rq->bRequest == USBRQ_HID_SET_IDLE){
237             idleRate = rq->wValue.bytes[1];
238         }
239     }else{
240         /* no vendor specific requests implemented */
241     }
242     return 0;
243 }
244 #endif
245
246 usbMsgLen_t usbFunctionSetup(uchar data[8])
247 {
248         usbRequest_t    *rq = (usbRequest_t *)data;
249         if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_CLASS) {    /* class request type */
250             color.name.red = 13;
251             switch(rq->bRequest) {
252         case USBRQ_HID_GET_REPORT: // send "no keys pressed" if asked here
253             // wValue: ReportType (highbyte), ReportID (lowbyte)
254             usbMsgPtr = (void *)&keyboard_report; // we only have this one
255             keyboard_report.modifier = 0;
256             keyboard_report.keycode[0] = 0;
257             return sizeof(keyboard_report);
258         case USBRQ_HID_SET_REPORT: // if wLength == 1, should be LED state
259             if (rq->wLength.word == 1) {
260                 current_command = LED_WRITE;
261                 return USB_NO_MSG;
262             }
263             return 0;
264         case USBRQ_HID_GET_IDLE: // send idle rate to PC as required by spec
265             usbMsgPtr = &idleRate;
266             return 1;
267         case USBRQ_HID_SET_IDLE: // save idle rate as required by spec
268             idleRate = rq->wValue.bytes[1];
269             return 0;
270         }
271     }
272     if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_VENDOR) {
273                 current_command = rq->bRequest;
274         switch(rq->bRequest)
275                 {
276                 case CUSTOM_RQ_SET_RGB:
277                         return USB_NO_MSG;
278                 case CUSTOM_RQ_GET_RGB:{
279                         usbMsgLen_t len = 6;
280                         if(len>rq->wLength.word){
281                                 len = rq->wLength.word;
282                         }
283                         usbMsgPtr = (uchar*)color.idx;
284                         return len;
285                 }
286                 case CUSTOM_RQ_READ_MEM:
287                         usbMsgPtr = (uchar*)rq->wValue.word;
288                         return rq->wLength.word;
289                 case CUSTOM_RQ_WRITE_MEM:
290                 case CUSTOM_RQ_EXEC_SPM:
291                         uni_buffer_fill = 4;
292                         uni_buffer.w16[0] = rq->wValue.word;
293                         uni_buffer.w16[1] = rq->wLength.word;
294                         return USB_NO_MSG;
295                 case CUSTOM_RQ_READ_FLASH:
296                         uni_buffer.w16[0] = rq->wValue.word;
297                         uni_buffer.w16[1] = rq->wLength.word;
298                         return USB_NO_MSG;
299                 case CUSTOM_RQ_RESET:
300                         soft_reset((uint8_t)(rq->wValue.word));
301                         break;
302                 case CUSTOM_RQ_READ_BUTTON:
303                         uni_buffer.w8[0] = read_button();
304                         usbMsgPtr = uni_buffer.w8;
305                         return 1;
306                 case CUSTOM_RQ_READ_TMPSENS:
307                         uni_buffer.w16[0] = read_temperture_sensor();
308                         usbMsgPtr = uni_buffer.w8;
309                         return 2;
310                 }
311     }
312
313     return 0;   /* default for not implemented requests: return no data back to host */
314 }
315
316
317 uchar usbFunctionWrite(uchar *data, uchar len)
318 {
319         switch(current_command){
320
321         case LED_WRITE:
322             if (data[0] != LED_state)
323                 LED_state = data[0];
324             return 1; // Data read, not expecting more
325         case CUSTOM_RQ_SET_RGB:
326                 if(len != 6){
327                         return 1;
328                 }
329                 memcpy(color.idx, data, 6);
330         key_state = STATE_SEND_KEY;
331                 return 1;
332         case CUSTOM_RQ_WRITE_MEM:
333                 memcpy(uni_buffer.ptr[0], data, len);
334                 uni_buffer.w16[0] += len;
335                 return !(uni_buffer.w16[1] -= len);
336         case CUSTOM_RQ_EXEC_SPM:
337                 if(uni_buffer_fill < 8){
338                         uint8_t l = 8 - uni_buffer_fill;
339                         if(len<l){
340                                 len = l;
341                         }
342                         memcpy(&(uni_buffer.w8[uni_buffer_fill]), data, len);
343                         uni_buffer_fill += len;
344                         return 0;
345                 }
346                 uni_buffer.w16[1] -= len;
347                 if (uni_buffer.w16[1] > 8) {
348                         memcpy(uni_buffer.ptr[0], data, len);
349                         uni_buffer.w16[0] += len;
350                         return 0;
351                 } else {
352                         memcpy(&(uni_buffer.w8[uni_buffer_fill]), data, len);
353                         exec_spm(uni_buffer.w16[2], uni_buffer.w16[3], uni_buffer.ptr[0], data, len);
354                         return 1;
355                 }
356         default:
357                 return 1;
358         }
359         return 0;
360 }
361 uchar usbFunctionRead(uchar *data, uchar len){
362         uchar ret = len;
363         switch(current_command){
364         case CUSTOM_RQ_READ_FLASH:
365                 while(len--){
366                         *data++ = pgm_read_byte((uni_buffer.w16[0])++);
367                 }
368                 return ret;
369         default:
370                 break;
371         }
372         return 0;
373 }
374
375 static void calibrateOscillator(void)
376 {
377 uchar       step = 128;
378 uchar       trialValue = 0, optimumValue;
379 int         x, optimumDev, targetValue = (unsigned)(1499 * (double)F_CPU / 10.5e6 + 0.5);
380  
381     /* do a binary search: */
382     do {
383         OSCCAL = trialValue + step;
384         x = usbMeasureFrameLength();    // proportional to current real frequency
385         if(x < targetValue)             // frequency still too low
386             trialValue += step;
387         step >>= 1;
388     } while(step > 0);
389     /* We have a precision of +/- 1 for optimum OSCCAL here */
390     /* now do a neighborhood search for optimum value */
391     optimumValue = trialValue;
392     optimumDev = x; // this is certainly far away from optimum
393     for (OSCCAL = trialValue - 1; OSCCAL <= trialValue + 1; OSCCAL++){
394         x = usbMeasureFrameLength() - targetValue;
395         if (x < 0)
396             x = -x;
397         if (x < optimumDev) {
398             optimumDev = x;
399             optimumValue = OSCCAL;
400         }
401     }
402     OSCCAL = optimumValue;
403 }
404  
405
406 void usbEventResetReady(void)
407 {
408     cli();  // usbMeasureFrameLength() counts CPU cycles, so disable interrupts.
409     calibrateOscillator();
410     sei();
411 // we never read the value from eeprom so this causes only degradation of eeprom
412 //    eeprom_write_byte(0, OSCCAL);   // store the calibrated value in EEPROM
413 }
414
415 /* ------------------------------------------------------------------------- */
416
417 int main(void)
418 {
419         uchar   i;
420
421     wdt_enable(WDTO_1S);
422     /* Even if you don't use the watchdog, turn it off here. On newer devices,
423      * the status of the watchdog (on/off, period) is PRESERVED OVER RESET!
424      */
425     /* RESET status: all port bits are inputs without pull-up.
426      * That's the way we need D+ and D-. Therefore we don't need any
427      * additional hardware initialization.
428      */
429
430     memset(&keyboard_report, 0, sizeof(keyboard_report));
431
432     init_temperature_sensor();
433     usbInit();
434     usbDeviceDisconnect();  /* enforce re-enumeration, do this while interrupts are disabled! */
435     i = 0;
436     while(--i){             /* fake USB disconnect for ~512 ms */
437         wdt_reset();
438         _delay_ms(2);
439     }
440     usbDeviceConnect();
441     LED_PORT_DDR |= _BV(R_BIT) | _BV(G_BIT) | _BV(B_BIT);   /* make the LED bit an output */
442
443         
444     sei();
445
446     for(;;){                /* main event loop */
447         //      update_pwm();
448                 
449         wdt_reset();
450         usbPoll();
451
452         if(usbInterruptIsReady())
453             color.name.green = 0x10 | key_state;
454         else
455             color.name.green = 0;
456
457         if(usbInterruptIsReady() && key_state != STATE_WAIT){
458             color.name.red = 16;
459             switch(key_state) {
460             case STATE_SEND_KEY:
461                 color.name.red = 17;
462                 buildReport('x');
463                 key_state = STATE_RELEASE_KEY; // release next
464                 break;
465             case STATE_RELEASE_KEY:
466                 color.name.red = 18;
467                 buildReport(0);
468             default:
469                 key_state = STATE_WAIT; // should not happen
470             }
471                         // start sending
472             usbSetInterrupt((void *)&keyboard_report, sizeof(keyboard_report));
473             color.name.red |= 0x40;
474
475         }
476
477     }
478     return 0;
479 }
480
481 /* ------------------------------------------------------------------------- */