]> git.cryptolib.org Git - labortage2013badge.git/blob - firmware/main.c
keyboard functionality still not working
[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 const PROGMEM char usbHidReportDescriptor[35] = {   /* USB report descriptor */
48     0x05, 0x01,                    // USAGE_PAGE (Generic Desktop)
49     0x09, 0x06,                    // USAGE (Keyboard)
50     0xa1, 0x01,                    // COLLECTION (Application)
51     0x05, 0x07,                    //   USAGE_PAGE (Keyboard)
52     0x19, 0xe0,                    //   USAGE_MINIMUM (Keyboard LeftControl)
53     0x29, 0xe7,                    //   USAGE_MAXIMUM (Keyboard Right GUI)
54     0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
55     0x25, 0x01,                    //   LOGICAL_MAXIMUM (1)
56     0x75, 0x01,                    //   REPORT_SIZE (1)
57     0x95, 0x08,                    //   REPORT_COUNT (8)
58     0x81, 0x02,                    //   INPUT (Data,Var,Abs)
59     0x95, 0x01,                    //   REPORT_COUNT (1)
60     0x75, 0x08,                    //   REPORT_SIZE (8)
61     0x25, 0x65,                    //   LOGICAL_MAXIMUM (101)
62     0x19, 0x00,                    //   USAGE_MINIMUM (Reserved (no event indicated))
63     0x29, 0x65,                    //   USAGE_MAXIMUM (Keyboard Application)
64     0x81, 0x00,                    //   INPUT (Data,Ary,Abs)
65     0xc0                           // END_COLLECTION
66 };
67 /* We use a simplifed keyboard report descriptor which does not support the
68  * boot protocol. We don't allow setting status LEDs and we only allow one
69  * simultaneous key press (except modifiers). We can therefore use short
70  * 2 byte input reports.
71  * The report descriptor has been created with usb.org's "HID Descriptor Tool"
72  * which can be downloaded from http://www.usb.org/developers/hidpage/.
73  * Redundant entries (such as LOGICAL_MINIMUM and USAGE_PAGE) have been omitted
74  * for the second INPUT item.
75  */
76
77 /* Keyboard usage values, see usb.org's HID-usage-tables document, chapter
78  * 10 Keyboard/Keypad Page for more codes.
79  */
80 #define MOD_CONTROL_LEFT    (1<<0)
81 #define MOD_SHIFT_LEFT      (1<<1)
82 #define MOD_ALT_LEFT        (1<<2)
83 #define MOD_GUI_LEFT        (1<<3)
84 #define MOD_CONTROL_RIGHT   (1<<4)
85 #define MOD_SHIFT_RIGHT     (1<<5)
86 #define MOD_ALT_RIGHT       (1<<6)
87 #define MOD_GUI_RIGHT       (1<<7)
88
89 #define KEY_A       4
90 #define KEY_B       5
91 #define KEY_C       6
92 #define KEY_D       7
93 #define KEY_E       8
94 #define KEY_F       9
95 #define KEY_G       10
96 #define KEY_H       11
97 #define KEY_I       12
98 #define KEY_J       13
99 #define KEY_K       14
100 #define KEY_L       15
101 #define KEY_M       16
102 #define KEY_N       17
103 #define KEY_O       18
104 #define KEY_P       19
105 #define KEY_Q       20
106 #define KEY_R       21
107 #define KEY_S       22
108 #define KEY_T       23
109 #define KEY_U       24
110 #define KEY_V       25
111 #define KEY_W       26
112 #define KEY_X       27
113 #define KEY_Y       28
114 #define KEY_Z       29
115 #define KEY_1       30
116 #define KEY_2       31
117 #define KEY_3       32
118 #define KEY_4       33
119 #define KEY_5       34
120 #define KEY_6       35
121 #define KEY_7       36
122 #define KEY_8       37
123 #define KEY_9       38
124 #define KEY_0       39
125
126 #define KEY_F1      58
127 #define KEY_F2      59
128 #define KEY_F3      60
129 #define KEY_F4      61
130 #define KEY_F5      62
131 #define KEY_F6      63
132 #define KEY_F7      64
133 #define KEY_F8      65
134 #define KEY_F9      66
135 #define KEY_F10     67
136 #define KEY_F11     68
137 #define KEY_F12     69
138
139 union {
140         struct {
141                 uint16_t red;
142                 uint16_t green;
143                 uint16_t blue;
144         } name;
145         uint16_t idx[3];
146 } color;
147
148 #define UNI_BUFFER_SIZE 16
149
150 static union {
151         uint8_t  w8[UNI_BUFFER_SIZE];
152         uint16_t w16[UNI_BUFFER_SIZE/2];
153         uint32_t w32[UNI_BUFFER_SIZE/4];
154         void*    ptr[UNI_BUFFER_SIZE/sizeof(void*)];
155 } uni_buffer;
156
157 static uint8_t uni_buffer_fill;
158 static uint8_t current_command;
159
160 static uchar    reportBuffer[2];    /* buffer for HID reports */
161 static uchar    idleRate;           /* in 4 ms units */
162
163 static bool  keyDidChange = false;
164 /* ------------------------------------------------------------------------- */
165
166
167 uint8_t read_button(void){
168         uint8_t t,v=0;
169         t = DDRB;
170         DDRB &= ~(1<<BUTTON_PIN);
171         PORTB |= 1<<BUTTON_PIN;
172         PORTB &= ~(1<<BUTTON_PIN);
173         v |= PINB;
174         DDRB |= t&(1<<BUTTON_PIN);
175         PORTB &= ~(t&(1<<BUTTON_PIN));
176         v >>= BUTTON_PIN;
177         v &= 1;
178         v ^= 1;
179         return v;
180 }
181
182 void init_temperature_sensor(void){
183         ADMUX = 0x8F;
184         ADCSRA = 0x87;
185 }
186
187 uint16_t read_temperture_sensor(void){
188         ADCSRA |= 0x40;
189         while(ADCSRA & 0x40)
190                 ;
191         return ADC;
192 }
193
194 #if 0
195 uchar   usbFunctionSetup(uchar data[8])
196 {
197 usbRequest_t    *rq = (void *)data;
198
199     usbMsgPtr = reportBuffer;
200     if((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_CLASS){    /* class request type */
201         if(rq->bRequest == USBRQ_HID_GET_REPORT){  /* wValue: ReportType (highbyte), ReportID (lowbyte) */
202             /* we only have one report type, so don't look at wValue */
203             buildReport(keyPressed());
204             return sizeof(reportBuffer);
205         }else if(rq->bRequest == USBRQ_HID_GET_IDLE){
206             usbMsgPtr = &idleRate;
207             return 1;
208         }else if(rq->bRequest == USBRQ_HID_SET_IDLE){
209             idleRate = rq->wValue.bytes[1];
210         }
211     }else{
212         /* no vendor specific requests implemented */
213     }
214     return 0;
215 }
216 #endif
217
218 usbMsgLen_t usbFunctionSetup(uchar data[8])
219 {
220         usbRequest_t    *rq = (usbRequest_t *)data;
221         if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_CLASS) {    /* class request type */
222             color.name.red = 13;
223             if (rq->bRequest == USBRQ_HID_GET_REPORT){  /* wValue: ReportType (highbyte), ReportID (lowbyte) */
224             /* we only have one report type, so don't look at wValue */
225             if (color.name.red == 133) {
226                 color.name.red = 23;
227                 usbMsgPtr = reportBuffer;
228                 reportBuffer[0] = 0;
229                 reportBuffer[1] = KEY_X;
230             }
231             return sizeof(reportBuffer);
232         } else if (rq->bRequest == USBRQ_HID_GET_IDLE) {
233             usbMsgPtr = &idleRate;
234             return 1;
235         }else if (rq->bRequest == USBRQ_HID_SET_IDLE) {
236             usbMsgPtr = reportBuffer;
237             idleRate = rq->wValue.bytes[1];
238         }
239     }
240     if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_VENDOR) {
241                 current_command = rq->bRequest;
242         switch(rq->bRequest)
243                 {
244                 case CUSTOM_RQ_SET_RGB:
245                         return USB_NO_MSG;
246                 case CUSTOM_RQ_GET_RGB:{
247                         usbMsgLen_t len=6;
248                         if(len>rq->wLength.word){
249                                 len = rq->wLength.word;
250                         }
251                         usbMsgPtr = (uchar*)color.idx;
252                         return len;
253                 }
254                 case CUSTOM_RQ_READ_MEM:
255                         usbMsgPtr = (uchar*)rq->wValue.word;
256                         return rq->wLength.word;
257                 case CUSTOM_RQ_WRITE_MEM:
258                 case CUSTOM_RQ_EXEC_SPM:
259                         uni_buffer_fill = 4;
260                         uni_buffer.w16[0] = rq->wValue.word;
261                         uni_buffer.w16[1] = rq->wLength.word;
262                         return USB_NO_MSG;
263                 case CUSTOM_RQ_READ_FLASH:
264                         uni_buffer.w16[0] = rq->wValue.word;
265                         uni_buffer.w16[1] = rq->wLength.word;
266                         return USB_NO_MSG;
267                 case CUSTOM_RQ_RESET:
268                         soft_reset((uint8_t)(rq->wValue.word));
269                         break;
270                 case CUSTOM_RQ_READ_BUTTON:
271                         uni_buffer.w8[0] = read_button();
272                         usbMsgPtr = uni_buffer.w8;
273                         return 1;
274                 case CUSTOM_RQ_READ_TMPSENS:
275                         uni_buffer.w16[0] = read_temperture_sensor();
276                         usbMsgPtr = uni_buffer.w8;
277                         return 2;
278                 }
279     }
280
281     return 0;   /* default for not implemented requests: return no data back to host */
282 }
283
284 uchar usbFunctionWrite(uchar *data, uchar len)
285 {
286         switch(current_command){
287         case CUSTOM_RQ_SET_RGB:
288                 if(len!=6){
289                         return 1;
290                 }
291                 memcpy(color.idx, data, 6);
292         keyDidChange = true;
293                 return 1;
294         case CUSTOM_RQ_WRITE_MEM:
295                 memcpy(uni_buffer.ptr[0], data, len);
296                 uni_buffer.w16[0] += len;
297                 return !(uni_buffer.w16[1] -= len);
298         case CUSTOM_RQ_EXEC_SPM:
299                 if(uni_buffer_fill<8){
300                         uint8_t l = 8-uni_buffer_fill;
301                         if(len<l){
302                                 len = l;
303                         }
304                         memcpy(&(uni_buffer.w8[uni_buffer_fill]), data, len);
305                         uni_buffer_fill += len;
306                         return 0;
307                 }
308                 uni_buffer.w16[1] -= len;
309                 if(uni_buffer.w16[1]>8){
310                         memcpy(uni_buffer.ptr[0], data, len);
311                         uni_buffer.w16[0] += len;
312                         return 0;
313                 }else{
314                         memcpy(&(uni_buffer.w8[uni_buffer_fill]), data, len);
315                         exec_spm(uni_buffer.w16[2], uni_buffer.w16[3], uni_buffer.ptr[0], data, len);
316                         return 1;
317                 }
318         default:
319                 return 1;
320         }
321         return 0;
322 }
323 uchar usbFunctionRead(uchar *data, uchar len){
324         uchar ret=len;
325         switch(current_command){
326         case CUSTOM_RQ_READ_FLASH:
327                 while(len--){
328                         *data++ = pgm_read_byte((uni_buffer.w16[0])++);
329                 }
330                 return ret;
331         default:
332                 break;
333         }
334         return 0;
335 }
336
337 static void calibrateOscillator(void)
338 {
339 uchar       step = 128;
340 uchar       trialValue = 0, optimumValue;
341 int         x, optimumDev, targetValue = (unsigned)(1499 * (double)F_CPU / 10.5e6 + 0.5);
342  
343     /* do a binary search: */
344     do{
345         OSCCAL = trialValue + step;
346         x = usbMeasureFrameLength();    // proportional to current real frequency
347         if(x < targetValue)             // frequency still too low
348             trialValue += step;
349         step >>= 1;
350     }while(step > 0);
351     /* We have a precision of +/- 1 for optimum OSCCAL here */
352     /* now do a neighborhood search for optimum value */
353     optimumValue = trialValue;
354     optimumDev = x; // this is certainly far away from optimum
355     for(OSCCAL = trialValue - 1; OSCCAL <= trialValue + 1; OSCCAL++){
356         x = usbMeasureFrameLength() - targetValue;
357         if(x < 0)
358             x = -x;
359         if(x < optimumDev){
360             optimumDev = x;
361             optimumValue = OSCCAL;
362         }
363     }
364     OSCCAL = optimumValue;
365 }
366  
367
368 void usbEventResetReady(void)
369 {
370     cli();  // usbMeasureFrameLength() counts CPU cycles, so disable interrupts.
371     calibrateOscillator();
372     sei();
373 // we never read the value from eeprom so this causes only degradation of eeprom
374 //    eeprom_write_byte(0, OSCCAL);   // store the calibrated value in EEPROM
375 }
376
377 /* ------------------------------------------------------------------------- */
378
379 int main(void)
380 {
381         uchar   i;
382
383     wdt_enable(WDTO_1S);
384     /* Even if you don't use the watchdog, turn it off here. On newer devices,
385      * the status of the watchdog (on/off, period) is PRESERVED OVER RESET!
386      */
387     /* RESET status: all port bits are inputs without pull-up.
388      * That's the way we need D+ and D-. Therefore we don't need any
389      * additional hardware initialization.
390      */
391
392     init_temperature_sensor();
393     usbInit();
394     usbDeviceDisconnect();  /* enforce re-enumeration, do this while interrupts are disabled! */
395     i = 0;
396     while(--i){             /* fake USB disconnect for > 250 ms */
397         wdt_reset();
398         _delay_ms(1);
399     }
400     usbDeviceConnect();
401     LED_PORT_DDR |= _BV(R_BIT) | _BV(G_BIT) | _BV(B_BIT);   /* make the LED bit an output */
402         
403     sei();
404
405     for(;;){                /* main event loop */
406         //      update_pwm();
407                 
408         wdt_reset();
409         usbPoll();
410         if(keyDidChange && usbInterruptIsReady()){
411             keyDidChange = 0;
412             color.name.red = 42;
413             /* use last key and not current key status in order to avoid lost
414                changes in key status. */
415            reportBuffer[0] = 0;
416            reportBuffer[1] = KEY_Y;
417            usbSetInterrupt(reportBuffer, sizeof(reportBuffer));
418         }
419     }
420     return 0;
421 }
422
423 /* ------------------------------------------------------------------------- */