From be9be90483ce083490c11b1ae4695ec5149bc783 Mon Sep 17 00:00:00 2001 From: flabbergast Date: Mon, 7 Sep 2015 21:33:06 +0100 Subject: [PATCH 01/29] Modularity and gcc warnings fixes. --- tmk_core/common.mk | 2 +- tmk_core/common/action_tapping.c | 2 +- tmk_core/common/bootmagic.c | 2 +- tmk_core/common/command.c | 15 ++++++++++++--- tmk_core/common/keymap.c | 6 ++++++ tmk_core/common/progmem.h | 4 ++-- 6 files changed, 23 insertions(+), 8 deletions(-) diff --git a/tmk_core/common.mk b/tmk_core/common.mk index cb030b33..f5a464d0 100644 --- a/tmk_core/common.mk +++ b/tmk_core/common.mk @@ -1,4 +1,4 @@ -COMMON_DIR = common +COMMON_DIR = $(TMK_DIR)/common SRC += $(COMMON_DIR)/host.c \ $(COMMON_DIR)/keyboard.c \ $(COMMON_DIR)/action.c \ diff --git a/tmk_core/common/action_tapping.c b/tmk_core/common/action_tapping.c index 826c2330..487c62f1 100644 --- a/tmk_core/common/action_tapping.c +++ b/tmk_core/common/action_tapping.c @@ -257,7 +257,7 @@ bool process_tapping(keyrecord_t *keyp) return true; } } else { - if (!IS_NOEVENT(event)) debug("Tapping: other key just after tap.\n"); + if (!IS_NOEVENT(event)) debug("Tapping: other key just after tap.\n") {}; process_action(keyp); return true; } diff --git a/tmk_core/common/bootmagic.c b/tmk_core/common/bootmagic.c index b002a585..d6684b2d 100644 --- a/tmk_core/common/bootmagic.c +++ b/tmk_core/common/bootmagic.c @@ -19,7 +19,7 @@ void bootmagic(void) } /* do scans in case of bounce */ - print("boogmagic scan: ... "); + print("bootmagic scan: ... "); uint8_t scan = 100; while (scan--) { matrix_scan(); _delay_ms(10); } print("done.\n"); diff --git a/tmk_core/common/command.c b/tmk_core/common/command.c index 1b6808be..b017f2e2 100644 --- a/tmk_core/common/command.c +++ b/tmk_core/common/command.c @@ -16,7 +16,7 @@ along with this program. If not, see . */ #include #include -#include +#include "wait.h" #include "keycode.h" #include "host.h" #include "keymap.h" @@ -97,12 +97,14 @@ bool command_proc(uint8_t code) bool command_extra(uint8_t code) __attribute__ ((weak)); bool command_extra(uint8_t code) { + (void)code; return false; } bool command_console_extra(uint8_t code) __attribute__ ((weak)); bool command_console_extra(uint8_t code) { + (void)code; return false; } @@ -178,7 +180,9 @@ static void print_eeconfig(void) static bool command_common(uint8_t code) { +#ifdef KEYBOARD_LOCK_ENABLE static host_driver_t *host_driver = 0; +#endif switch (code) { #ifdef SLEEP_LED_ENABLE case KC_Z: @@ -223,7 +227,7 @@ static bool command_common(uint8_t code) case KC_PAUSE: clear_keyboard(); print("\n\nbootloader... "); - _delay_ms(1000); + wait_ms(1000); bootloader_jump(); // not return break; case KC_D: @@ -307,15 +311,20 @@ static bool command_common(uint8_t code) " " STR(BOOTLOADER_SIZE) "\n"); print("GCC: " STR(__GNUC__) "." STR(__GNUC_MINOR__) "." STR(__GNUC_PATCHLEVEL__) +#if defined(__AVR__) " AVR-LIBC: " __AVR_LIBC_VERSION_STRING__ " AVR_ARCH: avr" STR(__AVR_ARCH__) "\n"); +#elif defined(__arm__) + // TODO + ); +#endif break; case KC_S: print("\n\t- Status -\n"); print_val_hex8(host_keyboard_leds()); print_val_hex8(keyboard_protocol); print_val_hex8(keyboard_idle); - print_val_hex32(timer_count); + print_val_hex32(timer_read32()); #ifdef PROTOCOL_PJRC print_val_hex8(UDCON); diff --git a/tmk_core/common/keymap.c b/tmk_core/common/keymap.c index 9f4fab52..be00076c 100644 --- a/tmk_core/common/keymap.c +++ b/tmk_core/common/keymap.c @@ -108,6 +108,9 @@ action_t action_for_key(uint8_t layer, keypos_t key) __attribute__ ((weak)) const macro_t *action_get_macro(keyrecord_t *record, uint8_t id, uint8_t opt) { + (void)record; + (void)id; + (void)opt; return MACRO_NONE; } @@ -115,6 +118,9 @@ const macro_t *action_get_macro(keyrecord_t *record, uint8_t id, uint8_t opt) __attribute__ ((weak)) void action_function(keyrecord_t *record, uint8_t id, uint8_t opt) { + (void)record; + (void)id; + (void)opt; } diff --git a/tmk_core/common/progmem.h b/tmk_core/common/progmem.h index 199b1bed..5b276562 100644 --- a/tmk_core/common/progmem.h +++ b/tmk_core/common/progmem.h @@ -5,8 +5,8 @@ # include #elif defined(__arm__) # define PROGMEM -# define pgm_read_byte(p) *(p) -# define pgm_read_word(p) *(p) +# define pgm_read_byte(p) *((unsigned char*)p) +# define pgm_read_word(p) *((uint16_t*)p) #endif #endif From 27dec2db7bb33cc45b04b89b6855bac6b98de2e5 Mon Sep 17 00:00:00 2001 From: flabbergast Date: Mon, 7 Sep 2015 21:57:04 +0100 Subject: [PATCH 02/29] Add ChibiOS support (USB stack + support files). --- tmk_core/common/chibios/bootloader.c | 7 + tmk_core/common/chibios/printf.c | 240 +++++ tmk_core/common/chibios/printf.h | 111 +++ tmk_core/common/chibios/suspend.c | 8 + tmk_core/common/chibios/timer.c | 27 + tmk_core/common/command.c | 3 + tmk_core/common/print.c | 8 +- tmk_core/common/print.h | 10 +- tmk_core/common/wait.h | 8 +- tmk_core/protocol/chibios/.gitignore | 1 + tmk_core/protocol/chibios/README.md | 25 + tmk_core/protocol/chibios/chibios.mk | 225 +++++ tmk_core/protocol/chibios/main.c | 91 ++ tmk_core/protocol/chibios/usb_main.c | 1251 ++++++++++++++++++++++++++ tmk_core/protocol/chibios/usb_main.h | 149 +++ tmk_core/tool/chibios/common.mk | 86 ++ 16 files changed, 2245 insertions(+), 5 deletions(-) create mode 100644 tmk_core/common/chibios/bootloader.c create mode 100644 tmk_core/common/chibios/printf.c create mode 100644 tmk_core/common/chibios/printf.h create mode 100644 tmk_core/common/chibios/suspend.c create mode 100644 tmk_core/common/chibios/timer.c create mode 100644 tmk_core/protocol/chibios/.gitignore create mode 100644 tmk_core/protocol/chibios/README.md create mode 100644 tmk_core/protocol/chibios/chibios.mk create mode 100644 tmk_core/protocol/chibios/main.c create mode 100644 tmk_core/protocol/chibios/usb_main.c create mode 100644 tmk_core/protocol/chibios/usb_main.h create mode 100644 tmk_core/tool/chibios/common.mk diff --git a/tmk_core/common/chibios/bootloader.c b/tmk_core/common/chibios/bootloader.c new file mode 100644 index 00000000..6c34e2e0 --- /dev/null +++ b/tmk_core/common/chibios/bootloader.c @@ -0,0 +1,7 @@ +/* TODO */ +/* ... chip dependent ... */ + +#include "bootloader.h" + + +void bootloader_jump(void) {} diff --git a/tmk_core/common/chibios/printf.c b/tmk_core/common/chibios/printf.c new file mode 100644 index 00000000..72e3d4f8 --- /dev/null +++ b/tmk_core/common/chibios/printf.c @@ -0,0 +1,240 @@ +/* + * found at: http://www.sparetimelabs.com/tinyprintf/tinyprintf.php + * and: http://www.sparetimelabs.com/printfrevisited/printfrevisited.php + */ + +/* +File: printf.c + +Copyright (C) 2004 Kustaa Nyholm + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +#include "printf.h" + +typedef void (*putcf) (void*,char); +static putcf stdout_putf; +static void* stdout_putp; + +// this adds cca 400 bytes +#define PRINTF_LONG_SUPPORT + +#ifdef PRINTF_LONG_SUPPORT + +static void uli2a(unsigned long int num, unsigned int base, int uc,char * bf) + { + int n=0; + unsigned int d=1; + while (num/d >= base) + d*=base; + while (d!=0) { + int dgt = num / d; + num%=d; + d/=base; + if (n || dgt>0|| d==0) { + *bf++ = dgt+(dgt<10 ? '0' : (uc ? 'A' : 'a')-10); + ++n; + } + } + *bf=0; + } + +static void li2a (long num, char * bf) + { + if (num<0) { + num=-num; + *bf++ = '-'; + } + uli2a(num,10,0,bf); + } + +#endif + +static void ui2a(unsigned int num, unsigned int base, int uc,char * bf) + { + int n=0; + unsigned int d=1; + while (num/d >= base) + d*=base; + while (d!=0) { + int dgt = num / d; + num%= d; + d/=base; + if (n || dgt>0 || d==0) { + *bf++ = dgt+(dgt<10 ? '0' : (uc ? 'A' : 'a')-10); + ++n; + } + } + *bf=0; + } + +static void i2a (int num, char * bf) + { + if (num<0) { + num=-num; + *bf++ = '-'; + } + ui2a(num,10,0,bf); + } + +static int a2d(char ch) + { + if (ch>='0' && ch<='9') + return ch-'0'; + else if (ch>='a' && ch<='f') + return ch-'a'+10; + else if (ch>='A' && ch<='F') + return ch-'A'+10; + else return -1; + } + +static char a2i(char ch, char** src,int base,int* nump) + { + char* p= *src; + int num=0; + int digit; + while ((digit=a2d(ch))>=0) { + if (digit>base) break; + num=num*base+digit; + ch=*p++; + } + *src=p; + *nump=num; + return ch; + } + +static void putchw(void* putp,putcf putf,int n, char z, char* bf) + { + char fc=z? '0' : ' '; + char ch; + char* p=bf; + while (*p++ && n > 0) + n--; + while (n-- > 0) + putf(putp,fc); + while ((ch= *bf++)) + putf(putp,ch); + } + +void tfp_format(void* putp,putcf putf,char *fmt, va_list va) + { + char bf[12]; + + char ch; + + + while ((ch=*(fmt++))) { + if (ch!='%') + putf(putp,ch); + else { + char lz=0; +#ifdef PRINTF_LONG_SUPPORT + char lng=0; +#endif + int w=0; + ch=*(fmt++); + if (ch=='0') { + ch=*(fmt++); + lz=1; + } + if (ch>='0' && ch<='9') { + ch=a2i(ch,&fmt,10,&w); + } +#ifdef PRINTF_LONG_SUPPORT + if (ch=='l') { + ch=*(fmt++); + lng=1; + } +#endif + switch (ch) { + case 0: + goto abort; + case 'u' : { +#ifdef PRINTF_LONG_SUPPORT + if (lng) + uli2a(va_arg(va, unsigned long int),10,0,bf); + else +#endif + ui2a(va_arg(va, unsigned int),10,0,bf); + putchw(putp,putf,w,lz,bf); + break; + } + case 'd' : { +#ifdef PRINTF_LONG_SUPPORT + if (lng) + li2a(va_arg(va, unsigned long int),bf); + else +#endif + i2a(va_arg(va, int),bf); + putchw(putp,putf,w,lz,bf); + break; + } + case 'x': case 'X' : +#ifdef PRINTF_LONG_SUPPORT + if (lng) + uli2a(va_arg(va, unsigned long int),16,(ch=='X'),bf); + else +#endif + ui2a(va_arg(va, unsigned int),16,(ch=='X'),bf); + putchw(putp,putf,w,lz,bf); + break; + case 'c' : + putf(putp,(char)(va_arg(va, int))); + break; + case 's' : + putchw(putp,putf,w,0,va_arg(va, char*)); + break; + case '%' : + putf(putp,ch); + default: + break; + } + } + } + abort:; + } + + +void init_printf(void* putp,void (*putf) (void*,char)) + { + stdout_putf=putf; + stdout_putp=putp; + } + +void tfp_printf(char *fmt, ...) + { + va_list va; + va_start(va,fmt); + tfp_format(stdout_putp,stdout_putf,fmt,va); + va_end(va); + } + +static void putcp(void* p,char c) + { + *(*((char**)p))++ = c; + } + + + +void tfp_sprintf(char* s,char *fmt, ...) + { + va_list va; + va_start(va,fmt); + tfp_format(&s,putcp,fmt,va); + putcp(&s,0); + va_end(va); + } diff --git a/tmk_core/common/chibios/printf.h b/tmk_core/common/chibios/printf.h new file mode 100644 index 00000000..00813198 --- /dev/null +++ b/tmk_core/common/chibios/printf.h @@ -0,0 +1,111 @@ +/* + * found at: http://www.sparetimelabs.com/tinyprintf/tinyprintf.php + * and: http://www.sparetimelabs.com/printfrevisited/printfrevisited.php + */ + +/* +File: printf.h + +Copyright (C) 2004 Kustaa Nyholm + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +See the GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +This library is realy just two files: 'printf.h' and 'printf.c'. + +They provide a simple and small (+200 loc) printf functionality to +be used in embedded systems. + +I've found them so usefull in debugging that I do not bother with a +debugger at all. + +They are distributed in source form, so to use them, just compile them +into your project. + +Two printf variants are provided: printf and sprintf. + +The formats supported by this implementation are: 'd' 'u' 'c' 's' 'x' 'X'. + +Zero padding and field width are also supported. + +If the library is compiled with 'PRINTF_SUPPORT_LONG' defined then the +long specifier is also +supported. Note that this will pull in some long math routines (pun intended!) +and thus make your executable noticably longer. + +The memory foot print of course depends on the target cpu, compiler and +compiler options, but a rough guestimate (based on a H8S target) is about +1.4 kB for code and some twenty 'int's and 'char's, say 60 bytes of stack space. +Not too bad. Your milage may vary. By hacking the source code you can +get rid of some hunred bytes, I'm sure, but personally I feel the balance of +functionality and flexibility versus code size is close to optimal for +many embedded systems. + +To use the printf you need to supply your own character output function, +something like : + + void putc ( void* p, char c) + { + while (!SERIAL_PORT_EMPTY) ; + SERIAL_PORT_TX_REGISTER = c; + } + +Before you can call printf you need to initialize it to use your +character output function with something like: + + init_printf(NULL,putc); + +Notice the 'NULL' in 'init_printf' and the parameter 'void* p' in 'putc', +the NULL (or any pointer) you pass into the 'init_printf' will eventually be +passed to your 'putc' routine. This allows you to pass some storage space (or +anything realy) to the character output function, if necessary. +This is not often needed but it was implemented like that because it made +implementing the sprintf function so neat (look at the source code). + +The code is re-entrant, except for the 'init_printf' function, so it +is safe to call it from interupts too, although this may result in mixed output. +If you rely on re-entrancy, take care that your 'putc' function is re-entrant! + +The printf and sprintf functions are actually macros that translate to +'tfp_printf' and 'tfp_sprintf'. This makes it possible +to use them along with 'stdio.h' printf's in a single source file. +You just need to undef the names before you include the 'stdio.h'. +Note that these are not function like macros, so if you have variables +or struct members with these names, things will explode in your face. +Without variadic macros this is the best we can do to wrap these +fucnction. If it is a problem just give up the macros and use the +functions directly or rename them. + +For further details see source code. + +regs Kusti, 23.10.2004 +*/ + + +#ifndef __TFP_PRINTF__ +#define __TFP_PRINTF__ + +#include + +void init_printf(void* putp,void (*putf) (void*,char)); + +void tfp_printf(char *fmt, ...); +void tfp_sprintf(char* s,char *fmt, ...); + +void tfp_format(void* putp,void (*putf) (void*,char),char *fmt, va_list va); + +#define printf tfp_printf +#define sprintf tfp_sprintf + +#endif diff --git a/tmk_core/common/chibios/suspend.c b/tmk_core/common/chibios/suspend.c new file mode 100644 index 00000000..49ecad43 --- /dev/null +++ b/tmk_core/common/chibios/suspend.c @@ -0,0 +1,8 @@ +/* TODO */ + +#include + + +void suspend_power_down(void) {} +bool suspend_wakeup_condition(void) { return true; } +void suspend_wakeup_init(void) {} diff --git a/tmk_core/common/chibios/timer.c b/tmk_core/common/chibios/timer.c new file mode 100644 index 00000000..c812994b --- /dev/null +++ b/tmk_core/common/chibios/timer.c @@ -0,0 +1,27 @@ +#include "ch.h" + +#include "timer.h" + +void timer_init(void) {} + +void timer_clear(void) {} + +uint16_t timer_read(void) +{ + return (uint16_t)ST2MS(chVTGetSystemTime()); +} + +uint32_t timer_read32(void) +{ + return ST2MS(chVTGetSystemTime()); +} + +uint16_t timer_elapsed(uint16_t last) +{ + return (uint16_t)(ST2MS(chVTTimeElapsedSinceX(MS2ST(last)))); +} + +uint32_t timer_elapsed32(uint32_t last) +{ + return ST2MS(chVTTimeElapsedSinceX(MS2ST(last))); +} diff --git a/tmk_core/common/command.c b/tmk_core/common/command.c index b017f2e2..8fb6db56 100644 --- a/tmk_core/common/command.c +++ b/tmk_core/common/command.c @@ -287,6 +287,9 @@ static bool command_common(uint8_t code) #ifdef PROTOCOL_VUSB " VUSB" #endif +#ifdef PROTOCOL_CHIBIOS + " CHIBIOS" +#endif #ifdef BOOTMAGIC_ENABLE " BOOTMAGIC" #endif diff --git a/tmk_core/common/print.c b/tmk_core/common/print.c index ca94e1e5..00489557 100644 --- a/tmk_core/common/print.c +++ b/tmk_core/common/print.c @@ -38,11 +38,15 @@ void print_set_sendchar(int8_t (*sendchar_func)(uint8_t)) xdev_out(sendchar_func); } -#elif defined(__arm__) +#elif defined(PROTOCOL_CHIBIOS) /* __AVR__ */ + +// don't need anything extra + +#elif defined(__arm__) /* __AVR__ */ // TODO //void print_set_sendchar(int8_t (*sendchar_func)(uint8_t)) { } -#endif +#endif /* __AVR__ */ #endif diff --git a/tmk_core/common/print.h b/tmk_core/common/print.h index c0e9e143..1e1b9b40 100644 --- a/tmk_core/common/print.h +++ b/tmk_core/common/print.h @@ -47,7 +47,15 @@ extern "C" /* function pointer of sendchar to be used by print utility */ void print_set_sendchar(int8_t (*print_sendchar_func)(uint8_t)); -#elif defined(__arm__) +#elif defined(PROTOCOL_CHIBIOS) /* __AVR__ */ + +#include "chibios/printf.h" + +#define print(s) printf(s) +#define println(s) printf(s "\r\n") +#define xprintf printf + +#elif defined(__arm__) /* __AVR__ */ #include "mbed/xprintf.h" diff --git a/tmk_core/common/wait.h b/tmk_core/common/wait.h index 40d00b0c..82727be0 100644 --- a/tmk_core/common/wait.h +++ b/tmk_core/common/wait.h @@ -9,9 +9,13 @@ extern "C" { # include # define wait_ms(ms) _delay_ms(ms) # define wait_us(us) _delay_us(us) -#elif defined(__arm__) +#elif defined(PROTOCOL_CHIBIOS) /* __AVR__ */ +# include "ch.h" +# define wait_ms(ms) chThdSleepMilliseconds(ms) +# define wait_us(us) chThdSleepMicroseconds(us) +#elif defined(__arm__) /* __AVR__ */ # include "wait_api.h" -#endif +#endif /* __AVR__ */ #ifdef __cplusplus } diff --git a/tmk_core/protocol/chibios/.gitignore b/tmk_core/protocol/chibios/.gitignore new file mode 100644 index 00000000..3118dbef --- /dev/null +++ b/tmk_core/protocol/chibios/.gitignore @@ -0,0 +1 @@ +chibios diff --git a/tmk_core/protocol/chibios/README.md b/tmk_core/protocol/chibios/README.md new file mode 100644 index 00000000..38fd495e --- /dev/null +++ b/tmk_core/protocol/chibios/README.md @@ -0,0 +1,25 @@ +## USB stack implementation using ChibiOS + +### Notes + +- To use, unpack or symlink ChibiOS here, to `chibios`. +- For gcc options, inspect `chibios.mk`. For instance, I enabled `-Wno-missing-field-initializers`, because TMK common bits generated a lot of hits on that. +Also pay attention to `-O0` (enabled for debugging); for deployment use `-O2`. +- USB string descriptors are a mess. I did not find a way to cleanly generate the right structures from actual strings, so the definitions in individual keyboards' `config.h` are ugly as heck. +- There are some random constants left so far, e.g. 5ms sleep between calling `keyboard_task` in `main.c`. There should be no such in `usb_main.c`. Everything is based on timers/interrupts/kernel scheduling (well except `keyboard_task`), so no periodically called things (again, except `keyboard_task`, which is just how TMK is designed). +- It is easy to add some code for testing (e.g. blink LED, do stuff on button press, etc...) - just create another thread in `main.c`, it will run independently of the keyboard business. +- The USB stack works pretty completely; however there are bits of other TMK stuff that are not done yet: + +### Immediate todo + +- suspend / sleep led + +### Missing / not working (TMK vs ChibiOS bits) + +- eeprom / bootmagic (will be chip dependent) +- bootloader jump (chip dependent) + +### Tried with + +- ChibiOS 3.0.1 and ST F072RB DISCOVERY board. +- Need to test on other STM32 chips (F3, F4) to make it as much chip-independent as possible. diff --git a/tmk_core/protocol/chibios/chibios.mk b/tmk_core/protocol/chibios/chibios.mk new file mode 100644 index 00000000..d667f60e --- /dev/null +++ b/tmk_core/protocol/chibios/chibios.mk @@ -0,0 +1,225 @@ +############################################################################## +# Build global options +# NOTE: Can be overridden externally. +# + +# Compiler options here. +ifeq ($(USE_OPT),) + USE_OPT = -O0 -ggdb -fomit-frame-pointer -falign-functions=16 -std=gnu99 -DPROTOCOL_CHIBIOS +endif + +# C specific options here (added to USE_OPT). +ifeq ($(USE_COPT),) + USE_COPT = +endif + +# include specific config.h? +ifdef CONFIG_H + USE_COPT += -include $(CONFIG_H) +endif + +# C++ specific options here (added to USE_OPT). +ifeq ($(USE_CPPOPT),) + USE_CPPOPT = -fno-rtti +endif + +# Enable this if you want the linker to remove unused code and data +ifeq ($(USE_LINK_GC),) + USE_LINK_GC = yes +endif + +# Linker extra options here. +ifeq ($(USE_LDOPT),) + USE_LDOPT = +endif + +# Enable this if you want link time optimizations (LTO) +ifeq ($(USE_LTO),) + USE_LTO = yes +endif + +# If enabled, this option allows to compile the application in THUMB mode. +ifeq ($(USE_THUMB),) + USE_THUMB = yes +endif + +# Enable this if you want to see the full log while compiling. +ifeq ($(USE_VERBOSE_COMPILE),) + USE_VERBOSE_COMPILE = no +endif + +# If enabled, this option makes the build process faster by not compiling +# modules not used in the current configuration. +ifeq ($(USE_SMART_BUILD),) + USE_SMART_BUILD = yes +endif + +# +# Build global options +############################################################################## + +############################################################################## +# Architecture or project specific options +# + +# Stack size to be allocated to the Cortex-M process stack. This stack is +# the stack used by the main() thread. +ifeq ($(USE_PROCESS_STACKSIZE),) + USE_PROCESS_STACKSIZE = 0x200 +endif + +# Stack size to the allocated to the Cortex-M main/exceptions stack. This +# stack is used for processing interrupts and exceptions. +ifeq ($(USE_EXCEPTIONS_STACKSIZE),) + USE_EXCEPTIONS_STACKSIZE = 0x400 +endif + +# +# Architecture or project specific options +############################################################################## + +############################################################################## +# Project, sources and paths +# + +# Imported source files and paths +CHIBIOS = $(TMK_DIR)/protocol/chibios/chibios +# Startup files. +include $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/mk/startup_$(shell echo $(MCU_SERIES) | tr '[:upper:]' '[:lower:]').mk +# HAL-OSAL files (optional). +include $(CHIBIOS)/os/hal/hal.mk +include $(CHIBIOS)/os/hal/ports/$(MCU_FAMILY)/$(MCU_SERIES)/platform.mk +ifneq ("$(wildcard $(TARGET_DIR)/boards/$(BOARD))","") + include $(TARGET_DIR)/boards/$(BOARD)/board.mk +else + include $(CHIBIOS)/os/hal/boards/$(BOARD)/board.mk +endif +include $(CHIBIOS)/os/hal/osal/rt/osal.mk +# RTOS files (optional). +include $(CHIBIOS)/os/rt/rt.mk +include $(CHIBIOS)/os/rt/ports/ARMCMx/compilers/GCC/mk/port_v6m.mk +# Other files (optional). + +# Define linker script file here +ifneq ("$(wildcard $(TARGET_DIR)/ld/$(MCU_MODEL_FAMILY).ld)","") +LDSCRIPT = $(TARGET_DIR)/ld/$(MCU_MODEL_FAMILY).ld +else +LDSCRIPT = $(STARTUPLD)/$(MCU_MODEL_FAMILY).ld +endif + +# C sources that can be compiled in ARM or THUMB mode depending on the global +# setting. +CSRC = $(STARTUPSRC) \ + $(KERNSRC) \ + $(PORTSRC) \ + $(OSALSRC) \ + $(HALSRC) \ + $(PLATFORMSRC) \ + $(BOARDSRC) \ + $(CHIBIOS)/os/hal/lib/streams/chprintf.c \ + $(TMK_DIR)/protocol/chibios/usb_main.c \ + $(TMK_DIR)/protocol/chibios/main.c \ + $(SRC) + +# C++ sources that can be compiled in ARM or THUMB mode depending on the global +# setting. +CPPSRC = + +# C sources to be compiled in ARM mode regardless of the global setting. +# NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler +# option that results in lower performance and larger code size. +ACSRC = + +# C++ sources to be compiled in ARM mode regardless of the global setting. +# NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler +# option that results in lower performance and larger code size. +ACPPSRC = + +# C sources to be compiled in THUMB mode regardless of the global setting. +# NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler +# option that results in lower performance and larger code size. +TCSRC = + +# C sources to be compiled in THUMB mode regardless of the global setting. +# NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler +# option that results in lower performance and larger code size. +TCPPSRC = + +# List ASM source files here +ASMSRC = $(STARTUPASM) $(PORTASM) $(OSALASM) + +INCDIR = $(STARTUPINC) $(KERNINC) $(PORTINC) $(OSALINC) \ + $(HALINC) $(PLATFORMINC) $(BOARDINC) $(TESTINC) \ + $(CHIBIOS)/os/hal/lib/streams $(CHIBIOS)/os/various \ + $(TMK_DIR) $(COMMON_DIR) $(TMK_DIR)/protocol/chibios \ + $(TARGET_DIR) + +# +# Project, sources and paths +############################################################################## + +############################################################################## +# Compiler settings +# + +MCU = cortex-m0 + +#TRGT = arm-elf- +TRGT = arm-none-eabi- +CC = $(TRGT)gcc +CPPC = $(TRGT)g++ +# Enable loading with g++ only if you need C++ runtime support. +# NOTE: You can use C++ even without C++ support if you are careful. C++ +# runtime support makes code size explode. +LD = $(TRGT)gcc +#LD = $(TRGT)g++ +CP = $(TRGT)objcopy +AS = $(TRGT)gcc -x assembler-with-cpp +AR = $(TRGT)ar +OD = $(TRGT)objdump +SZ = $(TRGT)size +HEX = $(CP) -O ihex +BIN = $(CP) -O binary + +# ARM-specific options here +AOPT = + +# THUMB-specific options here +TOPT = -mthumb -DTHUMB + +# Define C warning options here +CWARN = -Wall -Wextra -Wundef -Wstrict-prototypes -Wno-missing-field-initializers + +# Define C++ warning options here +CPPWARN = -Wall -Wextra -Wundef + +# +# Compiler settings +############################################################################## + +############################################################################## +# Start of user section +# + +# List all user C define here, like -D_DEBUG=1 +## Select which interfaces to include here! +UDEFS = $(OPT_DEFS) + +# Define ASM defines here +UADEFS = + +# List all user directories here +UINCDIR = + +# List the user directory to look for the libraries here +ULIBDIR = + +# List all user libraries here +ULIBS = + +# +# End of user defines +############################################################################## + +RULESPATH = $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC +include $(RULESPATH)/rules.mk diff --git a/tmk_core/protocol/chibios/main.c b/tmk_core/protocol/chibios/main.c new file mode 100644 index 00000000..ce7cd8e3 --- /dev/null +++ b/tmk_core/protocol/chibios/main.c @@ -0,0 +1,91 @@ +/* + * (c) 2015 flabberast + * + * Based on the following work: + * - Guillaume Duc's raw hid example (MIT License) + * https://github.com/guiduc/usb-hid-chibios-example + * - PJRC Teensy examples (MIT License) + * https://www.pjrc.com/teensy/usb_keyboard.html + * - hasu's TMK keyboard code (GPL v2 and some code Modified BSD) + * https://github.com/tmk/tmk_keyboard/ + * - ChibiOS demo code (Apache 2.0 License) + * http://www.chibios.org + * + * Since some GPL'd code is used, this work is licensed under + * GPL v2 or later. + */ + +#include "ch.h" +#include "hal.h" + +#include "usb_main.h" + +/* TMK includes */ +#include "report.h" +#include "host.h" +#include "host_driver.h" +#include "keyboard.h" +#include "action.h" +#include "led.h" +#include "sendchar.h" +#include "debug.h" +#ifdef SLEEP_LED_ENABLE +#include "sleep_led.h" +#endif +#include "suspend.h" + + +/* ------------------------- + * TMK host driver defs + * ------------------------- + */ + +host_driver_t chibios_driver = { + keyboard_leds, + send_keyboard, + send_mouse, + send_system, + send_consumer +}; + +/* Main thread + */ +int main(void) { + /* ChibiOS/RT init */ + halInit(); + chSysInit(); + + palSetPad(GPIOC, GPIOC_LED_BLUE); + chThdSleepMilliseconds(400); + palClearPad(GPIOC, GPIOC_LED_BLUE); + + /* Init USB */ + init_usb_driver(); + + /* init printf */ + init_printf(NULL,sendchar_pf); + + /* Wait until the USB is active */ + while(USB_DRIVER.state != USB_ACTIVE) + chThdSleepMilliseconds(50); + + print("USB configured.\n"); + + /* init TMK modules */ + keyboard_init(); + host_set_driver(&chibios_driver); + +#ifdef SLEEP_LED_ENABLE + sleep_led_init(); +#endif + + print("Keyboard start.\n"); + + /* Main loop */ + while(true) { + /* TODO: check for suspended event */ + + keyboard_task(); + chThdSleepMilliseconds(5); + } +} diff --git a/tmk_core/protocol/chibios/usb_main.c b/tmk_core/protocol/chibios/usb_main.c new file mode 100644 index 00000000..875f47dc --- /dev/null +++ b/tmk_core/protocol/chibios/usb_main.c @@ -0,0 +1,1251 @@ +/* + * (c) 2015 flabberast + * + * Based on the following work: + * - Guillaume Duc's raw hid example (MIT License) + * https://github.com/guiduc/usb-hid-chibios-example + * - PJRC Teensy examples (MIT License) + * https://www.pjrc.com/teensy/usb_keyboard.html + * - hasu's TMK keyboard code (GPL v2 and some code Modified BSD) + * https://github.com/tmk/tmk_keyboard/ + * - ChibiOS demo code (Apache 2.0 License) + * http://www.chibios.org + * + * Since some GPL'd code is used, this work is licensed under + * GPL v2 or later. + */ + +#include "ch.h" +#include "hal.h" + +#include "usb_main.h" + +/* --------------------------------------------------------- + * Global interface variables and declarations + * --------------------------------------------------------- + */ + +uint8_t keyboard_idle = 0; +uint8_t keyboard_protocol = 1; +uint16_t keyboard_led_stats = 0; +volatile uint16_t keyboard_idle_count = 0; +static virtual_timer_t keyboard_idle_timer; +static void keyboard_idle_timer_cb(void *arg); +#ifdef NKRO_ENABLE +bool keyboard_nkro = true; +#endif /* NKRO_ENABLE */ + +report_keyboard_t keyboard_report_sent = {{0}}; + +#ifdef CONSOLE_ENABLE +/* The emission queue */ +output_queue_t console_queue; +static uint8_t console_queue_buffer[CONSOLE_QUEUE_BUFFER_SIZE]; +static virtual_timer_t console_flush_timer; +void console_queue_onotify(io_queue_t *qp); +static void console_flush_cb(void *arg); +#endif /* CONSOLE_ENABLE */ + +/* --------------------------------------------------------- + * Descriptors and USB driver objects + * --------------------------------------------------------- + */ + +/* HID specific constants */ +#define USB_DESCRIPTOR_HID 0x21 +#define USB_DESCRIPTOR_HID_REPORT 0x22 +#define HID_GET_REPORT 0x01 +#define HID_GET_IDLE 0x02 +#define HID_GET_PROTOCOL 0x03 +#define HID_SET_REPORT 0x09 +#define HID_SET_IDLE 0x0A +#define HID_SET_PROTOCOL 0x0B + +/* USB Device Descriptor */ +static const uint8_t usb_device_descriptor_data[] = { + USB_DESC_DEVICE(0x0200, // bcdUSB (1.1) + 0, // bDeviceClass (defined in later in interface) + 0, // bDeviceSubClass + 0, // bDeviceProtocol + 64, // bMaxPacketSize (64 bytes) (the driver didn't work with 32) + VENDOR_ID, // idVendor + PRODUCT_ID, // idProduct + DEVICE_VER, // bcdDevice + 1, // iManufacturer + 2, // iProduct + 3, // iSerialNumber + 1) // bNumConfigurations +}; + +/* Device Descriptor wrapper */ +static const USBDescriptor usb_device_descriptor = { + sizeof usb_device_descriptor_data, + usb_device_descriptor_data +}; + +/* + * HID Report Descriptor + * + * See "Device Class Definition for Human Interface Devices (HID)" + * (http://www.usb.org/developers/hidpage/HID1_11.pdf) for the + * detailed descrition of all the fields + */ + +/* Keyboard Protocol 1, HID 1.11 spec, Appendix B, page 59-60 */ +static const uint8_t keyboard_hid_report_desc_data[] = { + 0x05, 0x01, // Usage Page (Generic Desktop), + 0x09, 0x06, // Usage (Keyboard), + 0xA1, 0x01, // Collection (Application), + 0x75, 0x01, // Report Size (1), + 0x95, 0x08, // Report Count (8), + 0x05, 0x07, // Usage Page (Key Codes), + 0x19, 0xE0, // Usage Minimum (224), + 0x29, 0xE7, // Usage Maximum (231), + 0x15, 0x00, // Logical Minimum (0), + 0x25, 0x01, // Logical Maximum (1), + 0x81, 0x02, // Input (Data, Variable, Absolute), ;Modifier byte + 0x95, 0x01, // Report Count (1), + 0x75, 0x08, // Report Size (8), + 0x81, 0x03, // Input (Constant), ;Reserved byte + 0x95, 0x05, // Report Count (5), + 0x75, 0x01, // Report Size (1), + 0x05, 0x08, // Usage Page (LEDs), + 0x19, 0x01, // Usage Minimum (1), + 0x29, 0x05, // Usage Maximum (5), + 0x91, 0x02, // Output (Data, Variable, Absolute), ;LED report + 0x95, 0x01, // Report Count (1), + 0x75, 0x03, // Report Size (3), + 0x91, 0x03, // Output (Constant), ;LED report padding + 0x95, KBD_REPORT_KEYS, // Report Count (), + 0x75, 0x08, // Report Size (8), + 0x15, 0x00, // Logical Minimum (0), + 0x25, 0xFF, // Logical Maximum(255), + 0x05, 0x07, // Usage Page (Key Codes), + 0x19, 0x00, // Usage Minimum (0), + 0x29, 0xFF, // Usage Maximum (255), + 0x81, 0x00, // Input (Data, Array), + 0xc0 // End Collection +}; +/* wrapper */ +static const USBDescriptor keyboard_hid_report_descriptor = { + sizeof keyboard_hid_report_desc_data, + keyboard_hid_report_desc_data +}; + +#ifdef NKRO_ENABLE +static const uint8_t nkro_hid_report_desc_data[] = { + 0x05, 0x01, // Usage Page (Generic Desktop), + 0x09, 0x06, // Usage (Keyboard), + 0xA1, 0x01, // Collection (Application), + // bitmap of modifiers + 0x75, 0x01, // Report Size (1), + 0x95, 0x08, // Report Count (8), + 0x05, 0x07, // Usage Page (Key Codes), + 0x19, 0xE0, // Usage Minimum (224), + 0x29, 0xE7, // Usage Maximum (231), + 0x15, 0x00, // Logical Minimum (0), + 0x25, 0x01, // Logical Maximum (1), + 0x81, 0x02, // Input (Data, Variable, Absolute), ;Modifier byte + // LED output report + 0x95, 0x05, // Report Count (5), + 0x75, 0x01, // Report Size (1), + 0x05, 0x08, // Usage Page (LEDs), + 0x19, 0x01, // Usage Minimum (1), + 0x29, 0x05, // Usage Maximum (5), + 0x91, 0x02, // Output (Data, Variable, Absolute), + 0x95, 0x01, // Report Count (1), + 0x75, 0x03, // Report Size (3), + 0x91, 0x03, // Output (Constant), + // bitmap of keys + 0x95, NKRO_REPORT_KEYS * 8, // Report Count (), + 0x75, 0x01, // Report Size (1), + 0x15, 0x00, // Logical Minimum (0), + 0x25, 0x01, // Logical Maximum(1), + 0x05, 0x07, // Usage Page (Key Codes), + 0x19, 0x00, // Usage Minimum (0), + 0x29, NKRO_REPORT_KEYS * 8 - 1, // Usage Maximum (), + 0x81, 0x02, // Input (Data, Variable, Absolute), + 0xc0 // End Collection +}; +/* wrapper */ +static const USBDescriptor nkro_hid_report_descriptor = { + sizeof nkro_hid_report_desc_data, + nkro_hid_report_desc_data +}; +#endif /* NKRO_ENABLE */ + +#ifdef MOUSE_ENABLE +/* Mouse Protocol 1, HID 1.11 spec, Appendix B, page 59-60, with wheel extension + * http://www.microchip.com/forums/tm.aspx?high=&m=391435&mpage=1#391521 + * http://www.keil.com/forum/15671/ + * http://www.microsoft.com/whdc/device/input/wheel.mspx */ +static const uint8_t mouse_hid_report_desc_data[] = { + /* mouse */ + 0x05, 0x01, // USAGE_PAGE (Generic Desktop) + 0x09, 0x02, // USAGE (Mouse) + 0xa1, 0x01, // COLLECTION (Application) + //0x85, REPORT_ID_MOUSE, // REPORT_ID (1) + 0x09, 0x01, // USAGE (Pointer) + 0xa1, 0x00, // COLLECTION (Physical) + // ---------------------------- Buttons + 0x05, 0x09, // USAGE_PAGE (Button) + 0x19, 0x01, // USAGE_MINIMUM (Button 1) + 0x29, 0x05, // USAGE_MAXIMUM (Button 5) + 0x15, 0x00, // LOGICAL_MINIMUM (0) + 0x25, 0x01, // LOGICAL_MAXIMUM (1) + 0x75, 0x01, // REPORT_SIZE (1) + 0x95, 0x05, // REPORT_COUNT (5) + 0x81, 0x02, // INPUT (Data,Var,Abs) + 0x75, 0x03, // REPORT_SIZE (3) + 0x95, 0x01, // REPORT_COUNT (1) + 0x81, 0x03, // INPUT (Cnst,Var,Abs) + // ---------------------------- X,Y position + 0x05, 0x01, // USAGE_PAGE (Generic Desktop) + 0x09, 0x30, // USAGE (X) + 0x09, 0x31, // USAGE (Y) + 0x15, 0x81, // LOGICAL_MINIMUM (-127) + 0x25, 0x7f, // LOGICAL_MAXIMUM (127) + 0x75, 0x08, // REPORT_SIZE (8) + 0x95, 0x02, // REPORT_COUNT (2) + 0x81, 0x06, // INPUT (Data,Var,Rel) + // ---------------------------- Vertical wheel + 0x09, 0x38, // USAGE (Wheel) + 0x15, 0x81, // LOGICAL_MINIMUM (-127) + 0x25, 0x7f, // LOGICAL_MAXIMUM (127) + 0x35, 0x00, // PHYSICAL_MINIMUM (0) - reset physical + 0x45, 0x00, // PHYSICAL_MAXIMUM (0) + 0x75, 0x08, // REPORT_SIZE (8) + 0x95, 0x01, // REPORT_COUNT (1) + 0x81, 0x06, // INPUT (Data,Var,Rel) + // ---------------------------- Horizontal wheel + 0x05, 0x0c, // USAGE_PAGE (Consumer Devices) + 0x0a, 0x38, 0x02, // USAGE (AC Pan) + 0x15, 0x81, // LOGICAL_MINIMUM (-127) + 0x25, 0x7f, // LOGICAL_MAXIMUM (127) + 0x75, 0x08, // REPORT_SIZE (8) + 0x95, 0x01, // REPORT_COUNT (1) + 0x81, 0x06, // INPUT (Data,Var,Rel) + 0xc0, // END_COLLECTION + 0xc0, // END_COLLECTION +}; +/* wrapper */ +static const USBDescriptor mouse_hid_report_descriptor = { + sizeof mouse_hid_report_desc_data, + mouse_hid_report_desc_data +}; +#endif /* MOUSE_ENABLE */ + +#ifdef CONSOLE_ENABLE +static const uint8_t console_hid_report_desc_data[] = { + 0x06, 0x31, 0xFF, // Usage Page 0xFF31 (vendor defined) + 0x09, 0x74, // Usage 0x74 + 0xA1, 0x53, // Collection 0x53 + 0x75, 0x08, // report size = 8 bits + 0x15, 0x00, // logical minimum = 0 + 0x26, 0xFF, 0x00, // logical maximum = 255 + 0x95, CONSOLE_SIZE, // report count + 0x09, 0x75, // usage + 0x81, 0x02, // Input (array) + 0xC0 // end collection +}; +/* wrapper */ +static const USBDescriptor console_hid_report_descriptor = { + sizeof console_hid_report_desc_data, + console_hid_report_desc_data +}; +#endif /* CONSOLE_ENABLE */ + +#ifdef EXTRAKEY_ENABLE +/* audio controls & system controls + * http://www.microsoft.com/whdc/archive/w2kbd.mspx */ +static const uint8_t extra_hid_report_desc_data[] = { + /* system control */ + 0x05, 0x01, // USAGE_PAGE (Generic Desktop) + 0x09, 0x80, // USAGE (System Control) + 0xa1, 0x01, // COLLECTION (Application) + 0x85, REPORT_ID_SYSTEM, // REPORT_ID (2) + 0x15, 0x01, // LOGICAL_MINIMUM (0x1) + 0x25, 0xb7, // LOGICAL_MAXIMUM (0xb7) + 0x19, 0x01, // USAGE_MINIMUM (0x1) + 0x29, 0xb7, // USAGE_MAXIMUM (0xb7) + 0x75, 0x10, // REPORT_SIZE (16) + 0x95, 0x01, // REPORT_COUNT (1) + 0x81, 0x00, // INPUT (Data,Array,Abs) + 0xc0, // END_COLLECTION + /* consumer */ + 0x05, 0x0c, // USAGE_PAGE (Consumer Devices) + 0x09, 0x01, // USAGE (Consumer Control) + 0xa1, 0x01, // COLLECTION (Application) + 0x85, REPORT_ID_CONSUMER, // REPORT_ID (3) + 0x15, 0x01, // LOGICAL_MINIMUM (0x1) + 0x26, 0x9c, 0x02, // LOGICAL_MAXIMUM (0x29c) + 0x19, 0x01, // USAGE_MINIMUM (0x1) + 0x2a, 0x9c, 0x02, // USAGE_MAXIMUM (0x29c) + 0x75, 0x10, // REPORT_SIZE (16) + 0x95, 0x01, // REPORT_COUNT (1) + 0x81, 0x00, // INPUT (Data,Array,Abs) + 0xc0, // END_COLLECTION +}; +/* wrapper */ +static const USBDescriptor extra_hid_report_descriptor = { + sizeof extra_hid_report_desc_data, + extra_hid_report_desc_data +}; +#endif /* EXTRAKEY_ENABLE */ + + +/* + * Configuration Descriptor tree for a HID device + * + * The HID Specifications version 1.11 require the following order: + * - Configuration Descriptor + * - Interface Descriptor + * - HID Descriptor + * - Endpoints Descriptors + */ +#define KBD_HID_DESC_NUM 0 +#define KBD_HID_DESC_OFFSET (9 + (9 + 9 + 7) * KBD_HID_DESC_NUM + 9) + +#ifdef MOUSE_ENABLE +# define MOUSE_HID_DESC_NUM (KBD_HID_DESC_NUM + 1) +# define MOUSE_HID_DESC_OFFSET (9 + (9 + 9 + 7) * MOUSE_HID_DESC_NUM + 9) +#else /* MOUSE_ENABLE */ +# define MOUSE_HID_DESC_NUM (KBD_HID_DESC_NUM + 0) +#endif /* MOUSE_ENABLE */ + +#ifdef CONSOLE_ENABLE +#define CONSOLE_HID_DESC_NUM (MOUSE_HID_DESC_NUM + 1) +#define CONSOLE_HID_DESC_OFFSET (9 + (9 + 9 + 7) * CONSOLE_HID_DESC_NUM + 9) +#else /* CONSOLE_ENABLE */ +# define CONSOLE_HID_DESC_NUM (MOUSE_HID_DESC_NUM + 0) +#endif /* CONSOLE_ENABLE */ + +#ifdef EXTRAKEY_ENABLE +# define EXTRA_HID_DESC_NUM (CONSOLE_HID_DESC_NUM + 1) +# define EXTRA_HID_DESC_OFFSET (9 + (9 + 9 + 7) * EXTRA_HID_DESC_NUM + 9) +#else /* EXTRAKEY_ENABLE */ +# define EXTRA_HID_DESC_NUM (CONSOLE_HID_DESC_NUM + 0) +#endif /* EXTRAKEY_ENABLE */ + +#ifdef NKRO_ENABLE +# define NKRO_HID_DESC_NUM (EXTRA_HID_DESC_NUM + 1) +# define NKRO_HID_DESC_OFFSET (9 + (9 + 9 + 7) * EXTRA_HID_DESC_NUM + 9) +#else /* NKRO_ENABLE */ +# define NKRO_HID_DESC_NUM (EXTRA_HID_DESC_NUM + 0) +#endif /* NKRO_ENABLE */ + +#define NUM_INTERFACES (NKRO_HID_DESC_NUM + 1) +#define CONFIG1_DESC_SIZE (9 + (9 + 9 + 7) * NUM_INTERFACES) + +static const uint8_t hid_configuration_descriptor_data[] = { + /* Configuration Descriptor (9 bytes) USB spec 9.6.3, page 264-266, Table 9-10 */ + USB_DESC_CONFIGURATION(CONFIG1_DESC_SIZE, // wTotalLength + NUM_INTERFACES, // bNumInterfaces + 1, // bConfigurationValue + 0, // iConfiguration + 0xA0, // bmAttributes + 50), // bMaxPower (100mA) + + /* Interface Descriptor (9 bytes) USB spec 9.6.5, page 267-269, Table 9-12 */ + USB_DESC_INTERFACE(KBD_INTERFACE, // bInterfaceNumber + 0, // bAlternateSetting + 1, // bNumEndpoints + 0x03, // bInterfaceClass: HID + 0x01, // bInterfaceSubClass: Boot + 0x01, // bInterfaceProtocol: Keyboard + 0), // iInterface + + /* HID descriptor (9 bytes) HID 1.11 spec, section 6.2.1 */ + USB_DESC_BYTE(9), // bLength + USB_DESC_BYTE(0x21), // bDescriptorType (HID class) + USB_DESC_BCD(0x0111), // bcdHID: HID version 1.11 + USB_DESC_BYTE(0), // bCountryCode + USB_DESC_BYTE(1), // bNumDescriptors + USB_DESC_BYTE(0x22), // bDescriptorType (report desc) + USB_DESC_WORD(sizeof(keyboard_hid_report_desc_data)), // wDescriptorLength + + /* Endpoint Descriptor (7 bytes) USB spec 9.6.6, page 269-271, Table 9-13 */ + USB_DESC_ENDPOINT(KBD_ENDPOINT | 0x80, // bEndpointAddress + 0x03, // bmAttributes (Interrupt) + KBD_SIZE, // wMaxPacketSize + 10), // bInterval + + #ifdef MOUSE_ENABLE + /* Interface Descriptor (9 bytes) USB spec 9.6.5, page 267-269, Table 9-12 */ + USB_DESC_INTERFACE(MOUSE_INTERFACE, // bInterfaceNumber + 0, // bAlternateSetting + 1, // bNumEndpoints + 0x03, // bInterfaceClass (0x03 = HID) + // ThinkPad T23 BIOS doesn't work with boot mouse. + 0x00, // bInterfaceSubClass (0x01 = Boot) + 0x00, // bInterfaceProtocol (0x02 = Mouse) + /* + 0x01, // bInterfaceSubClass (0x01 = Boot) + 0x02, // bInterfaceProtocol (0x02 = Mouse) + */ + 0), // iInterface + + /* HID descriptor (9 bytes) HID 1.11 spec, section 6.2.1 */ + USB_DESC_BYTE(9), // bLength + USB_DESC_BYTE(0x21), // bDescriptorType (HID class) + USB_DESC_BCD(0x0111), // bcdHID: HID version 1.11 + USB_DESC_BYTE(0), // bCountryCode + USB_DESC_BYTE(1), // bNumDescriptors + USB_DESC_BYTE(0x22), // bDescriptorType (report desc) + USB_DESC_WORD(sizeof(mouse_hid_report_desc_data)), // wDescriptorLength + + /* Endpoint Descriptor (7 bytes) USB spec 9.6.6, page 269-271, Table 9-13 */ + USB_DESC_ENDPOINT(MOUSE_ENDPOINT | 0x80, // bEndpointAddress + 0x03, // bmAttributes (Interrupt) + MOUSE_SIZE, // wMaxPacketSize + 1), // bInterval + #endif /* MOUSE_ENABLE */ + + #ifdef CONSOLE_ENABLE + /* Interface Descriptor (9 bytes) USB spec 9.6.5, page 267-269, Table 9-12 */ + USB_DESC_INTERFACE(CONSOLE_INTERFACE, // bInterfaceNumber + 0, // bAlternateSetting + 1, // bNumEndpoints + 0x03, // bInterfaceClass: HID + 0x00, // bInterfaceSubClass: None + 0x00, // bInterfaceProtocol: None + 0), // iInterface + + /* HID descriptor (9 bytes) HID 1.11 spec, section 6.2.1 */ + USB_DESC_BYTE(9), // bLength + USB_DESC_BYTE(0x21), // bDescriptorType (HID class) + USB_DESC_BCD(0x0111), // bcdHID: HID version 1.11 + USB_DESC_BYTE(0), // bCountryCode + USB_DESC_BYTE(1), // bNumDescriptors + USB_DESC_BYTE(0x22), // bDescriptorType (report desc) + USB_DESC_WORD(sizeof(console_hid_report_desc_data)), // wDescriptorLength + + /* Endpoint Descriptor (7 bytes) USB spec 9.6.6, page 269-271, Table 9-13 */ + USB_DESC_ENDPOINT(CONSOLE_ENDPOINT | 0x80, // bEndpointAddress + 0x03, // bmAttributes (Interrupt) + CONSOLE_SIZE, // wMaxPacketSize + 1), // bInterval + #endif /* CONSOLE_ENABLE */ + + #ifdef EXTRAKEY_ENABLE + /* Interface Descriptor (9 bytes) USB spec 9.6.5, page 267-269, Table 9-12 */ + USB_DESC_INTERFACE(EXTRA_INTERFACE, // bInterfaceNumber + 0, // bAlternateSetting + 1, // bNumEndpoints + 0x03, // bInterfaceClass: HID + 0x00, // bInterfaceSubClass: None + 0x00, // bInterfaceProtocol: None + 0), // iInterface + + /* HID descriptor (9 bytes) HID 1.11 spec, section 6.2.1 */ + USB_DESC_BYTE(9), // bLength + USB_DESC_BYTE(0x21), // bDescriptorType (HID class) + USB_DESC_BCD(0x0111), // bcdHID: HID version 1.11 + USB_DESC_BYTE(0), // bCountryCode + USB_DESC_BYTE(1), // bNumDescriptors + USB_DESC_BYTE(0x22), // bDescriptorType (report desc) + USB_DESC_WORD(sizeof(extra_hid_report_desc_data)), // wDescriptorLength + + /* Endpoint Descriptor (7 bytes) USB spec 9.6.6, page 269-271, Table 9-13 */ + USB_DESC_ENDPOINT(EXTRA_ENDPOINT | 0x80, // bEndpointAddress + 0x03, // bmAttributes (Interrupt) + EXTRA_SIZE, // wMaxPacketSize + 10), // bInterval + #endif /* EXTRAKEY_ENABLE */ + + #ifdef NKRO_ENABLE + /* Interface Descriptor (9 bytes) USB spec 9.6.5, page 267-269, Table 9-12 */ + USB_DESC_INTERFACE(NKRO_INTERFACE, // bInterfaceNumber + 0, // bAlternateSetting + 1, // bNumEndpoints + 0x03, // bInterfaceClass: HID + 0x00, // bInterfaceSubClass: None + 0x00, // bInterfaceProtocol: None + 0), // iInterface + + /* HID descriptor (9 bytes) HID 1.11 spec, section 6.2.1 */ + USB_DESC_BYTE(9), // bLength + USB_DESC_BYTE(0x21), // bDescriptorType (HID class) + USB_DESC_BCD(0x0111), // bcdHID: HID version 1.11 + USB_DESC_BYTE(0), // bCountryCode + USB_DESC_BYTE(1), // bNumDescriptors + USB_DESC_BYTE(0x22), // bDescriptorType (report desc) + USB_DESC_WORD(sizeof(nkro_hid_report_desc_data)), // wDescriptorLength + + /* Endpoint Descriptor (7 bytes) USB spec 9.6.6, page 269-271, Table 9-13 */ + USB_DESC_ENDPOINT(NKRO_ENDPOINT | 0x80, // bEndpointAddress + 0x03, // bmAttributes (Interrupt) + NKRO_SIZE, // wMaxPacketSize + 1), // bInterval + #endif /* NKRO_ENABLE */ +}; + +/* Configuration Descriptor wrapper */ +static const USBDescriptor hid_configuration_descriptor = { + sizeof hid_configuration_descriptor_data, + hid_configuration_descriptor_data +}; + +/* wrappers */ +#define HID_DESCRIPTOR_SIZE 9 +static const USBDescriptor keyboard_hid_descriptor = { + HID_DESCRIPTOR_SIZE, + &hid_configuration_descriptor_data[KBD_HID_DESC_OFFSET] +}; +#ifdef MOUSE_ENABLE +static const USBDescriptor mouse_hid_descriptor = { + HID_DESCRIPTOR_SIZE, + &hid_configuration_descriptor_data[MOUSE_HID_DESC_OFFSET] +}; +#endif /* MOUSE_ENABLE */ +#ifdef CONSOLE_ENABLE +static const USBDescriptor console_hid_descriptor = { + HID_DESCRIPTOR_SIZE, + &hid_configuration_descriptor_data[CONSOLE_HID_DESC_OFFSET] +}; +#endif /* CONSOLE_ENABLE */ +#ifdef EXTRAKEY_ENABLE +static const USBDescriptor extra_hid_descriptor = { + HID_DESCRIPTOR_SIZE, + &hid_configuration_descriptor_data[EXTRA_HID_DESC_OFFSET] +}; +#endif /* EXTRAKEY_ENABLE */ +#ifdef NKRO_ENABLE +static const USBDescriptor nkro_hid_descriptor = { + HID_DESCRIPTOR_SIZE, + &hid_configuration_descriptor_data[NKRO_HID_DESC_OFFSET] +}; +#endif /* NKRO_ENABLE */ + + +/* U.S. English language identifier */ +static const uint8_t usb_string_langid[] = { + USB_DESC_BYTE(4), // bLength + USB_DESC_BYTE(USB_DESCRIPTOR_STRING), // bDescriptorType + USB_DESC_WORD(0x0409) // wLANGID (U.S. English) +}; + +/* ugly ugly hack */ +#define PP_NARG(...) \ + PP_NARG_(__VA_ARGS__,PP_RSEQ_N()) +#define PP_NARG_(...) \ + PP_ARG_N(__VA_ARGS__) +#define PP_ARG_N( \ + _1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \ + _11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \ + _21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \ + _31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \ + _41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \ + _51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \ + _61,_62,_63,N,...) N +#define PP_RSEQ_N() \ + 63,62,61,60, \ + 59,58,57,56,55,54,53,52,51,50, \ + 49,48,47,46,45,44,43,42,41,40, \ + 39,38,37,36,35,34,33,32,31,30, \ + 29,28,27,26,25,24,23,22,21,20, \ + 19,18,17,16,15,14,13,12,11,10, \ + 9,8,7,6,5,4,3,2,1,0 + +/* Vendor string = manufacturer */ +static const uint8_t usb_string_vendor[] = { + USB_DESC_BYTE(PP_NARG(USBSTR_MANUFACTURER)+2), // bLength + USB_DESC_BYTE(USB_DESCRIPTOR_STRING), // bDescriptorType + USBSTR_MANUFACTURER +}; + +/* Device Description string = product */ +static const uint8_t usb_string_description[] = { + USB_DESC_BYTE(PP_NARG(USBSTR_PRODUCT)+2), // bLength + USB_DESC_BYTE(USB_DESCRIPTOR_STRING), // bDescriptorType + USBSTR_PRODUCT +}; + +/* Serial Number string (will be filled by the function init_usb_serial_string) */ +static uint8_t usb_string_serial[] = { + USB_DESC_BYTE(22), // bLength + USB_DESC_BYTE(USB_DESCRIPTOR_STRING), // bDescriptorType + '0', 0, 'x', 0, 'D', 0, 'E', 0, 'A', 0, 'D', 0, 'B', 0, 'E', 0, 'E', 0, 'F', 0 +}; + +/* Strings wrappers array */ +static const USBDescriptor usb_strings[] = { + { sizeof usb_string_langid, usb_string_langid } + , + { sizeof usb_string_vendor, usb_string_vendor } + , + { sizeof usb_string_description, usb_string_description } + , + { sizeof usb_string_serial, usb_string_serial } +}; + +/* + * Handles the GET_DESCRIPTOR callback + * + * Returns the proper descriptor + */ +static const USBDescriptor *usb_get_descriptor_cb(USBDriver *usbp, uint8_t dtype, uint8_t dindex, uint16_t lang) { + (void)usbp; + (void)lang; + switch(dtype) { + /* Generic descriptors */ + case USB_DESCRIPTOR_DEVICE: /* Device Descriptor */ + return &usb_device_descriptor; + + case USB_DESCRIPTOR_CONFIGURATION: /* Configuration Descriptor */ + return &hid_configuration_descriptor; + + case USB_DESCRIPTOR_STRING: /* Strings */ + if(dindex < 4) + return &usb_strings[dindex]; + break; + + /* HID specific descriptors */ + case USB_DESCRIPTOR_HID: /* HID Descriptors */ + switch(lang) { /* yea, poor label, it's actually wIndex from the setup packet */ + case KBD_INTERFACE: + return &keyboard_hid_descriptor; + +#ifdef MOUSE_ENABLE + case MOUSE_INTERFACE: + return &mouse_hid_descriptor; +#endif /* MOUSE_ENABLE */ +#ifdef CONSOLE_ENABLE + case CONSOLE_INTERFACE: + return &console_hid_descriptor; +#endif /* CONSOLE_ENABLE */ +#ifdef EXTRAKEY_ENABLE + case EXTRA_INTERFACE: + return &extra_hid_descriptor; +#endif /* EXTRAKEY_ENABLE */ +#ifdef NKRO_ENABLE + case NKRO_INTERFACE: + return &nkro_hid_descriptor; +#endif /* NKRO_ENABLE */ + } + + case USB_DESCRIPTOR_HID_REPORT: /* HID Report Descriptor */ + switch(lang) { + case KBD_INTERFACE: + return &keyboard_hid_report_descriptor; + +#ifdef MOUSE_ENABLE + case MOUSE_INTERFACE: + return &mouse_hid_report_descriptor; +#endif /* MOUSE_ENABLE */ +#ifdef CONSOLE_ENABLE + case CONSOLE_INTERFACE: + return &console_hid_report_descriptor; +#endif /* CONSOLE_ENABLE */ +#ifdef EXTRAKEY_ENABLE + case EXTRA_INTERFACE: + return &extra_hid_report_descriptor; +#endif /* EXTRAKEY_ENABLE */ +#ifdef NKRO_ENABLE + case NKRO_INTERFACE: + return &nkro_hid_report_descriptor; +#endif /* NKRO_ENABLE */ + } + } + return NULL; +} + +/* keyboard endpoint state structure */ +static USBInEndpointState kbd_ep_state; +/* keyboard endpoint initialization structure (IN) */ +static const USBEndpointConfig kbd_ep_config = { + USB_EP_MODE_TYPE_INTR, /* Interrupt EP */ + NULL, /* SETUP packet notification callback */ + kbd_in_cb, /* IN notification callback */ + NULL, /* OUT notification callback */ + KBD_SIZE, /* IN maximum packet size */ + 0, /* OUT maximum packet size */ + &kbd_ep_state, /* IN Endpoint state */ + NULL, /* OUT endpoint state */ + 2, /* IN multiplier */ + NULL /* SETUP buffer (not a SETUP endpoint) */ +}; + +#ifdef MOUSE_ENABLE +/* mouse endpoint state structure */ +static USBInEndpointState mouse_ep_state; + +/* mouse endpoint initialization structure (IN) */ +static const USBEndpointConfig mouse_ep_config = { + USB_EP_MODE_TYPE_INTR, /* Interrupt EP */ + NULL, /* SETUP packet notification callback */ + mouse_in_cb, /* IN notification callback */ + NULL, /* OUT notification callback */ + MOUSE_SIZE, /* IN maximum packet size */ + 0, /* OUT maximum packet size */ + &mouse_ep_state, /* IN Endpoint state */ + NULL, /* OUT endpoint state */ + 2, /* IN multiplier */ + NULL /* SETUP buffer (not a SETUP endpoint) */ +}; +#endif /* MOUSE_ENABLE */ + +#ifdef CONSOLE_ENABLE +/* console endpoint state structure */ +static USBInEndpointState console_ep_state; + +/* console endpoint initialization structure (IN) */ +static const USBEndpointConfig console_ep_config = { + USB_EP_MODE_TYPE_INTR, /* Interrupt EP */ + NULL, /* SETUP packet notification callback */ + console_in_cb, /* IN notification callback */ + NULL, /* OUT notification callback */ + CONSOLE_SIZE, /* IN maximum packet size */ + 0, /* OUT maximum packet size */ + &console_ep_state, /* IN Endpoint state */ + NULL, /* OUT endpoint state */ + 2, /* IN multiplier */ + NULL /* SETUP buffer (not a SETUP endpoint) */ +}; +#endif /* CONSOLE_ENABLE */ + +#ifdef EXTRAKEY_ENABLE +/* extrakey endpoint state structure */ +static USBInEndpointState extra_ep_state; + +/* extrakey endpoint initialization structure (IN) */ +static const USBEndpointConfig extra_ep_config = { + USB_EP_MODE_TYPE_INTR, /* Interrupt EP */ + NULL, /* SETUP packet notification callback */ + extra_in_cb, /* IN notification callback */ + NULL, /* OUT notification callback */ + EXTRA_SIZE, /* IN maximum packet size */ + 0, /* OUT maximum packet size */ + &extra_ep_state, /* IN Endpoint state */ + NULL, /* OUT endpoint state */ + 2, /* IN multiplier */ + NULL /* SETUP buffer (not a SETUP endpoint) */ +}; +#endif /* EXTRAKEY_ENABLE */ + +#ifdef NKRO_ENABLE +/* nkro endpoint state structure */ +static USBInEndpointState nkro_ep_state; + +/* nkro endpoint initialization structure (IN) */ +static const USBEndpointConfig nkro_ep_config = { + USB_EP_MODE_TYPE_INTR, /* Interrupt EP */ + NULL, /* SETUP packet notification callback */ + nkro_in_cb, /* IN notification callback */ + NULL, /* OUT notification callback */ + NKRO_SIZE, /* IN maximum packet size */ + 0, /* OUT maximum packet size */ + &nkro_ep_state, /* IN Endpoint state */ + NULL, /* OUT endpoint state */ + 2, /* IN multiplier */ + NULL /* SETUP buffer (not a SETUP endpoint) */ +}; +#endif /* NKRO_ENABLE */ + +/* --------------------------------------------------------- + * USB driver functions + * --------------------------------------------------------- + */ + +/* Handles the USB driver global events + * TODO: maybe disable some things when connection is lost? */ +static void usb_event_cb(USBDriver *usbp, usbevent_t event) { + switch(event) { + case USB_EVENT_RESET: + return; + + case USB_EVENT_ADDRESS: + return; + + case USB_EVENT_CONFIGURED: + osalSysLockFromISR(); + /* Enable the endpoints specified into the configuration. */ + usbInitEndpointI(usbp, KBD_ENDPOINT, &kbd_ep_config); +#ifdef MOUSE_ENABLE + usbInitEndpointI(usbp, MOUSE_ENDPOINT, &mouse_ep_config); +#endif /* MOUSE_ENABLE */ +#ifdef CONSOLE_ENABLE + usbInitEndpointI(usbp, CONSOLE_ENDPOINT, &console_ep_config); + /* don't need to start the flush timer, it starts from console_in_cb automatically */ +#endif /* CONSOLE_ENABLE */ +#ifdef EXTRAKEY_ENABLE + usbInitEndpointI(usbp, EXTRA_ENDPOINT, &extra_ep_config); +#endif /* EXTRAKEY_ENABLE */ +#ifdef NKRO_ENABLE + usbInitEndpointI(usbp, NKRO_ENDPOINT, &nkro_ep_config); +#endif /* NKRO_ENABLE */ + osalSysUnlockFromISR(); + return; + + case USB_EVENT_SUSPEND: + return; + + case USB_EVENT_WAKEUP: + return; + + case USB_EVENT_STALLED: + return; + } +} + +/* Function used locally in os/hal/src/usb.c for getting descriptors + * need it here for HID descriptor */ +static uint16_t get_hword(uint8_t *p) { + uint16_t hw; + + hw = (uint16_t)*p++; + hw |= (uint16_t)*p << 8U; + return hw; +} + +/* + * Appendix G: HID Request Support Requirements + * + * The following table enumerates the requests that need to be supported by various types of HID class devices. + * Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol + * ------------------------------------------------------------------------------------------ + * Boot Mouse Required Optional Optional Optional Required Required + * Non-Boot Mouse Required Optional Optional Optional Optional Optional + * Boot Keyboard Required Optional Required Required Required Required + * Non-Boot Keybrd Required Optional Required Required Optional Optional + * Other Device Required Optional Optional Optional Optional Optional + */ + +/* Callback for SETUP request on the endpoint 0 (control) */ +static bool usb_request_hook_cb(USBDriver *usbp) { + const USBDescriptor *dp; + + /* usbp->setup fields: + * 0: bmRequestType (bitmask) + * 1: bRequest + * 2,3: (LSB,MSB) wValue + * 4,5: (LSB,MSB) wIndex + * 6,7: (LSB,MSB) wLength (number of bytes to transfer if there is a data phase) */ + + /* Handle HID class specific requests */ + if(((usbp->setup[0] & USB_RTYPE_TYPE_MASK) == USB_RTYPE_TYPE_CLASS) && + ((usbp->setup[0] & USB_RTYPE_RECIPIENT_MASK) == USB_RTYPE_RECIPIENT_INTERFACE)) { + switch(usbp->setup[0] & USB_RTYPE_DIR_MASK) { + case USB_RTYPE_DIR_DEV2HOST: + switch(usbp->setup[1]) { /* bRequest */ + case HID_GET_REPORT: + switch(usbp->setup[4]) { /* LSB(wIndex) (check MSB==0?) */ + case KBD_INTERFACE: +#ifdef NKRO_ENABLE + case NKRO_INTERFACE: +#endif /* NKRO_ENABLE */ + usbSetupTransfer(usbp, (uint8_t *)&keyboard_report_sent, sizeof(keyboard_report_sent), NULL); + return TRUE; + break; + + default: + usbSetupTransfer(usbp, NULL, 0, NULL); + return TRUE; + break; + } + break; + + case HID_GET_PROTOCOL: + if((usbp->setup[4] == KBD_INTERFACE) && (usbp->setup[5] == 0)) { /* wIndex */ + usbSetupTransfer(usbp, &keyboard_protocol, 1, NULL); + return TRUE; + } + break; + + case HID_GET_IDLE: + usbSetupTransfer(usbp, &keyboard_idle, 1, NULL); + return TRUE; + break; + } + break; + + case USB_RTYPE_DIR_HOST2DEV: + switch(usbp->setup[1]) { /* bRequest */ + case HID_SET_REPORT: + switch(usbp->setup[4]) { /* LSB(wIndex) (check MSB==0 and wLength==1?) */ + case KBD_INTERFACE: +#ifdef NKRO_ENABLE + case NKRO_INTERFACE: +#endif /* NKRO_ENABLE */ + /* keyboard_led_stats = + * keyboard_led_stats needs be word (or dword), otherwise we get an exception on F0 */ + usbSetupTransfer(usbp, (uint8_t *)&keyboard_led_stats, 1, NULL); + return TRUE; + break; + } + break; + + case HID_SET_PROTOCOL: + if((usbp->setup[4] == KBD_INTERFACE) && (usbp->setup[5] == 0)) { /* wIndex */ + keyboard_protocol = ((usbp->setup[2]) != 0x00); /* LSB(wValue) */ +#ifdef NKRO_ENABLE + keyboard_nkro = !!keyboard_protocol; + if(!keyboard_nkro && keyboard_idle) { +#else /* NKRO_ENABLE */ + if(keyboard_idle) { +#endif /* NKRO_ENABLE */ + /* arm the idle timer if boot protocol & idle */ + osalSysLockFromISR(); + chVTSetI(&keyboard_idle_timer, 4*MS2ST(keyboard_idle), keyboard_idle_timer_cb, NULL); + osalSysUnlockFromISR(); + } + } + usbSetupTransfer(usbp, NULL, 0, NULL); + return TRUE; + break; + + case HID_SET_IDLE: + keyboard_idle = usbp->setup[3]; /* MSB(wValue) */ + /* arm the timer */ +#ifdef NKRO_ENABLE + if(!keyboard_nkro && keyboard_idle) { +#else /* NKRO_ENABLE */ + if(keyboard_idle) { +#endif /* NKRO_ENABLE */ + osalSysLockFromISR(); + chVTSetI(&keyboard_idle_timer, 4*MS2ST(keyboard_idle), keyboard_idle_timer_cb, NULL); + osalSysUnlockFromISR(); + } + usbSetupTransfer(usbp, NULL, 0, NULL); + return TRUE; + break; + } + break; + } + } + + /* Handle the Get_Descriptor Request for HID class (not handled by the default hook) */ + if((usbp->setup[0] == 0x81) && (usbp->setup[1] == USB_REQ_GET_DESCRIPTOR)) { + dp = usbp->config->get_descriptor_cb(usbp, usbp->setup[3], usbp->setup[2], get_hword(&usbp->setup[4])); + if(dp == NULL) + return FALSE; + usbSetupTransfer(usbp, (uint8_t *)dp->ud_string, dp->ud_size, NULL); + return TRUE; + } + + return FALSE; +} + +/* Start-of-frame callback */ +static void usb_sof_cb(USBDriver *usbp) { + kbd_sof_cb(usbp); +} + + +/* USB driver configuration */ +static const USBConfig usbcfg = { + usb_event_cb, /* USB events callback */ + usb_get_descriptor_cb, /* Device GET_DESCRIPTOR request callback */ + usb_request_hook_cb, /* Requests hook callback */ + usb_sof_cb /* Start Of Frame callback */ +}; + +/* + * Initialize the USB driver + */ +void init_usb_driver(void) { + /* + * Activates the USB driver and then the USB bus pull-up on D+. + * Note, a delay is inserted in order to not have to disconnect the cable + * after a reset. + */ + usbDisconnectBus(&USB_DRIVER); + chThdSleepMilliseconds(1500); + usbStart(&USB_DRIVER, &usbcfg); + usbConnectBus(&USB_DRIVER); + + chVTObjectInit(&keyboard_idle_timer); +#ifdef CONSOLE_ENABLE + oqObjectInit(&console_queue, console_queue_buffer, sizeof(console_queue_buffer), console_queue_onotify, NULL); + chVTObjectInit(&console_flush_timer); +#endif +} + +/* --------------------------------------------------------- + * Keyboard functions + * --------------------------------------------------------- + */ + +/* keyboard IN callback hander (a kbd report has made it IN) */ +void kbd_in_cb(USBDriver *usbp, usbep_t ep) { + /* STUB */ + (void)usbp; + (void)ep; +} + +#ifdef NKRO_ENABLE +/* nkro IN callback hander (a nkro report has made it IN) */ +void nkro_in_cb(USBDriver *usbp, usbep_t ep) { + /* STUB */ + (void)usbp; + (void)ep; +} +#endif /* NKRO_ENABLE */ + +/* start-of-frame handler + * TODO: i guess it would be better to re-implement using timers, + * so that this is not going to have to be checked every 1ms */ +void kbd_sof_cb(USBDriver *usbp) { + (void)usbp; +} + +/* Idle requests timer code + * callback (called from ISR, unlocked state) */ +static void keyboard_idle_timer_cb(void *arg) { + (void)arg; + + osalSysLockFromISR(); + + /* check that the states of things are as they're supposed to */ + if(usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) { + /* do not rearm the timer, should be enabled on IDLE request */ + osalSysUnlockFromISR(); + return; + } + +#ifdef NKRO_ENABLE + if(!keyboard_nkro && keyboard_idle) { +#else /* NKRO_ENABLE */ + if(keyboard_idle) { +#endif /* NKRO_ENABLE */ + /* TODO: are we sure we want the KBD_ENDPOINT? */ + osalSysUnlockFromISR(); + usbPrepareTransmit(&USB_DRIVER, KBD_ENDPOINT, (uint8_t *)&keyboard_report_sent, sizeof(keyboard_report_sent)); + osalSysLockFromISR(); + usbStartTransmitI(&USB_DRIVER, KBD_ENDPOINT); + /* rearm the timer */ + chVTSetI(&keyboard_idle_timer, 4*MS2ST(keyboard_idle), keyboard_idle_timer_cb, NULL); + } + + /* do not rearm the timer if the condition above fails + * it should be enabled again on either IDLE or SET_PROTOCOL requests */ + osalSysUnlockFromISR(); +} + +/* LED status */ +uint8_t keyboard_leds(void) { + return (uint8_t)(keyboard_led_stats & 0xFF); +} + +/* prepare and start sending a report IN + * not callable from ISR or locked state */ +void send_keyboard(report_keyboard_t *report) { + osalSysLock(); + if(usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) { + osalSysUnlock(); + return; + } + osalSysUnlock(); + +#ifdef NKRO_ENABLE + if(keyboard_nkro) { /* NKRO protocol */ + usbPrepareTransmit(&USB_DRIVER, NKRO_ENDPOINT, (uint8_t *)report, sizeof(report_keyboard_t)); + osalSysLock(); + usbStartTransmitI(&USB_DRIVER, NKRO_ENDPOINT); + osalSysUnlock(); + } else +#endif /* NKRO_ENABLE */ + { /* boot protocol */ + usbPrepareTransmit(&USB_DRIVER, KBD_ENDPOINT, (uint8_t *)report, sizeof(report_keyboard_t)); + osalSysLock(); + usbStartTransmitI(&USB_DRIVER, KBD_ENDPOINT); + osalSysUnlock(); + } + keyboard_report_sent = *report; +} + +/* --------------------------------------------------------- + * Mouse functions + * --------------------------------------------------------- + */ + +#ifdef MOUSE_ENABLE + +/* mouse IN callback hander (a mouse report has made it IN) */ +void mouse_in_cb(USBDriver *usbp, usbep_t ep) { + (void)usbp; + (void)ep; +} + +void send_mouse(report_mouse_t *report) { + osalSysLock(); + if(usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) { + osalSysUnlock(); + return; + } + osalSysUnlock(); + + /* TODO: LUFA manually waits for the endpoint to become ready + * for about 10ms for mouse, kbd, system; 1ms for nkro + * is this really needed? + */ + + usbPrepareTransmit(&USB_DRIVER, MOUSE_ENDPOINT, (uint8_t *)report, sizeof(report_mouse_t)); + osalSysLock(); + usbStartTransmitI(&USB_DRIVER, MOUSE_ENDPOINT); + osalSysUnlock(); +} + +#else /* MOUSE_ENABLE */ +void send_mouse(report_mouse_t *report) { + (void)report; +} +#endif /* MOUSE_ENABLE */ + +/* --------------------------------------------------------- + * Extrakey functions + * --------------------------------------------------------- + */ + +#ifdef EXTRAKEY_ENABLE + +/* extrakey IN callback hander */ +void extra_in_cb(USBDriver *usbp, usbep_t ep) { + /* STUB */ + (void)usbp; + (void)ep; +} + +static void send_extra_report(uint8_t report_id, uint16_t data) { + osalSysLock(); + if(usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) { + osalSysUnlock(); + return; + } + + report_extra_t report = { + .report_id = report_id, + .usage = data + }; + + osalSysUnlock(); + usbPrepareTransmit(&USB_DRIVER, EXTRA_ENDPOINT, (uint8_t *)&report, sizeof(report_extra_t)); + osalSysLock(); + usbStartTransmitI(&USB_DRIVER, EXTRA_ENDPOINT); + osalSysUnlock(); +} + +void send_system(uint16_t data) { + send_extra_report(REPORT_ID_SYSTEM, data); +} + +void send_consumer(uint16_t data) { + send_extra_report(REPORT_ID_CONSUMER, data); +} + +#else /* EXTRAKEY_ENABLE */ +void send_system(uint16_t data) { + (void)data; +} +void send_consumer(uint16_t data) { + (void)data; +} +#endif /* EXTRAKEY_ENABLE */ + +/* --------------------------------------------------------- + * Console functions + * --------------------------------------------------------- + */ + +#ifdef CONSOLE_ENABLE + +/* debug IN callback hander */ +void console_in_cb(USBDriver *usbp, usbep_t ep) { + (void)ep; + osalSysLockFromISR(); + + /* rearm the timer */ + chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, NULL); + + /* Check if there is data to send left in the output queue */ + if(chOQGetFullI(&console_queue) >= CONSOLE_SIZE) { + osalSysUnlockFromISR(); + usbPrepareQueuedTransmit(usbp, CONSOLE_ENDPOINT, &console_queue, CONSOLE_SIZE); + osalSysLockFromISR(); + usbStartTransmitI(usbp, CONSOLE_ENDPOINT); + } + + osalSysUnlockFromISR(); +} + +/* Callback when data is inserted into the output queue + * Called from a locked state */ +void console_queue_onotify(io_queue_t *qp) { + (void)qp; + + if(usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) + return; + + if(!usbGetTransmitStatusI(&USB_DRIVER, CONSOLE_ENDPOINT) + && (chOQGetFullI(&console_queue) >= CONSOLE_SIZE)) { + osalSysUnlock(); + usbPrepareQueuedTransmit(&USB_DRIVER, CONSOLE_ENDPOINT, &console_queue, CONSOLE_SIZE); + osalSysLock(); + usbStartTransmitI(&USB_DRIVER, CONSOLE_ENDPOINT); + } +} + +/* Flush timer code + * callback (called from ISR, unlocked state) */ +static void console_flush_cb(void *arg) { + (void)arg; + size_t i, n; + uint8_t buf[CONSOLE_SIZE]; /* TODO: a solution without extra buffer? */ + osalSysLockFromISR(); + + /* check that the states of things are as they're supposed to */ + if(usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) { + /* rearm the timer */ + chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, NULL); + osalSysUnlockFromISR(); + return; + } + + /* don't do anything if the queue is empty or has enough stuff in it */ + if(((n = oqGetFullI(&console_queue)) == 0) || (n >= CONSOLE_SIZE)) { + /* rearm the timer */ + chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, NULL); + osalSysUnlockFromISR(); + return; + } + + /* there's stuff hanging in the queue - so dequeue and send */ + for(i = 0; i < n; i++) + buf[i] = (uint8_t)oqGetI(&console_queue); + for(i = n; i < CONSOLE_SIZE; i++) + buf[i] = 0; + osalSysUnlockFromISR(); + usbPrepareTransmit(&USB_DRIVER, CONSOLE_ENDPOINT, buf, CONSOLE_SIZE); + osalSysLockFromISR(); + (void)usbStartTransmitI(&USB_DRIVER, CONSOLE_ENDPOINT); + + /* rearm the timer */ + chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, NULL); + osalSysUnlockFromISR(); +} + + +int8_t sendchar(uint8_t c) { + osalSysLock(); + if(usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) { + osalSysUnlock(); + return 0; + } + osalSysUnlock(); + /* should get suspended and wait if the queue is full + * but it's not blocking even if noone is listening, + * because the USB packets are sent anyway */ + return(chOQPut(&console_queue, c)); +} + +#else /* CONSOLE_ENABLE */ +int8_t sendchar(uint8_t c) { + (void)c; + return 0; +} +#endif /* CONSOLE_ENABLE */ + +void sendchar_pf(void *p, char c) { + (void)p; + sendchar((uint8_t)c); +} diff --git a/tmk_core/protocol/chibios/usb_main.h b/tmk_core/protocol/chibios/usb_main.h new file mode 100644 index 00000000..b7696643 --- /dev/null +++ b/tmk_core/protocol/chibios/usb_main.h @@ -0,0 +1,149 @@ +/* + * (c) 2015 flabberast + * + * Based on the following work: + * - Guillaume Duc's raw hid example (MIT License) + * https://github.com/guiduc/usb-hid-chibios-example + * - PJRC Teensy examples (MIT License) + * https://www.pjrc.com/teensy/usb_keyboard.html + * - hasu's TMK keyboard code (GPL v2 and some code Modified BSD) + * https://github.com/tmk/tmk_keyboard/ + * - ChibiOS demo code (Apache 2.0 License) + * http://www.chibios.org + * + * Since some GPL'd code is used, this work is licensed under + * GPL v2 or later. + */ + + +#ifndef _USB_MAIN_H_ +#define _USB_MAIN_H_ + +#include "ch.h" +#include "hal.h" + +/* ------------------------- + * General USB driver header + * ------------------------- + */ + +/* The USB driver to use */ +#define USB_DRIVER USBD1 + +/* Initialize the USB driver and bus */ +void init_usb_driver(void); + +/* --------------- + * Keyboard header + * --------------- + */ + +/* main keyboard (6kro) */ +#define KBD_INTERFACE 0 +#define KBD_ENDPOINT 1 +#define KBD_SIZE 8 +#define KBD_REPORT_KEYS (KBD_SIZE - 2) + +/* secondary keyboard */ +#ifdef NKRO_ENABLE +#define NKRO_INTERFACE 4 +#define NKRO_ENDPOINT 5 +#define NKRO_SIZE 16 +#define NKRO_REPORT_KEYS (NKRO_SIZE - 1) +#endif + +/* this defines report_keyboard_t and computes REPORT_SIZE defines */ +#include "report.h" + +/* extern report_keyboard_t keyboard_report_sent; */ + +/* keyboard IN request callback handler */ +void kbd_in_cb(USBDriver *usbp, usbep_t ep); + +/* start-of-frame handler */ +void kbd_sof_cb(USBDriver *usbp); + +#ifdef NKRO_ENABLE +/* nkro IN callback hander */ +void nkro_in_cb(USBDriver *usbp, usbep_t ep); +#endif /* NKRO_ENABLE */ + +/* ------------ + * Mouse header + * ------------ + */ + +#ifdef MOUSE_ENABLE + +#define MOUSE_INTERFACE 1 +#define MOUSE_ENDPOINT 2 +#define MOUSE_SIZE 8 + +/* mouse IN request callback handler */ +void mouse_in_cb(USBDriver *usbp, usbep_t ep); +#endif /* MOUSE_ENABLE */ + +/* --------------- + * Extrakey header + * --------------- + */ + +#ifdef EXTRAKEY_ENABLE + +#define EXTRA_INTERFACE 3 +#define EXTRA_ENDPOINT 4 +#define EXTRA_SIZE 8 + +/* extrakey IN request callback handler */ +void extra_in_cb(USBDriver *usbp, usbep_t ep); + +/* extra report structure */ +typedef struct { + uint8_t report_id; + uint16_t usage; +} __attribute__ ((packed)) report_extra_t; +#endif /* EXTRAKEY_ENABLE */ + +/* -------------- + * Console header + * -------------- + */ + +#ifdef CONSOLE_ENABLE + +#define CONSOLE_INTERFACE 2 +#define CONSOLE_ENDPOINT 3 +#define CONSOLE_SIZE 16 + +/* Number of IN reports that can be stored inside the output queue */ +#define CONSOLE_QUEUE_CAPACITY 2 +#define CONSOLE_QUEUE_BUFFER_SIZE (CONSOLE_QUEUE_CAPACITY * CONSOLE_SIZE) + +/* Console flush time */ +#define CONSOLE_FLUSH_MS 50 + +/* Putchar over the USB console */ +int8_t sendchar(uint8_t c); +/* wrapper for printf lib */ + +/* Flush output (send everything immediately) */ +void console_flush_output(void); + +/* console IN request callback handler */ +void console_in_cb(USBDriver *usbp, usbep_t ep); +#endif /* CONSOLE_ENABLE */ + +void sendchar_pf(void *p, char c); + +/* --------------------------- + * Host driver functions (TMK) + * --------------------------- + */ + +uint8_t keyboard_leds(void); +void send_keyboard(report_keyboard_t *report); +void send_mouse(report_mouse_t *report); +void send_system(uint16_t data); +void send_consumer(uint16_t data); + +#endif /* _USB_MAIN_H_ */ diff --git a/tmk_core/tool/chibios/common.mk b/tmk_core/tool/chibios/common.mk new file mode 100644 index 00000000..952ec493 --- /dev/null +++ b/tmk_core/tool/chibios/common.mk @@ -0,0 +1,86 @@ +COMMON_DIR = $(TMK_DIR)/common +SRC += $(COMMON_DIR)/host.c \ + $(COMMON_DIR)/keyboard.c \ + $(COMMON_DIR)/action.c \ + $(COMMON_DIR)/action_tapping.c \ + $(COMMON_DIR)/action_macro.c \ + $(COMMON_DIR)/action_layer.c \ + $(COMMON_DIR)/action_util.c \ + $(COMMON_DIR)/keymap.c \ + $(COMMON_DIR)/print.c \ + $(COMMON_DIR)/debug.c \ + $(COMMON_DIR)/util.c \ + $(COMMON_DIR)/chibios/suspend.c \ + $(COMMON_DIR)/chibios/printf.c \ + $(COMMON_DIR)/chibios/timer.c \ + $(COMMON_DIR)/chibios/bootloader.c + + +# Option modules +ifdef BOOTMAGIC_ENABLE + $(error Bootmagic Not Supported) + SRC += $(COMMON_DIR)/bootmagic.c + SRC += $(COMMON_DIR)/chibios/eeconfig.c + OPT_DEFS += -DBOOTMAGIC_ENABLE +endif + +ifdef MOUSEKEY_ENABLE + SRC += $(COMMON_DIR)/mousekey.c + OPT_DEFS += -DMOUSEKEY_ENABLE + OPT_DEFS += -DMOUSE_ENABLE +endif + +ifdef EXTRAKEY_ENABLE + OPT_DEFS += -DEXTRAKEY_ENABLE +endif + +ifdef CONSOLE_ENABLE + OPT_DEFS += -DCONSOLE_ENABLE +else + OPT_DEFS += -DNO_PRINT + OPT_DEFS += -DNO_DEBUG +endif + +ifdef COMMAND_ENABLE + SRC += $(COMMON_DIR)/command.c + OPT_DEFS += -DCOMMAND_ENABLE +endif + +ifdef NKRO_ENABLE + OPT_DEFS += -DNKRO_ENABLE +endif + +ifdef USB_6KRO_ENABLE + OPT_DEFS += -DUSB_6KRO_ENABLE +endif + +ifdef SLEEP_LED_ENABLE + $(error Sleep LED Not Supported) + SRC += $(COMMON_DIR)/sleep_led.c + OPT_DEFS += -DSLEEP_LED_ENABLE + OPT_DEFS += -DNO_SUSPEND_POWER_DOWN +endif + +ifdef BACKLIGHT_ENABLE + SRC += $(COMMON_DIR)/backlight.c + OPT_DEFS += -DBACKLIGHT_ENABLE +endif + +ifdef KEYMAP_SECTION_ENABLE + OPT_DEFS += -DKEYMAP_SECTION_ENABLE + + ifeq ($(strip $(MCU)),atmega32u2) + EXTRALDFLAGS = -Wl,-L$(TMK_DIR),-Tldscript_keymap_avr35.x + else ifeq ($(strip $(MCU)),atmega32u4) + EXTRALDFLAGS = -Wl,-L$(TMK_DIR),-Tldscript_keymap_avr5.x + else + EXTRALDFLAGS = $(error no ldscript for keymap section) + endif +endif + +# Version string +OPT_DEFS += -DVERSION=$(shell (git describe --always --dirty || echo 'unknown') 2> /dev/null) + + +# Search Path +VPATH += $(TMK_DIR)/common From 1d115301d4134f59e8043a34400f08aac094704e Mon Sep 17 00:00:00 2001 From: flabbergast Date: Tue, 8 Sep 2015 15:35:02 +0100 Subject: [PATCH 03/29] Make usb_main more USB_DRIVER #define independent. --- tmk_core/protocol/chibios/chibios.mk | 2 +- tmk_core/protocol/chibios/main.c | 2 +- tmk_core/protocol/chibios/usb_main.c | 50 ++++++++++++++-------------- tmk_core/protocol/chibios/usb_main.h | 2 +- 4 files changed, 28 insertions(+), 28 deletions(-) diff --git a/tmk_core/protocol/chibios/chibios.mk b/tmk_core/protocol/chibios/chibios.mk index d667f60e..2ae1e5f9 100644 --- a/tmk_core/protocol/chibios/chibios.mk +++ b/tmk_core/protocol/chibios/chibios.mk @@ -97,7 +97,7 @@ endif include $(CHIBIOS)/os/hal/osal/rt/osal.mk # RTOS files (optional). include $(CHIBIOS)/os/rt/rt.mk -include $(CHIBIOS)/os/rt/ports/ARMCMx/compilers/GCC/mk/port_v6m.mk +include $(CHIBIOS)/os/rt/ports/ARMCMx/compilers/GCC/mk/port_v$(ARMV)m.mk # Other files (optional). # Define linker script file here diff --git a/tmk_core/protocol/chibios/main.c b/tmk_core/protocol/chibios/main.c index ce7cd8e3..0d79a91f 100644 --- a/tmk_core/protocol/chibios/main.c +++ b/tmk_core/protocol/chibios/main.c @@ -60,7 +60,7 @@ int main(void) { palClearPad(GPIOC, GPIOC_LED_BLUE); /* Init USB */ - init_usb_driver(); + init_usb_driver(&USB_DRIVER); /* init printf */ init_printf(NULL,sendchar_pf); diff --git a/tmk_core/protocol/chibios/usb_main.c b/tmk_core/protocol/chibios/usb_main.c index 875f47dc..b10e5daa 100644 --- a/tmk_core/protocol/chibios/usb_main.c +++ b/tmk_core/protocol/chibios/usb_main.c @@ -886,7 +886,7 @@ static bool usb_request_hook_cb(USBDriver *usbp) { #endif /* NKRO_ENABLE */ /* arm the idle timer if boot protocol & idle */ osalSysLockFromISR(); - chVTSetI(&keyboard_idle_timer, 4*MS2ST(keyboard_idle), keyboard_idle_timer_cb, NULL); + chVTSetI(&keyboard_idle_timer, 4*MS2ST(keyboard_idle), keyboard_idle_timer_cb, (void *)usbp); osalSysUnlockFromISR(); } } @@ -903,7 +903,7 @@ static bool usb_request_hook_cb(USBDriver *usbp) { if(keyboard_idle) { #endif /* NKRO_ENABLE */ osalSysLockFromISR(); - chVTSetI(&keyboard_idle_timer, 4*MS2ST(keyboard_idle), keyboard_idle_timer_cb, NULL); + chVTSetI(&keyboard_idle_timer, 4*MS2ST(keyboard_idle), keyboard_idle_timer_cb, (void *)usbp); osalSysUnlockFromISR(); } usbSetupTransfer(usbp, NULL, 0, NULL); @@ -943,20 +943,20 @@ static const USBConfig usbcfg = { /* * Initialize the USB driver */ -void init_usb_driver(void) { +void init_usb_driver(USBDriver *usbp) { /* * Activates the USB driver and then the USB bus pull-up on D+. * Note, a delay is inserted in order to not have to disconnect the cable * after a reset. */ - usbDisconnectBus(&USB_DRIVER); + usbDisconnectBus(usbp); chThdSleepMilliseconds(1500); - usbStart(&USB_DRIVER, &usbcfg); - usbConnectBus(&USB_DRIVER); + usbStart(usbp, &usbcfg); + usbConnectBus(usbp); chVTObjectInit(&keyboard_idle_timer); #ifdef CONSOLE_ENABLE - oqObjectInit(&console_queue, console_queue_buffer, sizeof(console_queue_buffer), console_queue_onotify, NULL); + oqObjectInit(&console_queue, console_queue_buffer, sizeof(console_queue_buffer), console_queue_onotify, (void *)usbp); chVTObjectInit(&console_flush_timer); #endif } @@ -992,12 +992,12 @@ void kbd_sof_cb(USBDriver *usbp) { /* Idle requests timer code * callback (called from ISR, unlocked state) */ static void keyboard_idle_timer_cb(void *arg) { - (void)arg; + USBDriver *usbp = (USBDriver *)arg; osalSysLockFromISR(); /* check that the states of things are as they're supposed to */ - if(usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) { + if(usbGetDriverStateI(usbp) != USB_ACTIVE) { /* do not rearm the timer, should be enabled on IDLE request */ osalSysUnlockFromISR(); return; @@ -1010,11 +1010,11 @@ static void keyboard_idle_timer_cb(void *arg) { #endif /* NKRO_ENABLE */ /* TODO: are we sure we want the KBD_ENDPOINT? */ osalSysUnlockFromISR(); - usbPrepareTransmit(&USB_DRIVER, KBD_ENDPOINT, (uint8_t *)&keyboard_report_sent, sizeof(keyboard_report_sent)); + usbPrepareTransmit(usbp, KBD_ENDPOINT, (uint8_t *)&keyboard_report_sent, sizeof(keyboard_report_sent)); osalSysLockFromISR(); - usbStartTransmitI(&USB_DRIVER, KBD_ENDPOINT); + usbStartTransmitI(usbp, KBD_ENDPOINT); /* rearm the timer */ - chVTSetI(&keyboard_idle_timer, 4*MS2ST(keyboard_idle), keyboard_idle_timer_cb, NULL); + chVTSetI(&keyboard_idle_timer, 4*MS2ST(keyboard_idle), keyboard_idle_timer_cb, (void *)usbp); } /* do not rearm the timer if the condition above fails @@ -1155,7 +1155,7 @@ void console_in_cb(USBDriver *usbp, usbep_t ep) { osalSysLockFromISR(); /* rearm the timer */ - chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, NULL); + chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, (void *)usbp); /* Check if there is data to send left in the output queue */ if(chOQGetFullI(&console_queue) >= CONSOLE_SIZE) { @@ -1171,32 +1171,32 @@ void console_in_cb(USBDriver *usbp, usbep_t ep) { /* Callback when data is inserted into the output queue * Called from a locked state */ void console_queue_onotify(io_queue_t *qp) { - (void)qp; + USBDriver *usbp = qGetLink(qp); - if(usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) + if(usbGetDriverStateI(usbp) != USB_ACTIVE) return; - if(!usbGetTransmitStatusI(&USB_DRIVER, CONSOLE_ENDPOINT) + if(!usbGetTransmitStatusI(usbp, CONSOLE_ENDPOINT) && (chOQGetFullI(&console_queue) >= CONSOLE_SIZE)) { osalSysUnlock(); - usbPrepareQueuedTransmit(&USB_DRIVER, CONSOLE_ENDPOINT, &console_queue, CONSOLE_SIZE); + usbPrepareQueuedTransmit(usbp, CONSOLE_ENDPOINT, &console_queue, CONSOLE_SIZE); osalSysLock(); - usbStartTransmitI(&USB_DRIVER, CONSOLE_ENDPOINT); + usbStartTransmitI(usbp, CONSOLE_ENDPOINT); } } /* Flush timer code * callback (called from ISR, unlocked state) */ static void console_flush_cb(void *arg) { - (void)arg; + USBDriver *usbp = (USBDriver *)arg; size_t i, n; uint8_t buf[CONSOLE_SIZE]; /* TODO: a solution without extra buffer? */ osalSysLockFromISR(); /* check that the states of things are as they're supposed to */ - if(usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) { + if(usbGetDriverStateI(usbp) != USB_ACTIVE) { /* rearm the timer */ - chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, NULL); + chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, (void *)usbp); osalSysUnlockFromISR(); return; } @@ -1204,7 +1204,7 @@ static void console_flush_cb(void *arg) { /* don't do anything if the queue is empty or has enough stuff in it */ if(((n = oqGetFullI(&console_queue)) == 0) || (n >= CONSOLE_SIZE)) { /* rearm the timer */ - chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, NULL); + chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, (void *)usbp); osalSysUnlockFromISR(); return; } @@ -1215,12 +1215,12 @@ static void console_flush_cb(void *arg) { for(i = n; i < CONSOLE_SIZE; i++) buf[i] = 0; osalSysUnlockFromISR(); - usbPrepareTransmit(&USB_DRIVER, CONSOLE_ENDPOINT, buf, CONSOLE_SIZE); + usbPrepareTransmit(usbp, CONSOLE_ENDPOINT, buf, CONSOLE_SIZE); osalSysLockFromISR(); - (void)usbStartTransmitI(&USB_DRIVER, CONSOLE_ENDPOINT); + (void)usbStartTransmitI(usbp, CONSOLE_ENDPOINT); /* rearm the timer */ - chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, NULL); + chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, (void *)usbp); osalSysUnlockFromISR(); } diff --git a/tmk_core/protocol/chibios/usb_main.h b/tmk_core/protocol/chibios/usb_main.h index b7696643..baeae80a 100644 --- a/tmk_core/protocol/chibios/usb_main.h +++ b/tmk_core/protocol/chibios/usb_main.h @@ -31,7 +31,7 @@ #define USB_DRIVER USBD1 /* Initialize the USB driver and bus */ -void init_usb_driver(void); +void init_usb_driver(USBDriver *usbp); /* --------------- * Keyboard header From 8152d279a4a4aa01f7d3f0a0a7b09e2081aa0d93 Mon Sep 17 00:00:00 2001 From: flabbergast Date: Tue, 8 Sep 2015 16:06:33 +0100 Subject: [PATCH 04/29] Move chibios to tool. --- tmk_core/{protocol => tool}/chibios/.gitignore | 0 tmk_core/{protocol => tool}/chibios/chibios.mk | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename tmk_core/{protocol => tool}/chibios/.gitignore (100%) rename tmk_core/{protocol => tool}/chibios/chibios.mk (99%) diff --git a/tmk_core/protocol/chibios/.gitignore b/tmk_core/tool/chibios/.gitignore similarity index 100% rename from tmk_core/protocol/chibios/.gitignore rename to tmk_core/tool/chibios/.gitignore diff --git a/tmk_core/protocol/chibios/chibios.mk b/tmk_core/tool/chibios/chibios.mk similarity index 99% rename from tmk_core/protocol/chibios/chibios.mk rename to tmk_core/tool/chibios/chibios.mk index 2ae1e5f9..ee52082e 100644 --- a/tmk_core/protocol/chibios/chibios.mk +++ b/tmk_core/tool/chibios/chibios.mk @@ -83,7 +83,7 @@ endif # # Imported source files and paths -CHIBIOS = $(TMK_DIR)/protocol/chibios/chibios +CHIBIOS = $(TMK_DIR)/tool/chibios/chibios # Startup files. include $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/mk/startup_$(shell echo $(MCU_SERIES) | tr '[:upper:]' '[:lower:]').mk # HAL-OSAL files (optional). From d057e5157ed22508ce87f8fef113be52674ba209 Mon Sep 17 00:00:00 2001 From: flabbergast Date: Tue, 8 Sep 2015 16:07:34 +0100 Subject: [PATCH 05/29] Implement jump-to-bootloader. --- tmk_core/common/chibios/bootloader.c | 15 ++- .../tool/chibios/ch-bootloader-jump.patch | 115 ++++++++++++++++++ tmk_core/tool/chibios/common.mk | 4 + 3 files changed, 131 insertions(+), 3 deletions(-) create mode 100644 tmk_core/tool/chibios/ch-bootloader-jump.patch diff --git a/tmk_core/common/chibios/bootloader.c b/tmk_core/common/chibios/bootloader.c index 6c34e2e0..93f2e378 100644 --- a/tmk_core/common/chibios/bootloader.c +++ b/tmk_core/common/chibios/bootloader.c @@ -1,7 +1,16 @@ -/* TODO */ -/* ... chip dependent ... */ - #include "bootloader.h" +#include "ch.h" +#ifdef BOOTLOADER_ADDRESS +#define SYMVAL(sym) (uint32_t)(((uint8_t *)&(sym)) - ((uint8_t *)0)) +extern uint32_t __ram0_end__; + +void bootloader_jump(void) { + *((unsigned long *)(SYMVAL(__ram0_end__) - 4)) = 0xDEADBEEF; // set magic flag => reset handler will jump into boot loader + NVIC_SystemReset(); +} +#else /* BOOTLOADER_ADDRESS */ void bootloader_jump(void) {} +#endif /* BOOTLOADER_ADDRESS */ + diff --git a/tmk_core/tool/chibios/ch-bootloader-jump.patch b/tmk_core/tool/chibios/ch-bootloader-jump.patch new file mode 100644 index 00000000..7f33e8ac --- /dev/null +++ b/tmk_core/tool/chibios/ch-bootloader-jump.patch @@ -0,0 +1,115 @@ +diff --git a/os/common/ports/ARMCMx/compilers/GCC/crt0_v6m.s b/os/common/ports/ARMCMx/compilers/GCC/crt0_v6m.s +index 38b4513..12a3f39 100644 +--- a/os/common/ports/ARMCMx/compilers/GCC/crt0_v6m.s ++++ b/os/common/ports/ARMCMx/compilers/GCC/crt0_v6m.s +@@ -98,6 +98,13 @@ + #define CRT0_CALL_DESTRUCTORS TRUE + #endif + ++/** ++ * @brief Magic number for jumping to bootloader. ++ */ ++#if !defined(MAGIC_BOOTLOADER_NUMBER) || defined(__DOXYGEN__) ++#define MAGIC_BOOTLOADER_NUMBER 0xDEADBEEF ++#endif ++ + /*===========================================================================*/ + /* Code section. */ + /*===========================================================================*/ +@@ -117,6 +124,17 @@ + .thumb_func + .global Reset_Handler + Reset_Handler: ++ ++#ifdef BOOTLOADER_ADDRESS ++ /* jump to bootloader code */ ++ ldr r0, =__ram0_end__-4 ++ ldr r1, =MAGIC_BOOTLOADER_NUMBER ++ ldr r2, [r0, #0] ++ str r0, [r0, #0] /* erase stored magic */ ++ cmp r2, r1 ++ beq Bootloader_Jump ++#endif /* BOOTLOADER_ADDRESS */ ++ + /* Interrupts are globally masked initially.*/ + cpsid i + +@@ -230,6 +248,21 @@ endfiniloop: + ldr r1, =__default_exit + bx r1 + ++#ifdef BOOTLOADER_ADDRESS ++/* ++ * Jump-to-bootloader function. ++ */ ++ ++ .align 2 ++ .thumb_func ++Bootloader_Jump: ++ ldr r0, =BOOTLOADER_ADDRESS ++ ldr r1, [r0, #0] ++ mov sp, r1 ++ ldr r0, [r0, #4] ++ bx r0 ++#endif /* BOOTLOADER_ADDRESS */ ++ + #endif + + /** @} */ +diff --git a/os/common/ports/ARMCMx/compilers/GCC/crt0_v7m.s b/os/common/ports/ARMCMx/compilers/GCC/crt0_v7m.s +index fcfa4de..2d560da 100644 +--- a/os/common/ports/ARMCMx/compilers/GCC/crt0_v7m.s ++++ b/os/common/ports/ARMCMx/compilers/GCC/crt0_v7m.s +@@ -133,6 +133,13 @@ + #define CRT0_CPACR_INIT 0x00F00000 + #endif + ++/** ++ * @brief Magic number for jumping to bootloader. ++ */ ++#if !defined(MAGIC_BOOTLOADER_NUMBER) || defined(__DOXYGEN__) ++#define MAGIC_BOOTLOADER_NUMBER 0xDEADBEEF ++#endif ++ + /*===========================================================================*/ + /* Code section. */ + /*===========================================================================*/ +@@ -157,6 +164,16 @@ + .thumb_func + .global Reset_Handler + Reset_Handler: ++#ifdef BOOTLOADER_ADDRESS ++ /* jump to bootloader code */ ++ ldr r0, =__ram0_end__-4 ++ ldr r1, =MAGIC_BOOTLOADER_NUMBER ++ ldr r2, [r0, #0] ++ str r0, [r0, #0] /* erase stored magic */ ++ cmp r2, r1 ++ beq Bootloader_Jump ++#endif /* BOOTLOADER_ADDRESS */ ++ + /* Interrupts are globally masked initially.*/ + cpsid i + +@@ -289,6 +306,21 @@ endfiniloop: + /* Branching to the defined exit handler.*/ + b __default_exit + ++#ifdef BOOTLOADER_ADDRESS ++/* ++ * Jump-to-bootloader function. ++ */ ++ ++ .align 2 ++ .thumb_func ++Bootloader_Jump: ++ ldr r0, =BOOTLOADER_ADDRESS ++ ldr r1, [r0, #0] ++ mov sp, r1 ++ ldr r0, [r0, #4] ++ bx r0 ++#endif /* BOOTLOADER_ADDRESS */ ++ + #endif /* !defined(__DOXYGEN__) */ + + /** @} */ diff --git a/tmk_core/tool/chibios/common.mk b/tmk_core/tool/chibios/common.mk index 952ec493..0e9935dc 100644 --- a/tmk_core/tool/chibios/common.mk +++ b/tmk_core/tool/chibios/common.mk @@ -81,6 +81,10 @@ endif # Version string OPT_DEFS += -DVERSION=$(shell (git describe --always --dirty || echo 'unknown') 2> /dev/null) +# Bootloader address +ifdef BOOTLOADER_ADDRESS + OPT_DEFS += -DBOOTLOADER_ADDRESS=$(BOOTLOADER_ADDRESS) +endif # Search Path VPATH += $(TMK_DIR)/common From 9cc281b4efdf2dcd817189bb8e633578d638bc45 Mon Sep 17 00:00:00 2001 From: flabbergast Date: Tue, 8 Sep 2015 19:22:00 +0100 Subject: [PATCH 06/29] Small updates. --- tmk_core/protocol/chibios/README.md | 5 +++-- tmk_core/protocol/chibios/main.c | 2 +- tmk_core/protocol/chibios/usb_main.c | 18 ++++++++++++++++++ 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/tmk_core/protocol/chibios/README.md b/tmk_core/protocol/chibios/README.md index 38fd495e..6fbc7c6e 100644 --- a/tmk_core/protocol/chibios/README.md +++ b/tmk_core/protocol/chibios/README.md @@ -8,16 +8,17 @@ Also pay attention to `-O0` (enabled for debugging); for deployment use `-O2`. - USB string descriptors are a mess. I did not find a way to cleanly generate the right structures from actual strings, so the definitions in individual keyboards' `config.h` are ugly as heck. - There are some random constants left so far, e.g. 5ms sleep between calling `keyboard_task` in `main.c`. There should be no such in `usb_main.c`. Everything is based on timers/interrupts/kernel scheduling (well except `keyboard_task`), so no periodically called things (again, except `keyboard_task`, which is just how TMK is designed). - It is easy to add some code for testing (e.g. blink LED, do stuff on button press, etc...) - just create another thread in `main.c`, it will run independently of the keyboard business. +- Jumping to bootloader works, but it is not entirely pleasant, since it is very much MCU dependent. So, one needs to dig out the right address to jump to, and pass it to the compiler in the `Makefile`. Also, a patch to upstream ChibiOS is needed (supplied), because it `ResetHandler` needs adjusting. - The USB stack works pretty completely; however there are bits of other TMK stuff that are not done yet: ### Immediate todo -- suspend / sleep led +- suspend +- sleep led ### Missing / not working (TMK vs ChibiOS bits) - eeprom / bootmagic (will be chip dependent) -- bootloader jump (chip dependent) ### Tried with diff --git a/tmk_core/protocol/chibios/main.c b/tmk_core/protocol/chibios/main.c index 0d79a91f..6b4ec350 100644 --- a/tmk_core/protocol/chibios/main.c +++ b/tmk_core/protocol/chibios/main.c @@ -76,7 +76,7 @@ int main(void) { host_set_driver(&chibios_driver); #ifdef SLEEP_LED_ENABLE - sleep_led_init(); + sleep_led_init(); #endif print("Keyboard start.\n"); diff --git a/tmk_core/protocol/chibios/usb_main.c b/tmk_core/protocol/chibios/usb_main.c index b10e5daa..f8a31593 100644 --- a/tmk_core/protocol/chibios/usb_main.c +++ b/tmk_core/protocol/chibios/usb_main.c @@ -20,6 +20,11 @@ #include "usb_main.h" +#include "debug.h" +#ifdef SLEEP_LED_ENABLE +#include "sleep_led.h" +#endif + /* --------------------------------------------------------- * Global interface variables and declarations * --------------------------------------------------------- @@ -752,6 +757,7 @@ static const USBEndpointConfig nkro_ep_config = { static void usb_event_cb(USBDriver *usbp, usbevent_t event) { switch(event) { case USB_EVENT_RESET: + //TODO: from ISR! print("[R]"); return; case USB_EVENT_ADDRESS: @@ -778,9 +784,21 @@ static void usb_event_cb(USBDriver *usbp, usbevent_t event) { return; case USB_EVENT_SUSPEND: + //TODO: from ISR! print("[S]"); + //TODO: signal suspend? +#ifdef SLEEP_LED_ENABLE + sleep_led_enable(); +#endif /* SLEEP_LED_ENABLE */ return; case USB_EVENT_WAKEUP: + //TODO: from ISR! print("[W]"); + //TODO: suspend_wakeup_init(); +#ifdef SLEEP_LED_ENABLE + sleep_led_disable(); + // NOTE: converters may not accept this + led_set(host_keyboard_leds()); +#endif /* SLEEP_LED_ENABLE */ return; case USB_EVENT_STALLED: From 5248511209cb765c2548c7037801a8102c75f5a5 Mon Sep 17 00:00:00 2001 From: flabbergast Date: Tue, 8 Sep 2015 20:15:05 +0100 Subject: [PATCH 07/29] Fix bootloader-jump compiling. --- tmk_core/tool/chibios/chibios.mk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tmk_core/tool/chibios/chibios.mk b/tmk_core/tool/chibios/chibios.mk index ee52082e..ed5fd5b8 100644 --- a/tmk_core/tool/chibios/chibios.mk +++ b/tmk_core/tool/chibios/chibios.mk @@ -206,7 +206,7 @@ CPPWARN = -Wall -Wextra -Wundef UDEFS = $(OPT_DEFS) # Define ASM defines here -UADEFS = +UADEFS = $(OPT_DEFS) # List all user directories here UINCDIR = From 7d4f3dd5a148f922007f321a0bb61a571d5bbbc9 Mon Sep 17 00:00:00 2001 From: flabbergast Date: Thu, 10 Sep 2015 10:30:49 +0100 Subject: [PATCH 08/29] Move AVR specific sleep_led.c into avr. --- tmk_core/common.mk | 2 +- tmk_core/common/{ => avr}/sleep_led.c | 0 tmk_core/tool/chibios/common.mk | 3 +-- tmk_core/tool/mbed/common.mk | 2 +- 4 files changed, 3 insertions(+), 4 deletions(-) rename tmk_core/common/{ => avr}/sleep_led.c (100%) diff --git a/tmk_core/common.mk b/tmk_core/common.mk index f5a464d0..159183a2 100644 --- a/tmk_core/common.mk +++ b/tmk_core/common.mk @@ -54,7 +54,7 @@ ifdef USB_6KRO_ENABLE endif ifdef SLEEP_LED_ENABLE - SRC += $(COMMON_DIR)/sleep_led.c + SRC += $(COMMON_DIR)/avr/sleep_led.c OPT_DEFS += -DSLEEP_LED_ENABLE OPT_DEFS += -DNO_SUSPEND_POWER_DOWN endif diff --git a/tmk_core/common/sleep_led.c b/tmk_core/common/avr/sleep_led.c similarity index 100% rename from tmk_core/common/sleep_led.c rename to tmk_core/common/avr/sleep_led.c diff --git a/tmk_core/tool/chibios/common.mk b/tmk_core/tool/chibios/common.mk index 0e9935dc..f0d39f31 100644 --- a/tmk_core/tool/chibios/common.mk +++ b/tmk_core/tool/chibios/common.mk @@ -55,8 +55,7 @@ ifdef USB_6KRO_ENABLE endif ifdef SLEEP_LED_ENABLE - $(error Sleep LED Not Supported) - SRC += $(COMMON_DIR)/sleep_led.c + SRC += $(COMMON_DIR)/chibios/sleep_led.c OPT_DEFS += -DSLEEP_LED_ENABLE OPT_DEFS += -DNO_SUSPEND_POWER_DOWN endif diff --git a/tmk_core/tool/mbed/common.mk b/tmk_core/tool/mbed/common.mk index 77bf7c3e..a0aa8717 100644 --- a/tmk_core/tool/mbed/common.mk +++ b/tmk_core/tool/mbed/common.mk @@ -63,7 +63,7 @@ endif ifdef SLEEP_LED_ENABLE $(error Not Supported) - SRC += common/sleep_led.c + SRC += common/mbed/sleep_led.c OPT_DEFS += -DSLEEP_LED_ENABLE OPT_DEFS += -DNO_SUSPEND_POWER_DOWN endif From dc9fc9a7a457d44efc45f1dce51db3c5d4bc17c9 Mon Sep 17 00:00:00 2001 From: flabbergast Date: Thu, 10 Sep 2015 10:31:19 +0100 Subject: [PATCH 09/29] Add basic sleep_led for chibios. --- tmk_core/common/chibios/printf.h | 12 ++++++------ tmk_core/common/chibios/sleep_led.c | 19 +++++++++++++++++++ tmk_core/common/chibios/timer.c | 2 +- tmk_core/protocol/chibios/README.md | 13 +++++++++---- tmk_core/protocol/chibios/main.c | 25 +++++++++++++++++++++++++ tmk_core/protocol/chibios/usb_main.c | 2 ++ tmk_core/protocol/chibios/usb_main.h | 3 +++ 7 files changed, 65 insertions(+), 11 deletions(-) create mode 100644 tmk_core/common/chibios/sleep_led.c diff --git a/tmk_core/common/chibios/printf.h b/tmk_core/common/chibios/printf.h index 00813198..678a100c 100644 --- a/tmk_core/common/chibios/printf.h +++ b/tmk_core/common/chibios/printf.h @@ -55,16 +55,16 @@ many embedded systems. To use the printf you need to supply your own character output function, something like : - void putc ( void* p, char c) - { - while (!SERIAL_PORT_EMPTY) ; - SERIAL_PORT_TX_REGISTER = c; - } + void putc ( void* p, char c) + { + while (!SERIAL_PORT_EMPTY) ; + SERIAL_PORT_TX_REGISTER = c; + } Before you can call printf you need to initialize it to use your character output function with something like: - init_printf(NULL,putc); + init_printf(NULL,putc); Notice the 'NULL' in 'init_printf' and the parameter 'void* p' in 'putc', the NULL (or any pointer) you pass into the 'init_printf' will eventually be diff --git a/tmk_core/common/chibios/sleep_led.c b/tmk_core/common/chibios/sleep_led.c new file mode 100644 index 00000000..b08c9c2a --- /dev/null +++ b/tmk_core/common/chibios/sleep_led.c @@ -0,0 +1,19 @@ +#include "ch.h" + +#include "led.h" +#include "sleep_led.h" + +void sleep_led_init(void) { +} + +void sleep_led_enable(void) { + led_set(1< Date: Thu, 10 Sep 2015 10:32:15 +0100 Subject: [PATCH 10/29] Add chibi_onekey example. --- keyboard/chibi_onekey/Makefile | 51 +++ keyboard/chibi_onekey/chconf.h | 499 +++++++++++++++++++++++++++ keyboard/chibi_onekey/config.h | 74 ++++ keyboard/chibi_onekey/halconf.h | 334 ++++++++++++++++++ keyboard/chibi_onekey/keymap_plain.c | 44 +++ keyboard/chibi_onekey/led.c | 34 ++ keyboard/chibi_onekey/matrix.c | 163 +++++++++ keyboard/chibi_onekey/mcuconf.h | 171 +++++++++ 8 files changed, 1370 insertions(+) create mode 100644 keyboard/chibi_onekey/Makefile create mode 100644 keyboard/chibi_onekey/chconf.h create mode 100644 keyboard/chibi_onekey/config.h create mode 100644 keyboard/chibi_onekey/halconf.h create mode 100644 keyboard/chibi_onekey/keymap_plain.c create mode 100644 keyboard/chibi_onekey/led.c create mode 100644 keyboard/chibi_onekey/matrix.c create mode 100644 keyboard/chibi_onekey/mcuconf.h diff --git a/keyboard/chibi_onekey/Makefile b/keyboard/chibi_onekey/Makefile new file mode 100644 index 00000000..3e8e715c --- /dev/null +++ b/keyboard/chibi_onekey/Makefile @@ -0,0 +1,51 @@ +# Target file name (without extension). +PROJECT = ch +TARGET = alps64 + +# Directory common source files exist +TMK_DIR = ../../tmk_core + +# Directory keyboard dependent files exist +TARGET_DIR = . + +# project specific files +SRC = matrix.c \ + led.c + +ifdef KEYMAP + SRC := keymap_$(KEYMAP).c $(SRC) +else + SRC := keymap_plain.c $(SRC) +endif + +CONFIG_H = config.h + +# chip/board +MCU_FAMILY = STM32 +MCU_SERIES = STM32F0xx +# linker script to use +MCU_MODEL_FAMILY = STM32F072xB +# the directory in board/ +BOARD = ST_STM32F072B_DISCOVERY +# ARM version, M0/M1 are 6, M3/M4/M7 are 7 +ARMV = 6 +# If you want to be able to jump to bootloader from firmware (on STM32 MCUs), +# set the correct BOOTLOADER_ADDRESS here. Otherwise leave commented out. +# It is chip dependent, the correct number can be looked up here (page 175): +# http://www.st.com/web/en/resource/technical/document/application_note/CD00167594.pdf +# This also requires a patch to chibios: /tmk_core/ +BOOTLOADER_ADDRESS = 0x1FFFC800 + +# Build Options +# comment out to disable the options. +# +#BOOTMAGIC_ENABLE = yes # Virtual DIP switch configuration +MOUSEKEY_ENABLE = yes # Mouse keys +EXTRAKEY_ENABLE = yes # Audio control and System control +CONSOLE_ENABLE = yes # Console for debug +COMMAND_ENABLE = yes # Commands for debug and configuration +SLEEP_LED_ENABLE = yes # Breathing sleep LED during USB suspend +#NKRO_ENABLE = yes # USB Nkey Rollover + +include $(TMK_DIR)/tool/chibios/common.mk +include $(TMK_DIR)/tool/chibios/chibios.mk diff --git a/keyboard/chibi_onekey/chconf.h b/keyboard/chibi_onekey/chconf.h new file mode 100644 index 00000000..da4160b6 --- /dev/null +++ b/keyboard/chibi_onekey/chconf.h @@ -0,0 +1,499 @@ +/* + ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +/** + * @file templates/chconf.h + * @brief Configuration file template. + * @details A copy of this file must be placed in each project directory, it + * contains the application specific kernel settings. + * + * @addtogroup config + * @details Kernel related settings and hooks. + * @{ + */ + +#ifndef _CHCONF_H_ +#define _CHCONF_H_ + +/*===========================================================================*/ +/** + * @name System timers settings + * @{ + */ +/*===========================================================================*/ + +/** + * @brief System time counter resolution. + * @note Allowed values are 16 or 32 bits. + */ +#define CH_CFG_ST_RESOLUTION 32 + +/** + * @brief System tick frequency. + * @details Frequency of the system timer that drives the system ticks. This + * setting also defines the system tick time unit. + */ +#define CH_CFG_ST_FREQUENCY 10000 + +/** + * @brief Time delta constant for the tick-less mode. + * @note If this value is zero then the system uses the classic + * periodic tick. This value represents the minimum number + * of ticks that is safe to specify in a timeout directive. + * The value one is not valid, timeouts are rounded up to + * this value. + */ +#define CH_CFG_ST_TIMEDELTA 2 + +/** @} */ + +/*===========================================================================*/ +/** + * @name Kernel parameters and options + * @{ + */ +/*===========================================================================*/ + +/** + * @brief Round robin interval. + * @details This constant is the number of system ticks allowed for the + * threads before preemption occurs. Setting this value to zero + * disables the preemption for threads with equal priority and the + * round robin becomes cooperative. Note that higher priority + * threads can still preempt, the kernel is always preemptive. + * @note Disabling the round robin preemption makes the kernel more compact + * and generally faster. + * @note The round robin preemption is not supported in tickless mode and + * must be set to zero in that case. + */ +#define CH_CFG_TIME_QUANTUM 0 + +/** + * @brief Managed RAM size. + * @details Size of the RAM area to be managed by the OS. If set to zero + * then the whole available RAM is used. The core memory is made + * available to the heap allocator and/or can be used directly through + * the simplified core memory allocator. + * + * @note In order to let the OS manage the whole RAM the linker script must + * provide the @p __heap_base__ and @p __heap_end__ symbols. + * @note Requires @p CH_CFG_USE_MEMCORE. + */ +#define CH_CFG_MEMCORE_SIZE 0 + +/** + * @brief Idle thread automatic spawn suppression. + * @details When this option is activated the function @p chSysInit() + * does not spawn the idle thread. The application @p main() + * function becomes the idle thread and must implement an + * infinite loop. + */ +#define CH_CFG_NO_IDLE_THREAD FALSE + +/** @} */ + +/*===========================================================================*/ +/** + * @name Performance options + * @{ + */ +/*===========================================================================*/ + +/** + * @brief OS optimization. + * @details If enabled then time efficient rather than space efficient code + * is used when two possible implementations exist. + * + * @note This is not related to the compiler optimization options. + * @note The default is @p TRUE. + */ +#define CH_CFG_OPTIMIZE_SPEED FALSE + +/** @} */ + +/*===========================================================================*/ +/** + * @name Subsystem options + * @{ + */ +/*===========================================================================*/ + +/** + * @brief Time Measurement APIs. + * @details If enabled then the time measurement APIs are included in + * the kernel. + * + * @note The default is @p TRUE. + */ +#define CH_CFG_USE_TM FALSE + +/** + * @brief Threads registry APIs. + * @details If enabled then the registry APIs are included in the kernel. + * + * @note The default is @p TRUE. + */ +#define CH_CFG_USE_REGISTRY TRUE + +/** + * @brief Threads synchronization APIs. + * @details If enabled then the @p chThdWait() function is included in + * the kernel. + * + * @note The default is @p TRUE. + */ +#define CH_CFG_USE_WAITEXIT TRUE + +/** + * @brief Semaphores APIs. + * @details If enabled then the Semaphores APIs are included in the kernel. + * + * @note The default is @p TRUE. + */ +#define CH_CFG_USE_SEMAPHORES TRUE + +/** + * @brief Semaphores queuing mode. + * @details If enabled then the threads are enqueued on semaphores by + * priority rather than in FIFO order. + * + * @note The default is @p FALSE. Enable this if you have special + * requirements. + * @note Requires @p CH_CFG_USE_SEMAPHORES. + */ +#define CH_CFG_USE_SEMAPHORES_PRIORITY FALSE + +/** + * @brief Mutexes APIs. + * @details If enabled then the mutexes APIs are included in the kernel. + * + * @note The default is @p TRUE. + */ +#define CH_CFG_USE_MUTEXES TRUE + +/** + * @brief Enables recursive behavior on mutexes. + * @note Recursive mutexes are heavier and have an increased + * memory footprint. + * + * @note The default is @p FALSE. + * @note Requires @p CH_CFG_USE_MUTEXES. + */ +#define CH_CFG_USE_MUTEXES_RECURSIVE FALSE + +/** + * @brief Conditional Variables APIs. + * @details If enabled then the conditional variables APIs are included + * in the kernel. + * + * @note The default is @p TRUE. + * @note Requires @p CH_CFG_USE_MUTEXES. + */ +#define CH_CFG_USE_CONDVARS TRUE + +/** + * @brief Conditional Variables APIs with timeout. + * @details If enabled then the conditional variables APIs with timeout + * specification are included in the kernel. + * + * @note The default is @p TRUE. + * @note Requires @p CH_CFG_USE_CONDVARS. + */ +#define CH_CFG_USE_CONDVARS_TIMEOUT FALSE + +/** + * @brief Events Flags APIs. + * @details If enabled then the event flags APIs are included in the kernel. + * + * @note The default is @p TRUE. + */ +#define CH_CFG_USE_EVENTS TRUE + +/** + * @brief Events Flags APIs with timeout. + * @details If enabled then the events APIs with timeout specification + * are included in the kernel. + * + * @note The default is @p TRUE. + * @note Requires @p CH_CFG_USE_EVENTS. + */ +#define CH_CFG_USE_EVENTS_TIMEOUT TRUE + +/** + * @brief Synchronous Messages APIs. + * @details If enabled then the synchronous messages APIs are included + * in the kernel. + * + * @note The default is @p TRUE. + */ +#define CH_CFG_USE_MESSAGES TRUE + +/** + * @brief Synchronous Messages queuing mode. + * @details If enabled then messages are served by priority rather than in + * FIFO order. + * + * @note The default is @p FALSE. Enable this if you have special + * requirements. + * @note Requires @p CH_CFG_USE_MESSAGES. + */ +#define CH_CFG_USE_MESSAGES_PRIORITY FALSE + +/** + * @brief Mailboxes APIs. + * @details If enabled then the asynchronous messages (mailboxes) APIs are + * included in the kernel. + * + * @note The default is @p TRUE. + * @note Requires @p CH_CFG_USE_SEMAPHORES. + */ +#define CH_CFG_USE_MAILBOXES TRUE + +/** + * @brief I/O Queues APIs. + * @details If enabled then the I/O queues APIs are included in the kernel. + * + * @note The default is @p TRUE. + */ +#define CH_CFG_USE_QUEUES TRUE + +/** + * @brief Core Memory Manager APIs. + * @details If enabled then the core memory manager APIs are included + * in the kernel. + * + * @note The default is @p TRUE. + */ +#define CH_CFG_USE_MEMCORE FALSE + +/** + * @brief Heap Allocator APIs. + * @details If enabled then the memory heap allocator APIs are included + * in the kernel. + * + * @note The default is @p TRUE. + * @note Requires @p CH_CFG_USE_MEMCORE and either @p CH_CFG_USE_MUTEXES or + * @p CH_CFG_USE_SEMAPHORES. + * @note Mutexes are recommended. + */ +#define CH_CFG_USE_HEAP FALSE + +/** + * @brief Memory Pools Allocator APIs. + * @details If enabled then the memory pools allocator APIs are included + * in the kernel. + * + * @note The default is @p TRUE. + */ +#define CH_CFG_USE_MEMPOOLS FALSE + +/** + * @brief Dynamic Threads APIs. + * @details If enabled then the dynamic threads creation APIs are included + * in the kernel. + * + * @note The default is @p TRUE. + * @note Requires @p CH_CFG_USE_WAITEXIT. + * @note Requires @p CH_CFG_USE_HEAP and/or @p CH_CFG_USE_MEMPOOLS. + */ +#define CH_CFG_USE_DYNAMIC FALSE + +/** @} */ + +/*===========================================================================*/ +/** + * @name Debug options + * @{ + */ +/*===========================================================================*/ + +/** + * @brief Debug option, kernel statistics. + * + * @note The default is @p FALSE. + */ +#define CH_DBG_STATISTICS FALSE + +/** + * @brief Debug option, system state check. + * @details If enabled the correct call protocol for system APIs is checked + * at runtime. + * + * @note The default is @p FALSE. + */ +#define CH_DBG_SYSTEM_STATE_CHECK FALSE + +/** + * @brief Debug option, parameters checks. + * @details If enabled then the checks on the API functions input + * parameters are activated. + * + * @note The default is @p FALSE. + */ +#define CH_DBG_ENABLE_CHECKS FALSE + +/** + * @brief Debug option, consistency checks. + * @details If enabled then all the assertions in the kernel code are + * activated. This includes consistency checks inside the kernel, + * runtime anomalies and port-defined checks. + * + * @note The default is @p FALSE. + */ +#define CH_DBG_ENABLE_ASSERTS FALSE + +/** + * @brief Debug option, trace buffer. + * @details If enabled then the context switch circular trace buffer is + * activated. + * + * @note The default is @p FALSE. + */ +#define CH_DBG_ENABLE_TRACE FALSE + +/** + * @brief Debug option, stack checks. + * @details If enabled then a runtime stack check is performed. + * + * @note The default is @p FALSE. + * @note The stack check is performed in a architecture/port dependent way. + * It may not be implemented or some ports. + * @note The default failure mode is to halt the system with the global + * @p panic_msg variable set to @p NULL. + */ +#define CH_DBG_ENABLE_STACK_CHECK FALSE + +/** + * @brief Debug option, stacks initialization. + * @details If enabled then the threads working area is filled with a byte + * value when a thread is created. This can be useful for the + * runtime measurement of the used stack. + * + * @note The default is @p FALSE. + */ +#define CH_DBG_FILL_THREADS FALSE + +/** + * @brief Debug option, threads profiling. + * @details If enabled then a field is added to the @p thread_t structure that + * counts the system ticks occurred while executing the thread. + * + * @note The default is @p FALSE. + * @note This debug option is not currently compatible with the + * tickless mode. + */ +#define CH_DBG_THREADS_PROFILING FALSE + +/** @} */ + +/*===========================================================================*/ +/** + * @name Kernel hooks + * @{ + */ +/*===========================================================================*/ + +/** + * @brief Threads descriptor structure extension. + * @details User fields added to the end of the @p thread_t structure. + */ +#define CH_CFG_THREAD_EXTRA_FIELDS \ + /* Add threads custom fields here.*/ + +/** + * @brief Threads initialization hook. + * @details User initialization code added to the @p chThdInit() API. + * + * @note It is invoked from within @p chThdInit() and implicitly from all + * the threads creation APIs. + */ +#define CH_CFG_THREAD_INIT_HOOK(tp) { \ + /* Add threads initialization code here.*/ \ +} + +/** + * @brief Threads finalization hook. + * @details User finalization code added to the @p chThdExit() API. + * + * @note It is inserted into lock zone. + * @note It is also invoked when the threads simply return in order to + * terminate. + */ +#define CH_CFG_THREAD_EXIT_HOOK(tp) { \ + /* Add threads finalization code here.*/ \ +} + +/** + * @brief Context switch hook. + * @details This hook is invoked just before switching between threads. + */ +#define CH_CFG_CONTEXT_SWITCH_HOOK(ntp, otp) { \ + /* Context switch code here.*/ \ +} + +/** + * @brief Idle thread enter hook. + * @note This hook is invoked within a critical zone, no OS functions + * should be invoked from here. + * @note This macro can be used to activate a power saving mode. + */ +#define CH_CFG_IDLE_ENTER_HOOK() { \ +} + +/** + * @brief Idle thread leave hook. + * @note This hook is invoked within a critical zone, no OS functions + * should be invoked from here. + * @note This macro can be used to deactivate a power saving mode. + */ +#define CH_CFG_IDLE_LEAVE_HOOK() { \ +} + +/** + * @brief Idle Loop hook. + * @details This hook is continuously invoked by the idle thread loop. + */ +#define CH_CFG_IDLE_LOOP_HOOK() { \ + /* Idle loop code here.*/ \ +} + +/** + * @brief System tick event hook. + * @details This hook is invoked in the system tick handler immediately + * after processing the virtual timers queue. + */ +#define CH_CFG_SYSTEM_TICK_HOOK() { \ + /* System tick event code here.*/ \ +} + +/** + * @brief System halt hook. + * @details This hook is invoked in case to a system halting error before + * the system is halted. + */ +#define CH_CFG_SYSTEM_HALT_HOOK(reason) { \ + /* System halt code here.*/ \ +} + +/** @} */ + +/*===========================================================================*/ +/* Port-specific settings (override port settings defaulted in chcore.h). */ +/*===========================================================================*/ + +#endif /* _CHCONF_H_ */ + +/** @} */ diff --git a/keyboard/chibi_onekey/config.h b/keyboard/chibi_onekey/config.h new file mode 100644 index 00000000..8063c57e --- /dev/null +++ b/keyboard/chibi_onekey/config.h @@ -0,0 +1,74 @@ +/* +Copyright 2015 Jun Wako + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#ifndef CONFIG_H +#define CONFIG_H + + +/* USB Device descriptor parameter */ +#define VENDOR_ID 0xFEED +#define PRODUCT_ID 0x6464 +#define DEVICE_VER 0x0001 +/* in python2: list(u"whatever".encode('utf-16-le')) */ +/* at most 32 characters or the ugly hack in usb_main.c borks */ +#define MANUFACTURER "TMK" +#define USBSTR_MANUFACTURER 'T', '\x00', 'M', '\x00', 'K', '\x00', ' ', '\x00', '\xc6', '\x00' +#define PRODUCT "ChibiOS TMK test" +#define USBSTR_PRODUCT 'C', '\x00', 'h', '\x00', 'i', '\x00', 'b', '\x00', 'i', '\x00', 'O', '\x00', 'S', '\x00', ' ', '\x00', 'T', '\x00', 'M', '\x00', 'K', '\x00', ' ', '\x00', 't', '\x00', 'e', '\x00', 's', '\x00', 't', '\x00' +#define DESCRIPTION "TMK keyboard firmware over ChibiOS" + +/* key matrix size */ +#define MATRIX_ROWS 1 +#define MATRIX_COLS 1 + +/* define if matrix has ghost */ +//#define MATRIX_HAS_GHOST + +/* Set 0 if debouncing isn't needed */ +#define DEBOUNCE 5 + +/* Mechanical locking support. Use KC_LCAP, KC_LNUM or KC_LSCR instead in keymap */ +#define LOCKING_SUPPORT_ENABLE +/* Locking resynchronize hack */ +#define LOCKING_RESYNC_ENABLE + +/* key combination for command */ +#define IS_COMMAND() ( \ + keyboard_report->mods == (MOD_BIT(KC_LSHIFT) | MOD_BIT(KC_RSHIFT)) \ +) + + + +/* + * Feature disable options + * These options are also useful to firmware size reduction. + */ + +/* disable debug print */ +//#define NO_DEBUG + +/* disable print */ +//#define NO_PRINT + +/* disable action features */ +//#define NO_ACTION_LAYER +//#define NO_ACTION_TAPPING +//#define NO_ACTION_ONESHOT +//#define NO_ACTION_MACRO +//#define NO_ACTION_FUNCTION + +#endif diff --git a/keyboard/chibi_onekey/halconf.h b/keyboard/chibi_onekey/halconf.h new file mode 100644 index 00000000..d3415c55 --- /dev/null +++ b/keyboard/chibi_onekey/halconf.h @@ -0,0 +1,334 @@ +/* + ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +/** + * @file templates/halconf.h + * @brief HAL configuration header. + * @details HAL configuration file, this file allows to enable or disable the + * various device drivers from your application. You may also use + * this file in order to override the device drivers default settings. + * + * @addtogroup HAL_CONF + * @{ + */ + +#ifndef _HALCONF_H_ +#define _HALCONF_H_ + +#include "mcuconf.h" + +/** + * @brief Enables the PAL subsystem. + */ +#if !defined(HAL_USE_PAL) || defined(__DOXYGEN__) +#define HAL_USE_PAL TRUE +#endif + +/** + * @brief Enables the ADC subsystem. + */ +#if !defined(HAL_USE_ADC) || defined(__DOXYGEN__) +#define HAL_USE_ADC FALSE +#endif + +/** + * @brief Enables the CAN subsystem. + */ +#if !defined(HAL_USE_CAN) || defined(__DOXYGEN__) +#define HAL_USE_CAN FALSE +#endif + +/** + * @brief Enables the DAC subsystem. + */ +#if !defined(HAL_USE_DAC) || defined(__DOXYGEN__) +#define HAL_USE_DAC FALSE +#endif + +/** + * @brief Enables the EXT subsystem. + */ +#if !defined(HAL_USE_EXT) || defined(__DOXYGEN__) +#define HAL_USE_EXT FALSE +#endif + +/** + * @brief Enables the GPT subsystem. + */ +#if !defined(HAL_USE_GPT) || defined(__DOXYGEN__) +#define HAL_USE_GPT FALSE +#endif + +/** + * @brief Enables the I2C subsystem. + */ +#if !defined(HAL_USE_I2C) || defined(__DOXYGEN__) +#define HAL_USE_I2C FALSE +#endif + +/** + * @brief Enables the I2S subsystem. + */ +#if !defined(HAL_USE_I2S) || defined(__DOXYGEN__) +#define HAL_USE_I2S FALSE +#endif + +/** + * @brief Enables the ICU subsystem. + */ +#if !defined(HAL_USE_ICU) || defined(__DOXYGEN__) +#define HAL_USE_ICU FALSE +#endif + +/** + * @brief Enables the MAC subsystem. + */ +#if !defined(HAL_USE_MAC) || defined(__DOXYGEN__) +#define HAL_USE_MAC FALSE +#endif + +/** + * @brief Enables the MMC_SPI subsystem. + */ +#if !defined(HAL_USE_MMC_SPI) || defined(__DOXYGEN__) +#define HAL_USE_MMC_SPI FALSE +#endif + +/** + * @brief Enables the PWM subsystem. + */ +#if !defined(HAL_USE_PWM) || defined(__DOXYGEN__) +#define HAL_USE_PWM FALSE +#endif + +/** + * @brief Enables the RTC subsystem. + */ +#if !defined(HAL_USE_RTC) || defined(__DOXYGEN__) +#define HAL_USE_RTC FALSE +#endif + +/** + * @brief Enables the SDC subsystem. + */ +#if !defined(HAL_USE_SDC) || defined(__DOXYGEN__) +#define HAL_USE_SDC FALSE +#endif + +/** + * @brief Enables the SERIAL subsystem. + */ +#if !defined(HAL_USE_SERIAL) || defined(__DOXYGEN__) +#define HAL_USE_SERIAL FALSE +#endif + +/** + * @brief Enables the SERIAL over USB subsystem. + */ +#if !defined(HAL_USE_SERIAL_USB) || defined(__DOXYGEN__) +#define HAL_USE_SERIAL_USB FALSE +#endif + +/** + * @brief Enables the SPI subsystem. + */ +#if !defined(HAL_USE_SPI) || defined(__DOXYGEN__) +#define HAL_USE_SPI FALSE +#endif + +/** + * @brief Enables the UART subsystem. + */ +#if !defined(HAL_USE_UART) || defined(__DOXYGEN__) +#define HAL_USE_UART FALSE +#endif + +/** + * @brief Enables the USB subsystem. + */ +#if !defined(HAL_USE_USB) || defined(__DOXYGEN__) +#define HAL_USE_USB TRUE +#endif + +/*===========================================================================*/ +/* ADC driver related settings. */ +/*===========================================================================*/ + +/** + * @brief Enables synchronous APIs. + * @note Disabling this option saves both code and data space. + */ +#if !defined(ADC_USE_WAIT) || defined(__DOXYGEN__) +#define ADC_USE_WAIT TRUE +#endif + +/** + * @brief Enables the @p adcAcquireBus() and @p adcReleaseBus() APIs. + * @note Disabling this option saves both code and data space. + */ +#if !defined(ADC_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__) +#define ADC_USE_MUTUAL_EXCLUSION TRUE +#endif + +/*===========================================================================*/ +/* CAN driver related settings. */ +/*===========================================================================*/ + +/** + * @brief Sleep mode related APIs inclusion switch. + */ +#if !defined(CAN_USE_SLEEP_MODE) || defined(__DOXYGEN__) +#define CAN_USE_SLEEP_MODE TRUE +#endif + +/*===========================================================================*/ +/* I2C driver related settings. */ +/*===========================================================================*/ + +/** + * @brief Enables the mutual exclusion APIs on the I2C bus. + */ +#if !defined(I2C_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__) +#define I2C_USE_MUTUAL_EXCLUSION TRUE +#endif + +/*===========================================================================*/ +/* MAC driver related settings. */ +/*===========================================================================*/ + +/** + * @brief Enables an event sources for incoming packets. + */ +#if !defined(MAC_USE_ZERO_COPY) || defined(__DOXYGEN__) +#define MAC_USE_ZERO_COPY FALSE +#endif + +/** + * @brief Enables an event sources for incoming packets. + */ +#if !defined(MAC_USE_EVENTS) || defined(__DOXYGEN__) +#define MAC_USE_EVENTS TRUE +#endif + +/*===========================================================================*/ +/* MMC_SPI driver related settings. */ +/*===========================================================================*/ + +/** + * @brief Delays insertions. + * @details If enabled this options inserts delays into the MMC waiting + * routines releasing some extra CPU time for the threads with + * lower priority, this may slow down the driver a bit however. + * This option is recommended also if the SPI driver does not + * use a DMA channel and heavily loads the CPU. + */ +#if !defined(MMC_NICE_WAITING) || defined(__DOXYGEN__) +#define MMC_NICE_WAITING TRUE +#endif + +/*===========================================================================*/ +/* SDC driver related settings. */ +/*===========================================================================*/ + +/** + * @brief Number of initialization attempts before rejecting the card. + * @note Attempts are performed at 10mS intervals. + */ +#if !defined(SDC_INIT_RETRY) || defined(__DOXYGEN__) +#define SDC_INIT_RETRY 100 +#endif + +/** + * @brief Include support for MMC cards. + * @note MMC support is not yet implemented so this option must be kept + * at @p FALSE. + */ +#if !defined(SDC_MMC_SUPPORT) || defined(__DOXYGEN__) +#define SDC_MMC_SUPPORT FALSE +#endif + +/** + * @brief Delays insertions. + * @details If enabled this options inserts delays into the MMC waiting + * routines releasing some extra CPU time for the threads with + * lower priority, this may slow down the driver a bit however. + */ +#if !defined(SDC_NICE_WAITING) || defined(__DOXYGEN__) +#define SDC_NICE_WAITING TRUE +#endif + +/*===========================================================================*/ +/* SERIAL driver related settings. */ +/*===========================================================================*/ + +/** + * @brief Default bit rate. + * @details Configuration parameter, this is the baud rate selected for the + * default configuration. + */ +#if !defined(SERIAL_DEFAULT_BITRATE) || defined(__DOXYGEN__) +#define SERIAL_DEFAULT_BITRATE 38400 +#endif + +/** + * @brief Serial buffers size. + * @details Configuration parameter, you can change the depth of the queue + * buffers depending on the requirements of your application. + * @note The default is 64 bytes for both the transmission and receive + * buffers. + */ +#if !defined(SERIAL_BUFFERS_SIZE) || defined(__DOXYGEN__) +#define SERIAL_BUFFERS_SIZE 16 +#endif + +/*===========================================================================*/ +/* SERIAL_USB driver related setting. */ +/*===========================================================================*/ + +/** + * @brief Serial over USB buffers size. + * @details Configuration parameter, the buffer size must be a multiple of + * the USB data endpoint maximum packet size. + * @note The default is 64 bytes for both the transmission and receive + * buffers. + */ +#if !defined(SERIAL_USB_BUFFERS_SIZE) || defined(__DOXYGEN__) +#define SERIAL_USB_BUFFERS_SIZE 256 +#endif + +/*===========================================================================*/ +/* SPI driver related settings. */ +/*===========================================================================*/ + +/** + * @brief Enables synchronous APIs. + * @note Disabling this option saves both code and data space. + */ +#if !defined(SPI_USE_WAIT) || defined(__DOXYGEN__) +#define SPI_USE_WAIT TRUE +#endif + +/** + * @brief Enables the @p spiAcquireBus() and @p spiReleaseBus() APIs. + * @note Disabling this option saves both code and data space. + */ +#if !defined(SPI_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__) +#define SPI_USE_MUTUAL_EXCLUSION TRUE +#endif + +#endif /* _HALCONF_H_ */ + +/** @} */ diff --git a/keyboard/chibi_onekey/keymap_plain.c b/keyboard/chibi_onekey/keymap_plain.c new file mode 100644 index 00000000..ea173935 --- /dev/null +++ b/keyboard/chibi_onekey/keymap_plain.c @@ -0,0 +1,44 @@ +/* +Copyright 2012,2013 Jun Wako + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#include "keycode.h" +#include "action.h" +#include "action_macro.h" +#include "report.h" +#include "host.h" +#include "print.h" +#include "debug.h" +#include "keymap.h" + +static const uint8_t keymaps[][MATRIX_ROWS][MATRIX_COLS] = { + {{KC_A}}, +}; + +static const uint16_t fn_actions[] = { +}; + +/* translates key to keycode */ +uint8_t keymap_key_to_keycode(uint8_t layer, keypos_t key) +{ + return keymaps[(layer)][(key.row)][(key.col)]; +} + +/* translates Fn keycode to action */ +action_t keymap_fn_to_action(uint8_t keycode) +{ + return (action_t){ .code = fn_actions[FN_INDEX(keycode)] }; +} diff --git a/keyboard/chibi_onekey/led.c b/keyboard/chibi_onekey/led.c new file mode 100644 index 00000000..18edb8ba --- /dev/null +++ b/keyboard/chibi_onekey/led.c @@ -0,0 +1,34 @@ +/* +Copyright 2012 Jun Wako + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#include "hal.h" + +#include "led.h" + + +void led_set(uint8_t usb_led) +{ + (void)usb_led; + if (usb_led & (1< + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#include "ch.h" +#include "hal.h" + +/* + * scan matrix + */ +#include "print.h" +#include "debug.h" +#include "util.h" +#include "matrix.h" +#include "wait.h" + +#ifndef DEBOUNCE +# define DEBOUNCE 5 +#endif +static uint8_t debouncing = DEBOUNCE; + +/* matrix state(1:on, 0:off) */ +static matrix_row_t matrix[MATRIX_ROWS]; +static matrix_row_t matrix_debouncing[MATRIX_ROWS]; + +static matrix_row_t read_cols(void); +static void init_cols(void); +static void unselect_rows(void); +static void select_row(uint8_t row); + + +inline +uint8_t matrix_rows(void) +{ + return MATRIX_ROWS; +} + +inline +uint8_t matrix_cols(void) +{ + return MATRIX_COLS; +} + +#define LED_ON() do { palSetPad(GPIOC, GPIOC_LED_BLUE) ;} while (0) +#define LED_OFF() do { palClearPad(GPIOC, GPIOC_LED_BLUE); } while (0) +#define LED_TGL() do { palTogglePad(GPIOC, GPIOC_LED_BLUE); } while (0) + +void matrix_init(void) +{ + // initialize row and col + unselect_rows(); + init_cols(); + + // initialize matrix state: all keys off + for (uint8_t i=0; i < MATRIX_ROWS; i++) { + matrix[i] = 0; + matrix_debouncing[i] = 0; + } + + //debug + debug_matrix = true; + LED_ON(); + wait_ms(500); + LED_OFF(); +} + +uint8_t matrix_scan(void) +{ + for (uint8_t i = 0; i < MATRIX_ROWS; i++) { + select_row(i); + wait_us(30); // without this wait read unstable value. + matrix_row_t cols = read_cols(); + if (matrix_debouncing[i] != cols) { + matrix_debouncing[i] = cols; + if (debouncing) { + debug("bounce!: "); debug_hex(debouncing); debug("\n"); + } + debouncing = DEBOUNCE; + } + unselect_rows(); + } + + if (debouncing) { + if (--debouncing) { + wait_ms(1); + } else { + for (uint8_t i = 0; i < MATRIX_ROWS; i++) { + matrix[i] = matrix_debouncing[i]; + } + } + } + + return 1; +} + +inline +bool matrix_is_on(uint8_t row, uint8_t col) +{ + return (matrix[row] & ((matrix_row_t)1< Date: Thu, 10 Sep 2015 10:49:47 +0100 Subject: [PATCH 11/29] Update chibios README. --- tmk_core/protocol/chibios/README.md | 31 +++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/tmk_core/protocol/chibios/README.md b/tmk_core/protocol/chibios/README.md index 5df4c6e7..06569c51 100644 --- a/tmk_core/protocol/chibios/README.md +++ b/tmk_core/protocol/chibios/README.md @@ -1,12 +1,12 @@ -## USB stack implementation using ChibiOS +## TMK running on top of ChibiOS ### Notes -- To use, unpack or symlink ChibiOS here, to `chibios`. -- For gcc options, inspect `chibios.mk`. For instance, I enabled `-Wno-missing-field-initializers`, because TMK common bits generated a lot of hits on that. +- To use, unpack or symlink [ChibiOS] {currently 3.0.1} to `tmk_core/tool/chibios/chibios`. +- For gcc options, inspect `tmk_core/tool/chibios/chibios.mk`. For instance, I enabled `-Wno-missing-field-initializers`, because TMK common bits generated a lot of warnings on that. Also pay attention to `-O0` (enabled for debugging); for deployment use `-O2`. -- USB string descriptors are a mess. I did not find a way to cleanly generate the right structures from actual strings, so the definitions in individual keyboards' `config.h` are ugly as heck. -- There are some random constants left so far, e.g. 5ms sleep between calling `keyboard_task` in `main.c`. There should be no such in `usb_main.c`. Everything is based on timers/interrupts/kernel scheduling (well except `keyboard_task`), so no periodically called things (again, except `keyboard_task`, which is just how TMK is designed). +- USB string descriptors are messy. I did not find a way to cleanly generate the right structures from actual strings, so the definitions in individual keyboards' `config.h` are ugly as heck. +- There are some random constants left so far, e.g. 5ms sleep between calling `keyboard_task`, or 1.5sec wait for USB init, in `main.c`. There should be no such in `usb_main.c` (the main USB stack). Everything is based on timers/interrupts/kernel scheduling (well except `keyboard_task`), so no periodically called things (again, except `keyboard_task`, which is just how TMK is designed). - It is easy to add some code for testing (e.g. blink LED, do stuff on button press, etc...) - just create another thread in `main.c`, it will run independently of the keyboard business. - Jumping to bootloader works, but it is not entirely pleasant, since it is very much MCU dependent. The code is now geared towards STM32 chips and their built-in bootloaders. So, one needs to dig out the right address to jump to, and pass it to the compiler in the `Makefile`. Also, a patch to upstream ChibiOS is needed (supplied), because it `ResetHandler` needs adjusting. - Sleep LED works, but at the moment only on/off, i.e. no breathing. @@ -14,6 +14,7 @@ Also pay attention to `-O0` (enabled for debugging); for deployment use `-O2`. ### Immediate todo +- host-wakeup packet sending during suspend - power saving for suspend? - PWM for sleep led @@ -23,9 +24,27 @@ Also pay attention to `-O0` (enabled for debugging); for deployment use `-O2`. ### Missing / not working (TMK vs ChibiOS bits) -- eeprom / bootmagic (will be chip dependent; eeprom needs to be emulated in flash, which means less writes; wear-levelling?) +- eeprom / bootmagic (will be chip dependent; eeprom needs to be emulated in flash, which means less writes; wear-levelling?) There is a semi-official ST "driver" for eeprom, with wear-levelling, but I think it consumes a lot of RAM (like 2 pages, i.e. 1kB or so). ### Tried with - ChibiOS 3.0.1 and ST F072RB DISCOVERY board. - Need to test on other STM32 chips (F3, F4) to make it as much chip-independent as possible. + +## STM32-based keyboard design considerations + +- STM32F0x2 chips can do crystal-less USB, but they still need a 3.3V voltage regulator. +- The BOOT0 pin should be tied to GND. +- For a hardware way of accessing the in-built DFU bootloader, in addition to the reset button, put another button between the BOOT0 pin and 3V3. +- For breathing the caps lock LED during the suspended state ("sleep LED"), it is desirable to have that LED on a hardware PWM pin (there's usually plenty of those, look for TIMERs in the datasheet). + +## ChibiOS-supported MCUs (as of 3.0.1) + +- Pretty much all STM32 chips. +- There is also support for AVR8, but the USB stack is not implemented for them yet, and also the kernel itself takes about 1k of RAM. I think people managed to get ChibiOS running on atmega32[8p/u4] though. +- There is some support for K20 and KL25 Freescale chips (i.e. Teensy 3.0, mchck, FRDM-KL25Z, FRDM-K20D50M), but again, no USB stack yet. +- I've seen community support for Nordic NRF51822 (the chip in Adafruit's Bluefruit bluetooth-low-energy boards), but not sure about the extent. + + + +[ChibiOS]: http://chibios.org From a24ddf3403670724b798d18e1d39bc3f0751aecf Mon Sep 17 00:00:00 2001 From: flabbergast Date: Thu, 10 Sep 2015 12:48:44 +0100 Subject: [PATCH 12/29] NKRO fixes. --- tmk_core/common/report.h | 5 ++++ tmk_core/protocol/chibios/main.c | 23 ++++++++++----- tmk_core/protocol/chibios/usb_main.c | 42 ++++++++++++++-------------- tmk_core/protocol/chibios/usb_main.h | 31 +++++++------------- 4 files changed, 52 insertions(+), 49 deletions(-) diff --git a/tmk_core/common/report.h b/tmk_core/common/report.h index f6c0a315..0c799eca 100644 --- a/tmk_core/common/report.h +++ b/tmk_core/common/report.h @@ -84,6 +84,11 @@ along with this program. If not, see . # define KEYBOARD_REPORT_SIZE NKRO_EPSIZE # define KEYBOARD_REPORT_KEYS (NKRO_EPSIZE - 2) # define KEYBOARD_REPORT_BITS (NKRO_EPSIZE - 1) +#elif defined(PROTOCOL_CHIBIOS) && defined(NKRO_ENABLE) +# include "protocol/chibios/usb_main.h" +# define KEYBOARD_REPORT_SIZE NKRO_EPSIZE +# define KEYBOARD_REPORT_KEYS (NKRO_EPSIZE - 2) +# define KEYBOARD_REPORT_BITS (NKRO_EPSIZE - 1) #else # define KEYBOARD_REPORT_SIZE 8 diff --git a/tmk_core/protocol/chibios/main.c b/tmk_core/protocol/chibios/main.c index 7aec7e3e..589675aa 100644 --- a/tmk_core/protocol/chibios/main.c +++ b/tmk_core/protocol/chibios/main.c @@ -40,6 +40,14 @@ * ------------------------- */ +/* declarations */ +uint8_t keyboard_leds(void); +void send_keyboard(report_keyboard_t *report); +void send_mouse(report_mouse_t *report); +void send_system(uint16_t data); +void send_consumer(uint16_t data); + +/* host struct */ host_driver_t chibios_driver = { keyboard_leds, send_keyboard, @@ -52,14 +60,15 @@ host_driver_t chibios_driver = { /* TESTING * Amber LED blinker thread, times are in milliseconds. */ -// uint8_t blinkLedState = 0; -// static THD_WORKING_AREA(waThread1, 128); -// static THD_FUNCTION(Thread1, arg) { +/* set this variable to non-zero anywhere to blink once */ +// uint8_t blinkLed = 0; +// static THD_WORKING_AREA(waBlinkerThread, 128); +// static THD_FUNCTION(blinkerThread, arg) { // (void)arg; -// chRegSetThreadName("blinker1"); +// chRegSetThreadName("blinkOrange"); // while(true) { -// if(blinkLedState) { -// blinkLedState = 0; +// if(blinkLed) { +// blinkLed = 0; // palSetPad(GPIOC, GPIOC_LED_ORANGE); // chThdSleepMilliseconds(100); // palClearPad(GPIOC, GPIOC_LED_ORANGE); @@ -82,7 +91,7 @@ int main(void) { palClearPad(GPIOC, GPIOC_LED_BLUE); // TESTING - // chThdCreateStatic(waThread1, sizeof(waThread1), NORMALPRIO, Thread1, NULL); + // chThdCreateStatic(waBlinkerThread, sizeof(waBlinkerThread), NORMALPRIO, blinkerThread, NULL); /* Init USB */ init_usb_driver(&USB_DRIVER); diff --git a/tmk_core/protocol/chibios/usb_main.c b/tmk_core/protocol/chibios/usb_main.c index daefc490..f5f2dad7 100644 --- a/tmk_core/protocol/chibios/usb_main.c +++ b/tmk_core/protocol/chibios/usb_main.c @@ -20,11 +20,11 @@ #include "usb_main.h" +#include "host.h" #include "debug.h" #ifdef SLEEP_LED_ENABLE #include "sleep_led.h" #include "led.h" -#include "host.h" #endif /* --------------------------------------------------------- @@ -39,7 +39,7 @@ volatile uint16_t keyboard_idle_count = 0; static virtual_timer_t keyboard_idle_timer; static void keyboard_idle_timer_cb(void *arg); #ifdef NKRO_ENABLE -bool keyboard_nkro = true; +extern bool keyboard_nkro; #endif /* NKRO_ENABLE */ report_keyboard_t keyboard_report_sent = {{0}}; @@ -250,7 +250,7 @@ static const uint8_t console_hid_report_desc_data[] = { 0x75, 0x08, // report size = 8 bits 0x15, 0x00, // logical minimum = 0 0x26, 0xFF, 0x00, // logical maximum = 255 - 0x95, CONSOLE_SIZE, // report count + 0x95, CONSOLE_EPSIZE, // report count 0x09, 0x75, // usage 0x81, 0x02, // Input (array) 0xC0 // end collection @@ -374,7 +374,7 @@ static const uint8_t hid_configuration_descriptor_data[] = { /* Endpoint Descriptor (7 bytes) USB spec 9.6.6, page 269-271, Table 9-13 */ USB_DESC_ENDPOINT(KBD_ENDPOINT | 0x80, // bEndpointAddress 0x03, // bmAttributes (Interrupt) - KBD_SIZE, // wMaxPacketSize + KBD_EPSIZE,// wMaxPacketSize 10), // bInterval #ifdef MOUSE_ENABLE @@ -404,7 +404,7 @@ static const uint8_t hid_configuration_descriptor_data[] = { /* Endpoint Descriptor (7 bytes) USB spec 9.6.6, page 269-271, Table 9-13 */ USB_DESC_ENDPOINT(MOUSE_ENDPOINT | 0x80, // bEndpointAddress 0x03, // bmAttributes (Interrupt) - MOUSE_SIZE, // wMaxPacketSize + MOUSE_EPSIZE, // wMaxPacketSize 1), // bInterval #endif /* MOUSE_ENABLE */ @@ -430,7 +430,7 @@ static const uint8_t hid_configuration_descriptor_data[] = { /* Endpoint Descriptor (7 bytes) USB spec 9.6.6, page 269-271, Table 9-13 */ USB_DESC_ENDPOINT(CONSOLE_ENDPOINT | 0x80, // bEndpointAddress 0x03, // bmAttributes (Interrupt) - CONSOLE_SIZE, // wMaxPacketSize + CONSOLE_EPSIZE, // wMaxPacketSize 1), // bInterval #endif /* CONSOLE_ENABLE */ @@ -456,7 +456,7 @@ static const uint8_t hid_configuration_descriptor_data[] = { /* Endpoint Descriptor (7 bytes) USB spec 9.6.6, page 269-271, Table 9-13 */ USB_DESC_ENDPOINT(EXTRA_ENDPOINT | 0x80, // bEndpointAddress 0x03, // bmAttributes (Interrupt) - EXTRA_SIZE, // wMaxPacketSize + EXTRA_EPSIZE, // wMaxPacketSize 10), // bInterval #endif /* EXTRAKEY_ENABLE */ @@ -482,7 +482,7 @@ static const uint8_t hid_configuration_descriptor_data[] = { /* Endpoint Descriptor (7 bytes) USB spec 9.6.6, page 269-271, Table 9-13 */ USB_DESC_ENDPOINT(NKRO_ENDPOINT | 0x80, // bEndpointAddress 0x03, // bmAttributes (Interrupt) - NKRO_SIZE, // wMaxPacketSize + NKRO_EPSIZE, // wMaxPacketSize 1), // bInterval #endif /* NKRO_ENABLE */ }; @@ -665,7 +665,7 @@ static const USBEndpointConfig kbd_ep_config = { NULL, /* SETUP packet notification callback */ kbd_in_cb, /* IN notification callback */ NULL, /* OUT notification callback */ - KBD_SIZE, /* IN maximum packet size */ + KBD_EPSIZE, /* IN maximum packet size */ 0, /* OUT maximum packet size */ &kbd_ep_state, /* IN Endpoint state */ NULL, /* OUT endpoint state */ @@ -683,7 +683,7 @@ static const USBEndpointConfig mouse_ep_config = { NULL, /* SETUP packet notification callback */ mouse_in_cb, /* IN notification callback */ NULL, /* OUT notification callback */ - MOUSE_SIZE, /* IN maximum packet size */ + MOUSE_EPSIZE, /* IN maximum packet size */ 0, /* OUT maximum packet size */ &mouse_ep_state, /* IN Endpoint state */ NULL, /* OUT endpoint state */ @@ -702,7 +702,7 @@ static const USBEndpointConfig console_ep_config = { NULL, /* SETUP packet notification callback */ console_in_cb, /* IN notification callback */ NULL, /* OUT notification callback */ - CONSOLE_SIZE, /* IN maximum packet size */ + CONSOLE_EPSIZE, /* IN maximum packet size */ 0, /* OUT maximum packet size */ &console_ep_state, /* IN Endpoint state */ NULL, /* OUT endpoint state */ @@ -721,7 +721,7 @@ static const USBEndpointConfig extra_ep_config = { NULL, /* SETUP packet notification callback */ extra_in_cb, /* IN notification callback */ NULL, /* OUT notification callback */ - EXTRA_SIZE, /* IN maximum packet size */ + EXTRA_EPSIZE, /* IN maximum packet size */ 0, /* OUT maximum packet size */ &extra_ep_state, /* IN Endpoint state */ NULL, /* OUT endpoint state */ @@ -740,7 +740,7 @@ static const USBEndpointConfig nkro_ep_config = { NULL, /* SETUP packet notification callback */ nkro_in_cb, /* IN notification callback */ NULL, /* OUT notification callback */ - NKRO_SIZE, /* IN maximum packet size */ + NKRO_EPSIZE, /* IN maximum packet size */ 0, /* OUT maximum packet size */ &nkro_ep_state, /* IN Endpoint state */ NULL, /* OUT endpoint state */ @@ -1178,9 +1178,9 @@ void console_in_cb(USBDriver *usbp, usbep_t ep) { chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, (void *)usbp); /* Check if there is data to send left in the output queue */ - if(chOQGetFullI(&console_queue) >= CONSOLE_SIZE) { + if(chOQGetFullI(&console_queue) >= CONSOLE_EPSIZE) { osalSysUnlockFromISR(); - usbPrepareQueuedTransmit(usbp, CONSOLE_ENDPOINT, &console_queue, CONSOLE_SIZE); + usbPrepareQueuedTransmit(usbp, CONSOLE_ENDPOINT, &console_queue, CONSOLE_EPSIZE); osalSysLockFromISR(); usbStartTransmitI(usbp, CONSOLE_ENDPOINT); } @@ -1197,9 +1197,9 @@ void console_queue_onotify(io_queue_t *qp) { return; if(!usbGetTransmitStatusI(usbp, CONSOLE_ENDPOINT) - && (chOQGetFullI(&console_queue) >= CONSOLE_SIZE)) { + && (chOQGetFullI(&console_queue) >= CONSOLE_EPSIZE)) { osalSysUnlock(); - usbPrepareQueuedTransmit(usbp, CONSOLE_ENDPOINT, &console_queue, CONSOLE_SIZE); + usbPrepareQueuedTransmit(usbp, CONSOLE_ENDPOINT, &console_queue, CONSOLE_EPSIZE); osalSysLock(); usbStartTransmitI(usbp, CONSOLE_ENDPOINT); } @@ -1210,7 +1210,7 @@ void console_queue_onotify(io_queue_t *qp) { static void console_flush_cb(void *arg) { USBDriver *usbp = (USBDriver *)arg; size_t i, n; - uint8_t buf[CONSOLE_SIZE]; /* TODO: a solution without extra buffer? */ + uint8_t buf[CONSOLE_EPSIZE]; /* TODO: a solution without extra buffer? */ osalSysLockFromISR(); /* check that the states of things are as they're supposed to */ @@ -1222,7 +1222,7 @@ static void console_flush_cb(void *arg) { } /* don't do anything if the queue is empty or has enough stuff in it */ - if(((n = oqGetFullI(&console_queue)) == 0) || (n >= CONSOLE_SIZE)) { + if(((n = oqGetFullI(&console_queue)) == 0) || (n >= CONSOLE_EPSIZE)) { /* rearm the timer */ chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, (void *)usbp); osalSysUnlockFromISR(); @@ -1232,10 +1232,10 @@ static void console_flush_cb(void *arg) { /* there's stuff hanging in the queue - so dequeue and send */ for(i = 0; i < n; i++) buf[i] = (uint8_t)oqGetI(&console_queue); - for(i = n; i < CONSOLE_SIZE; i++) + for(i = n; i < CONSOLE_EPSIZE; i++) buf[i] = 0; osalSysUnlockFromISR(); - usbPrepareTransmit(usbp, CONSOLE_ENDPOINT, buf, CONSOLE_SIZE); + usbPrepareTransmit(usbp, CONSOLE_ENDPOINT, buf, CONSOLE_EPSIZE); osalSysLockFromISR(); (void)usbStartTransmitI(usbp, CONSOLE_ENDPOINT); diff --git a/tmk_core/protocol/chibios/usb_main.h b/tmk_core/protocol/chibios/usb_main.h index 5897375b..3a7e76fc 100644 --- a/tmk_core/protocol/chibios/usb_main.h +++ b/tmk_core/protocol/chibios/usb_main.h @@ -20,7 +20,7 @@ #define _USB_MAIN_H_ // TESTING -// extern uint8_t blinkLedState; +// extern uint8_t blinkLed; #include "ch.h" #include "hal.h" @@ -44,19 +44,19 @@ void init_usb_driver(USBDriver *usbp); /* main keyboard (6kro) */ #define KBD_INTERFACE 0 #define KBD_ENDPOINT 1 -#define KBD_SIZE 8 -#define KBD_REPORT_KEYS (KBD_SIZE - 2) +#define KBD_EPSIZE 8 +#define KBD_REPORT_KEYS (KBD_EPSIZE - 2) /* secondary keyboard */ #ifdef NKRO_ENABLE #define NKRO_INTERFACE 4 #define NKRO_ENDPOINT 5 -#define NKRO_SIZE 16 -#define NKRO_REPORT_KEYS (NKRO_SIZE - 1) +#define NKRO_EPSIZE 16 +#define NKRO_REPORT_KEYS (NKRO_EPSIZE - 1) #endif /* this defines report_keyboard_t and computes REPORT_SIZE defines */ -#include "report.h" +// #include "report.h" /* extern report_keyboard_t keyboard_report_sent; */ @@ -80,7 +80,7 @@ void nkro_in_cb(USBDriver *usbp, usbep_t ep); #define MOUSE_INTERFACE 1 #define MOUSE_ENDPOINT 2 -#define MOUSE_SIZE 8 +#define MOUSE_EPSIZE 8 /* mouse IN request callback handler */ void mouse_in_cb(USBDriver *usbp, usbep_t ep); @@ -95,7 +95,7 @@ void mouse_in_cb(USBDriver *usbp, usbep_t ep); #define EXTRA_INTERFACE 3 #define EXTRA_ENDPOINT 4 -#define EXTRA_SIZE 8 +#define EXTRA_EPSIZE 8 /* extrakey IN request callback handler */ void extra_in_cb(USBDriver *usbp, usbep_t ep); @@ -116,11 +116,11 @@ typedef struct { #define CONSOLE_INTERFACE 2 #define CONSOLE_ENDPOINT 3 -#define CONSOLE_SIZE 16 +#define CONSOLE_EPSIZE 16 /* Number of IN reports that can be stored inside the output queue */ #define CONSOLE_QUEUE_CAPACITY 2 -#define CONSOLE_QUEUE_BUFFER_SIZE (CONSOLE_QUEUE_CAPACITY * CONSOLE_SIZE) +#define CONSOLE_QUEUE_BUFFER_SIZE (CONSOLE_QUEUE_CAPACITY * CONSOLE_EPSIZE) /* Console flush time */ #define CONSOLE_FLUSH_MS 50 @@ -138,15 +138,4 @@ void console_in_cb(USBDriver *usbp, usbep_t ep); void sendchar_pf(void *p, char c); -/* --------------------------- - * Host driver functions (TMK) - * --------------------------- - */ - -uint8_t keyboard_leds(void); -void send_keyboard(report_keyboard_t *report); -void send_mouse(report_mouse_t *report); -void send_system(uint16_t data); -void send_consumer(uint16_t data); - #endif /* _USB_MAIN_H_ */ From 1bcf15a8ea08b1728bc6caf27117a5ade0659a15 Mon Sep 17 00:00:00 2001 From: flabbergast Date: Thu, 10 Sep 2015 12:50:41 +0100 Subject: [PATCH 13/29] Add comments to chibi_onekey Makefile. --- keyboard/chibi_onekey/Makefile | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/keyboard/chibi_onekey/Makefile b/keyboard/chibi_onekey/Makefile index 3e8e715c..0a88f075 100644 --- a/keyboard/chibi_onekey/Makefile +++ b/keyboard/chibi_onekey/Makefile @@ -20,12 +20,17 @@ endif CONFIG_H = config.h -# chip/board +## chip/board settings +# the next two should match the directories in +# /os/hal/ports/$(MCU_FAMILY)/$(MCU_SERIES) MCU_FAMILY = STM32 MCU_SERIES = STM32F0xx # linker script to use +# it should exist either in /os/common/ports/ARMCMx/compilers/GCC/ld/ +# or /ld/ MCU_MODEL_FAMILY = STM32F072xB -# the directory in board/ +# it should exist either in /os/hal/boards/ +# or /boards BOARD = ST_STM32F072B_DISCOVERY # ARM version, M0/M1 are 6, M3/M4/M7 are 7 ARMV = 6 @@ -45,7 +50,7 @@ EXTRAKEY_ENABLE = yes # Audio control and System control CONSOLE_ENABLE = yes # Console for debug COMMAND_ENABLE = yes # Commands for debug and configuration SLEEP_LED_ENABLE = yes # Breathing sleep LED during USB suspend -#NKRO_ENABLE = yes # USB Nkey Rollover +NKRO_ENABLE = yes # USB Nkey Rollover include $(TMK_DIR)/tool/chibios/common.mk include $(TMK_DIR)/tool/chibios/chibios.mk From 438559f11dba792630201d66a2b690760550c2e2 Mon Sep 17 00:00:00 2001 From: flabbergast Date: Tue, 15 Sep 2015 08:52:03 +0100 Subject: [PATCH 14/29] Rename some Makefile defines. --- keyboard/chibi_onekey/Makefile | 7 +++++-- tmk_core/protocol/chibios/usb_main.h | 1 - tmk_core/tool/chibios/chibios.mk | 8 ++++---- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/keyboard/chibi_onekey/Makefile b/keyboard/chibi_onekey/Makefile index 0a88f075..2d5ff8cd 100644 --- a/keyboard/chibi_onekey/Makefile +++ b/keyboard/chibi_onekey/Makefile @@ -28,11 +28,14 @@ MCU_SERIES = STM32F0xx # linker script to use # it should exist either in /os/common/ports/ARMCMx/compilers/GCC/ld/ # or /ld/ -MCU_MODEL_FAMILY = STM32F072xB +MCU_LDSCRIPT = STM32F072xB +# startup code to use +# is should exist in /os/common/ports/ARMCMx/compilers/GCC/mk/ +MCU_STARTUP = stm32f0xx # it should exist either in /os/hal/boards/ # or /boards BOARD = ST_STM32F072B_DISCOVERY -# ARM version, M0/M1 are 6, M3/M4/M7 are 7 +# ARM version, CORTEX-M0/M1 are 6, CORTEX-M3/M4/M7 are 7 ARMV = 6 # If you want to be able to jump to bootloader from firmware (on STM32 MCUs), # set the correct BOOTLOADER_ADDRESS here. Otherwise leave commented out. diff --git a/tmk_core/protocol/chibios/usb_main.h b/tmk_core/protocol/chibios/usb_main.h index 3a7e76fc..85ea9153 100644 --- a/tmk_core/protocol/chibios/usb_main.h +++ b/tmk_core/protocol/chibios/usb_main.h @@ -127,7 +127,6 @@ typedef struct { /* Putchar over the USB console */ int8_t sendchar(uint8_t c); -/* wrapper for printf lib */ /* Flush output (send everything immediately) */ void console_flush_output(void); diff --git a/tmk_core/tool/chibios/chibios.mk b/tmk_core/tool/chibios/chibios.mk index ed5fd5b8..6ba783e3 100644 --- a/tmk_core/tool/chibios/chibios.mk +++ b/tmk_core/tool/chibios/chibios.mk @@ -85,7 +85,7 @@ endif # Imported source files and paths CHIBIOS = $(TMK_DIR)/tool/chibios/chibios # Startup files. -include $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/mk/startup_$(shell echo $(MCU_SERIES) | tr '[:upper:]' '[:lower:]').mk +include $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/mk/startup_$(MCU_STARTUP).mk # HAL-OSAL files (optional). include $(CHIBIOS)/os/hal/hal.mk include $(CHIBIOS)/os/hal/ports/$(MCU_FAMILY)/$(MCU_SERIES)/platform.mk @@ -101,10 +101,10 @@ include $(CHIBIOS)/os/rt/ports/ARMCMx/compilers/GCC/mk/port_v$(ARMV)m.mk # Other files (optional). # Define linker script file here -ifneq ("$(wildcard $(TARGET_DIR)/ld/$(MCU_MODEL_FAMILY).ld)","") -LDSCRIPT = $(TARGET_DIR)/ld/$(MCU_MODEL_FAMILY).ld +ifneq ("$(wildcard $(TARGET_DIR)/ld/$(MCU_LDSCRIPT).ld)","") +LDSCRIPT = $(TARGET_DIR)/ld/$(MCU_LDSCRIPT).ld else -LDSCRIPT = $(STARTUPLD)/$(MCU_MODEL_FAMILY).ld +LDSCRIPT = $(STARTUPLD)/$(MCU_LDSCRIPT).ld endif # C sources that can be compiled in ARM or THUMB mode depending on the global From 88c053f78e24d9906c0f469ab1862a468044a376 Mon Sep 17 00:00:00 2001 From: flabbergast Date: Mon, 5 Oct 2015 10:23:31 +0100 Subject: [PATCH 15/29] Move STM32 bootloader address config to separate .h file. --- keyboard/chibi_onekey/Makefile | 12 ++++-- keyboard/chibi_onekey/bootloader_defs.h | 7 ++++ tmk_core/common/chibios/bootloader.c | 6 +-- tmk_core/protocol/chibios/README.md | 12 +++--- .../tool/chibios/ch-bootloader-jump.patch | 37 ++++++++++--------- tmk_core/tool/chibios/chibios.mk | 8 ++++ 6 files changed, 51 insertions(+), 31 deletions(-) create mode 100644 keyboard/chibi_onekey/bootloader_defs.h diff --git a/keyboard/chibi_onekey/Makefile b/keyboard/chibi_onekey/Makefile index 2d5ff8cd..2c5af44b 100644 --- a/keyboard/chibi_onekey/Makefile +++ b/keyboard/chibi_onekey/Makefile @@ -37,12 +37,16 @@ MCU_STARTUP = stm32f0xx BOARD = ST_STM32F072B_DISCOVERY # ARM version, CORTEX-M0/M1 are 6, CORTEX-M3/M4/M7 are 7 ARMV = 6 -# If you want to be able to jump to bootloader from firmware (on STM32 MCUs), -# set the correct BOOTLOADER_ADDRESS here. Otherwise leave commented out. +# If you want to be able to jump to bootloader from firmware on STM32 MCUs, +# set the correct BOOTLOADER_ADDRESS. Either set it here, or define it in +# ./bootloader_defs.h or in ./boards//bootloader_defs.h (if you have +# a custom board definition that you plan to reuse). +# If you're not setting it here, leave it commented out. # It is chip dependent, the correct number can be looked up here (page 175): # http://www.st.com/web/en/resource/technical/document/application_note/CD00167594.pdf -# This also requires a patch to chibios: /tmk_core/ -BOOTLOADER_ADDRESS = 0x1FFFC800 +# This also requires a patch to chibios: +# /tmk_core/tool/chibios/ch-bootloader-jump.patch +#STM32_BOOTLOADER_ADDRESS = 0x1FFFC800 # Build Options # comment out to disable the options. diff --git a/keyboard/chibi_onekey/bootloader_defs.h b/keyboard/chibi_onekey/bootloader_defs.h new file mode 100644 index 00000000..02c48c4e --- /dev/null +++ b/keyboard/chibi_onekey/bootloader_defs.h @@ -0,0 +1,7 @@ +/* Address for jumping to bootloader on STM32 chips. */ +/* It is chip dependent, the correct number can be looked up here (page 175): + * http://www.st.com/web/en/resource/technical/document/application_note/CD00167594.pdf + * This also requires a patch to chibios: + * /tmk_core/tool/chibios/ch-bootloader-jump.patch + */ +#define STM32_BOOTLOADER_ADDRESS 0x1FFFC800 diff --git a/tmk_core/common/chibios/bootloader.c b/tmk_core/common/chibios/bootloader.c index 93f2e378..f36eced4 100644 --- a/tmk_core/common/chibios/bootloader.c +++ b/tmk_core/common/chibios/bootloader.c @@ -2,7 +2,7 @@ #include "ch.h" -#ifdef BOOTLOADER_ADDRESS +#ifdef STM32_BOOTLOADER_ADDRESS #define SYMVAL(sym) (uint32_t)(((uint8_t *)&(sym)) - ((uint8_t *)0)) extern uint32_t __ram0_end__; @@ -10,7 +10,7 @@ void bootloader_jump(void) { *((unsigned long *)(SYMVAL(__ram0_end__) - 4)) = 0xDEADBEEF; // set magic flag => reset handler will jump into boot loader NVIC_SystemReset(); } -#else /* BOOTLOADER_ADDRESS */ +#else /* STM32_BOOTLOADER_ADDRESS */ void bootloader_jump(void) {} -#endif /* BOOTLOADER_ADDRESS */ +#endif /* STM32_BOOTLOADER_ADDRESS */ diff --git a/tmk_core/protocol/chibios/README.md b/tmk_core/protocol/chibios/README.md index 06569c51..676a5f4f 100644 --- a/tmk_core/protocol/chibios/README.md +++ b/tmk_core/protocol/chibios/README.md @@ -2,13 +2,13 @@ ### Notes -- To use, unpack or symlink [ChibiOS] {currently 3.0.1} to `tmk_core/tool/chibios/chibios`. +- To use, unpack or symlink [ChibiOS] {currently 3.0.2} to `tmk_core/tool/chibios/chibios`. - For gcc options, inspect `tmk_core/tool/chibios/chibios.mk`. For instance, I enabled `-Wno-missing-field-initializers`, because TMK common bits generated a lot of warnings on that. Also pay attention to `-O0` (enabled for debugging); for deployment use `-O2`. - USB string descriptors are messy. I did not find a way to cleanly generate the right structures from actual strings, so the definitions in individual keyboards' `config.h` are ugly as heck. - There are some random constants left so far, e.g. 5ms sleep between calling `keyboard_task`, or 1.5sec wait for USB init, in `main.c`. There should be no such in `usb_main.c` (the main USB stack). Everything is based on timers/interrupts/kernel scheduling (well except `keyboard_task`), so no periodically called things (again, except `keyboard_task`, which is just how TMK is designed). - It is easy to add some code for testing (e.g. blink LED, do stuff on button press, etc...) - just create another thread in `main.c`, it will run independently of the keyboard business. -- Jumping to bootloader works, but it is not entirely pleasant, since it is very much MCU dependent. The code is now geared towards STM32 chips and their built-in bootloaders. So, one needs to dig out the right address to jump to, and pass it to the compiler in the `Makefile`. Also, a patch to upstream ChibiOS is needed (supplied), because it `ResetHandler` needs adjusting. +- Jumping to bootloader works, but it is not entirely pleasant, since it is very much MCU dependent. The code is now geared towards STM32 chips and their built-in bootloaders. So, one needs to dig out the right address to jump to, and either pass it to the compiler in the `Makefile`, or better, define it in `/bootloader_defs.h`. Also, a patch to upstream ChibiOS is needed (supplied), because it `ResetHandler` needs adjusting. - Sleep LED works, but at the moment only on/off, i.e. no breathing. - The USB stack works pretty completely; however there are bits of other TMK stuff that are not done yet: @@ -28,7 +28,7 @@ Also pay attention to `-O0` (enabled for debugging); for deployment use `-O2`. ### Tried with -- ChibiOS 3.0.1 and ST F072RB DISCOVERY board. +- ChibiOS 3.0.1, 3.0.2 and ST F072RB DISCOVERY board. - Need to test on other STM32 chips (F3, F4) to make it as much chip-independent as possible. ## STM32-based keyboard design considerations @@ -36,13 +36,13 @@ Also pay attention to `-O0` (enabled for debugging); for deployment use `-O2`. - STM32F0x2 chips can do crystal-less USB, but they still need a 3.3V voltage regulator. - The BOOT0 pin should be tied to GND. - For a hardware way of accessing the in-built DFU bootloader, in addition to the reset button, put another button between the BOOT0 pin and 3V3. -- For breathing the caps lock LED during the suspended state ("sleep LED"), it is desirable to have that LED on a hardware PWM pin (there's usually plenty of those, look for TIMERs in the datasheet). +- For breathing the caps lock LED during the suspended state ("sleep LED"), it is desirable to have that LED on a hardware PWM pin (there's usually plenty of those, look for TIMERs in the datasheet). However this is not strictly necessary, because instead of direct output of a timer to a pin (better of course), it is easy to define timer callbacks in ChibiOS that turn on/off an arbitrary pin. -## ChibiOS-supported MCUs (as of 3.0.1) +## ChibiOS-supported MCUs (as of 3.0.2) - Pretty much all STM32 chips. - There is also support for AVR8, but the USB stack is not implemented for them yet, and also the kernel itself takes about 1k of RAM. I think people managed to get ChibiOS running on atmega32[8p/u4] though. -- There is some support for K20 and KL25 Freescale chips (i.e. Teensy 3.0, mchck, FRDM-KL25Z, FRDM-K20D50M), but again, no USB stack yet. +- There is some support for K20x and KL2x Freescale chips (i.e. Teensy 3.0, mchck, FRDM-KL25Z, FRDM-K20D50M), but again, no official USB stack yet. This is being worked on, see the `kinetis` branch of [my ChibiOS fork](https://github.com/flabbergast/ChibiOS). It supports also Teensy LC, 3.1 and FRDM-KL26Z. - I've seen community support for Nordic NRF51822 (the chip in Adafruit's Bluefruit bluetooth-low-energy boards), but not sure about the extent. diff --git a/tmk_core/tool/chibios/ch-bootloader-jump.patch b/tmk_core/tool/chibios/ch-bootloader-jump.patch index 7f33e8ac..d8865762 100644 --- a/tmk_core/tool/chibios/ch-bootloader-jump.patch +++ b/tmk_core/tool/chibios/ch-bootloader-jump.patch @@ -1,8 +1,8 @@ diff --git a/os/common/ports/ARMCMx/compilers/GCC/crt0_v6m.s b/os/common/ports/ARMCMx/compilers/GCC/crt0_v6m.s -index 38b4513..12a3f39 100644 +index 51a79bb..42d07bd 100644 --- a/os/common/ports/ARMCMx/compilers/GCC/crt0_v6m.s +++ b/os/common/ports/ARMCMx/compilers/GCC/crt0_v6m.s -@@ -98,6 +98,13 @@ +@@ -105,6 +105,13 @@ #define CRT0_CALL_DESTRUCTORS TRUE #endif @@ -16,12 +16,12 @@ index 38b4513..12a3f39 100644 /*===========================================================================*/ /* Code section. */ /*===========================================================================*/ -@@ -117,6 +124,17 @@ +@@ -124,6 +131,17 @@ .thumb_func .global Reset_Handler Reset_Handler: + -+#ifdef BOOTLOADER_ADDRESS ++#ifdef STM32_BOOTLOADER_ADDRESS + /* jump to bootloader code */ + ldr r0, =__ram0_end__-4 + ldr r1, =MAGIC_BOOTLOADER_NUMBER @@ -29,16 +29,16 @@ index 38b4513..12a3f39 100644 + str r0, [r0, #0] /* erase stored magic */ + cmp r2, r1 + beq Bootloader_Jump -+#endif /* BOOTLOADER_ADDRESS */ ++#endif /* STM32_BOOTLOADER_ADDRESS */ + /* Interrupts are globally masked initially.*/ cpsid i -@@ -230,6 +248,21 @@ endfiniloop: +@@ -242,6 +260,21 @@ endfiniloop: ldr r1, =__default_exit bx r1 -+#ifdef BOOTLOADER_ADDRESS ++#ifdef STM32_BOOTLOADER_ADDRESS +/* + * Jump-to-bootloader function. + */ @@ -46,21 +46,21 @@ index 38b4513..12a3f39 100644 + .align 2 + .thumb_func +Bootloader_Jump: -+ ldr r0, =BOOTLOADER_ADDRESS ++ ldr r0, =STM32_BOOTLOADER_ADDRESS + ldr r1, [r0, #0] + mov sp, r1 + ldr r0, [r0, #4] + bx r0 -+#endif /* BOOTLOADER_ADDRESS */ ++#endif /* STM32_BOOTLOADER_ADDRESS */ + #endif /** @} */ diff --git a/os/common/ports/ARMCMx/compilers/GCC/crt0_v7m.s b/os/common/ports/ARMCMx/compilers/GCC/crt0_v7m.s -index fcfa4de..2d560da 100644 +index 4812a29..dca9f88 100644 --- a/os/common/ports/ARMCMx/compilers/GCC/crt0_v7m.s +++ b/os/common/ports/ARMCMx/compilers/GCC/crt0_v7m.s -@@ -133,6 +133,13 @@ +@@ -140,6 +140,13 @@ #define CRT0_CPACR_INIT 0x00F00000 #endif @@ -74,11 +74,12 @@ index fcfa4de..2d560da 100644 /*===========================================================================*/ /* Code section. */ /*===========================================================================*/ -@@ -157,6 +164,16 @@ +@@ -164,6 +171,17 @@ .thumb_func .global Reset_Handler Reset_Handler: -+#ifdef BOOTLOADER_ADDRESS ++ ++#ifdef STM32_BOOTLOADER_ADDRESS + /* jump to bootloader code */ + ldr r0, =__ram0_end__-4 + ldr r1, =MAGIC_BOOTLOADER_NUMBER @@ -86,16 +87,16 @@ index fcfa4de..2d560da 100644 + str r0, [r0, #0] /* erase stored magic */ + cmp r2, r1 + beq Bootloader_Jump -+#endif /* BOOTLOADER_ADDRESS */ ++#endif /* STM32_BOOTLOADER_ADDRESS */ + /* Interrupts are globally masked initially.*/ cpsid i -@@ -289,6 +306,21 @@ endfiniloop: +@@ -305,6 +323,21 @@ endfiniloop: /* Branching to the defined exit handler.*/ b __default_exit -+#ifdef BOOTLOADER_ADDRESS ++#ifdef STM32_BOOTLOADER_ADDRESS +/* + * Jump-to-bootloader function. + */ @@ -103,12 +104,12 @@ index fcfa4de..2d560da 100644 + .align 2 + .thumb_func +Bootloader_Jump: -+ ldr r0, =BOOTLOADER_ADDRESS ++ ldr r0, =STM32_BOOTLOADER_ADDRESS + ldr r1, [r0, #0] + mov sp, r1 + ldr r0, [r0, #4] + bx r0 -+#endif /* BOOTLOADER_ADDRESS */ ++#endif /* STM32_BOOTLOADER_ADDRESS */ + #endif /* !defined(__DOXYGEN__) */ diff --git a/tmk_core/tool/chibios/chibios.mk b/tmk_core/tool/chibios/chibios.mk index 6ba783e3..bc8c61b3 100644 --- a/tmk_core/tool/chibios/chibios.mk +++ b/tmk_core/tool/chibios/chibios.mk @@ -207,6 +207,14 @@ UDEFS = $(OPT_DEFS) # Define ASM defines here UADEFS = $(OPT_DEFS) +# bootloader definitions may be used in the startup .s file +ifneq ("$(wildcard $(TARGET_DIR)/bootloader_defs.h)","") + UADEFS += -include $(TARGET_DIR)/bootloader_defs.h + UDEFS += -include $(TARGET_DIR)/bootloader_defs.h +else ifneq ("$(wildcard $(TARGET_DIR)/boards/$(BOARD)/bootloader_defs.h)","") + UADEFS += -include $(TARGET_DIR)/boards/$(BOARD)/bootloader_defs.h + UDEFS += -include $(TARGET_DIR)/boards/$(BOARD)/bootloader_defs.h +endif # List all user directories here UINCDIR = From 19bb28d102b8c9b226aae38e2d8d9e53e574d6ec Mon Sep 17 00:00:00 2001 From: flabbergast Date: Sat, 10 Oct 2015 15:20:55 +0100 Subject: [PATCH 16/29] Add ARM Teensies bootloader code. --- tmk_core/common/chibios/bootloader.c | 23 ++++++++++++++++++++--- tmk_core/protocol/chibios/main.c | 8 ++------ 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/tmk_core/common/chibios/bootloader.c b/tmk_core/common/chibios/bootloader.c index f36eced4..cac52209 100644 --- a/tmk_core/common/chibios/bootloader.c +++ b/tmk_core/common/chibios/bootloader.c @@ -1,8 +1,13 @@ #include "bootloader.h" #include "ch.h" +#include "hal.h" #ifdef STM32_BOOTLOADER_ADDRESS +/* STM32 */ + +#if defined(STM32F0XX) +/* This code should be checked whether it runs correctly on platforms */ #define SYMVAL(sym) (uint32_t)(((uint8_t *)&(sym)) - ((uint8_t *)0)) extern uint32_t __ram0_end__; @@ -10,7 +15,19 @@ void bootloader_jump(void) { *((unsigned long *)(SYMVAL(__ram0_end__) - 4)) = 0xDEADBEEF; // set magic flag => reset handler will jump into boot loader NVIC_SystemReset(); } -#else /* STM32_BOOTLOADER_ADDRESS */ -void bootloader_jump(void) {} -#endif /* STM32_BOOTLOADER_ADDRESS */ +#else /* defined(STM32F0XX) */ +#error Check that the bootloader code works on your platform and add it to bootloader.c! +#endif /* defined(STM32F0XX) */ + +#elif defined(KL2x) || defined(K20x) /* STM32_BOOTLOADER_ADDRESS */ +/* Kinetis */ + +void bootloader_jump(void) { + chThdSleepMilliseconds(100); + __BKPT(0); +} + +#else /* neither STM32 nor KINETIS */ +void bootloader_jump(void) {} +#endif \ No newline at end of file diff --git a/tmk_core/protocol/chibios/main.c b/tmk_core/protocol/chibios/main.c index 589675aa..b2526d14 100644 --- a/tmk_core/protocol/chibios/main.c +++ b/tmk_core/protocol/chibios/main.c @@ -69,9 +69,9 @@ host_driver_t chibios_driver = { // while(true) { // if(blinkLed) { // blinkLed = 0; -// palSetPad(GPIOC, GPIOC_LED_ORANGE); +// palSetPad(TEENSY_PIN13_IOPORT, TEENSY_PIN13); // chThdSleepMilliseconds(100); -// palClearPad(GPIOC, GPIOC_LED_ORANGE); +// palClearPad(TEENSY_PIN13_IOPORT, TEENSY_PIN13); // } // chThdSleepMilliseconds(100); // } @@ -86,10 +86,6 @@ int main(void) { halInit(); chSysInit(); - palSetPad(GPIOC, GPIOC_LED_BLUE); - chThdSleepMilliseconds(400); - palClearPad(GPIOC, GPIOC_LED_BLUE); - // TESTING // chThdCreateStatic(waBlinkerThread, sizeof(waBlinkerThread), NORMALPRIO, blinkerThread, NULL); From 3c08375616beed21b9882231795b2fd05ff4f3ad Mon Sep 17 00:00:00 2001 From: flabbergast Date: Mon, 12 Oct 2015 06:52:26 +0100 Subject: [PATCH 17/29] Fix chibios/usb_main GET_REPORT handing. --- tmk_core/protocol/chibios/usb_main.c | 43 ++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/tmk_core/protocol/chibios/usb_main.c b/tmk_core/protocol/chibios/usb_main.c index f5f2dad7..2625c425 100644 --- a/tmk_core/protocol/chibios/usb_main.c +++ b/tmk_core/protocol/chibios/usb_main.c @@ -43,6 +43,12 @@ extern bool keyboard_nkro; #endif /* NKRO_ENABLE */ report_keyboard_t keyboard_report_sent = {{0}}; +#ifdef MOUSE_ENABLE +report_mouse_t mouse_report_blank = {0}; +#endif /* MOUSE_ENABLE */ +#ifdef EXTRAKEY_ENABLE +uint8_t extra_report_blank[3] = {0}; +#endif /* EXTRAKEY_ENABLE */ #ifdef CONSOLE_ENABLE /* The emission queue */ @@ -858,6 +864,43 @@ static bool usb_request_hook_cb(USBDriver *usbp) { return TRUE; break; +#ifdef MOUSE_ENABLE + case MOUSE_INTERFACE: + usbSetupTransfer(usbp, (uint8_t *)&mouse_report_blank, sizeof(mouse_report_blank), NULL); + return TRUE; + break; +#endif /* MOUSE_ENABLE */ + +#ifdef CONSOLE_ENABLE + case CONSOLE_INTERFACE: + usbSetupTransfer(usbp, console_queue_buffer, CONSOLE_EPSIZE, NULL); + return TRUE; + break; +#endif /* CONSOLE_ENABLE */ + +#ifdef EXTRAKEY_ENABLE + case EXTRA_INTERFACE: + if(usbp->setup[3] == 1) { /* MSB(wValue) [Report Type] == 1 [Input Report] */ + switch(usbp->setup[2]) { /* LSB(wValue) [Report ID] */ + case REPORT_ID_SYSTEM: + extra_report_blank[0] = REPORT_ID_SYSTEM; + usbSetupTransfer(usbp, (uint8_t *)extra_report_blank, sizeof(extra_report_blank), NULL); + return TRUE; + break; + case REPORT_ID_CONSUMER: + extra_report_blank[0] = REPORT_ID_CONSUMER; + usbSetupTransfer(usbp, (uint8_t *)extra_report_blank, sizeof(extra_report_blank), NULL); + return TRUE; + break; + default: + return FALSE; + } + } else { + return FALSE; + } + break; +#endif /* EXTRAKEY_ENABLE */ + default: usbSetupTransfer(usbp, NULL, 0, NULL); return TRUE; From cd7f30299a26dd32d19ef8ddd587eb8e1a5d4958 Mon Sep 17 00:00:00 2001 From: flabbergast Date: Mon, 12 Oct 2015 07:14:07 +0100 Subject: [PATCH 18/29] Add missing #include to keymap.c. --- tmk_core/common/keymap.c | 1 + 1 file changed, 1 insertion(+) diff --git a/tmk_core/common/keymap.c b/tmk_core/common/keymap.c index ece69fd5..d227add8 100644 --- a/tmk_core/common/keymap.c +++ b/tmk_core/common/keymap.c @@ -22,6 +22,7 @@ along with this program. If not, see . #include "action_macro.h" #include "wait.h" #include "debug.h" +#include "bootloader.h" static action_t keycode_to_action(uint8_t keycode); From d9652cdf992baaa066f75866689ac50d2b37cb9f Mon Sep 17 00:00:00 2001 From: flabbergast Date: Mon, 12 Oct 2015 09:40:06 +0100 Subject: [PATCH 19/29] Make bootmagic.c code portable (_delay_ms -> wait_ms). --- tmk_core/common/bootmagic.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tmk_core/common/bootmagic.c b/tmk_core/common/bootmagic.c index d6684b2d..698693cb 100644 --- a/tmk_core/common/bootmagic.c +++ b/tmk_core/common/bootmagic.c @@ -1,6 +1,6 @@ #include #include -#include +#include "wait.h" #include "matrix.h" #include "bootloader.h" #include "debug.h" @@ -21,7 +21,7 @@ void bootmagic(void) /* do scans in case of bounce */ print("bootmagic scan: ... "); uint8_t scan = 100; - while (scan--) { matrix_scan(); _delay_ms(10); } + while (scan--) { matrix_scan(); wait_ms(10); } print("done.\n"); /* bootmagic skip */ From cb663eeca6f5f2924974b4c6798a64489a5cdacc Mon Sep 17 00:00:00 2001 From: flabbergast Date: Mon, 12 Oct 2015 09:46:48 +0100 Subject: [PATCH 20/29] Move declaration of keymap_config. Should really not declare variables in .h files - since it's included in different .c files, a proper linker then complains that the same variable is declared more than once (once for each .c file that the offending .h is included in). --- tmk_core/common/bootmagic.c | 1 + tmk_core/common/keymap.c | 3 +++ tmk_core/common/keymap.h | 1 - 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/tmk_core/common/bootmagic.c b/tmk_core/common/bootmagic.c index 698693cb..08241f7d 100644 --- a/tmk_core/common/bootmagic.c +++ b/tmk_core/common/bootmagic.c @@ -10,6 +10,7 @@ #include "eeconfig.h" #include "bootmagic.h" +keymap_config_t keymap_config; void bootmagic(void) { diff --git a/tmk_core/common/keymap.c b/tmk_core/common/keymap.c index d227add8..876f5c82 100644 --- a/tmk_core/common/keymap.c +++ b/tmk_core/common/keymap.c @@ -24,6 +24,9 @@ along with this program. If not, see . #include "debug.h" #include "bootloader.h" +#ifdef BOOTMAGIC_ENABLE +extern keymap_config_t keymap_config; +#endif static action_t keycode_to_action(uint8_t keycode); diff --git a/tmk_core/common/keymap.h b/tmk_core/common/keymap.h index e1a6f992..659ea357 100644 --- a/tmk_core/common/keymap.h +++ b/tmk_core/common/keymap.h @@ -38,7 +38,6 @@ typedef union { bool nkro:1; }; } keymap_config_t; -keymap_config_t keymap_config; #endif From 2ac5cd730bf1578e9d593f83926a49b9053c4919 Mon Sep 17 00:00:00 2001 From: flabbergast Date: Mon, 12 Oct 2015 09:47:27 +0100 Subject: [PATCH 21/29] Add eeprom support for chibios/kinetis. --- tmk_core/common/chibios/eeconfig.c | 551 +++++++++++++++++++++++++++++ tmk_core/tool/chibios/common.mk | 1 - 2 files changed, 551 insertions(+), 1 deletion(-) create mode 100644 tmk_core/common/chibios/eeconfig.c diff --git a/tmk_core/common/chibios/eeconfig.c b/tmk_core/common/chibios/eeconfig.c new file mode 100644 index 00000000..f9e2718a --- /dev/null +++ b/tmk_core/common/chibios/eeconfig.c @@ -0,0 +1,551 @@ +#include "ch.h" +#include "hal.h" + +#include "eeconfig.h" + +/*************************************/ +/* Hardware backend */ +/* */ +/* Code from PJRC/Teensyduino */ +/*************************************/ + +/* Teensyduino Core Library + * http://www.pjrc.com/teensy/ + * Copyright (c) 2013 PJRC.COM, LLC. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * 1. The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * 2. If the Software is incorporated into a build system that allows + * selection among a list of target devices, then similar target + * devices manufactured by PJRC.COM must be included in the list of + * target devices and selectable in the same manner. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + + +#if defined(K20x) /* chip selection */ +/* Teensy 3.0, 3.1, 3.2; mchck; infinity keyboard */ + +// The EEPROM is really RAM with a hardware-based backup system to +// flash memory. Selecting a smaller size EEPROM allows more wear +// leveling, for higher write endurance. If you edit this file, +// set this to the smallest size your application can use. Also, +// due to Freescale's implementation, writing 16 or 32 bit words +// (aligned to 2 or 4 byte boundaries) has twice the endurance +// compared to writing 8 bit bytes. +// +#define EEPROM_SIZE 32 + +// Writing unaligned 16 or 32 bit data is handled automatically when +// this is defined, but at a cost of extra code size. Without this, +// any unaligned write will cause a hard fault exception! If you're +// absolutely sure all 16 and 32 bit writes will be aligned, you can +// remove the extra unnecessary code. +// +#define HANDLE_UNALIGNED_WRITES + +// Minimum EEPROM Endurance +// ------------------------ +#if (EEPROM_SIZE == 2048) // 35000 writes/byte or 70000 writes/word + #define EEESIZE 0x33 +#elif (EEPROM_SIZE == 1024) // 75000 writes/byte or 150000 writes/word + #define EEESIZE 0x34 +#elif (EEPROM_SIZE == 512) // 155000 writes/byte or 310000 writes/word + #define EEESIZE 0x35 +#elif (EEPROM_SIZE == 256) // 315000 writes/byte or 630000 writes/word + #define EEESIZE 0x36 +#elif (EEPROM_SIZE == 128) // 635000 writes/byte or 1270000 writes/word + #define EEESIZE 0x37 +#elif (EEPROM_SIZE == 64) // 1275000 writes/byte or 2550000 writes/word + #define EEESIZE 0x38 +#elif (EEPROM_SIZE == 32) // 2555000 writes/byte or 5110000 writes/word + #define EEESIZE 0x39 +#endif + +void eeprom_initialize(void) +{ + uint32_t count=0; + uint16_t do_flash_cmd[] = { + 0xf06f, 0x037f, 0x7003, 0x7803, + 0xf013, 0x0f80, 0xd0fb, 0x4770}; + uint8_t status; + + if (FTFL->FCNFG & FTFL_FCNFG_RAMRDY) { + // FlexRAM is configured as traditional RAM + // We need to reconfigure for EEPROM usage + FTFL->FCCOB0 = 0x80; // PGMPART = Program Partition Command + FTFL->FCCOB4 = EEESIZE; // EEPROM Size + FTFL->FCCOB5 = 0x03; // 0K for Dataflash, 32K for EEPROM backup + __disable_irq(); + // do_flash_cmd() must execute from RAM. Luckily the C syntax is simple... + (*((void (*)(volatile uint8_t *))((uint32_t)do_flash_cmd | 1)))(&(FTFL->FSTAT)); + __enable_irq(); + status = FTFL->FSTAT; + if (status & (FTFL_FSTAT_RDCOLERR|FTFL_FSTAT_ACCERR|FTFL_FSTAT_FPVIOL)) { + FTFL->FSTAT = (status & (FTFL_FSTAT_RDCOLERR|FTFL_FSTAT_ACCERR|FTFL_FSTAT_FPVIOL)); + return; // error + } + } + // wait for eeprom to become ready (is this really necessary?) + while (!(FTFL->FCNFG & FTFL_FCNFG_EEERDY)) { + if (++count > 20000) break; + } +} + +#define FlexRAM ((uint8_t *)0x14000000) + +uint8_t eeprom_read_byte(const uint8_t *addr) +{ + uint32_t offset = (uint32_t)addr; + if (offset >= EEPROM_SIZE) return 0; + if (!(FTFL->FCNFG & FTFL_FCNFG_EEERDY)) eeprom_initialize(); + return FlexRAM[offset]; +} + +uint16_t eeprom_read_word(const uint16_t *addr) +{ + uint32_t offset = (uint32_t)addr; + if (offset >= EEPROM_SIZE-1) return 0; + if (!(FTFL->FCNFG & FTFL_FCNFG_EEERDY)) eeprom_initialize(); + return *(uint16_t *)(&FlexRAM[offset]); +} + +uint32_t eeprom_read_dword(const uint32_t *addr) +{ + uint32_t offset = (uint32_t)addr; + if (offset >= EEPROM_SIZE-3) return 0; + if (!(FTFL->FCNFG & FTFL_FCNFG_EEERDY)) eeprom_initialize(); + return *(uint32_t *)(&FlexRAM[offset]); +} + +void eeprom_read_block(void *buf, const void *addr, uint32_t len) +{ + uint32_t offset = (uint32_t)addr; + uint8_t *dest = (uint8_t *)buf; + uint32_t end = offset + len; + + if (!(FTFL->FCNFG & FTFL_FCNFG_EEERDY)) eeprom_initialize(); + if (end > EEPROM_SIZE) end = EEPROM_SIZE; + while (offset < end) { + *dest++ = FlexRAM[offset++]; + } +} + +int eeprom_is_ready(void) +{ + return (FTFL->FCNFG & FTFL_FCNFG_EEERDY) ? 1 : 0; +} + +static void flexram_wait(void) +{ + while (!(FTFL->FCNFG & FTFL_FCNFG_EEERDY)) { + // TODO: timeout + } +} + +void eeprom_write_byte(uint8_t *addr, uint8_t value) +{ + uint32_t offset = (uint32_t)addr; + + if (offset >= EEPROM_SIZE) return; + if (!(FTFL->FCNFG & FTFL_FCNFG_EEERDY)) eeprom_initialize(); + if (FlexRAM[offset] != value) { + FlexRAM[offset] = value; + flexram_wait(); + } +} + +void eeprom_write_word(uint16_t *addr, uint16_t value) +{ + uint32_t offset = (uint32_t)addr; + + if (offset >= EEPROM_SIZE-1) return; + if (!(FTFL->FCNFG & FTFL_FCNFG_EEERDY)) eeprom_initialize(); +#ifdef HANDLE_UNALIGNED_WRITES + if ((offset & 1) == 0) { +#endif + if (*(uint16_t *)(&FlexRAM[offset]) != value) { + *(uint16_t *)(&FlexRAM[offset]) = value; + flexram_wait(); + } +#ifdef HANDLE_UNALIGNED_WRITES + } else { + if (FlexRAM[offset] != value) { + FlexRAM[offset] = value; + flexram_wait(); + } + if (FlexRAM[offset + 1] != (value >> 8)) { + FlexRAM[offset + 1] = value >> 8; + flexram_wait(); + } + } +#endif +} + +void eeprom_write_dword(uint32_t *addr, uint32_t value) +{ + uint32_t offset = (uint32_t)addr; + + if (offset >= EEPROM_SIZE-3) return; + if (!(FTFL->FCNFG & FTFL_FCNFG_EEERDY)) eeprom_initialize(); +#ifdef HANDLE_UNALIGNED_WRITES + switch (offset & 3) { + case 0: +#endif + if (*(uint32_t *)(&FlexRAM[offset]) != value) { + *(uint32_t *)(&FlexRAM[offset]) = value; + flexram_wait(); + } + return; +#ifdef HANDLE_UNALIGNED_WRITES + case 2: + if (*(uint16_t *)(&FlexRAM[offset]) != value) { + *(uint16_t *)(&FlexRAM[offset]) = value; + flexram_wait(); + } + if (*(uint16_t *)(&FlexRAM[offset + 2]) != (value >> 16)) { + *(uint16_t *)(&FlexRAM[offset + 2]) = value >> 16; + flexram_wait(); + } + return; + default: + if (FlexRAM[offset] != value) { + FlexRAM[offset] = value; + flexram_wait(); + } + if (*(uint16_t *)(&FlexRAM[offset + 1]) != (value >> 8)) { + *(uint16_t *)(&FlexRAM[offset + 1]) = value >> 8; + flexram_wait(); + } + if (FlexRAM[offset + 3] != (value >> 24)) { + FlexRAM[offset + 3] = value >> 24; + flexram_wait(); + } + } +#endif +} + +void eeprom_write_block(const void *buf, void *addr, uint32_t len) +{ + uint32_t offset = (uint32_t)addr; + const uint8_t *src = (const uint8_t *)buf; + + if (offset >= EEPROM_SIZE) return; + if (!(FTFL->FCNFG & FTFL_FCNFG_EEERDY)) eeprom_initialize(); + if (len >= EEPROM_SIZE) len = EEPROM_SIZE; + if (offset + len >= EEPROM_SIZE) len = EEPROM_SIZE - offset; + while (len > 0) { + uint32_t lsb = offset & 3; + if (lsb == 0 && len >= 4) { + // write aligned 32 bits + uint32_t val32; + val32 = *src++; + val32 |= (*src++ << 8); + val32 |= (*src++ << 16); + val32 |= (*src++ << 24); + if (*(uint32_t *)(&FlexRAM[offset]) != val32) { + *(uint32_t *)(&FlexRAM[offset]) = val32; + flexram_wait(); + } + offset += 4; + len -= 4; + } else if ((lsb == 0 || lsb == 2) && len >= 2) { + // write aligned 16 bits + uint16_t val16; + val16 = *src++; + val16 |= (*src++ << 8); + if (*(uint16_t *)(&FlexRAM[offset]) != val16) { + *(uint16_t *)(&FlexRAM[offset]) = val16; + flexram_wait(); + } + offset += 2; + len -= 2; + } else { + // write 8 bits + uint8_t val8 = *src++; + if (FlexRAM[offset] != val8) { + FlexRAM[offset] = val8; + flexram_wait(); + } + offset++; + len--; + } + } +} + +/* +void do_flash_cmd(volatile uint8_t *fstat) +{ + *fstat = 0x80; + while ((*fstat & 0x80) == 0) ; // wait +} +00000000 : + 0: f06f 037f mvn.w r3, #127 ; 0x7f + 4: 7003 strb r3, [r0, #0] + 6: 7803 ldrb r3, [r0, #0] + 8: f013 0f80 tst.w r3, #128 ; 0x80 + c: d0fb beq.n 6 + e: 4770 bx lr +*/ + +#elif defined(KL2x) /* chip selection */ +/* Teensy LC (emulated) */ + +#define SYMVAL(sym) (uint32_t)(((uint8_t *)&(sym)) - ((uint8_t *)0)) + +extern uint32_t __eeprom_workarea_start__; +extern uint32_t __eeprom_workarea_end__; + +#define EEPROM_SIZE 128 + +static uint32_t flashend = 0; + +void eeprom_initialize(void) +{ + const uint16_t *p = (uint16_t *)SYMVAL(__eeprom_workarea_start__); + + do { + if (*p++ == 0xFFFF) { + flashend = (uint32_t)(p - 2); + return; + } + } while (p < (uint16_t *)SYMVAL(__eeprom_workarea_end__)); + flashend = (uint32_t)((uint16_t *)SYMVAL(__eeprom_workarea_end__) - 1); +} + +uint8_t eeprom_read_byte(const uint8_t *addr) +{ + uint32_t offset = (uint32_t)addr; + const uint16_t *p = (uint16_t *)SYMVAL(__eeprom_workarea_start__); + const uint16_t *end = (const uint16_t *)((uint32_t)flashend); + uint16_t val; + uint8_t data=0xFF; + + if (!end) { + eeprom_initialize(); + end = (const uint16_t *)((uint32_t)flashend); + } + if (offset < EEPROM_SIZE) { + while (p <= end) { + val = *p++; + if ((val & 255) == offset) data = val >> 8; + } + } + return data; +} + +static void flash_write(const uint16_t *code, uint32_t addr, uint32_t data) +{ + // with great power comes great responsibility.... + uint32_t stat; + *(uint32_t *)&(FTFA->FCCOB3) = 0x06000000 | (addr & 0x00FFFFFC); + *(uint32_t *)&(FTFA->FCCOB7) = data; + __disable_irq(); + (*((void (*)(volatile uint8_t *))((uint32_t)code | 1)))(&(FTFA->FSTAT)); + __enable_irq(); + stat = FTFA->FSTAT & (FTFA_FSTAT_RDCOLERR|FTFA_FSTAT_ACCERR|FTFA_FSTAT_FPVIOL); + if (stat) { + FTFA->FSTAT = stat; + } + MCM->PLACR |= MCM_PLACR_CFCC; +} + +void eeprom_write_byte(uint8_t *addr, uint8_t data) +{ + uint32_t offset = (uint32_t)addr; + const uint16_t *p, *end = (const uint16_t *)((uint32_t)flashend); + uint32_t i, val, flashaddr; + uint16_t do_flash_cmd[] = { + 0x2380, 0x7003, 0x7803, 0xb25b, 0x2b00, 0xdafb, 0x4770}; + uint8_t buf[EEPROM_SIZE]; + + if (offset >= EEPROM_SIZE) return; + if (!end) { + eeprom_initialize(); + end = (const uint16_t *)((uint32_t)flashend); + } + if (++end < (uint16_t *)SYMVAL(__eeprom_workarea_end__)) { + val = (data << 8) | offset; + flashaddr = (uint32_t)end; + flashend = flashaddr; + if ((flashaddr & 2) == 0) { + val |= 0xFFFF0000; + } else { + val <<= 16; + val |= 0x0000FFFF; + } + flash_write(do_flash_cmd, flashaddr, val); + } else { + for (i=0; i < EEPROM_SIZE; i++) { + buf[i] = 0xFF; + } + for (p = (uint16_t *)SYMVAL(__eeprom_workarea_start__); p < (uint16_t *)SYMVAL(__eeprom_workarea_end__); p++) { + val = *p; + if ((val & 255) < EEPROM_SIZE) { + buf[val & 255] = val >> 8; + } + } + buf[offset] = data; + for (flashaddr=(uint32_t)(uint16_t *)SYMVAL(__eeprom_workarea_start__); flashaddr < (uint32_t)(uint16_t *)SYMVAL(__eeprom_workarea_end__); flashaddr += 1024) { + *(uint32_t *)&(FTFA->FCCOB3) = 0x09000000 | flashaddr; + __disable_irq(); + (*((void (*)(volatile uint8_t *))((uint32_t)do_flash_cmd | 1)))(&(FTFA->FSTAT)); + __enable_irq(); + val = FTFA->FSTAT & (FTFA_FSTAT_RDCOLERR|FTFA_FSTAT_ACCERR|FTFA_FSTAT_FPVIOL);; + if (val) FTFA->FSTAT = val; + MCM->PLACR |= MCM_PLACR_CFCC; + } + flashaddr=(uint32_t)(uint16_t *)SYMVAL(__eeprom_workarea_start__); + for (i=0; i < EEPROM_SIZE; i++) { + if (buf[i] == 0xFF) continue; + if ((flashaddr & 2) == 0) { + val = (buf[i] << 8) | i; + } else { + val = val | (buf[i] << 24) | (i << 16); + flash_write(do_flash_cmd, flashaddr, val); + } + flashaddr += 2; + } + flashend = flashaddr; + if ((flashaddr & 2)) { + val |= 0xFFFF0000; + flash_write(do_flash_cmd, flashaddr, val); + } + } +} + +/* +void do_flash_cmd(volatile uint8_t *fstat) +{ + *fstat = 0x80; + while ((*fstat & 0x80) == 0) ; // wait +} +00000000 : + 0: 2380 movs r3, #128 ; 0x80 + 2: 7003 strb r3, [r0, #0] + 4: 7803 ldrb r3, [r0, #0] + 6: b25b sxtb r3, r3 + 8: 2b00 cmp r3, #0 + a: dafb bge.n 4 + c: 4770 bx lr +*/ + + +uint16_t eeprom_read_word(const uint16_t *addr) +{ + const uint8_t *p = (const uint8_t *)addr; + return eeprom_read_byte(p) | (eeprom_read_byte(p+1) << 8); +} + +uint32_t eeprom_read_dword(const uint32_t *addr) +{ + const uint8_t *p = (const uint8_t *)addr; + return eeprom_read_byte(p) | (eeprom_read_byte(p+1) << 8) + | (eeprom_read_byte(p+2) << 16) | (eeprom_read_byte(p+3) << 24); +} + +void eeprom_read_block(void *buf, const void *addr, uint32_t len) +{ + const uint8_t *p = (const uint8_t *)addr; + uint8_t *dest = (uint8_t *)buf; + while (len--) { + *dest++ = eeprom_read_byte(p++); + } +} + +int eeprom_is_ready(void) +{ + return 1; +} + +void eeprom_write_word(uint16_t *addr, uint16_t value) +{ + uint8_t *p = (uint8_t *)addr; + eeprom_write_byte(p++, value); + eeprom_write_byte(p, value >> 8); +} + +void eeprom_write_dword(uint32_t *addr, uint32_t value) +{ + uint8_t *p = (uint8_t *)addr; + eeprom_write_byte(p++, value); + eeprom_write_byte(p++, value >> 8); + eeprom_write_byte(p++, value >> 16); + eeprom_write_byte(p, value >> 24); +} + +void eeprom_write_block(const void *buf, void *addr, uint32_t len) +{ + uint8_t *p = (uint8_t *)addr; + const uint8_t *src = (const uint8_t *)buf; + while (len--) { + eeprom_write_byte(p++, *src++); + } +} + +#else +#error EEPROM support not implemented for your chip +#endif /* chip selection */ + + +/*****************/ +/* TMK functions */ +/*****************/ + +void eeconfig_init(void) +{ + eeprom_write_word(EECONFIG_MAGIC, EECONFIG_MAGIC_NUMBER); + eeprom_write_byte(EECONFIG_DEBUG, 0); + eeprom_write_byte(EECONFIG_DEFAULT_LAYER, 0); + eeprom_write_byte(EECONFIG_KEYMAP, 0); + eeprom_write_byte(EECONFIG_MOUSEKEY_ACCEL, 0); +#ifdef BACKLIGHT_ENABLE + eeprom_write_byte(EECONFIG_BACKLIGHT, 0); +#endif +} + +void eeconfig_enable(void) +{ + eeprom_write_word(EECONFIG_MAGIC, EECONFIG_MAGIC_NUMBER); +} + +void eeconfig_disable(void) +{ + eeprom_write_word(EECONFIG_MAGIC, 0xFFFF); +} + +bool eeconfig_is_enabled(void) +{ + return (eeprom_read_word(EECONFIG_MAGIC) == EECONFIG_MAGIC_NUMBER); +} + +uint8_t eeconfig_read_debug(void) { return eeprom_read_byte(EECONFIG_DEBUG); } +void eeconfig_write_debug(uint8_t val) { eeprom_write_byte(EECONFIG_DEBUG, val); } + +uint8_t eeconfig_read_default_layer(void) { return eeprom_read_byte(EECONFIG_DEFAULT_LAYER); } +void eeconfig_write_default_layer(uint8_t val) { eeprom_write_byte(EECONFIG_DEFAULT_LAYER, val); } + +uint8_t eeconfig_read_keymap(void) { return eeprom_read_byte(EECONFIG_KEYMAP); } +void eeconfig_write_keymap(uint8_t val) { eeprom_write_byte(EECONFIG_KEYMAP, val); } + +#ifdef BACKLIGHT_ENABLE +uint8_t eeconfig_read_backlight(void) { return eeprom_read_byte(EECONFIG_BACKLIGHT); } +void eeconfig_write_backlight(uint8_t val) { eeprom_write_byte(EECONFIG_BACKLIGHT, val); } +#endif diff --git a/tmk_core/tool/chibios/common.mk b/tmk_core/tool/chibios/common.mk index f0d39f31..883054a4 100644 --- a/tmk_core/tool/chibios/common.mk +++ b/tmk_core/tool/chibios/common.mk @@ -18,7 +18,6 @@ SRC += $(COMMON_DIR)/host.c \ # Option modules ifdef BOOTMAGIC_ENABLE - $(error Bootmagic Not Supported) SRC += $(COMMON_DIR)/bootmagic.c SRC += $(COMMON_DIR)/chibios/eeconfig.c OPT_DEFS += -DBOOTMAGIC_ENABLE From 9178ea2d73511786182317fe3e7b8ffc02cc3dc4 Mon Sep 17 00:00:00 2001 From: flabbergast Date: Mon, 12 Oct 2015 10:20:16 +0100 Subject: [PATCH 22/29] Rename chibios example keyboard. --- .../{chibi_onekey => stm32_onekey}/Makefile | 1 + .../bootloader_defs.h | 0 .../{chibi_onekey => stm32_onekey}/chconf.h | 0 .../{chibi_onekey => stm32_onekey}/config.h | 0 .../{chibi_onekey => stm32_onekey}/halconf.h | 0 .../keymap_plain.c | 0 keyboard/{chibi_onekey => stm32_onekey}/led.c | 0 .../{chibi_onekey => stm32_onekey}/matrix.c | 0 .../{chibi_onekey => stm32_onekey}/mcuconf.h | 0 tmk_core/protocol/chibios/README.md | 22 +++++++++---------- tmk_core/tool/chibios/chibios.mk | 2 +- 11 files changed, 13 insertions(+), 12 deletions(-) rename keyboard/{chibi_onekey => stm32_onekey}/Makefile (97%) rename keyboard/{chibi_onekey => stm32_onekey}/bootloader_defs.h (100%) rename keyboard/{chibi_onekey => stm32_onekey}/chconf.h (100%) rename keyboard/{chibi_onekey => stm32_onekey}/config.h (100%) rename keyboard/{chibi_onekey => stm32_onekey}/halconf.h (100%) rename keyboard/{chibi_onekey => stm32_onekey}/keymap_plain.c (100%) rename keyboard/{chibi_onekey => stm32_onekey}/led.c (100%) rename keyboard/{chibi_onekey => stm32_onekey}/matrix.c (100%) rename keyboard/{chibi_onekey => stm32_onekey}/mcuconf.h (100%) diff --git a/keyboard/chibi_onekey/Makefile b/keyboard/stm32_onekey/Makefile similarity index 97% rename from keyboard/chibi_onekey/Makefile rename to keyboard/stm32_onekey/Makefile index 2c5af44b..d84bfa4b 100644 --- a/keyboard/chibi_onekey/Makefile +++ b/keyboard/stm32_onekey/Makefile @@ -52,6 +52,7 @@ ARMV = 6 # comment out to disable the options. # #BOOTMAGIC_ENABLE = yes # Virtual DIP switch configuration +## BOOTMAGIC is not supported on STM32 chips yet. MOUSEKEY_ENABLE = yes # Mouse keys EXTRAKEY_ENABLE = yes # Audio control and System control CONSOLE_ENABLE = yes # Console for debug diff --git a/keyboard/chibi_onekey/bootloader_defs.h b/keyboard/stm32_onekey/bootloader_defs.h similarity index 100% rename from keyboard/chibi_onekey/bootloader_defs.h rename to keyboard/stm32_onekey/bootloader_defs.h diff --git a/keyboard/chibi_onekey/chconf.h b/keyboard/stm32_onekey/chconf.h similarity index 100% rename from keyboard/chibi_onekey/chconf.h rename to keyboard/stm32_onekey/chconf.h diff --git a/keyboard/chibi_onekey/config.h b/keyboard/stm32_onekey/config.h similarity index 100% rename from keyboard/chibi_onekey/config.h rename to keyboard/stm32_onekey/config.h diff --git a/keyboard/chibi_onekey/halconf.h b/keyboard/stm32_onekey/halconf.h similarity index 100% rename from keyboard/chibi_onekey/halconf.h rename to keyboard/stm32_onekey/halconf.h diff --git a/keyboard/chibi_onekey/keymap_plain.c b/keyboard/stm32_onekey/keymap_plain.c similarity index 100% rename from keyboard/chibi_onekey/keymap_plain.c rename to keyboard/stm32_onekey/keymap_plain.c diff --git a/keyboard/chibi_onekey/led.c b/keyboard/stm32_onekey/led.c similarity index 100% rename from keyboard/chibi_onekey/led.c rename to keyboard/stm32_onekey/led.c diff --git a/keyboard/chibi_onekey/matrix.c b/keyboard/stm32_onekey/matrix.c similarity index 100% rename from keyboard/chibi_onekey/matrix.c rename to keyboard/stm32_onekey/matrix.c diff --git a/keyboard/chibi_onekey/mcuconf.h b/keyboard/stm32_onekey/mcuconf.h similarity index 100% rename from keyboard/chibi_onekey/mcuconf.h rename to keyboard/stm32_onekey/mcuconf.h diff --git a/tmk_core/protocol/chibios/README.md b/tmk_core/protocol/chibios/README.md index 676a5f4f..9796f8c7 100644 --- a/tmk_core/protocol/chibios/README.md +++ b/tmk_core/protocol/chibios/README.md @@ -2,15 +2,14 @@ ### Notes -- To use, unpack or symlink [ChibiOS] {currently 3.0.2} to `tmk_core/tool/chibios/chibios`. +- To use, unpack or symlink [ChibiOS] {currently 3.0.2} to `tmk_core/tool/chibios/chibios`. For Kinetis support, you'll need a fork which implements the USB driver, e.g. [this one](https://github.com/flabbergast/ChibiOS/tree/kinetis). - For gcc options, inspect `tmk_core/tool/chibios/chibios.mk`. For instance, I enabled `-Wno-missing-field-initializers`, because TMK common bits generated a lot of warnings on that. Also pay attention to `-O0` (enabled for debugging); for deployment use `-O2`. - USB string descriptors are messy. I did not find a way to cleanly generate the right structures from actual strings, so the definitions in individual keyboards' `config.h` are ugly as heck. - There are some random constants left so far, e.g. 5ms sleep between calling `keyboard_task`, or 1.5sec wait for USB init, in `main.c`. There should be no such in `usb_main.c` (the main USB stack). Everything is based on timers/interrupts/kernel scheduling (well except `keyboard_task`), so no periodically called things (again, except `keyboard_task`, which is just how TMK is designed). - It is easy to add some code for testing (e.g. blink LED, do stuff on button press, etc...) - just create another thread in `main.c`, it will run independently of the keyboard business. -- Jumping to bootloader works, but it is not entirely pleasant, since it is very much MCU dependent. The code is now geared towards STM32 chips and their built-in bootloaders. So, one needs to dig out the right address to jump to, and either pass it to the compiler in the `Makefile`, or better, define it in `/bootloader_defs.h`. Also, a patch to upstream ChibiOS is needed (supplied), because it `ResetHandler` needs adjusting. +- Jumping to (the built-in) bootloaders on STM32 works, but it is not entirely pleasant, since it is very much MCU dependent. So, one needs to dig out the right address to jump to, and either pass it to the compiler in the `Makefile`, or better, define it in `/bootloader_defs.h`. Also, a patch to upstream ChibiOS is needed (supplied), because it `ResetHandler` needs adjusting. - Sleep LED works, but at the moment only on/off, i.e. no breathing. -- The USB stack works pretty completely; however there are bits of other TMK stuff that are not done yet: ### Immediate todo @@ -24,12 +23,20 @@ Also pay attention to `-O0` (enabled for debugging); for deployment use `-O2`. ### Missing / not working (TMK vs ChibiOS bits) -- eeprom / bootmagic (will be chip dependent; eeprom needs to be emulated in flash, which means less writes; wear-levelling?) There is a semi-official ST "driver" for eeprom, with wear-levelling, but I think it consumes a lot of RAM (like 2 pages, i.e. 1kB or so). +- eeprom / bootmagic for STM32 (will be chip dependent; eeprom needs to be emulated in flash, which means less writes; wear-levelling?) There is a semi-official ST "driver" for eeprom, with wear-levelling, but I think it consumes a lot of RAM (like 2 pages, i.e. 1kB or so). ### Tried with - ChibiOS 3.0.1, 3.0.2 and ST F072RB DISCOVERY board. - Need to test on other STM32 chips (F3, F4) to make it as much chip-independent as possible. +- ChibiOS with Kinetis patches and Teensy LC and 3.0. + +## ChibiOS-supported MCUs (as of 3.0.2) + +- Pretty much all STM32 chips. +- There is some support for K20x and KL2x Freescale chips (i.e. Teensy 3.x/LC, mchck, FRDM-KL2{5,6}Z, FRDM-K20D50M), but again, no official USB stack yet. However the `kinetis` branch of [my ChibiOS fork](https://github.com/flabbergast/ChibiOS). With this fork, TMK work normally on all the ARM Teensies. +- There is also support for AVR8, but the USB stack is not implemented for them yet, and also the kernel itself takes about 1k of RAM. I think people managed to get ChibiOS running on atmega32[8p/u4] though. +- I've seen community support for Nordic NRF51822 (the chip in Adafruit's Bluefruit bluetooth-low-energy boards), but not sure about the extent. ## STM32-based keyboard design considerations @@ -38,13 +45,6 @@ Also pay attention to `-O0` (enabled for debugging); for deployment use `-O2`. - For a hardware way of accessing the in-built DFU bootloader, in addition to the reset button, put another button between the BOOT0 pin and 3V3. - For breathing the caps lock LED during the suspended state ("sleep LED"), it is desirable to have that LED on a hardware PWM pin (there's usually plenty of those, look for TIMERs in the datasheet). However this is not strictly necessary, because instead of direct output of a timer to a pin (better of course), it is easy to define timer callbacks in ChibiOS that turn on/off an arbitrary pin. -## ChibiOS-supported MCUs (as of 3.0.2) - -- Pretty much all STM32 chips. -- There is also support for AVR8, but the USB stack is not implemented for them yet, and also the kernel itself takes about 1k of RAM. I think people managed to get ChibiOS running on atmega32[8p/u4] though. -- There is some support for K20x and KL2x Freescale chips (i.e. Teensy 3.0, mchck, FRDM-KL25Z, FRDM-K20D50M), but again, no official USB stack yet. This is being worked on, see the `kinetis` branch of [my ChibiOS fork](https://github.com/flabbergast/ChibiOS). It supports also Teensy LC, 3.1 and FRDM-KL26Z. -- I've seen community support for Nordic NRF51822 (the chip in Adafruit's Bluefruit bluetooth-low-energy boards), but not sure about the extent. - [ChibiOS]: http://chibios.org diff --git a/tmk_core/tool/chibios/chibios.mk b/tmk_core/tool/chibios/chibios.mk index bc8c61b3..d1738c13 100644 --- a/tmk_core/tool/chibios/chibios.mk +++ b/tmk_core/tool/chibios/chibios.mk @@ -5,7 +5,7 @@ # Compiler options here. ifeq ($(USE_OPT),) - USE_OPT = -O0 -ggdb -fomit-frame-pointer -falign-functions=16 -std=gnu99 -DPROTOCOL_CHIBIOS + USE_OPT = -O2 -ggdb -fomit-frame-pointer -falign-functions=16 -std=gnu99 -DPROTOCOL_CHIBIOS endif # C specific options here (added to USE_OPT). From 2b4066bb93ffda75dde58342a21c28878b6f50e6 Mon Sep 17 00:00:00 2001 From: flabbergast Date: Mon, 12 Oct 2015 10:38:47 +0100 Subject: [PATCH 23/29] Move chibios/cortex selection to local Makefiles. --- keyboard/stm32_onekey/Makefile | 3 +++ tmk_core/tool/chibios/chibios.mk | 2 -- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/keyboard/stm32_onekey/Makefile b/keyboard/stm32_onekey/Makefile index d84bfa4b..3868ee3d 100644 --- a/keyboard/stm32_onekey/Makefile +++ b/keyboard/stm32_onekey/Makefile @@ -35,6 +35,9 @@ MCU_STARTUP = stm32f0xx # it should exist either in /os/hal/boards/ # or /boards BOARD = ST_STM32F072B_DISCOVERY +# Cortex version +# Teensy LC is cortex-m0; Teensy 3.x are cortex-m4 +MCU = cortex-m0 # ARM version, CORTEX-M0/M1 are 6, CORTEX-M3/M4/M7 are 7 ARMV = 6 # If you want to be able to jump to bootloader from firmware on STM32 MCUs, diff --git a/tmk_core/tool/chibios/chibios.mk b/tmk_core/tool/chibios/chibios.mk index d1738c13..0f6af53d 100644 --- a/tmk_core/tool/chibios/chibios.mk +++ b/tmk_core/tool/chibios/chibios.mk @@ -162,8 +162,6 @@ INCDIR = $(STARTUPINC) $(KERNINC) $(PORTINC) $(OSALINC) \ # Compiler settings # -MCU = cortex-m0 - #TRGT = arm-elf- TRGT = arm-none-eabi- CC = $(TRGT)gcc From c61210cfff21f88c25ad102dcd3afe58ce251c96 Mon Sep 17 00:00:00 2001 From: flabbergast Date: Mon, 12 Oct 2015 10:39:24 +0100 Subject: [PATCH 24/29] Add Teensy LC onekey example. --- keyboard/teensy_lc_onekey/Makefile | 77 ++++ keyboard/teensy_lc_onekey/Makefile.3.0 | 77 ++++ keyboard/teensy_lc_onekey/chconf.h | 499 ++++++++++++++++++++++ keyboard/teensy_lc_onekey/config.h | 74 ++++ keyboard/teensy_lc_onekey/halconf.h | 168 ++++++++ keyboard/teensy_lc_onekey/instructions.md | 62 +++ keyboard/teensy_lc_onekey/keymap_plain.c | 44 ++ keyboard/teensy_lc_onekey/ld/MKL26Z64.ld | 161 +++++++ keyboard/teensy_lc_onekey/led.c | 32 ++ keyboard/teensy_lc_onekey/matrix.c | 163 +++++++ keyboard/teensy_lc_onekey/mcuconf.h | 55 +++ 11 files changed, 1412 insertions(+) create mode 100644 keyboard/teensy_lc_onekey/Makefile create mode 100644 keyboard/teensy_lc_onekey/Makefile.3.0 create mode 100644 keyboard/teensy_lc_onekey/chconf.h create mode 100644 keyboard/teensy_lc_onekey/config.h create mode 100644 keyboard/teensy_lc_onekey/halconf.h create mode 100644 keyboard/teensy_lc_onekey/instructions.md create mode 100644 keyboard/teensy_lc_onekey/keymap_plain.c create mode 100644 keyboard/teensy_lc_onekey/ld/MKL26Z64.ld create mode 100644 keyboard/teensy_lc_onekey/led.c create mode 100644 keyboard/teensy_lc_onekey/matrix.c create mode 100644 keyboard/teensy_lc_onekey/mcuconf.h diff --git a/keyboard/teensy_lc_onekey/Makefile b/keyboard/teensy_lc_onekey/Makefile new file mode 100644 index 00000000..dc489cb7 --- /dev/null +++ b/keyboard/teensy_lc_onekey/Makefile @@ -0,0 +1,77 @@ +# Target file name (without extension). +PROJECT = ch + +# Directory common source files exist +TMK_DIR = ../../tmk_core + +# Directory keyboard dependent files exist +TARGET_DIR = . + +# project specific files +SRC = matrix.c \ + led.c + +ifdef KEYMAP + SRC := keymap_$(KEYMAP).c $(SRC) +else + SRC := keymap_plain.c $(SRC) +endif + +CONFIG_H = config.h + +## chip/board settings +# - the next two should match the directories in +# /os/hal/ports/$(MCU_FAMILY)/$(MCU_SERIES) +# - For Teensies, FAMILY = KINETIS and SERIES is either +# KL2x (LC) or K20x (3.0,3.1,3.2). +MCU_FAMILY = KINETIS +MCU_SERIES = KL2x + +# Linker script to use +# - it should exist either in /os/common/ports/ARMCMx/compilers/GCC/ld/ +# or /ld/ +# - NOTE: a custom ld script is needed for EEPROM on Teensy LC +# - LDSCRIPT = +# - MKL26Z64 for Teensy LC +# - MK20DX128 for Teensy 3.0 +# - MK20DX256 for Teensy 3.1 and 3.2 +MCU_LDSCRIPT = MKL26Z64 + +# Startup code to use +# - it should exist in /os/common/ports/ARMCMx/compilers/GCC/mk/ +# - STARTUP = +# - kl2x for Teensy LC +# - k20x5 for Teensy 3.0 +# - k20x7 for Teensy 3.1 and 3.2 +MCU_STARTUP = kl2x + +# Board: it should exist either in /os/hal/boards/ +# or /boards +# - BOARD = +# - PJRC_TEENSY_LC for Teensy LC +# - PJRC_TEENSY_3 for Teensy 3.0 +# - PJRC_TEENSY_3_1 for Teensy 3.1 or 3.2 +BOARD = PJRC_TEENSY_LC + +# Cortex version +# Teensy LC is cortex-m0; Teensy 3.x are cortex-m4 +MCU = cortex-m0 + +# ARM version, CORTEX-M0/M1 are 6, CORTEX-M3/M4/M7 are 7 +# I.e. 6 for Teensy LC; 7 for Teensy 3.x +ARMV = 6 + +# Build Options +# comment out to disable the options. +# +BOOTMAGIC_ENABLE = yes # Virtual DIP switch configuration +## (Note that for BOOTMAGIC on Teensy LC you have to use a custom .ld script.) +MOUSEKEY_ENABLE = yes # Mouse keys +EXTRAKEY_ENABLE = yes # Audio control and System control +CONSOLE_ENABLE = yes # Console for debug +COMMAND_ENABLE = yes # Commands for debug and configuration +SLEEP_LED_ENABLE = yes # Breathing sleep LED during USB suspend +NKRO_ENABLE = yes # USB Nkey Rollover + +include $(TMK_DIR)/tool/chibios/common.mk +include $(TMK_DIR)/tool/chibios/chibios.mk diff --git a/keyboard/teensy_lc_onekey/Makefile.3.0 b/keyboard/teensy_lc_onekey/Makefile.3.0 new file mode 100644 index 00000000..a2f98c7e --- /dev/null +++ b/keyboard/teensy_lc_onekey/Makefile.3.0 @@ -0,0 +1,77 @@ +# Target file name (without extension). +PROJECT = ch + +# Directory common source files exist +TMK_DIR = ../../tmk_core + +# Directory keyboard dependent files exist +TARGET_DIR = . + +# project specific files +SRC = matrix.c \ + led.c + +ifdef KEYMAP + SRC := keymap_$(KEYMAP).c $(SRC) +else + SRC := keymap_plain.c $(SRC) +endif + +CONFIG_H = config.h + +## chip/board settings +# - the next two should match the directories in +# /os/hal/ports/$(MCU_FAMILY)/$(MCU_SERIES) +# - For Teensies, FAMILY = KINETIS and SERIES is either +# KL2x (LC) or K20x (3.0,3.1,3.2). +MCU_FAMILY = KINETIS +MCU_SERIES = K20x + +# Linker script to use +# - it should exist either in /os/common/ports/ARMCMx/compilers/GCC/ld/ +# or /ld/ +# - NOTE: a custom ld script is needed for EEPROM on Teensy LC +# - LDSCRIPT = +# - MKL26Z64 for Teensy LC +# - MK20DX128 for Teensy 3.0 +# - MK20DX256 for Teensy 3.1 and 3.2 +MCU_LDSCRIPT = MK20DX128 + +# Startup code to use +# - it should exist in /os/common/ports/ARMCMx/compilers/GCC/mk/ +# - STARTUP = +# - kl2x for Teensy LC +# - k20x5 for Teensy 3.0 +# - k20x7 for Teensy 3.1 and 3.2 +MCU_STARTUP = k20x5 + +# Board: it should exist either in /os/hal/boards/ +# or /boards +# - BOARD = +# - PJRC_TEENSY_LC for Teensy LC +# - PJRC_TEENSY_3 for Teensy 3.0 +# - PJRC_TEENSY_3_1 for Teensy 3.1 or 3.2 +BOARD = PJRC_TEENSY_3 + +# Cortex version +# Teensy LC is cortex-m0; Teensy 3.x are cortex-m4 +MCU = cortex-m0 + +# ARM version, CORTEX-M0/M1 are 6, CORTEX-M3/M4/M7 are 7 +# I.e. 6 for Teensy LC; 7 for Teensy 3.x +ARMV = 7 + +# Build Options +# comment out to disable the options. +# +BOOTMAGIC_ENABLE = yes # Virtual DIP switch configuration +## (Note that for BOOTMAGIC on Teensy LC you have to use a custom .ld script.) +MOUSEKEY_ENABLE = yes # Mouse keys +EXTRAKEY_ENABLE = yes # Audio control and System control +CONSOLE_ENABLE = yes # Console for debug +COMMAND_ENABLE = yes # Commands for debug and configuration +SLEEP_LED_ENABLE = yes # Breathing sleep LED during USB suspend +NKRO_ENABLE = yes # USB Nkey Rollover + +include $(TMK_DIR)/tool/chibios/common.mk +include $(TMK_DIR)/tool/chibios/chibios.mk diff --git a/keyboard/teensy_lc_onekey/chconf.h b/keyboard/teensy_lc_onekey/chconf.h new file mode 100644 index 00000000..50cb1be4 --- /dev/null +++ b/keyboard/teensy_lc_onekey/chconf.h @@ -0,0 +1,499 @@ +/* + ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +/** + * @file templates/chconf.h + * @brief Configuration file template. + * @details A copy of this file must be placed in each project directory, it + * contains the application specific kernel settings. + * + * @addtogroup config + * @details Kernel related settings and hooks. + * @{ + */ + +#ifndef _CHCONF_H_ +#define _CHCONF_H_ + +/*===========================================================================*/ +/** + * @name System timers settings + * @{ + */ +/*===========================================================================*/ + +/** + * @brief System time counter resolution. + * @note Allowed values are 16 or 32 bits. + */ +#define CH_CFG_ST_RESOLUTION 32 + +/** + * @brief System tick frequency. + * @details Frequency of the system timer that drives the system ticks. This + * setting also defines the system tick time unit. + */ +#define CH_CFG_ST_FREQUENCY 1000 + +/** + * @brief Time delta constant for the tick-less mode. + * @note If this value is zero then the system uses the classic + * periodic tick. This value represents the minimum number + * of ticks that is safe to specify in a timeout directive. + * The value one is not valid, timeouts are rounded up to + * this value. + */ +#define CH_CFG_ST_TIMEDELTA 0 + +/** @} */ + +/*===========================================================================*/ +/** + * @name Kernel parameters and options + * @{ + */ +/*===========================================================================*/ + +/** + * @brief Round robin interval. + * @details This constant is the number of system ticks allowed for the + * threads before preemption occurs. Setting this value to zero + * disables the preemption for threads with equal priority and the + * round robin becomes cooperative. Note that higher priority + * threads can still preempt, the kernel is always preemptive. + * @note Disabling the round robin preemption makes the kernel more compact + * and generally faster. + * @note The round robin preemption is not supported in tickless mode and + * must be set to zero in that case. + */ +#define CH_CFG_TIME_QUANTUM 20 + +/** + * @brief Managed RAM size. + * @details Size of the RAM area to be managed by the OS. If set to zero + * then the whole available RAM is used. The core memory is made + * available to the heap allocator and/or can be used directly through + * the simplified core memory allocator. + * + * @note In order to let the OS manage the whole RAM the linker script must + * provide the @p __heap_base__ and @p __heap_end__ symbols. + * @note Requires @p CH_CFG_USE_MEMCORE. + */ +#define CH_CFG_MEMCORE_SIZE 0 + +/** + * @brief Idle thread automatic spawn suppression. + * @details When this option is activated the function @p chSysInit() + * does not spawn the idle thread. The application @p main() + * function becomes the idle thread and must implement an + * infinite loop. + */ +#define CH_CFG_NO_IDLE_THREAD FALSE + +/** @} */ + +/*===========================================================================*/ +/** + * @name Performance options + * @{ + */ +/*===========================================================================*/ + +/** + * @brief OS optimization. + * @details If enabled then time efficient rather than space efficient code + * is used when two possible implementations exist. + * + * @note This is not related to the compiler optimization options. + * @note The default is @p TRUE. + */ +#define CH_CFG_OPTIMIZE_SPEED TRUE + +/** @} */ + +/*===========================================================================*/ +/** + * @name Subsystem options + * @{ + */ +/*===========================================================================*/ + +/** + * @brief Time Measurement APIs. + * @details If enabled then the time measurement APIs are included in + * the kernel. + * + * @note The default is @p TRUE. + */ +#define CH_CFG_USE_TM FALSE + +/** + * @brief Threads registry APIs. + * @details If enabled then the registry APIs are included in the kernel. + * + * @note The default is @p TRUE. + */ +#define CH_CFG_USE_REGISTRY TRUE + +/** + * @brief Threads synchronization APIs. + * @details If enabled then the @p chThdWait() function is included in + * the kernel. + * + * @note The default is @p TRUE. + */ +#define CH_CFG_USE_WAITEXIT TRUE + +/** + * @brief Semaphores APIs. + * @details If enabled then the Semaphores APIs are included in the kernel. + * + * @note The default is @p TRUE. + */ +#define CH_CFG_USE_SEMAPHORES TRUE + +/** + * @brief Semaphores queuing mode. + * @details If enabled then the threads are enqueued on semaphores by + * priority rather than in FIFO order. + * + * @note The default is @p FALSE. Enable this if you have special + * requirements. + * @note Requires @p CH_CFG_USE_SEMAPHORES. + */ +#define CH_CFG_USE_SEMAPHORES_PRIORITY TRUE + +/** + * @brief Mutexes APIs. + * @details If enabled then the mutexes APIs are included in the kernel. + * + * @note The default is @p TRUE. + */ +#define CH_CFG_USE_MUTEXES TRUE + +/** + * @brief Enables recursive behavior on mutexes. + * @note Recursive mutexes are heavier and have an increased + * memory footprint. + * + * @note The default is @p FALSE. + * @note Requires @p CH_CFG_USE_MUTEXES. + */ +#define CH_CFG_USE_MUTEXES_RECURSIVE FALSE + +/** + * @brief Conditional Variables APIs. + * @details If enabled then the conditional variables APIs are included + * in the kernel. + * + * @note The default is @p TRUE. + * @note Requires @p CH_CFG_USE_MUTEXES. + */ +#define CH_CFG_USE_CONDVARS TRUE + +/** + * @brief Conditional Variables APIs with timeout. + * @details If enabled then the conditional variables APIs with timeout + * specification are included in the kernel. + * + * @note The default is @p TRUE. + * @note Requires @p CH_CFG_USE_CONDVARS. + */ +#define CH_CFG_USE_CONDVARS_TIMEOUT TRUE + +/** + * @brief Events Flags APIs. + * @details If enabled then the event flags APIs are included in the kernel. + * + * @note The default is @p TRUE. + */ +#define CH_CFG_USE_EVENTS TRUE + +/** + * @brief Events Flags APIs with timeout. + * @details If enabled then the events APIs with timeout specification + * are included in the kernel. + * + * @note The default is @p TRUE. + * @note Requires @p CH_CFG_USE_EVENTS. + */ +#define CH_CFG_USE_EVENTS_TIMEOUT TRUE + +/** + * @brief Synchronous Messages APIs. + * @details If enabled then the synchronous messages APIs are included + * in the kernel. + * + * @note The default is @p TRUE. + */ +#define CH_CFG_USE_MESSAGES TRUE + +/** + * @brief Synchronous Messages queuing mode. + * @details If enabled then messages are served by priority rather than in + * FIFO order. + * + * @note The default is @p FALSE. Enable this if you have special + * requirements. + * @note Requires @p CH_CFG_USE_MESSAGES. + */ +#define CH_CFG_USE_MESSAGES_PRIORITY FALSE + +/** + * @brief Mailboxes APIs. + * @details If enabled then the asynchronous messages (mailboxes) APIs are + * included in the kernel. + * + * @note The default is @p TRUE. + * @note Requires @p CH_CFG_USE_SEMAPHORES. + */ +#define CH_CFG_USE_MAILBOXES TRUE + +/** + * @brief I/O Queues APIs. + * @details If enabled then the I/O queues APIs are included in the kernel. + * + * @note The default is @p TRUE. + */ +#define CH_CFG_USE_QUEUES TRUE + +/** + * @brief Core Memory Manager APIs. + * @details If enabled then the core memory manager APIs are included + * in the kernel. + * + * @note The default is @p TRUE. + */ +#define CH_CFG_USE_MEMCORE TRUE + +/** + * @brief Heap Allocator APIs. + * @details If enabled then the memory heap allocator APIs are included + * in the kernel. + * + * @note The default is @p TRUE. + * @note Requires @p CH_CFG_USE_MEMCORE and either @p CH_CFG_USE_MUTEXES or + * @p CH_CFG_USE_SEMAPHORES. + * @note Mutexes are recommended. + */ +#define CH_CFG_USE_HEAP TRUE + +/** + * @brief Memory Pools Allocator APIs. + * @details If enabled then the memory pools allocator APIs are included + * in the kernel. + * + * @note The default is @p TRUE. + */ +#define CH_CFG_USE_MEMPOOLS TRUE + +/** + * @brief Dynamic Threads APIs. + * @details If enabled then the dynamic threads creation APIs are included + * in the kernel. + * + * @note The default is @p TRUE. + * @note Requires @p CH_CFG_USE_WAITEXIT. + * @note Requires @p CH_CFG_USE_HEAP and/or @p CH_CFG_USE_MEMPOOLS. + */ +#define CH_CFG_USE_DYNAMIC TRUE + +/** @} */ + +/*===========================================================================*/ +/** + * @name Debug options + * @{ + */ +/*===========================================================================*/ + +/** + * @brief Debug option, kernel statistics. + * + * @note The default is @p FALSE. + */ +#define CH_DBG_STATISTICS FALSE + +/** + * @brief Debug option, system state check. + * @details If enabled the correct call protocol for system APIs is checked + * at runtime. + * + * @note The default is @p FALSE. + */ +#define CH_DBG_SYSTEM_STATE_CHECK TRUE + +/** + * @brief Debug option, parameters checks. + * @details If enabled then the checks on the API functions input + * parameters are activated. + * + * @note The default is @p FALSE. + */ +#define CH_DBG_ENABLE_CHECKS TRUE + +/** + * @brief Debug option, consistency checks. + * @details If enabled then all the assertions in the kernel code are + * activated. This includes consistency checks inside the kernel, + * runtime anomalies and port-defined checks. + * + * @note The default is @p FALSE. + */ +#define CH_DBG_ENABLE_ASSERTS TRUE + +/** + * @brief Debug option, trace buffer. + * @details If enabled then the context switch circular trace buffer is + * activated. + * + * @note The default is @p FALSE. + */ +#define CH_DBG_ENABLE_TRACE TRUE + +/** + * @brief Debug option, stack checks. + * @details If enabled then a runtime stack check is performed. + * + * @note The default is @p FALSE. + * @note The stack check is performed in a architecture/port dependent way. + * It may not be implemented or some ports. + * @note The default failure mode is to halt the system with the global + * @p panic_msg variable set to @p NULL. + */ +#define CH_DBG_ENABLE_STACK_CHECK TRUE + +/** + * @brief Debug option, stacks initialization. + * @details If enabled then the threads working area is filled with a byte + * value when a thread is created. This can be useful for the + * runtime measurement of the used stack. + * + * @note The default is @p FALSE. + */ +#define CH_DBG_FILL_THREADS TRUE + +/** + * @brief Debug option, threads profiling. + * @details If enabled then a field is added to the @p thread_t structure that + * counts the system ticks occurred while executing the thread. + * + * @note The default is @p FALSE. + * @note This debug option is not currently compatible with the + * tickless mode. + */ +#define CH_DBG_THREADS_PROFILING FALSE + +/** @} */ + +/*===========================================================================*/ +/** + * @name Kernel hooks + * @{ + */ +/*===========================================================================*/ + +/** + * @brief Threads descriptor structure extension. + * @details User fields added to the end of the @p thread_t structure. + */ +#define CH_CFG_THREAD_EXTRA_FIELDS \ + /* Add threads custom fields here.*/ + +/** + * @brief Threads initialization hook. + * @details User initialization code added to the @p chThdInit() API. + * + * @note It is invoked from within @p chThdInit() and implicitly from all + * the threads creation APIs. + */ +#define CH_CFG_THREAD_INIT_HOOK(tp) { \ + /* Add threads initialization code here.*/ \ +} + +/** + * @brief Threads finalization hook. + * @details User finalization code added to the @p chThdExit() API. + * + * @note It is inserted into lock zone. + * @note It is also invoked when the threads simply return in order to + * terminate. + */ +#define CH_CFG_THREAD_EXIT_HOOK(tp) { \ + /* Add threads finalization code here.*/ \ +} + +/** + * @brief Context switch hook. + * @details This hook is invoked just before switching between threads. + */ +#define CH_CFG_CONTEXT_SWITCH_HOOK(ntp, otp) { \ + /* Context switch code here.*/ \ +} + +/** + * @brief Idle thread enter hook. + * @note This hook is invoked within a critical zone, no OS functions + * should be invoked from here. + * @note This macro can be used to activate a power saving mode. + */ +#define CH_CFG_IDLE_ENTER_HOOK() { \ +} + +/** + * @brief Idle thread leave hook. + * @note This hook is invoked within a critical zone, no OS functions + * should be invoked from here. + * @note This macro can be used to deactivate a power saving mode. + */ +#define CH_CFG_IDLE_LEAVE_HOOK() { \ +} + +/** + * @brief Idle Loop hook. + * @details This hook is continuously invoked by the idle thread loop. + */ +#define CH_CFG_IDLE_LOOP_HOOK() { \ + /* Idle loop code here.*/ \ +} + +/** + * @brief System tick event hook. + * @details This hook is invoked in the system tick handler immediately + * after processing the virtual timers queue. + */ +#define CH_CFG_SYSTEM_TICK_HOOK() { \ + /* System tick event code here.*/ \ +} + +/** + * @brief System halt hook. + * @details This hook is invoked in case to a system halting error before + * the system is halted. + */ +#define CH_CFG_SYSTEM_HALT_HOOK(reason) { \ + /* System halt code here.*/ \ +} + +/** @} */ + +/*===========================================================================*/ +/* Port-specific settings (override port settings defaulted in chcore.h). */ +/*===========================================================================*/ + +#endif /* _CHCONF_H_ */ + +/** @} */ diff --git a/keyboard/teensy_lc_onekey/config.h b/keyboard/teensy_lc_onekey/config.h new file mode 100644 index 00000000..8063c57e --- /dev/null +++ b/keyboard/teensy_lc_onekey/config.h @@ -0,0 +1,74 @@ +/* +Copyright 2015 Jun Wako + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#ifndef CONFIG_H +#define CONFIG_H + + +/* USB Device descriptor parameter */ +#define VENDOR_ID 0xFEED +#define PRODUCT_ID 0x6464 +#define DEVICE_VER 0x0001 +/* in python2: list(u"whatever".encode('utf-16-le')) */ +/* at most 32 characters or the ugly hack in usb_main.c borks */ +#define MANUFACTURER "TMK" +#define USBSTR_MANUFACTURER 'T', '\x00', 'M', '\x00', 'K', '\x00', ' ', '\x00', '\xc6', '\x00' +#define PRODUCT "ChibiOS TMK test" +#define USBSTR_PRODUCT 'C', '\x00', 'h', '\x00', 'i', '\x00', 'b', '\x00', 'i', '\x00', 'O', '\x00', 'S', '\x00', ' ', '\x00', 'T', '\x00', 'M', '\x00', 'K', '\x00', ' ', '\x00', 't', '\x00', 'e', '\x00', 's', '\x00', 't', '\x00' +#define DESCRIPTION "TMK keyboard firmware over ChibiOS" + +/* key matrix size */ +#define MATRIX_ROWS 1 +#define MATRIX_COLS 1 + +/* define if matrix has ghost */ +//#define MATRIX_HAS_GHOST + +/* Set 0 if debouncing isn't needed */ +#define DEBOUNCE 5 + +/* Mechanical locking support. Use KC_LCAP, KC_LNUM or KC_LSCR instead in keymap */ +#define LOCKING_SUPPORT_ENABLE +/* Locking resynchronize hack */ +#define LOCKING_RESYNC_ENABLE + +/* key combination for command */ +#define IS_COMMAND() ( \ + keyboard_report->mods == (MOD_BIT(KC_LSHIFT) | MOD_BIT(KC_RSHIFT)) \ +) + + + +/* + * Feature disable options + * These options are also useful to firmware size reduction. + */ + +/* disable debug print */ +//#define NO_DEBUG + +/* disable print */ +//#define NO_PRINT + +/* disable action features */ +//#define NO_ACTION_LAYER +//#define NO_ACTION_TAPPING +//#define NO_ACTION_ONESHOT +//#define NO_ACTION_MACRO +//#define NO_ACTION_FUNCTION + +#endif diff --git a/keyboard/teensy_lc_onekey/halconf.h b/keyboard/teensy_lc_onekey/halconf.h new file mode 100644 index 00000000..0d4bc4d0 --- /dev/null +++ b/keyboard/teensy_lc_onekey/halconf.h @@ -0,0 +1,168 @@ +/* + ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +/** + * @file templates/halconf.h + * @brief HAL configuration header. + * @details HAL configuration file, this file allows to enable or disable the + * various device drivers from your application. You may also use + * this file in order to override the device drivers default settings. + * + * @addtogroup HAL_CONF + * @{ + */ + +#ifndef _HALCONF_H_ +#define _HALCONF_H_ + +#include "mcuconf.h" + +/** + * @brief Enables the PAL subsystem. + */ +#if !defined(HAL_USE_PAL) || defined(__DOXYGEN__) +#define HAL_USE_PAL TRUE +#endif + +/** + * @brief Enables the ADC subsystem. + */ +#if !defined(HAL_USE_ADC) || defined(__DOXYGEN__) +#define HAL_USE_ADC FALSE +#endif + +/** + * @brief Enables the CAN subsystem. + */ +#if !defined(HAL_USE_CAN) || defined(__DOXYGEN__) +#define HAL_USE_CAN FALSE +#endif + +/** + * @brief Enables the DAC subsystem. + */ +#if !defined(HAL_USE_DAC) || defined(__DOXYGEN__) +#define HAL_USE_DAC FALSE +#endif + +/** + * @brief Enables the EXT subsystem. + */ +#if !defined(HAL_USE_EXT) || defined(__DOXYGEN__) +#define HAL_USE_EXT FALSE +#endif + +/** + * @brief Enables the GPT subsystem. + */ +#if !defined(HAL_USE_GPT) || defined(__DOXYGEN__) +#define HAL_USE_GPT FALSE +#endif + +/** + * @brief Enables the I2C subsystem. + */ +#if !defined(HAL_USE_I2C) || defined(__DOXYGEN__) +#define HAL_USE_I2C FALSE +#endif + +/** + * @brief Enables the I2S subsystem. + */ +#if !defined(HAL_USE_I2S) || defined(__DOXYGEN__) +#define HAL_USE_I2S FALSE +#endif + +/** + * @brief Enables the ICU subsystem. + */ +#if !defined(HAL_USE_ICU) || defined(__DOXYGEN__) +#define HAL_USE_ICU FALSE +#endif + +/** + * @brief Enables the MAC subsystem. + */ +#if !defined(HAL_USE_MAC) || defined(__DOXYGEN__) +#define HAL_USE_MAC FALSE +#endif + +/** + * @brief Enables the MMC_SPI subsystem. + */ +#if !defined(HAL_USE_MMC_SPI) || defined(__DOXYGEN__) +#define HAL_USE_MMC_SPI FALSE +#endif + +/** + * @brief Enables the PWM subsystem. + */ +#if !defined(HAL_USE_PWM) || defined(__DOXYGEN__) +#define HAL_USE_PWM FALSE +#endif + +/** + * @brief Enables the RTC subsystem. + */ +#if !defined(HAL_USE_RTC) || defined(__DOXYGEN__) +#define HAL_USE_RTC FALSE +#endif + +/** + * @brief Enables the SDC subsystem. + */ +#if !defined(HAL_USE_SDC) || defined(__DOXYGEN__) +#define HAL_USE_SDC FALSE +#endif + +/** + * @brief Enables the SERIAL subsystem. + */ +#if !defined(HAL_USE_SERIAL) || defined(__DOXYGEN__) +#define HAL_USE_SERIAL FALSE +#endif + +/** + * @brief Enables the SERIAL over USB subsystem. + */ +#if !defined(HAL_USE_SERIAL_USB) || defined(__DOXYGEN__) +#define HAL_USE_SERIAL_USB FALSE +#endif + +/** + * @brief Enables the SPI subsystem. + */ +#if !defined(HAL_USE_SPI) || defined(__DOXYGEN__) +#define HAL_USE_SPI FALSE +#endif + +/** + * @brief Enables the UART subsystem. + */ +#if !defined(HAL_USE_UART) || defined(__DOXYGEN__) +#define HAL_USE_UART FALSE +#endif + +/** + * @brief Enables the USB subsystem. + */ +#if !defined(HAL_USE_USB) || defined(__DOXYGEN__) +#define HAL_USE_USB TRUE +#endif + +#endif /* _HALCONF_H_ */ + +/** @} */ diff --git a/keyboard/teensy_lc_onekey/instructions.md b/keyboard/teensy_lc_onekey/instructions.md new file mode 100644 index 00000000..b19b8984 --- /dev/null +++ b/keyboard/teensy_lc_onekey/instructions.md @@ -0,0 +1,62 @@ +# Teensy LC, 3.0, 3.1, 3.2 support + +These ARM Teensies are now supported through [chibios](http://chibios.org). + +You'll need to install an ARM toolchain, for instance from [gcc ARM embedded](https://launchpad.net/gcc-arm-embedded) website, or using your favourite package manager. After installing, you should be able to run `arm-none-eabi-gcc -v` in the command prompt and get sensible output. This toolchain is used instead of `avr-gcc`, which is only for AVR chips. Naturally you'll also need the usual development tools (e.g. `make`), just as in the AVR setting. + +Next, you'll need ChibiOS. The current release (3.0.2) does not have sufficient Kinetis support, so you'll need to get a patched version from [my fork](https://github.com/flabbergast/ChibiOS/tree/kinetis): you can download a current tree zipped from [here](https://github.com/flabbergast/ChibiOS/archive/kinetis.zip). Unpack the zip, rename the newly created `ChibiOS-kinetis` to `chibios`, and move it to `tmk/tool/chibios/` (so that the ChibiOS files reside in `tmk/tool/chibios/chibios`). + +This should be it. Running `make` in `keyboard/teensy_lc_onekey` should create a working firmware in `build/`, called `ch.hex`. + +For more notes about the ChibiOS backend in TMK, see `tmk_core/protocol/chibios/README.md`. + +## About this onekey example + +It's set up for Teensy LC. To use 3.x, you'll need to edit the `Makefile` (and comment out one line in `mcuconf.h`). A sample makefile for Teensy 3.0 is provided as `Makefile.3.0`, can be used without renaming with `make -f Makefile.3.0`. + +## Credits + +The USB support for Kinetis MCUs is due to RedoX. His ChibiOS fork is also [on github](https://github.com/RedoXyde/ChibiOS); but it doesn't include Teensy LC definitions. + +## Features that are not implemented yet + +Currently only the more fancy suspend features are not there (i.e. "breathing" LED during suspend, power saving during suspend, sending a wakeup packet). The rest should work fine (reports either way are welcome). + +# Matrix programming notes + +The notes below explain what commands can be used to examine and set the status of Teensy pins. + +## ChibiOS pin manipulation basics + +### Pins + +Each pin sits on a "port", each of which comprises at most 32 individual pins. +So for instance "PTC5" from Kinetis manual/datasheet refers to port C (or GPIOA), pin 5. Most functions dealing with pins take 2 parameters which specify the pin -- the first being the port, the second being the pin number. + +Within ChibiOS, there are definitions which simplify this a bit for the Teensies. `TEENSY_PINn_IOPORT` represents the port of the MCU's pin connected Teensy's PIN `n`, and `TEENSY_PINn` represents its MCU's pin number. + +### Mode + +A MCU pin can be in several modes. The basic command to set a pin mode is + + palSetPadMode(TEENSY_PINn_IOPORT, TEENSY_PINn, PAL_MODE_INPUT_PULLUP); + +The last parameter is the mode. For keyboards, the usual ones that are used are `PAL_MODE_INPUT_PULLUP` (input with a pullup), `PAL_MODE_INPUT_PULLDOWN` (input with a pulldown), `PAL_MODE_INPUT` (input floating, a.k.a. Hi-Z), `PAL_MODE_OUTPUT_PUSHPULL` (output in the Arduino sense -- can be then set HIGH or LOW). + +### Setting + +Pins are set HIGH (after they've been put into `OUTPUT_PUSHPULL` mode) by + + palSetPad(TEENSY_PINn_IOPORT, TEENSY_PINn); + +or set LOW by + + palClearPad(TEENSY_PINn_IOPORT, TEENSY_PINn); + +### Reading + +Reading pin status is done with + + palReadPad(TEENSY_PINn_IOPORT, TEENSY_PINn); + +The function returns either `PAL_HIGH` (actually `1`) or `PAL_LOW` (actually `0`). diff --git a/keyboard/teensy_lc_onekey/keymap_plain.c b/keyboard/teensy_lc_onekey/keymap_plain.c new file mode 100644 index 00000000..a8357489 --- /dev/null +++ b/keyboard/teensy_lc_onekey/keymap_plain.c @@ -0,0 +1,44 @@ +/* +Copyright 2012,2013 Jun Wako + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#include "keycode.h" +#include "action.h" +#include "action_macro.h" +#include "report.h" +#include "host.h" +#include "print.h" +#include "debug.h" +#include "keymap.h" + +static const uint8_t keymaps[][MATRIX_ROWS][MATRIX_COLS] = { + {{KC_BTLD}}, +}; // to test: KC_CAPS, KT_BTLD + +static const uint16_t fn_actions[] = { +}; + +/* translates key to keycode */ +uint8_t keymap_key_to_keycode(uint8_t layer, keypos_t key) +{ + return keymaps[(layer)][(key.row)][(key.col)]; +} + +/* translates Fn keycode to action */ +action_t keymap_fn_to_action(uint8_t keycode) +{ + return (action_t){ .code = fn_actions[FN_INDEX(keycode)] }; +} diff --git a/keyboard/teensy_lc_onekey/ld/MKL26Z64.ld b/keyboard/teensy_lc_onekey/ld/MKL26Z64.ld new file mode 100644 index 00000000..fd9102de --- /dev/null +++ b/keyboard/teensy_lc_onekey/ld/MKL26Z64.ld @@ -0,0 +1,161 @@ +/* + ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio. + + This file is part of ChibiOS. + + ChibiOS is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + ChibiOS is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +/* + * KL25Z64 memory setup. + */ + +ENTRY(Reset_Handler) + +MEMORY +{ + flash0 : org = 0x00000000, len = 0xc0 + flashcfg : org = 0x00000400, len = 0x10 + flash : org = 0x00000410, len = 62k - 0x410 + eeprom_emu : org = 0x0000F800, len = 2k + ram : org = 0x1FFFF800, len = 8k +} + +__ram_start__ = ORIGIN(ram); +__ram_size__ = LENGTH(ram); +__ram_end__ = __ram_start__ + __ram_size__; + +__eeprom_workarea_start__ = ORIGIN(eeprom_emu); +__eeprom_workarea_size__ = LENGTH(eeprom_emu); +__eeprom_workarea_end__ = __eeprom_workarea_start__ + __eeprom_workarea_size__; + +SECTIONS +{ + . = 0; + + .isr : ALIGN(4) SUBALIGN(4) + { + KEEP(*(.vectors)) + } > flash0 + + .cfmprotect : ALIGN(4) SUBALIGN(4) + { + KEEP(*(.cfmconfig)) + } > flashcfg + + _text = .; + + constructors : ALIGN(4) SUBALIGN(4) + { + PROVIDE(__init_array_start = .); + KEEP(*(SORT(.init_array.*))) + KEEP(*(.init_array)) + PROVIDE(__init_array_end = .); + } > flash + + destructors : ALIGN(4) SUBALIGN(4) + { + PROVIDE(__fini_array_start = .); + KEEP(*(.fini_array)) + KEEP(*(SORT(.fini_array.*))) + PROVIDE(__fini_array_end = .); + } > flash + + .text : ALIGN(4) SUBALIGN(4) + { + *(.text) + *(.text.*) + *(.rodata) + *(.rodata.*) + *(.glue_7t) + *(.glue_7) + *(.gcc*) + } > flash + + .ARM.extab : + { + *(.ARM.extab* .gnu.linkonce.armextab.*) + } > flash + + .ARM.exidx : { + PROVIDE(__exidx_start = .); + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + PROVIDE(__exidx_end = .); + } > flash + + .eh_frame_hdr : + { + *(.eh_frame_hdr) + } > flash + + .eh_frame : ONLY_IF_RO + { + *(.eh_frame) + } > flash + + .textalign : ONLY_IF_RO + { + . = ALIGN(8); + } > flash + + _etext = .; + _textdata = _etext; + + .stacks : + { + . = ALIGN(8); + __main_stack_base__ = .; + . += __main_stack_size__; + . = ALIGN(8); + __main_stack_end__ = .; + __process_stack_base__ = .; + __main_thread_stack_base__ = .; + . += __process_stack_size__; + . = ALIGN(8); + __process_stack_end__ = .; + __main_thread_stack_end__ = .; + } > ram + + .data : + { + . = ALIGN(4); + PROVIDE(_data = .); + *(.data) + . = ALIGN(4); + *(.data.*) + . = ALIGN(4); + *(.ramtext) + . = ALIGN(4); + PROVIDE(_edata = .); + } > ram AT > flash + + .bss : + { + . = ALIGN(4); + PROVIDE(_bss_start = .); + *(.bss) + . = ALIGN(4); + *(.bss.*) + . = ALIGN(4); + *(COMMON) + . = ALIGN(4); + PROVIDE(_bss_end = .); + } > ram +} + +PROVIDE(end = .); +_end = .; + +__heap_base__ = _end; +__heap_end__ = __ram_end__; diff --git a/keyboard/teensy_lc_onekey/led.c b/keyboard/teensy_lc_onekey/led.c new file mode 100644 index 00000000..dfa60c10 --- /dev/null +++ b/keyboard/teensy_lc_onekey/led.c @@ -0,0 +1,32 @@ +/* +Copyright 2012 Jun Wako + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#include "hal.h" + +#include "led.h" + + +void led_set(uint8_t usb_led) { + if (usb_led & (1< + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#include "ch.h" +#include "hal.h" + +/* + * scan matrix + */ +#include "print.h" +#include "debug.h" +#include "util.h" +#include "matrix.h" +#include "wait.h" + +#ifndef DEBOUNCE +# define DEBOUNCE 5 +#endif +static uint8_t debouncing = DEBOUNCE; + +/* matrix state(1:on, 0:off) */ +static matrix_row_t matrix[MATRIX_ROWS]; +static matrix_row_t matrix_debouncing[MATRIX_ROWS]; + +static matrix_row_t read_cols(void); +static void init_cols(void); +static void unselect_rows(void); +static void select_row(uint8_t row); + + +inline +uint8_t matrix_rows(void) +{ + return MATRIX_ROWS; +} + +inline +uint8_t matrix_cols(void) +{ + return MATRIX_COLS; +} + +#define LED_ON() do { palSetPad(TEENSY_PIN13_IOPORT, TEENSY_PIN13) ;} while (0) +#define LED_OFF() do { palClearPad(TEENSY_PIN13_IOPORT, TEENSY_PIN13); } while (0) +#define LED_TGL() do { palTogglePad(TEENSY_PIN13_IOPORT, TEENSY_PIN13); } while (0) + +void matrix_init(void) +{ + // initialize row and col + unselect_rows(); + init_cols(); + + // initialize matrix state: all keys off + for (uint8_t i=0; i < MATRIX_ROWS; i++) { + matrix[i] = 0; + matrix_debouncing[i] = 0; + } + + //debug + debug_matrix = true; + LED_ON(); + wait_ms(500); + LED_OFF(); +} + +uint8_t matrix_scan(void) +{ + for (uint8_t i = 0; i < MATRIX_ROWS; i++) { + select_row(i); + wait_us(30); // without this wait read unstable value. + matrix_row_t cols = read_cols(); + if (matrix_debouncing[i] != cols) { + matrix_debouncing[i] = cols; + if (debouncing) { + debug("bounce!: "); debug_hex(debouncing); debug("\n"); + } + debouncing = DEBOUNCE; + } + unselect_rows(); + } + + if (debouncing) { + if (--debouncing) { + wait_ms(1); + } else { + for (uint8_t i = 0; i < MATRIX_ROWS; i++) { + matrix[i] = matrix_debouncing[i]; + } + } + } + + return 1; +} + +inline +bool matrix_is_on(uint8_t row, uint8_t col) +{ + return (matrix[row] & ((matrix_row_t)1< Date: Wed, 14 Oct 2015 10:13:49 +0100 Subject: [PATCH 25/29] Chibios: use WFI in idle. WIP suspend stuff. --- keyboard/stm32_onekey/chconf.h | 4 ++ keyboard/stm32_onekey/keymap_plain.c | 2 +- keyboard/teensy_lc_onekey/chconf.h | 4 ++ keyboard/teensy_lc_onekey/instructions.md | 2 + keyboard/teensy_lc_onekey/keymap_plain.c | 4 +- tmk_core/common/chibios/sleep_led.c | 4 ++ tmk_core/common/chibios/suspend.c | 65 +++++++++++++++++++++-- tmk_core/protocol/chibios/main.c | 21 +++++++- tmk_core/protocol/chibios/usb_main.c | 8 +-- 9 files changed, 102 insertions(+), 12 deletions(-) diff --git a/keyboard/stm32_onekey/chconf.h b/keyboard/stm32_onekey/chconf.h index da4160b6..be362a95 100644 --- a/keyboard/stm32_onekey/chconf.h +++ b/keyboard/stm32_onekey/chconf.h @@ -103,6 +103,10 @@ */ #define CH_CFG_NO_IDLE_THREAD FALSE +/* Use __WFI in the idle thread for waiting. Does lower the power + * consumption. */ +#define CORTEX_ENABLE_WFI_IDLE TRUE + /** @} */ /*===========================================================================*/ diff --git a/keyboard/stm32_onekey/keymap_plain.c b/keyboard/stm32_onekey/keymap_plain.c index ea173935..8de1c027 100644 --- a/keyboard/stm32_onekey/keymap_plain.c +++ b/keyboard/stm32_onekey/keymap_plain.c @@ -25,7 +25,7 @@ along with this program. If not, see . #include "keymap.h" static const uint8_t keymaps[][MATRIX_ROWS][MATRIX_COLS] = { - {{KC_A}}, + {{KC_CAPS}}, // test with KC_CAPS, KC_A, KC_BTLD }; static const uint16_t fn_actions[] = { diff --git a/keyboard/teensy_lc_onekey/chconf.h b/keyboard/teensy_lc_onekey/chconf.h index 50cb1be4..ee527d47 100644 --- a/keyboard/teensy_lc_onekey/chconf.h +++ b/keyboard/teensy_lc_onekey/chconf.h @@ -103,6 +103,10 @@ */ #define CH_CFG_NO_IDLE_THREAD FALSE +/* Use __WFI in the idle thread for waiting. Does lower the power + * consumption. */ +#define CORTEX_ENABLE_WFI_IDLE TRUE + /** @} */ /*===========================================================================*/ diff --git a/keyboard/teensy_lc_onekey/instructions.md b/keyboard/teensy_lc_onekey/instructions.md index b19b8984..9a7aeece 100644 --- a/keyboard/teensy_lc_onekey/instructions.md +++ b/keyboard/teensy_lc_onekey/instructions.md @@ -16,6 +16,8 @@ It's set up for Teensy LC. To use 3.x, you'll need to edit the `Makefile` (and c ## Credits +TMK itself is written by hasu, original sources [here](https://github.com/tmk/tmk_keyboard). + The USB support for Kinetis MCUs is due to RedoX. His ChibiOS fork is also [on github](https://github.com/RedoXyde/ChibiOS); but it doesn't include Teensy LC definitions. ## Features that are not implemented yet diff --git a/keyboard/teensy_lc_onekey/keymap_plain.c b/keyboard/teensy_lc_onekey/keymap_plain.c index a8357489..922fa537 100644 --- a/keyboard/teensy_lc_onekey/keymap_plain.c +++ b/keyboard/teensy_lc_onekey/keymap_plain.c @@ -25,8 +25,8 @@ along with this program. If not, see . #include "keymap.h" static const uint8_t keymaps[][MATRIX_ROWS][MATRIX_COLS] = { - {{KC_BTLD}}, -}; // to test: KC_CAPS, KT_BTLD + {{KC_A}}, +}; // to test: KC_CAPS, KT_BTLD, KC_A static const uint16_t fn_actions[] = { }; diff --git a/tmk_core/common/chibios/sleep_led.c b/tmk_core/common/chibios/sleep_led.c index b08c9c2a..fad7ac04 100644 --- a/tmk_core/common/chibios/sleep_led.c +++ b/tmk_core/common/chibios/sleep_led.c @@ -4,6 +4,10 @@ #include "sleep_led.h" void sleep_led_init(void) { + // we could go the 'software way' -- just enable *some* timer + // and go with callbacks + // or we could go the 'hardware way' -- and use timer output to + // pins directly } void sleep_led_enable(void) { diff --git a/tmk_core/common/chibios/suspend.c b/tmk_core/common/chibios/suspend.c index 49ecad43..6ca16034 100644 --- a/tmk_core/common/chibios/suspend.c +++ b/tmk_core/common/chibios/suspend.c @@ -1,8 +1,65 @@ /* TODO */ -#include +#include "ch.h" +#include "hal.h" +#include "matrix.h" +#include "action.h" +#include "action_util.h" +#include "mousekey.h" +#include "host.h" +#include "backlight.h" +#include "suspend.h" -void suspend_power_down(void) {} -bool suspend_wakeup_condition(void) { return true; } -void suspend_wakeup_init(void) {} +void suspend_idle(uint8_t time) { + // TODO: this is not used anywhere - what units is 'time' in? + chThdSleepMilliseconds(time); +} + +void suspend_power_down(void) { + // TODO: figure out what to power down and how + // shouldn't power down TPM/FTM if we want a breathing LED + // also shouldn't power down USB + + // on AVR, this enables the watchdog for 15ms (max), and goes to + // SLEEP_MODE_PWR_DOWN + + chThdSleepMilliseconds(17); +} + +__attribute__ ((weak)) void matrix_power_up(void) {} +__attribute__ ((weak)) void matrix_power_down(void) {} +bool suspend_wakeup_condition(void) +{ + matrix_power_up(); + matrix_scan(); + matrix_power_down(); + for (uint8_t r = 0; r < MATRIX_ROWS; r++) { + if (matrix_get_row(r)) return true; + } + return false; +} + +// run immediately after wakeup +void suspend_wakeup_init(void) +{ + // clear keyboard state + // need to do it manually, because we're running from ISR + // and clear_keyboard() calls print + // so only clear the variables in memory + // the reports will be sent from main.c afterwards + // or if the PC asks for GET_REPORT + clear_mods(); + clear_weak_mods(); + clear_keys(); +#ifdef MOUSEKEY_ENABLE + mousekey_clear(); +#endif /* MOUSEKEY_ENABLE */ +#ifdef EXTRAKEY_ENABLE + host_system_send(0); + host_consumer_send(0); +#endif /* EXTRAKEY_ENABLE */ +#ifdef BACKLIGHT_ENABLE + backlight_init(); +#endif /* BACKLIGHT_ENABLE */ +} diff --git a/tmk_core/protocol/chibios/main.c b/tmk_core/protocol/chibios/main.c index b2526d14..c4666ebd 100644 --- a/tmk_core/protocol/chibios/main.c +++ b/tmk_core/protocol/chibios/main.c @@ -26,6 +26,8 @@ #include "host_driver.h" #include "keyboard.h" #include "action.h" +#include "action_util.h" +#include "mousekey.h" #include "led.h" #include "sendchar.h" #include "debug.h" @@ -113,7 +115,24 @@ int main(void) { /* Main loop */ while(true) { - /* TODO: check for suspended event */ + + if(USB_DRIVER.state == USB_SUSPENDED) { + print("[s]"); + while(USB_DRIVER.state == USB_SUSPENDED) { + /* Do this in the suspended state */ + suspend_power_down(); // on AVR this deep sleeps for 15ms + // TODO: remote wakeup + // if(USB_Device_RemoteWakeupEnabled (USB_DRIVER.status & 2) && suspend_wakeup_condition()) { + // USB_Device_SendRemoteWakeup(); + // } + } + /* Woken up */ + // variables has been already cleared by the wakeup hook + send_keyboard_report(); +#ifdef MOUSEKEY_ENABLE + mousekey_send(); +#endif /* MOUSEKEY_ENABLE */ + } keyboard_task(); chThdSleepMilliseconds(5); diff --git a/tmk_core/protocol/chibios/usb_main.c b/tmk_core/protocol/chibios/usb_main.c index 2625c425..872d1c65 100644 --- a/tmk_core/protocol/chibios/usb_main.c +++ b/tmk_core/protocol/chibios/usb_main.c @@ -22,6 +22,7 @@ #include "host.h" #include "debug.h" +#include "suspend.h" #ifdef SLEEP_LED_ENABLE #include "sleep_led.h" #include "led.h" @@ -356,8 +357,8 @@ static const uint8_t hid_configuration_descriptor_data[] = { NUM_INTERFACES, // bNumInterfaces 1, // bConfigurationValue 0, // iConfiguration - 0xA0, // bmAttributes - 50), // bMaxPower (100mA) + 0xA0, // bmAttributes (RESERVED|REMOTEWAKEUP) + 50), // bMaxPower (50mA) /* Interface Descriptor (9 bytes) USB spec 9.6.5, page 267-269, Table 9-12 */ USB_DESC_INTERFACE(KBD_INTERFACE, // bInterfaceNumber @@ -793,7 +794,6 @@ static void usb_event_cb(USBDriver *usbp, usbevent_t event) { case USB_EVENT_SUSPEND: //TODO: from ISR! print("[S]"); - //TODO: signal suspend? #ifdef SLEEP_LED_ENABLE sleep_led_enable(); #endif /* SLEEP_LED_ENABLE */ @@ -801,7 +801,7 @@ static void usb_event_cb(USBDriver *usbp, usbevent_t event) { case USB_EVENT_WAKEUP: //TODO: from ISR! print("[W]"); - //TODO: suspend_wakeup_init(); + suspend_wakeup_init(); #ifdef SLEEP_LED_ENABLE sleep_led_disable(); // NOTE: converters may not accept this From b25da7a51df91a73520df5f5120478438d84dad7 Mon Sep 17 00:00:00 2001 From: flabbergast Date: Wed, 14 Oct 2015 10:35:45 +0100 Subject: [PATCH 26/29] Update chibi/teensy instructions. --- keyboard/teensy_lc_onekey/instructions.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/keyboard/teensy_lc_onekey/instructions.md b/keyboard/teensy_lc_onekey/instructions.md index 9a7aeece..4d8e51df 100644 --- a/keyboard/teensy_lc_onekey/instructions.md +++ b/keyboard/teensy_lc_onekey/instructions.md @@ -4,7 +4,9 @@ These ARM Teensies are now supported through [chibios](http://chibios.org). You'll need to install an ARM toolchain, for instance from [gcc ARM embedded](https://launchpad.net/gcc-arm-embedded) website, or using your favourite package manager. After installing, you should be able to run `arm-none-eabi-gcc -v` in the command prompt and get sensible output. This toolchain is used instead of `avr-gcc`, which is only for AVR chips. Naturally you'll also need the usual development tools (e.g. `make`), just as in the AVR setting. -Next, you'll need ChibiOS. The current release (3.0.2) does not have sufficient Kinetis support, so you'll need to get a patched version from [my fork](https://github.com/flabbergast/ChibiOS/tree/kinetis): you can download a current tree zipped from [here](https://github.com/flabbergast/ChibiOS/archive/kinetis.zip). Unpack the zip, rename the newly created `ChibiOS-kinetis` to `chibios`, and move it to `tmk/tool/chibios/` (so that the ChibiOS files reside in `tmk/tool/chibios/chibios`). +You'll need this fork/branch of TMK. If you're reading this from your own hard drive, then you already have it ;) Anyway, you can get a zip from [here](https://https://github.com/flabbergast/tmk_keyboard/archive/chibios.zip) {or clone this repo from github and checkout the `chibios` branch}. + +Next, you'll need ChibiOS. The current release (3.0.2) does not have sufficient Kinetis support, so you'll need to get a patched version from [my fork](https://github.com/flabbergast/ChibiOS/tree/kinetis): you can download a current tree zipped from [here](https://github.com/flabbergast/ChibiOS/archive/kinetis.zip) {or clone that repo from github and checkout the `kinetis` branch}. Unpack the zip, rename the newly created `ChibiOS-kinetis` to `chibios`, and move it to `tmk/tool/chibios/` (so that the ChibiOS files reside in `tmk/tool/chibios/chibios`). This should be it. Running `make` in `keyboard/teensy_lc_onekey` should create a working firmware in `build/`, called `ch.hex`. From aa2c56823574b56735b81e5db08bd9c2ec501294 Mon Sep 17 00:00:00 2001 From: flabbergast Date: Wed, 14 Oct 2015 18:04:25 +0100 Subject: [PATCH 27/29] Update chibios/Teensy instructions. --- keyboard/teensy_lc_onekey/instructions.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/keyboard/teensy_lc_onekey/instructions.md b/keyboard/teensy_lc_onekey/instructions.md index 4d8e51df..ed355e29 100644 --- a/keyboard/teensy_lc_onekey/instructions.md +++ b/keyboard/teensy_lc_onekey/instructions.md @@ -57,6 +57,16 @@ or set LOW by palClearPad(TEENSY_PINn_IOPORT, TEENSY_PINn); +Toggling can be done with + + palTogglePad(TEENSY_PINn_IOPORT, TEENSY_PINn); + +Alternatively, you can use + + palWritePad(TEENSY_PINn_IOPORT, TEENSY_PINn, bit); + +where `bit` is either `PAL_LOW` or `PAL_HIGH` (i.e. `0` or `1`). + ### Reading Reading pin status is done with @@ -64,3 +74,7 @@ Reading pin status is done with palReadPad(TEENSY_PINn_IOPORT, TEENSY_PINn); The function returns either `PAL_HIGH` (actually `1`) or `PAL_LOW` (actually `0`). + +### Further docs + +All the commands that are available for pin manipulation through ChibiOS HAL are documented in [ChibiOS PAL driver docs](http://chibios.sourceforge.net/docs3/hal/group___p_a_l.html). From 2e06ccf70a7f86e4abeaf5cec73886c909a2f7a9 Mon Sep 17 00:00:00 2001 From: flabbergast Date: Wed, 14 Oct 2015 19:55:09 +0100 Subject: [PATCH 28/29] ChibiOS/kinetis: sending remote wakeup. --- tmk_core/protocol/chibios/main.c | 8 ++++---- tmk_core/protocol/chibios/usb_main.c | 17 +++++++++++++++++ tmk_core/protocol/chibios/usb_main.h | 3 +++ 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/tmk_core/protocol/chibios/main.c b/tmk_core/protocol/chibios/main.c index c4666ebd..9607f1a9 100644 --- a/tmk_core/protocol/chibios/main.c +++ b/tmk_core/protocol/chibios/main.c @@ -121,10 +121,10 @@ int main(void) { while(USB_DRIVER.state == USB_SUSPENDED) { /* Do this in the suspended state */ suspend_power_down(); // on AVR this deep sleeps for 15ms - // TODO: remote wakeup - // if(USB_Device_RemoteWakeupEnabled (USB_DRIVER.status & 2) && suspend_wakeup_condition()) { - // USB_Device_SendRemoteWakeup(); - // } + /* Remote wakeup */ + if((USB_DRIVER.status & 2) && suspend_wakeup_condition()) { + send_remote_wakeup(&USB_DRIVER); + } } /* Woken up */ // variables has been already cleared by the wakeup hook diff --git a/tmk_core/protocol/chibios/usb_main.c b/tmk_core/protocol/chibios/usb_main.c index 872d1c65..09de7196 100644 --- a/tmk_core/protocol/chibios/usb_main.c +++ b/tmk_core/protocol/chibios/usb_main.c @@ -1024,6 +1024,23 @@ void init_usb_driver(USBDriver *usbp) { #endif } +/* + * Send remote wakeup packet + * Note: should not be called from ISR + */ +void send_remote_wakeup(USBDriver *usbp) { + (void)usbp; +#if defined(K20x) || defined(KL2x) +#if KINETIS_USB_USE_USB0 + USB0->CTL |= USBx_CTL_RESUME; + chThdSleepMilliseconds(15); + USB0->CTL &= ~USBx_CTL_RESUME; +#endif /* KINETIS_USB_USE_USB0 */ +#else /* K20x || KL2x */ +#warning Sending remote wakeup packet not implemented for your platform. +#endif /* K20x || KL2x */ +} + /* --------------------------------------------------------- * Keyboard functions * --------------------------------------------------------- diff --git a/tmk_core/protocol/chibios/usb_main.h b/tmk_core/protocol/chibios/usb_main.h index 85ea9153..d8f30e95 100644 --- a/tmk_core/protocol/chibios/usb_main.h +++ b/tmk_core/protocol/chibios/usb_main.h @@ -36,6 +36,9 @@ /* Initialize the USB driver and bus */ void init_usb_driver(USBDriver *usbp); +/* Send remote wakeup packet */ +void send_remote_wakeup(USBDriver *usbp); + /* --------------- * Keyboard header * --------------- From 6def1045305aaf9c539b5ebbe04232a4c83662ec Mon Sep 17 00:00:00 2001 From: flabbergast Date: Thu, 15 Oct 2015 09:34:51 +0100 Subject: [PATCH 29/29] ChibiOS/STM32: send remote wakeup. --- tmk_core/protocol/chibios/usb_main.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tmk_core/protocol/chibios/usb_main.c b/tmk_core/protocol/chibios/usb_main.c index 09de7196..382966b9 100644 --- a/tmk_core/protocol/chibios/usb_main.c +++ b/tmk_core/protocol/chibios/usb_main.c @@ -1036,7 +1036,11 @@ void send_remote_wakeup(USBDriver *usbp) { chThdSleepMilliseconds(15); USB0->CTL &= ~USBx_CTL_RESUME; #endif /* KINETIS_USB_USE_USB0 */ -#else /* K20x || KL2x */ +#elif defined(STM32F0XX) /* K20x || KL2x */ + STM32_USB->CNTR |= CNTR_RESUME; + chThdSleepMilliseconds(15); + STM32_USB->CNTR &= ~CNTR_RESUME; +#else /* STM32F0XX */ #warning Sending remote wakeup packet not implemented for your platform. #endif /* K20x || KL2x */ }