Browse Source

Use pi pico SDK rather than arduino for USB

The keypad isn't working yet but I'm hopeful.
master
Macoy Madson 5 months ago
parent
commit
220a39d7c8
  1. 5
      .gitignore
  2. 25
      BuildPico.sh
  3. 4
      FlashPico.sh
  4. 61
      ReadMe.org
  5. 46
      src/CMakeLists.txt
  6. 9
      src/Config_RP2040.cake
  7. 0
      src/KeypadArduino.cake
  8. 192
      src/KeypadPico.cake
  9. 59
      src/pico_extras_import_optional.cmake
  10. 73
      src/pico_sdk_import.cmake
  11. 111
      src/tusb_config.h
  12. 233
      src/usb_descriptors.c
  13. 37
      src/usb_descriptors.h

5
.gitignore

@ -72,11 +72,8 @@ UserData.bin
UserData.cakedata
UserData_TestWrite.cakedata
# TODO Make this less general
*.txt
autoTest
.vs/
game-dev-environment
build/

25
BuildPico.sh

@ -0,0 +1,25 @@
#!/bin/sh
CAKELISP_DIR=Dependencies/cakelisp
# Build Cakelisp itself
echo "\n\nCakelisp\n\n"
cd $CAKELISP_DIR
./Build.sh || exit $?
cd ../..
echo "\n\nKeyboards\n\n"
CAKELISP=./Dependencies/cakelisp/bin/cakelisp
#
# Keypad
#
$CAKELISP --verbose-processes --skip-build \
src/Config_RP2040.cake \
src/KeypadPico.cake || exit $?
cd build || exit $?
make -j || exit $?

4
FlashPico.sh

@ -0,0 +1,4 @@
#!/bin/sh
sudo /home/macoy/Development/code/3rdParty/repositories/picotool/build/picotool load build/keypad.uf2 || exit $?
sudo /home/macoy/Development/code/3rdParty/repositories/picotool/build/picotool verify build/keypad.uf2 || exit $?

61
ReadMe.org

@ -3,6 +3,67 @@
This is my dumping ground for various physical keyboard firmware and designs.
* Building and running
** Via Raspberry Pi Pico
*** Initial setup
- See [[https://datasheets.raspberrypi.com/pico/getting-started-with-pico.pdf][Getting started with Pico]] and [[https://github.com/raspberrypi/pico-sdk][pico-sdk readme]]
#+BEGIN_SRC sh
# Get all the compilers and code
sudo apt install cmake gcc-arm-none-eabi libnewlib-arm-none-eabi libstdc++-arm-none-eabi-newlib
git clone https://github.com/raspberrypi/pico-sdk
cd pico-sdk
git submodule update --init
cd lib/tinyusb
git submodule update --init
cd ../../../
# Get picotool for flashing
git clone https://github.com/raspberrypi/picotool.git --branch master
cd picotool
mkdir build
cd build
cmake .. -DPICO_SDK_PATH=/home/macoy/Development/code/3rdParty/repositories/pico-sdk
#+END_SRC
To get the pico examples working:
#+BEGIN_SRC sh
git clone https://github.com/raspberrypi/pico-examples
cd pico-examples
mkdir build
cd build
cmake .. -DPICO_SDK_PATH=/home/macoy/Development/code/3rdParty/repositories/pico-sdk -DPICO_BOARD=adafruit_kb2040
make -j
#+END_SRC
Example flashing:
- Hold down the boot button and plug in the board
- Run in ~picotool/build~:
#+BEGIN_SRC sh
sudo ./picotool load ../../pico-examples/build/usb/device/dev_hid_composite/dev_hid_composite.uf2
sudo ./picotool verify ../../pico-examples/build/usb/device/dev_hid_composite/dev_hid_composite.uf2
sudo ./picotool reboot
#+END_SRC
*** Building Keypad
Before flashing, plug in the kb2040 while holding the boot button down.
#+BEGIN_SRC sh
mkdir build
cd build
cmake .. -DPICO_SDK_PATH=/home/macoy/Development/code/3rdParty/repositories/pico-sdk -DPICO_BOARD=adafruit_kb2040
cd ../
./BuildPico.sh
./FlashPico.sh
#+END_SRC
Now, unplug and replug the pico or:
#+BEGIN_SRC sh
sudo /home/macoy/Development/code/3rdParty/repositories/picotool/build/picotool reboot
#+END_SRC
** Via Arduino (*old*, don't use)
Follow [[https://learn.adafruit.com/adafruit-kb2040/arduino-ide-setup][Arduino IDE Setup]].
In short:
- Get Arduino IDE (and Arduino Console while you're at it)

46
src/CMakeLists.txt

@ -0,0 +1,46 @@
cmake_minimum_required(VERSION 3.13)
cmake_minimum_required(VERSION 3.12)
# Pull in SDK (must be before project)
include(pico_sdk_import.cmake)
include(pico_extras_import_optional.cmake)
project(keypad_project C CXX ASM)
set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 17)
if (PICO_SDK_VERSION_STRING VERSION_LESS "1.3.0")
message(FATAL_ERROR "Raspberry Pi Pico SDK version 1.3.0 (or later) required. Your version is ${PICO_SDK_VERSION_STRING}")
endif()
# Initialize the SDK
pico_sdk_init()
add_compile_options(-Wall
-Wno-format # int != int32_t as far as the compiler is concerned because gcc has int32_t as long int
-Wno-unused-function # we have some for the docs that aren't called
)
if (CMAKE_C_COMPILER_ID STREQUAL "GNU")
add_compile_options(-Wno-maybe-uninitialized)
endif()
add_executable(keypad)
target_sources(keypad PUBLIC
${CMAKE_CURRENT_LIST_DIR}/../cakelisp_cache/Keypad/KeypadPico.cake.c
${CMAKE_CURRENT_LIST_DIR}/usb_descriptors.c
)
# Make sure TinyUSB can find tusb_config.h
target_include_directories(keypad PUBLIC
${CMAKE_CURRENT_LIST_DIR})
# In addition to pico_stdlib required for common PicoSDK functionality, add dependency on tinyusb_device
# for TinyUSB device support and tinyusb_board for the additional board support library used by the example
target_link_libraries(keypad PUBLIC pico_stdlib pico_unique_id tinyusb_device tinyusb_board)
# Uncomment this line to enable fix for Errata RP2040-E5 (the fix requires use of GPIO 15)
#target_compile_definitions(keypad PUBLIC PICO_RP2040_USB_DEVICE_ENUMERATION_FIX=1)
pico_add_extra_outputs(keypad)

9
src/Config_RP2040.cake

@ -1,10 +1 @@
(comptime-define-symbol 'Unix)
;; Uncomment for profiling
;; (comptime-define-symbol 'Profile)
(comptime-cond
('Profile
(add-build-options-global "-O3")
(add-cakelisp-search-directory "Dependencies/gamelib/src")
(import "ProfilerAutoInstrument.cake")))

0
src/Keypad.cake → src/KeypadArduino.cake

192
src/KeypadPico.cake

@ -0,0 +1,192 @@
;; Arduino build expects things to have specific names and extensions. We'll create a build label
;; just to make our build directory match, which appears to be necessary.
(add-build-config-label "Keypad")
(set-cakelisp-option cakelisp-src-dir "Dependencies/cakelisp/src")
(add-cakelisp-search-directory "Dependencies/gamelib/src")
(add-cakelisp-search-directory "Dependencies/cakelisp/runtime")
(add-cakelisp-search-directory "src")
(import "CHelpers.cake")
(c-import
;; sdk
"pico/stdlib.h"
"bsp/board.h"
"tusb.h"
;; Our stuff
"usb_descriptors.h"
"stdint.h")
(var row-pins (array (const int)) ;; Samples. Yellow wires.
(array 29 28 27 26)) ;; A3 A2 A1 A0
(var column-pins (array (const int)) ;; Sends power. White wires.
(array 2 3 4 5 6)) ;; 2 3 4 5 6
(var last-scan-matrix (array 4 (array 5 int)) (array 0))
(var matrix (array 4 (array 5 int)) (array 0))
(var matrix-to-keys (array 4 (array 5 char))
(array
(array 'n' '7' '4' '1' '0') ;; a3
(array '/' '8' '5' '2' '_') ;; a2
(array '*' '9' '6' '3' '.') ;; a1
(array '+' 'b' '_' '_' 'e'))) ;; a0
(var keycode-unused (const uint8_t) 0)
(var matrix-to-keycodes (array 4 (array 5 uint8_t))
(array
(array HID_KEY_NUM_LOCK HID_KEY_KEYPAD_7 HID_KEY_KEYPAD_4 HID_KEY_KEYPAD_1 HID_KEY_KEYPAD_0) ;; a3
(array HID_KEY_KEYPAD_DIVIDE HID_KEY_KEYPAD_8 HID_KEY_KEYPAD_5 HID_KEY_KEYPAD_2 keycode-unused) ;; a2
(array HID_KEY_KEYPAD_MULTIPLY HID_KEY_KEYPAD_9 HID_KEY_KEYPAD_6 HID_KEY_KEYPAD_3 HID_KEY_KEYPAD_DECIMAL) ;; a1
(array HID_KEY_KEYPAD_ADD HID_KEY_KEYPAD_SUBTRACT keycode-unused keycode-unused HID_KEY_KEYPAD_ENTER))) ;; a0
(defmacro print-line (line any)
;; (tokenize-push output (call-on println Serial (token-splice line)))
(return true))
(defun main (&return int)
(board_init)
(tusb_init)
;; (call-on begin Serial 115200)
;; (pinMode LED_BUILTIN OUTPUT)
(each-item-in-array row-pins row row-pin int
(gpio_init row-pin)
(gpio_set_dir row-pin GPIO_IN))
(each-item-in-array column-pins column col-pin int
(gpio_init col-pin)
(gpio_set_dir col-pin GPIO_IN)
(gpio_pull_up col-pin))
(while true
(tud_task)
(hid-task))
;; Should never happen
(return 1))
(defun hid-task ()
(var poll-interval-ms uint32_t 10)
(var-static start-ms uint32_t 0)
(when (< (- (board_millis) start-ms) poll-interval-ms)
;; (todo feature) Should this actually delay to save power?
(return))
(set start-ms (+ start-ms poll-interval-ms))
(scan-matrix)
(var any-key-pressed bool false)
(each-in-range (array-size row-pins) row
(each-in-range (array-size column-pins) column
(when (and (at row column matrix)
(not (at row column last-scan-matrix)))
(set any-key-pressed true))))
;; Wake up host if we are in suspend mode
;; and REMOTE_WAKEUP feature is enabled by host
(cond
((and any-key-pressed (tud_suspended))
(tud_remote_wakeup))
(true ;; Host is awake and should receive our report
(send-keyboard-report))))
(defun send-keyboard-report ()
(unless (tud_hid_ready)
(return))
(var num-keys-reported int 0)
;; We are limited here in the number of keys we can send at once. It should be possible to roll
;; them over or use a different API to send more keys.
(var keycodes (array 6 uint8_t) (array 0))
(var key-just-pressed bool false)
(var key-just-released bool false)
(ignore ;; Sanity check (press boot button)
(var-static has-key bool false)
(var button-pressed uint32_t (board_button_read))
(if button-pressed
(scope
(set (at 0 keycodes) HID_KEY_A)
(set has-key true)
(set key-just-pressed true))
(scope
(set key-just-released has-key)
(set has-key false))))
(each-in-range (array-size row-pins) row
(each-in-range (array-size column-pins) column
(when (and (at row column matrix)
(not (at row column last-scan-matrix))
(< num-keys-reported (array-size keycodes)))
(var key-code uint8_t (at row column matrix-to-keycodes))
(unless (= key-code keycode-unused)
(set (at num-keys-reported keycodes) key-code)
(incr num-keys-reported)
(set key-just-pressed true)))
(when (and (at row column last-scan-matrix)
(not (at row column matrix)))
(set key-just-released true))
(set (at row column last-scan-matrix)
(at row column matrix))))
;; Avoid sending multiple empty key reports if nothing changed
(when (or key-just-pressed key-just-released)
(tud_hid_keyboard_report
REPORT_ID_KEYBOARD
0 ;; modifier
keycodes)))
(defun scan-matrix ()
(each-item-in-array column-pins column col-pin int
(gpio_set_dir col-pin GPIO_OUT)
(gpio_disable_pulls col-pin)
(gpio_put col-pin 0)
(sleep_ms 1) ;; Seems necessary to prevent extraneous key presses.
(each-item-in-array row-pins row row-pin int
(gpio_set_dir row-pin GPIO_IN)
(gpio_pull_up row-pin)
(set (at row column matrix) (= 0 (gpio_get row-pin)))
(gpio_set_dir row-pin GPIO_OUT)
(gpio_disable_pulls row-pin))
(gpio_set_dir col-pin GPIO_IN)
(gpio_pull_up col-pin)))
;; (defun loop ()
;; (scan-matrix)
;; ;; (print-line "\n-------")
;; (each-in-range (array-size row-pins) row
;; (each-in-range (array-size column-pins) column
;; (when (and (at row column matrix)
;; (not (at row column last-scan-matrix)))
;; ;; (print-line "----")
;; ;; (print-line row)
;; ;; (print-line column)
;; ;; (print-line (? (at row column matrix) "ON" "OFF"))
;; (print-line (at row column matrix-to-keys)))
;; (set (at row column last-scan-matrix)
;; (at row column matrix))))
;; ;; wait for a bit
;; (ignore (sleep_ms 500)))
;; Invoked when received SET_REPORT control request or
;; received data on OUT endpoint ( Report ID = 0, Type = 0 )
;; In other words, the computer is telling US to do something (e.g. set caps lock LED)
(defun-nodecl tud_hid_set_report_cb
(instance uint8_t
report_id uint8_t
report_type hid_report_type_t
buffer (addr (const uint8_t))
bufsize uint16_t)
(ignore))
;; Invoked when received GET_REPORT control request
;; Application must fill buffer report's content and return its length.
;; Return zero will cause the stack to STALL request
(defun-nodecl tud_hid_get_report_cb
(instance uint8_t
report_id uint8_t
report_type hid_report_type_t
buffer (addr uint8_t)
reqlen uint16_t
&return uint16_t)
;; (todo robustness) I think I need to implement this...
(return 0))

59
src/pico_extras_import_optional.cmake

@ -0,0 +1,59 @@
# This is a copy of <PICO_EXTRAS_PATH>/external/pico_extras_import.cmake
# This can be dropped into an external project to help locate pico-extras
# It should be include()ed prior to project()
if (DEFINED ENV{PICO_EXTRAS_PATH} AND (NOT PICO_EXTRAS_PATH))
set(PICO_EXTRAS_PATH $ENV{PICO_EXTRAS_PATH})
message("Using PICO_EXTRAS_PATH from environment ('${PICO_EXTRAS_PATH}')")
endif ()
if (DEFINED ENV{PICO_EXTRAS_FETCH_FROM_GIT} AND (NOT PICO_EXTRAS_FETCH_FROM_GIT))
set(PICO_EXTRAS_FETCH_FROM_GIT $ENV{PICO_EXTRAS_FETCH_FROM_GIT})
message("Using PICO_EXTRAS_FETCH_FROM_GIT from environment ('${PICO_EXTRAS_FETCH_FROM_GIT}')")
endif ()
if (DEFINED ENV{PICO_EXTRAS_FETCH_FROM_GIT_PATH} AND (NOT PICO_EXTRAS_FETCH_FROM_GIT_PATH))
set(PICO_EXTRAS_FETCH_FROM_GIT_PATH $ENV{PICO_EXTRAS_FETCH_FROM_GIT_PATH})
message("Using PICO_EXTRAS_FETCH_FROM_GIT_PATH from environment ('${PICO_EXTRAS_FETCH_FROM_GIT_PATH}')")
endif ()
if (NOT PICO_EXTRAS_PATH)
if (PICO_EXTRAS_FETCH_FROM_GIT)
include(FetchContent)
set(FETCHCONTENT_BASE_DIR_SAVE ${FETCHCONTENT_BASE_DIR})
if (PICO_EXTRAS_FETCH_FROM_GIT_PATH)
get_filename_component(FETCHCONTENT_BASE_DIR "${PICO_EXTRAS_FETCH_FROM_GIT_PATH}" REALPATH BASE_DIR "${CMAKE_SOURCE_DIR}")
endif ()
FetchContent_Declare(
pico_extras
GIT_REPOSITORY https://github.com/raspberrypi/pico-extras
GIT_TAG master
)
if (NOT pico_extras)
message("Downloading Raspberry Pi Pico Extras")
FetchContent_Populate(pico_extras)
set(PICO_EXTRAS_PATH ${pico_extras_SOURCE_DIR})
endif ()
set(FETCHCONTENT_BASE_DIR ${FETCHCONTENT_BASE_DIR_SAVE})
else ()
if (PICO_SDK_PATH AND EXISTS "${PICO_SDK_PATH}/../pico-extras")
set(PICO_EXTRAS_PATH ${PICO_SDK_PATH}/../pico-extras)
message("Defaulting PICO_EXTRAS_PATH as sibling of PICO_SDK_PATH: ${PICO_EXTRAS_PATH}")
endif()
endif ()
endif ()
if (PICO_EXTRAS_PATH)
set(PICO_EXTRAS_PATH "${PICO_EXTRAS_PATH}" CACHE PATH "Path to the PICO EXTRAS")
set(PICO_EXTRAS_FETCH_FROM_GIT "${PICO_EXTRAS_FETCH_FROM_GIT}" CACHE BOOL "Set to ON to fetch copy of PICO EXTRAS from git if not otherwise locatable")
set(PICO_EXTRAS_FETCH_FROM_GIT_PATH "${PICO_EXTRAS_FETCH_FROM_GIT_PATH}" CACHE FILEPATH "location to download EXTRAS")
get_filename_component(PICO_EXTRAS_PATH "${PICO_EXTRAS_PATH}" REALPATH BASE_DIR "${CMAKE_BINARY_DIR}")
if (NOT EXISTS ${PICO_EXTRAS_PATH})
message(FATAL_ERROR "Directory '${PICO_EXTRAS_PATH}' not found")
endif ()
set(PICO_EXTRAS_PATH ${PICO_EXTRAS_PATH} CACHE PATH "Path to the PICO EXTRAS" FORCE)
add_subdirectory(${PICO_EXTRAS_PATH} pico_extras)
endif()

73
src/pico_sdk_import.cmake

@ -0,0 +1,73 @@
# This is a copy of <PICO_SDK_PATH>/external/pico_sdk_import.cmake
# This can be dropped into an external project to help locate this SDK
# It should be include()ed prior to project()
if (DEFINED ENV{PICO_SDK_PATH} AND (NOT PICO_SDK_PATH))
set(PICO_SDK_PATH $ENV{PICO_SDK_PATH})
message("Using PICO_SDK_PATH from environment ('${PICO_SDK_PATH}')")
endif ()
if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT} AND (NOT PICO_SDK_FETCH_FROM_GIT))
set(PICO_SDK_FETCH_FROM_GIT $ENV{PICO_SDK_FETCH_FROM_GIT})
message("Using PICO_SDK_FETCH_FROM_GIT from environment ('${PICO_SDK_FETCH_FROM_GIT}')")
endif ()
if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT_PATH} AND (NOT PICO_SDK_FETCH_FROM_GIT_PATH))
set(PICO_SDK_FETCH_FROM_GIT_PATH $ENV{PICO_SDK_FETCH_FROM_GIT_PATH})
message("Using PICO_SDK_FETCH_FROM_GIT_PATH from environment ('${PICO_SDK_FETCH_FROM_GIT_PATH}')")
endif ()
set(PICO_SDK_PATH "${PICO_SDK_PATH}" CACHE PATH "Path to the Raspberry Pi Pico SDK")
set(PICO_SDK_FETCH_FROM_GIT "${PICO_SDK_FETCH_FROM_GIT}" CACHE BOOL "Set to ON to fetch copy of SDK from git if not otherwise locatable")
set(PICO_SDK_FETCH_FROM_GIT_PATH "${PICO_SDK_FETCH_FROM_GIT_PATH}" CACHE FILEPATH "location to download SDK")
if (NOT PICO_SDK_PATH)
if (PICO_SDK_FETCH_FROM_GIT)
include(FetchContent)
set(FETCHCONTENT_BASE_DIR_SAVE ${FETCHCONTENT_BASE_DIR})
if (PICO_SDK_FETCH_FROM_GIT_PATH)
get_filename_component(FETCHCONTENT_BASE_DIR "${PICO_SDK_FETCH_FROM_GIT_PATH}" REALPATH BASE_DIR "${CMAKE_SOURCE_DIR}")
endif ()
# GIT_SUBMODULES_RECURSE was added in 3.17
if (${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.17.0")
FetchContent_Declare(
pico_sdk
GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk
GIT_TAG master
GIT_SUBMODULES_RECURSE FALSE
)
else ()
FetchContent_Declare(
pico_sdk
GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk
GIT_TAG master
)
endif ()
if (NOT pico_sdk)
message("Downloading Raspberry Pi Pico SDK")
FetchContent_Populate(pico_sdk)
set(PICO_SDK_PATH ${pico_sdk_SOURCE_DIR})
endif ()
set(FETCHCONTENT_BASE_DIR ${FETCHCONTENT_BASE_DIR_SAVE})
else ()
message(FATAL_ERROR
"SDK location was not specified. Please set PICO_SDK_PATH or set PICO_SDK_FETCH_FROM_GIT to on to fetch from git."
)
endif ()
endif ()
get_filename_component(PICO_SDK_PATH "${PICO_SDK_PATH}" REALPATH BASE_DIR "${CMAKE_BINARY_DIR}")
if (NOT EXISTS ${PICO_SDK_PATH})
message(FATAL_ERROR "Directory '${PICO_SDK_PATH}' not found")
endif ()
set(PICO_SDK_INIT_CMAKE_FILE ${PICO_SDK_PATH}/pico_sdk_init.cmake)
if (NOT EXISTS ${PICO_SDK_INIT_CMAKE_FILE})
message(FATAL_ERROR "Directory '${PICO_SDK_PATH}' does not appear to contain the Raspberry Pi Pico SDK")
endif ()
set(PICO_SDK_PATH ${PICO_SDK_PATH} CACHE PATH "Path to the Raspberry Pi Pico SDK" FORCE)
include(${PICO_SDK_INIT_CMAKE_FILE})

111
src/tusb_config.h

@ -0,0 +1,111 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*
*/
#ifndef _TUSB_CONFIG_H_
#define _TUSB_CONFIG_H_
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------
// COMMON CONFIGURATION
//--------------------------------------------------------------------
// defined by board.mk
#ifndef CFG_TUSB_MCU
#error CFG_TUSB_MCU must be defined
#endif
// RHPort number used for device can be defined by board.mk, default to port 0
#ifndef BOARD_DEVICE_RHPORT_NUM
#define BOARD_DEVICE_RHPORT_NUM 0
#endif
// RHPort max operational speed can defined by board.mk
// Default to Highspeed for MCU with internal HighSpeed PHY (can be port specific), otherwise FullSpeed
#ifndef BOARD_DEVICE_RHPORT_SPEED
#if (CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX || \
CFG_TUSB_MCU == OPT_MCU_NUC505 || CFG_TUSB_MCU == OPT_MCU_CXD56 || CFG_TUSB_MCU == OPT_MCU_SAMX7X)
#define BOARD_DEVICE_RHPORT_SPEED OPT_MODE_HIGH_SPEED
#else
#define BOARD_DEVICE_RHPORT_SPEED OPT_MODE_FULL_SPEED
#endif
#endif
// Device mode with rhport and speed defined by board.mk
#if BOARD_DEVICE_RHPORT_NUM == 0
#define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | BOARD_DEVICE_RHPORT_SPEED)
#elif BOARD_DEVICE_RHPORT_NUM == 1
#define CFG_TUSB_RHPORT1_MODE (OPT_MODE_DEVICE | BOARD_DEVICE_RHPORT_SPEED)
#else
#error "Incorrect RHPort configuration"
#endif
#ifndef CFG_TUSB_OS
#define CFG_TUSB_OS OPT_OS_NONE
#endif
// CFG_TUSB_DEBUG is defined by compiler in DEBUG build
// #define CFG_TUSB_DEBUG 0
/* USB DMA on some MCUs can only access a specific SRAM region with restriction on alignment.
* Tinyusb use follows macros to declare transferring memory so that they can be put
* into those specific section.
* e.g
* - CFG_TUSB_MEM SECTION : __attribute__ (( section(".usb_ram") ))
* - CFG_TUSB_MEM_ALIGN : __attribute__ ((aligned(4)))
*/
#ifndef CFG_TUSB_MEM_SECTION
#define CFG_TUSB_MEM_SECTION
#endif
#ifndef CFG_TUSB_MEM_ALIGN
#define CFG_TUSB_MEM_ALIGN __attribute__ ((aligned(4)))
#endif
//--------------------------------------------------------------------
// DEVICE CONFIGURATION
//--------------------------------------------------------------------
#ifndef CFG_TUD_ENDPOINT0_SIZE
#define CFG_TUD_ENDPOINT0_SIZE 64
#endif
//------------- CLASS -------------//
#define CFG_TUD_HID 1
#define CFG_TUD_CDC 0
#define CFG_TUD_MSC 0
#define CFG_TUD_MIDI 0
#define CFG_TUD_VENDOR 0
// HID buffer size Should be sufficient to hold ID (if any) + Data
#define CFG_TUD_HID_EP_BUFSIZE 16
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_CONFIG_H_ */

233
src/usb_descriptors.c

@ -0,0 +1,233 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*
*/
#include "pico/unique_id.h"
#include "tusb.h"
#include "usb_descriptors.h"
/* A combination of interfaces must have a unique product id, since PC will save device driver after the first plug.
* Same VID/PID with different interface e.g MSC (first), then CDC (later) will possibly cause system error on PC.
*
* Auto ProductID layout's Bitmap:
* [MSB] HID | MSC | CDC [LSB]
*/
#define _PID_MAP(itf, n) ( (CFG_TUD_##itf) << (n) )
#define USB_PID (0x4000 | _PID_MAP(CDC, 0) | _PID_MAP(MSC, 1) | _PID_MAP(HID, 2) | \
_PID_MAP(MIDI, 3) | _PID_MAP(VENDOR, 4) )
#define USB_VID 0xCafe
#define USB_BCD 0x0200
//--------------------------------------------------------------------+
// Device Descriptors
//--------------------------------------------------------------------+
tusb_desc_device_t const desc_device =
{
.bLength = sizeof(tusb_desc_device_t),
.bDescriptorType = TUSB_DESC_DEVICE,
.bcdUSB = USB_BCD,
.bDeviceClass = 0x00,
.bDeviceSubClass = 0x00,
.bDeviceProtocol = 0x00,
.bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE,
.idVendor = USB_VID,
.idProduct = USB_PID,
.bcdDevice = 0x0100,
.iManufacturer = 0x01,
.iProduct = 0x02,
.iSerialNumber = 0x03,
.bNumConfigurations = 0x01
};
// Invoked when received GET DEVICE DESCRIPTOR
// Application return pointer to descriptor
uint8_t const * tud_descriptor_device_cb(void)
{
return (uint8_t const *) &desc_device;
}
//--------------------------------------------------------------------+
// HID Report Descriptor
//--------------------------------------------------------------------+
uint8_t const desc_hid_report[] =
{
TUD_HID_REPORT_DESC_KEYBOARD( HID_REPORT_ID(REPORT_ID_KEYBOARD )),
TUD_HID_REPORT_DESC_MOUSE ( HID_REPORT_ID(REPORT_ID_MOUSE )),
TUD_HID_REPORT_DESC_CONSUMER( HID_REPORT_ID(REPORT_ID_CONSUMER_CONTROL )),
TUD_HID_REPORT_DESC_GAMEPAD ( HID_REPORT_ID(REPORT_ID_GAMEPAD ))
};
// Invoked when received GET HID REPORT DESCRIPTOR
// Application return pointer to descriptor
// Descriptor contents must exist long enough for transfer to complete
uint8_t const * tud_hid_descriptor_report_cb(uint8_t instance)
{
(void) instance;
return desc_hid_report;
}
//--------------------------------------------------------------------+
// Configuration Descriptor
//--------------------------------------------------------------------+
enum
{
ITF_NUM_HID,
ITF_NUM_TOTAL
};
#define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_HID_DESC_LEN)
#define EPNUM_HID 0x81
uint8_t const desc_configuration[] =
{
// Config number, interface count, string index, total length, attribute, power in mA
TUD_CONFIG_DESCRIPTOR(1, ITF_NUM_TOTAL, 0, CONFIG_TOTAL_LEN, TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP, 100),
// Interface number, string index, protocol, report descriptor len, EP In address, size & polling interval
TUD_HID_DESCRIPTOR(ITF_NUM_HID, 0, HID_ITF_PROTOCOL_NONE, sizeof(desc_hid_report), EPNUM_HID, CFG_TUD_HID_EP_BUFSIZE, 5)
};
#if TUD_OPT_HIGH_SPEED
// Per USB specs: high speed capable device must report device_qualifier and other_speed_configuration
// other speed configuration
uint8_t desc_other_speed_config[CONFIG_TOTAL_LEN];
// device qualifier is mostly similar to device descriptor since we don't change configuration based on speed
tusb_desc_device_qualifier_t const desc_device_qualifier =
{
.bLength = sizeof(tusb_desc_device_qualifier_t),
.bDescriptorType = TUSB_DESC_DEVICE_QUALIFIER,
.bcdUSB = USB_BCD,
.bDeviceClass = 0x00,
.bDeviceSubClass = 0x00,
.bDeviceProtocol = 0x00,
.bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE,
.bNumConfigurations = 0x01,
.bReserved = 0x00
};
// Invoked when received GET DEVICE QUALIFIER DESCRIPTOR request
// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete.
// device_qualifier descriptor describes information about a high-speed capable device that would
// change if the device were operating at the other speed. If not highspeed capable stall this request.
uint8_t const* tud_descriptor_device_qualifier_cb(void)
{
return (uint8_t const*) &desc_device_qualifier;
}
// Invoked when received GET OTHER SEED CONFIGURATION DESCRIPTOR request
// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete
// Configuration descriptor in the other speed e.g if high speed then this is for full speed and vice versa
uint8_t const* tud_descriptor_other_speed_configuration_cb(uint8_t index)
{
(void) index; // for multiple configurations
// other speed config is basically configuration with type = OHER_SPEED_CONFIG
memcpy(desc_other_speed_config, desc_configuration, CONFIG_TOTAL_LEN);
desc_other_speed_config[1] = TUSB_DESC_OTHER_SPEED_CONFIG;
// this example use the same configuration for both high and full speed mode
return desc_other_speed_config;
}
#endif // highspeed
// Invoked when received GET CONFIGURATION DESCRIPTOR
// Application return pointer to descriptor
// Descriptor contents must exist long enough for transfer to complete
uint8_t const * tud_descriptor_configuration_cb(uint8_t index)
{
(void) index; // for multiple configurations
// This example use the same configuration for both high and full speed mode
return desc_configuration;
}
//--------------------------------------------------------------------+
// String Descriptors
//--------------------------------------------------------------------+
// buffer to hold flash ID
char serial[2 * PICO_UNIQUE_BOARD_ID_SIZE_BYTES + 1];
// array of pointer to string descriptors
char const* string_desc_arr [] =
{
(const char[]) { 0x09, 0x04 }, // 0: is supported language is English (0x0409)
"TinyUSB", // 1: Manufacturer
"TinyUSB Device", // 2: Product
serial, // 3: Serials, uses the flash ID
};
static uint16_t _desc_str[32];
// Invoked when received GET STRING DESCRIPTOR request
// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete
uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid)
{
(void) langid;
uint8_t chr_count;
if ( index == 0)
{
memcpy(&_desc_str[1], string_desc_arr[0], 2);
chr_count = 1;
}else
{
// Note: the 0xEE index string is a Microsoft OS 1.0 Descriptors.
// https://docs.microsoft.com/en-us/windows-hardware/drivers/usbcon/microsoft-defined-usb-descriptors
if (index == 3) pico_get_unique_board_id_string(serial, sizeof(serial));
if ( !(index < sizeof(string_desc_arr)/sizeof(string_desc_arr[0])) ) return NULL;
const char* str = string_desc_arr[index];
// Cap at max char
chr_count = strlen(str);
if ( chr_count > 31 ) chr_count = 31;
// Convert ASCII string into UTF-16
for(uint8_t i=0; i<chr_count; i++)
{
_desc_str[1+i] = str[i];
}
}
// first byte is length (including header), second byte is string type
_desc_str[0] = (TUSB_DESC_STRING << 8 ) | (2*chr_count + 2);
return _desc_str;
}

37
src/usb_descriptors.h

@ -0,0 +1,37 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#ifndef USB_DESCRIPTORS_H_
#define USB_DESCRIPTORS_H_
enum
{
REPORT_ID_KEYBOARD = 1,
REPORT_ID_MOUSE,
REPORT_ID_CONSUMER_CONTROL,
REPORT_ID_GAMEPAD,
REPORT_ID_COUNT
};
#endif /* USB_DESCRIPTORS_H_ */
Loading…
Cancel
Save