aboutsummaryrefslogtreecommitdiff
path: root/ports/teensy
diff options
context:
space:
mode:
authorDamien George2017-09-06 13:40:51 +1000
committerDamien George2017-09-06 13:40:51 +1000
commit01dd7804b87d60b2deab16712eccb3b97351a9b7 (patch)
tree1aa21f38a872b8e62a3d4e4f74f68033c6f827e4 /ports/teensy
parenta9862b30068fc9df1022f08019fb35aaa5085f64 (diff)
ports: Make new ports/ sub-directory and move all ports there.
This is to keep the top-level directory clean, to make it clear what is core and what is a port, and to allow the repository to grow with new ports in a sustainable way.
Diffstat (limited to 'ports/teensy')
-rw-r--r--ports/teensy/Makefile235
-rw-r--r--ports/teensy/README.md72
-rwxr-xr-xports/teensy/add-memzip.sh27
-rw-r--r--ports/teensy/core/Arduino.h3
-rw-r--r--ports/teensy/core/HardwareSerial.h227
-rw-r--r--ports/teensy/core/analog.c463
-rw-r--r--ports/teensy/core/avr_functions.h107
-rw-r--r--ports/teensy/core/core_pins.h841
-rw-r--r--ports/teensy/core/mk20dx128.c662
-rw-r--r--ports/teensy/core/mk20dx128.h2385
-rw-r--r--ports/teensy/core/pins_arduino.h113
-rw-r--r--ports/teensy/core/pins_teensy.c817
-rw-r--r--ports/teensy/core/usb_desc.c895
-rw-r--r--ports/teensy/core/usb_desc.h313
-rw-r--r--ports/teensy/core/usb_dev.c980
-rw-r--r--ports/teensy/core/usb_dev.h108
-rw-r--r--ports/teensy/core/usb_mem.c109
-rw-r--r--ports/teensy/core/usb_mem.h55
-rw-r--r--ports/teensy/core/usb_names.h57
-rw-r--r--ports/teensy/core/usb_serial.c273
-rw-r--r--ports/teensy/core/usb_serial.h144
-rw-r--r--ports/teensy/core/yield.c32
-rw-r--r--ports/teensy/hal_ftm.c201
-rw-r--r--ports/teensy/hal_ftm.h186
-rw-r--r--ports/teensy/hal_gpio.c123
-rw-r--r--ports/teensy/help.c69
-rw-r--r--ports/teensy/lcd.c14
-rw-r--r--ports/teensy/led.c144
-rw-r--r--ports/teensy/led.h14
-rw-r--r--ports/teensy/lexerfrozen.c13
-rw-r--r--ports/teensy/lexermemzip.h6
-rw-r--r--ports/teensy/main.c381
-rwxr-xr-xports/teensy/make-pins.py405
-rw-r--r--ports/teensy/memzip_files/boot.py12
-rw-r--r--ports/teensy/memzip_files/main.py15
-rw-r--r--ports/teensy/mk20dx256.ld176
-rw-r--r--ports/teensy/mk20dx256_af.csv65
-rw-r--r--ports/teensy/mk20dx256_prefix.c33
-rw-r--r--ports/teensy/modpyb.c358
-rw-r--r--ports/teensy/mpconfigport.h139
-rw-r--r--ports/teensy/pin_defs_teensy.c71
-rw-r--r--ports/teensy/pin_defs_teensy.h49
-rw-r--r--ports/teensy/qstrdefsport.h1
-rw-r--r--ports/teensy/reg.c47
-rw-r--r--ports/teensy/reg.h13
-rw-r--r--ports/teensy/servo.c265
-rw-r--r--ports/teensy/servo.h11
-rw-r--r--ports/teensy/std.h25
-rw-r--r--ports/teensy/teensy_hal.c65
-rw-r--r--ports/teensy/teensy_hal.h128
-rw-r--r--ports/teensy/teensy_pins.csv56
-rw-r--r--ports/teensy/timer.c992
-rw-r--r--ports/teensy/timer.h34
-rw-r--r--ports/teensy/uart.c488
-rw-r--r--ports/teensy/usb.c52
-rw-r--r--ports/teensy/usb.h12
56 files changed, 13581 insertions, 0 deletions
diff --git a/ports/teensy/Makefile b/ports/teensy/Makefile
new file mode 100644
index 000000000..944e281a4
--- /dev/null
+++ b/ports/teensy/Makefile
@@ -0,0 +1,235 @@
+include ../py/mkenv.mk
+
+# qstr definitions (must come before including py.mk)
+QSTR_DEFS = qstrdefsport.h $(BUILD)/pins_qstr.h
+
+# include py core make definitions
+include $(TOP)/py/py.mk
+
+# If you set USE_ARDUINO_TOOLCHAIN=1 then this makefile will attempt to use
+# the toolchain that comes with Teensyduino
+ifeq ($(USE_ARDUINO_TOOLCHAIN),)
+USE_ARDUINO_TOOLCHAIN = 0
+endif
+
+ifeq ($(USE_ARDUINO_TOOLCHAIN),1)
+ifeq ($(ARDUINO),)
+$(error USE_ARDUINO_TOOLCHAIN requires that ARDUINO be set)
+endif
+endif
+
+ifeq ($(USE_ARDUINO_TOOLCHAIN),1)
+$(info Using ARDUINO toolchain)
+CROSS_COMPILE = $(ARDUINO)/hardware/tools/arm-none-eabi/bin/arm-none-eabi-
+else
+$(info Using toolchain from PATH)
+CROSS_COMPILE = arm-none-eabi-
+endif
+
+CFLAGS_TEENSY = -DF_CPU=96000000 -DUSB_SERIAL -D__MK20DX256__
+CFLAGS_CORTEX_M4 = -mthumb -mtune=cortex-m4 -mcpu=cortex-m4 -msoft-float -mfloat-abi=soft -fsingle-precision-constant -Wdouble-promotion $(CFLAGS_TEENSY)
+
+INC += -I.
+INC += -I$(TOP)
+INC += -I$(TOP)/stmhal
+INC += -I$(BUILD)
+INC += -Icore
+
+CFLAGS = $(INC) -Wall -Wpointer-arith -std=gnu99 -nostdlib $(CFLAGS_CORTEX_M4)
+LDFLAGS = -nostdlib -T mk20dx256.ld -msoft-float -mfloat-abi=soft
+
+ifeq ($(USE_ARDUINO_TOOLCHAIN),1)
+
+LIBGCC_FILE_NAME = $(ARDUINO)/hardware/tools/arm-none-eabi/lib/gcc/arm-none-eabi/4.7.2/thumb2/libgcc.a
+LIBM_FILE_NAME = $(ARDUINO)/hardware/tools/arm-none-eabi/arm-none-eabi/lib/thumb2/libm.a
+LIBC_FILE_NAME = $(ARDUINO)/hardware/tools/arm-none-eabi/arm-none-eabi/lib/thumb2/libc.a
+
+else
+
+LIBGCC_FILE_NAME = $(shell $(CC) $(CFLAGS) -print-libgcc-file-name)
+LIBM_FILE_NAME = $(shell $(CC) $(CFLAGS) -print-file-name=libm.a)
+LIBC_FILE_NAME = $(shell $(CC) $(CFLAGS) -print-file-name=libc.a)
+
+endif
+
+#$(info %%%%% LIBGCC_FILE_NAME = $(LIBGCC_FILE_NAME))
+#$(info %%%%% LIBM_FILE_NAME = $(LIBM_FILE_NAME))
+#$(info %%%%% LIBC_FILE_NAME = $(LIBC_FILE_NAME))
+
+#$(info %%%%% dirname LIBGCC_FILE_NAME = $(dir $(LIBGCC_FILE_NAME)))
+#$(info %%%%% dirname LIBM_FILE_NAME = $(dir $(LIBM_FILE_NAME)))
+#$(info %%%%% dirname LIBC_FILE_NAME = $(dir $(LIBC_FILE_NAME)))
+
+LIBS = -L $(dir $(LIBM_FILE_NAME)) -lm
+LIBS += -L $(dir $(LIBC_FILE_NAME)) -lc
+LIBS += -L $(dir $(LIBGCC_FILE_NAME)) -lgcc
+
+#Debugging/Optimization
+ifdef DEBUG
+CFLAGS += -Og -ggdb
+else
+CFLAGS += -Os #-DNDEBUG
+endif
+CFLAGS += -fdata-sections -ffunction-sections
+LDFLAGS += -Wl,--gc-sections
+
+USE_FROZEN = 1
+USE_MEMZIP = 0
+
+SRC_C = \
+ hal_ftm.c \
+ hal_gpio.c \
+ help.c \
+ main.c \
+ lcd.c \
+ led.c \
+ modpyb.c \
+ pin_defs_teensy.c \
+ reg.c \
+ teensy_hal.c \
+ timer.c \
+ uart.c \
+ usb.c \
+
+STM_SRC_C = $(addprefix stmhal/,\
+ gccollect.c \
+ irq.c \
+ pin.c \
+ pin_named_pins.c \
+ )
+
+STM_SRC_S = $(addprefix stmhal/,\
+ gchelper.s \
+ )
+
+LIB_SRC_C = $(addprefix lib/,\
+ libc/string0.c \
+ mp-readline/readline.c \
+ utils/pyexec.c \
+ utils/sys_stdio_mphal.c \
+ )
+
+SRC_TEENSY = $(addprefix core/,\
+ mk20dx128.c \
+ pins_teensy.c \
+ analog.c \
+ usb_desc.c \
+ usb_dev.c \
+ usb_mem.c \
+ usb_serial.c \
+ yield.c \
+ )
+
+OBJ = $(PY_O) $(addprefix $(BUILD)/, $(SRC_C:.c=.o) $(STM_SRC_C:.c=.o) $(STM_SRC_S:.s=.o) $(SRC_TEENSY:.c=.o))
+OBJ += $(addprefix $(BUILD)/, $(LIB_SRC_C:.c=.o))
+OBJ += $(BUILD)/pins_gen.o
+
+all: hex
+hex: $(BUILD)/micropython.hex
+
+ifeq ($(USE_MEMZIP),1)
+SRC_C += \
+ lib/memzip/import.c \
+ lib/memzip/lexermemzip.c \
+ lib/memzip/memzip.c \
+
+OBJ += $(BUILD)/memzip-files.o
+
+MAKE_MEMZIP = $(TOP)/lib/memzip/make-memzip.py
+ifeq ($(MEMZIP_DIR),)
+MEMZIP_DIR = memzip_files
+endif
+
+$(BUILD)/memzip-files.o: $(BUILD)/memzip-files.c
+ $(call compile_c)
+
+$(BUILD)/memzip-files.c: $(shell find ${MEMZIP_DIR} -type f)
+ @$(ECHO) "Creating $@"
+ $(Q)$(PYTHON) $(MAKE_MEMZIP) --zip-file $(BUILD)/memzip-files.zip --c-file $@ $(MEMZIP_DIR)
+
+endif # USE_MEMZIP
+
+ifeq ($(USE_FROZEN),1)
+
+ifeq ($(FROZEN_DIR),)
+FROZEN_DIR = memzip_files
+endif
+
+CFLAGS += -DMICROPY_MODULE_FROZEN_STR
+
+SRC_C += \
+ lexerfrozen.c \
+ $(BUILD)/frozen.c
+
+endif # USE_FROZEN
+
+ifeq ($(ARDUINO),)
+post_compile: $(BUILD)/micropython.hex
+ $(ECHO) "Please define ARDUINO (where TeensyDuino is installed)"
+ exit 1
+
+reboot:
+ $(ECHO) "Please define ARDUINO (where TeensyDuino is installed)"
+ exit 1
+
+else
+TOOLS_PATH = $(ARDUINO)/hardware/tools
+
+post_compile: $(BUILD)/micropython.hex
+ $(ECHO) "Preparing $@ for upload"
+ $(Q)$(TOOLS_PATH)/teensy_post_compile -file="$(basename $(<F))" -path="$(abspath $(<D))" -tools="$(TOOLS_PATH)"
+
+reboot:
+ $(ECHO) "REBOOT"
+ -$(Q)$(TOOLS_PATH)/teensy_reboot
+endif
+
+.PHONY: deploy
+deploy: post_compile reboot
+
+$(BUILD)/micropython.elf: $(OBJ)
+ $(ECHO) "LINK $@"
+ $(Q)$(CC) $(LDFLAGS) -o "$@" -Wl,-Map,$(@:.elf=.map) $^ $(LIBS)
+ $(Q)$(SIZE) $@
+
+$(BUILD)/%.hex: $(BUILD)/%.elf
+ $(ECHO) "HEX $<"
+ $(Q)$(OBJCOPY) -O ihex -R .eeprom "$<" "$@"
+
+MAKE_PINS = make-pins.py
+BOARD_PINS = teensy_pins.csv
+AF_FILE = mk20dx256_af.csv
+PREFIX_FILE = mk20dx256_prefix.c
+GEN_PINS_SRC = $(BUILD)/pins_gen.c
+GEN_PINS_HDR = $(HEADER_BUILD)/pins.h
+GEN_PINS_QSTR = $(BUILD)/pins_qstr.h
+GEN_PINS_AF_CONST = $(HEADER_BUILD)/pins_af_const.h
+GEN_PINS_AF_PY = $(BUILD)/pins_af.py
+
+# List of sources for qstr extraction
+SRC_QSTR += $(SRC_C) $(STM_SRC_C) $(LIB_SRC_C)
+# Append any auto-generated sources that are needed by sources listed in
+# SRC_QSTR
+SRC_QSTR_AUTO_DEPS +=
+
+# Making OBJ use an order-only depenedency on the generated pins.h file
+# has the side effect of making the pins.h file before we actually compile
+# any of the objects. The normal dependency generation will deal with the
+# case when pins.h is modified. But when it doesn't exist, we don't know
+# which source files might need it.
+$(OBJ): | $(HEADER_BUILD)/pins.h
+
+# Use a pattern rule here so that make will only call make-pins.py once to make
+# both pins_$(BOARD).c and pins.h
+$(BUILD)/%_gen.c $(HEADER_BUILD)/%.h $(HEADER_BUILD)/%_af_const.h $(BUILD)/%_qstr.h: teensy_%.csv $(MAKE_PINS) $(AF_FILE) $(PREFIX_FILE) | $(HEADER_BUILD)
+ $(ECHO) "Create $@"
+ $(Q)$(PYTHON) $(MAKE_PINS) --board $(BOARD_PINS) --af $(AF_FILE) --prefix $(PREFIX_FILE) --hdr $(GEN_PINS_HDR) --qstr $(GEN_PINS_QSTR) --af-const $(GEN_PINS_AF_CONST) --af-py $(GEN_PINS_AF_PY) > $(GEN_PINS_SRC)
+
+$(BUILD)/pins_gen.o: $(BUILD)/pins_gen.c
+ $(call compile_c)
+
+$(BUILD)/%.pp: $(BUILD)/%.c
+ $(ECHO) "PreProcess $<"
+ $(Q)$(CC) $(CFLAGS) -E -Wp,-C,-dD,-dI -o $@ $<
+
+include $(TOP)/py/mkrules.mk
diff --git a/ports/teensy/README.md b/ports/teensy/README.md
new file mode 100644
index 000000000..c586853b5
--- /dev/null
+++ b/ports/teensy/README.md
@@ -0,0 +1,72 @@
+# Build Instructions for Teensy 3.1
+
+Currently the Teensy 3.1 port of MicroPython builds under Linux and not under Windows.
+
+The tool chain required for the build can be found at <https://launchpad.net/gcc-arm-embedded>.
+
+Download the current Linux *.tar.bz2 file. Instructions regarding unpacking the file and moving it to the correct location
+as well as adding the extracted folders to the enviroment variable can be found at
+<http://eliaselectronics.com/stm32f4-tutorials/setting-up-the-stm32f4-arm-development-toolchain/>
+
+In order to download the firmware image to the teensy, you'll need to use the
+downloader included with TeensyDuino. The following assumes that you have
+TeensyDuino installed and set the ARDUINO environment variable pointing to the
+where Arduino with TeensyDuino is installed.
+
+```bash
+cd teensy
+ARDUINO=~/arduino-1.0.5 make
+```
+
+To upload MicroPython to the Teensy 3.1.
+
+Press the Program button on the Teensy 3.1
+```bash
+sudo ARDUINO=~/arduino-1.0.5/ make deploy
+```
+
+Currently, the Python prompt is through the USB serial interface, i.e.
+
+```bash
+minicom -D /dev/ttyACM0
+```
+
+## TIPS
+
+### Install 49-teensy.rules into /etc/udev/rules.d
+If you install the 49-teensy.rules file from http://www.pjrc.com/teensy/49-teensy.rules
+into your ```/etc/udev/rules.d``` folder then you won't need to use sudo:
+```bash
+sudo cp ~/Downloads/49-teensy.rules /etc/udev/rules.d
+sudo udevadm control --reload-rules
+```
+Unplug and replug the teensy board, and then you can use: ```ARDUINO=~/arduino-1.0.5/ make deploy```
+
+### Create a GNUmakefile to hold your ARDUINO setting.
+Create a file call GNUmakefile (note the lowercase m) in the teensy folder
+with the following contents:
+```make
+$(info Executing GNUmakefile)
+
+ARDUINO=${HOME}/arduino-1.0.5
+$(info ARDUINO=${ARDUINO})
+
+include Makefile
+```
+GNUmakefile is not checked into the source code control system, so it will
+retain your settings when updating your source tree. You can also add
+additional Makefile customizations this way.
+
+### Tips for OSX
+
+Set the ARDUINO environment variable to the location where Arduino with TeensyDuino is installed.
+```bash
+export ARDUINO=~/Downloads/Arduino.app/Contents/Java/
+```
+
+Search /dev/ for USB port name, which will be cu.usbmodem followed by a few numbers. The name of the port maybe different depending on the version of OSX.
+To access the Python prompt type:
+
+```bash
+screen <devicename> 115200
+```
diff --git a/ports/teensy/add-memzip.sh b/ports/teensy/add-memzip.sh
new file mode 100755
index 000000000..a00489eff
--- /dev/null
+++ b/ports/teensy/add-memzip.sh
@@ -0,0 +1,27 @@
+#!/bin/bash
+
+if [ "$#" != 3 ]; then
+ echo "Usage: add-memzip.sh input.hex output.hex file-directory"
+ exit 1
+fi
+
+#set -x
+
+input_hex=$1
+output_hex=$2
+memzip_src_dir=$3
+
+input_bin=${input_hex}.bin
+output_bin=${output_hex}.bin
+zip_file=${output_hex}.zip
+zip_base=$(basename ${zip_file})
+zip_dir=$(dirname ${zip_file})
+abs_zip_dir=$(realpath ${zip_dir})
+
+rm -f ${zip_file}
+(cd ${memzip_src_dir}; zip -0 -r -D ${abs_zip_dir}/${zip_base} .)
+objcopy -I ihex -O binary ${input_hex} ${input_bin}
+cat ${input_bin} ${zip_file} > ${output_bin}
+objcopy -I binary -O ihex ${output_bin} ${output_hex}
+echo "Added ${memzip_src_dir} to ${input_hex} creating ${output_hex}"
+
diff --git a/ports/teensy/core/Arduino.h b/ports/teensy/core/Arduino.h
new file mode 100644
index 000000000..1b053f050
--- /dev/null
+++ b/ports/teensy/core/Arduino.h
@@ -0,0 +1,3 @@
+//#include "WProgram.h"
+#include "core_pins.h"
+#include "pins_arduino.h"
diff --git a/ports/teensy/core/HardwareSerial.h b/ports/teensy/core/HardwareSerial.h
new file mode 100644
index 000000000..439e0f736
--- /dev/null
+++ b/ports/teensy/core/HardwareSerial.h
@@ -0,0 +1,227 @@
+/* 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.
+ */
+
+#ifndef HardwareSerial_h
+#define HardwareSerial_h
+
+#include "mk20dx128.h"
+#include <inttypes.h>
+
+// uncomment to enable 9 bit formats
+//#define SERIAL_9BIT_SUPPORT
+
+
+#define SERIAL_7E1 0x02
+#define SERIAL_7O1 0x03
+#define SERIAL_8N1 0x00
+#define SERIAL_8N2 0x04
+#define SERIAL_8E1 0x06
+#define SERIAL_8O1 0x07
+#define SERIAL_7E1_RXINV 0x12
+#define SERIAL_7O1_RXINV 0x13
+#define SERIAL_8N1_RXINV 0x10
+#define SERIAL_8N2_RXINV 0x14
+#define SERIAL_8E1_RXINV 0x16
+#define SERIAL_8O1_RXINV 0x17
+#define SERIAL_7E1_TXINV 0x22
+#define SERIAL_7O1_TXINV 0x23
+#define SERIAL_8N1_TXINV 0x20
+#define SERIAL_8N2_TXINV 0x24
+#define SERIAL_8E1_TXINV 0x26
+#define SERIAL_8O1_TXINV 0x27
+#define SERIAL_7E1_RXINV_TXINV 0x32
+#define SERIAL_7O1_RXINV_TXINV 0x33
+#define SERIAL_8N1_RXINV_TXINV 0x30
+#define SERIAL_8N2_RXINV_TXINV 0x34
+#define SERIAL_8E1_RXINV_TXINV 0x36
+#define SERIAL_8O1_RXINV_TXINV 0x37
+#ifdef SERIAL_9BIT_SUPPORT
+#define SERIAL_9N1 0x84
+#define SERIAL_9E1 0x8E
+#define SERIAL_9O1 0x8F
+#define SERIAL_9N1_RXINV 0x94
+#define SERIAL_9E1_RXINV 0x9E
+#define SERIAL_9O1_RXINV 0x9F
+#define SERIAL_9N1_TXINV 0xA4
+#define SERIAL_9E1_TXINV 0xAE
+#define SERIAL_9O1_TXINV 0xAF
+#define SERIAL_9N1_RXINV_TXINV 0xB4
+#define SERIAL_9E1_RXINV_TXINV 0xBE
+#define SERIAL_9O1_RXINV_TXINV 0xBF
+#endif
+// bit0: parity, 0=even, 1=odd
+// bit1: parity, 0=disable, 1=enable
+// bit2: mode, 1=9bit, 0=8bit
+// bit3: mode10: 1=10bit, 0=8bit
+// bit4: rxinv, 0=normal, 1=inverted
+// bit5: txinv, 0=normal, 1=inverted
+// bit6: unused
+// bit7: actual data goes into 9th bit
+
+
+#define BAUD2DIV(baud) (((F_CPU * 2) + ((baud) >> 1)) / (baud))
+#define BAUD2DIV3(baud) (((F_BUS * 2) + ((baud) >> 1)) / (baud))
+
+// C language implementation
+//
+#ifdef __cplusplus
+extern "C" {
+#endif
+void serial_begin(uint32_t divisor);
+void serial_format(uint32_t format);
+void serial_end(void);
+void serial_set_transmit_pin(uint8_t pin);
+void serial_putchar(uint32_t c);
+void serial_write(const void *buf, unsigned int count);
+void serial_flush(void);
+int serial_available(void);
+int serial_getchar(void);
+int serial_peek(void);
+void serial_clear(void);
+void serial_print(const char *p);
+void serial_phex(uint32_t n);
+void serial_phex16(uint32_t n);
+void serial_phex32(uint32_t n);
+
+void serial2_begin(uint32_t divisor);
+void serial2_format(uint32_t format);
+void serial2_end(void);
+void serial2_putchar(uint32_t c);
+void serial2_write(const void *buf, unsigned int count);
+void serial2_flush(void);
+int serial2_available(void);
+int serial2_getchar(void);
+int serial2_peek(void);
+void serial2_clear(void);
+
+void serial3_begin(uint32_t divisor);
+void serial3_format(uint32_t format);
+void serial3_end(void);
+void serial3_putchar(uint32_t c);
+void serial3_write(const void *buf, unsigned int count);
+void serial3_flush(void);
+int serial3_available(void);
+int serial3_getchar(void);
+int serial3_peek(void);
+void serial3_clear(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+
+// C++ interface
+//
+#ifdef __cplusplus
+#include "Stream.h"
+class HardwareSerial : public Stream
+{
+public:
+ virtual void begin(uint32_t baud) { serial_begin(BAUD2DIV(baud)); }
+ virtual void begin(uint32_t baud, uint32_t format) {
+ serial_begin(BAUD2DIV(baud));
+ serial_format(format); }
+ virtual void end(void) { serial_end(); }
+ virtual void transmitterEnable(uint8_t pin) { serial_set_transmit_pin(pin); }
+ virtual int available(void) { return serial_available(); }
+ virtual int peek(void) { return serial_peek(); }
+ virtual int read(void) { return serial_getchar(); }
+ virtual void flush(void) { serial_flush(); }
+ virtual void clear(void) { serial_clear(); }
+ virtual size_t write(uint8_t c) { serial_putchar(c); return 1; }
+ virtual size_t write(unsigned long n) { return write((uint8_t)n); }
+ virtual size_t write(long n) { return write((uint8_t)n); }
+ virtual size_t write(unsigned int n) { return write((uint8_t)n); }
+ virtual size_t write(int n) { return write((uint8_t)n); }
+ virtual size_t write(const uint8_t *buffer, size_t size)
+ { serial_write(buffer, size); return size; }
+ virtual size_t write(const char *str) { size_t len = strlen(str);
+ serial_write((const uint8_t *)str, len);
+ return len; }
+ virtual size_t write9bit(uint32_t c) { serial_putchar(c); return 1; }
+};
+extern HardwareSerial Serial1;
+
+class HardwareSerial2 : public HardwareSerial
+{
+public:
+ virtual void begin(uint32_t baud) { serial2_begin(BAUD2DIV(baud)); }
+ virtual void begin(uint32_t baud, uint32_t format) {
+ serial2_begin(BAUD2DIV(baud));
+ serial2_format(format); }
+ virtual void end(void) { serial2_end(); }
+ virtual int available(void) { return serial2_available(); }
+ virtual int peek(void) { return serial2_peek(); }
+ virtual int read(void) { return serial2_getchar(); }
+ virtual void flush(void) { serial2_flush(); }
+ virtual void clear(void) { serial2_clear(); }
+ virtual size_t write(uint8_t c) { serial2_putchar(c); return 1; }
+ virtual size_t write(unsigned long n) { return write((uint8_t)n); }
+ virtual size_t write(long n) { return write((uint8_t)n); }
+ virtual size_t write(unsigned int n) { return write((uint8_t)n); }
+ virtual size_t write(int n) { return write((uint8_t)n); }
+ virtual size_t write(const uint8_t *buffer, size_t size)
+ { serial2_write(buffer, size); return size; }
+ virtual size_t write(const char *str) { size_t len = strlen(str);
+ serial2_write((const uint8_t *)str, len);
+ return len; }
+ virtual size_t write9bit(uint32_t c) { serial2_putchar(c); return 1; }
+};
+extern HardwareSerial2 Serial2;
+
+class HardwareSerial3 : public HardwareSerial
+{
+public:
+ virtual void begin(uint32_t baud) { serial3_begin(BAUD2DIV3(baud)); }
+ virtual void begin(uint32_t baud, uint32_t format) {
+ serial3_begin(BAUD2DIV3(baud));
+ serial3_format(format); }
+ virtual void end(void) { serial3_end(); }
+ virtual int available(void) { return serial3_available(); }
+ virtual int peek(void) { return serial3_peek(); }
+ virtual int read(void) { return serial3_getchar(); }
+ virtual void flush(void) { serial3_flush(); }
+ virtual void clear(void) { serial3_clear(); }
+ virtual size_t write(uint8_t c) { serial3_putchar(c); return 1; }
+ virtual size_t write(unsigned long n) { return write((uint8_t)n); }
+ virtual size_t write(long n) { return write((uint8_t)n); }
+ virtual size_t write(unsigned int n) { return write((uint8_t)n); }
+ virtual size_t write(int n) { return write((uint8_t)n); }
+ virtual size_t write(const uint8_t *buffer, size_t size)
+ { serial3_write(buffer, size); return size; }
+ virtual size_t write(const char *str) { size_t len = strlen(str);
+ serial3_write((const uint8_t *)str, len);
+ return len; }
+ virtual size_t write9bit(uint32_t c) { serial3_putchar(c); return 1; }
+};
+extern HardwareSerial3 Serial3;
+
+#endif
+#endif
diff --git a/ports/teensy/core/analog.c b/ports/teensy/core/analog.c
new file mode 100644
index 000000000..f408ec9f1
--- /dev/null
+++ b/ports/teensy/core/analog.c
@@ -0,0 +1,463 @@
+/* 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.
+ */
+
+#include "core_pins.h"
+//#include "HardwareSerial.h"
+
+static uint8_t calibrating;
+static uint8_t analog_right_shift = 0;
+static uint8_t analog_config_bits = 10;
+static uint8_t analog_num_average = 4;
+static uint8_t analog_reference_internal = 0;
+
+// the alternate clock is connected to OSCERCLK (16 MHz).
+// datasheet says ADC clock should be 2 to 12 MHz for 16 bit mode
+// datasheet says ADC clock should be 1 to 18 MHz for 8-12 bit mode
+
+#if F_BUS == 60000000
+ #define ADC_CFG1_16BIT ADC_CFG1_ADIV(2) + ADC_CFG1_ADICLK(1) // 7.5 MHz
+ #define ADC_CFG1_12BIT ADC_CFG1_ADIV(1) + ADC_CFG1_ADICLK(1) // 15 MHz
+ #define ADC_CFG1_10BIT ADC_CFG1_ADIV(1) + ADC_CFG1_ADICLK(1) // 15 MHz
+ #define ADC_CFG1_8BIT ADC_CFG1_ADIV(1) + ADC_CFG1_ADICLK(1) // 15 MHz
+#elif F_BUS == 56000000
+ #define ADC_CFG1_16BIT ADC_CFG1_ADIV(2) + ADC_CFG1_ADICLK(1) // 7 MHz
+ #define ADC_CFG1_12BIT ADC_CFG1_ADIV(1) + ADC_CFG1_ADICLK(1) // 14 MHz
+ #define ADC_CFG1_10BIT ADC_CFG1_ADIV(1) + ADC_CFG1_ADICLK(1) // 14 MHz
+ #define ADC_CFG1_8BIT ADC_CFG1_ADIV(1) + ADC_CFG1_ADICLK(1) // 14 MHz
+#elif F_BUS == 48000000
+ #define ADC_CFG1_16BIT ADC_CFG1_ADIV(1) + ADC_CFG1_ADICLK(1) // 12 MHz
+ #define ADC_CFG1_12BIT ADC_CFG1_ADIV(1) + ADC_CFG1_ADICLK(1) // 12 MHz
+ #define ADC_CFG1_10BIT ADC_CFG1_ADIV(1) + ADC_CFG1_ADICLK(1) // 12 MHz
+ #define ADC_CFG1_8BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(1) // 24 MHz
+#elif F_BUS == 40000000
+ #define ADC_CFG1_16BIT ADC_CFG1_ADIV(1) + ADC_CFG1_ADICLK(1) // 10 MHz
+ #define ADC_CFG1_12BIT ADC_CFG1_ADIV(1) + ADC_CFG1_ADICLK(1) // 10 MHz
+ #define ADC_CFG1_10BIT ADC_CFG1_ADIV(1) + ADC_CFG1_ADICLK(1) // 10 MHz
+ #define ADC_CFG1_8BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(1) // 20 MHz
+#elif F_BUS == 36000000
+ #define ADC_CFG1_16BIT ADC_CFG1_ADIV(1) + ADC_CFG1_ADICLK(1) // 9 MHz
+ #define ADC_CFG1_12BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(1) // 18 MHz
+ #define ADC_CFG1_10BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(1) // 18 MHz
+ #define ADC_CFG1_8BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(1) // 18 MHz
+#elif F_BUS == 24000000
+ #define ADC_CFG1_16BIT ADC_CFG1_ADIV(1) + ADC_CFG1_ADICLK(0) // 12 MHz
+ #define ADC_CFG1_12BIT ADC_CFG1_ADIV(1) + ADC_CFG1_ADICLK(0) // 12 MHz
+ #define ADC_CFG1_10BIT ADC_CFG1_ADIV(1) + ADC_CFG1_ADICLK(0) // 12 MHz
+ #define ADC_CFG1_8BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(0) // 24 MHz
+#elif F_BUS == 16000000
+ #define ADC_CFG1_16BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(0) // 8 MHz
+ #define ADC_CFG1_12BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(0) // 8 MHz
+ #define ADC_CFG1_10BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(0) // 8 MHz
+ #define ADC_CFG1_8BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(0) // 16 MHz
+#elif F_BUS == 8000000
+ #define ADC_CFG1_16BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(0) // 8 MHz
+ #define ADC_CFG1_12BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(0) // 8 MHz
+ #define ADC_CFG1_10BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(0) // 8 MHz
+ #define ADC_CFG1_8BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(0) // 8 MHz
+#elif F_BUS == 4000000
+ #define ADC_CFG1_16BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(0) // 4 MHz
+ #define ADC_CFG1_12BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(0) // 4 MHz
+ #define ADC_CFG1_10BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(0) // 4 MHz
+ #define ADC_CFG1_8BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(0) // 4 MHz
+#elif F_BUS == 2000000
+ #define ADC_CFG1_16BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(0) // 2 MHz
+ #define ADC_CFG1_12BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(0) // 2 MHz
+ #define ADC_CFG1_10BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(0) // 2 MHz
+ #define ADC_CFG1_8BIT ADC_CFG1_ADIV(0) + ADC_CFG1_ADICLK(0) // 2 MHz
+#else
+#error "F_BUS must be 60, 56, 48, 40, 36, 24, 4 or 2 MHz"
+#endif
+
+void analog_init(void)
+{
+ uint32_t num;
+
+ VREF_TRM = 0x60;
+ VREF_SC = 0xE1; // enable 1.2 volt ref
+
+ if (analog_config_bits == 8) {
+ ADC0_CFG1 = ADC_CFG1_8BIT + ADC_CFG1_MODE(0);
+ ADC0_CFG2 = ADC_CFG2_MUXSEL + ADC_CFG2_ADLSTS(3);
+ #if defined(__MK20DX256__)
+ ADC1_CFG1 = ADC_CFG1_8BIT + ADC_CFG1_MODE(0);
+ ADC1_CFG2 = ADC_CFG2_MUXSEL + ADC_CFG2_ADLSTS(3);
+ #endif
+ } else if (analog_config_bits == 10) {
+ ADC0_CFG1 = ADC_CFG1_10BIT + ADC_CFG1_MODE(2) + ADC_CFG1_ADLSMP;
+ ADC0_CFG2 = ADC_CFG2_MUXSEL + ADC_CFG2_ADLSTS(3);
+ #if defined(__MK20DX256__)
+ ADC1_CFG1 = ADC_CFG1_10BIT + ADC_CFG1_MODE(2) + ADC_CFG1_ADLSMP;
+ ADC1_CFG2 = ADC_CFG2_MUXSEL + ADC_CFG2_ADLSTS(3);
+ #endif
+ } else if (analog_config_bits == 12) {
+ ADC0_CFG1 = ADC_CFG1_12BIT + ADC_CFG1_MODE(1) + ADC_CFG1_ADLSMP;
+ ADC0_CFG2 = ADC_CFG2_MUXSEL + ADC_CFG2_ADLSTS(2);
+ #if defined(__MK20DX256__)
+ ADC1_CFG1 = ADC_CFG1_12BIT + ADC_CFG1_MODE(1) + ADC_CFG1_ADLSMP;
+ ADC1_CFG2 = ADC_CFG2_MUXSEL + ADC_CFG2_ADLSTS(2);
+ #endif
+ } else {
+ ADC0_CFG1 = ADC_CFG1_16BIT + ADC_CFG1_MODE(3) + ADC_CFG1_ADLSMP;
+ ADC0_CFG2 = ADC_CFG2_MUXSEL + ADC_CFG2_ADLSTS(2);
+ #if defined(__MK20DX256__)
+ ADC1_CFG1 = ADC_CFG1_16BIT + ADC_CFG1_MODE(3) + ADC_CFG1_ADLSMP;
+ ADC1_CFG2 = ADC_CFG2_MUXSEL + ADC_CFG2_ADLSTS(2);
+ #endif
+ }
+
+ if (analog_reference_internal) {
+ ADC0_SC2 = ADC_SC2_REFSEL(1); // 1.2V ref
+ #if defined(__MK20DX256__)
+ ADC1_SC2 = ADC_SC2_REFSEL(1); // 1.2V ref
+ #endif
+ } else {
+ ADC0_SC2 = ADC_SC2_REFSEL(0); // vcc/ext ref
+ #if defined(__MK20DX256__)
+ ADC1_SC2 = ADC_SC2_REFSEL(0); // vcc/ext ref
+ #endif
+ }
+
+ num = analog_num_average;
+ if (num <= 1) {
+ ADC0_SC3 = ADC_SC3_CAL; // begin cal
+ #if defined(__MK20DX256__)
+ ADC1_SC3 = ADC_SC3_CAL; // begin cal
+ #endif
+ } else if (num <= 4) {
+ ADC0_SC3 = ADC_SC3_CAL + ADC_SC3_AVGE + ADC_SC3_AVGS(0);
+ #if defined(__MK20DX256__)
+ ADC1_SC3 = ADC_SC3_CAL + ADC_SC3_AVGE + ADC_SC3_AVGS(0);
+ #endif
+ } else if (num <= 8) {
+ ADC0_SC3 = ADC_SC3_CAL + ADC_SC3_AVGE + ADC_SC3_AVGS(1);
+ #if defined(__MK20DX256__)
+ ADC1_SC3 = ADC_SC3_CAL + ADC_SC3_AVGE + ADC_SC3_AVGS(1);
+ #endif
+ } else if (num <= 16) {
+ ADC0_SC3 = ADC_SC3_CAL + ADC_SC3_AVGE + ADC_SC3_AVGS(2);
+ #if defined(__MK20DX256__)
+ ADC1_SC3 = ADC_SC3_CAL + ADC_SC3_AVGE + ADC_SC3_AVGS(2);
+ #endif
+ } else {
+ ADC0_SC3 = ADC_SC3_CAL + ADC_SC3_AVGE + ADC_SC3_AVGS(3);
+ #if defined(__MK20DX256__)
+ ADC1_SC3 = ADC_SC3_CAL + ADC_SC3_AVGE + ADC_SC3_AVGS(3);
+ #endif
+ }
+ calibrating = 1;
+}
+
+static void wait_for_cal(void)
+{
+ uint16_t sum;
+
+ //serial_print("wait_for_cal\n");
+#if defined(__MK20DX128__)
+ while (ADC0_SC3 & ADC_SC3_CAL) {
+ // wait
+ }
+#elif defined(__MK20DX256__)
+ while ((ADC0_SC3 & ADC_SC3_CAL) || (ADC1_SC3 & ADC_SC3_CAL)) {
+ // wait
+ }
+#endif
+ __disable_irq();
+ if (calibrating) {
+ //serial_print("\n");
+ sum = ADC0_CLPS + ADC0_CLP4 + ADC0_CLP3 + ADC0_CLP2 + ADC0_CLP1 + ADC0_CLP0;
+ sum = (sum / 2) | 0x8000;
+ ADC0_PG = sum;
+ //serial_print("ADC0_PG = ");
+ //serial_phex16(sum);
+ //serial_print("\n");
+ sum = ADC0_CLMS + ADC0_CLM4 + ADC0_CLM3 + ADC0_CLM2 + ADC0_CLM1 + ADC0_CLM0;
+ sum = (sum / 2) | 0x8000;
+ ADC0_MG = sum;
+ //serial_print("ADC0_MG = ");
+ //serial_phex16(sum);
+ //serial_print("\n");
+#if defined(__MK20DX256__)
+ sum = ADC1_CLPS + ADC1_CLP4 + ADC1_CLP3 + ADC1_CLP2 + ADC1_CLP1 + ADC1_CLP0;
+ sum = (sum / 2) | 0x8000;
+ ADC1_PG = sum;
+ sum = ADC1_CLMS + ADC1_CLM4 + ADC1_CLM3 + ADC1_CLM2 + ADC1_CLM1 + ADC1_CLM0;
+ sum = (sum / 2) | 0x8000;
+ ADC1_MG = sum;
+#endif
+ calibrating = 0;
+ }
+ __enable_irq();
+}
+
+// ADCx_SC2[REFSEL] bit selects the voltage reference sources for ADC.
+// VREFH/VREFL - connected as the primary reference option
+// 1.2 V VREF_OUT - connected as the VALT reference option
+
+
+#define DEFAULT 0
+#define INTERNAL 2
+#define INTERNAL1V2 2
+#define INTERNAL1V1 2
+#define EXTERNAL 0
+
+void analogReference(uint8_t type)
+{
+ if (type) {
+ // internal reference requested
+ if (!analog_reference_internal) {
+ analog_reference_internal = 1;
+ if (calibrating) {
+ ADC0_SC3 = 0; // cancel cal
+#if defined(__MK20DX256__)
+ ADC1_SC3 = 0; // cancel cal
+#endif
+ }
+ analog_init();
+ }
+ } else {
+ // vcc or external reference requested
+ if (analog_reference_internal) {
+ analog_reference_internal = 0;
+ if (calibrating) {
+ ADC0_SC3 = 0; // cancel cal
+#if defined(__MK20DX256__)
+ ADC1_SC3 = 0; // cancel cal
+#endif
+ }
+ analog_init();
+ }
+ }
+}
+
+
+void analogReadRes(unsigned int bits)
+{
+ unsigned int config;
+
+ if (bits >= 13) {
+ if (bits > 16) bits = 16;
+ config = 16;
+ } else if (bits >= 11) {
+ config = 12;
+ } else if (bits >= 9) {
+ config = 10;
+ } else {
+ config = 8;
+ }
+ analog_right_shift = config - bits;
+ if (config != analog_config_bits) {
+ analog_config_bits = config;
+ if (calibrating) ADC0_SC3 = 0; // cancel cal
+ analog_init();
+ }
+}
+
+void analogReadAveraging(unsigned int num)
+{
+
+ if (calibrating) wait_for_cal();
+ if (num <= 1) {
+ num = 0;
+ ADC0_SC3 = 0;
+ } else if (num <= 4) {
+ num = 4;
+ ADC0_SC3 = ADC_SC3_AVGE + ADC_SC3_AVGS(0);
+ } else if (num <= 8) {
+ num = 8;
+ ADC0_SC3 = ADC_SC3_AVGE + ADC_SC3_AVGS(1);
+ } else if (num <= 16) {
+ num = 16;
+ ADC0_SC3 = ADC_SC3_AVGE + ADC_SC3_AVGS(2);
+ } else {
+ num = 32;
+ ADC0_SC3 = ADC_SC3_AVGE + ADC_SC3_AVGS(3);
+ }
+ analog_num_average = num;
+}
+
+// The SC1A register is used for both software and hardware trigger modes of operation.
+
+#if defined(__MK20DX128__)
+static const uint8_t channel2sc1a[] = {
+ 5, 14, 8, 9, 13, 12, 6, 7, 15, 4,
+ 0, 19, 3, 21, 26, 22, 23
+};
+#elif defined(__MK20DX256__)
+static const uint8_t channel2sc1a[] = {
+ 5, 14, 8, 9, 13, 12, 6, 7, 15, 4,
+ 0, 19, 3, 19+128, 26, 18+128, 23,
+ 5+192, 5+128, 4+128, 6+128, 7+128, 4+192
+// A15 26 E1 ADC1_SE5a 5+64
+// A16 27 C9 ADC1_SE5b 5
+// A17 28 C8 ADC1_SE4b 4
+// A18 29 C10 ADC1_SE6b 6
+// A19 30 C11 ADC1_SE7b 7
+// A20 31 E0 ADC1_SE4a 4+64
+};
+#endif
+
+
+
+// TODO: perhaps this should store the NVIC priority, so it works recursively?
+static volatile uint8_t analogReadBusyADC0 = 0;
+#if defined(__MK20DX256__)
+static volatile uint8_t analogReadBusyADC1 = 0;
+#endif
+
+int analogRead(uint8_t pin)
+{
+ int result;
+ uint8_t index, channel;
+
+ //serial_phex(pin);
+ //serial_print(" ");
+
+ if (pin <= 13) {
+ index = pin; // 0-13 refer to A0-A13
+ } else if (pin <= 23) {
+ index = pin - 14; // 14-23 are A0-A9
+#if defined(__MK20DX256__)
+ } else if (pin >= 26 && pin <= 31) {
+ index = pin - 9; // 26-31 are A15-A20
+#endif
+ } else if (pin >= 34 && pin <= 40) {
+ index = pin - 24; // 34-37 are A10-A13, 38 is temp sensor,
+ // 39 is vref, 40 is unused (A14 on Teensy 3.1)
+ } else {
+ return 0; // all others are invalid
+ }
+
+ //serial_phex(index);
+ //serial_print(" ");
+
+ channel = channel2sc1a[index];
+ //serial_phex(channel);
+ //serial_print(" ");
+
+ //serial_print("analogRead");
+ //return 0;
+ if (calibrating) wait_for_cal();
+ //pin = 5; // PTD1/SE5b, pin 14, analog 0
+
+#if defined(__MK20DX256__)
+ if (channel & 0x80) goto beginADC1;
+#endif
+
+ __disable_irq();
+startADC0:
+ //serial_print("startADC0\n");
+ ADC0_SC1A = channel;
+ analogReadBusyADC0 = 1;
+ __enable_irq();
+ while (1) {
+ __disable_irq();
+ if ((ADC0_SC1A & ADC_SC1_COCO)) {
+ result = ADC0_RA;
+ analogReadBusyADC0 = 0;
+ __enable_irq();
+ result >>= analog_right_shift;
+ return result;
+ }
+ // detect if analogRead was used from an interrupt
+ // if so, our analogRead got canceled, so it must
+ // be restarted.
+ if (!analogReadBusyADC0) goto startADC0;
+ __enable_irq();
+ yield();
+ }
+
+#if defined(__MK20DX256__)
+beginADC1:
+ __disable_irq();
+startADC1:
+ //serial_print("startADC0\n");
+ // ADC1_CFG2[MUXSEL] bit selects between ADCx_SEn channels a and b.
+ if (channel & 0x40) {
+ ADC1_CFG2 &= ~ADC_CFG2_MUXSEL;
+ } else {
+ ADC1_CFG2 |= ADC_CFG2_MUXSEL;
+ }
+ ADC1_SC1A = channel & 0x3F;
+ analogReadBusyADC1 = 1;
+ __enable_irq();
+ while (1) {
+ __disable_irq();
+ if ((ADC1_SC1A & ADC_SC1_COCO)) {
+ result = ADC1_RA;
+ analogReadBusyADC1 = 0;
+ __enable_irq();
+ result >>= analog_right_shift;
+ return result;
+ }
+ // detect if analogRead was used from an interrupt
+ // if so, our analogRead got canceled, so it must
+ // be restarted.
+ if (!analogReadBusyADC1) goto startADC1;
+ __enable_irq();
+ yield();
+ }
+#endif
+}
+
+
+
+void analogWriteDAC0(int val)
+{
+#if defined(__MK20DX256__)
+ SIM_SCGC2 |= SIM_SCGC2_DAC0;
+ if (analog_reference_internal) {
+ DAC0_C0 = DAC_C0_DACEN; // 1.2V ref is DACREF_1
+ } else {
+ DAC0_C0 = DAC_C0_DACEN | DAC_C0_DACRFS; // 3.3V VDDA is DACREF_2
+ }
+ if (val < 0) val = 0; // TODO: saturate instruction?
+ else if (val > 4095) val = 4095;
+ *(int16_t *)&(DAC0_DAT0L) = val;
+#endif
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/ports/teensy/core/avr_functions.h b/ports/teensy/core/avr_functions.h
new file mode 100644
index 000000000..fe99f26f3
--- /dev/null
+++ b/ports/teensy/core/avr_functions.h
@@ -0,0 +1,107 @@
+/* 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.
+ */
+
+#ifndef _avr_functions_h_
+#define _avr_functions_h_
+
+#include <inttypes.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void eeprom_initialize(void);
+uint8_t eeprom_read_byte(const uint8_t *addr) __attribute__ ((pure));
+uint16_t eeprom_read_word(const uint16_t *addr) __attribute__ ((pure));
+uint32_t eeprom_read_dword(const uint32_t *addr) __attribute__ ((pure));
+void eeprom_read_block(void *buf, const void *addr, uint32_t len);
+void eeprom_write_byte(uint8_t *addr, uint8_t value);
+void eeprom_write_word(uint16_t *addr, uint16_t value);
+void eeprom_write_dword(uint32_t *addr, uint32_t value);
+void eeprom_write_block(const void *buf, void *addr, uint32_t len);
+int eeprom_is_ready(void);
+#define eeprom_busy_wait() do {} while (!eeprom_is_ready())
+
+static inline float eeprom_read_float(const float *addr) __attribute__((pure, always_inline, unused));
+static inline float eeprom_read_float(const float *addr)
+{
+ union {float f; uint32_t u32;} u;
+ u.u32 = eeprom_read_dword((const uint32_t *)addr);
+ return u.f;
+}
+static inline void eeprom_write_float(float *addr, float value) __attribute__((always_inline, unused));
+static inline void eeprom_write_float(float *addr, float value)
+{
+ union {float f; uint32_t u32;} u;
+ u.f = value;
+ eeprom_write_dword((uint32_t *)addr, u.u32);
+}
+static inline void eeprom_update_byte(uint8_t *addr, uint8_t value) __attribute__((always_inline, unused));
+static inline void eeprom_update_byte(uint8_t *addr, uint8_t value)
+{
+ eeprom_write_byte(addr, value);
+}
+static inline void eeprom_update_word(uint16_t *addr, uint16_t value) __attribute__((always_inline, unused));
+static inline void eeprom_update_word(uint16_t *addr, uint16_t value)
+{
+ eeprom_write_word(addr, value);
+}
+static inline void eeprom_update_dword(uint32_t *addr, uint32_t value) __attribute__((always_inline, unused));
+static inline void eeprom_update_dword(uint32_t *addr, uint32_t value)
+{
+ eeprom_write_dword(addr, value);
+}
+static inline void eeprom_update_float(float *addr, float value) __attribute__((always_inline, unused));
+static inline void eeprom_update_float(float *addr, float value)
+{
+ union {float f; uint32_t u32;} u;
+ u.f = value;
+ eeprom_write_dword((uint32_t *)addr, u.u32);
+}
+static inline void eeprom_update_block(const void *buf, void *addr, uint32_t len) __attribute__((always_inline, unused));
+static inline void eeprom_update_block(const void *buf, void *addr, uint32_t len)
+{
+ eeprom_write_block(buf, addr, len);
+}
+
+
+char * ultoa(unsigned long val, char *buf, int radix);
+char * ltoa(long val, char *buf, int radix);
+static inline char * utoa(unsigned int val, char *buf, int radix) __attribute__((always_inline, unused));
+static inline char * utoa(unsigned int val, char *buf, int radix) { return ultoa(val, buf, radix); }
+static inline char * itoa(int val, char *buf, int radix) __attribute__((always_inline, unused));
+static inline char * itoa(int val, char *buf, int radix) { return ltoa(val, buf, radix); }
+char * dtostrf(float val, int width, unsigned int precision, char *buf);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/ports/teensy/core/core_pins.h b/ports/teensy/core/core_pins.h
new file mode 100644
index 000000000..169bf3c16
--- /dev/null
+++ b/ports/teensy/core/core_pins.h
@@ -0,0 +1,841 @@
+/* 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.
+ */
+
+#ifndef _core_pins_h_
+#define _core_pins_h_
+
+#include "mk20dx128.h"
+#include "pins_arduino.h"
+
+
+#define HIGH 1
+#define LOW 0
+#define INPUT 0
+#define OUTPUT 1
+#define INPUT_PULLUP 2
+#define LSBFIRST 0
+#define MSBFIRST 1
+#define _BV(n) (1<<(n))
+#define CHANGE 4
+#define FALLING 2
+#define RISING 3
+
+// Pin Arduino
+// 0 B16 RXD
+// 1 B17 TXD
+// 2 D0
+// 3 A12 FTM1_CH0
+// 4 A13 FTM1_CH1
+// 5 D7 FTM0_CH7 OC0B/T1
+// 6 D4 FTM0_CH4 OC0A
+// 7 D2
+// 8 D3 ICP1
+// 9 C3 FTM0_CH2 OC1A
+// 10 C4 FTM0_CH3 SS/OC1B
+// 11 C6 MOSI/OC2A
+// 12 C7 MISO
+// 13 C5 SCK
+// 14 D1
+// 15 C0
+// 16 B0 (FTM1_CH0)
+// 17 B1 (FTM1_CH1)
+// 18 B3 SDA
+// 19 B2 SCL
+// 20 D5 FTM0_CH5
+// 21 D6 FTM0_CH6
+// 22 C1 FTM0_CH0
+// 23 C2 FTM0_CH1
+// 24 A5 (FTM0_CH2)
+// 25 B19
+// 26 E1
+// 27 C9
+// 28 C8
+// 29 C10
+// 30 C11
+// 31 E0
+// 32 B18
+// 33 A4 (FTM0_CH1)
+// (34) analog only
+// (35) analog only
+// (36) analog only
+// (37) analog only
+
+// not available to user:
+// A0 FTM0_CH5 SWD Clock
+// A1 FTM0_CH6 USB ID
+// A2 FTM0_CH7 SWD Trace
+// A3 FTM0_CH0 SWD Data
+
+#define CORE_NUM_TOTAL_PINS 34
+#define CORE_NUM_DIGITAL 34
+#define CORE_NUM_INTERRUPT 34
+#if defined(__MK20DX128__)
+#define CORE_NUM_ANALOG 14
+#define CORE_NUM_PWM 10
+#elif defined(__MK20DX256__)
+#define CORE_NUM_ANALOG 21
+#define CORE_NUM_PWM 12
+#endif
+
+#define CORE_PIN0_BIT 16
+#define CORE_PIN1_BIT 17
+#define CORE_PIN2_BIT 0
+#define CORE_PIN3_BIT 12
+#define CORE_PIN4_BIT 13
+#define CORE_PIN5_BIT 7
+#define CORE_PIN6_BIT 4
+#define CORE_PIN7_BIT 2
+#define CORE_PIN8_BIT 3
+#define CORE_PIN9_BIT 3
+#define CORE_PIN10_BIT 4
+#define CORE_PIN11_BIT 6
+#define CORE_PIN12_BIT 7
+#define CORE_PIN13_BIT 5
+#define CORE_PIN14_BIT 1
+#define CORE_PIN15_BIT 0
+#define CORE_PIN16_BIT 0
+#define CORE_PIN17_BIT 1
+#define CORE_PIN18_BIT 3
+#define CORE_PIN19_BIT 2
+#define CORE_PIN20_BIT 5
+#define CORE_PIN21_BIT 6
+#define CORE_PIN22_BIT 1
+#define CORE_PIN23_BIT 2
+#define CORE_PIN24_BIT 5
+#define CORE_PIN25_BIT 19
+#define CORE_PIN26_BIT 1
+#define CORE_PIN27_BIT 9
+#define CORE_PIN28_BIT 8
+#define CORE_PIN29_BIT 10
+#define CORE_PIN30_BIT 11
+#define CORE_PIN31_BIT 0
+#define CORE_PIN32_BIT 18
+#define CORE_PIN33_BIT 4
+
+#define CORE_PIN0_BITMASK (1<<(CORE_PIN0_BIT))
+#define CORE_PIN1_BITMASK (1<<(CORE_PIN1_BIT))
+#define CORE_PIN2_BITMASK (1<<(CORE_PIN2_BIT))
+#define CORE_PIN3_BITMASK (1<<(CORE_PIN3_BIT))
+#define CORE_PIN4_BITMASK (1<<(CORE_PIN4_BIT))
+#define CORE_PIN5_BITMASK (1<<(CORE_PIN5_BIT))
+#define CORE_PIN6_BITMASK (1<<(CORE_PIN6_BIT))
+#define CORE_PIN7_BITMASK (1<<(CORE_PIN7_BIT))
+#define CORE_PIN8_BITMASK (1<<(CORE_PIN8_BIT))
+#define CORE_PIN9_BITMASK (1<<(CORE_PIN9_BIT))
+#define CORE_PIN10_BITMASK (1<<(CORE_PIN10_BIT))
+#define CORE_PIN11_BITMASK (1<<(CORE_PIN11_BIT))
+#define CORE_PIN12_BITMASK (1<<(CORE_PIN12_BIT))
+#define CORE_PIN13_BITMASK (1<<(CORE_PIN13_BIT))
+#define CORE_PIN14_BITMASK (1<<(CORE_PIN14_BIT))
+#define CORE_PIN15_BITMASK (1<<(CORE_PIN15_BIT))
+#define CORE_PIN16_BITMASK (1<<(CORE_PIN16_BIT))
+#define CORE_PIN17_BITMASK (1<<(CORE_PIN17_BIT))
+#define CORE_PIN18_BITMASK (1<<(CORE_PIN18_BIT))
+#define CORE_PIN19_BITMASK (1<<(CORE_PIN19_BIT))
+#define CORE_PIN20_BITMASK (1<<(CORE_PIN20_BIT))
+#define CORE_PIN21_BITMASK (1<<(CORE_PIN21_BIT))
+#define CORE_PIN22_BITMASK (1<<(CORE_PIN22_BIT))
+#define CORE_PIN23_BITMASK (1<<(CORE_PIN23_BIT))
+#define CORE_PIN24_BITMASK (1<<(CORE_PIN24_BIT))
+#define CORE_PIN25_BITMASK (1<<(CORE_PIN25_BIT))
+#define CORE_PIN26_BITMASK (1<<(CORE_PIN26_BIT))
+#define CORE_PIN27_BITMASK (1<<(CORE_PIN27_BIT))
+#define CORE_PIN28_BITMASK (1<<(CORE_PIN28_BIT))
+#define CORE_PIN29_BITMASK (1<<(CORE_PIN29_BIT))
+#define CORE_PIN30_BITMASK (1<<(CORE_PIN30_BIT))
+#define CORE_PIN31_BITMASK (1<<(CORE_PIN31_BIT))
+#define CORE_PIN32_BITMASK (1<<(CORE_PIN32_BIT))
+#define CORE_PIN33_BITMASK (1<<(CORE_PIN33_BIT))
+
+#define CORE_PIN0_PORTREG GPIOB_PDOR
+#define CORE_PIN1_PORTREG GPIOB_PDOR
+#define CORE_PIN2_PORTREG GPIOD_PDOR
+#define CORE_PIN3_PORTREG GPIOA_PDOR
+#define CORE_PIN4_PORTREG GPIOA_PDOR
+#define CORE_PIN5_PORTREG GPIOD_PDOR
+#define CORE_PIN6_PORTREG GPIOD_PDOR
+#define CORE_PIN7_PORTREG GPIOD_PDOR
+#define CORE_PIN8_PORTREG GPIOD_PDOR
+#define CORE_PIN9_PORTREG GPIOC_PDOR
+#define CORE_PIN10_PORTREG GPIOC_PDOR
+#define CORE_PIN11_PORTREG GPIOC_PDOR
+#define CORE_PIN12_PORTREG GPIOC_PDOR
+#define CORE_PIN13_PORTREG GPIOC_PDOR
+#define CORE_PIN14_PORTREG GPIOD_PDOR
+#define CORE_PIN15_PORTREG GPIOC_PDOR
+#define CORE_PIN16_PORTREG GPIOB_PDOR
+#define CORE_PIN17_PORTREG GPIOB_PDOR
+#define CORE_PIN18_PORTREG GPIOB_PDOR
+#define CORE_PIN19_PORTREG GPIOB_PDOR
+#define CORE_PIN20_PORTREG GPIOD_PDOR
+#define CORE_PIN21_PORTREG GPIOD_PDOR
+#define CORE_PIN22_PORTREG GPIOC_PDOR
+#define CORE_PIN23_PORTREG GPIOC_PDOR
+#define CORE_PIN24_PORTREG GPIOA_PDOR
+#define CORE_PIN25_PORTREG GPIOB_PDOR
+#define CORE_PIN26_PORTREG GPIOE_PDOR
+#define CORE_PIN27_PORTREG GPIOC_PDOR
+#define CORE_PIN28_PORTREG GPIOC_PDOR
+#define CORE_PIN29_PORTREG GPIOC_PDOR
+#define CORE_PIN30_PORTREG GPIOC_PDOR
+#define CORE_PIN31_PORTREG GPIOE_PDOR
+#define CORE_PIN32_PORTREG GPIOB_PDOR
+#define CORE_PIN33_PORTREG GPIOA_PDOR
+
+#define CORE_PIN0_PORTSET GPIOB_PSOR
+#define CORE_PIN1_PORTSET GPIOB_PSOR
+#define CORE_PIN2_PORTSET GPIOD_PSOR
+#define CORE_PIN3_PORTSET GPIOA_PSOR
+#define CORE_PIN4_PORTSET GPIOA_PSOR
+#define CORE_PIN5_PORTSET GPIOD_PSOR
+#define CORE_PIN6_PORTSET GPIOD_PSOR
+#define CORE_PIN7_PORTSET GPIOD_PSOR
+#define CORE_PIN8_PORTSET GPIOD_PSOR
+#define CORE_PIN9_PORTSET GPIOC_PSOR
+#define CORE_PIN10_PORTSET GPIOC_PSOR
+#define CORE_PIN11_PORTSET GPIOC_PSOR
+#define CORE_PIN12_PORTSET GPIOC_PSOR
+#define CORE_PIN13_PORTSET GPIOC_PSOR
+#define CORE_PIN14_PORTSET GPIOD_PSOR
+#define CORE_PIN15_PORTSET GPIOC_PSOR
+#define CORE_PIN16_PORTSET GPIOB_PSOR
+#define CORE_PIN17_PORTSET GPIOB_PSOR
+#define CORE_PIN18_PORTSET GPIOB_PSOR
+#define CORE_PIN19_PORTSET GPIOB_PSOR
+#define CORE_PIN20_PORTSET GPIOD_PSOR
+#define CORE_PIN21_PORTSET GPIOD_PSOR
+#define CORE_PIN22_PORTSET GPIOC_PSOR
+#define CORE_PIN23_PORTSET GPIOC_PSOR
+#define CORE_PIN24_PORTSET GPIOA_PSOR
+#define CORE_PIN25_PORTSET GPIOB_PSOR
+#define CORE_PIN26_PORTSET GPIOE_PSOR
+#define CORE_PIN27_PORTSET GPIOC_PSOR
+#define CORE_PIN28_PORTSET GPIOC_PSOR
+#define CORE_PIN29_PORTSET GPIOC_PSOR
+#define CORE_PIN30_PORTSET GPIOC_PSOR
+#define CORE_PIN31_PORTSET GPIOE_PSOR
+#define CORE_PIN32_PORTSET GPIOB_PSOR
+#define CORE_PIN33_PORTSET GPIOA_PSOR
+
+#define CORE_PIN0_PORTCLEAR GPIOB_PCOR
+#define CORE_PIN1_PORTCLEAR GPIOB_PCOR
+#define CORE_PIN2_PORTCLEAR GPIOD_PCOR
+#define CORE_PIN3_PORTCLEAR GPIOA_PCOR
+#define CORE_PIN4_PORTCLEAR GPIOA_PCOR
+#define CORE_PIN5_PORTCLEAR GPIOD_PCOR
+#define CORE_PIN6_PORTCLEAR GPIOD_PCOR
+#define CORE_PIN7_PORTCLEAR GPIOD_PCOR
+#define CORE_PIN8_PORTCLEAR GPIOD_PCOR
+#define CORE_PIN9_PORTCLEAR GPIOC_PCOR
+#define CORE_PIN10_PORTCLEAR GPIOC_PCOR
+#define CORE_PIN11_PORTCLEAR GPIOC_PCOR
+#define CORE_PIN12_PORTCLEAR GPIOC_PCOR
+#define CORE_PIN13_PORTCLEAR GPIOC_PCOR
+#define CORE_PIN14_PORTCLEAR GPIOD_PCOR
+#define CORE_PIN15_PORTCLEAR GPIOC_PCOR
+#define CORE_PIN16_PORTCLEAR GPIOB_PCOR
+#define CORE_PIN17_PORTCLEAR GPIOB_PCOR
+#define CORE_PIN18_PORTCLEAR GPIOB_PCOR
+#define CORE_PIN19_PORTCLEAR GPIOB_PCOR
+#define CORE_PIN20_PORTCLEAR GPIOD_PCOR
+#define CORE_PIN21_PORTCLEAR GPIOD_PCOR
+#define CORE_PIN22_PORTCLEAR GPIOC_PCOR
+#define CORE_PIN23_PORTCLEAR GPIOC_PCOR
+#define CORE_PIN24_PORTCLEAR GPIOA_PCOR
+#define CORE_PIN25_PORTCLEAR GPIOB_PCOR
+#define CORE_PIN26_PORTCLEAR GPIOE_PCOR
+#define CORE_PIN27_PORTCLEAR GPIOC_PCOR
+#define CORE_PIN28_PORTCLEAR GPIOC_PCOR
+#define CORE_PIN29_PORTCLEAR GPIOC_PCOR
+#define CORE_PIN30_PORTCLEAR GPIOC_PCOR
+#define CORE_PIN31_PORTCLEAR GPIOE_PCOR
+#define CORE_PIN32_PORTCLEAR GPIOB_PCOR
+#define CORE_PIN33_PORTCLEAR GPIOA_PCOR
+
+#define CORE_PIN0_DDRREG GPIOB_PDDR
+#define CORE_PIN1_DDRREG GPIOB_PDDR
+#define CORE_PIN2_DDRREG GPIOD_PDDR
+#define CORE_PIN3_DDRREG GPIOA_PDDR
+#define CORE_PIN4_DDRREG GPIOA_PDDR
+#define CORE_PIN5_DDRREG GPIOD_PDDR
+#define CORE_PIN6_DDRREG GPIOD_PDDR
+#define CORE_PIN7_DDRREG GPIOD_PDDR
+#define CORE_PIN8_DDRREG GPIOD_PDDR
+#define CORE_PIN9_DDRREG GPIOC_PDDR
+#define CORE_PIN10_DDRREG GPIOC_PDDR
+#define CORE_PIN11_DDRREG GPIOC_PDDR
+#define CORE_PIN12_DDRREG GPIOC_PDDR
+#define CORE_PIN13_DDRREG GPIOC_PDDR
+#define CORE_PIN14_DDRREG GPIOD_PDDR
+#define CORE_PIN15_DDRREG GPIOC_PDDR
+#define CORE_PIN16_DDRREG GPIOB_PDDR
+#define CORE_PIN17_DDRREG GPIOB_PDDR
+#define CORE_PIN18_DDRREG GPIOB_PDDR
+#define CORE_PIN19_DDRREG GPIOB_PDDR
+#define CORE_PIN20_DDRREG GPIOD_PDDR
+#define CORE_PIN21_DDRREG GPIOD_PDDR
+#define CORE_PIN22_DDRREG GPIOC_PDDR
+#define CORE_PIN23_DDRREG GPIOC_PDDR
+#define CORE_PIN24_DDRREG GPIOA_PDDR
+#define CORE_PIN25_DDRREG GPIOB_PDDR
+#define CORE_PIN26_DDRREG GPIOE_PDDR
+#define CORE_PIN27_DDRREG GPIOC_PDDR
+#define CORE_PIN28_DDRREG GPIOC_PDDR
+#define CORE_PIN29_DDRREG GPIOC_PDDR
+#define CORE_PIN30_DDRREG GPIOC_PDDR
+#define CORE_PIN31_DDRREG GPIOE_PDDR
+#define CORE_PIN32_DDRREG GPIOB_PDDR
+#define CORE_PIN33_DDRREG GPIOA_PDDR
+
+#define CORE_PIN0_PINREG GPIOB_PDIR
+#define CORE_PIN1_PINREG GPIOB_PDIR
+#define CORE_PIN2_PINREG GPIOD_PDIR
+#define CORE_PIN3_PINREG GPIOA_PDIR
+#define CORE_PIN4_PINREG GPIOA_PDIR
+#define CORE_PIN5_PINREG GPIOD_PDIR
+#define CORE_PIN6_PINREG GPIOD_PDIR
+#define CORE_PIN7_PINREG GPIOD_PDIR
+#define CORE_PIN8_PINREG GPIOD_PDIR
+#define CORE_PIN9_PINREG GPIOC_PDIR
+#define CORE_PIN10_PINREG GPIOC_PDIR
+#define CORE_PIN11_PINREG GPIOC_PDIR
+#define CORE_PIN12_PINREG GPIOC_PDIR
+#define CORE_PIN13_PINREG GPIOC_PDIR
+#define CORE_PIN14_PINREG GPIOD_PDIR
+#define CORE_PIN15_PINREG GPIOC_PDIR
+#define CORE_PIN16_PINREG GPIOB_PDIR
+#define CORE_PIN17_PINREG GPIOB_PDIR
+#define CORE_PIN18_PINREG GPIOB_PDIR
+#define CORE_PIN19_PINREG GPIOB_PDIR
+#define CORE_PIN20_PINREG GPIOD_PDIR
+#define CORE_PIN21_PINREG GPIOD_PDIR
+#define CORE_PIN22_PINREG GPIOC_PDIR
+#define CORE_PIN23_PINREG GPIOC_PDIR
+#define CORE_PIN24_PINREG GPIOA_PDIR
+#define CORE_PIN25_PINREG GPIOB_PDIR
+#define CORE_PIN26_PINREG GPIOE_PDIR
+#define CORE_PIN27_PINREG GPIOC_PDIR
+#define CORE_PIN28_PINREG GPIOC_PDIR
+#define CORE_PIN29_PINREG GPIOC_PDIR
+#define CORE_PIN30_PINREG GPIOC_PDIR
+#define CORE_PIN31_PINREG GPIOE_PDIR
+#define CORE_PIN32_PINREG GPIOB_PDIR
+#define CORE_PIN33_PINREG GPIOA_PDIR
+
+#define CORE_PIN0_CONFIG PORTB_PCR16
+#define CORE_PIN1_CONFIG PORTB_PCR17
+#define CORE_PIN2_CONFIG PORTD_PCR0
+#define CORE_PIN3_CONFIG PORTA_PCR12
+#define CORE_PIN4_CONFIG PORTA_PCR13
+#define CORE_PIN5_CONFIG PORTD_PCR7
+#define CORE_PIN6_CONFIG PORTD_PCR4
+#define CORE_PIN7_CONFIG PORTD_PCR2
+#define CORE_PIN8_CONFIG PORTD_PCR3
+#define CORE_PIN9_CONFIG PORTC_PCR3
+#define CORE_PIN10_CONFIG PORTC_PCR4
+#define CORE_PIN11_CONFIG PORTC_PCR6
+#define CORE_PIN12_CONFIG PORTC_PCR7
+#define CORE_PIN13_CONFIG PORTC_PCR5
+#define CORE_PIN14_CONFIG PORTD_PCR1
+#define CORE_PIN15_CONFIG PORTC_PCR0
+#define CORE_PIN16_CONFIG PORTB_PCR0
+#define CORE_PIN17_CONFIG PORTB_PCR1
+#define CORE_PIN18_CONFIG PORTB_PCR3
+#define CORE_PIN19_CONFIG PORTB_PCR2
+#define CORE_PIN20_CONFIG PORTD_PCR5
+#define CORE_PIN21_CONFIG PORTD_PCR6
+#define CORE_PIN22_CONFIG PORTC_PCR1
+#define CORE_PIN23_CONFIG PORTC_PCR2
+#define CORE_PIN24_CONFIG PORTA_PCR5
+#define CORE_PIN25_CONFIG PORTB_PCR19
+#define CORE_PIN26_CONFIG PORTE_PCR1
+#define CORE_PIN27_CONFIG PORTC_PCR9
+#define CORE_PIN28_CONFIG PORTC_PCR8
+#define CORE_PIN29_CONFIG PORTC_PCR10
+#define CORE_PIN30_CONFIG PORTC_PCR11
+#define CORE_PIN31_CONFIG PORTE_PCR0
+#define CORE_PIN32_CONFIG PORTB_PCR18
+#define CORE_PIN33_CONFIG PORTA_PCR4
+
+#define CORE_ADC0_PIN 14
+#define CORE_ADC1_PIN 15
+#define CORE_ADC2_PIN 16
+#define CORE_ADC3_PIN 17
+#define CORE_ADC4_PIN 18
+#define CORE_ADC5_PIN 19
+#define CORE_ADC6_PIN 20
+#define CORE_ADC7_PIN 21
+#define CORE_ADC8_PIN 22
+#define CORE_ADC9_PIN 23
+#define CORE_ADC10_PIN 34
+#define CORE_ADC11_PIN 35
+#define CORE_ADC12_PIN 36
+#define CORE_ADC13_PIN 37
+
+#define CORE_RXD0_PIN 0
+#define CORE_TXD0_PIN 1
+#define CORE_RXD1_PIN 9
+#define CORE_TXD1_PIN 10
+#define CORE_RXD2_PIN 7
+#define CORE_TXD2_PIN 8
+
+#define CORE_INT0_PIN 0
+#define CORE_INT1_PIN 1
+#define CORE_INT2_PIN 2
+#define CORE_INT3_PIN 3
+#define CORE_INT4_PIN 4
+#define CORE_INT5_PIN 5
+#define CORE_INT6_PIN 6
+#define CORE_INT7_PIN 7
+#define CORE_INT8_PIN 8
+#define CORE_INT9_PIN 9
+#define CORE_INT10_PIN 10
+#define CORE_INT11_PIN 11
+#define CORE_INT12_PIN 12
+#define CORE_INT13_PIN 13
+#define CORE_INT14_PIN 14
+#define CORE_INT15_PIN 15
+#define CORE_INT16_PIN 16
+#define CORE_INT17_PIN 17
+#define CORE_INT18_PIN 18
+#define CORE_INT19_PIN 19
+#define CORE_INT20_PIN 20
+#define CORE_INT21_PIN 21
+#define CORE_INT22_PIN 22
+#define CORE_INT23_PIN 23
+#define CORE_INT24_PIN 24
+#define CORE_INT25_PIN 25
+#define CORE_INT26_PIN 26
+#define CORE_INT27_PIN 27
+#define CORE_INT28_PIN 28
+#define CORE_INT29_PIN 29
+#define CORE_INT30_PIN 30
+#define CORE_INT31_PIN 31
+#define CORE_INT32_PIN 32
+#define CORE_INT33_PIN 33
+#define CORE_INT_EVERY_PIN 1
+
+
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void digitalWrite(uint8_t pin, uint8_t val);
+static inline void digitalWriteFast(uint8_t pin, uint8_t val) __attribute__((always_inline, unused));
+static inline void digitalWriteFast(uint8_t pin, uint8_t val)
+{
+ if (__builtin_constant_p(pin)) {
+ if (val) {
+ if (pin == 0) {
+ CORE_PIN0_PORTSET = CORE_PIN0_BITMASK;
+ } else if (pin == 1) {
+ CORE_PIN1_PORTSET = CORE_PIN1_BITMASK;
+ } else if (pin == 2) {
+ CORE_PIN2_PORTSET = CORE_PIN2_BITMASK;
+ } else if (pin == 3) {
+ CORE_PIN3_PORTSET = CORE_PIN3_BITMASK;
+ } else if (pin == 4) {
+ CORE_PIN4_PORTSET = CORE_PIN4_BITMASK;
+ } else if (pin == 5) {
+ CORE_PIN5_PORTSET = CORE_PIN5_BITMASK;
+ } else if (pin == 6) {
+ CORE_PIN6_PORTSET = CORE_PIN6_BITMASK;
+ } else if (pin == 7) {
+ CORE_PIN7_PORTSET = CORE_PIN7_BITMASK;
+ } else if (pin == 8) {
+ CORE_PIN8_PORTSET = CORE_PIN8_BITMASK;
+ } else if (pin == 9) {
+ CORE_PIN9_PORTSET = CORE_PIN9_BITMASK;
+ } else if (pin == 10) {
+ CORE_PIN10_PORTSET = CORE_PIN10_BITMASK;
+ } else if (pin == 11) {
+ CORE_PIN11_PORTSET = CORE_PIN11_BITMASK;
+ } else if (pin == 12) {
+ CORE_PIN12_PORTSET = CORE_PIN12_BITMASK;
+ } else if (pin == 13) {
+ CORE_PIN13_PORTSET = CORE_PIN13_BITMASK;
+ } else if (pin == 14) {
+ CORE_PIN14_PORTSET = CORE_PIN14_BITMASK;
+ } else if (pin == 15) {
+ CORE_PIN15_PORTSET = CORE_PIN15_BITMASK;
+ } else if (pin == 16) {
+ CORE_PIN16_PORTSET = CORE_PIN16_BITMASK;
+ } else if (pin == 17) {
+ CORE_PIN17_PORTSET = CORE_PIN17_BITMASK;
+ } else if (pin == 18) {
+ CORE_PIN18_PORTSET = CORE_PIN18_BITMASK;
+ } else if (pin == 19) {
+ CORE_PIN19_PORTSET = CORE_PIN19_BITMASK;
+ } else if (pin == 20) {
+ CORE_PIN20_PORTSET = CORE_PIN20_BITMASK;
+ } else if (pin == 21) {
+ CORE_PIN21_PORTSET = CORE_PIN21_BITMASK;
+ } else if (pin == 22) {
+ CORE_PIN22_PORTSET = CORE_PIN22_BITMASK;
+ } else if (pin == 23) {
+ CORE_PIN23_PORTSET = CORE_PIN23_BITMASK;
+ } else if (pin == 24) {
+ CORE_PIN24_PORTSET = CORE_PIN24_BITMASK;
+ } else if (pin == 25) {
+ CORE_PIN25_PORTSET = CORE_PIN25_BITMASK;
+ } else if (pin == 26) {
+ CORE_PIN26_PORTSET = CORE_PIN26_BITMASK;
+ } else if (pin == 27) {
+ CORE_PIN27_PORTSET = CORE_PIN27_BITMASK;
+ } else if (pin == 28) {
+ CORE_PIN28_PORTSET = CORE_PIN28_BITMASK;
+ } else if (pin == 29) {
+ CORE_PIN29_PORTSET = CORE_PIN29_BITMASK;
+ } else if (pin == 30) {
+ CORE_PIN30_PORTSET = CORE_PIN30_BITMASK;
+ } else if (pin == 31) {
+ CORE_PIN31_PORTSET = CORE_PIN31_BITMASK;
+ } else if (pin == 32) {
+ CORE_PIN32_PORTSET = CORE_PIN32_BITMASK;
+ } else if (pin == 33) {
+ CORE_PIN33_PORTSET = CORE_PIN33_BITMASK;
+ }
+ } else {
+ if (pin == 0) {
+ CORE_PIN0_PORTCLEAR = CORE_PIN0_BITMASK;
+ } else if (pin == 1) {
+ CORE_PIN1_PORTCLEAR = CORE_PIN1_BITMASK;
+ } else if (pin == 2) {
+ CORE_PIN2_PORTCLEAR = CORE_PIN2_BITMASK;
+ } else if (pin == 3) {
+ CORE_PIN3_PORTCLEAR = CORE_PIN3_BITMASK;
+ } else if (pin == 4) {
+ CORE_PIN4_PORTCLEAR = CORE_PIN4_BITMASK;
+ } else if (pin == 5) {
+ CORE_PIN5_PORTCLEAR = CORE_PIN5_BITMASK;
+ } else if (pin == 6) {
+ CORE_PIN6_PORTCLEAR = CORE_PIN6_BITMASK;
+ } else if (pin == 7) {
+ CORE_PIN7_PORTCLEAR = CORE_PIN7_BITMASK;
+ } else if (pin == 8) {
+ CORE_PIN8_PORTCLEAR = CORE_PIN8_BITMASK;
+ } else if (pin == 9) {
+ CORE_PIN9_PORTCLEAR = CORE_PIN9_BITMASK;
+ } else if (pin == 10) {
+ CORE_PIN10_PORTCLEAR = CORE_PIN10_BITMASK;
+ } else if (pin == 11) {
+ CORE_PIN11_PORTCLEAR = CORE_PIN11_BITMASK;
+ } else if (pin == 12) {
+ CORE_PIN12_PORTCLEAR = CORE_PIN12_BITMASK;
+ } else if (pin == 13) {
+ CORE_PIN13_PORTCLEAR = CORE_PIN13_BITMASK;
+ } else if (pin == 14) {
+ CORE_PIN14_PORTCLEAR = CORE_PIN14_BITMASK;
+ } else if (pin == 15) {
+ CORE_PIN15_PORTCLEAR = CORE_PIN15_BITMASK;
+ } else if (pin == 16) {
+ CORE_PIN16_PORTCLEAR = CORE_PIN16_BITMASK;
+ } else if (pin == 17) {
+ CORE_PIN17_PORTCLEAR = CORE_PIN17_BITMASK;
+ } else if (pin == 18) {
+ CORE_PIN18_PORTCLEAR = CORE_PIN18_BITMASK;
+ } else if (pin == 19) {
+ CORE_PIN19_PORTCLEAR = CORE_PIN19_BITMASK;
+ } else if (pin == 20) {
+ CORE_PIN20_PORTCLEAR = CORE_PIN20_BITMASK;
+ } else if (pin == 21) {
+ CORE_PIN21_PORTCLEAR = CORE_PIN21_BITMASK;
+ } else if (pin == 22) {
+ CORE_PIN22_PORTCLEAR = CORE_PIN22_BITMASK;
+ } else if (pin == 23) {
+ CORE_PIN23_PORTCLEAR = CORE_PIN23_BITMASK;
+ } else if (pin == 24) {
+ CORE_PIN24_PORTCLEAR = CORE_PIN24_BITMASK;
+ } else if (pin == 25) {
+ CORE_PIN25_PORTCLEAR = CORE_PIN25_BITMASK;
+ } else if (pin == 26) {
+ CORE_PIN26_PORTCLEAR = CORE_PIN26_BITMASK;
+ } else if (pin == 27) {
+ CORE_PIN27_PORTCLEAR = CORE_PIN27_BITMASK;
+ } else if (pin == 28) {
+ CORE_PIN28_PORTCLEAR = CORE_PIN28_BITMASK;
+ } else if (pin == 29) {
+ CORE_PIN29_PORTCLEAR = CORE_PIN29_BITMASK;
+ } else if (pin == 30) {
+ CORE_PIN30_PORTCLEAR = CORE_PIN30_BITMASK;
+ } else if (pin == 31) {
+ CORE_PIN31_PORTCLEAR = CORE_PIN31_BITMASK;
+ } else if (pin == 32) {
+ CORE_PIN32_PORTCLEAR = CORE_PIN32_BITMASK;
+ } else if (pin == 33) {
+ CORE_PIN33_PORTCLEAR = CORE_PIN33_BITMASK;
+ }
+ }
+ } else {
+ if (val) {
+ *portSetRegister(pin) = 1;
+ } else {
+ *portClearRegister(pin) = 1;
+ }
+ }
+}
+
+uint8_t digitalRead(uint8_t pin);
+static inline uint8_t digitalReadFast(uint8_t pin) __attribute__((always_inline, unused));
+static inline uint8_t digitalReadFast(uint8_t pin)
+{
+ if (__builtin_constant_p(pin)) {
+ if (pin == 0) {
+ return (CORE_PIN0_PINREG & CORE_PIN0_BITMASK) ? 1 : 0;
+ } else if (pin == 1) {
+ return (CORE_PIN1_PINREG & CORE_PIN1_BITMASK) ? 1 : 0;
+ } else if (pin == 2) {
+ return (CORE_PIN2_PINREG & CORE_PIN2_BITMASK) ? 1 : 0;
+ } else if (pin == 3) {
+ return (CORE_PIN3_PINREG & CORE_PIN3_BITMASK) ? 1 : 0;
+ } else if (pin == 4) {
+ return (CORE_PIN4_PINREG & CORE_PIN4_BITMASK) ? 1 : 0;
+ } else if (pin == 5) {
+ return (CORE_PIN5_PINREG & CORE_PIN5_BITMASK) ? 1 : 0;
+ } else if (pin == 6) {
+ return (CORE_PIN6_PINREG & CORE_PIN6_BITMASK) ? 1 : 0;
+ } else if (pin == 7) {
+ return (CORE_PIN7_PINREG & CORE_PIN7_BITMASK) ? 1 : 0;
+ } else if (pin == 8) {
+ return (CORE_PIN8_PINREG & CORE_PIN8_BITMASK) ? 1 : 0;
+ } else if (pin == 9) {
+ return (CORE_PIN9_PINREG & CORE_PIN9_BITMASK) ? 1 : 0;
+ } else if (pin == 10) {
+ return (CORE_PIN10_PINREG & CORE_PIN10_BITMASK) ? 1 : 0;
+ } else if (pin == 11) {
+ return (CORE_PIN11_PINREG & CORE_PIN11_BITMASK) ? 1 : 0;
+ } else if (pin == 12) {
+ return (CORE_PIN12_PINREG & CORE_PIN12_BITMASK) ? 1 : 0;
+ } else if (pin == 13) {
+ return (CORE_PIN13_PINREG & CORE_PIN13_BITMASK) ? 1 : 0;
+ } else if (pin == 14) {
+ return (CORE_PIN14_PINREG & CORE_PIN14_BITMASK) ? 1 : 0;
+ } else if (pin == 15) {
+ return (CORE_PIN15_PINREG & CORE_PIN15_BITMASK) ? 1 : 0;
+ } else if (pin == 16) {
+ return (CORE_PIN16_PINREG & CORE_PIN16_BITMASK) ? 1 : 0;
+ } else if (pin == 17) {
+ return (CORE_PIN17_PINREG & CORE_PIN17_BITMASK) ? 1 : 0;
+ } else if (pin == 18) {
+ return (CORE_PIN18_PINREG & CORE_PIN18_BITMASK) ? 1 : 0;
+ } else if (pin == 19) {
+ return (CORE_PIN19_PINREG & CORE_PIN19_BITMASK) ? 1 : 0;
+ } else if (pin == 20) {
+ return (CORE_PIN20_PINREG & CORE_PIN20_BITMASK) ? 1 : 0;
+ } else if (pin == 21) {
+ return (CORE_PIN21_PINREG & CORE_PIN21_BITMASK) ? 1 : 0;
+ } else if (pin == 22) {
+ return (CORE_PIN22_PINREG & CORE_PIN22_BITMASK) ? 1 : 0;
+ } else if (pin == 23) {
+ return (CORE_PIN23_PINREG & CORE_PIN23_BITMASK) ? 1 : 0;
+ } else if (pin == 24) {
+ return (CORE_PIN24_PINREG & CORE_PIN24_BITMASK) ? 1 : 0;
+ } else if (pin == 25) {
+ return (CORE_PIN25_PINREG & CORE_PIN25_BITMASK) ? 1 : 0;
+ } else if (pin == 26) {
+ return (CORE_PIN26_PINREG & CORE_PIN26_BITMASK) ? 1 : 0;
+ } else if (pin == 27) {
+ return (CORE_PIN27_PINREG & CORE_PIN27_BITMASK) ? 1 : 0;
+ } else if (pin == 28) {
+ return (CORE_PIN28_PINREG & CORE_PIN28_BITMASK) ? 1 : 0;
+ } else if (pin == 29) {
+ return (CORE_PIN29_PINREG & CORE_PIN29_BITMASK) ? 1 : 0;
+ } else if (pin == 30) {
+ return (CORE_PIN30_PINREG & CORE_PIN30_BITMASK) ? 1 : 0;
+ } else if (pin == 31) {
+ return (CORE_PIN31_PINREG & CORE_PIN31_BITMASK) ? 1 : 0;
+ } else if (pin == 32) {
+ return (CORE_PIN32_PINREG & CORE_PIN32_BITMASK) ? 1 : 0;
+ } else if (pin == 33) {
+ return (CORE_PIN33_PINREG & CORE_PIN33_BITMASK) ? 1 : 0;
+ } else {
+ return 0;
+ }
+ } else {
+ return *portInputRegister(pin);
+ }
+}
+
+
+void pinMode(uint8_t pin, uint8_t mode);
+void init_pins(void);
+void analogWrite(uint8_t pin, int val);
+void analogWriteRes(uint32_t bits);
+static inline void analogWriteResolution(uint32_t bits) { analogWriteRes(bits); }
+void analogWriteFrequency(uint8_t pin, uint32_t frequency);
+void analogWriteDAC0(int val);
+void attachInterrupt(uint8_t pin, void (*function)(void), int mode);
+void detachInterrupt(uint8_t pin);
+void _init_Teensyduino_internal_(void);
+
+int analogRead(uint8_t pin);
+void analogReference(uint8_t type);
+void analogReadRes(unsigned int bits);
+static inline void analogReadResolution(unsigned int bits) { analogReadRes(bits); }
+void analogReadAveraging(unsigned int num);
+void analog_init(void);
+
+#define DEFAULT 0
+#define INTERNAL 2
+#define INTERNAL1V2 2
+#define INTERNAL1V1 2
+#define EXTERNAL 0
+
+int touchRead(uint8_t pin);
+
+
+static inline void shiftOut(uint8_t, uint8_t, uint8_t, uint8_t) __attribute__((always_inline, unused));
+extern void _shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t value) __attribute__((noinline));
+extern void shiftOut_lsbFirst(uint8_t dataPin, uint8_t clockPin, uint8_t value) __attribute__((noinline));
+extern void shiftOut_msbFirst(uint8_t dataPin, uint8_t clockPin, uint8_t value) __attribute__((noinline));
+
+static inline void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t value)
+{
+ if (__builtin_constant_p(bitOrder)) {
+ if (bitOrder == LSBFIRST) {
+ shiftOut_lsbFirst(dataPin, clockPin, value);
+ } else {
+ shiftOut_msbFirst(dataPin, clockPin, value);
+ }
+ } else {
+ _shiftOut(dataPin, clockPin, bitOrder, value);
+ }
+}
+
+static inline uint8_t shiftIn(uint8_t, uint8_t, uint8_t) __attribute__((always_inline, unused));
+extern uint8_t _shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder) __attribute__((noinline));
+extern uint8_t shiftIn_lsbFirst(uint8_t dataPin, uint8_t clockPin) __attribute__((noinline));
+extern uint8_t shiftIn_msbFirst(uint8_t dataPin, uint8_t clockPin) __attribute__((noinline));
+
+static inline uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder)
+{
+ if (__builtin_constant_p(bitOrder)) {
+ if (bitOrder == LSBFIRST) {
+ return shiftIn_lsbFirst(dataPin, clockPin);
+ } else {
+ return shiftIn_msbFirst(dataPin, clockPin);
+ }
+ } else {
+ return _shiftIn(dataPin, clockPin, bitOrder);
+ }
+}
+
+void _reboot_Teensyduino_(void) __attribute__((noreturn));
+void _restart_Teensyduino_(void) __attribute__((noreturn));
+
+void yield(void);
+
+void delay(uint32_t msec);
+
+extern volatile uint32_t systick_millis_count;
+
+static inline uint32_t millis(void) __attribute__((always_inline, unused));
+static inline uint32_t millis(void)
+{
+ volatile uint32_t ret = systick_millis_count; // single aligned 32 bit is atomic;
+ return ret;
+}
+
+uint32_t micros(void);
+
+static inline void delayMicroseconds(uint32_t) __attribute__((always_inline, unused));
+static inline void delayMicroseconds(uint32_t usec)
+{
+#if F_CPU == 168000000
+ uint32_t n = usec * 56;
+#elif F_CPU == 144000000
+ uint32_t n = usec * 48;
+#elif F_CPU == 120000000
+ uint32_t n = usec * 40;
+#elif F_CPU == 96000000
+ uint32_t n = usec << 5;
+#elif F_CPU == 72000000
+ uint32_t n = usec * 24;
+#elif F_CPU == 48000000
+ uint32_t n = usec << 4;
+#elif F_CPU == 24000000
+ uint32_t n = usec << 3;
+#elif F_CPU == 16000000
+ uint32_t n = usec << 2;
+#elif F_CPU == 8000000
+ uint32_t n = usec << 1;
+#elif F_CPU == 4000000
+ uint32_t n = usec;
+#elif F_CPU == 2000000
+ uint32_t n = usec >> 1;
+#endif
+ // changed because a delay of 1 micro Sec @ 2MHz will be 0
+ if (n == 0) return;
+ __asm__ volatile(
+ "L_%=_delayMicroseconds:" "\n\t"
+#if F_CPU < 24000000
+ "nop" "\n\t"
+#endif
+ "subs %0, #1" "\n\t"
+ "bne L_%=_delayMicroseconds" "\n"
+ : "+r" (n) :
+ );
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+
+
+
+
+
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+unsigned long rtc_get(void);
+void rtc_set(unsigned long t);
+void rtc_compensate(int adjust);
+#ifdef __cplusplus
+}
+class teensy3_clock_class
+{
+public:
+ static unsigned long get(void) __attribute__((always_inline)) { return rtc_get(); }
+ static void set(unsigned long t) __attribute__((always_inline)) { rtc_set(t); }
+ static void compensate(int adj) __attribute__((always_inline)) { rtc_compensate(adj); }
+};
+extern teensy3_clock_class Teensy3Clock;
+#endif
+
+
+
+
+#endif
diff --git a/ports/teensy/core/mk20dx128.c b/ports/teensy/core/mk20dx128.c
new file mode 100644
index 000000000..0f5f1e19e
--- /dev/null
+++ b/ports/teensy/core/mk20dx128.c
@@ -0,0 +1,662 @@
+/* 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.
+ */
+
+#include "mk20dx128.h"
+
+
+extern unsigned long _stext;
+extern unsigned long _etext;
+extern unsigned long _sdata;
+extern unsigned long _edata;
+extern unsigned long _sbss;
+extern unsigned long _ebss;
+extern unsigned long _estack;
+//extern void __init_array_start(void);
+//extern void __init_array_end(void);
+
+
+
+extern int main (void);
+void ResetHandler(void);
+void _init_Teensyduino_internal_(void);
+void __libc_init_array(void);
+
+
+void fault_isr(void)
+{
+ while (1) {
+ // keep polling some communication while in fault
+ // mode, so we don't completely die.
+ if (SIM_SCGC4 & SIM_SCGC4_USBOTG) usb_isr();
+ if (SIM_SCGC4 & SIM_SCGC4_UART0) uart0_status_isr();
+ if (SIM_SCGC4 & SIM_SCGC4_UART1) uart1_status_isr();
+ if (SIM_SCGC4 & SIM_SCGC4_UART2) uart2_status_isr();
+ }
+}
+
+void unused_isr(void)
+{
+ fault_isr();
+}
+
+extern volatile uint32_t systick_millis_count;
+void systick_default_isr(void)
+{
+ systick_millis_count++;
+}
+
+void nmi_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void hard_fault_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void memmanage_fault_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void bus_fault_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void usage_fault_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void svcall_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void debugmonitor_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void pendablesrvreq_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void systick_isr(void) __attribute__ ((weak, alias("systick_default_isr")));
+
+void dma_ch0_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void dma_ch1_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void dma_ch2_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void dma_ch3_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void dma_ch4_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void dma_ch5_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void dma_ch6_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void dma_ch7_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void dma_ch8_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void dma_ch9_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void dma_ch10_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void dma_ch11_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void dma_ch12_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void dma_ch13_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void dma_ch14_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void dma_ch15_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void dma_error_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void mcm_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void flash_cmd_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void flash_error_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void low_voltage_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void wakeup_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void watchdog_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void i2c0_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void i2c1_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void i2c2_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void spi0_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void spi1_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void spi2_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void sdhc_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void can0_message_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void can0_bus_off_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void can0_error_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void can0_tx_warn_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void can0_rx_warn_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void can0_wakeup_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void i2s0_tx_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void i2s0_rx_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void uart0_lon_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void uart0_status_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void uart0_error_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void uart1_status_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void uart1_error_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void uart2_status_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void uart2_error_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void uart3_status_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void uart3_error_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void uart4_status_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void uart4_error_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void uart5_status_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void uart5_error_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void adc0_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void adc1_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void cmp0_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void cmp1_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void cmp2_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void ftm0_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void ftm1_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void ftm2_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void ftm3_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void cmt_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void rtc_alarm_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void rtc_seconds_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void pit0_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void pit1_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void pit2_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void pit3_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void pdb_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void usb_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void usb_charge_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void dac0_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void dac1_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void tsi0_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void mcg_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void lptmr_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void porta_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void portb_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void portc_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void portd_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void porte_isr(void) __attribute__ ((weak, alias("unused_isr")));
+void software_isr(void) __attribute__ ((weak, alias("unused_isr")));
+
+
+// TODO: create AVR-stype ISR() macro, with default linkage to undefined handler
+//
+__attribute__ ((section(".vectors"), used))
+void (* const gVectors[])(void) =
+{
+ (void (*)(void))((unsigned long)&_estack), // 0 ARM: Initial Stack Pointer
+ ResetHandler, // 1 ARM: Initial Program Counter
+ nmi_isr, // 2 ARM: Non-maskable Interrupt (NMI)
+ hard_fault_isr, // 3 ARM: Hard Fault
+ memmanage_fault_isr, // 4 ARM: MemManage Fault
+ bus_fault_isr, // 5 ARM: Bus Fault
+ usage_fault_isr, // 6 ARM: Usage Fault
+ fault_isr, // 7 --
+ fault_isr, // 8 --
+ fault_isr, // 9 --
+ fault_isr, // 10 --
+ svcall_isr, // 11 ARM: Supervisor call (SVCall)
+ debugmonitor_isr, // 12 ARM: Debug Monitor
+ fault_isr, // 13 --
+ pendablesrvreq_isr, // 14 ARM: Pendable req serv(PendableSrvReq)
+ systick_isr, // 15 ARM: System tick timer (SysTick)
+#if defined(__MK20DX128__)
+ dma_ch0_isr, // 16 DMA channel 0 transfer complete
+ dma_ch1_isr, // 17 DMA channel 1 transfer complete
+ dma_ch2_isr, // 18 DMA channel 2 transfer complete
+ dma_ch3_isr, // 19 DMA channel 3 transfer complete
+ dma_error_isr, // 20 DMA error interrupt channel
+ unused_isr, // 21 DMA --
+ flash_cmd_isr, // 22 Flash Memory Command complete
+ flash_error_isr, // 23 Flash Read collision
+ low_voltage_isr, // 24 Low-voltage detect/warning
+ wakeup_isr, // 25 Low Leakage Wakeup
+ watchdog_isr, // 26 Both EWM and WDOG interrupt
+ i2c0_isr, // 27 I2C0
+ spi0_isr, // 28 SPI0
+ i2s0_tx_isr, // 29 I2S0 Transmit
+ i2s0_rx_isr, // 30 I2S0 Receive
+ uart0_lon_isr, // 31 UART0 CEA709.1-B (LON) status
+ uart0_status_isr, // 32 UART0 status
+ uart0_error_isr, // 33 UART0 error
+ uart1_status_isr, // 34 UART1 status
+ uart1_error_isr, // 35 UART1 error
+ uart2_status_isr, // 36 UART2 status
+ uart2_error_isr, // 37 UART2 error
+ adc0_isr, // 38 ADC0
+ cmp0_isr, // 39 CMP0
+ cmp1_isr, // 40 CMP1
+ ftm0_isr, // 41 FTM0
+ ftm1_isr, // 42 FTM1
+ cmt_isr, // 43 CMT
+ rtc_alarm_isr, // 44 RTC Alarm interrupt
+ rtc_seconds_isr, // 45 RTC Seconds interrupt
+ pit0_isr, // 46 PIT Channel 0
+ pit1_isr, // 47 PIT Channel 1
+ pit2_isr, // 48 PIT Channel 2
+ pit3_isr, // 49 PIT Channel 3
+ pdb_isr, // 50 PDB Programmable Delay Block
+ usb_isr, // 51 USB OTG
+ usb_charge_isr, // 52 USB Charger Detect
+ tsi0_isr, // 53 TSI0
+ mcg_isr, // 54 MCG
+ lptmr_isr, // 55 Low Power Timer
+ porta_isr, // 56 Pin detect (Port A)
+ portb_isr, // 57 Pin detect (Port B)
+ portc_isr, // 58 Pin detect (Port C)
+ portd_isr, // 59 Pin detect (Port D)
+ porte_isr, // 60 Pin detect (Port E)
+ software_isr, // 61 Software interrupt
+#elif defined(__MK20DX256__)
+ dma_ch0_isr, // 16 DMA channel 0 transfer complete
+ dma_ch1_isr, // 17 DMA channel 1 transfer complete
+ dma_ch2_isr, // 18 DMA channel 2 transfer complete
+ dma_ch3_isr, // 19 DMA channel 3 transfer complete
+ dma_ch4_isr, // 20 DMA channel 4 transfer complete
+ dma_ch5_isr, // 21 DMA channel 5 transfer complete
+ dma_ch6_isr, // 22 DMA channel 6 transfer complete
+ dma_ch7_isr, // 23 DMA channel 7 transfer complete
+ dma_ch8_isr, // 24 DMA channel 8 transfer complete
+ dma_ch9_isr, // 25 DMA channel 9 transfer complete
+ dma_ch10_isr, // 26 DMA channel 10 transfer complete
+ dma_ch11_isr, // 27 DMA channel 10 transfer complete
+ dma_ch12_isr, // 28 DMA channel 10 transfer complete
+ dma_ch13_isr, // 29 DMA channel 10 transfer complete
+ dma_ch14_isr, // 30 DMA channel 10 transfer complete
+ dma_ch15_isr, // 31 DMA channel 10 transfer complete
+ dma_error_isr, // 32 DMA error interrupt channel
+ unused_isr, // 33 --
+ flash_cmd_isr, // 34 Flash Memory Command complete
+ flash_error_isr, // 35 Flash Read collision
+ low_voltage_isr, // 36 Low-voltage detect/warning
+ wakeup_isr, // 37 Low Leakage Wakeup
+ watchdog_isr, // 38 Both EWM and WDOG interrupt
+ unused_isr, // 39 --
+ i2c0_isr, // 40 I2C0
+ i2c1_isr, // 41 I2C1
+ spi0_isr, // 42 SPI0
+ spi1_isr, // 43 SPI1
+ unused_isr, // 44 --
+ can0_message_isr, // 45 CAN OR'ed Message buffer (0-15)
+ can0_bus_off_isr, // 46 CAN Bus Off
+ can0_error_isr, // 47 CAN Error
+ can0_tx_warn_isr, // 48 CAN Transmit Warning
+ can0_rx_warn_isr, // 49 CAN Receive Warning
+ can0_wakeup_isr, // 50 CAN Wake Up
+ i2s0_tx_isr, // 51 I2S0 Transmit
+ i2s0_rx_isr, // 52 I2S0 Receive
+ unused_isr, // 53 --
+ unused_isr, // 54 --
+ unused_isr, // 55 --
+ unused_isr, // 56 --
+ unused_isr, // 57 --
+ unused_isr, // 58 --
+ unused_isr, // 59 --
+ uart0_lon_isr, // 60 UART0 CEA709.1-B (LON) status
+ uart0_status_isr, // 61 UART0 status
+ uart0_error_isr, // 62 UART0 error
+ uart1_status_isr, // 63 UART1 status
+ uart1_error_isr, // 64 UART1 error
+ uart2_status_isr, // 65 UART2 status
+ uart2_error_isr, // 66 UART2 error
+ unused_isr, // 67 --
+ unused_isr, // 68 --
+ unused_isr, // 69 --
+ unused_isr, // 70 --
+ unused_isr, // 71 --
+ unused_isr, // 72 --
+ adc0_isr, // 73 ADC0
+ adc1_isr, // 74 ADC1
+ cmp0_isr, // 75 CMP0
+ cmp1_isr, // 76 CMP1
+ cmp2_isr, // 77 CMP2
+ ftm0_isr, // 78 FTM0
+ ftm1_isr, // 79 FTM1
+ ftm2_isr, // 80 FTM2
+ cmt_isr, // 81 CMT
+ rtc_alarm_isr, // 82 RTC Alarm interrupt
+ rtc_seconds_isr, // 83 RTC Seconds interrupt
+ pit0_isr, // 84 PIT Channel 0
+ pit1_isr, // 85 PIT Channel 1
+ pit2_isr, // 86 PIT Channel 2
+ pit3_isr, // 87 PIT Channel 3
+ pdb_isr, // 88 PDB Programmable Delay Block
+ usb_isr, // 89 USB OTG
+ usb_charge_isr, // 90 USB Charger Detect
+ unused_isr, // 91 --
+ unused_isr, // 92 --
+ unused_isr, // 93 --
+ unused_isr, // 94 --
+ unused_isr, // 95 --
+ unused_isr, // 96 --
+ dac0_isr, // 97 DAC0
+ unused_isr, // 98 --
+ tsi0_isr, // 99 TSI0
+ mcg_isr, // 100 MCG
+ lptmr_isr, // 101 Low Power Timer
+ unused_isr, // 102 --
+ porta_isr, // 103 Pin detect (Port A)
+ portb_isr, // 104 Pin detect (Port B)
+ portc_isr, // 105 Pin detect (Port C)
+ portd_isr, // 106 Pin detect (Port D)
+ porte_isr, // 107 Pin detect (Port E)
+ unused_isr, // 108 --
+ unused_isr, // 109 --
+ software_isr, // 110 Software interrupt
+#endif
+};
+
+//void usb_isr(void)
+//{
+//}
+
+__attribute__ ((section(".flashconfig"), used))
+const uint8_t flashconfigbytes[16] = {
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF
+};
+
+
+// Automatically initialize the RTC. When the build defines the compile
+// time, and the user has added a crystal, the RTC will automatically
+// begin at the time of the first upload.
+#ifndef TIME_T
+#define TIME_T 1349049600 // default 1 Oct 2012 (never used, Arduino sets this)
+#endif
+extern void rtc_set(unsigned long t);
+
+
+static void startup_default_early_hook(void) { WDOG_STCTRLH = WDOG_STCTRLH_ALLOWUPDATE; }
+static void startup_default_late_hook(void) {}
+void startup_early_hook(void) __attribute__ ((weak, alias("startup_default_early_hook")));
+void startup_late_hook(void) __attribute__ ((weak, alias("startup_default_late_hook")));
+
+__attribute__ ((section(".startup")))
+void ResetHandler(void)
+{
+ uint32_t *src = &_etext;
+ uint32_t *dest = &_sdata;
+ unsigned int i;
+#if F_CPU <= 2000000
+ volatile int n;
+#endif
+
+ WDOG_UNLOCK = WDOG_UNLOCK_SEQ1;
+ WDOG_UNLOCK = WDOG_UNLOCK_SEQ2;
+ __asm__ volatile ("nop");
+ __asm__ volatile ("nop");
+ // programs using the watchdog timer or needing to initialize hardware as
+ // early as possible can implement startup_early_hook()
+ startup_early_hook();
+
+ // enable clocks to always-used peripherals
+#if defined(__MK20DX128__)
+ SIM_SCGC5 = 0x00043F82; // clocks active to all GPIO
+ SIM_SCGC6 = SIM_SCGC6_RTC | SIM_SCGC6_FTM0 | SIM_SCGC6_FTM1 | SIM_SCGC6_ADC0 | SIM_SCGC6_FTFL;
+#elif defined(__MK20DX256__)
+ SIM_SCGC3 = SIM_SCGC3_ADC1 | SIM_SCGC3_FTM2;
+ SIM_SCGC5 = 0x00043F82; // clocks active to all GPIO
+ SIM_SCGC6 = SIM_SCGC6_RTC | SIM_SCGC6_FTM0 | SIM_SCGC6_FTM1 | SIM_SCGC6_ADC0 | SIM_SCGC6_FTFL;
+#endif
+ // if the RTC oscillator isn't enabled, get it started early
+ if (!(RTC_CR & RTC_CR_OSCE)) {
+ RTC_SR = 0;
+ RTC_CR = RTC_CR_SC16P | RTC_CR_SC4P | RTC_CR_OSCE;
+ }
+
+ // release I/O pins hold, if we woke up from VLLS mode
+ if (PMC_REGSC & PMC_REGSC_ACKISO) PMC_REGSC |= PMC_REGSC_ACKISO;
+
+ // since this is a write once register, make it visible to all F_CPU's
+ // so we can into other sleep modes in the future at any speed
+ SMC_PMPROT = SMC_PMPROT_AVLP | SMC_PMPROT_ALLS | SMC_PMPROT_AVLLS;
+
+ // TODO: do this while the PLL is waiting to lock....
+ while (dest < &_edata) *dest++ = *src++;
+ dest = &_sbss;
+ while (dest < &_ebss) *dest++ = 0;
+ SCB_VTOR = 0; // use vector table in flash
+
+ // default all interrupts to medium priority level
+ for (i=0; i < NVIC_NUM_INTERRUPTS; i++) NVIC_SET_PRIORITY(i, 128);
+
+ // hardware always starts in FEI mode
+ // C1[CLKS] bits are written to 00
+ // C1[IREFS] bit is written to 1
+ // C6[PLLS] bit is written to 0
+// MCG_SC[FCDIV] defaults to divide by two for internal ref clock
+// I tried changing MSG_SC to divide by 1, it didn't work for me
+#if F_CPU <= 2000000
+ // use the internal oscillator
+ MCG_C1 = MCG_C1_CLKS(1) | MCG_C1_IREFS;
+ // wait for MCGOUT to use oscillator
+ while ((MCG_S & MCG_S_CLKST_MASK) != MCG_S_CLKST(1)) ;
+ for (n=0; n<10; n++) ; // TODO: why do we get 2 mA extra without this delay?
+ MCG_C2 = MCG_C2_IRCS;
+ while (!(MCG_S & MCG_S_IRCST)) ;
+ // now in FBI mode:
+ // C1[CLKS] bits are written to 01
+ // C1[IREFS] bit is written to 1
+ // C6[PLLS] is written to 0
+ // C2[LP] is written to 0
+ MCG_C2 = MCG_C2_IRCS | MCG_C2_LP;
+ // now in BLPI mode:
+ // C1[CLKS] bits are written to 01
+ // C1[IREFS] bit is written to 1
+ // C6[PLLS] bit is written to 0
+ // C2[LP] bit is written to 1
+#else
+ // enable capacitors for crystal
+ OSC0_CR = OSC_SC8P | OSC_SC2P;
+ // enable osc, 8-32 MHz range, low power mode
+ MCG_C2 = MCG_C2_RANGE0(2) | MCG_C2_EREFS;
+ // switch to crystal as clock source, FLL input = 16 MHz / 512
+ MCG_C1 = MCG_C1_CLKS(2) | MCG_C1_FRDIV(4);
+ // wait for crystal oscillator to begin
+ while ((MCG_S & MCG_S_OSCINIT0) == 0) ;
+ // wait for FLL to use oscillator
+ while ((MCG_S & MCG_S_IREFST) != 0) ;
+ // wait for MCGOUT to use oscillator
+ while ((MCG_S & MCG_S_CLKST_MASK) != MCG_S_CLKST(2)) ;
+ // now in FBE mode
+ // C1[CLKS] bits are written to 10
+ // C1[IREFS] bit is written to 0
+ // C1[FRDIV] must be written to divide xtal to 31.25-39 kHz
+ // C6[PLLS] bit is written to 0
+ // C2[LP] is written to 0
+ #if F_CPU <= 16000000
+ // if the crystal is fast enough, use it directly (no FLL or PLL)
+ MCG_C2 = MCG_C2_RANGE0(2) | MCG_C2_EREFS | MCG_C2_LP;
+ // BLPE mode:
+ // C1[CLKS] bits are written to 10
+ // C1[IREFS] bit is written to 0
+ // C2[LP] bit is written to 1
+ #else
+ // if we need faster than the crystal, turn on the PLL
+ #if F_CPU == 72000000
+ MCG_C5 = MCG_C5_PRDIV0(5); // config PLL input for 16 MHz Crystal / 6 = 2.667 Hz
+ #else
+ MCG_C5 = MCG_C5_PRDIV0(3); // config PLL input for 16 MHz Crystal / 4 = 4 MHz
+ #endif
+ #if F_CPU == 168000000
+ MCG_C6 = MCG_C6_PLLS | MCG_C6_VDIV0(18); // config PLL for 168 MHz output
+ #elif F_CPU == 144000000
+ MCG_C6 = MCG_C6_PLLS | MCG_C6_VDIV0(12); // config PLL for 144 MHz output
+ #elif F_CPU == 120000000
+ MCG_C6 = MCG_C6_PLLS | MCG_C6_VDIV0(6); // config PLL for 120 MHz output
+ #elif F_CPU == 72000000
+ MCG_C6 = MCG_C6_PLLS | MCG_C6_VDIV0(3); // config PLL for 72 MHz output
+ #else
+ MCG_C6 = MCG_C6_PLLS | MCG_C6_VDIV0(0); // config PLL for 96 MHz output
+ #endif
+ // wait for PLL to start using xtal as its input
+ while (!(MCG_S & MCG_S_PLLST)) ;
+ // wait for PLL to lock
+ while (!(MCG_S & MCG_S_LOCK0)) ;
+ // now we're in PBE mode
+ #endif
+#endif
+
+ // now program the clock dividers
+#if F_CPU == 168000000
+ // config divisors: 168 MHz core, 56 MHz bus, 33.6 MHz flash, USB = 168 * 2 / 7
+ SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(2) | SIM_CLKDIV1_OUTDIV4(4);
+ SIM_CLKDIV2 = SIM_CLKDIV2_USBDIV(6) | SIM_CLKDIV2_USBFRAC;
+#elif F_CPU == 144000000
+ // config divisors: 144 MHz core, 48 MHz bus, 28.8 MHz flash, USB = 144 / 3
+ SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(2) | SIM_CLKDIV1_OUTDIV4(4);
+ SIM_CLKDIV2 = SIM_CLKDIV2_USBDIV(2);
+#elif F_CPU == 120000000
+ // config divisors: 120 MHz core, 60 MHz bus, 24 MHz flash, USB = 128 * 2 / 5
+ SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(1) | SIM_CLKDIV1_OUTDIV4(4);
+ SIM_CLKDIV2 = SIM_CLKDIV2_USBDIV(4) | SIM_CLKDIV2_USBFRAC;
+#elif F_CPU == 96000000
+ // config divisors: 96 MHz core, 48 MHz bus, 24 MHz flash, USB = 96 / 2
+ SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(1) | SIM_CLKDIV1_OUTDIV4(3);
+ SIM_CLKDIV2 = SIM_CLKDIV2_USBDIV(1);
+#elif F_CPU == 72000000
+ // config divisors: 72 MHz core, 36 MHz bus, 24 MHz flash, USB = 72 * 2 / 3
+ SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(1) | SIM_CLKDIV1_OUTDIV4(2);
+ SIM_CLKDIV2 = SIM_CLKDIV2_USBDIV(2) | SIM_CLKDIV2_USBFRAC;
+#elif F_CPU == 48000000
+ // config divisors: 48 MHz core, 48 MHz bus, 24 MHz flash, USB = 96 / 2
+ SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(1) | SIM_CLKDIV1_OUTDIV2(1) | SIM_CLKDIV1_OUTDIV4(3);
+ SIM_CLKDIV2 = SIM_CLKDIV2_USBDIV(1);
+#elif F_CPU == 24000000
+ // config divisors: 24 MHz core, 24 MHz bus, 24 MHz flash, USB = 96 / 2
+ SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(3) | SIM_CLKDIV1_OUTDIV2(3) | SIM_CLKDIV1_OUTDIV4(3);
+ SIM_CLKDIV2 = SIM_CLKDIV2_USBDIV(1);
+#elif F_CPU == 16000000
+ // config divisors: 16 MHz core, 16 MHz bus, 16 MHz flash
+ SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(0) | SIM_CLKDIV1_OUTDIV4(0);
+#elif F_CPU == 8000000
+ // config divisors: 8 MHz core, 8 MHz bus, 8 MHz flash
+ SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(1) | SIM_CLKDIV1_OUTDIV2(1) | SIM_CLKDIV1_OUTDIV4(1);
+#elif F_CPU == 4000000
+ // config divisors: 4 MHz core, 4 MHz bus, 2 MHz flash
+ // since we are running from external clock 16MHz
+ // fix outdiv too -> cpu 16/4, bus 16/4, flash 16/4
+ // here we can go into vlpr?
+ // config divisors: 4 MHz core, 4 MHz bus, 4 MHz flash
+ SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(3) | SIM_CLKDIV1_OUTDIV2(3) | SIM_CLKDIV1_OUTDIV4(3);
+#elif F_CPU == 2000000
+ // since we are running from the fast internal reference clock 4MHz
+ // but is divided down by 2 so we actually have a 2MHz, MCG_SC[FCDIV] default is 2
+ // fix outdiv -> cpu 2/1, bus 2/1, flash 2/2
+ // config divisors: 2 MHz core, 2 MHz bus, 1 MHz flash
+ SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(0) | SIM_CLKDIV1_OUTDIV4(1);
+#else
+#error "Error, F_CPU must be 168, 144, 120, 96, 72, 48, 24, 16, 8, 4, or 2 MHz"
+#endif
+
+#if F_CPU > 16000000
+ // switch to PLL as clock source, FLL input = 16 MHz / 512
+ MCG_C1 = MCG_C1_CLKS(0) | MCG_C1_FRDIV(4);
+ // wait for PLL clock to be used
+ while ((MCG_S & MCG_S_CLKST_MASK) != MCG_S_CLKST(3)) ;
+ // now we're in PEE mode
+ // USB uses PLL clock, trace is CPU clock, CLKOUT=OSCERCLK0
+ SIM_SOPT2 = SIM_SOPT2_USBSRC | SIM_SOPT2_PLLFLLSEL | SIM_SOPT2_TRACECLKSEL | SIM_SOPT2_CLKOUTSEL(6);
+#else
+ SIM_SOPT2 = SIM_SOPT2_TRACECLKSEL | SIM_SOPT2_CLKOUTSEL(3);
+#endif
+
+#if F_CPU <= 2000000
+ // since we are not going into "stop mode" i removed it
+ SMC_PMCTRL = SMC_PMCTRL_RUNM(2); // VLPR mode :-)
+#endif
+
+ // initialize the SysTick counter
+ SYST_RVR = (F_CPU / 1000) - 1;
+ SYST_CSR = SYST_CSR_CLKSOURCE | SYST_CSR_TICKINT | SYST_CSR_ENABLE;
+
+ //init_pins();
+ __enable_irq();
+
+ _init_Teensyduino_internal_();
+ if (RTC_SR & RTC_SR_TIF) {
+ // TODO: this should probably set the time more agressively, if
+ // we could reliably detect the first reboot after programming.
+ rtc_set(TIME_T);
+ }
+
+ __libc_init_array();
+
+ startup_late_hook();
+ main();
+ while (1) ;
+}
+
+char *__brkval = (char *)&_ebss;
+
+void * _sbrk(int incr)
+{
+ char *prev = __brkval;
+ __brkval += incr;
+ return prev;
+}
+
+__attribute__((weak))
+int _read(int file, char *ptr, int len)
+{
+ return 0;
+}
+
+__attribute__((weak))
+int _close(int fd)
+{
+ return -1;
+}
+
+#include <sys/stat.h>
+
+__attribute__((weak))
+int _fstat(int fd, struct stat *st)
+{
+ st->st_mode = S_IFCHR;
+ return 0;
+}
+
+__attribute__((weak))
+int _isatty(int fd)
+{
+ return 1;
+}
+
+__attribute__((weak))
+int _lseek(int fd, long long offset, int whence)
+{
+ return -1;
+}
+
+__attribute__((weak))
+void _exit(int status)
+{
+ while (1);
+}
+
+__attribute__((weak))
+void __cxa_pure_virtual()
+{
+ while (1);
+}
+
+__attribute__((weak))
+int __cxa_guard_acquire (char *g)
+{
+ return !(*g);
+}
+
+__attribute__((weak))
+void __cxa_guard_release(char *g)
+{
+ *g = 1;
+}
+
+int nvic_execution_priority(void)
+{
+ int priority=256;
+ uint32_t primask, faultmask, basepri, ipsr;
+
+ // full algorithm in ARM DDI0403D, page B1-639
+ // this isn't quite complete, but hopefully good enough
+ __asm__ volatile("mrs %0, faultmask\n" : "=r" (faultmask)::);
+ if (faultmask) return -1;
+ __asm__ volatile("mrs %0, primask\n" : "=r" (primask)::);
+ if (primask) return 0;
+ __asm__ volatile("mrs %0, ipsr\n" : "=r" (ipsr)::);
+ if (ipsr) {
+ if (ipsr < 16) priority = 0; // could be non-zero
+ else priority = NVIC_GET_PRIORITY(ipsr - 16);
+ }
+ __asm__ volatile("mrs %0, basepri\n" : "=r" (basepri)::);
+ if (basepri > 0 && basepri < priority) priority = basepri;
+ return priority;
+}
+
diff --git a/ports/teensy/core/mk20dx128.h b/ports/teensy/core/mk20dx128.h
new file mode 100644
index 000000000..ab1376050
--- /dev/null
+++ b/ports/teensy/core/mk20dx128.h
@@ -0,0 +1,2385 @@
+/* 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.
+ */
+
+#ifndef _mk20dx128_h_
+#define _mk20dx128_h_
+
+//#ifdef F_CPU
+//#undef F_CPU
+//#endif
+//#define F_CPU 168000000
+//#define F_CPU 144000000
+//#define F_CPU 120000000
+//#define F_CPU 96000000
+//#define F_CPU 72000000
+//#define F_CPU 48000000
+//#define F_CPU 24000000
+
+#if (F_CPU == 168000000)
+ #define F_BUS 56000000
+ #define F_MEM 33600000
+#elif (F_CPU == 144000000)
+ #define F_BUS 48000000
+ #define F_MEM 28800000
+#elif (F_CPU == 120000000)
+ #define F_BUS 60000000
+ #define F_MEM 24000000
+#elif (F_CPU == 96000000)
+ #define F_BUS 48000000
+ #define F_MEM 24000000
+#elif (F_CPU == 72000000)
+ #define F_BUS 36000000
+ #define F_MEM 24000000
+#elif (F_CPU == 48000000)
+ #define F_BUS 48000000
+ #define F_MEM 24000000
+#elif (F_CPU == 24000000)
+ #define F_BUS 24000000
+ #define F_MEM 24000000
+#elif (F_CPU == 16000000)
+ #define F_BUS 16000000
+ #define F_MEM 16000000
+#elif (F_CPU == 8000000)
+ #define F_BUS 8000000
+ #define F_MEM 8000000
+#elif (F_CPU == 4000000)
+ #define F_BUS 4000000
+ #define F_MEM 4000000
+#elif (F_CPU == 2000000)
+ #define F_BUS 2000000
+ #define F_MEM 1000000
+#endif
+
+
+#ifndef NULL
+#define NULL ((void *)0)
+#endif
+
+#include <stdint.h>
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// chapter 11: Port control and interrupts (PORT)
+#define PORTA_PCR0 *(volatile uint32_t *)0x40049000 // Pin Control Register n
+#define PORT_PCR_ISF (uint32_t)0x01000000 // Interrupt Status Flag
+#define PORT_PCR_IRQC(n) (uint32_t)(((n) & 15) << 16) // Interrupt Configuration
+#define PORT_PCR_IRQC_MASK (uint32_t)0x000F0000
+#define PORT_PCR_LK (uint32_t)0x00008000 // Lock Register
+#define PORT_PCR_MUX(n) (uint32_t)(((n) & 7) << 8) // Pin Mux Control
+#define PORT_PCR_MUX_MASK (uint32_t)0x00000700
+#define PORT_PCR_DSE (uint32_t)0x00000040 // Drive Strength Enable
+#define PORT_PCR_ODE (uint32_t)0x00000020 // Open Drain Enable
+#define PORT_PCR_PFE (uint32_t)0x00000010 // Passive Filter Enable
+#define PORT_PCR_SRE (uint32_t)0x00000004 // Slew Rate Enable
+#define PORT_PCR_PE (uint32_t)0x00000002 // Pull Enable
+#define PORT_PCR_PS (uint32_t)0x00000001 // Pull Select
+#define PORTA_PCR1 *(volatile uint32_t *)0x40049004 // Pin Control Register n
+#define PORTA_PCR2 *(volatile uint32_t *)0x40049008 // Pin Control Register n
+#define PORTA_PCR3 *(volatile uint32_t *)0x4004900C // Pin Control Register n
+#define PORTA_PCR4 *(volatile uint32_t *)0x40049010 // Pin Control Register n
+#define PORTA_PCR5 *(volatile uint32_t *)0x40049014 // Pin Control Register n
+#define PORTA_PCR6 *(volatile uint32_t *)0x40049018 // Pin Control Register n
+#define PORTA_PCR7 *(volatile uint32_t *)0x4004901C // Pin Control Register n
+#define PORTA_PCR8 *(volatile uint32_t *)0x40049020 // Pin Control Register n
+#define PORTA_PCR9 *(volatile uint32_t *)0x40049024 // Pin Control Register n
+#define PORTA_PCR10 *(volatile uint32_t *)0x40049028 // Pin Control Register n
+#define PORTA_PCR11 *(volatile uint32_t *)0x4004902C // Pin Control Register n
+#define PORTA_PCR12 *(volatile uint32_t *)0x40049030 // Pin Control Register n
+#define PORTA_PCR13 *(volatile uint32_t *)0x40049034 // Pin Control Register n
+#define PORTA_PCR14 *(volatile uint32_t *)0x40049038 // Pin Control Register n
+#define PORTA_PCR15 *(volatile uint32_t *)0x4004903C // Pin Control Register n
+#define PORTA_PCR16 *(volatile uint32_t *)0x40049040 // Pin Control Register n
+#define PORTA_PCR17 *(volatile uint32_t *)0x40049044 // Pin Control Register n
+#define PORTA_PCR18 *(volatile uint32_t *)0x40049048 // Pin Control Register n
+#define PORTA_PCR19 *(volatile uint32_t *)0x4004904C // Pin Control Register n
+#define PORTA_PCR20 *(volatile uint32_t *)0x40049050 // Pin Control Register n
+#define PORTA_PCR21 *(volatile uint32_t *)0x40049054 // Pin Control Register n
+#define PORTA_PCR22 *(volatile uint32_t *)0x40049058 // Pin Control Register n
+#define PORTA_PCR23 *(volatile uint32_t *)0x4004905C // Pin Control Register n
+#define PORTA_PCR24 *(volatile uint32_t *)0x40049060 // Pin Control Register n
+#define PORTA_PCR25 *(volatile uint32_t *)0x40049064 // Pin Control Register n
+#define PORTA_PCR26 *(volatile uint32_t *)0x40049068 // Pin Control Register n
+#define PORTA_PCR27 *(volatile uint32_t *)0x4004906C // Pin Control Register n
+#define PORTA_PCR28 *(volatile uint32_t *)0x40049070 // Pin Control Register n
+#define PORTA_PCR29 *(volatile uint32_t *)0x40049074 // Pin Control Register n
+#define PORTA_PCR30 *(volatile uint32_t *)0x40049078 // Pin Control Register n
+#define PORTA_PCR31 *(volatile uint32_t *)0x4004907C // Pin Control Register n
+#define PORTA_GPCLR *(volatile uint32_t *)0x40049080 // Global Pin Control Low Register
+#define PORTA_GPCHR *(volatile uint32_t *)0x40049084 // Global Pin Control High Register
+#define PORTA_ISFR *(volatile uint32_t *)0x400490A0 // Interrupt Status Flag Register
+#define PORTB_PCR0 *(volatile uint32_t *)0x4004A000 // Pin Control Register n
+#define PORTB_PCR1 *(volatile uint32_t *)0x4004A004 // Pin Control Register n
+#define PORTB_PCR2 *(volatile uint32_t *)0x4004A008 // Pin Control Register n
+#define PORTB_PCR3 *(volatile uint32_t *)0x4004A00C // Pin Control Register n
+#define PORTB_PCR4 *(volatile uint32_t *)0x4004A010 // Pin Control Register n
+#define PORTB_PCR5 *(volatile uint32_t *)0x4004A014 // Pin Control Register n
+#define PORTB_PCR6 *(volatile uint32_t *)0x4004A018 // Pin Control Register n
+#define PORTB_PCR7 *(volatile uint32_t *)0x4004A01C // Pin Control Register n
+#define PORTB_PCR8 *(volatile uint32_t *)0x4004A020 // Pin Control Register n
+#define PORTB_PCR9 *(volatile uint32_t *)0x4004A024 // Pin Control Register n
+#define PORTB_PCR10 *(volatile uint32_t *)0x4004A028 // Pin Control Register n
+#define PORTB_PCR11 *(volatile uint32_t *)0x4004A02C // Pin Control Register n
+#define PORTB_PCR12 *(volatile uint32_t *)0x4004A030 // Pin Control Register n
+#define PORTB_PCR13 *(volatile uint32_t *)0x4004A034 // Pin Control Register n
+#define PORTB_PCR14 *(volatile uint32_t *)0x4004A038 // Pin Control Register n
+#define PORTB_PCR15 *(volatile uint32_t *)0x4004A03C // Pin Control Register n
+#define PORTB_PCR16 *(volatile uint32_t *)0x4004A040 // Pin Control Register n
+#define PORTB_PCR17 *(volatile uint32_t *)0x4004A044 // Pin Control Register n
+#define PORTB_PCR18 *(volatile uint32_t *)0x4004A048 // Pin Control Register n
+#define PORTB_PCR19 *(volatile uint32_t *)0x4004A04C // Pin Control Register n
+#define PORTB_PCR20 *(volatile uint32_t *)0x4004A050 // Pin Control Register n
+#define PORTB_PCR21 *(volatile uint32_t *)0x4004A054 // Pin Control Register n
+#define PORTB_PCR22 *(volatile uint32_t *)0x4004A058 // Pin Control Register n
+#define PORTB_PCR23 *(volatile uint32_t *)0x4004A05C // Pin Control Register n
+#define PORTB_PCR24 *(volatile uint32_t *)0x4004A060 // Pin Control Register n
+#define PORTB_PCR25 *(volatile uint32_t *)0x4004A064 // Pin Control Register n
+#define PORTB_PCR26 *(volatile uint32_t *)0x4004A068 // Pin Control Register n
+#define PORTB_PCR27 *(volatile uint32_t *)0x4004A06C // Pin Control Register n
+#define PORTB_PCR28 *(volatile uint32_t *)0x4004A070 // Pin Control Register n
+#define PORTB_PCR29 *(volatile uint32_t *)0x4004A074 // Pin Control Register n
+#define PORTB_PCR30 *(volatile uint32_t *)0x4004A078 // Pin Control Register n
+#define PORTB_PCR31 *(volatile uint32_t *)0x4004A07C // Pin Control Register n
+#define PORTB_GPCLR *(volatile uint32_t *)0x4004A080 // Global Pin Control Low Register
+#define PORTB_GPCHR *(volatile uint32_t *)0x4004A084 // Global Pin Control High Register
+#define PORTB_ISFR *(volatile uint32_t *)0x4004A0A0 // Interrupt Status Flag Register
+#define PORTC_PCR0 *(volatile uint32_t *)0x4004B000 // Pin Control Register n
+#define PORTC_PCR1 *(volatile uint32_t *)0x4004B004 // Pin Control Register n
+#define PORTC_PCR2 *(volatile uint32_t *)0x4004B008 // Pin Control Register n
+#define PORTC_PCR3 *(volatile uint32_t *)0x4004B00C // Pin Control Register n
+#define PORTC_PCR4 *(volatile uint32_t *)0x4004B010 // Pin Control Register n
+#define PORTC_PCR5 *(volatile uint32_t *)0x4004B014 // Pin Control Register n
+#define PORTC_PCR6 *(volatile uint32_t *)0x4004B018 // Pin Control Register n
+#define PORTC_PCR7 *(volatile uint32_t *)0x4004B01C // Pin Control Register n
+#define PORTC_PCR8 *(volatile uint32_t *)0x4004B020 // Pin Control Register n
+#define PORTC_PCR9 *(volatile uint32_t *)0x4004B024 // Pin Control Register n
+#define PORTC_PCR10 *(volatile uint32_t *)0x4004B028 // Pin Control Register n
+#define PORTC_PCR11 *(volatile uint32_t *)0x4004B02C // Pin Control Register n
+#define PORTC_PCR12 *(volatile uint32_t *)0x4004B030 // Pin Control Register n
+#define PORTC_PCR13 *(volatile uint32_t *)0x4004B034 // Pin Control Register n
+#define PORTC_PCR14 *(volatile uint32_t *)0x4004B038 // Pin Control Register n
+#define PORTC_PCR15 *(volatile uint32_t *)0x4004B03C // Pin Control Register n
+#define PORTC_PCR16 *(volatile uint32_t *)0x4004B040 // Pin Control Register n
+#define PORTC_PCR17 *(volatile uint32_t *)0x4004B044 // Pin Control Register n
+#define PORTC_PCR18 *(volatile uint32_t *)0x4004B048 // Pin Control Register n
+#define PORTC_PCR19 *(volatile uint32_t *)0x4004B04C // Pin Control Register n
+#define PORTC_PCR20 *(volatile uint32_t *)0x4004B050 // Pin Control Register n
+#define PORTC_PCR21 *(volatile uint32_t *)0x4004B054 // Pin Control Register n
+#define PORTC_PCR22 *(volatile uint32_t *)0x4004B058 // Pin Control Register n
+#define PORTC_PCR23 *(volatile uint32_t *)0x4004B05C // Pin Control Register n
+#define PORTC_PCR24 *(volatile uint32_t *)0x4004B060 // Pin Control Register n
+#define PORTC_PCR25 *(volatile uint32_t *)0x4004B064 // Pin Control Register n
+#define PORTC_PCR26 *(volatile uint32_t *)0x4004B068 // Pin Control Register n
+#define PORTC_PCR27 *(volatile uint32_t *)0x4004B06C // Pin Control Register n
+#define PORTC_PCR28 *(volatile uint32_t *)0x4004B070 // Pin Control Register n
+#define PORTC_PCR29 *(volatile uint32_t *)0x4004B074 // Pin Control Register n
+#define PORTC_PCR30 *(volatile uint32_t *)0x4004B078 // Pin Control Register n
+#define PORTC_PCR31 *(volatile uint32_t *)0x4004B07C // Pin Control Register n
+#define PORTC_GPCLR *(volatile uint32_t *)0x4004B080 // Global Pin Control Low Register
+#define PORTC_GPCHR *(volatile uint32_t *)0x4004B084 // Global Pin Control High Register
+#define PORTC_ISFR *(volatile uint32_t *)0x4004B0A0 // Interrupt Status Flag Register
+#define PORTD_PCR0 *(volatile uint32_t *)0x4004C000 // Pin Control Register n
+#define PORTD_PCR1 *(volatile uint32_t *)0x4004C004 // Pin Control Register n
+#define PORTD_PCR2 *(volatile uint32_t *)0x4004C008 // Pin Control Register n
+#define PORTD_PCR3 *(volatile uint32_t *)0x4004C00C // Pin Control Register n
+#define PORTD_PCR4 *(volatile uint32_t *)0x4004C010 // Pin Control Register n
+#define PORTD_PCR5 *(volatile uint32_t *)0x4004C014 // Pin Control Register n
+#define PORTD_PCR6 *(volatile uint32_t *)0x4004C018 // Pin Control Register n
+#define PORTD_PCR7 *(volatile uint32_t *)0x4004C01C // Pin Control Register n
+#define PORTD_PCR8 *(volatile uint32_t *)0x4004C020 // Pin Control Register n
+#define PORTD_PCR9 *(volatile uint32_t *)0x4004C024 // Pin Control Register n
+#define PORTD_PCR10 *(volatile uint32_t *)0x4004C028 // Pin Control Register n
+#define PORTD_PCR11 *(volatile uint32_t *)0x4004C02C // Pin Control Register n
+#define PORTD_PCR12 *(volatile uint32_t *)0x4004C030 // Pin Control Register n
+#define PORTD_PCR13 *(volatile uint32_t *)0x4004C034 // Pin Control Register n
+#define PORTD_PCR14 *(volatile uint32_t *)0x4004C038 // Pin Control Register n
+#define PORTD_PCR15 *(volatile uint32_t *)0x4004C03C // Pin Control Register n
+#define PORTD_PCR16 *(volatile uint32_t *)0x4004C040 // Pin Control Register n
+#define PORTD_PCR17 *(volatile uint32_t *)0x4004C044 // Pin Control Register n
+#define PORTD_PCR18 *(volatile uint32_t *)0x4004C048 // Pin Control Register n
+#define PORTD_PCR19 *(volatile uint32_t *)0x4004C04C // Pin Control Register n
+#define PORTD_PCR20 *(volatile uint32_t *)0x4004C050 // Pin Control Register n
+#define PORTD_PCR21 *(volatile uint32_t *)0x4004C054 // Pin Control Register n
+#define PORTD_PCR22 *(volatile uint32_t *)0x4004C058 // Pin Control Register n
+#define PORTD_PCR23 *(volatile uint32_t *)0x4004C05C // Pin Control Register n
+#define PORTD_PCR24 *(volatile uint32_t *)0x4004C060 // Pin Control Register n
+#define PORTD_PCR25 *(volatile uint32_t *)0x4004C064 // Pin Control Register n
+#define PORTD_PCR26 *(volatile uint32_t *)0x4004C068 // Pin Control Register n
+#define PORTD_PCR27 *(volatile uint32_t *)0x4004C06C // Pin Control Register n
+#define PORTD_PCR28 *(volatile uint32_t *)0x4004C070 // Pin Control Register n
+#define PORTD_PCR29 *(volatile uint32_t *)0x4004C074 // Pin Control Register n
+#define PORTD_PCR30 *(volatile uint32_t *)0x4004C078 // Pin Control Register n
+#define PORTD_PCR31 *(volatile uint32_t *)0x4004C07C // Pin Control Register n
+#define PORTD_GPCLR *(volatile uint32_t *)0x4004C080 // Global Pin Control Low Register
+#define PORTD_GPCHR *(volatile uint32_t *)0x4004C084 // Global Pin Control High Register
+#define PORTD_ISFR *(volatile uint32_t *)0x4004C0A0 // Interrupt Status Flag Register
+#define PORTE_PCR0 *(volatile uint32_t *)0x4004D000 // Pin Control Register n
+#define PORTE_PCR1 *(volatile uint32_t *)0x4004D004 // Pin Control Register n
+#define PORTE_PCR2 *(volatile uint32_t *)0x4004D008 // Pin Control Register n
+#define PORTE_PCR3 *(volatile uint32_t *)0x4004D00C // Pin Control Register n
+#define PORTE_PCR4 *(volatile uint32_t *)0x4004D010 // Pin Control Register n
+#define PORTE_PCR5 *(volatile uint32_t *)0x4004D014 // Pin Control Register n
+#define PORTE_PCR6 *(volatile uint32_t *)0x4004D018 // Pin Control Register n
+#define PORTE_PCR7 *(volatile uint32_t *)0x4004D01C // Pin Control Register n
+#define PORTE_PCR8 *(volatile uint32_t *)0x4004D020 // Pin Control Register n
+#define PORTE_PCR9 *(volatile uint32_t *)0x4004D024 // Pin Control Register n
+#define PORTE_PCR10 *(volatile uint32_t *)0x4004D028 // Pin Control Register n
+#define PORTE_PCR11 *(volatile uint32_t *)0x4004D02C // Pin Control Register n
+#define PORTE_PCR12 *(volatile uint32_t *)0x4004D030 // Pin Control Register n
+#define PORTE_PCR13 *(volatile uint32_t *)0x4004D034 // Pin Control Register n
+#define PORTE_PCR14 *(volatile uint32_t *)0x4004D038 // Pin Control Register n
+#define PORTE_PCR15 *(volatile uint32_t *)0x4004D03C // Pin Control Register n
+#define PORTE_PCR16 *(volatile uint32_t *)0x4004D040 // Pin Control Register n
+#define PORTE_PCR17 *(volatile uint32_t *)0x4004D044 // Pin Control Register n
+#define PORTE_PCR18 *(volatile uint32_t *)0x4004D048 // Pin Control Register n
+#define PORTE_PCR19 *(volatile uint32_t *)0x4004D04C // Pin Control Register n
+#define PORTE_PCR20 *(volatile uint32_t *)0x4004D050 // Pin Control Register n
+#define PORTE_PCR21 *(volatile uint32_t *)0x4004D054 // Pin Control Register n
+#define PORTE_PCR22 *(volatile uint32_t *)0x4004D058 // Pin Control Register n
+#define PORTE_PCR23 *(volatile uint32_t *)0x4004D05C // Pin Control Register n
+#define PORTE_PCR24 *(volatile uint32_t *)0x4004D060 // Pin Control Register n
+#define PORTE_PCR25 *(volatile uint32_t *)0x4004D064 // Pin Control Register n
+#define PORTE_PCR26 *(volatile uint32_t *)0x4004D068 // Pin Control Register n
+#define PORTE_PCR27 *(volatile uint32_t *)0x4004D06C // Pin Control Register n
+#define PORTE_PCR28 *(volatile uint32_t *)0x4004D070 // Pin Control Register n
+#define PORTE_PCR29 *(volatile uint32_t *)0x4004D074 // Pin Control Register n
+#define PORTE_PCR30 *(volatile uint32_t *)0x4004D078 // Pin Control Register n
+#define PORTE_PCR31 *(volatile uint32_t *)0x4004D07C // Pin Control Register n
+#define PORTE_GPCLR *(volatile uint32_t *)0x4004D080 // Global Pin Control Low Register
+#define PORTE_GPCHR *(volatile uint32_t *)0x4004D084 // Global Pin Control High Register
+#define PORTE_ISFR *(volatile uint32_t *)0x4004D0A0 // Interrupt Status Flag Register
+
+// Chapter 12: System Integration Module (SIM)
+#define SIM_SOPT1 *(volatile uint32_t *)0x40047000 // System Options Register 1
+#define SIM_SOPT1CFG *(volatile uint32_t *)0x40047004 // SOPT1 Configuration Register
+#define SIM_SOPT2 *(volatile uint32_t *)0x40048004 // System Options Register 2
+#define SIM_SOPT2_USBSRC (uint32_t)0x00040000 // 0=USB_CLKIN, 1=FFL/PLL
+#define SIM_SOPT2_PLLFLLSEL (uint32_t)0x00010000 // 0=FLL, 1=PLL
+#define SIM_SOPT2_TRACECLKSEL (uint32_t)0x00001000 // 0=MCGOUTCLK, 1=CPU
+#define SIM_SOPT2_PTD7PAD (uint32_t)0x00000800 // 0=normal, 1=double drive PTD7
+#define SIM_SOPT2_CLKOUTSEL(n) (uint32_t)(((n) & 7) << 5) // Selects the clock to output on the CLKOUT pin.
+#define SIM_SOPT2_RTCCLKOUTSEL (uint32_t)0x00000010 // RTC clock out select
+#define SIM_SOPT4 *(volatile uint32_t *)0x4004800C // System Options Register 4
+#define SIM_SOPT5 *(volatile uint32_t *)0x40048010 // System Options Register 5
+#define SIM_SOPT7 *(volatile uint32_t *)0x40048018 // System Options Register 7
+#define SIM_SDID *(const uint32_t *)0x40048024 // System Device Identification Register
+#define SIM_SCGC2 *(volatile uint32_t *)0x4004802C // System Clock Gating Control Register 2
+#define SIM_SCGC2_DAC0 (uint32_t)0x00001000 // DAC0 Clock Gate Control
+#define SIM_SCGC3 *(volatile uint32_t *)0x40048030 // System Clock Gating Control Register 3
+#define SIM_SCGC3_ADC1 (uint32_t)0x08000000 // ADC1 Clock Gate Control
+#define SIM_SCGC3_FTM2 (uint32_t)0x01000000 // FTM2 Clock Gate Control
+#define SIM_SCGC4 *(volatile uint32_t *)0x40048034 // System Clock Gating Control Register 4
+#define SIM_SCGC4_VREF (uint32_t)0x00100000 // VREF Clock Gate Control
+#define SIM_SCGC4_CMP (uint32_t)0x00080000 // Comparator Clock Gate Control
+#define SIM_SCGC4_USBOTG (uint32_t)0x00040000 // USB Clock Gate Control
+#define SIM_SCGC4_UART2 (uint32_t)0x00001000 // UART2 Clock Gate Control
+#define SIM_SCGC4_UART1 (uint32_t)0x00000800 // UART1 Clock Gate Control
+#define SIM_SCGC4_UART0 (uint32_t)0x00000400 // UART0 Clock Gate Control
+#define SIM_SCGC4_I2C1 (uint32_t)0x00000080 // I2C1 Clock Gate Control
+#define SIM_SCGC4_I2C0 (uint32_t)0x00000040 // I2C0 Clock Gate Control
+#define SIM_SCGC4_CMT (uint32_t)0x00000004 // CMT Clock Gate Control
+#define SIM_SCGC4_EWM (uint32_t)0x00000002 // EWM Clock Gate Control
+#define SIM_SCGC5 *(volatile uint32_t *)0x40048038 // System Clock Gating Control Register 5
+#define SIM_SCGC5_PORTE (uint32_t)0x00002000 // Port E Clock Gate Control
+#define SIM_SCGC5_PORTD (uint32_t)0x00001000 // Port D Clock Gate Control
+#define SIM_SCGC5_PORTC (uint32_t)0x00000800 // Port C Clock Gate Control
+#define SIM_SCGC5_PORTB (uint32_t)0x00000400 // Port B Clock Gate Control
+#define SIM_SCGC5_PORTA (uint32_t)0x00000200 // Port A Clock Gate Control
+#define SIM_SCGC5_TSI (uint32_t)0x00000020 // Touch Sense Input TSI Clock Gate Control
+#define SIM_SCGC5_LPTIMER (uint32_t)0x00000001 // Low Power Timer Access Control
+#define SIM_SCGC6 *(volatile uint32_t *)0x4004803C // System Clock Gating Control Register 6
+#define SIM_SCGC6_RTC (uint32_t)0x20000000 // RTC Access
+#define SIM_SCGC6_ADC0 (uint32_t)0x08000000 // ADC0 Clock Gate Control
+#define SIM_SCGC6_FTM1 (uint32_t)0x02000000 // FTM1 Clock Gate Control
+#define SIM_SCGC6_FTM0 (uint32_t)0x01000000 // FTM0 Clock Gate Control
+#define SIM_SCGC6_PIT (uint32_t)0x00800000 // PIT Clock Gate Control
+#define SIM_SCGC6_PDB (uint32_t)0x00400000 // PDB Clock Gate Control
+#define SIM_SCGC6_USBDCD (uint32_t)0x00200000 // USB DCD Clock Gate Control
+#define SIM_SCGC6_CRC (uint32_t)0x00040000 // CRC Clock Gate Control
+#define SIM_SCGC6_I2S (uint32_t)0x00008000 // I2S Clock Gate Control
+#define SIM_SCGC6_SPI1 (uint32_t)0x00002000 // SPI1 Clock Gate Control
+#define SIM_SCGC6_SPI0 (uint32_t)0x00001000 // SPI0 Clock Gate Control
+#define SIM_SCGC6_FLEXCAN0 (uint32_t)0x00000010 // FlexCAN0 Clock Gate Control
+#define SIM_SCGC6_DMAMUX (uint32_t)0x00000002 // DMA Mux Clock Gate Control
+#define SIM_SCGC6_FTFL (uint32_t)0x00000001 // Flash Memory Clock Gate Control
+#define SIM_SCGC7 *(volatile uint32_t *)0x40048040 // System Clock Gating Control Register 7
+#define SIM_SCGC7_DMA (uint32_t)0x00000002 // DMA Clock Gate Control
+#define SIM_CLKDIV1 *(volatile uint32_t *)0x40048044 // System Clock Divider Register 1
+#define SIM_CLKDIV1_OUTDIV1(n) (uint32_t)(((n) & 0x0F) << 28) // divide value for the core/system clock
+#define SIM_CLKDIV1_OUTDIV2(n) (uint32_t)(((n) & 0x0F) << 24) // divide value for the peripheral clock
+#define SIM_CLKDIV1_OUTDIV4(n) (uint32_t)(((n) & 0x0F) << 16) // divide value for the flash clock
+#define SIM_CLKDIV2 *(volatile uint32_t *)0x40048048 // System Clock Divider Register 2
+#define SIM_CLKDIV2_USBDIV(n) (uint32_t)(((n) & 0x07) << 1)
+#define SIM_CLKDIV2_USBFRAC (uint32_t)0x01
+#define SIM_FCFG1 *(const uint32_t *)0x4004804C // Flash Configuration Register 1
+#define SIM_FCFG2 *(const uint32_t *)0x40048050 // Flash Configuration Register 2
+#define SIM_UIDH *(const uint32_t *)0x40048054 // Unique Identification Register High
+#define SIM_UIDMH *(const uint32_t *)0x40048058 // Unique Identification Register Mid-High
+#define SIM_UIDML *(const uint32_t *)0x4004805C // Unique Identification Register Mid Low
+#define SIM_UIDL *(const uint32_t *)0x40048060 // Unique Identification Register Low
+
+// Chapter 13: Reset Control Module (RCM)
+#define RCM_SRS0 *(volatile uint8_t *)0x4007F000 // System Reset Status Register 0
+#define RCM_SRS1 *(volatile uint8_t *)0x4007F001 // System Reset Status Register 1
+#define RCM_RPFC *(volatile uint8_t *)0x4007F004 // Reset Pin Filter Control Register
+#define RCM_RPFW *(volatile uint8_t *)0x4007F005 // Reset Pin Filter Width Register
+#define RCM_MR *(volatile uint8_t *)0x4007F007 // Mode Register
+
+// Chapter 14: System Mode Controller
+#define SMC_PMPROT *(volatile uint8_t *)0x4007E000 // Power Mode Protection Register
+#define SMC_PMPROT_AVLP (uint8_t)0x20 // Allow very low power modes
+#define SMC_PMPROT_ALLS (uint8_t)0x08 // Allow low leakage stop mode
+#define SMC_PMPROT_AVLLS (uint8_t)0x02 // Allow very low leakage stop mode
+#define SMC_PMCTRL *(volatile uint8_t *)0x4007E001 // Power Mode Control Register
+#define SMC_PMCTRL_LPWUI (uint8_t)0x80 // Low Power Wake Up on Interrupt
+#define SMC_PMCTRL_RUNM(n) (uint8_t)(((n) & 0x03) << 5) // Run Mode Control
+#define SMC_PMCTRL_STOPA (uint8_t)0x08 // Stop Aborted
+#define SMC_PMCTRL_STOPM(n) (uint8_t)((n) & 0x07) // Stop Mode Control
+#define SMC_VLLSCTRL *(volatile uint8_t *)0x4007E002 // VLLS Control Register
+#define SMC_VLLSCTRL_PORPO (uint8_t)0x20 // POR Power Option
+#define SMC_VLLSCTRL_VLLSM(n) (uint8_t)((n) & 0x07) // VLLS Mode Control
+#define SMC_PMSTAT *(volatile uint8_t *)0x4007E003 // Power Mode Status Register
+#define SMC_PMSTAT_RUN (uint8_t)0x01 // Current power mode is RUN
+#define SMC_PMSTAT_STOP (uint8_t)0x02 // Current power mode is STOP
+#define SMC_PMSTAT_VLPR (uint8_t)0x04 // Current power mode is VLPR
+#define SMC_PMSTAT_VLPW (uint8_t)0x08 // Current power mode is VLPW
+#define SMC_PMSTAT_VLPS (uint8_t)0x10 // Current power mode is VLPS
+#define SMC_PMSTAT_LLS (uint8_t)0x20 // Current power mode is LLS
+#define SMC_PMSTAT_VLLS (uint8_t)0x40 // Current power mode is VLLS
+
+// Chapter 15: Power Management Controller
+#define PMC_LVDSC1 *(volatile uint8_t *)0x4007D000 // Low Voltage Detect Status And Control 1 register
+#define PMC_LVDSC1_LVDF (uint8_t)0x80 // Low-Voltage Detect Flag
+#define PMC_LVDSC1_LVDACK (uint8_t)0x40 // Low-Voltage Detect Acknowledge
+#define PMC_LVDSC1_LVDIE (uint8_t)0x20 // Low-Voltage Detect Interrupt Enable
+#define PMC_LVDSC1_LVDRE (uint8_t)0x10 // Low-Voltage Detect Reset Enable
+#define PMC_LVDSC1_LVDV(n) (uint8_t)((n) & 0x03) // Low-Voltage Detect Voltage Select
+#define PMC_LVDSC2 *(volatile uint8_t *)0x4007D001 // Low Voltage Detect Status And Control 2 register
+#define PMC_LVDSC2_LVWF (uint8_t)0x80 // Low-Voltage Warning Flag
+#define PMC_LVDSC2_LVWACK (uint8_t)0x40 // Low-Voltage Warning Acknowledge
+#define PMC_LVDSC2_LVWIE (uint8_t)0x20 // Low-Voltage Warning Interrupt Enable
+#define PMC_LVDSC2_LVWV(n) (uint8_t)((n) & 0x03) // Low-Voltage Warning Voltage Select
+#define PMC_REGSC *(volatile uint8_t *)0x4007D002 // Regulator Status And Control register
+#define PMC_REGSC_BGEN (uint8_t)0x10 // Bandgap Enable In VLPx Operation
+#define PMC_REGSC_ACKISO (uint8_t)0x08 // Acknowledge Isolation
+#define PMC_REGSC_REGONS (uint8_t)0x04 // Regulator In Run Regulation Status
+#define PMC_REGSC_BGBE (uint8_t)0x01 // Bandgap Buffer Enable
+
+// Chapter 16: Low-Leakage Wakeup Unit (LLWU)
+#define LLWU_PE1 *(volatile uint8_t *)0x4007C000 // LLWU Pin Enable 1 register
+#define LLWU_PE2 *(volatile uint8_t *)0x4007C001 // LLWU Pin Enable 2 register
+#define LLWU_PE3 *(volatile uint8_t *)0x4007C002 // LLWU Pin Enable 3 register
+#define LLWU_PE4 *(volatile uint8_t *)0x4007C003 // LLWU Pin Enable 4 register
+#define LLWU_ME *(volatile uint8_t *)0x4007C004 // LLWU Module Enable register
+#define LLWU_F1 *(volatile uint8_t *)0x4007C005 // LLWU Flag 1 register
+#define LLWU_F2 *(volatile uint8_t *)0x4007C006 // LLWU Flag 2 register
+#define LLWU_F3 *(volatile uint8_t *)0x4007C007 // LLWU Flag 3 register
+#define LLWU_FILT1 *(volatile uint8_t *)0x4007C008 // LLWU Pin Filter 1 register
+#define LLWU_FILT2 *(volatile uint8_t *)0x4007C009 // LLWU Pin Filter 2 register
+#define LLWU_RST *(volatile uint8_t *)0x4007C00A // LLWU Reset Enable register
+
+// Chapter 17: Miscellaneous Control Module (MCM)
+#define MCM_PLASC *(volatile uint16_t *)0xE0080008 // Crossbar Switch (AXBS) Slave Configuration
+#define MCM_PLAMC *(volatile uint16_t *)0xE008000A // Crossbar Switch (AXBS) Master Configuration
+#define MCM_PLACR *(volatile uint32_t *)0xE008000C // Crossbar Switch (AXBS) Control Register (MK20DX128)
+#define MCM_PLACR_ARG (uint32_t)0x00000200 // Arbitration select, 0=fixed, 1=round-robin
+#define MCM_CR *(volatile uint32_t *)0xE008000C // RAM arbitration control register (MK20DX256)
+#define MCM_CR_SRAMLWP (uint32_t)0x40000000 // SRAM_L write protect
+#define MCM_CR_SRAMLAP(n) (uint32_t)(((n) & 0x03) << 28) // SRAM_L priority, 0=RR, 1=favor DMA, 2=CPU, 3=DMA
+#define MCM_CR_SRAMUWP (uint32_t)0x04000000 // SRAM_U write protect
+#define MCM_CR_SRAMUAP(n) (uint32_t)(((n) & 0x03) << 24) // SRAM_U priority, 0=RR, 1=favor DMA, 2=CPU, 3=DMA
+
+// Crossbar Switch (AXBS) - only programmable on MK20DX256
+#define AXBS_PRS0 *(volatile uint32_t *)0x40004000 // Priority Registers Slave 0
+#define AXBS_CRS0 *(volatile uint32_t *)0x40004010 // Control Register 0
+#define AXBS_PRS1 *(volatile uint32_t *)0x40004100 // Priority Registers Slave 1
+#define AXBS_CRS1 *(volatile uint32_t *)0x40004110 // Control Register 1
+#define AXBS_PRS2 *(volatile uint32_t *)0x40004200 // Priority Registers Slave 2
+#define AXBS_CRS2 *(volatile uint32_t *)0x40004210 // Control Register 2
+#define AXBS_PRS3 *(volatile uint32_t *)0x40004300 // Priority Registers Slave 3
+#define AXBS_CRS3 *(volatile uint32_t *)0x40004310 // Control Register 3
+#define AXBS_PRS4 *(volatile uint32_t *)0x40004400 // Priority Registers Slave 4
+#define AXBS_CRS4 *(volatile uint32_t *)0x40004410 // Control Register 4
+#define AXBS_PRS5 *(volatile uint32_t *)0x40004500 // Priority Registers Slave 5
+#define AXBS_CRS5 *(volatile uint32_t *)0x40004510 // Control Register 5
+#define AXBS_PRS6 *(volatile uint32_t *)0x40004600 // Priority Registers Slave 6
+#define AXBS_CRS6 *(volatile uint32_t *)0x40004610 // Control Register 6
+#define AXBS_PRS7 *(volatile uint32_t *)0x40004700 // Priority Registers Slave 7
+#define AXBS_CRS7 *(volatile uint32_t *)0x40004710 // Control Register 7
+#define AXBS_MGPCR0 *(volatile uint32_t *)0x40004800 // Master 0 General Purpose Control Register
+#define AXBS_MGPCR1 *(volatile uint32_t *)0x40004900 // Master 1 General Purpose Control Register
+#define AXBS_MGPCR2 *(volatile uint32_t *)0x40004A00 // Master 2 General Purpose Control Register
+#define AXBS_MGPCR3 *(volatile uint32_t *)0x40004B00 // Master 3 General Purpose Control Register
+#define AXBS_MGPCR4 *(volatile uint32_t *)0x40004C00 // Master 4 General Purpose Control Register
+#define AXBS_MGPCR5 *(volatile uint32_t *)0x40004D00 // Master 5 General Purpose Control Register
+#define AXBS_MGPCR6 *(volatile uint32_t *)0x40004E00 // Master 6 General Purpose Control Register
+#define AXBS_MGPCR7 *(volatile uint32_t *)0x40004F00 // Master 7 General Purpose Control Register
+#define AXBS_CRS_READONLY (uint32_t)0x80000000
+#define AXBS_CRS_HALTLOWPRIORITY (uint32_t)0x40000000
+#define AXBS_CRS_ARB_FIXED (uint32_t)0x00000000
+#define AXBS_CRS_ARB_ROUNDROBIN (uint32_t)0x00010000
+#define AXBS_CRS_PARK_FIXED (uint32_t)0x00000000
+#define AXBS_CRS_PARK_PREVIOUS (uint32_t)0x00000010
+#define AXBS_CRS_PARK_NONE (uint32_t)0x00000020
+#define AXBS_CRS_PARK(n) (uint32_t)(((n) & 7) << 0)
+
+
+
+// Chapter 20: Direct Memory Access Multiplexer (DMAMUX)
+#define DMAMUX0_CHCFG0 *(volatile uint8_t *)0x40021000 // Channel Configuration register
+#define DMAMUX0_CHCFG1 *(volatile uint8_t *)0x40021001 // Channel Configuration register
+#define DMAMUX0_CHCFG2 *(volatile uint8_t *)0x40021002 // Channel Configuration register
+#define DMAMUX0_CHCFG3 *(volatile uint8_t *)0x40021003 // Channel Configuration register
+#define DMAMUX0_CHCFG4 *(volatile uint8_t *)0x40021004 // Channel Configuration register
+#define DMAMUX0_CHCFG5 *(volatile uint8_t *)0x40021005 // Channel Configuration register
+#define DMAMUX0_CHCFG6 *(volatile uint8_t *)0x40021006 // Channel Configuration register
+#define DMAMUX0_CHCFG7 *(volatile uint8_t *)0x40021007 // Channel Configuration register
+#define DMAMUX0_CHCFG8 *(volatile uint8_t *)0x40021008 // Channel Configuration register
+#define DMAMUX0_CHCFG9 *(volatile uint8_t *)0x40021009 // Channel Configuration register
+#define DMAMUX0_CHCFG10 *(volatile uint8_t *)0x4002100A // Channel Configuration register
+#define DMAMUX0_CHCFG11 *(volatile uint8_t *)0x4002100B // Channel Configuration register
+#define DMAMUX0_CHCFG12 *(volatile uint8_t *)0x4002100C // Channel Configuration register
+#define DMAMUX0_CHCFG13 *(volatile uint8_t *)0x4002100D // Channel Configuration register
+#define DMAMUX0_CHCFG14 *(volatile uint8_t *)0x4002100E // Channel Configuration register
+#define DMAMUX0_CHCFG15 *(volatile uint8_t *)0x4002100F // Channel Configuration register
+#define DMAMUX_DISABLE 0
+#define DMAMUX_TRIG 64
+#define DMAMUX_ENABLE 128
+#define DMAMUX_SOURCE_UART0_RX 2
+#define DMAMUX_SOURCE_UART0_TX 3
+#define DMAMUX_SOURCE_UART1_RX 4
+#define DMAMUX_SOURCE_UART1_TX 5
+#define DMAMUX_SOURCE_UART2_RX 6
+#define DMAMUX_SOURCE_UART2_TX 7
+#define DMAMUX_SOURCE_I2S0_RX 14
+#define DMAMUX_SOURCE_I2S0_TX 15
+#define DMAMUX_SOURCE_SPI0_RX 16
+#define DMAMUX_SOURCE_SPI0_TX 17
+#define DMAMUX_SOURCE_I2C0 22
+#define DMAMUX_SOURCE_I2C1 23
+#define DMAMUX_SOURCE_FTM0_CH0 24
+#define DMAMUX_SOURCE_FTM0_CH1 25
+#define DMAMUX_SOURCE_FTM0_CH2 26
+#define DMAMUX_SOURCE_FTM0_CH3 27
+#define DMAMUX_SOURCE_FTM0_CH4 28
+#define DMAMUX_SOURCE_FTM0_CH5 29
+#define DMAMUX_SOURCE_FTM0_CH6 30
+#define DMAMUX_SOURCE_FTM0_CH7 31
+#define DMAMUX_SOURCE_FTM1_CH0 32
+#define DMAMUX_SOURCE_FTM1_CH1 33
+#define DMAMUX_SOURCE_FTM2_CH0 34
+#define DMAMUX_SOURCE_FTM2_CH1 35
+#define DMAMUX_SOURCE_ADC0 40
+#define DMAMUX_SOURCE_ADC1 41
+#define DMAMUX_SOURCE_CMP0 42
+#define DMAMUX_SOURCE_CMP1 43
+#define DMAMUX_SOURCE_CMP2 44
+#define DMAMUX_SOURCE_DAC0 45
+#define DMAMUX_SOURCE_CMT 47
+#define DMAMUX_SOURCE_PDB 48
+#define DMAMUX_SOURCE_PORTA 49
+#define DMAMUX_SOURCE_PORTB 50
+#define DMAMUX_SOURCE_PORTC 51
+#define DMAMUX_SOURCE_PORTD 52
+#define DMAMUX_SOURCE_PORTE 53
+#define DMAMUX_SOURCE_ALWAYS0 54
+#define DMAMUX_SOURCE_ALWAYS1 55
+#define DMAMUX_SOURCE_ALWAYS2 56
+#define DMAMUX_SOURCE_ALWAYS3 57
+#define DMAMUX_SOURCE_ALWAYS4 58
+#define DMAMUX_SOURCE_ALWAYS5 59
+#define DMAMUX_SOURCE_ALWAYS6 60
+#define DMAMUX_SOURCE_ALWAYS7 61
+#define DMAMUX_SOURCE_ALWAYS8 62
+#define DMAMUX_SOURCE_ALWAYS9 63
+
+// Chapter 21: Direct Memory Access Controller (eDMA)
+#define DMA_CR *(volatile uint32_t *)0x40008000 // Control Register
+#define DMA_CR_CX ((uint32_t)(1<<17)) // Cancel Transfer
+#define DMA_CR_ECX ((uint32_t)(1<<16)) // Error Cancel Transfer
+#define DMA_CR_EMLM ((uint32_t)0x80) // Enable Minor Loop Mapping
+#define DMA_CR_CLM ((uint32_t)0x40) // Continuous Link Mode
+#define DMA_CR_HALT ((uint32_t)0x20) // Halt DMA Operations
+#define DMA_CR_HOE ((uint32_t)0x10) // Halt On Error
+#define DMA_CR_ERCA ((uint32_t)0x04) // Enable Round Robin Channel Arbitration
+#define DMA_CR_EDBG ((uint32_t)0x02) // Enable Debug
+#define DMA_ES *(volatile uint32_t *)0x40008004 // Error Status Register
+#define DMA_ERQ *(volatile uint32_t *)0x4000800C // Enable Request Register
+#define DMA_ERQ_ERQ0 ((uint32_t)1<<0) // Enable DMA Request 0
+#define DMA_ERQ_ERQ1 ((uint32_t)1<<1) // Enable DMA Request 1
+#define DMA_ERQ_ERQ2 ((uint32_t)1<<2) // Enable DMA Request 2
+#define DMA_ERQ_ERQ3 ((uint32_t)1<<3) // Enable DMA Request 3
+#define DMA_ERQ_ERQ4 ((uint32_t)1<<4) // Enable DMA Request 4
+#define DMA_ERQ_ERQ5 ((uint32_t)1<<5) // Enable DMA Request 5
+#define DMA_ERQ_ERQ6 ((uint32_t)1<<6) // Enable DMA Request 6
+#define DMA_ERQ_ERQ7 ((uint32_t)1<<7) // Enable DMA Request 7
+#define DMA_ERQ_ERQ8 ((uint32_t)1<<8) // Enable DMA Request 8
+#define DMA_ERQ_ERQ9 ((uint32_t)1<<9) // Enable DMA Request 9
+#define DMA_ERQ_ERQ10 ((uint32_t)1<<10) // Enable DMA Request 10
+#define DMA_ERQ_ERQ11 ((uint32_t)1<<11) // Enable DMA Request 11
+#define DMA_ERQ_ERQ12 ((uint32_t)1<<12) // Enable DMA Request 12
+#define DMA_ERQ_ERQ13 ((uint32_t)1<<13) // Enable DMA Request 13
+#define DMA_ERQ_ERQ14 ((uint32_t)1<<14) // Enable DMA Request 14
+#define DMA_ERQ_ERQ15 ((uint32_t)1<<15) // Enable DMA Request 15
+#define DMA_EEI *(volatile uint32_t *)0x40008014 // Enable Error Interrupt Register
+#define DMA_EEI_EEI0 ((uint32_t)1<<0) // Enable Error Interrupt 0
+#define DMA_EEI_EEI1 ((uint32_t)1<<1) // Enable Error Interrupt 1
+#define DMA_EEI_EEI2 ((uint32_t)1<<2) // Enable Error Interrupt 2
+#define DMA_EEI_EEI3 ((uint32_t)1<<3) // Enable Error Interrupt 3
+#define DMA_EEI_EEI4 ((uint32_t)1<<4) // Enable Error Interrupt 4
+#define DMA_EEI_EEI5 ((uint32_t)1<<5) // Enable Error Interrupt 5
+#define DMA_EEI_EEI6 ((uint32_t)1<<6) // Enable Error Interrupt 6
+#define DMA_EEI_EEI7 ((uint32_t)1<<7) // Enable Error Interrupt 7
+#define DMA_EEI_EEI8 ((uint32_t)1<<8) // Enable Error Interrupt 8
+#define DMA_EEI_EEI9 ((uint32_t)1<<9) // Enable Error Interrupt 9
+#define DMA_EEI_EEI10 ((uint32_t)1<<10) // Enable Error Interrupt 10
+#define DMA_EEI_EEI11 ((uint32_t)1<<11) // Enable Error Interrupt 11
+#define DMA_EEI_EEI12 ((uint32_t)1<<12) // Enable Error Interrupt 12
+#define DMA_EEI_EEI13 ((uint32_t)1<<13) // Enable Error Interrupt 13
+#define DMA_EEI_EEI14 ((uint32_t)1<<14) // Enable Error Interrupt 14
+#define DMA_EEI_EEI15 ((uint32_t)1<<15) // Enable Error Interrupt 15
+#define DMA_CEEI *(volatile uint8_t *)0x40008018 // Clear Enable Error Interrupt Register
+#define DMA_CEEI_CEEI(n) ((uint8_t)(n & 15)<<0) // Clear Enable Error Interrupt
+#define DMA_CEEI_CAEE ((uint8_t)1<<6) // Clear All Enable Error Interrupts
+#define DMA_CEEI_NOP ((uint8_t)1<<7) // NOP
+#define DMA_SEEI *(volatile uint8_t *)0x40008019 // Set Enable Error Interrupt Register
+#define DMA_SEEI_SEEI(n) ((uint8_t)(n & 15)<<0) // Set Enable Error Interrupt
+#define DMA_SEEI_SAEE ((uint8_t)1<<6) // Set All Enable Error Interrupts
+#define DMA_SEEI_NOP ((uint8_t)1<<7) // NOP
+#define DMA_CERQ *(volatile uint8_t *)0x4000801A // Clear Enable Request Register
+#define DMA_CERQ_CERQ(n) ((uint8_t)(n & 15)<<0) // Clear Enable Request
+#define DMA_CERQ_CAER ((uint8_t)1<<6) // Clear All Enable Requests
+#define DMA_CERQ_NOP ((uint8_t)1<<7) // NOP
+#define DMA_SERQ *(volatile uint8_t *)0x4000801B // Set Enable Request Register
+#define DMA_SERQ_SERQ(n) ((uint8_t)(n & 15)<<0) // Set Enable Request
+#define DMA_SERQ_SAER ((uint8_t)1<<6) // Set All Enable Requests
+#define DMA_SERQ_NOP ((uint8_t)1<<7) // NOP
+#define DMA_CDNE *(volatile uint8_t *)0x4000801C // Clear DONE Status Bit Register
+#define DMA_CDNE_CDNE(n) ((uint8_t)(n & 15)<<0) // Clear Done Bit
+#define DMA_CDNE_CADN ((uint8_t)1<<6) // Clear All Done Bits
+#define DMA_CDNE_NOP ((uint8_t)1<<7) // NOP
+#define DMA_SSRT *(volatile uint8_t *)0x4000801D // Set START Bit Register
+#define DMA_SSRT_SSRT(n) ((uint8_t)(n & 15)<<0) // Set Start Bit
+#define DMA_SSRT_SAST ((uint8_t)1<<6) // Set All Start Bits
+#define DMA_SSRT_NOP ((uint8_t)1<<7) // NOP
+#define DMA_CERR *(volatile uint8_t *)0x4000801E // Clear Error Register
+#define DMA_CERR_CERR(n) ((uint8_t)(n & 15)<<0) // Clear Error Indicator
+#define DMA_CERR_CAEI ((uint8_t)1<<6) // Clear All Error Indicators
+#define DMA_CERR_NOP ((uint8_t)1<<7) // NOP
+#define DMA_CINT *(volatile uint8_t *)0x4000801F // Clear Interrupt Request Register
+#define DMA_CINT_CINT(n) ((uint8_t)(n & 15)<<0) // Clear Interrupt Request
+#define DMA_CINT_CAIR ((uint8_t)1<<6) // Clear All Interrupt Requests
+#define DMA_CINT_NOP ((uint8_t)1<<7) // NOP
+#define DMA_INT *(volatile uint32_t *)0x40008024 // Interrupt Request Register
+#define DMA_INT_INT0 ((uint32_t)1<<0) // Interrupt Request 0
+#define DMA_INT_INT1 ((uint32_t)1<<1) // Interrupt Request 1
+#define DMA_INT_INT2 ((uint32_t)1<<2) // Interrupt Request 2
+#define DMA_INT_INT3 ((uint32_t)1<<3) // Interrupt Request 3
+#define DMA_INT_INT4 ((uint32_t)1<<4) // Interrupt Request 4
+#define DMA_INT_INT5 ((uint32_t)1<<5) // Interrupt Request 5
+#define DMA_INT_INT6 ((uint32_t)1<<6) // Interrupt Request 6
+#define DMA_INT_INT7 ((uint32_t)1<<7) // Interrupt Request 7
+#define DMA_INT_INT8 ((uint32_t)1<<8) // Interrupt Request 8
+#define DMA_INT_INT9 ((uint32_t)1<<9) // Interrupt Request 9
+#define DMA_INT_INT10 ((uint32_t)1<<10) // Interrupt Request 10
+#define DMA_INT_INT11 ((uint32_t)1<<11) // Interrupt Request 11
+#define DMA_INT_INT12 ((uint32_t)1<<12) // Interrupt Request 12
+#define DMA_INT_INT13 ((uint32_t)1<<13) // Interrupt Request 13
+#define DMA_INT_INT14 ((uint32_t)1<<14) // Interrupt Request 14
+#define DMA_INT_INT15 ((uint32_t)1<<15) // Interrupt Request 15
+#define DMA_ERR *(volatile uint32_t *)0x4000802C // Error Register
+#define DMA_ERR_ERR0 ((uint32_t)1<<0) // Error in Channel 0
+#define DMA_ERR_ERR1 ((uint32_t)1<<1) // Error in Channel 1
+#define DMA_ERR_ERR2 ((uint32_t)1<<2) // Error in Channel 2
+#define DMA_ERR_ERR3 ((uint32_t)1<<3) // Error in Channel 3
+#define DMA_ERR_ERR4 ((uint32_t)1<<4) // Error in Channel 4
+#define DMA_ERR_ERR5 ((uint32_t)1<<5) // Error in Channel 5
+#define DMA_ERR_ERR6 ((uint32_t)1<<6) // Error in Channel 6
+#define DMA_ERR_ERR7 ((uint32_t)1<<7) // Error in Channel 7
+#define DMA_ERR_ERR8 ((uint32_t)1<<8) // Error in Channel 8
+#define DMA_ERR_ERR9 ((uint32_t)1<<9) // Error in Channel 9
+#define DMA_ERR_ERR10 ((uint32_t)1<<10) // Error in Channel 10
+#define DMA_ERR_ERR11 ((uint32_t)1<<11) // Error in Channel 11
+#define DMA_ERR_ERR12 ((uint32_t)1<<12) // Error in Channel 12
+#define DMA_ERR_ERR13 ((uint32_t)1<<13) // Error in Channel 13
+#define DMA_ERR_ERR14 ((uint32_t)1<<14) // Error in Channel 14
+#define DMA_ERR_ERR15 ((uint32_t)1<<15) // Error in Channel 15
+#define DMA_HRS *(volatile uint32_t *)0x40008034 // Hardware Request Status Register
+#define DMA_HRS_HRS0 ((uint32_t)1<<0) // Hardware Request Status Channel 0
+#define DMA_HRS_HRS1 ((uint32_t)1<<1) // Hardware Request Status Channel 1
+#define DMA_HRS_HRS2 ((uint32_t)1<<2) // Hardware Request Status Channel 2
+#define DMA_HRS_HRS3 ((uint32_t)1<<3) // Hardware Request Status Channel 3
+#define DMA_HRS_HRS4 ((uint32_t)1<<4) // Hardware Request Status Channel 4
+#define DMA_HRS_HRS5 ((uint32_t)1<<5) // Hardware Request Status Channel 5
+#define DMA_HRS_HRS6 ((uint32_t)1<<6) // Hardware Request Status Channel 6
+#define DMA_HRS_HRS7 ((uint32_t)1<<7) // Hardware Request Status Channel 7
+#define DMA_HRS_HRS8 ((uint32_t)1<<8) // Hardware Request Status Channel 8
+#define DMA_HRS_HRS9 ((uint32_t)1<<9) // Hardware Request Status Channel 9
+#define DMA_HRS_HRS10 ((uint32_t)1<<10) // Hardware Request Status Channel 10
+#define DMA_HRS_HRS11 ((uint32_t)1<<11) // Hardware Request Status Channel 11
+#define DMA_HRS_HRS12 ((uint32_t)1<<12) // Hardware Request Status Channel 12
+#define DMA_HRS_HRS13 ((uint32_t)1<<13) // Hardware Request Status Channel 13
+#define DMA_HRS_HRS14 ((uint32_t)1<<14) // Hardware Request Status Channel 14
+#define DMA_HRS_HRS15 ((uint32_t)1<<15) // Hardware Request Status Channel 15
+#define DMA_DCHPRI3 *(volatile uint8_t *)0x40008100 // Channel n Priority Register
+#define DMA_DCHPRI2 *(volatile uint8_t *)0x40008101 // Channel n Priority Register
+#define DMA_DCHPRI1 *(volatile uint8_t *)0x40008102 // Channel n Priority Register
+#define DMA_DCHPRI0 *(volatile uint8_t *)0x40008103 // Channel n Priority Register
+#define DMA_DCHPRI_CHPRI(n) ((uint8_t)(n & 15)<<0) // Channel Arbitration Priority
+#define DMA_DCHPRI_DPA ((uint8_t)1<<6) // Disable PreEmpt Ability
+#define DMA_DCHPRI_ECP ((uint8_t)1<<7) // Enable PreEmption
+#define DMA_DCHPRI7 *(volatile uint8_t *)0x40008104 // Channel n Priority Register
+#define DMA_DCHPRI6 *(volatile uint8_t *)0x40008105 // Channel n Priority Register
+#define DMA_DCHPRI5 *(volatile uint8_t *)0x40008106 // Channel n Priority Register
+#define DMA_DCHPRI4 *(volatile uint8_t *)0x40008107 // Channel n Priority Register
+#define DMA_DCHPRI11 *(volatile uint8_t *)0x40008108 // Channel n Priority Register
+#define DMA_DCHPRI10 *(volatile uint8_t *)0x40008109 // Channel n Priority Register
+#define DMA_DCHPRI9 *(volatile uint8_t *)0x4000810A // Channel n Priority Register
+#define DMA_DCHPRI8 *(volatile uint8_t *)0x4000810B // Channel n Priority Register
+#define DMA_DCHPRI15 *(volatile uint8_t *)0x4000810C // Channel n Priority Register
+#define DMA_DCHPRI14 *(volatile uint8_t *)0x4000810D // Channel n Priority Register
+#define DMA_DCHPRI13 *(volatile uint8_t *)0x4000810E // Channel n Priority Register
+#define DMA_DCHPRI12 *(volatile uint8_t *)0x4000810F // Channel n Priority Register
+
+
+#define DMA_TCD_ATTR_SMOD(n) (((n) & 0x1F) << 11)
+#define DMA_TCD_ATTR_SSIZE(n) (((n) & 0x7) << 8)
+#define DMA_TCD_ATTR_DMOD(n) (((n) & 0x1F) << 3)
+#define DMA_TCD_ATTR_DSIZE(n) (((n) & 0x7) << 0)
+#define DMA_TCD_ATTR_SIZE_8BIT 0
+#define DMA_TCD_ATTR_SIZE_16BIT 1
+#define DMA_TCD_ATTR_SIZE_32BIT 2
+#define DMA_TCD_ATTR_SIZE_16BYTE 4
+#define DMA_TCD_ATTR_SIZE_32BYTE 5
+#define DMA_TCD_CSR_BWC(n) (((n) & 0x3) << 14)
+#define DMA_TCD_CSR_MAJORLINKCH(n) (((n) & 0x3) << 8)
+#define DMA_TCD_CSR_DONE 0x0080
+#define DMA_TCD_CSR_ACTIVE 0x0040
+#define DMA_TCD_CSR_MAJORELINK 0x0020
+#define DMA_TCD_CSR_ESG 0x0010
+#define DMA_TCD_CSR_DREQ 0x0008
+#define DMA_TCD_CSR_INTHALF 0x0004
+#define DMA_TCD_CSR_INTMAJOR 0x0002
+#define DMA_TCD_CSR_START 0x0001
+#define DMA_TCD_CITER_MASK ((uint16_t)0x7FFF) // Loop count mask
+#define DMA_TCD_CITER_ELINK ((uint16_t)1<<15) // Enable channel linking on minor-loop complete
+#define DMA_TCD_BITER_MASK ((uint16_t)0x7FFF) // Loop count mask
+#define DMA_TCD_BITER_ELINK ((uint16_t)1<<15) // Enable channel linking on minor-loop complete
+#define DMA_TCD_NBYTES_SMLOE ((uint32_t)1<<31) // Source Minor Loop Offset Enable
+#define DMA_TCD_NBYTES_DMLOE ((uint32_t)1<<30) // Destination Minor Loop Offset Enable
+#define DMA_TCD_NBYTES_MLOFFNO_NBYTES(n) ((uint32_t)(n)) // NBytes transfer count when minor loop disabled
+#define DMA_TCD_NBYTES_MLOFFYES_NBYTES(n) ((uint32_t)(n & 0x1F)) // NBytes transfer count when minor loop enabled
+#define DMA_TCD_NBYTES_MLOFFYES_MLOFF(n) ((uint32_t)(n & 0xFFFFF)<<10) // Offset
+
+#define DMA_TCD0_SADDR *(volatile const void * volatile *)0x40009000 // TCD Source Address
+#define DMA_TCD0_SOFF *(volatile int16_t *)0x40009004 // TCD Signed Source Address Offset
+#define DMA_TCD0_ATTR *(volatile uint16_t *)0x40009006 // TCD Transfer Attributes
+#define DMA_TCD0_NBYTES_MLNO *(volatile uint32_t *)0x40009008 // TCD Minor Byte Count (Minor Loop Disabled)
+#define DMA_TCD0_NBYTES_MLOFFNO *(volatile uint32_t *)0x40009008 // TCD Signed Minor Loop Offset (Minor Loop Enabled and Offset Disabled)
+#define DMA_TCD0_NBYTES_MLOFFYES *(volatile uint32_t *)0x40009008 // TCD Signed Minor Loop Offset (Minor Loop and Offset Enabled)
+#define DMA_TCD0_SLAST *(volatile int32_t *)0x4000900C // TCD Last Source Address Adjustment
+#define DMA_TCD0_DADDR *(volatile void * volatile *)0x40009010 // TCD Destination Address
+#define DMA_TCD0_DOFF *(volatile int16_t *)0x40009014 // TCD Signed Destination Address Offset
+#define DMA_TCD0_CITER_ELINKYES *(volatile uint16_t *)0x40009016 // TCD Current Minor Loop Link, Major Loop Count, Channel Linking Enabled
+#define DMA_TCD0_CITER_ELINKNO *(volatile uint16_t *)0x40009016 // ??
+#define DMA_TCD0_DLASTSGA *(volatile int32_t *)0x40009018 // TCD Last Destination Address Adjustment/Scatter Gather Address
+#define DMA_TCD0_CSR *(volatile uint16_t *)0x4000901C // TCD Control and Status
+#define DMA_TCD0_BITER_ELINKYES *(volatile uint16_t *)0x4000901E // TCD Beginning Minor Loop Link, Major Loop Count, Channel Linking Enabled
+#define DMA_TCD0_BITER_ELINKNO *(volatile uint16_t *)0x4000901E // TCD Beginning Minor Loop Link, Major Loop Count, Channel Linking Disabled
+
+#define DMA_TCD1_SADDR *(volatile const void * volatile *)0x40009020 // TCD Source Address
+#define DMA_TCD1_SOFF *(volatile int16_t *)0x40009024 // TCD Signed Source Address Offset
+#define DMA_TCD1_ATTR *(volatile uint16_t *)0x40009026 // TCD Transfer Attributes
+#define DMA_TCD1_NBYTES_MLNO *(volatile uint32_t *)0x40009028 // TCD Minor Byte Count, Minor Loop Disabled
+#define DMA_TCD1_NBYTES_MLOFFNO *(volatile uint32_t *)0x40009028 // TCD Signed Minor Loop Offset, Minor Loop Enabled and Offset Disabled
+#define DMA_TCD1_NBYTES_MLOFFYES *(volatile uint32_t *)0x40009028 // TCD Signed Minor Loop Offset, Minor Loop and Offset Enabled
+#define DMA_TCD1_SLAST *(volatile int32_t *)0x4000902C // TCD Last Source Address Adjustment
+#define DMA_TCD1_DADDR *(volatile void * volatile *)0x40009030 // TCD Destination Address
+#define DMA_TCD1_DOFF *(volatile int16_t *)0x40009034 // TCD Signed Destination Address Offset
+#define DMA_TCD1_CITER_ELINKYES *(volatile uint16_t *)0x40009036 // TCD Current Minor Loop Link, Major Loop Count, Channel Linking Enabled
+#define DMA_TCD1_CITER_ELINKNO *(volatile uint16_t *)0x40009036 // ??
+#define DMA_TCD1_DLASTSGA *(volatile int32_t *)0x40009038 // TCD Last Destination Address Adjustment/Scatter Gather Address
+#define DMA_TCD1_CSR *(volatile uint16_t *)0x4000903C // TCD Control and Status
+#define DMA_TCD1_BITER_ELINKYES *(volatile uint16_t *)0x4000903E // TCD Beginning Minor Loop Link, Major Loop Count Channel Linking Enabled
+#define DMA_TCD1_BITER_ELINKNO *(volatile uint16_t *)0x4000903E // TCD Beginning Minor Loop Link, Major Loop Count, Channel Linking Disabled
+
+#define DMA_TCD2_SADDR *(volatile const void * volatile *)0x40009040 // TCD Source Address
+#define DMA_TCD2_SOFF *(volatile int16_t *)0x40009044 // TCD Signed Source Address Offset
+#define DMA_TCD2_ATTR *(volatile uint16_t *)0x40009046 // TCD Transfer Attributes
+#define DMA_TCD2_NBYTES_MLNO *(volatile uint32_t *)0x40009048 // TCD Minor Byte Count, Minor Loop Disabled
+#define DMA_TCD2_NBYTES_MLOFFNO *(volatile uint32_t *)0x40009048 // TCD Signed Minor Loop Offset, Minor Loop Enabled and Offset Disabled
+#define DMA_TCD2_NBYTES_MLOFFYES *(volatile uint32_t *)0x40009048 // TCD Signed Minor Loop Offset, Minor Loop and Offset Enabled
+#define DMA_TCD2_SLAST *(volatile int32_t *)0x4000904C // TCD Last Source Address Adjustment
+#define DMA_TCD2_DADDR *(volatile void * volatile *)0x40009050 // TCD Destination Address
+#define DMA_TCD2_DOFF *(volatile int16_t *)0x40009054 // TCD Signed Destination Address Offset
+#define DMA_TCD2_CITER_ELINKYES *(volatile uint16_t *)0x40009056 // TCD Current Minor Loop Link, Major Loop Count, Channel Linking Enabled
+#define DMA_TCD2_CITER_ELINKNO *(volatile uint16_t *)0x40009056 // ??
+#define DMA_TCD2_DLASTSGA *(volatile int32_t *)0x40009058 // TCD Last Destination Address Adjustment/Scatter Gather Address
+#define DMA_TCD2_CSR *(volatile uint16_t *)0x4000905C // TCD Control and Status
+#define DMA_TCD2_BITER_ELINKYES *(volatile uint16_t *)0x4000905E // TCD Beginning Minor Loop Link, Major Loop Count, Channel Linking Enabled
+#define DMA_TCD2_BITER_ELINKNO *(volatile uint16_t *)0x4000905E // TCD Beginning Minor Loop Link, Major Loop Count, Channel Linking Disabled
+
+#define DMA_TCD3_SADDR *(volatile const void * volatile *)0x40009060 // TCD Source Address
+#define DMA_TCD3_SOFF *(volatile int16_t *)0x40009064 // TCD Signed Source Address Offset
+#define DMA_TCD3_ATTR *(volatile uint16_t *)0x40009066 // TCD Transfer Attributes
+#define DMA_TCD3_NBYTES_MLNO *(volatile uint32_t *)0x40009068 // TCD Minor Byte Count, Minor Loop Disabled
+#define DMA_TCD3_NBYTES_MLOFFNO *(volatile uint32_t *)0x40009068 // TCD Signed Minor Loop Offset, Minor Loop Enabled and Offset Disabled
+#define DMA_TCD3_NBYTES_MLOFFYES *(volatile uint32_t *)0x40009068 // TCD Signed Minor Loop Offset, Minor Loop and Offset Enabled
+#define DMA_TCD3_SLAST *(volatile int32_t *)0x4000906C // TCD Last Source Address Adjustment
+#define DMA_TCD3_DADDR *(volatile void * volatile *)0x40009070 // TCD Destination Address
+#define DMA_TCD3_DOFF *(volatile int16_t *)0x40009074 // TCD Signed Destination Address Offset
+#define DMA_TCD3_CITER_ELINKYES *(volatile uint16_t *)0x40009076 // TCD Current Minor Loop Link, Major Loop Count, Channel Linking Enabled
+#define DMA_TCD3_CITER_ELINKNO *(volatile uint16_t *)0x40009076 // ??
+#define DMA_TCD3_DLASTSGA *(volatile int32_t *)0x40009078 // TCD Last Destination Address Adjustment/Scatter Gather Address
+#define DMA_TCD3_CSR *(volatile uint16_t *)0x4000907C // TCD Control and Status
+#define DMA_TCD3_BITER_ELINKYES *(volatile uint16_t *)0x4000907E // TCD Beginning Minor Loop Link, Major Loop Count ,Channel Linking Enabled
+#define DMA_TCD3_BITER_ELINKNO *(volatile uint16_t *)0x4000907E // TCD Beginning Minor Loop Link, Major Loop Count ,Channel Linking Disabled
+
+#define DMA_TCD4_SADDR *(volatile const void * volatile *)0x40009080 // TCD Source Addr
+#define DMA_TCD4_SOFF *(volatile int16_t *)0x40009084 // TCD Signed Source Address Offset
+#define DMA_TCD4_ATTR *(volatile uint16_t *)0x40009086 // TCD Transfer Attributes
+#define DMA_TCD4_NBYTES_MLNO *(volatile uint32_t *)0x40009088 // TCD Minor Byte Count
+#define DMA_TCD4_NBYTES_MLOFFNO *(volatile uint32_t *)0x40009088 // TCD Signed Minor Loop Offset
+#define DMA_TCD4_NBYTES_MLOFFYES *(volatile uint32_t *)0x40009088 // TCD Signed Minor Loop Offset
+#define DMA_TCD4_SLAST *(volatile int32_t *)0x4000908C // TCD Last Source Addr Adj.
+#define DMA_TCD4_DADDR *(volatile void * volatile *)0x40009090 // TCD Destination Address
+#define DMA_TCD4_DOFF *(volatile int16_t *)0x40009094 // TCD Signed Dest Address Offset
+#define DMA_TCD4_CITER_ELINKYES *(volatile uint16_t *)0x40009096 // TCD Current Minor Loop Link
+#define DMA_TCD4_CITER_ELINKNO *(volatile uint16_t *)0x40009096 // ??
+#define DMA_TCD4_DLASTSGA *(volatile int32_t *)0x40009098 // TCD Last Destination Addr Adj
+#define DMA_TCD4_CSR *(volatile uint16_t *)0x4000909C // TCD Control and Status
+#define DMA_TCD4_BITER_ELINKYES *(volatile uint16_t *)0x4000909E // TCD Beginning Minor Loop Link
+#define DMA_TCD4_BITER_ELINKNO *(volatile uint16_t *)0x4000909E // TCD Beginning Minor Loop Link
+
+#define DMA_TCD5_SADDR *(volatile const void * volatile *)0x400090A0 // TCD Source Addr
+#define DMA_TCD5_SOFF *(volatile int16_t *)0x400090A4 // TCD Signed Source Address Offset
+#define DMA_TCD5_ATTR *(volatile uint16_t *)0x400090A6 // TCD Transfer Attributes
+#define DMA_TCD5_NBYTES_MLNO *(volatile uint32_t *)0x400090A8 // TCD Minor Byte Count
+#define DMA_TCD5_NBYTES_MLOFFNO *(volatile uint32_t *)0x400090A8 // TCD Signed Minor Loop Offset
+#define DMA_TCD5_NBYTES_MLOFFYES *(volatile uint32_t *)0x400090A8 // TCD Signed Minor Loop Offset
+#define DMA_TCD5_SLAST *(volatile int32_t *)0x400090AC // TCD Last Source Addr Adj.
+#define DMA_TCD5_DADDR *(volatile void * volatile *)0x400090B0 // TCD Destination Address
+#define DMA_TCD5_DOFF *(volatile int16_t *)0x400090B4 // TCD Signed Dest Address Offset
+#define DMA_TCD5_CITER_ELINKYES *(volatile uint16_t *)0x400090B6 // TCD Current Minor Loop Link
+#define DMA_TCD5_CITER_ELINKNO *(volatile uint16_t *)0x400090B6 // ??
+#define DMA_TCD5_DLASTSGA *(volatile int32_t *)0x400090B8 // TCD Last Destination Addr Adj
+#define DMA_TCD5_CSR *(volatile uint16_t *)0x400090BC // TCD Control and Status
+#define DMA_TCD5_BITER_ELINKYES *(volatile uint16_t *)0x400090BE // TCD Beginning Minor Loop Link
+#define DMA_TCD5_BITER_ELINKNO *(volatile uint16_t *)0x400090BE // TCD Beginning Minor Loop Link
+
+#define DMA_TCD6_SADDR *(volatile const void * volatile *)0x400090C0 // TCD Source Addr
+#define DMA_TCD6_SOFF *(volatile int16_t *)0x400090C4 // TCD Signed Source Address Offset
+#define DMA_TCD6_ATTR *(volatile uint16_t *)0x400090C6 // TCD Transfer Attributes
+#define DMA_TCD6_NBYTES_MLNO *(volatile uint32_t *)0x400090C8 // TCD Minor Byte Count
+#define DMA_TCD6_NBYTES_MLOFFNO *(volatile uint32_t *)0x400090C8 // TCD Signed Minor Loop Offset
+#define DMA_TCD6_NBYTES_MLOFFYES *(volatile uint32_t *)0x400090C8 // TCD Signed Minor Loop Offset
+#define DMA_TCD6_SLAST *(volatile int32_t *)0x400090CC // TCD Last Source Addr Adj.
+#define DMA_TCD6_DADDR *(volatile void * volatile *)0x400090D0 // TCD Destination Address
+#define DMA_TCD6_DOFF *(volatile int16_t *)0x400090D4 // TCD Signed Dest Address Offset
+#define DMA_TCD6_CITER_ELINKYES *(volatile uint16_t *)0x400090D6 // TCD Current Minor Loop Link
+#define DMA_TCD6_CITER_ELINKNO *(volatile uint16_t *)0x400090D6 // ??
+#define DMA_TCD6_DLASTSGA *(volatile int32_t *)0x400090D8 // TCD Last Destination Addr Adj
+#define DMA_TCD6_CSR *(volatile uint16_t *)0x400090DC // TCD Control and Status
+#define DMA_TCD6_BITER_ELINKYES *(volatile uint16_t *)0x400090DE // TCD Beginning Minor Loop Link
+#define DMA_TCD6_BITER_ELINKNO *(volatile uint16_t *)0x400090DE // TCD Beginning Minor Loop Link
+
+#define DMA_TCD7_SADDR *(volatile const void * volatile *)0x400090E0 // TCD Source Addr
+#define DMA_TCD7_SOFF *(volatile int16_t *)0x400090E4 // TCD Signed Source Address Offset
+#define DMA_TCD7_ATTR *(volatile uint16_t *)0x400090E6 // TCD Transfer Attributes
+#define DMA_TCD7_NBYTES_MLNO *(volatile uint32_t *)0x400090E8 // TCD Minor Byte Count
+#define DMA_TCD7_NBYTES_MLOFFNO *(volatile uint32_t *)0x400090E8 // TCD Signed Minor Loop Offset
+#define DMA_TCD7_NBYTES_MLOFFYES *(volatile uint32_t *)0x400090E8 // TCD Signed Minor Loop Offset
+#define DMA_TCD7_SLAST *(volatile int32_t *)0x400090EC // TCD Last Source Addr Adj.
+#define DMA_TCD7_DADDR *(volatile void * volatile *)0x400090F0 // TCD Destination Address
+#define DMA_TCD7_DOFF *(volatile int16_t *)0x400090F4 // TCD Signed Dest Address Offset
+#define DMA_TCD7_CITER_ELINKYES *(volatile uint16_t *)0x400090F6 // TCD Current Minor Loop Link
+#define DMA_TCD7_CITER_ELINKNO *(volatile uint16_t *)0x400090F6 // ??
+#define DMA_TCD7_DLASTSGA *(volatile int32_t *)0x400090F8 // TCD Last Destination Addr Adj
+#define DMA_TCD7_CSR *(volatile uint16_t *)0x400090FC // TCD Control and Status
+#define DMA_TCD7_BITER_ELINKYES *(volatile uint16_t *)0x400090FE // TCD Beginning Minor Loop Link
+#define DMA_TCD7_BITER_ELINKNO *(volatile uint16_t *)0x400090FE // TCD Beginning Minor Loop Link
+
+#define DMA_TCD8_SADDR *(volatile const void * volatile *)0x40009100 // TCD Source Addr
+#define DMA_TCD8_SOFF *(volatile int16_t *)0x40009104 // TCD Signed Source Address Offset
+#define DMA_TCD8_ATTR *(volatile uint16_t *)0x40009106 // TCD Transfer Attributes
+#define DMA_TCD8_NBYTES_MLNO *(volatile uint32_t *)0x40009108 // TCD Minor Byte Count
+#define DMA_TCD8_NBYTES_MLOFFNO *(volatile uint32_t *)0x40009108 // TCD Signed Minor Loop Offset
+#define DMA_TCD8_NBYTES_MLOFFYES *(volatile uint32_t *)0x40009108 // TCD Signed Minor Loop Offset
+#define DMA_TCD8_SLAST *(volatile int32_t *)0x4000910C // TCD Last Source Addr Adj.
+#define DMA_TCD8_DADDR *(volatile void * volatile *)0x40009110 // TCD Destination Address
+#define DMA_TCD8_DOFF *(volatile int16_t *)0x40009114 // TCD Signed Dest Address Offset
+#define DMA_TCD8_CITER_ELINKYES *(volatile uint16_t *)0x40009116 // TCD Current Minor Loop Link
+#define DMA_TCD8_CITER_ELINKNO *(volatile uint16_t *)0x40009116 // ??
+#define DMA_TCD8_DLASTSGA *(volatile int32_t *)0x40009118 // TCD Last Destination Addr Adj
+#define DMA_TCD8_CSR *(volatile uint16_t *)0x4000911C // TCD Control and Status
+#define DMA_TCD8_BITER_ELINKYES *(volatile uint16_t *)0x4000911E // TCD Beginning Minor Loop Link
+#define DMA_TCD8_BITER_ELINKNO *(volatile uint16_t *)0x4000911E // TCD Beginning Minor Loop Link
+
+#define DMA_TCD9_SADDR *(volatile const void * volatile *)0x40009120 // TCD Source Addr
+#define DMA_TCD9_SOFF *(volatile int16_t *)0x40009124 // TCD Signed Source Address Offset
+#define DMA_TCD9_ATTR *(volatile uint16_t *)0x40009126 // TCD Transfer Attributes
+#define DMA_TCD9_NBYTES_MLNO *(volatile uint32_t *)0x40009128 // TCD Minor Byte Count
+#define DMA_TCD9_NBYTES_MLOFFNO *(volatile uint32_t *)0x40009128 // TCD Signed Minor Loop Offset
+#define DMA_TCD9_NBYTES_MLOFFYES *(volatile uint32_t *)0x40009128 // TCD Signed Minor Loop Offset
+#define DMA_TCD9_SLAST *(volatile int32_t *)0x4000912C // TCD Last Source Addr Adj.
+#define DMA_TCD9_DADDR *(volatile void * volatile *)0x40009130 // TCD Destination Address
+#define DMA_TCD9_DOFF *(volatile int16_t *)0x40009134 // TCD Signed Dest Address Offset
+#define DMA_TCD9_CITER_ELINKYES *(volatile uint16_t *)0x40009136 // TCD Current Minor Loop Link
+#define DMA_TCD9_CITER_ELINKNO *(volatile uint16_t *)0x40009136 // ??
+#define DMA_TCD9_DLASTSGA *(volatile int32_t *)0x40009138 // TCD Last Destination Addr Adj
+#define DMA_TCD9_CSR *(volatile uint16_t *)0x4000913C // TCD Control and Status
+#define DMA_TCD9_BITER_ELINKYES *(volatile uint16_t *)0x4000913E // TCD Beginning Minor Loop Link
+#define DMA_TCD9_BITER_ELINKNO *(volatile uint16_t *)0x4000913E // TCD Beginning Minor Loop Link
+
+#define DMA_TCD10_SADDR *(volatile const void * volatile *)0x40009140 // TCD Source Addr
+#define DMA_TCD10_SOFF *(volatile int16_t *)0x40009144 // TCD Signed Source Address Offset
+#define DMA_TCD10_ATTR *(volatile uint16_t *)0x40009146 // TCD Transfer Attributes
+#define DMA_TCD10_NBYTES_MLNO *(volatile uint32_t *)0x40009148 // TCD Minor Byte Count
+#define DMA_TCD10_NBYTES_MLOFFNO *(volatile uint32_t *)0x40009148 // TCD Signed Minor Loop Offset
+#define DMA_TCD10_NBYTES_MLOFFYES *(volatile uint32_t *)0x40009148 // TCD Signed Minor Loop Offset
+#define DMA_TCD10_SLAST *(volatile int32_t *)0x4000914C // TCD Last Source Addr Adj.
+#define DMA_TCD10_DADDR *(volatile void * volatile *)0x40009150 // TCD Destination Address
+#define DMA_TCD10_DOFF *(volatile int16_t *)0x40009154 // TCD Signed Dest Address Offset
+#define DMA_TCD10_CITER_ELINKYES *(volatile uint16_t *)0x40009156 // TCD Current Minor Loop Link
+#define DMA_TCD10_CITER_ELINKNO *(volatile uint16_t *)0x40009156 // ??
+#define DMA_TCD10_DLASTSGA *(volatile int32_t *)0x40009158 // TCD Last Destination Addr Adj
+#define DMA_TCD10_CSR *(volatile uint16_t *)0x4000915C // TCD Control and Status
+#define DMA_TCD10_BITER_ELINKYES *(volatile uint16_t *)0x4000915E // TCD Beginning Minor Loop Link
+#define DMA_TCD10_BITER_ELINKNO *(volatile uint16_t *)0x4000915E // TCD Beginning Minor Loop Link
+
+#define DMA_TCD11_SADDR *(volatile const void * volatile *)0x40009160 // TCD Source Addr
+#define DMA_TCD11_SOFF *(volatile int16_t *)0x40009164 // TCD Signed Source Address Offset
+#define DMA_TCD11_ATTR *(volatile uint16_t *)0x40009166 // TCD Transfer Attributes
+#define DMA_TCD11_NBYTES_MLNO *(volatile uint32_t *)0x40009168 // TCD Minor Byte Count
+#define DMA_TCD11_NBYTES_MLOFFNO *(volatile uint32_t *)0x40009168 // TCD Signed Minor Loop Offset
+#define DMA_TCD11_NBYTES_MLOFFYES *(volatile uint32_t *)0x40009168 // TCD Signed Minor Loop Offset
+#define DMA_TCD11_SLAST *(volatile int32_t *)0x4000916C // TCD Last Source Addr Adj.
+#define DMA_TCD11_DADDR *(volatile void * volatile *)0x40009170 // TCD Destination Address
+#define DMA_TCD11_DOFF *(volatile int16_t *)0x40009174 // TCD Signed Dest Address Offset
+#define DMA_TCD11_CITER_ELINKYES *(volatile uint16_t *)0x40009176 // TCD Current Minor Loop Link
+#define DMA_TCD11_CITER_ELINKNO *(volatile uint16_t *)0x40009176 // ??
+#define DMA_TCD11_DLASTSGA *(volatile int32_t *)0x40009178 // TCD Last Destination Addr Adj
+#define DMA_TCD11_CSR *(volatile uint16_t *)0x4000917C // TCD Control and Status
+#define DMA_TCD11_BITER_ELINKYES *(volatile uint16_t *)0x4000917E // TCD Beginning Minor Loop Link
+#define DMA_TCD11_BITER_ELINKNO *(volatile uint16_t *)0x4000917E // TCD Beginning Minor Loop Link
+
+#define DMA_TCD12_SADDR *(volatile const void * volatile *)0x40009180 // TCD Source Addr
+#define DMA_TCD12_SOFF *(volatile int16_t *)0x40009184 // TCD Signed Source Address Offset
+#define DMA_TCD12_ATTR *(volatile uint16_t *)0x40009186 // TCD Transfer Attributes
+#define DMA_TCD12_NBYTES_MLNO *(volatile uint32_t *)0x40009188 // TCD Minor Byte Count
+#define DMA_TCD12_NBYTES_MLOFFNO *(volatile uint32_t *)0x40009188 // TCD Signed Minor Loop Offset
+#define DMA_TCD12_NBYTES_MLOFFYES *(volatile uint32_t *)0x40009188 // TCD Signed Minor Loop Offset
+#define DMA_TCD12_SLAST *(volatile int32_t *)0x4000918C // TCD Last Source Addr Adj.
+#define DMA_TCD12_DADDR *(volatile void * volatile *)0x40009190 // TCD Destination Address
+#define DMA_TCD12_DOFF *(volatile int16_t *)0x40009194 // TCD Signed Dest Address Offset
+#define DMA_TCD12_CITER_ELINKYES *(volatile uint16_t *)0x40009196 // TCD Current Minor Loop Link
+#define DMA_TCD12_CITER_ELINKNO *(volatile uint16_t *)0x40009196 // ??
+#define DMA_TCD12_DLASTSGA *(volatile int32_t *)0x40009198 // TCD Last Destination Addr Adj
+#define DMA_TCD12_CSR *(volatile uint16_t *)0x4000919C // TCD Control and Status
+#define DMA_TCD12_BITER_ELINKYES *(volatile uint16_t *)0x4000919E // TCD Beginning Minor Loop Link
+#define DMA_TCD12_BITER_ELINKNO *(volatile uint16_t *)0x4000919E // TCD Beginning Minor Loop Link
+
+#define DMA_TCD13_SADDR *(volatile const void * volatile *)0x400091A0 // TCD Source Addr
+#define DMA_TCD13_SOFF *(volatile int16_t *)0x400091A4 // TCD Signed Source Address Offset
+#define DMA_TCD13_ATTR *(volatile uint16_t *)0x400091A6 // TCD Transfer Attributes
+#define DMA_TCD13_NBYTES_MLNO *(volatile uint32_t *)0x400091A8 // TCD Minor Byte Count
+#define DMA_TCD13_NBYTES_MLOFFNO *(volatile uint32_t *)0x400091A8 // TCD Signed Minor Loop Offset
+#define DMA_TCD13_NBYTES_MLOFFYES *(volatile uint32_t *)0x400091A8 // TCD Signed Minor Loop Offset
+#define DMA_TCD13_SLAST *(volatile int32_t *)0x400091AC // TCD Last Source Addr Adj.
+#define DMA_TCD13_DADDR *(volatile void * volatile *)0x400091B0 // TCD Destination Address
+#define DMA_TCD13_DOFF *(volatile int16_t *)0x400091B4 // TCD Signed Dest Address Offset
+#define DMA_TCD13_CITER_ELINKYES *(volatile uint16_t *)0x400091B6 // TCD Current Minor Loop Link
+#define DMA_TCD13_CITER_ELINKNO *(volatile uint16_t *)0x400091B6 // ??
+#define DMA_TCD13_DLASTSGA *(volatile int32_t *)0x400091B8 // TCD Last Destination Addr Adj
+#define DMA_TCD13_CSR *(volatile uint16_t *)0x400091BC // TCD Control and Status
+#define DMA_TCD13_BITER_ELINKYES *(volatile uint16_t *)0x400091BE // TCD Beginning Minor Loop Link
+#define DMA_TCD13_BITER_ELINKNO *(volatile uint16_t *)0x400091BE // TCD Beginning Minor Loop Link
+
+#define DMA_TCD14_SADDR *(volatile const void * volatile *)0x400091C0 // TCD Source Addr
+#define DMA_TCD14_SOFF *(volatile int16_t *)0x400091C4 // TCD Signed Source Address Offset
+#define DMA_TCD14_ATTR *(volatile uint16_t *)0x400091C6 // TCD Transfer Attributes
+#define DMA_TCD14_NBYTES_MLNO *(volatile uint32_t *)0x400091C8 // TCD Minor Byte Count
+#define DMA_TCD14_NBYTES_MLOFFNO *(volatile uint32_t *)0x400091C8 // TCD Signed Minor Loop Offset
+#define DMA_TCD14_NBYTES_MLOFFYES *(volatile uint32_t *)0x400091C8 // TCD Signed Minor Loop Offset
+#define DMA_TCD14_SLAST *(volatile int32_t *)0x400091CC // TCD Last Source Addr Adj.
+#define DMA_TCD14_DADDR *(volatile void * volatile *)0x400091D0 // TCD Destination Address
+#define DMA_TCD14_DOFF *(volatile int16_t *)0x400091D4 // TCD Signed Dest Address Offset
+#define DMA_TCD14_CITER_ELINKYES *(volatile uint16_t *)0x400091D6 // TCD Current Minor Loop Link
+#define DMA_TCD14_CITER_ELINKNO *(volatile uint16_t *)0x400091D6 // ??
+#define DMA_TCD14_DLASTSGA *(volatile int32_t *)0x400091D8 // TCD Last Destination Addr Adj
+#define DMA_TCD14_CSR *(volatile uint16_t *)0x400091DC // TCD Control and Status
+#define DMA_TCD14_BITER_ELINKYES *(volatile uint16_t *)0x400091DE // TCD Beginning Minor Loop Link
+#define DMA_TCD14_BITER_ELINKNO *(volatile uint16_t *)0x400091DE // TCD Beginning Minor Loop Link
+
+#define DMA_TCD15_SADDR *(volatile const void * volatile *)0x400091E0 // TCD Source Addr
+#define DMA_TCD15_SOFF *(volatile int16_t *)0x400091E4 // TCD Signed Source Address Offset
+#define DMA_TCD15_ATTR *(volatile uint16_t *)0x400091E6 // TCD Transfer Attributes
+#define DMA_TCD15_NBYTES_MLNO *(volatile uint32_t *)0x400091E8 // TCD Minor Byte Count
+#define DMA_TCD15_NBYTES_MLOFFNO *(volatile uint32_t *)0x400091E8 // TCD Signed Minor Loop Offset
+#define DMA_TCD15_NBYTES_MLOFFYES *(volatile uint32_t *)0x400091E8 // TCD Signed Minor Loop Offset
+#define DMA_TCD15_SLAST *(volatile int32_t *)0x400091EC // TCD Last Source Addr Adj.
+#define DMA_TCD15_DADDR *(volatile void * volatile *)0x400091F0 // TCD Destination Address
+#define DMA_TCD15_DOFF *(volatile int16_t *)0x400091F4 // TCD Signed Dest Address Offset
+#define DMA_TCD15_CITER_ELINKYES *(volatile uint16_t *)0x400091F6 // TCD Current Minor Loop Link
+#define DMA_TCD15_CITER_ELINKNO *(volatile uint16_t *)0x400091F6 // ??
+#define DMA_TCD15_DLASTSGA *(volatile int32_t *)0x400091F8 // TCD Last Destination Addr Adj
+#define DMA_TCD15_CSR *(volatile uint16_t *)0x400091FC // TCD Control and Status
+#define DMA_TCD15_BITER_ELINKYES *(volatile uint16_t *)0x400091FE // TCD Beginning Minor Loop Link
+#define DMA_TCD15_BITER_ELINKNO *(volatile uint16_t *)0x400091FE // TCD Beginning Minor Loop Link
+
+
+// Chapter 22: External Watchdog Monitor (EWM)
+#define EWM_CTRL *(volatile uint8_t *)0x40061000 // Control Register
+#define EWM_SERV *(volatile uint8_t *)0x40061001 // Service Register
+#define EWM_CMPL *(volatile uint8_t *)0x40061002 // Compare Low Register
+#define EWM_CMPH *(volatile uint8_t *)0x40061003 // Compare High Register
+
+// Chapter 23: Watchdog Timer (WDOG)
+#define WDOG_STCTRLH *(volatile uint16_t *)0x40052000 // Watchdog Status and Control Register High
+#define WDOG_STCTRLH_DISTESTWDOG (uint16_t)0x4000 // Allows the WDOG's functional test mode to be disabled permanently.
+#define WDOG_STCTRLH_BYTESEL(n) (uint16_t)(((n) & 3) << 12) // selects the byte to be tested when the watchdog is in the byte test mode.
+#define WDOG_STCTRLH_TESTSEL (uint16_t)0x0800
+#define WDOG_STCTRLH_TESTWDOG (uint16_t)0x0400
+#define WDOG_STCTRLH_WAITEN (uint16_t)0x0080
+#define WDOG_STCTRLH_STOPEN (uint16_t)0x0040
+#define WDOG_STCTRLH_DBGEN (uint16_t)0x0020
+#define WDOG_STCTRLH_ALLOWUPDATE (uint16_t)0x0010
+#define WDOG_STCTRLH_WINEN (uint16_t)0x0008
+#define WDOG_STCTRLH_IRQRSTEN (uint16_t)0x0004
+#define WDOG_STCTRLH_CLKSRC (uint16_t)0x0002
+#define WDOG_STCTRLH_WDOGEN (uint16_t)0x0001
+#define WDOG_STCTRLL *(volatile uint16_t *)0x40052002 // Watchdog Status and Control Register Low
+#define WDOG_TOVALH *(volatile uint16_t *)0x40052004 // Watchdog Time-out Value Register High
+#define WDOG_TOVALL *(volatile uint16_t *)0x40052006 // Watchdog Time-out Value Register Low
+#define WDOG_WINH *(volatile uint16_t *)0x40052008 // Watchdog Window Register High
+#define WDOG_WINL *(volatile uint16_t *)0x4005200A // Watchdog Window Register Low
+#define WDOG_REFRESH *(volatile uint16_t *)0x4005200C // Watchdog Refresh register
+#define WDOG_UNLOCK *(volatile uint16_t *)0x4005200E // Watchdog Unlock register
+#define WDOG_UNLOCK_SEQ1 (uint16_t)0xC520
+#define WDOG_UNLOCK_SEQ2 (uint16_t)0xD928
+#define WDOG_TMROUTH *(volatile uint16_t *)0x40052010 // Watchdog Timer Output Register High
+#define WDOG_TMROUTL *(volatile uint16_t *)0x40052012 // Watchdog Timer Output Register Low
+#define WDOG_RSTCNT *(volatile uint16_t *)0x40052014 // Watchdog Reset Count register
+#define WDOG_PRESC *(volatile uint16_t *)0x40052016 // Watchdog Prescaler register
+
+// Chapter 24: Multipurpose Clock Generator (MCG)
+#define MCG_C1 *(volatile uint8_t *)0x40064000 // MCG Control 1 Register
+#define MCG_C1_IREFSTEN (uint8_t)0x01 // Internal Reference Stop Enable, Controls whether or not the internal reference clock remains enabled when the MCG enters Stop mode.
+#define MCG_C1_IRCLKEN (uint8_t)0x02 // Internal Reference Clock Enable, Enables the internal reference clock for use as MCGIRCLK.
+#define MCG_C1_IREFS (uint8_t)0x04 // Internal Reference Select, Selects the reference clock source for the FLL.
+#define MCG_C1_FRDIV(n) (uint8_t)(((n) & 0x07) << 3) // FLL External Reference Divider, Selects the amount to divide down the external reference clock for the FLL
+#define MCG_C1_CLKS(n) (uint8_t)(((n) & 0x03) << 6) // Clock Source Select, Selects the clock source for MCGOUTCLK
+#define MCG_C2 *(volatile uint8_t *)0x40064001 // MCG Control 2 Register
+#define MCG_C2_IRCS (uint8_t)0x01 // Internal Reference Clock Select, Selects between the fast or slow internal reference clock source.
+#define MCG_C2_LP (uint8_t)0x02 // Low Power Select, Controls whether the FLL or PLL is disabled in BLPI and BLPE modes.
+#define MCG_C2_EREFS (uint8_t)0x04 // External Reference Select, Selects the source for the external reference clock.
+#define MCG_C2_HGO0 (uint8_t)0x08 // High Gain Oscillator Select, Controls the crystal oscillator mode of operation
+#define MCG_C2_RANGE0(n) (uint8_t)(((n) & 0x03) << 4) // Frequency Range Select, Selects the frequency range for the crystal oscillator
+#define MCG_C2_LOCRE0 (uint8_t)0x80 // Loss of Clock Reset Enable, Determines whether an interrupt or a reset request is made following a loss of OSC0
+#define MCG_C3 *(volatile uint8_t *)0x40064002 // MCG Control 3 Register
+#define MCG_C3_SCTRIM(n) (uint8_t)(n) // Slow Internal Reference Clock Trim Setting
+#define MCG_C4 *(volatile uint8_t *)0x40064003 // MCG Control 4 Register
+#define MCG_C4_SCFTRIM (uint8_t)0x01 // Slow Internal Reference Clock Fine Trim
+#define MCG_C4_FCTRIM(n) (uint8_t)(((n) & 0x0F) << 1) // Fast Internal Reference Clock Trim Setting
+#define MCG_C4_DRST_DRS(n) (uint8_t)(((n) & 0x03) << 5) // DCO Range Select
+#define MCG_C4_DMX32 (uint8_t)0x80 // DCO Maximum Frequency with 32.768 kHz Reference, controls whether the DCO frequency range is narrowed
+#define MCG_C5 *(volatile uint8_t *)0x40064004 // MCG Control 5 Register
+#define MCG_C5_PRDIV0(n) (uint8_t)((n) & 0x1F) // PLL External Reference Divider
+#define MCG_C5_PLLSTEN0 (uint8_t)0x20 // PLL Stop Enable
+#define MCG_C5_PLLCLKEN0 (uint8_t)0x40 // PLL Clock Enable
+#define MCG_C6 *(volatile uint8_t *)0x40064005 // MCG Control 6 Register
+#define MCG_C6_VDIV0(n) (uint8_t)((n) & 0x1F) // VCO 0 Divider
+#define MCG_C6_CME0 (uint8_t)0x20 // Clock Monitor Enable
+#define MCG_C6_PLLS (uint8_t)0x40 // PLL Select, Controls whether the PLL or FLL output is selected as the MCG source when CLKS[1:0]=00.
+#define MCG_C6_LOLIE0 (uint8_t)0x80 // Loss of Lock Interrrupt Enable
+#define MCG_S *(volatile uint8_t *)0x40064006 // MCG Status Register
+#define MCG_S_IRCST (uint8_t)0x01 // Internal Reference Clock Status
+#define MCG_S_OSCINIT0 (uint8_t)0x02 // OSC Initialization, resets to 0, is set to 1 after the initialization cycles of the crystal oscillator
+#define MCG_S_CLKST(n) (uint8_t)(((n) & 0x03) << 2) // Clock Mode Status, 0=FLL is selected, 1= Internal ref, 2=External ref, 3=PLL
+#define MCG_S_CLKST_MASK (uint8_t)0x0C
+#define MCG_S_IREFST (uint8_t)0x10 // Internal Reference Status
+#define MCG_S_PLLST (uint8_t)0x20 // PLL Select Status
+#define MCG_S_LOCK0 (uint8_t)0x40 // Lock Status, 0=PLL Unlocked, 1=PLL Locked
+#define MCG_S_LOLS0 (uint8_t)0x80 // Loss of Lock Status
+#define MCG_SC *(volatile uint8_t *)0x40064008 // MCG Status and Control Register
+#define MCG_SC_LOCS0 (uint8_t)0x01 // OSC0 Loss of Clock Status
+#define MCG_SC_FCRDIV(n) (uint8_t)(((n) & 0x07) << 1) // Fast Clock Internal Reference Divider
+#define MCG_SC_FLTPRSRV (uint8_t)0x10 // FLL Filter Preserve Enable
+#define MCG_SC_ATMF (uint8_t)0x20 // Automatic Trim Machine Fail Flag
+#define MCG_SC_ATMS (uint8_t)0x40 // Automatic Trim Machine Select
+#define MCG_SC_ATME (uint8_t)0x80 // Automatic Trim Machine Enable
+#define MCG_ATCVH *(volatile uint8_t *)0x4006400A // MCG Auto Trim Compare Value High Register
+#define MCG_ATCVL *(volatile uint8_t *)0x4006400B // MCG Auto Trim Compare Value Low Register
+#define MCG_C7 *(volatile uint8_t *)0x4006400C // MCG Control 7 Register
+#define MCG_C8 *(volatile uint8_t *)0x4006400D // MCG Control 8 Register
+
+// Chapter 25: Oscillator (OSC)
+#define OSC0_CR *(volatile uint8_t *)0x40065000 // OSC Control Register
+#define OSC_SC16P (uint8_t)0x01 // Oscillator 16 pF Capacitor Load Configure
+#define OSC_SC8P (uint8_t)0x02 // Oscillator 8 pF Capacitor Load Configure
+#define OSC_SC4P (uint8_t)0x04 // Oscillator 4 pF Capacitor Load Configure
+#define OSC_SC2P (uint8_t)0x08 // Oscillator 2 pF Capacitor Load Configure
+#define OSC_EREFSTEN (uint8_t)0x20 // External Reference Stop Enable, Controls whether or not the external reference clock (OSCERCLK) remains enabled when MCU enters Stop mode.
+#define OSC_ERCLKEN (uint8_t)0x80 // External Reference Enable, Enables external reference clock (OSCERCLK).
+
+// Chapter 27: Flash Memory Controller (FMC)
+#define FMC_PFAPR *(volatile uint32_t *)0x4001F000 // Flash Access Protection
+#define FMC_PFB0CR *(volatile uint32_t *)0x4001F004 // Flash Control
+#define FMC_TAGVDW0S0 *(volatile uint32_t *)0x4001F100 // Cache Tag Storage
+#define FMC_TAGVDW0S1 *(volatile uint32_t *)0x4001F104 // Cache Tag Storage
+#define FMC_TAGVDW1S0 *(volatile uint32_t *)0x4001F108 // Cache Tag Storage
+#define FMC_TAGVDW1S1 *(volatile uint32_t *)0x4001F10C // Cache Tag Storage
+#define FMC_TAGVDW2S0 *(volatile uint32_t *)0x4001F110 // Cache Tag Storage
+#define FMC_TAGVDW2S1 *(volatile uint32_t *)0x4001F114 // Cache Tag Storage
+#define FMC_TAGVDW3S0 *(volatile uint32_t *)0x4001F118 // Cache Tag Storage
+#define FMC_TAGVDW3S1 *(volatile uint32_t *)0x4001F11C // Cache Tag Storage
+#define FMC_DATAW0S0 *(volatile uint32_t *)0x4001F200 // Cache Data Storage
+#define FMC_DATAW0S1 *(volatile uint32_t *)0x4001F204 // Cache Data Storage
+#define FMC_DATAW1S0 *(volatile uint32_t *)0x4001F208 // Cache Data Storage
+#define FMC_DATAW1S1 *(volatile uint32_t *)0x4001F20C // Cache Data Storage
+#define FMC_DATAW2S0 *(volatile uint32_t *)0x4001F210 // Cache Data Storage
+#define FMC_DATAW2S1 *(volatile uint32_t *)0x4001F214 // Cache Data Storage
+#define FMC_DATAW3S0 *(volatile uint32_t *)0x4001F218 // Cache Data Storage
+#define FMC_DATAW3S1 *(volatile uint32_t *)0x4001F21C // Cache Data Storage
+
+// Chapter 28: Flash Memory Module (FTFL)
+#define FTFL_FSTAT *(volatile uint8_t *)0x40020000 // Flash Status Register
+#define FTFL_FSTAT_CCIF (uint8_t)0x80 // Command Complete Interrupt Flag
+#define FTFL_FSTAT_RDCOLERR (uint8_t)0x40 // Flash Read Collision Error Flag
+#define FTFL_FSTAT_ACCERR (uint8_t)0x20 // Flash Access Error Flag
+#define FTFL_FSTAT_FPVIOL (uint8_t)0x10 // Flash Protection Violation Flag
+#define FTFL_FSTAT_MGSTAT0 (uint8_t)0x01 // Memory Controller Command Completion Status Flag
+#define FTFL_FCNFG *(volatile uint8_t *)0x40020001 // Flash Configuration Register
+#define FTFL_FCNFG_CCIE (uint8_t)0x80 // Command Complete Interrupt Enable
+#define FTFL_FCNFG_RDCOLLIE (uint8_t)0x40 // Read Collision Error Interrupt Enable
+#define FTFL_FCNFG_ERSAREQ (uint8_t)0x20 // Erase All Request
+#define FTFL_FCNFG_ERSSUSP (uint8_t)0x10 // Erase Suspend
+#define FTFL_FCNFG_PFLSH (uint8_t)0x04 // Flash memory configuration
+#define FTFL_FCNFG_RAMRDY (uint8_t)0x02 // RAM Ready
+#define FTFL_FCNFG_EEERDY (uint8_t)0x01 // EEPROM Ready
+#define FTFL_FSEC *(const uint8_t *)0x40020002 // Flash Security Register
+#define FTFL_FOPT *(const uint8_t *)0x40020003 // Flash Option Register
+#define FTFL_FCCOB3 *(volatile uint8_t *)0x40020004 // Flash Common Command Object Registers
+#define FTFL_FCCOB2 *(volatile uint8_t *)0x40020005
+#define FTFL_FCCOB1 *(volatile uint8_t *)0x40020006
+#define FTFL_FCCOB0 *(volatile uint8_t *)0x40020007
+#define FTFL_FCCOB7 *(volatile uint8_t *)0x40020008
+#define FTFL_FCCOB6 *(volatile uint8_t *)0x40020009
+#define FTFL_FCCOB5 *(volatile uint8_t *)0x4002000A
+#define FTFL_FCCOB4 *(volatile uint8_t *)0x4002000B
+#define FTFL_FCCOBB *(volatile uint8_t *)0x4002000C
+#define FTFL_FCCOBA *(volatile uint8_t *)0x4002000D
+#define FTFL_FCCOB9 *(volatile uint8_t *)0x4002000E
+#define FTFL_FCCOB8 *(volatile uint8_t *)0x4002000F
+#define FTFL_FPROT3 *(volatile uint8_t *)0x40020010 // Program Flash Protection Registers
+#define FTFL_FPROT2 *(volatile uint8_t *)0x40020011 // Program Flash Protection Registers
+#define FTFL_FPROT1 *(volatile uint8_t *)0x40020012 // Program Flash Protection Registers
+#define FTFL_FPROT0 *(volatile uint8_t *)0x40020013 // Program Flash Protection Registers
+#define FTFL_FEPROT *(volatile uint8_t *)0x40020016 // EEPROM Protection Register
+#define FTFL_FDPROT *(volatile uint8_t *)0x40020017 // Data Flash Protection Register
+
+// Chapter 30: Cyclic Redundancy Check (CRC)
+#define CRC_CRC *(volatile uint32_t *)0x40032000 // CRC Data register
+#define CRC_GPOLY *(volatile uint32_t *)0x40032004 // CRC Polynomial register
+#define CRC_CTRL *(volatile uint32_t *)0x40032008 // CRC Control register
+
+// Chapter 31: Analog-to-Digital Converter (ADC)
+#define ADC0_SC1A *(volatile uint32_t *)0x4003B000 // ADC status and control registers 1
+#define ADC0_SC1B *(volatile uint32_t *)0x4003B004 // ADC status and control registers 1
+#define ADC_SC1_COCO (uint32_t)0x80 // Conversion complete flag
+#define ADC_SC1_AIEN (uint32_t)0x40 // Interrupt enable
+#define ADC_SC1_DIFF (uint32_t)0x20 // Differential mode enable
+#define ADC_SC1_ADCH(n) (uint32_t)((n) & 0x1F) // Input channel select
+#define ADC0_CFG1 *(volatile uint32_t *)0x4003B008 // ADC configuration register 1
+#define ADC_CFG1_ADLPC (uint32_t)0x80 // Low-power configuration
+#define ADC_CFG1_ADIV(n) (uint32_t)(((n) & 3) << 5) // Clock divide select, 0=direct, 1=div2, 2=div4, 3=div8
+#define ADC_CFG1_ADLSMP (uint32_t)0x10 // Sample time configuration, 0=Short, 1=Long
+#define ADC_CFG1_MODE(n) (uint32_t)(((n) & 3) << 2) // Conversion mode, 0=8 bit, 1=12 bit, 2=10 bit, 3=16 bit
+#define ADC_CFG1_ADICLK(n) (uint32_t)(((n) & 3) << 0) // Input clock, 0=bus, 1=bus/2, 2=OSCERCLK, 3=async
+#define ADC0_CFG2 *(volatile uint32_t *)0x4003B00C // Configuration register 2
+#define ADC_CFG2_MUXSEL (uint32_t)0x10 // 0=a channels, 1=b channels
+#define ADC_CFG2_ADACKEN (uint32_t)0x08 // async clock enable
+#define ADC_CFG2_ADHSC (uint32_t)0x04 // High speed configuration
+#define ADC_CFG2_ADLSTS(n) (uint32_t)(((n) & 3) << 0) // Sample time, 0=24 cycles, 1=12 cycles, 2=6 cycles, 3=2 cycles
+#define ADC0_RA *(volatile uint32_t *)0x4003B010 // ADC data result register
+#define ADC0_RB *(volatile uint32_t *)0x4003B014 // ADC data result register
+#define ADC0_CV1 *(volatile uint32_t *)0x4003B018 // Compare value registers
+#define ADC0_CV2 *(volatile uint32_t *)0x4003B01C // Compare value registers
+#define ADC0_SC2 *(volatile uint32_t *)0x4003B020 // Status and control register 2
+#define ADC_SC2_ADACT (uint32_t)0x80 // Conversion active
+#define ADC_SC2_ADTRG (uint32_t)0x40 // Conversion trigger select, 0=software, 1=hardware
+#define ADC_SC2_ACFE (uint32_t)0x20 // Compare function enable
+#define ADC_SC2_ACFGT (uint32_t)0x10 // Compare function greater than enable
+#define ADC_SC2_ACREN (uint32_t)0x08 // Compare function range enable
+#define ADC_SC2_DMAEN (uint32_t)0x04 // DMA enable
+#define ADC_SC2_REFSEL(n) (uint32_t)(((n) & 3) << 0) // Voltage reference, 0=vcc/external, 1=1.2 volts
+#define ADC0_SC3 *(volatile uint32_t *)0x4003B024 // Status and control register 3
+#define ADC_SC3_CAL (uint32_t)0x80 // Calibration, 1=begin, stays set while cal in progress
+#define ADC_SC3_CALF (uint32_t)0x40 // Calibration failed flag
+#define ADC_SC3_ADCO (uint32_t)0x08 // Continuous conversion enable
+#define ADC_SC3_AVGE (uint32_t)0x04 // Hardware average enable
+#define ADC_SC3_AVGS(n) (uint32_t)(((n) & 3) << 0) // avg select, 0=4 samples, 1=8 samples, 2=16 samples, 3=32 samples
+#define ADC0_OFS *(volatile uint32_t *)0x4003B028 // ADC offset correction register
+#define ADC0_PG *(volatile uint32_t *)0x4003B02C // ADC plus-side gain register
+#define ADC0_MG *(volatile uint32_t *)0x4003B030 // ADC minus-side gain register
+#define ADC0_CLPD *(volatile uint32_t *)0x4003B034 // ADC plus-side general calibration value register
+#define ADC0_CLPS *(volatile uint32_t *)0x4003B038 // ADC plus-side general calibration value register
+#define ADC0_CLP4 *(volatile uint32_t *)0x4003B03C // ADC plus-side general calibration value register
+#define ADC0_CLP3 *(volatile uint32_t *)0x4003B040 // ADC plus-side general calibration value register
+#define ADC0_CLP2 *(volatile uint32_t *)0x4003B044 // ADC plus-side general calibration value register
+#define ADC0_CLP1 *(volatile uint32_t *)0x4003B048 // ADC plus-side general calibration value register
+#define ADC0_CLP0 *(volatile uint32_t *)0x4003B04C // ADC plus-side general calibration value register
+#define ADC0_PGA *(volatile uint32_t *)0x4003B050 // ADC Programmable Gain Amplifier
+#define ADC_PGA_PGAEN (uint32_t)0x00800000 // Enable
+#define ADC_PGA_PGALPB (uint32_t)0x00100000 // Low-Power Mode Control, 0=low power, 1=normal
+#define ADC_PGA_PGAG(n) (uint32_t)(((n) & 15) << 16) // Gain, 0=1X, 1=2X, 2=4X, 3=8X, 4=16X, 5=32X, 6=64X
+#define ADC0_CLMD *(volatile uint32_t *)0x4003B054 // ADC minus-side general calibration value register
+#define ADC0_CLMS *(volatile uint32_t *)0x4003B058 // ADC minus-side general calibration value register
+#define ADC0_CLM4 *(volatile uint32_t *)0x4003B05C // ADC minus-side general calibration value register
+#define ADC0_CLM3 *(volatile uint32_t *)0x4003B060 // ADC minus-side general calibration value register
+#define ADC0_CLM2 *(volatile uint32_t *)0x4003B064 // ADC minus-side general calibration value register
+#define ADC0_CLM1 *(volatile uint32_t *)0x4003B068 // ADC minus-side general calibration value register
+#define ADC0_CLM0 *(volatile uint32_t *)0x4003B06C // ADC minus-side general calibration value register
+
+#define ADC1_SC1A *(volatile uint32_t *)0x400BB000 // ADC status and control registers 1
+#define ADC1_SC1B *(volatile uint32_t *)0x400BB004 // ADC status and control registers 1
+#define ADC1_CFG1 *(volatile uint32_t *)0x400BB008 // ADC configuration register 1
+#define ADC1_CFG2 *(volatile uint32_t *)0x400BB00C // Configuration register 2
+#define ADC1_RA *(volatile uint32_t *)0x400BB010 // ADC data result register
+#define ADC1_RB *(volatile uint32_t *)0x400BB014 // ADC data result register
+#define ADC1_CV1 *(volatile uint32_t *)0x400BB018 // Compare value registers
+#define ADC1_CV2 *(volatile uint32_t *)0x400BB01C // Compare value registers
+#define ADC1_SC2 *(volatile uint32_t *)0x400BB020 // Status and control register 2
+#define ADC1_SC3 *(volatile uint32_t *)0x400BB024 // Status and control register 3
+#define ADC1_OFS *(volatile uint32_t *)0x400BB028 // ADC offset correction register
+#define ADC1_PG *(volatile uint32_t *)0x400BB02C // ADC plus-side gain register
+#define ADC1_MG *(volatile uint32_t *)0x400BB030 // ADC minus-side gain register
+#define ADC1_CLPD *(volatile uint32_t *)0x400BB034 // ADC plus-side general calibration value register
+#define ADC1_CLPS *(volatile uint32_t *)0x400BB038 // ADC plus-side general calibration value register
+#define ADC1_CLP4 *(volatile uint32_t *)0x400BB03C // ADC plus-side general calibration value register
+#define ADC1_CLP3 *(volatile uint32_t *)0x400BB040 // ADC plus-side general calibration value register
+#define ADC1_CLP2 *(volatile uint32_t *)0x400BB044 // ADC plus-side general calibration value register
+#define ADC1_CLP1 *(volatile uint32_t *)0x400BB048 // ADC plus-side general calibration value register
+#define ADC1_CLP0 *(volatile uint32_t *)0x400BB04C // ADC plus-side general calibration value register
+#define ADC1_PGA *(volatile uint32_t *)0x400BB050 // ADC Programmable Gain Amplifier
+#define ADC1_CLMD *(volatile uint32_t *)0x400BB054 // ADC minus-side general calibration value register
+#define ADC1_CLMS *(volatile uint32_t *)0x400BB058 // ADC minus-side general calibration value register
+#define ADC1_CLM4 *(volatile uint32_t *)0x400BB05C // ADC minus-side general calibration value register
+#define ADC1_CLM3 *(volatile uint32_t *)0x400BB060 // ADC minus-side general calibration value register
+#define ADC1_CLM2 *(volatile uint32_t *)0x400BB064 // ADC minus-side general calibration value register
+#define ADC1_CLM1 *(volatile uint32_t *)0x400BB068 // ADC minus-side general calibration value register
+#define ADC1_CLM0 *(volatile uint32_t *)0x400BB06C // ADC minus-side general calibration value register
+
+#define DAC0_DAT0L *(volatile uint8_t *)0x400CC000 // DAC Data Low Register
+#define DAC0_DATH *(volatile uint8_t *)0x400CC001 // DAC Data High Register
+#define DAC0_DAT1L *(volatile uint8_t *)0x400CC002 // DAC Data Low Register
+#define DAC0_DAT2L *(volatile uint8_t *)0x400CC004 // DAC Data Low Register
+#define DAC0_DAT3L *(volatile uint8_t *)0x400CC006 // DAC Data Low Register
+#define DAC0_DAT4L *(volatile uint8_t *)0x400CC008 // DAC Data Low Register
+#define DAC0_DAT5L *(volatile uint8_t *)0x400CC00A // DAC Data Low Register
+#define DAC0_DAT6L *(volatile uint8_t *)0x400CC00C // DAC Data Low Register
+#define DAC0_DAT7L *(volatile uint8_t *)0x400CC00E // DAC Data Low Register
+#define DAC0_DAT8L *(volatile uint8_t *)0x400CC010 // DAC Data Low Register
+#define DAC0_DAT9L *(volatile uint8_t *)0x400CC012 // DAC Data Low Register
+#define DAC0_DAT10L *(volatile uint8_t *)0x400CC014 // DAC Data Low Register
+#define DAC0_DAT11L *(volatile uint8_t *)0x400CC016 // DAC Data Low Register
+#define DAC0_DAT12L *(volatile uint8_t *)0x400CC018 // DAC Data Low Register
+#define DAC0_DAT13L *(volatile uint8_t *)0x400CC01A // DAC Data Low Register
+#define DAC0_DAT14L *(volatile uint8_t *)0x400CC01C // DAC Data Low Register
+#define DAC0_DAT15L *(volatile uint8_t *)0x400CC01E // DAC Data Low Register
+#define DAC0_SR *(volatile uint8_t *)0x400CC020 // DAC Status Register
+#define DAC0_C0 *(volatile uint8_t *)0x400CC021 // DAC Control Register
+#define DAC_C0_DACEN 0x80 // DAC Enable
+#define DAC_C0_DACRFS 0x40 // DAC Reference Select
+#define DAC_C0_DACTRGSEL 0x20 // DAC Trigger Select
+#define DAC_C0_DACSWTRG 0x10 // DAC Software Trigger
+#define DAC_C0_LPEN 0x08 // DAC Low Power Control
+#define DAC_C0_DACBWIEN 0x04 // DAC Buffer Watermark Interrupt Enable
+#define DAC_C0_DACBTIEN 0x02 // DAC Buffer Read Pointer Top Flag Interrupt Enable
+#define DAC_C0_DACBBIEN 0x01 // DAC Buffer Read Pointer Bottom Flag Interrupt Enable
+#define DAC0_C1 *(volatile uint8_t *)0x400CC022 // DAC Control Register 1
+#define DAC_C1_DMAEN 0x80 // DMA Enable Select
+#define DAC_C1_DACBFWM(n) (((n) & 3) << 3) // DAC Buffer Watermark Select
+#define DAC_C1_DACBFMD(n) (((n) & 3) << 0) // DAC Buffer Work Mode Select
+#define DAC_C1_DACBFEN 0x00 // DAC Buffer Enable
+
+#define DAC0_C2 *(volatile uint8_t *)0x400CC023 // DAC Control Register 2
+#define DAC_C2_DACBFRP(n) (((n) & 15) << 4) // DAC Buffer Read Pointer
+#define DAC_C2_DACBFUP(n) (((n) & 15) << 0) // DAC Buffer Upper Limit
+
+
+//#define MCG_C2_RANGE0(n) (uint8_t)(((n) & 0x03) << 4) // Frequency Range Select, Selects the frequency range for the crystal oscillator
+//#define MCG_C2_LOCRE0 (uint8_t)0x80 // Loss of Clock Reset Enable, Determines whether an interrupt or a reset request is made following a loss of OSC0
+
+// Chapter 32: Comparator (CMP)
+#define CMP0_CR0 *(volatile uint8_t *)0x40073000 // CMP Control Register 0
+#define CMP0_CR1 *(volatile uint8_t *)0x40073001 // CMP Control Register 1
+#define CMP0_FPR *(volatile uint8_t *)0x40073002 // CMP Filter Period Register
+#define CMP0_SCR *(volatile uint8_t *)0x40073003 // CMP Status and Control Register
+#define CMP0_DACCR *(volatile uint8_t *)0x40073004 // DAC Control Register
+#define CMP0_MUXCR *(volatile uint8_t *)0x40073005 // MUX Control Register
+#define CMP1_CR0 *(volatile uint8_t *)0x40073008 // CMP Control Register 0
+#define CMP1_CR1 *(volatile uint8_t *)0x40073009 // CMP Control Register 1
+#define CMP1_FPR *(volatile uint8_t *)0x4007300A // CMP Filter Period Register
+#define CMP1_SCR *(volatile uint8_t *)0x4007300B // CMP Status and Control Register
+#define CMP1_DACCR *(volatile uint8_t *)0x4007300C // DAC Control Register
+#define CMP1_MUXCR *(volatile uint8_t *)0x4007300D // MUX Control Register
+
+// Chapter 33: Voltage Reference (VREFV1)
+#define VREF_TRM *(volatile uint8_t *)0x40074000 // VREF Trim Register
+#define VREF_TRM_CHOPEN (uint8_t)0x40 // Chop oscillator enable
+#define VREF_TRM_TRIM(n) ((n) & 0x3F) // Trim bits
+#define VREF_SC *(volatile uint8_t *)0x40074001 // VREF Status and Control Register
+#define VREF_SC_VREFEN (uint8_t)0x80 // Internal Voltage Reference enable
+#define VREF_SC_REGEN (uint8_t)0x40 // Regulator enable
+#define VREF_SC_ICOMPEN (uint8_t)0x20 // Second order curvature compensation enable
+#define VREF_SC_VREFST (uint8_t)0x04 // Internal Voltage Reference stable flag
+#define VREF_SC_MODE_LV(n) (uint8_t)(((n) & 3) << 0) // Buffer Mode selection: 0=Bandgap on only
+ // 1=High power buffer mode,
+ // 2=Low-power buffer mode
+
+// Chapter 34: Programmable Delay Block (PDB)
+#define PDB0_SC *(volatile uint32_t *)0x40036000 // Status and Control Register
+#define PDB_SC_LDMOD(n) (((n) & 3) << 18) // Load Mode Select
+#define PDB_SC_PDBEIE 0x00020000 // Sequence Error Interrupt Enable
+#define PDB_SC_SWTRIG 0x00010000 // Software Trigger
+#define PDB_SC_DMAEN 0x00008000 // DMA Enable
+#define PDB_SC_PRESCALER(n) (((n) & 7) << 12) // Prescaler Divider Select
+#define PDB_SC_TRGSEL(n) (((n) & 15) << 8) // Trigger Input Source Select
+#define PDB_SC_PDBEN 0x00000080 // PDB Enable
+#define PDB_SC_PDBIF 0x00000040 // PDB Interrupt Flag
+#define PDB_SC_PDBIE 0x00000020 // PDB Interrupt Enable.
+#define PDB_SC_MULT(n) (((n) & 3) << 2) // Multiplication Factor
+#define PDB_SC_CONT 0x00000002 // Continuous Mode Enable
+#define PDB_SC_LDOK 0x00000001 // Load OK
+#define PDB0_MOD *(volatile uint32_t *)0x40036004 // Modulus Register
+#define PDB0_CNT *(volatile uint32_t *)0x40036008 // Counter Register
+#define PDB0_IDLY *(volatile uint32_t *)0x4003600C // Interrupt Delay Register
+#define PDB0_CH0C1 *(volatile uint32_t *)0x40036010 // Channel n Control Register 1
+#define PDB0_CH0S *(volatile uint32_t *)0x40036014 // Channel n Status Register
+#define PDB0_CH0DLY0 *(volatile uint32_t *)0x40036018 // Channel n Delay 0 Register
+#define PDB0_CH0DLY1 *(volatile uint32_t *)0x4003601C // Channel n Delay 1 Register
+#define PDB0_POEN *(volatile uint32_t *)0x40036190 // Pulse-Out n Enable Register
+#define PDB0_PO0DLY *(volatile uint32_t *)0x40036194 // Pulse-Out n Delay Register
+#define PDB0_PO1DLY *(volatile uint32_t *)0x40036198 // Pulse-Out n Delay Register
+
+// Chapter 35: FlexTimer Module (FTM)
+#define FTM0_SC *(volatile uint32_t *)0x40038000 // Status And Control
+#define FTM_SC_TOF 0x80 // Timer Overflow Flag
+#define FTM_SC_TOIE 0x40 // Timer Overflow Interrupt Enable
+#define FTM_SC_CPWMS 0x20 // Center-Aligned PWM Select
+#define FTM_SC_CLKS(n) (((n) & 3) << 3) // Clock Source Selection
+#define FTM_SC_PS(n) (((n) & 7) << 0) // Prescale Factor Selection
+#define FTM0_CNT *(volatile uint32_t *)0x40038004 // Counter
+#define FTM0_MOD *(volatile uint32_t *)0x40038008 // Modulo
+#define FTM0_C0SC *(volatile uint32_t *)0x4003800C // Channel 0 Status And Control
+#define FTM0_C0V *(volatile uint32_t *)0x40038010 // Channel 0 Value
+#define FTM0_C1SC *(volatile uint32_t *)0x40038014 // Channel 1 Status And Control
+#define FTM0_C1V *(volatile uint32_t *)0x40038018 // Channel 1 Value
+#define FTM0_C2SC *(volatile uint32_t *)0x4003801C // Channel 2 Status And Control
+#define FTM0_C2V *(volatile uint32_t *)0x40038020 // Channel 2 Value
+#define FTM0_C3SC *(volatile uint32_t *)0x40038024 // Channel 3 Status And Control
+#define FTM0_C3V *(volatile uint32_t *)0x40038028 // Channel 3 Value
+#define FTM0_C4SC *(volatile uint32_t *)0x4003802C // Channel 4 Status And Control
+#define FTM0_C4V *(volatile uint32_t *)0x40038030 // Channel 4 Value
+#define FTM0_C5SC *(volatile uint32_t *)0x40038034 // Channel 5 Status And Control
+#define FTM0_C5V *(volatile uint32_t *)0x40038038 // Channel 5 Value
+#define FTM0_C6SC *(volatile uint32_t *)0x4003803C // Channel 6 Status And Control
+#define FTM0_C6V *(volatile uint32_t *)0x40038040 // Channel 6 Value
+#define FTM0_C7SC *(volatile uint32_t *)0x40038044 // Channel 7 Status And Control
+#define FTM0_C7V *(volatile uint32_t *)0x40038048 // Channel 7 Value
+#define FTM0_CNTIN *(volatile uint32_t *)0x4003804C // Counter Initial Value
+#define FTM0_STATUS *(volatile uint32_t *)0x40038050 // Capture And Compare Status
+#define FTM0_MODE *(volatile uint32_t *)0x40038054 // Features Mode Selection
+#define FTM_MODE_FAULTIE 0x80 // Fault Interrupt Enable
+#define FTM_MODE_FAULTM(n) (((n) & 3) << 5) // Fault Control Mode
+#define FTM_MODE_CAPTEST 0x10 // Capture Test Mode Enable
+#define FTM_MODE_PWMSYNC 0x08 // PWM Synchronization Mode
+#define FTM_MODE_WPDIS 0x04 // Write Protection Disable
+#define FTM_MODE_INIT 0x02 // Initialize The Channels Output
+#define FTM_MODE_FTMEN 0x01 // FTM Enable
+#define FTM0_SYNC *(volatile uint32_t *)0x40038058 // Synchronization
+#define FTM_SYNC_SWSYNC 0x80 //
+#define FTM_SYNC_TRIG2 0x40 //
+#define FTM_SYNC_TRIG1 0x20 //
+#define FTM_SYNC_TRIG0 0x10 //
+#define FTM_SYNC_SYNCHOM 0x08 //
+#define FTM_SYNC_REINIT 0x04 //
+#define FTM_SYNC_CNTMAX 0x02 //
+#define FTM_SYNC_CNTMIN 0x01 //
+#define FTM0_OUTINIT *(volatile uint32_t *)0x4003805C // Initial State For Channels Output
+#define FTM0_OUTMASK *(volatile uint32_t *)0x40038060 // Output Mask
+#define FTM0_COMBINE *(volatile uint32_t *)0x40038064 // Function For Linked Channels
+#define FTM0_DEADTIME *(volatile uint32_t *)0x40038068 // Deadtime Insertion Control
+#define FTM0_EXTTRIG *(volatile uint32_t *)0x4003806C // FTM External Trigger
+#define FTM0_POL *(volatile uint32_t *)0x40038070 // Channels Polarity
+#define FTM0_FMS *(volatile uint32_t *)0x40038074 // Fault Mode Status
+#define FTM0_FILTER *(volatile uint32_t *)0x40038078 // Input Capture Filter Control
+#define FTM0_FLTCTRL *(volatile uint32_t *)0x4003807C // Fault Control
+#define FTM0_QDCTRL *(volatile uint32_t *)0x40038080 // Quadrature Decoder Control And Status
+#define FTM0_CONF *(volatile uint32_t *)0x40038084 // Configuration
+#define FTM0_FLTPOL *(volatile uint32_t *)0x40038088 // FTM Fault Input Polarity
+#define FTM0_SYNCONF *(volatile uint32_t *)0x4003808C // Synchronization Configuration
+#define FTM0_INVCTRL *(volatile uint32_t *)0x40038090 // FTM Inverting Control
+#define FTM0_SWOCTRL *(volatile uint32_t *)0x40038094 // FTM Software Output Control
+#define FTM0_PWMLOAD *(volatile uint32_t *)0x40038098 // FTM PWM Load
+#define FTM1_SC *(volatile uint32_t *)0x40039000 // Status And Control
+#define FTM1_CNT *(volatile uint32_t *)0x40039004 // Counter
+#define FTM1_MOD *(volatile uint32_t *)0x40039008 // Modulo
+#define FTM1_C0SC *(volatile uint32_t *)0x4003900C // Channel 0 Status And Control
+#define FTM1_C0V *(volatile uint32_t *)0x40039010 // Channel 0 Value
+#define FTM1_C1SC *(volatile uint32_t *)0x40039014 // Channel 1 Status And Control
+#define FTM1_C1V *(volatile uint32_t *)0x40039018 // Channel 1 Value
+#define FTM1_CNTIN *(volatile uint32_t *)0x4003904C // Counter Initial Value
+#define FTM1_STATUS *(volatile uint32_t *)0x40039050 // Capture And Compare Status
+#define FTM1_MODE *(volatile uint32_t *)0x40039054 // Features Mode Selection
+#define FTM1_SYNC *(volatile uint32_t *)0x40039058 // Synchronization
+#define FTM1_OUTINIT *(volatile uint32_t *)0x4003905C // Initial State For Channels Output
+#define FTM1_OUTMASK *(volatile uint32_t *)0x40039060 // Output Mask
+#define FTM1_COMBINE *(volatile uint32_t *)0x40039064 // Function For Linked Channels
+#define FTM1_DEADTIME *(volatile uint32_t *)0x40039068 // Deadtime Insertion Control
+#define FTM1_EXTTRIG *(volatile uint32_t *)0x4003906C // FTM External Trigger
+#define FTM1_POL *(volatile uint32_t *)0x40039070 // Channels Polarity
+#define FTM1_FMS *(volatile uint32_t *)0x40039074 // Fault Mode Status
+#define FTM1_FILTER *(volatile uint32_t *)0x40039078 // Input Capture Filter Control
+#define FTM1_FLTCTRL *(volatile uint32_t *)0x4003907C // Fault Control
+#define FTM1_QDCTRL *(volatile uint32_t *)0x40039080 // Quadrature Decoder Control And Status
+#define FTM1_CONF *(volatile uint32_t *)0x40039084 // Configuration
+#define FTM1_FLTPOL *(volatile uint32_t *)0x40039088 // FTM Fault Input Polarity
+#define FTM1_SYNCONF *(volatile uint32_t *)0x4003908C // Synchronization Configuration
+#define FTM1_INVCTRL *(volatile uint32_t *)0x40039090 // FTM Inverting Control
+#define FTM1_SWOCTRL *(volatile uint32_t *)0x40039094 // FTM Software Output Control
+#define FTM1_PWMLOAD *(volatile uint32_t *)0x40039098 // FTM PWM Load
+#define FTM2_SC *(volatile uint32_t *)0x400B8000 // Status And Control
+#define FTM2_CNT *(volatile uint32_t *)0x400B8004 // Counter
+#define FTM2_MOD *(volatile uint32_t *)0x400B8008 // Modulo
+#define FTM2_C0SC *(volatile uint32_t *)0x400B800C // Channel 0 Status And Control
+#define FTM2_C0V *(volatile uint32_t *)0x400B8010 // Channel 0 Value
+#define FTM2_C1SC *(volatile uint32_t *)0x400B8014 // Channel 1 Status And Control
+#define FTM2_C1V *(volatile uint32_t *)0x400B8018 // Channel 1 Value
+#define FTM2_CNTIN *(volatile uint32_t *)0x400B804C // Counter Initial Value
+#define FTM2_STATUS *(volatile uint32_t *)0x400B8050 // Capture And Compare Status
+#define FTM2_MODE *(volatile uint32_t *)0x400B8054 // Features Mode Selection
+#define FTM2_SYNC *(volatile uint32_t *)0x400B8058 // Synchronization
+#define FTM2_OUTINIT *(volatile uint32_t *)0x400B805C // Initial State For Channels Output
+#define FTM2_OUTMASK *(volatile uint32_t *)0x400B8060 // Output Mask
+#define FTM2_COMBINE *(volatile uint32_t *)0x400B8064 // Function For Linked Channels
+#define FTM2_DEADTIME *(volatile uint32_t *)0x400B8068 // Deadtime Insertion Control
+#define FTM2_EXTTRIG *(volatile uint32_t *)0x400B806C // FTM External Trigger
+#define FTM2_POL *(volatile uint32_t *)0x400B8070 // Channels Polarity
+#define FTM2_FMS *(volatile uint32_t *)0x400B8074 // Fault Mode Status
+#define FTM2_FILTER *(volatile uint32_t *)0x400B8078 // Input Capture Filter Control
+#define FTM2_FLTCTRL *(volatile uint32_t *)0x400B807C // Fault Control
+#define FTM2_QDCTRL *(volatile uint32_t *)0x400B8080 // Quadrature Decoder Control And Status
+#define FTM2_CONF *(volatile uint32_t *)0x400B8084 // Configuration
+#define FTM2_FLTPOL *(volatile uint32_t *)0x400B8088 // FTM Fault Input Polarity
+#define FTM2_SYNCONF *(volatile uint32_t *)0x400B808C // Synchronization Configuration
+#define FTM2_INVCTRL *(volatile uint32_t *)0x400B8090 // FTM Inverting Control
+#define FTM2_SWOCTRL *(volatile uint32_t *)0x400B8094 // FTM Software Output Control
+#define FTM2_PWMLOAD *(volatile uint32_t *)0x400B8098 // FTM PWM Load
+
+// Chapter 36: Periodic Interrupt Timer (PIT)
+#define PIT_MCR *(volatile uint32_t *)0x40037000 // PIT Module Control Register
+#define PIT_LDVAL0 *(volatile uint32_t *)0x40037100 // Timer Load Value Register
+#define PIT_CVAL0 *(volatile uint32_t *)0x40037104 // Current Timer Value Register
+#define PIT_TCTRL0 *(volatile uint32_t *)0x40037108 // Timer Control Register
+#define PIT_TFLG0 *(volatile uint32_t *)0x4003710C // Timer Flag Register
+#define PIT_LDVAL1 *(volatile uint32_t *)0x40037110 // Timer Load Value Register
+#define PIT_CVAL1 *(volatile uint32_t *)0x40037114 // Current Timer Value Register
+#define PIT_TCTRL1 *(volatile uint32_t *)0x40037118 // Timer Control Register
+#define PIT_TFLG1 *(volatile uint32_t *)0x4003711C // Timer Flag Register
+#define PIT_LDVAL2 *(volatile uint32_t *)0x40037120 // Timer Load Value Register
+#define PIT_CVAL2 *(volatile uint32_t *)0x40037124 // Current Timer Value Register
+#define PIT_TCTRL2 *(volatile uint32_t *)0x40037128 // Timer Control Register
+#define PIT_TFLG2 *(volatile uint32_t *)0x4003712C // Timer Flag Register
+#define PIT_LDVAL3 *(volatile uint32_t *)0x40037130 // Timer Load Value Register
+#define PIT_CVAL3 *(volatile uint32_t *)0x40037134 // Current Timer Value Register
+#define PIT_TCTRL3 *(volatile uint32_t *)0x40037138 // Timer Control Register
+#define PIT_TFLG3 *(volatile uint32_t *)0x4003713C // Timer Flag Register
+
+// Chapter 37: Low-Power Timer (LPTMR)
+#define LPTMR0_CSR *(volatile uint32_t *)0x40040000 // Low Power Timer Control Status Register
+#define LPTMR0_PSR *(volatile uint32_t *)0x40040004 // Low Power Timer Prescale Register
+#define LPTMR0_CMR *(volatile uint32_t *)0x40040008 // Low Power Timer Compare Register
+#define LPTMR0_CNR *(volatile uint32_t *)0x4004000C // Low Power Timer Counter Register
+
+// Chapter 38: Carrier Modulator Transmitter (CMT)
+#define CMT_CGH1 *(volatile uint8_t *)0x40062000 // CMT Carrier Generator High Data Register 1
+#define CMT_CGL1 *(volatile uint8_t *)0x40062001 // CMT Carrier Generator Low Data Register 1
+#define CMT_CGH2 *(volatile uint8_t *)0x40062002 // CMT Carrier Generator High Data Register 2
+#define CMT_CGL2 *(volatile uint8_t *)0x40062003 // CMT Carrier Generator Low Data Register 2
+#define CMT_OC *(volatile uint8_t *)0x40062004 // CMT Output Control Register
+#define CMT_MSC *(volatile uint8_t *)0x40062005 // CMT Modulator Status and Control Register
+#define CMT_CMD1 *(volatile uint8_t *)0x40062006 // CMT Modulator Data Register Mark High
+#define CMT_CMD2 *(volatile uint8_t *)0x40062007 // CMT Modulator Data Register Mark Low
+#define CMT_CMD3 *(volatile uint8_t *)0x40062008 // CMT Modulator Data Register Space High
+#define CMT_CMD4 *(volatile uint8_t *)0x40062009 // CMT Modulator Data Register Space Low
+#define CMT_PPS *(volatile uint8_t *)0x4006200A // CMT Primary Prescaler Register
+#define CMT_DMA *(volatile uint8_t *)0x4006200B // CMT Direct Memory Access Register
+
+// Chapter 39: Real Time Clock (RTC)
+#define RTC_TSR *(volatile uint32_t *)0x4003D000 // RTC Time Seconds Register
+#define RTC_TPR *(volatile uint32_t *)0x4003D004 // RTC Time Prescaler Register
+#define RTC_TAR *(volatile uint32_t *)0x4003D008 // RTC Time Alarm Register
+#define RTC_TCR *(volatile uint32_t *)0x4003D00C // RTC Time Compensation Register
+#define RTC_TCR_CIC(n) (((n) & 255) << 24) // Compensation Interval Counter
+#define RTC_TCR_TCV(n) (((n) & 255) << 16) // Time Compensation Value
+#define RTC_TCR_CIR(n) (((n) & 255) << 8) // Compensation Interval Register
+#define RTC_TCR_TCR(n) (((n) & 255) << 0) // Time Compensation Register
+#define RTC_CR *(volatile uint32_t *)0x4003D010 // RTC Control Register
+#define RTC_CR_SC2P (uint32_t)0x00002000 //
+#define RTC_CR_SC4P (uint32_t)0x00001000 //
+#define RTC_CR_SC8P (uint32_t)0x00000800 //
+#define RTC_CR_SC16P (uint32_t)0x00000400 //
+#define RTC_CR_CLKO (uint32_t)0x00000200 //
+#define RTC_CR_OSCE (uint32_t)0x00000100 //
+#define RTC_CR_UM (uint32_t)0x00000008 //
+#define RTC_CR_SUP (uint32_t)0x00000004 //
+#define RTC_CR_WPE (uint32_t)0x00000002 //
+#define RTC_CR_SWR (uint32_t)0x00000001 //
+#define RTC_SR *(volatile uint32_t *)0x4003D014 // RTC Status Register
+#define RTC_SR_TCE (uint32_t)0x00000010 //
+#define RTC_SR_TAF (uint32_t)0x00000004 //
+#define RTC_SR_TOF (uint32_t)0x00000002 //
+#define RTC_SR_TIF (uint32_t)0x00000001 //
+#define RTC_LR *(volatile uint32_t *)0x4003D018 // RTC Lock Register
+#define RTC_IER *(volatile uint32_t *)0x4003D01C // RTC Interrupt Enable Register
+#define RTC_WAR *(volatile uint32_t *)0x4003D800 // RTC Write Access Register
+#define RTC_RAR *(volatile uint32_t *)0x4003D804 // RTC Read Access Register
+
+// Chapter 40: Universal Serial Bus OTG Controller (USBOTG)
+#define USB0_PERID *(const uint8_t *)0x40072000 // Peripheral ID register
+#define USB0_IDCOMP *(const uint8_t *)0x40072004 // Peripheral ID Complement register
+#define USB0_REV *(const uint8_t *)0x40072008 // Peripheral Revision register
+#define USB0_ADDINFO *(volatile uint8_t *)0x4007200C // Peripheral Additional Info register
+#define USB0_OTGISTAT *(volatile uint8_t *)0x40072010 // OTG Interrupt Status register
+#define USB_OTGISTAT_IDCHG (uint8_t)0x80 //
+#define USB_OTGISTAT_ONEMSEC (uint8_t)0x40 //
+#define USB_OTGISTAT_LINE_STATE_CHG (uint8_t)0x20 //
+#define USB_OTGISTAT_SESSVLDCHG (uint8_t)0x08 //
+#define USB_OTGISTAT_B_SESS_CHG (uint8_t)0x04 //
+#define USB_OTGISTAT_AVBUSCHG (uint8_t)0x01 //
+#define USB0_OTGICR *(volatile uint8_t *)0x40072014 // OTG Interrupt Control Register
+#define USB_OTGICR_IDEN (uint8_t)0x80 //
+#define USB_OTGICR_ONEMSECEN (uint8_t)0x40 //
+#define USB_OTGICR_LINESTATEEN (uint8_t)0x20 //
+#define USB_OTGICR_SESSVLDEN (uint8_t)0x08 //
+#define USB_OTGICR_BSESSEN (uint8_t)0x04 //
+#define USB_OTGICR_AVBUSEN (uint8_t)0x01 //
+#define USB0_OTGSTAT *(volatile uint8_t *)0x40072018 // OTG Status register
+#define USB_OTGSTAT_ID (uint8_t)0x80 //
+#define USB_OTGSTAT_ONEMSECEN (uint8_t)0x40 //
+#define USB_OTGSTAT_LINESTATESTABLE (uint8_t)0x20 //
+#define USB_OTGSTAT_SESS_VLD (uint8_t)0x08 //
+#define USB_OTGSTAT_BSESSEND (uint8_t)0x04 //
+#define USB_OTGSTAT_AVBUSVLD (uint8_t)0x01 //
+#define USB0_OTGCTL *(volatile uint8_t *)0x4007201C // OTG Control Register
+#define USB_OTGCTL_DPHIGH (uint8_t)0x80 //
+#define USB_OTGCTL_DPLOW (uint8_t)0x20 //
+#define USB_OTGCTL_DMLOW (uint8_t)0x10 //
+#define USB_OTGCTL_OTGEN (uint8_t)0x04 //
+#define USB0_ISTAT *(volatile uint8_t *)0x40072080 // Interrupt Status Register
+#define USB_ISTAT_STALL (uint8_t)0x80 //
+#define USB_ISTAT_ATTACH (uint8_t)0x40 //
+#define USB_ISTAT_RESUME (uint8_t)0x20 //
+#define USB_ISTAT_SLEEP (uint8_t)0x10 //
+#define USB_ISTAT_TOKDNE (uint8_t)0x08 //
+#define USB_ISTAT_SOFTOK (uint8_t)0x04 //
+#define USB_ISTAT_ERROR (uint8_t)0x02 //
+#define USB_ISTAT_USBRST (uint8_t)0x01 //
+#define USB0_INTEN *(volatile uint8_t *)0x40072084 // Interrupt Enable Register
+#define USB_INTEN_STALLEN (uint8_t)0x80 //
+#define USB_INTEN_ATTACHEN (uint8_t)0x40 //
+#define USB_INTEN_RESUMEEN (uint8_t)0x20 //
+#define USB_INTEN_SLEEPEN (uint8_t)0x10 //
+#define USB_INTEN_TOKDNEEN (uint8_t)0x08 //
+#define USB_INTEN_SOFTOKEN (uint8_t)0x04 //
+#define USB_INTEN_ERROREN (uint8_t)0x02 //
+#define USB_INTEN_USBRSTEN (uint8_t)0x01 //
+#define USB0_ERRSTAT *(volatile uint8_t *)0x40072088 // Error Interrupt Status Register
+#define USB_ERRSTAT_BTSERR (uint8_t)0x80 //
+#define USB_ERRSTAT_DMAERR (uint8_t)0x20 //
+#define USB_ERRSTAT_BTOERR (uint8_t)0x10 //
+#define USB_ERRSTAT_DFN8 (uint8_t)0x08 //
+#define USB_ERRSTAT_CRC16 (uint8_t)0x04 //
+#define USB_ERRSTAT_CRC5EOF (uint8_t)0x02 //
+#define USB_ERRSTAT_PIDERR (uint8_t)0x01 //
+#define USB0_ERREN *(volatile uint8_t *)0x4007208C // Error Interrupt Enable Register
+#define USB_ERREN_BTSERREN (uint8_t)0x80 //
+#define USB_ERREN_DMAERREN (uint8_t)0x20 //
+#define USB_ERREN_BTOERREN (uint8_t)0x10 //
+#define USB_ERREN_DFN8EN (uint8_t)0x08 //
+#define USB_ERREN_CRC16EN (uint8_t)0x04 //
+#define USB_ERREN_CRC5EOFEN (uint8_t)0x02 //
+#define USB_ERREN_PIDERREN (uint8_t)0x01 //
+#define USB0_STAT *(volatile uint8_t *)0x40072090 // Status Register
+#define USB_STAT_TX (uint8_t)0x08 //
+#define USB_STAT_ODD (uint8_t)0x04 //
+#define USB_STAT_ENDP(n) (uint8_t)((n) >> 4) //
+#define USB0_CTL *(volatile uint8_t *)0x40072094 // Control Register
+#define USB_CTL_JSTATE (uint8_t)0x80 //
+#define USB_CTL_SE0 (uint8_t)0x40 //
+#define USB_CTL_TXSUSPENDTOKENBUSY (uint8_t)0x20 //
+#define USB_CTL_RESET (uint8_t)0x10 //
+#define USB_CTL_HOSTMODEEN (uint8_t)0x08 //
+#define USB_CTL_RESUME (uint8_t)0x04 //
+#define USB_CTL_ODDRST (uint8_t)0x02 //
+#define USB_CTL_USBENSOFEN (uint8_t)0x01 //
+#define USB0_ADDR *(volatile uint8_t *)0x40072098 // Address Register
+#define USB0_BDTPAGE1 *(volatile uint8_t *)0x4007209C // BDT Page Register 1
+#define USB0_FRMNUML *(volatile uint8_t *)0x400720A0 // Frame Number Register Low
+#define USB0_FRMNUMH *(volatile uint8_t *)0x400720A4 // Frame Number Register High
+#define USB0_TOKEN *(volatile uint8_t *)0x400720A8 // Token Register
+#define USB0_SOFTHLD *(volatile uint8_t *)0x400720AC // SOF Threshold Register
+#define USB0_BDTPAGE2 *(volatile uint8_t *)0x400720B0 // BDT Page Register 2
+#define USB0_BDTPAGE3 *(volatile uint8_t *)0x400720B4 // BDT Page Register 3
+#define USB0_ENDPT0 *(volatile uint8_t *)0x400720C0 // Endpoint Control Register
+#define USB_ENDPT_HOSTWOHUB (uint8_t)0x80 // host only, enable low speed
+#define USB_ENDPT_RETRYDIS (uint8_t)0x40 // host only, set to disable NAK retry
+#define USB_ENDPT_EPCTLDIS (uint8_t)0x10 // 0=control, 1=bulk, interrupt, isync
+#define USB_ENDPT_EPRXEN (uint8_t)0x08 // enables the endpoint for RX transfers.
+#define USB_ENDPT_EPTXEN (uint8_t)0x04 // enables the endpoint for TX transfers.
+#define USB_ENDPT_EPSTALL (uint8_t)0x02 // set to stall endpoint
+#define USB_ENDPT_EPHSHK (uint8_t)0x01 // enable handshaking during a transaction, generally set unless Isochronous
+#define USB0_ENDPT1 *(volatile uint8_t *)0x400720C4 // Endpoint Control Register
+#define USB0_ENDPT2 *(volatile uint8_t *)0x400720C8 // Endpoint Control Register
+#define USB0_ENDPT3 *(volatile uint8_t *)0x400720CC // Endpoint Control Register
+#define USB0_ENDPT4 *(volatile uint8_t *)0x400720D0 // Endpoint Control Register
+#define USB0_ENDPT5 *(volatile uint8_t *)0x400720D4 // Endpoint Control Register
+#define USB0_ENDPT6 *(volatile uint8_t *)0x400720D8 // Endpoint Control Register
+#define USB0_ENDPT7 *(volatile uint8_t *)0x400720DC // Endpoint Control Register
+#define USB0_ENDPT8 *(volatile uint8_t *)0x400720E0 // Endpoint Control Register
+#define USB0_ENDPT9 *(volatile uint8_t *)0x400720E4 // Endpoint Control Register
+#define USB0_ENDPT10 *(volatile uint8_t *)0x400720E8 // Endpoint Control Register
+#define USB0_ENDPT11 *(volatile uint8_t *)0x400720EC // Endpoint Control Register
+#define USB0_ENDPT12 *(volatile uint8_t *)0x400720F0 // Endpoint Control Register
+#define USB0_ENDPT13 *(volatile uint8_t *)0x400720F4 // Endpoint Control Register
+#define USB0_ENDPT14 *(volatile uint8_t *)0x400720F8 // Endpoint Control Register
+#define USB0_ENDPT15 *(volatile uint8_t *)0x400720FC // Endpoint Control Register
+#define USB0_USBCTRL *(volatile uint8_t *)0x40072100 // USB Control Register
+#define USB_USBCTRL_SUSP (uint8_t)0x80 // Places the USB transceiver into the suspend state.
+#define USB_USBCTRL_PDE (uint8_t)0x40 // Enables the weak pulldowns on the USB transceiver.
+#define USB0_OBSERVE *(volatile uint8_t *)0x40072104 // USB OTG Observe Register
+#define USB_OBSERVE_DPPU (uint8_t)0x80 //
+#define USB_OBSERVE_DPPD (uint8_t)0x40 //
+#define USB_OBSERVE_DMPD (uint8_t)0x10 //
+#define USB0_CONTROL *(volatile uint8_t *)0x40072108 // USB OTG Control Register
+#define USB_CONTROL_DPPULLUPNONOTG (uint8_t)0x10 // Provides control of the DP PULLUP in the USB OTG module, if USB is configured in non-OTG device mode.
+#define USB0_USBTRC0 *(volatile uint8_t *)0x4007210C // USB Transceiver Control Register 0
+#define USB_USBTRC_USBRESET (uint8_t)0x80 //
+#define USB_USBTRC_USBRESMEN (uint8_t)0x20 //
+#define USB_USBTRC_SYNC_DET (uint8_t)0x02 //
+#define USB_USBTRC_USB_RESUME_INT (uint8_t)0x01 //
+#define USB0_USBFRMADJUST *(volatile uint8_t *)0x40072114 // Frame Adjust Register
+
+// Chapter 41: USB Device Charger Detection Module (USBDCD)
+#define USBDCD_CONTROL *(volatile uint32_t *)0x40035000 // Control register
+#define USBDCD_CLOCK *(volatile uint32_t *)0x40035004 // Clock register
+#define USBDCD_STATUS *(volatile uint32_t *)0x40035008 // Status register
+#define USBDCD_TIMER0 *(volatile uint32_t *)0x40035010 // TIMER0 register
+#define USBDCD_TIMER1 *(volatile uint32_t *)0x40035014 // TIMER1 register
+#define USBDCD_TIMER2 *(volatile uint32_t *)0x40035018 // TIMER2 register
+
+// Chapter 43: SPI (DSPI)
+#define SPI0_MCR *(volatile uint32_t *)0x4002C000 // DSPI Module Configuration Register
+#define SPI_MCR_MSTR (uint32_t)0x80000000 // Master/Slave Mode Select
+#define SPI_MCR_CONT_SCKE (uint32_t)0x40000000 //
+#define SPI_MCR_DCONF(n) (((n) & 3) << 28) //
+#define SPI_MCR_FRZ (uint32_t)0x08000000 //
+#define SPI_MCR_MTFE (uint32_t)0x04000000 //
+#define SPI_MCR_ROOE (uint32_t)0x01000000 //
+#define SPI_MCR_PCSIS(n) (((n) & 0x1F) << 16) //
+#define SPI_MCR_DOZE (uint32_t)0x00008000 //
+#define SPI_MCR_MDIS (uint32_t)0x00004000 //
+#define SPI_MCR_DIS_TXF (uint32_t)0x00002000 //
+#define SPI_MCR_DIS_RXF (uint32_t)0x00001000 //
+#define SPI_MCR_CLR_TXF (uint32_t)0x00000800 //
+#define SPI_MCR_CLR_RXF (uint32_t)0x00000400 //
+#define SPI_MCR_SMPL_PT(n) (((n) & 3) << 8) //
+#define SPI_MCR_HALT (uint32_t)0x00000001 //
+#define SPI0_TCR *(volatile uint32_t *)0x4002C008 // DSPI Transfer Count Register
+#define SPI0_CTAR0 *(volatile uint32_t *)0x4002C00C // DSPI Clock and Transfer Attributes Register, In Master Mode
+#define SPI_CTAR_DBR (uint32_t)0x80000000 // Double Baud Rate
+#define SPI_CTAR_FMSZ(n) (((n) & 15) << 27) // Frame Size (+1)
+#define SPI_CTAR_CPOL (uint32_t)0x04000000 // Clock Polarity
+#define SPI_CTAR_CPHA (uint32_t)0x02000000 // Clock Phase
+#define SPI_CTAR_LSBFE (uint32_t)0x01000000 // LSB First
+#define SPI_CTAR_PCSSCK(n) (((n) & 3) << 22) // PCS to SCK Delay Prescaler
+#define SPI_CTAR_PASC(n) (((n) & 3) << 20) // After SCK Delay Prescaler
+#define SPI_CTAR_PDT(n) (((n) & 3) << 18) // Delay after Transfer Prescaler
+#define SPI_CTAR_PBR(n) (((n) & 3) << 16) // Baud Rate Prescaler
+#define SPI_CTAR_CSSCK(n) (((n) & 15) << 12) // PCS to SCK Delay Scaler
+#define SPI_CTAR_ASC(n) (((n) & 15) << 8) // After SCK Delay Scaler
+#define SPI_CTAR_DT(n) (((n) & 15) << 4) // Delay After Transfer Scaler
+#define SPI_CTAR_BR(n) (((n) & 15) << 0) // Baud Rate Scaler
+#define SPI0_CTAR0_SLAVE *(volatile uint32_t *)0x4002C00C // DSPI Clock and Transfer Attributes Register, In Slave Mode
+#define SPI0_CTAR1 *(volatile uint32_t *)0x4002C010 // DSPI Clock and Transfer Attributes Register, In Master Mode
+#define SPI0_SR *(volatile uint32_t *)0x4002C02C // DSPI Status Register
+#define SPI_SR_TCF (uint32_t)0x80000000 // Transfer Complete Flag
+#define SPI_SR_TXRXS (uint32_t)0x40000000 // TX and RX Status
+#define SPI_SR_EOQF (uint32_t)0x10000000 // End of Queue Flag
+#define SPI_SR_TFUF (uint32_t)0x08000000 // Transmit FIFO Underflow Flag
+#define SPI_SR_TFFF (uint32_t)0x02000000 // Transmit FIFO Fill Flag
+#define SPI_SR_RFOF (uint32_t)0x00080000 // Receive FIFO Overflow Flag
+#define SPI_SR_RFDF (uint32_t)0x00020000 // Receive FIFO Drain Flag
+#define SPI0_RSER *(volatile uint32_t *)0x4002C030 // DSPI DMA/Interrupt Request Select and Enable Register
+#define SPI_RSER_TCF_RE (uint32_t)0x80000000 // Transmission Complete Request Enable
+#define SPI_RSER_EOQF_RE (uint32_t)0x10000000 // DSPI Finished Request Request Enable
+#define SPI_RSER_TFUF_RE (uint32_t)0x08000000 // Transmit FIFO Underflow Request Enable
+#define SPI_RSER_TFFF_RE (uint32_t)0x02000000 // Transmit FIFO Fill Request Enable
+#define SPI_RSER_TFFF_DIRS (uint32_t)0x01000000 // Transmit FIFO FIll Dma or Interrupt Request Select
+#define SPI_RSER_RFOF_RE (uint32_t)0x00080000 // Receive FIFO Overflow Request Enable
+#define SPI_RSER_RFDF_RE (uint32_t)0x00020000 // Receive FIFO Drain Request Enable
+#define SPI_RSER_RFDF_DIRS (uint32_t)0x00010000 // Receive FIFO Drain DMA or Interrupt Request Select
+#define SPI0_PUSHR *(volatile uint32_t *)0x4002C034 // DSPI PUSH TX FIFO Register In Master Mode
+#define SPI_PUSHR_CONT (uint32_t)0x80000000 //
+#define SPI_PUSHR_CTAS(n) (((n) & 7) << 28) //
+#define SPI_PUSHR_EOQ (uint32_t)0x08000000 //
+#define SPI_PUSHR_CTCNT (uint32_t)0x04000000 //
+#define SPI_PUSHR_PCS(n) (((n) & 31) << 16) //
+#define SPI0_PUSHR_SLAVE *(volatile uint32_t *)0x4002C034 // DSPI PUSH TX FIFO Register In Slave Mode
+#define SPI0_POPR *(volatile uint32_t *)0x4002C038 // DSPI POP RX FIFO Register
+#define SPI0_TXFR0 *(volatile uint32_t *)0x4002C03C // DSPI Transmit FIFO Registers
+#define SPI0_TXFR1 *(volatile uint32_t *)0x4002C040 // DSPI Transmit FIFO Registers
+#define SPI0_TXFR2 *(volatile uint32_t *)0x4002C044 // DSPI Transmit FIFO Registers
+#define SPI0_TXFR3 *(volatile uint32_t *)0x4002C048 // DSPI Transmit FIFO Registers
+#define SPI0_RXFR0 *(volatile uint32_t *)0x4002C07C // DSPI Receive FIFO Registers
+#define SPI0_RXFR1 *(volatile uint32_t *)0x4002C080 // DSPI Receive FIFO Registers
+#define SPI0_RXFR2 *(volatile uint32_t *)0x4002C084 // DSPI Receive FIFO Registers
+#define SPI0_RXFR3 *(volatile uint32_t *)0x4002C088 // DSPI Receive FIFO Registers
+typedef struct {
+ volatile uint32_t MCR; // 0
+ volatile uint32_t unused1;// 4
+ volatile uint32_t TCR; // 8
+ volatile uint32_t CTAR0; // c
+ volatile uint32_t CTAR1; // 10
+ volatile uint32_t CTAR2; // 14
+ volatile uint32_t CTAR3; // 18
+ volatile uint32_t CTAR4; // 1c
+ volatile uint32_t CTAR5; // 20
+ volatile uint32_t CTAR6; // 24
+ volatile uint32_t CTAR7; // 28
+ volatile uint32_t SR; // 2c
+ volatile uint32_t RSER; // 30
+ volatile uint32_t PUSHR; // 34
+ volatile uint32_t POPR; // 38
+ volatile uint32_t TXFR[16]; // 3c
+ volatile uint32_t RXFR[16]; // 7c
+} SPI_t;
+#define SPI0 (*(SPI_t *)0x4002C000)
+
+// Chapter 44: Inter-Integrated Circuit (I2C)
+#define I2C0_A1 *(volatile uint8_t *)0x40066000 // I2C Address Register 1
+#define I2C0_F *(volatile uint8_t *)0x40066001 // I2C Frequency Divider register
+#define I2C0_C1 *(volatile uint8_t *)0x40066002 // I2C Control Register 1
+#define I2C_C1_IICEN (uint8_t)0x80 // I2C Enable
+#define I2C_C1_IICIE (uint8_t)0x40 // I2C Interrupt Enable
+#define I2C_C1_MST (uint8_t)0x20 // Master Mode Select
+#define I2C_C1_TX (uint8_t)0x10 // Transmit Mode Select
+#define I2C_C1_TXAK (uint8_t)0x08 // Transmit Acknowledge Enable
+#define I2C_C1_RSTA (uint8_t)0x04 // Repeat START
+#define I2C_C1_WUEN (uint8_t)0x02 // Wakeup Enable
+#define I2C_C1_DMAEN (uint8_t)0x01 // DMA Enable
+#define I2C0_S *(volatile uint8_t *)0x40066003 // I2C Status register
+#define I2C_S_TCF (uint8_t)0x80 // Transfer Complete Flag
+#define I2C_S_IAAS (uint8_t)0x40 // Addressed As A Slave
+#define I2C_S_BUSY (uint8_t)0x20 // Bus Busy
+#define I2C_S_ARBL (uint8_t)0x10 // Arbitration Lost
+#define I2C_S_RAM (uint8_t)0x08 // Range Address Match
+#define I2C_S_SRW (uint8_t)0x04 // Slave Read/Write
+#define I2C_S_IICIF (uint8_t)0x02 // Interrupt Flag
+#define I2C_S_RXAK (uint8_t)0x01 // Receive Acknowledge
+#define I2C0_D *(volatile uint8_t *)0x40066004 // I2C Data I/O register
+#define I2C0_C2 *(volatile uint8_t *)0x40066005 // I2C Control Register 2
+#define I2C_C2_GCAEN (uint8_t)0x80 // General Call Address Enable
+#define I2C_C2_ADEXT (uint8_t)0x40 // Address Extension
+#define I2C_C2_HDRS (uint8_t)0x20 // High Drive Select
+#define I2C_C2_SBRC (uint8_t)0x10 // Slave Baud Rate Control
+#define I2C_C2_RMEN (uint8_t)0x08 // Range Address Matching Enable
+#define I2C_C2_AD(n) ((n) & 7) // Slave Address, upper 3 bits
+#define I2C0_FLT *(volatile uint8_t *)0x40066006 // I2C Programmable Input Glitch Filter register
+#define I2C0_RA *(volatile uint8_t *)0x40066007 // I2C Range Address register
+#define I2C0_SMB *(volatile uint8_t *)0x40066008 // I2C SMBus Control and Status register
+#define I2C0_A2 *(volatile uint8_t *)0x40066009 // I2C Address Register 2
+#define I2C0_SLTH *(volatile uint8_t *)0x4006600A // I2C SCL Low Timeout Register High
+#define I2C0_SLTL *(volatile uint8_t *)0x4006600B // I2C SCL Low Timeout Register Low
+
+#define I2C1_A1 *(volatile uint8_t *)0x40067000 // I2C Address Register 1
+#define I2C1_F *(volatile uint8_t *)0x40067001 // I2C Frequency Divider register
+#define I2C1_C1 *(volatile uint8_t *)0x40067002 // I2C Control Register 1
+#define I2C1_S *(volatile uint8_t *)0x40067003 // I2C Status register
+#define I2C1_D *(volatile uint8_t *)0x40067004 // I2C Data I/O register
+#define I2C1_C2 *(volatile uint8_t *)0x40067005 // I2C Control Register 2
+#define I2C1_FLT *(volatile uint8_t *)0x40067006 // I2C Programmable Input Glitch Filter register
+#define I2C1_RA *(volatile uint8_t *)0x40067007 // I2C Range Address register
+#define I2C1_SMB *(volatile uint8_t *)0x40067008 // I2C SMBus Control and Status register
+#define I2C1_A2 *(volatile uint8_t *)0x40067009 // I2C Address Register 2
+#define I2C1_SLTH *(volatile uint8_t *)0x4006700A // I2C SCL Low Timeout Register High
+#define I2C1_SLTL *(volatile uint8_t *)0x4006700B // I2C SCL Low Timeout Register Low
+
+// Chapter 45: Universal Asynchronous Receiver/Transmitter (UART)
+#define UART0_BDH *(volatile uint8_t *)0x4006A000 // UART Baud Rate Registers: High
+#define UART0_BDL *(volatile uint8_t *)0x4006A001 // UART Baud Rate Registers: Low
+#define UART0_C1 *(volatile uint8_t *)0x4006A002 // UART Control Register 1
+#define UART_C1_LOOPS (uint8_t)0x80 // When LOOPS is set, the RxD pin is disconnected from the UART and the transmitter output is internally connected to the receiver input
+#define UART_C1_UARTSWAI (uint8_t)0x40 // UART Stops in Wait Mode
+#define UART_C1_RSRC (uint8_t)0x20 // When LOOPS is set, the RSRC field determines the source for the receiver shift register input
+#define UART_C1_M (uint8_t)0x10 // 9-bit or 8-bit Mode Select
+#define UART_C1_WAKE (uint8_t)0x08 // Determines which condition wakes the UART
+#define UART_C1_ILT (uint8_t)0x04 // Idle Line Type Select
+#define UART_C1_PE (uint8_t)0x02 // Parity Enable
+#define UART_C1_PT (uint8_t)0x01 // Parity Type, 0=even, 1=odd
+#define UART0_C2 *(volatile uint8_t *)0x4006A003 // UART Control Register 2
+#define UART_C2_TIE (uint8_t)0x80 // Transmitter Interrupt or DMA Transfer Enable.
+#define UART_C2_TCIE (uint8_t)0x40 // Transmission Complete Interrupt Enable
+#define UART_C2_RIE (uint8_t)0x20 // Receiver Full Interrupt or DMA Transfer Enable
+#define UART_C2_ILIE (uint8_t)0x10 // Idle Line Interrupt Enable
+#define UART_C2_TE (uint8_t)0x08 // Transmitter Enable
+#define UART_C2_RE (uint8_t)0x04 // Receiver Enable
+#define UART_C2_RWU (uint8_t)0x02 // Receiver Wakeup Control
+#define UART_C2_SBK (uint8_t)0x01 // Send Break
+#define UART0_S1 *(volatile uint8_t *)0x4006A004 // UART Status Register 1
+#define UART_S1_TDRE (uint8_t)0x80 // Transmit Data Register Empty Flag
+#define UART_S1_TC (uint8_t)0x40 // Transmit Complete Flag
+#define UART_S1_RDRF (uint8_t)0x20 // Receive Data Register Full Flag
+#define UART_S1_IDLE (uint8_t)0x10 // Idle Line Flag
+#define UART_S1_OR (uint8_t)0x08 // Receiver Overrun Flag
+#define UART_S1_NF (uint8_t)0x04 // Noise Flag
+#define UART_S1_FE (uint8_t)0x02 // Framing Error Flag
+#define UART_S1_PF (uint8_t)0x01 // Parity Error Flag
+#define UART0_S2 *(volatile uint8_t *)0x4006A005 // UART Status Register 2
+#define UART0_C3 *(volatile uint8_t *)0x4006A006 // UART Control Register 3
+#define UART0_D *(volatile uint8_t *)0x4006A007 // UART Data Register
+#define UART0_MA1 *(volatile uint8_t *)0x4006A008 // UART Match Address Registers 1
+#define UART0_MA2 *(volatile uint8_t *)0x4006A009 // UART Match Address Registers 2
+#define UART0_C4 *(volatile uint8_t *)0x4006A00A // UART Control Register 4
+#define UART0_C5 *(volatile uint8_t *)0x4006A00B // UART Control Register 5
+#define UART0_ED *(volatile uint8_t *)0x4006A00C // UART Extended Data Register
+#define UART0_MODEM *(volatile uint8_t *)0x4006A00D // UART Modem Register
+#define UART0_IR *(volatile uint8_t *)0x4006A00E // UART Infrared Register
+#define UART0_PFIFO *(volatile uint8_t *)0x4006A010 // UART FIFO Parameters
+#define UART_PFIFO_TXFE (uint8_t)0x80
+#define UART_PFIFO_RXFE (uint8_t)0x08
+#define UART0_CFIFO *(volatile uint8_t *)0x4006A011 // UART FIFO Control Register
+#define UART_CFIFO_TXFLUSH (uint8_t)0x80 //
+#define UART_CFIFO_RXFLUSH (uint8_t)0x40 //
+#define UART_CFIFO_RXOFE (uint8_t)0x04 //
+#define UART_CFIFO_TXOFE (uint8_t)0x02 //
+#define UART_CFIFO_RXUFE (uint8_t)0x01 //
+#define UART0_SFIFO *(volatile uint8_t *)0x4006A012 // UART FIFO Status Register
+#define UART_SFIFO_TXEMPT (uint8_t)0x80
+#define UART_SFIFO_RXEMPT (uint8_t)0x40
+#define UART_SFIFO_RXOF (uint8_t)0x04
+#define UART_SFIFO_TXOF (uint8_t)0x02
+#define UART_SFIFO_RXUF (uint8_t)0x01
+#define UART0_TWFIFO *(volatile uint8_t *)0x4006A013 // UART FIFO Transmit Watermark
+#define UART0_TCFIFO *(volatile uint8_t *)0x4006A014 // UART FIFO Transmit Count
+#define UART0_RWFIFO *(volatile uint8_t *)0x4006A015 // UART FIFO Receive Watermark
+#define UART0_RCFIFO *(volatile uint8_t *)0x4006A016 // UART FIFO Receive Count
+#define UART0_C7816 *(volatile uint8_t *)0x4006A018 // UART 7816 Control Register
+#define UART0_IE7816 *(volatile uint8_t *)0x4006A019 // UART 7816 Interrupt Enable Register
+#define UART0_IS7816 *(volatile uint8_t *)0x4006A01A // UART 7816 Interrupt Status Register
+#define UART0_WP7816T0 *(volatile uint8_t *)0x4006A01B // UART 7816 Wait Parameter Register
+#define UART0_WP7816T1 *(volatile uint8_t *)0x4006A01B // UART 7816 Wait Parameter Register
+#define UART0_WN7816 *(volatile uint8_t *)0x4006A01C // UART 7816 Wait N Register
+#define UART0_WF7816 *(volatile uint8_t *)0x4006A01D // UART 7816 Wait FD Register
+#define UART0_ET7816 *(volatile uint8_t *)0x4006A01E // UART 7816 Error Threshold Register
+#define UART0_TL7816 *(volatile uint8_t *)0x4006A01F // UART 7816 Transmit Length Register
+#define UART0_C6 *(volatile uint8_t *)0x4006A021 // UART CEA709.1-B Control Register 6
+#define UART0_PCTH *(volatile uint8_t *)0x4006A022 // UART CEA709.1-B Packet Cycle Time Counter High
+#define UART0_PCTL *(volatile uint8_t *)0x4006A023 // UART CEA709.1-B Packet Cycle Time Counter Low
+#define UART0_B1T *(volatile uint8_t *)0x4006A024 // UART CEA709.1-B Beta1 Timer
+#define UART0_SDTH *(volatile uint8_t *)0x4006A025 // UART CEA709.1-B Secondary Delay Timer High
+#define UART0_SDTL *(volatile uint8_t *)0x4006A026 // UART CEA709.1-B Secondary Delay Timer Low
+#define UART0_PRE *(volatile uint8_t *)0x4006A027 // UART CEA709.1-B Preamble
+#define UART0_TPL *(volatile uint8_t *)0x4006A028 // UART CEA709.1-B Transmit Packet Length
+#define UART0_IE *(volatile uint8_t *)0x4006A029 // UART CEA709.1-B Interrupt Enable Register
+#define UART0_WB *(volatile uint8_t *)0x4006A02A // UART CEA709.1-B WBASE
+#define UART0_S3 *(volatile uint8_t *)0x4006A02B // UART CEA709.1-B Status Register
+#define UART0_S4 *(volatile uint8_t *)0x4006A02C // UART CEA709.1-B Status Register
+#define UART0_RPL *(volatile uint8_t *)0x4006A02D // UART CEA709.1-B Received Packet Length
+#define UART0_RPREL *(volatile uint8_t *)0x4006A02E // UART CEA709.1-B Received Preamble Length
+#define UART0_CPW *(volatile uint8_t *)0x4006A02F // UART CEA709.1-B Collision Pulse Width
+#define UART0_RIDT *(volatile uint8_t *)0x4006A030 // UART CEA709.1-B Receive Indeterminate Time
+#define UART0_TIDT *(volatile uint8_t *)0x4006A031 // UART CEA709.1-B Transmit Indeterminate Time
+#define UART1_BDH *(volatile uint8_t *)0x4006B000 // UART Baud Rate Registers: High
+#define UART1_BDL *(volatile uint8_t *)0x4006B001 // UART Baud Rate Registers: Low
+#define UART1_C1 *(volatile uint8_t *)0x4006B002 // UART Control Register 1
+#define UART1_C2 *(volatile uint8_t *)0x4006B003 // UART Control Register 2
+#define UART1_S1 *(volatile uint8_t *)0x4006B004 // UART Status Register 1
+#define UART1_S2 *(volatile uint8_t *)0x4006B005 // UART Status Register 2
+#define UART1_C3 *(volatile uint8_t *)0x4006B006 // UART Control Register 3
+#define UART1_D *(volatile uint8_t *)0x4006B007 // UART Data Register
+#define UART1_MA1 *(volatile uint8_t *)0x4006B008 // UART Match Address Registers 1
+#define UART1_MA2 *(volatile uint8_t *)0x4006B009 // UART Match Address Registers 2
+#define UART1_C4 *(volatile uint8_t *)0x4006B00A // UART Control Register 4
+#define UART1_C5 *(volatile uint8_t *)0x4006B00B // UART Control Register 5
+#define UART1_ED *(volatile uint8_t *)0x4006B00C // UART Extended Data Register
+#define UART1_MODEM *(volatile uint8_t *)0x4006B00D // UART Modem Register
+#define UART1_IR *(volatile uint8_t *)0x4006B00E // UART Infrared Register
+#define UART1_PFIFO *(volatile uint8_t *)0x4006B010 // UART FIFO Parameters
+#define UART1_CFIFO *(volatile uint8_t *)0x4006B011 // UART FIFO Control Register
+#define UART1_SFIFO *(volatile uint8_t *)0x4006B012 // UART FIFO Status Register
+#define UART1_TWFIFO *(volatile uint8_t *)0x4006B013 // UART FIFO Transmit Watermark
+#define UART1_TCFIFO *(volatile uint8_t *)0x4006B014 // UART FIFO Transmit Count
+#define UART1_RWFIFO *(volatile uint8_t *)0x4006B015 // UART FIFO Receive Watermark
+#define UART1_RCFIFO *(volatile uint8_t *)0x4006B016 // UART FIFO Receive Count
+#define UART1_C7816 *(volatile uint8_t *)0x4006B018 // UART 7816 Control Register
+#define UART1_IE7816 *(volatile uint8_t *)0x4006B019 // UART 7816 Interrupt Enable Register
+#define UART1_IS7816 *(volatile uint8_t *)0x4006B01A // UART 7816 Interrupt Status Register
+#define UART1_WP7816T0 *(volatile uint8_t *)0x4006B01B // UART 7816 Wait Parameter Register
+#define UART1_WP7816T1 *(volatile uint8_t *)0x4006B01B // UART 7816 Wait Parameter Register
+#define UART1_WN7816 *(volatile uint8_t *)0x4006B01C // UART 7816 Wait N Register
+#define UART1_WF7816 *(volatile uint8_t *)0x4006B01D // UART 7816 Wait FD Register
+#define UART1_ET7816 *(volatile uint8_t *)0x4006B01E // UART 7816 Error Threshold Register
+#define UART1_TL7816 *(volatile uint8_t *)0x4006B01F // UART 7816 Transmit Length Register
+#define UART1_C6 *(volatile uint8_t *)0x4006B021 // UART CEA709.1-B Control Register 6
+#define UART1_PCTH *(volatile uint8_t *)0x4006B022 // UART CEA709.1-B Packet Cycle Time Counter High
+#define UART1_PCTL *(volatile uint8_t *)0x4006B023 // UART CEA709.1-B Packet Cycle Time Counter Low
+#define UART1_B1T *(volatile uint8_t *)0x4006B024 // UART CEA709.1-B Beta1 Timer
+#define UART1_SDTH *(volatile uint8_t *)0x4006B025 // UART CEA709.1-B Secondary Delay Timer High
+#define UART1_SDTL *(volatile uint8_t *)0x4006B026 // UART CEA709.1-B Secondary Delay Timer Low
+#define UART1_PRE *(volatile uint8_t *)0x4006B027 // UART CEA709.1-B Preamble
+#define UART1_TPL *(volatile uint8_t *)0x4006B028 // UART CEA709.1-B Transmit Packet Length
+#define UART1_IE *(volatile uint8_t *)0x4006B029 // UART CEA709.1-B Interrupt Enable Register
+#define UART1_WB *(volatile uint8_t *)0x4006B02A // UART CEA709.1-B WBASE
+#define UART1_S3 *(volatile uint8_t *)0x4006B02B // UART CEA709.1-B Status Register
+#define UART1_S4 *(volatile uint8_t *)0x4006B02C // UART CEA709.1-B Status Register
+#define UART1_RPL *(volatile uint8_t *)0x4006B02D // UART CEA709.1-B Received Packet Length
+#define UART1_RPREL *(volatile uint8_t *)0x4006B02E // UART CEA709.1-B Received Preamble Length
+#define UART1_CPW *(volatile uint8_t *)0x4006B02F // UART CEA709.1-B Collision Pulse Width
+#define UART1_RIDT *(volatile uint8_t *)0x4006B030 // UART CEA709.1-B Receive Indeterminate Time
+#define UART1_TIDT *(volatile uint8_t *)0x4006B031 // UART CEA709.1-B Transmit Indeterminate Time
+#define UART2_BDH *(volatile uint8_t *)0x4006C000 // UART Baud Rate Registers: High
+#define UART2_BDL *(volatile uint8_t *)0x4006C001 // UART Baud Rate Registers: Low
+#define UART2_C1 *(volatile uint8_t *)0x4006C002 // UART Control Register 1
+#define UART2_C2 *(volatile uint8_t *)0x4006C003 // UART Control Register 2
+#define UART2_S1 *(volatile uint8_t *)0x4006C004 // UART Status Register 1
+#define UART2_S2 *(volatile uint8_t *)0x4006C005 // UART Status Register 2
+#define UART2_C3 *(volatile uint8_t *)0x4006C006 // UART Control Register 3
+#define UART2_D *(volatile uint8_t *)0x4006C007 // UART Data Register
+#define UART2_MA1 *(volatile uint8_t *)0x4006C008 // UART Match Address Registers 1
+#define UART2_MA2 *(volatile uint8_t *)0x4006C009 // UART Match Address Registers 2
+#define UART2_C4 *(volatile uint8_t *)0x4006C00A // UART Control Register 4
+#define UART2_C5 *(volatile uint8_t *)0x4006C00B // UART Control Register 5
+#define UART2_ED *(volatile uint8_t *)0x4006C00C // UART Extended Data Register
+#define UART2_MODEM *(volatile uint8_t *)0x4006C00D // UART Modem Register
+#define UART2_IR *(volatile uint8_t *)0x4006C00E // UART Infrared Register
+#define UART2_PFIFO *(volatile uint8_t *)0x4006C010 // UART FIFO Parameters
+#define UART2_CFIFO *(volatile uint8_t *)0x4006C011 // UART FIFO Control Register
+#define UART2_SFIFO *(volatile uint8_t *)0x4006C012 // UART FIFO Status Register
+#define UART2_TWFIFO *(volatile uint8_t *)0x4006C013 // UART FIFO Transmit Watermark
+#define UART2_TCFIFO *(volatile uint8_t *)0x4006C014 // UART FIFO Transmit Count
+#define UART2_RWFIFO *(volatile uint8_t *)0x4006C015 // UART FIFO Receive Watermark
+#define UART2_RCFIFO *(volatile uint8_t *)0x4006C016 // UART FIFO Receive Count
+#define UART2_C7816 *(volatile uint8_t *)0x4006C018 // UART 7816 Control Register
+#define UART2_IE7816 *(volatile uint8_t *)0x4006C019 // UART 7816 Interrupt Enable Register
+#define UART2_IS7816 *(volatile uint8_t *)0x4006C01A // UART 7816 Interrupt Status Register
+#define UART2_WP7816T0 *(volatile uint8_t *)0x4006C01B // UART 7816 Wait Parameter Register
+#define UART2_WP7816T1 *(volatile uint8_t *)0x4006C01B // UART 7816 Wait Parameter Register
+#define UART2_WN7816 *(volatile uint8_t *)0x4006C01C // UART 7816 Wait N Register
+#define UART2_WF7816 *(volatile uint8_t *)0x4006C01D // UART 7816 Wait FD Register
+#define UART2_ET7816 *(volatile uint8_t *)0x4006C01E // UART 7816 Error Threshold Register
+#define UART2_TL7816 *(volatile uint8_t *)0x4006C01F // UART 7816 Transmit Length Register
+#define UART2_C6 *(volatile uint8_t *)0x4006C021 // UART CEA709.1-B Control Register 6
+#define UART2_PCTH *(volatile uint8_t *)0x4006C022 // UART CEA709.1-B Packet Cycle Time Counter High
+#define UART2_PCTL *(volatile uint8_t *)0x4006C023 // UART CEA709.1-B Packet Cycle Time Counter Low
+#define UART2_B1T *(volatile uint8_t *)0x4006C024 // UART CEA709.1-B Beta1 Timer
+#define UART2_SDTH *(volatile uint8_t *)0x4006C025 // UART CEA709.1-B Secondary Delay Timer High
+#define UART2_SDTL *(volatile uint8_t *)0x4006C026 // UART CEA709.1-B Secondary Delay Timer Low
+#define UART2_PRE *(volatile uint8_t *)0x4006C027 // UART CEA709.1-B Preamble
+#define UART2_TPL *(volatile uint8_t *)0x4006C028 // UART CEA709.1-B Transmit Packet Length
+#define UART2_IE *(volatile uint8_t *)0x4006C029 // UART CEA709.1-B Interrupt Enable Register
+#define UART2_WB *(volatile uint8_t *)0x4006C02A // UART CEA709.1-B WBASE
+#define UART2_S3 *(volatile uint8_t *)0x4006C02B // UART CEA709.1-B Status Register
+#define UART2_S4 *(volatile uint8_t *)0x4006C02C // UART CEA709.1-B Status Register
+#define UART2_RPL *(volatile uint8_t *)0x4006C02D // UART CEA709.1-B Received Packet Length
+#define UART2_RPREL *(volatile uint8_t *)0x4006C02E // UART CEA709.1-B Received Preamble Length
+#define UART2_CPW *(volatile uint8_t *)0x4006C02F // UART CEA709.1-B Collision Pulse Width
+#define UART2_RIDT *(volatile uint8_t *)0x4006C030 // UART CEA709.1-B Receive Indeterminate Time
+#define UART2_TIDT *(volatile uint8_t *)0x4006C031 // UART CEA709.1-B Transmit Indeterminate Time
+
+// Chapter 46: Synchronous Audio Interface (SAI)
+#define I2S0_TCSR *(volatile uint32_t *)0x4002F000 // SAI Transmit Control Register
+#define I2S_TCSR_TE (uint32_t)0x80000000 // Transmitter Enable
+#define I2S_TCSR_STOPE (uint32_t)0x40000000 // Transmitter Enable in Stop mode
+#define I2S_TCSR_DBGE (uint32_t)0x20000000 // Transmitter Enable in Debug mode
+#define I2S_TCSR_BCE (uint32_t)0x10000000 // Bit Clock Enable
+#define I2S_TCSR_FR (uint32_t)0x02000000 // FIFO Reset
+#define I2S_TCSR_SR (uint32_t)0x01000000 // Software Reset
+#define I2S_TCSR_WSF (uint32_t)0x00100000 // Word Start Flag
+#define I2S_TCSR_SEF (uint32_t)0x00080000 // Sync Error Flag
+#define I2S_TCSR_FEF (uint32_t)0x00040000 // FIFO Error Flag (underrun)
+#define I2S_TCSR_FWF (uint32_t)0x00020000 // FIFO Warning Flag (empty)
+#define I2S_TCSR_FRF (uint32_t)0x00010000 // FIFO Request Flag (Data Ready)
+#define I2S_TCSR_WSIE (uint32_t)0x00001000 // Word Start Interrupt Enable
+#define I2S_TCSR_SEIE (uint32_t)0x00000800 // Sync Error Interrupt Enable
+#define I2S_TCSR_FEIE (uint32_t)0x00000400 // FIFO Error Interrupt Enable
+#define I2S_TCSR_FWIE (uint32_t)0x00000200 // FIFO Warning Interrupt Enable
+#define I2S_TCSR_FRIE (uint32_t)0x00000100 // FIFO Request Interrupt Enable
+#define I2S_TCSR_FWDE (uint32_t)0x00000002 // FIFO Warning DMA Enable
+#define I2S_TCSR_FRDE (uint32_t)0x00000001 // FIFO Request DMA Enable
+#define I2S0_TCR1 *(volatile uint32_t *)0x4002F004 // SAI Transmit Configuration 1 Register
+#define I2S_TCR1_TFW(n) ((uint32_t)n & 0x03) // Transmit FIFO watermark
+#define I2S0_TCR2 *(volatile uint32_t *)0x4002F008 // SAI Transmit Configuration 2 Register
+#define I2S_TCR2_DIV(n) ((uint32_t)n & 0xff) // Bit clock divide by (DIV+1)*2
+#define I2S_TCR2_BCD ((uint32_t)1<<24) // Bit clock direction
+#define I2S_TCR2_BCP ((uint32_t)1<<25) // Bit clock polarity
+#define I2S_TCR2_MSEL(n) ((uint32_t)(n & 3)<<26) // MCLK select, 0=bus clock, 1=I2S0_MCLK
+#define I2S_TCR2_BCI ((uint32_t)1<<28) // Bit clock input
+#define I2S_TCR2_BCS ((uint32_t)1<<29) // Bit clock swap
+#define I2S_TCR2_SYNC(n) ((uint32_t)(n & 3)<<30) // 0=async 1=sync with receiver
+#define I2S0_TCR3 *(volatile uint32_t *)0x4002F00C // SAI Transmit Configuration 3 Register
+#define I2S_TCR3_WDFL(n) ((uint32_t)n & 0x0f) // word flag configuration
+#define I2S_TCR3_TCE ((uint32_t)0x10000) // transmit channel enable
+#define I2S0_TCR4 *(volatile uint32_t *)0x4002F010 // SAI Transmit Configuration 4 Register
+#define I2S_TCR4_FSD ((uint32_t)1) // Frame Sync Direction
+#define I2S_TCR4_FSP ((uint32_t)2) // Frame Sync Polarity
+#define I2S_TCR4_FSE ((uint32_t)8) // Frame Sync Early
+#define I2S_TCR4_MF ((uint32_t)0x10) // MSB First
+#define I2S_TCR4_SYWD(n) ((uint32_t)(n & 0x1f)<<8) // Sync Width
+#define I2S_TCR4_FRSZ(n) ((uint32_t)(n & 0x0f)<<16) // Frame Size
+#define I2S0_TCR5 *(volatile uint32_t *)0x4002F014 // SAI Transmit Configuration 5 Register
+#define I2S_TCR5_FBT(n) ((uint32_t)(n & 0x1f)<<8) // First Bit Shifted
+#define I2S_TCR5_W0W(n) ((uint32_t)(n & 0x1f)<<16) // Word 0 Width
+#define I2S_TCR5_WNW(n) ((uint32_t)(n & 0x1f)<<24) // Word N Width
+#define I2S0_TDR0 *(volatile uint32_t *)0x4002F020 // SAI Transmit Data Register
+#define I2S0_TDR1 *(volatile uint32_t *)0x4002F024 // SAI Transmit Data Register
+#define I2S0_TFR0 *(volatile uint32_t *)0x4002F040 // SAI Transmit FIFO Register
+#define I2S0_TFR1 *(volatile uint32_t *)0x4002F044 // SAI Transmit FIFO Register
+#define I2S_TFR_RFP(n) ((uint32_t)n & 7) // read FIFO pointer
+#define I2S_TFR_WFP(n) ((uint32_t)(n & 7)<<16) // write FIFO pointer
+#define I2S0_TMR *(volatile uint32_t *)0x4002F060 // SAI Transmit Mask Register
+#define I2S_TMR_TWM(n) ((uint32_t)n & 0xFFFFFFFF)
+#define I2S0_RCSR *(volatile uint32_t *)0x4002F080 // SAI Receive Control Register
+#define I2S_RCSR_RE (uint32_t)0x80000000 // Receiver Enable
+#define I2S_RCSR_STOPE (uint32_t)0x40000000 // Receiver Enable in Stop mode
+#define I2S_RCSR_DBGE (uint32_t)0x20000000 // Receiver Enable in Debug mode
+#define I2S_RCSR_BCE (uint32_t)0x10000000 // Bit Clock Enable
+#define I2S_RCSR_FR (uint32_t)0x02000000 // FIFO Reset
+#define I2S_RCSR_SR (uint32_t)0x01000000 // Software Reset
+#define I2S_RCSR_WSF (uint32_t)0x00100000 // Word Start Flag
+#define I2S_RCSR_SEF (uint32_t)0x00080000 // Sync Error Flag
+#define I2S_RCSR_FEF (uint32_t)0x00040000 // FIFO Error Flag (underrun)
+#define I2S_RCSR_FWF (uint32_t)0x00020000 // FIFO Warning Flag (empty)
+#define I2S_RCSR_FRF (uint32_t)0x00010000 // FIFO Request Flag (Data Ready)
+#define I2S_RCSR_WSIE (uint32_t)0x00001000 // Word Start Interrupt Enable
+#define I2S_RCSR_SEIE (uint32_t)0x00000800 // Sync Error Interrupt Enable
+#define I2S_RCSR_FEIE (uint32_t)0x00000400 // FIFO Error Interrupt Enable
+#define I2S_RCSR_FWIE (uint32_t)0x00000200 // FIFO Warning Interrupt Enable
+#define I2S_RCSR_FRIE (uint32_t)0x00000100 // FIFO Request Interrupt Enable
+#define I2S_RCSR_FWDE (uint32_t)0x00000002 // FIFO Warning DMA Enable
+#define I2S_RCSR_FRDE (uint32_t)0x00000001 // FIFO Request DMA Enable
+#define I2S0_RCR1 *(volatile uint32_t *)0x4002F084 // SAI Receive Configuration 1 Register
+#define I2S_RCR1_RFW(n) ((uint32_t)n & 0x03) // Receive FIFO watermark
+#define I2S0_RCR2 *(volatile uint32_t *)0x4002F088 // SAI Receive Configuration 2 Register
+#define I2S_RCR2_DIV(n) ((uint32_t)n & 0xff) // Bit clock divide by (DIV+1)*2
+#define I2S_RCR2_BCD ((uint32_t)1<<24) // Bit clock direction
+#define I2S_RCR2_BCP ((uint32_t)1<<25) // Bit clock polarity
+#define I2S_RCR2_MSEL(n) ((uint32_t)(n & 3)<<26) // MCLK select, 0=bus clock, 1=I2S0_MCLK
+#define I2S_RCR2_BCI ((uint32_t)1<<28) // Bit clock input
+#define I2S_RCR2_BCS ((uint32_t)1<<29) // Bit clock swap
+#define I2S_RCR2_SYNC(n) ((uint32_t)(n & 3)<<30) // 0=async 1=sync with receiver
+#define I2S0_RCR3 *(volatile uint32_t *)0x4002F08C // SAI Receive Configuration 3 Register
+#define I2S_RCR3_WDFL(n) ((uint32_t)n & 0x0f) // word flag configuration
+#define I2S_RCR3_RCE ((uint32_t)0x10000) // receive channel enable
+#define I2S0_RCR4 *(volatile uint32_t *)0x4002F090 // SAI Receive Configuration 4 Register
+#define I2S_RCR4_FSD ((uint32_t)1) // Frame Sync Direction
+#define I2S_RCR4_FSP ((uint32_t)2) // Frame Sync Polarity
+#define I2S_RCR4_FSE ((uint32_t)8) // Frame Sync Early
+#define I2S_RCR4_MF ((uint32_t)0x10) // MSB First
+#define I2S_RCR4_SYWD(n) ((uint32_t)(n & 0x1f)<<8) // Sync Width
+#define I2S_RCR4_FRSZ(n) ((uint32_t)(n & 0x0f)<<16) // Frame Size
+#define I2S0_RCR5 *(volatile uint32_t *)0x4002F094 // SAI Receive Configuration 5 Register
+#define I2S_RCR5_FBT(n) ((uint32_t)(n & 0x1f)<<8) // First Bit Shifted
+#define I2S_RCR5_W0W(n) ((uint32_t)(n & 0x1f)<<16) // Word 0 Width
+#define I2S_RCR5_WNW(n) ((uint32_t)(n & 0x1f)<<24) // Word N Width
+#define I2S0_RDR0 *(volatile uint32_t *)0x4002F0A0 // SAI Receive Data Register
+#define I2S0_RDR1 *(volatile uint32_t *)0x4002F0A4 // SAI Receive Data Register
+#define I2S0_RFR0 *(volatile uint32_t *)0x4002F0C0 // SAI Receive FIFO Register
+#define I2S0_RFR1 *(volatile uint32_t *)0x4002F0C4 // SAI Receive FIFO Register
+#define I2S_RFR_RFP(n) ((uint32_t)n & 7) // read FIFO pointer
+#define I2S_RFR_WFP(n) ((uint32_t)(n & 7)<<16) // write FIFO pointer
+#define I2S0_RMR *(volatile uint32_t *)0x4002F0E0 // SAI Receive Mask Register
+#define I2S_RMR_RWM(n) ((uint32_t)n & 0xFFFFFFFF)
+#define I2S0_MCR *(volatile uint32_t *)0x4002F100 // SAI MCLK Control Register
+#define I2S_MCR_DUF ((uint32_t)1<<31) // Divider Update Flag
+#define I2S_MCR_MOE ((uint32_t)1<<30) // MCLK Output Enable
+#define I2S_MCR_MICS(n) ((uint32_t)(n & 3)<<24) // MCLK Input Clock Select
+#define I2S0_MDR *(volatile uint32_t *)0x4002F104 // SAI MCLK Divide Register
+#define I2S_MDR_FRACT(n) ((uint32_t)(n & 0xff)<<12) // MCLK Fraction
+#define I2S_MDR_DIVIDE(n) ((uint32_t)(n & 0xfff)) // MCLK Divide
+
+// Chapter 47: General-Purpose Input/Output (GPIO)
+#define GPIOA_PDOR *(volatile uint32_t *)0x400FF000 // Port Data Output Register
+#define GPIOA_PSOR *(volatile uint32_t *)0x400FF004 // Port Set Output Register
+#define GPIOA_PCOR *(volatile uint32_t *)0x400FF008 // Port Clear Output Register
+#define GPIOA_PTOR *(volatile uint32_t *)0x400FF00C // Port Toggle Output Register
+#define GPIOA_PDIR *(volatile uint32_t *)0x400FF010 // Port Data Input Register
+#define GPIOA_PDDR *(volatile uint32_t *)0x400FF014 // Port Data Direction Register
+#define GPIOB_PDOR *(volatile uint32_t *)0x400FF040 // Port Data Output Register
+#define GPIOB_PSOR *(volatile uint32_t *)0x400FF044 // Port Set Output Register
+#define GPIOB_PCOR *(volatile uint32_t *)0x400FF048 // Port Clear Output Register
+#define GPIOB_PTOR *(volatile uint32_t *)0x400FF04C // Port Toggle Output Register
+#define GPIOB_PDIR *(volatile uint32_t *)0x400FF050 // Port Data Input Register
+#define GPIOB_PDDR *(volatile uint32_t *)0x400FF054 // Port Data Direction Register
+#define GPIOC_PDOR *(volatile uint32_t *)0x400FF080 // Port Data Output Register
+#define GPIOC_PSOR *(volatile uint32_t *)0x400FF084 // Port Set Output Register
+#define GPIOC_PCOR *(volatile uint32_t *)0x400FF088 // Port Clear Output Register
+#define GPIOC_PTOR *(volatile uint32_t *)0x400FF08C // Port Toggle Output Register
+#define GPIOC_PDIR *(volatile uint32_t *)0x400FF090 // Port Data Input Register
+#define GPIOC_PDDR *(volatile uint32_t *)0x400FF094 // Port Data Direction Register
+#define GPIOD_PDOR *(volatile uint32_t *)0x400FF0C0 // Port Data Output Register
+#define GPIOD_PSOR *(volatile uint32_t *)0x400FF0C4 // Port Set Output Register
+#define GPIOD_PCOR *(volatile uint32_t *)0x400FF0C8 // Port Clear Output Register
+#define GPIOD_PTOR *(volatile uint32_t *)0x400FF0CC // Port Toggle Output Register
+#define GPIOD_PDIR *(volatile uint32_t *)0x400FF0D0 // Port Data Input Register
+#define GPIOD_PDDR *(volatile uint32_t *)0x400FF0D4 // Port Data Direction Register
+#define GPIOE_PDOR *(volatile uint32_t *)0x400FF100 // Port Data Output Register
+#define GPIOE_PSOR *(volatile uint32_t *)0x400FF104 // Port Set Output Register
+#define GPIOE_PCOR *(volatile uint32_t *)0x400FF108 // Port Clear Output Register
+#define GPIOE_PTOR *(volatile uint32_t *)0x400FF10C // Port Toggle Output Register
+#define GPIOE_PDIR *(volatile uint32_t *)0x400FF110 // Port Data Input Register
+#define GPIOE_PDDR *(volatile uint32_t *)0x400FF114 // Port Data Direction Register
+
+// Chapter 48: Touch sense input (TSI)
+#define TSI0_GENCS *(volatile uint32_t *)0x40045000 // General Control and Status Register
+#define TSI_GENCS_LPCLKS (uint32_t)0x10000000 //
+#define TSI_GENCS_LPSCNITV(n) (((n) & 15) << 24) //
+#define TSI_GENCS_NSCN(n) (((n) & 31) << 19) //
+#define TSI_GENCS_PS(n) (((n) & 7) << 16) //
+#define TSI_GENCS_EOSF (uint32_t)0x00008000 //
+#define TSI_GENCS_OUTRGF (uint32_t)0x00004000 //
+#define TSI_GENCS_EXTERF (uint32_t)0x00002000 //
+#define TSI_GENCS_OVRF (uint32_t)0x00001000 //
+#define TSI_GENCS_SCNIP (uint32_t)0x00000200 //
+#define TSI_GENCS_SWTS (uint32_t)0x00000100 //
+#define TSI_GENCS_TSIEN (uint32_t)0x00000080 //
+#define TSI_GENCS_TSIIE (uint32_t)0x00000040 //
+#define TSI_GENCS_ERIE (uint32_t)0x00000020 //
+#define TSI_GENCS_ESOR (uint32_t)0x00000010 //
+#define TSI_GENCS_STM (uint32_t)0x00000002 //
+#define TSI_GENCS_STPE (uint32_t)0x00000001 //
+#define TSI0_SCANC *(volatile uint32_t *)0x40045004 // SCAN Control Register
+#define TSI_SCANC_REFCHRG(n) (((n) & 15) << 24) //
+#define TSI_SCANC_EXTCHRG(n) (((n) & 7) << 16) //
+#define TSI_SCANC_SMOD(n) (((n) & 255) << 8) //
+#define TSI_SCANC_AMCLKS(n) (((n) & 3) << 3) //
+#define TSI_SCANC_AMPSC(n) (((n) & 7) << 0) //
+#define TSI0_PEN *(volatile uint32_t *)0x40045008 // Pin Enable Register
+#define TSI0_WUCNTR *(volatile uint32_t *)0x4004500C // Wake-Up Channel Counter Register
+#define TSI0_CNTR1 *(volatile uint32_t *)0x40045100 // Counter Register
+#define TSI0_CNTR3 *(volatile uint32_t *)0x40045104 // Counter Register
+#define TSI0_CNTR5 *(volatile uint32_t *)0x40045108 // Counter Register
+#define TSI0_CNTR7 *(volatile uint32_t *)0x4004510C // Counter Register
+#define TSI0_CNTR9 *(volatile uint32_t *)0x40045110 // Counter Register
+#define TSI0_CNTR11 *(volatile uint32_t *)0x40045114 // Counter Register
+#define TSI0_CNTR13 *(volatile uint32_t *)0x40045118 // Counter Register
+#define TSI0_CNTR15 *(volatile uint32_t *)0x4004511C // Counter Register
+#define TSI0_THRESHOLD *(volatile uint32_t *)0x40045120 // Low Power Channel Threshold Register
+
+// Nested Vectored Interrupt Controller, Table 3-4 & ARMv7 ref, appendix B3.4 (page 750)
+#define NVIC_ENABLE_IRQ(n) (*((volatile uint32_t *)0xE000E100 + (n >> 5)) = (1 << (n & 31)))
+#define NVIC_DISABLE_IRQ(n) (*((volatile uint32_t *)0xE000E180 + (n >> 5)) = (1 << (n & 31)))
+#define NVIC_SET_PENDING(n) (*((volatile uint32_t *)0xE000E200 + (n >> 5)) = (1 << (n & 31)))
+#define NVIC_CLEAR_PENDING(n) (*((volatile uint32_t *)0xE000E280 + (n >> 5)) = (1 << (n & 31)))
+
+#define NVIC_ISER0 *(volatile uint32_t *)0xE000E100
+#define NVIC_ISER1 *(volatile uint32_t *)0xE000E104
+#define NVIC_ICER0 *(volatile uint32_t *)0xE000E180
+#define NVIC_ICER1 *(volatile uint32_t *)0xE000E184
+
+// 0 = highest priority
+// Cortex-M4: 0,16,32,48,64,80,96,112,128,144,160,176,192,208,224,240
+// Cortex-M0: 0,64,128,192
+#define NVIC_SET_PRIORITY(irqnum, priority) (*((volatile uint8_t *)0xE000E400 + (irqnum)) = (uint8_t)(priority))
+#define NVIC_GET_PRIORITY(irqnum) (*((uint8_t *)0xE000E400 + (irqnum)))
+
+#if defined(__MK20DX128__)
+#define IRQ_DMA_CH0 0
+#define IRQ_DMA_CH1 1
+#define IRQ_DMA_CH2 2
+#define IRQ_DMA_CH3 3
+#define IRQ_DMA_ERROR 4
+#define IRQ_FTFL_COMPLETE 6
+#define IRQ_FTFL_COLLISION 7
+#define IRQ_LOW_VOLTAGE 8
+#define IRQ_LLWU 9
+#define IRQ_WDOG 10
+#define IRQ_I2C0 11
+#define IRQ_SPI0 12
+#define IRQ_I2S0_TX 13
+#define IRQ_I2S0_RX 14
+#define IRQ_UART0_LON 15
+#define IRQ_UART0_STATUS 16
+#define IRQ_UART0_ERROR 17
+#define IRQ_UART1_STATUS 18
+#define IRQ_UART1_ERROR 19
+#define IRQ_UART2_STATUS 20
+#define IRQ_UART2_ERROR 21
+#define IRQ_ADC0 22
+#define IRQ_CMP0 23
+#define IRQ_CMP1 24
+#define IRQ_FTM0 25
+#define IRQ_FTM1 26
+#define IRQ_CMT 27
+#define IRQ_RTC_ALARM 28
+#define IRQ_RTC_SECOND 29
+#define IRQ_PIT_CH0 30
+#define IRQ_PIT_CH1 31
+#define IRQ_PIT_CH2 32
+#define IRQ_PIT_CH3 33
+#define IRQ_PDB 34
+#define IRQ_USBOTG 35
+#define IRQ_USBDCD 36
+#define IRQ_TSI 37
+#define IRQ_MCG 38
+#define IRQ_LPTMR 39
+#define IRQ_PORTA 40
+#define IRQ_PORTB 41
+#define IRQ_PORTC 42
+#define IRQ_PORTD 43
+#define IRQ_PORTE 44
+#define IRQ_SOFTWARE 45
+#define NVIC_NUM_INTERRUPTS 46
+
+#elif defined(__MK20DX256__)
+#define IRQ_DMA_CH0 0
+#define IRQ_DMA_CH1 1
+#define IRQ_DMA_CH2 2
+#define IRQ_DMA_CH3 3
+#define IRQ_DMA_CH4 4
+#define IRQ_DMA_CH5 5
+#define IRQ_DMA_CH6 6
+#define IRQ_DMA_CH7 7
+#define IRQ_DMA_CH8 8
+#define IRQ_DMA_CH9 9
+#define IRQ_DMA_CH10 10
+#define IRQ_DMA_CH11 11
+#define IRQ_DMA_CH12 12
+#define IRQ_DMA_CH13 13
+#define IRQ_DMA_CH14 14
+#define IRQ_DMA_CH15 15
+#define IRQ_DMA_ERROR 16
+#define IRQ_FTFL_COMPLETE 18
+#define IRQ_FTFL_COLLISION 19
+#define IRQ_LOW_VOLTAGE 20
+#define IRQ_LLWU 21
+#define IRQ_WDOG 22
+#define IRQ_I2C0 24
+#define IRQ_I2C1 25
+#define IRQ_SPI0 26
+#define IRQ_SPI1 27
+#define IRQ_CAN_MESSAGE 29
+#define IRQ_CAN_BUS_OFF 30
+#define IRQ_CAN_ERROR 31
+#define IRQ_CAN_TX_WARN 32
+#define IRQ_CAN_RX_WARN 33
+#define IRQ_CAN_WAKEUP 34
+#define IRQ_I2S0_TX 35
+#define IRQ_I2S0_RX 36
+#define IRQ_UART0_LON 44
+#define IRQ_UART0_STATUS 45
+#define IRQ_UART0_ERROR 46
+#define IRQ_UART1_STATUS 47
+#define IRQ_UART1_ERROR 48
+#define IRQ_UART2_STATUS 49
+#define IRQ_UART2_ERROR 50
+#define IRQ_ADC0 57
+#define IRQ_ADC1 58
+#define IRQ_CMP0 59
+#define IRQ_CMP1 60
+#define IRQ_CMP2 61
+#define IRQ_FTM0 62
+#define IRQ_FTM1 63
+#define IRQ_FTM2 64
+#define IRQ_CMT 65
+#define IRQ_RTC_ALARM 66
+#define IRQ_RTC_SECOND 67
+#define IRQ_PIT_CH0 68
+#define IRQ_PIT_CH1 69
+#define IRQ_PIT_CH2 70
+#define IRQ_PIT_CH3 71
+#define IRQ_PDB 72
+#define IRQ_USBOTG 73
+#define IRQ_USBDCD 74
+#define IRQ_DAC0 81
+#define IRQ_TSI 83
+#define IRQ_MCG 84
+#define IRQ_LPTMR 85
+#define IRQ_PORTA 87
+#define IRQ_PORTB 88
+#define IRQ_PORTC 89
+#define IRQ_PORTD 90
+#define IRQ_PORTE 91
+#define IRQ_SOFTWARE 94
+#define NVIC_NUM_INTERRUPTS 95
+
+#endif
+
+
+
+
+
+#define __disable_irq() __asm__ volatile("CPSID i");
+#define __enable_irq() __asm__ volatile("CPSIE i");
+
+// System Control Space (SCS), ARMv7 ref manual, B3.2, page 708
+#define SCB_CPUID *(const uint32_t *)0xE000ED00 // CPUID Base Register
+#define SCB_ICSR *(volatile uint32_t *)0xE000ED04 // Interrupt Control and State
+#define SCB_ICSR_PENDSTSET (uint32_t)0x04000000
+#define SCB_VTOR *(volatile uint32_t *)0xE000ED08 // Vector Table Offset
+#define SCB_AIRCR *(volatile uint32_t *)0xE000ED0C // Application Interrupt and Reset Control
+#define SCB_SCR *(volatile uint32_t *)0xE000ED10 // System Control Register
+#define SCB_CCR *(volatile uint32_t *)0xE000ED14 // Configuration and Control
+#define SCB_SHPR1 *(volatile uint32_t *)0xE000ED18 // System Handler Priority Register 1
+#define SCB_SHPR2 *(volatile uint32_t *)0xE000ED1C // System Handler Priority Register 2
+#define SCB_SHPR3 *(volatile uint32_t *)0xE000ED20 // System Handler Priority Register 3
+#define SCB_SHCSR *(volatile uint32_t *)0xE000ED24 // System Handler Control and State
+#define SCB_CFSR *(volatile uint32_t *)0xE000ED28 // Configurable Fault Status Register
+#define SCB_HFSR *(volatile uint32_t *)0xE000ED2C // HardFault Status
+#define SCB_DFSR *(volatile uint32_t *)0xE000ED30 // Debug Fault Status
+#define SCB_MMFAR *(volatile uint32_t *)0xE000ED34 // MemManage Fault Address
+
+#define SYST_CSR *(volatile uint32_t *)0xE000E010 // SysTick Control and Status
+#define SYST_CSR_COUNTFLAG (uint32_t)0x00010000
+#define SYST_CSR_CLKSOURCE (uint32_t)0x00000004
+#define SYST_CSR_TICKINT (uint32_t)0x00000002
+#define SYST_CSR_ENABLE (uint32_t)0x00000001
+#define SYST_RVR *(volatile uint32_t *)0xE000E014 // SysTick Reload Value Register
+#define SYST_CVR *(volatile uint32_t *)0xE000E018 // SysTick Current Value Register
+#define SYST_CALIB *(const uint32_t *)0xE000E01C // SysTick Calibration Value
+
+
+#define ARM_DEMCR *(volatile uint32_t *)0xE000EDFC // Debug Exception and Monitor Control
+#define ARM_DEMCR_TRCENA (1 << 24) // Enable debugging & monitoring blocks
+#define ARM_DWT_CTRL *(volatile uint32_t *)0xE0001000 // DWT control register
+#define ARM_DWT_CTRL_CYCCNTENA (1 << 0) // Enable cycle count
+#define ARM_DWT_CYCCNT *(volatile uint32_t *)0xE0001004 // Cycle count register
+
+extern int nvic_execution_priority(void);
+
+extern void nmi_isr(void);
+extern void hard_fault_isr(void);
+extern void memmanage_fault_isr(void);
+extern void bus_fault_isr(void);
+extern void usage_fault_isr(void);
+extern void svcall_isr(void);
+extern void debugmonitor_isr(void);
+extern void pendablesrvreq_isr(void);
+extern void systick_isr(void);
+extern void dma_ch0_isr(void);
+extern void dma_ch1_isr(void);
+extern void dma_ch2_isr(void);
+extern void dma_ch3_isr(void);
+extern void dma_ch4_isr(void);
+extern void dma_ch5_isr(void);
+extern void dma_ch6_isr(void);
+extern void dma_ch7_isr(void);
+extern void dma_ch8_isr(void);
+extern void dma_ch9_isr(void);
+extern void dma_ch10_isr(void);
+extern void dma_ch11_isr(void);
+extern void dma_ch12_isr(void);
+extern void dma_ch13_isr(void);
+extern void dma_ch14_isr(void);
+extern void dma_ch15_isr(void);
+extern void dma_error_isr(void);
+extern void mcm_isr(void);
+extern void flash_cmd_isr(void);
+extern void flash_error_isr(void);
+extern void low_voltage_isr(void);
+extern void wakeup_isr(void);
+extern void watchdog_isr(void);
+extern void i2c0_isr(void);
+extern void i2c1_isr(void);
+extern void i2c2_isr(void);
+extern void spi0_isr(void);
+extern void spi1_isr(void);
+extern void spi2_isr(void);
+extern void sdhc_isr(void);
+extern void can0_message_isr(void);
+extern void can0_bus_off_isr(void);
+extern void can0_error_isr(void);
+extern void can0_tx_warn_isr(void);
+extern void can0_rx_warn_isr(void);
+extern void can0_wakeup_isr(void);
+extern void i2s0_tx_isr(void);
+extern void i2s0_rx_isr(void);
+extern void uart0_lon_isr(void);
+extern void uart0_status_isr(void);
+extern void uart0_error_isr(void);
+extern void uart1_status_isr(void);
+extern void uart1_error_isr(void);
+extern void uart2_status_isr(void);
+extern void uart2_error_isr(void);
+extern void uart3_status_isr(void);
+extern void uart3_error_isr(void);
+extern void uart4_status_isr(void);
+extern void uart4_error_isr(void);
+extern void uart5_status_isr(void);
+extern void uart5_error_isr(void);
+extern void adc0_isr(void);
+extern void adc1_isr(void);
+extern void cmp0_isr(void);
+extern void cmp1_isr(void);
+extern void cmp2_isr(void);
+extern void ftm0_isr(void);
+extern void ftm1_isr(void);
+extern void ftm2_isr(void);
+extern void ftm3_isr(void);
+extern void cmt_isr(void);
+extern void rtc_alarm_isr(void);
+extern void rtc_seconds_isr(void);
+extern void pit0_isr(void);
+extern void pit1_isr(void);
+extern void pit2_isr(void);
+extern void pit3_isr(void);
+extern void pdb_isr(void);
+extern void usb_isr(void);
+extern void usb_charge_isr(void);
+extern void dac0_isr(void);
+extern void dac1_isr(void);
+extern void tsi0_isr(void);
+extern void mcg_isr(void);
+extern void lptmr_isr(void);
+extern void porta_isr(void);
+extern void portb_isr(void);
+extern void portc_isr(void);
+extern void portd_isr(void);
+extern void porte_isr(void);
+extern void software_isr(void);
+
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/ports/teensy/core/pins_arduino.h b/ports/teensy/core/pins_arduino.h
new file mode 100644
index 000000000..03674933c
--- /dev/null
+++ b/ports/teensy/core/pins_arduino.h
@@ -0,0 +1,113 @@
+/* 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.
+ */
+
+#ifndef pins_macros_for_arduino_compatibility_h
+#define pins_macros_for_arduino_compatibility_h
+
+#include <stdint.h>
+
+const static uint8_t A0 = 14;
+const static uint8_t A1 = 15;
+const static uint8_t A2 = 16;
+const static uint8_t A3 = 17;
+const static uint8_t A4 = 18;
+const static uint8_t A5 = 19;
+const static uint8_t A6 = 20;
+const static uint8_t A7 = 21;
+const static uint8_t A8 = 22;
+const static uint8_t A9 = 23;
+const static uint8_t A10 = 34;
+const static uint8_t A11 = 35;
+const static uint8_t A12 = 36;
+const static uint8_t A13 = 37;
+const static uint8_t A14 = 40;
+
+const static uint8_t A15 = 26;
+const static uint8_t A16 = 27;
+const static uint8_t A17 = 28;
+const static uint8_t A18 = 29;
+const static uint8_t A19 = 30;
+const static uint8_t A20 = 31;
+
+const static uint8_t SS = 10;
+const static uint8_t MOSI = 11;
+const static uint8_t MISO = 12;
+const static uint8_t SCK = 13;
+const static uint8_t LED_BUILTIN = 13;
+const static uint8_t SDA = 18;
+const static uint8_t SCL = 19;
+
+
+#define NUM_DIGITAL_PINS 34
+#define NUM_ANALOG_INPUTS 14
+
+#define analogInputToDigitalPin(p) (((p) < 10) ? (p) + 14 : -1)
+#define digitalPinHasPWM(p) (((p) >= 3 && (p) <= 6) || (p) == 9 || (p) == 10 || ((p) >= 20 && (p) <= 23))
+
+#define NOT_AN_INTERRUPT -1
+#define digitalPinToInterrupt(p) ((p) < NUM_DIGITAL_PINS ? (p) : -1)
+
+
+struct digital_pin_bitband_and_config_table_struct {
+ volatile uint32_t *reg;
+ volatile uint32_t *config;
+};
+extern const struct digital_pin_bitband_and_config_table_struct digital_pin_to_info_PGM[];
+
+// compatibility macros
+#define digitalPinToPort(pin) (pin)
+#define digitalPinToBitMask(pin) (1)
+#define portOutputRegister(pin) ((volatile uint8_t *)(digital_pin_to_info_PGM[(pin)].reg + 0))
+#define portSetRegister(pin) ((volatile uint8_t *)(digital_pin_to_info_PGM[(pin)].reg + 32))
+#define portClearRegister(pin) ((volatile uint8_t *)(digital_pin_to_info_PGM[(pin)].reg + 64))
+#define portToggleRegister(pin) ((volatile uint8_t *)(digital_pin_to_info_PGM[(pin)].reg + 96))
+#define portInputRegister(pin) ((volatile uint8_t *)(digital_pin_to_info_PGM[(pin)].reg + 128))
+#define portModeRegister(pin) ((volatile uint8_t *)(digital_pin_to_info_PGM[(pin)].reg + 160))
+#define portConfigRegister(pin) ((volatile uint32_t *)(digital_pin_to_info_PGM[(pin)].config))
+
+
+#define digitalPinToPortReg(pin) (portOutputRegister(pin))
+#define digitalPinToBit(pin) (1)
+
+
+#define NOT_ON_TIMER 0
+static inline uint8_t digitalPinToTimer(uint8_t) __attribute__((always_inline, unused));
+static inline uint8_t digitalPinToTimer(uint8_t pin)
+{
+ if (pin >= 3 && pin <= 6) return pin - 2;
+ if (pin >= 9 && pin <= 10) return pin - 4;
+ if (pin >= 20 && pin <= 23) return pin - 13;
+ return NOT_ON_TIMER;
+}
+
+
+
+
+#endif
diff --git a/ports/teensy/core/pins_teensy.c b/ports/teensy/core/pins_teensy.c
new file mode 100644
index 000000000..b28f94a9e
--- /dev/null
+++ b/ports/teensy/core/pins_teensy.c
@@ -0,0 +1,817 @@
+/* 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.
+ */
+
+#include "core_pins.h"
+#include "pins_arduino.h"
+#include "HardwareSerial.h"
+
+#if 0
+// moved to pins_arduino.h
+struct digital_pin_bitband_and_config_table_struct {
+ volatile uint32_t *reg;
+ volatile uint32_t *config;
+};
+const struct digital_pin_bitband_and_config_table_struct digital_pin_to_info_PGM[];
+
+// compatibility macros
+#define digitalPinToPort(pin) (pin)
+#define digitalPinToBitMask(pin) (1)
+#define portOutputRegister(pin) ((volatile uint8_t *)(digital_pin_to_info_PGM[(pin)].reg + 0))
+#define portSetRegister(pin) ((volatile uint8_t *)(digital_pin_to_info_PGM[(pin)].reg + 32))
+#define portClearRegister(pin) ((volatile uint8_t *)(digital_pin_to_info_PGM[(pin)].reg + 64))
+#define portToggleRegister(pin) ((volatile uint8_t *)(digital_pin_to_info_PGM[(pin)].reg + 96))
+#define portInputRegister(pin) ((volatile uint8_t *)(digital_pin_to_info_PGM[(pin)].reg + 128))
+#define portModeRegister(pin) ((volatile uint8_t *)(digital_pin_to_info_PGM[(pin)].reg + 160))
+#define portConfigRegister(pin) ((volatile uint32_t *)(digital_pin_to_info_PGM[(pin)].config))
+#endif
+
+//#define digitalPinToTimer(P) ( pgm_read_byte( digital_pin_to_timer_PGM + (P) ) )
+//#define analogInPinToBit(P) (P)
+
+#define GPIO_BITBAND_ADDR(reg, bit) (((uint32_t)&(reg) - 0x40000000) * 32 + (bit) * 4 + 0x42000000)
+#define GPIO_BITBAND_PTR(reg, bit) ((uint32_t *)GPIO_BITBAND_ADDR((reg), (bit)))
+//#define GPIO_SET_BIT(reg, bit) (*GPIO_BITBAND_PTR((reg), (bit)) = 1)
+//#define GPIO_CLR_BIT(reg, bit) (*GPIO_BITBAND_PTR((reg), (bit)) = 0)
+
+const struct digital_pin_bitband_and_config_table_struct digital_pin_to_info_PGM[] = {
+ {GPIO_BITBAND_PTR(CORE_PIN0_PORTREG, CORE_PIN0_BIT), &CORE_PIN0_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN1_PORTREG, CORE_PIN1_BIT), &CORE_PIN1_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN2_PORTREG, CORE_PIN2_BIT), &CORE_PIN2_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN3_PORTREG, CORE_PIN3_BIT), &CORE_PIN3_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN4_PORTREG, CORE_PIN4_BIT), &CORE_PIN4_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN5_PORTREG, CORE_PIN5_BIT), &CORE_PIN5_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN6_PORTREG, CORE_PIN6_BIT), &CORE_PIN6_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN7_PORTREG, CORE_PIN7_BIT), &CORE_PIN7_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN8_PORTREG, CORE_PIN8_BIT), &CORE_PIN8_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN9_PORTREG, CORE_PIN9_BIT), &CORE_PIN9_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN10_PORTREG, CORE_PIN10_BIT), &CORE_PIN10_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN11_PORTREG, CORE_PIN11_BIT), &CORE_PIN11_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN12_PORTREG, CORE_PIN12_BIT), &CORE_PIN12_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN13_PORTREG, CORE_PIN13_BIT), &CORE_PIN13_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN14_PORTREG, CORE_PIN14_BIT), &CORE_PIN14_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN15_PORTREG, CORE_PIN15_BIT), &CORE_PIN15_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN16_PORTREG, CORE_PIN16_BIT), &CORE_PIN16_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN17_PORTREG, CORE_PIN17_BIT), &CORE_PIN17_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN18_PORTREG, CORE_PIN18_BIT), &CORE_PIN18_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN19_PORTREG, CORE_PIN19_BIT), &CORE_PIN19_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN20_PORTREG, CORE_PIN20_BIT), &CORE_PIN20_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN21_PORTREG, CORE_PIN21_BIT), &CORE_PIN21_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN22_PORTREG, CORE_PIN22_BIT), &CORE_PIN22_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN23_PORTREG, CORE_PIN23_BIT), &CORE_PIN23_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN24_PORTREG, CORE_PIN24_BIT), &CORE_PIN24_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN25_PORTREG, CORE_PIN25_BIT), &CORE_PIN25_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN26_PORTREG, CORE_PIN26_BIT), &CORE_PIN26_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN27_PORTREG, CORE_PIN27_BIT), &CORE_PIN27_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN28_PORTREG, CORE_PIN28_BIT), &CORE_PIN28_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN29_PORTREG, CORE_PIN29_BIT), &CORE_PIN29_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN30_PORTREG, CORE_PIN30_BIT), &CORE_PIN30_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN31_PORTREG, CORE_PIN31_BIT), &CORE_PIN31_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN32_PORTREG, CORE_PIN32_BIT), &CORE_PIN32_CONFIG},
+ {GPIO_BITBAND_PTR(CORE_PIN33_PORTREG, CORE_PIN33_BIT), &CORE_PIN33_CONFIG}
+};
+
+
+
+
+typedef void (*voidFuncPtr)(void);
+volatile static voidFuncPtr intFunc[CORE_NUM_DIGITAL];
+
+void init_pin_interrupts(void)
+{
+ //SIM_SCGC5 = 0x00043F82; // clocks active to all GPIO
+ NVIC_ENABLE_IRQ(IRQ_PORTA);
+ NVIC_ENABLE_IRQ(IRQ_PORTB);
+ NVIC_ENABLE_IRQ(IRQ_PORTC);
+ NVIC_ENABLE_IRQ(IRQ_PORTD);
+ NVIC_ENABLE_IRQ(IRQ_PORTE);
+ // TODO: maybe these should be set to a lower priority
+ // so if the user puts lots of slow code on attachInterrupt
+ // fast interrupts will still be serviced quickly?
+}
+
+void attachInterrupt(uint8_t pin, void (*function)(void), int mode)
+{
+ volatile uint32_t *config;
+ uint32_t cfg, mask;
+
+ if (pin >= CORE_NUM_DIGITAL) return;
+ switch (mode) {
+ case CHANGE: mask = 0x0B; break;
+ case RISING: mask = 0x09; break;
+ case FALLING: mask = 0x0A; break;
+ case LOW: mask = 0x08; break;
+ case HIGH: mask = 0x0C; break;
+ default: return;
+ }
+ mask = (mask << 16) | 0x01000000;
+ config = portConfigRegister(pin);
+
+ __disable_irq();
+ cfg = *config;
+ cfg &= ~0x000F0000; // disable any previous interrupt
+ *config = cfg;
+ intFunc[pin] = function; // set the function pointer
+ cfg |= mask;
+ *config = cfg; // enable the new interrupt
+ __enable_irq();
+}
+
+void detachInterrupt(uint8_t pin)
+{
+ volatile uint32_t *config;
+
+ config = portConfigRegister(pin);
+ __disable_irq();
+ *config = ((*config & ~0x000F0000) | 0x01000000);
+ intFunc[pin] = NULL;
+ __enable_irq();
+}
+
+
+void porta_isr(void)
+{
+ uint32_t isfr = PORTA_ISFR;
+ PORTA_ISFR = isfr;
+ if ((isfr & CORE_PIN3_BITMASK) && intFunc[3]) intFunc[3]();
+ if ((isfr & CORE_PIN4_BITMASK) && intFunc[4]) intFunc[4]();
+ if ((isfr & CORE_PIN24_BITMASK) && intFunc[24]) intFunc[24]();
+ if ((isfr & CORE_PIN33_BITMASK) && intFunc[33]) intFunc[33]();
+}
+
+void portb_isr(void)
+{
+ uint32_t isfr = PORTB_ISFR;
+ PORTB_ISFR = isfr;
+ if ((isfr & CORE_PIN0_BITMASK) && intFunc[0]) intFunc[0]();
+ if ((isfr & CORE_PIN1_BITMASK) && intFunc[1]) intFunc[1]();
+ if ((isfr & CORE_PIN16_BITMASK) && intFunc[16]) intFunc[16]();
+ if ((isfr & CORE_PIN17_BITMASK) && intFunc[17]) intFunc[17]();
+ if ((isfr & CORE_PIN18_BITMASK) && intFunc[18]) intFunc[18]();
+ if ((isfr & CORE_PIN19_BITMASK) && intFunc[19]) intFunc[19]();
+ if ((isfr & CORE_PIN25_BITMASK) && intFunc[25]) intFunc[25]();
+ if ((isfr & CORE_PIN32_BITMASK) && intFunc[32]) intFunc[32]();
+}
+
+void portc_isr(void)
+{
+ // TODO: these are inefficent. Use CLZ somehow....
+ uint32_t isfr = PORTC_ISFR;
+ PORTC_ISFR = isfr;
+ if ((isfr & CORE_PIN9_BITMASK) && intFunc[9]) intFunc[9]();
+ if ((isfr & CORE_PIN10_BITMASK) && intFunc[10]) intFunc[10]();
+ if ((isfr & CORE_PIN11_BITMASK) && intFunc[11]) intFunc[11]();
+ if ((isfr & CORE_PIN12_BITMASK) && intFunc[12]) intFunc[12]();
+ if ((isfr & CORE_PIN13_BITMASK) && intFunc[13]) intFunc[13]();
+ if ((isfr & CORE_PIN15_BITMASK) && intFunc[15]) intFunc[15]();
+ if ((isfr & CORE_PIN22_BITMASK) && intFunc[22]) intFunc[22]();
+ if ((isfr & CORE_PIN23_BITMASK) && intFunc[23]) intFunc[23]();
+ if ((isfr & CORE_PIN27_BITMASK) && intFunc[27]) intFunc[27]();
+ if ((isfr & CORE_PIN28_BITMASK) && intFunc[28]) intFunc[28]();
+ if ((isfr & CORE_PIN29_BITMASK) && intFunc[29]) intFunc[29]();
+ if ((isfr & CORE_PIN30_BITMASK) && intFunc[30]) intFunc[30]();
+}
+
+void portd_isr(void)
+{
+ uint32_t isfr = PORTD_ISFR;
+ PORTD_ISFR = isfr;
+ if ((isfr & CORE_PIN2_BITMASK) && intFunc[2]) intFunc[2]();
+ if ((isfr & CORE_PIN5_BITMASK) && intFunc[5]) intFunc[5]();
+ if ((isfr & CORE_PIN6_BITMASK) && intFunc[6]) intFunc[6]();
+ if ((isfr & CORE_PIN7_BITMASK) && intFunc[7]) intFunc[7]();
+ if ((isfr & CORE_PIN8_BITMASK) && intFunc[8]) intFunc[8]();
+ if ((isfr & CORE_PIN14_BITMASK) && intFunc[14]) intFunc[14]();
+ if ((isfr & CORE_PIN20_BITMASK) && intFunc[20]) intFunc[20]();
+ if ((isfr & CORE_PIN21_BITMASK) && intFunc[21]) intFunc[21]();
+}
+
+void porte_isr(void)
+{
+ uint32_t isfr = PORTE_ISFR;
+ PORTE_ISFR = isfr;
+ if ((isfr & CORE_PIN26_BITMASK) && intFunc[26]) intFunc[26]();
+ if ((isfr & CORE_PIN31_BITMASK) && intFunc[31]) intFunc[31]();
+}
+
+
+
+
+unsigned long rtc_get(void)
+{
+ return RTC_TSR;
+}
+
+void rtc_set(unsigned long t)
+{
+ RTC_SR = 0;
+ RTC_TPR = 0;
+ RTC_TSR = t;
+ RTC_SR = RTC_SR_TCE;
+}
+
+
+// adjust is the amount of crystal error to compensate, 1 = 0.1192 ppm
+// For example, adjust = -100 is slows the clock by 11.92 ppm
+//
+void rtc_compensate(int adjust)
+{
+ uint32_t comp, interval, tcr;
+
+ // This simple approach tries to maximize the interval.
+ // Perhaps minimizing TCR would be better, so the
+ // compensation is distributed more evenly across
+ // many seconds, rather than saving it all up and then
+ // altering one second up to +/- 0.38%
+ if (adjust >= 0) {
+ comp = adjust;
+ interval = 256;
+ while (1) {
+ tcr = comp * interval;
+ if (tcr < 128*256) break;
+ if (--interval == 1) break;
+ }
+ tcr = tcr >> 8;
+ } else {
+ comp = -adjust;
+ interval = 256;
+ while (1) {
+ tcr = comp * interval;
+ if (tcr < 129*256) break;
+ if (--interval == 1) break;
+ }
+ tcr = tcr >> 8;
+ tcr = 256 - tcr;
+ }
+ RTC_TCR = ((interval - 1) << 8) | tcr;
+}
+
+#if 0
+// TODO: build system should define this
+// so RTC is automatically initialized to approx correct time
+// at least when the program begins running right after upload
+#ifndef TIME_T
+#define TIME_T 1350160272
+#endif
+
+void init_rtc(void)
+{
+ serial_print("init_rtc\n");
+ //SIM_SCGC6 |= SIM_SCGC6_RTC;
+
+ // enable the RTC crystal oscillator, for approx 12pf crystal
+ if (!(RTC_CR & RTC_CR_OSCE)) {
+ serial_print("start RTC oscillator\n");
+ RTC_SR = 0;
+ RTC_CR = RTC_CR_SC16P | RTC_CR_SC4P | RTC_CR_OSCE;
+ }
+ // should wait for crystal to stabilize.....
+
+ serial_print("SR=");
+ serial_phex32(RTC_SR);
+ serial_print("\n");
+ serial_print("CR=");
+ serial_phex32(RTC_CR);
+ serial_print("\n");
+ serial_print("TSR=");
+ serial_phex32(RTC_TSR);
+ serial_print("\n");
+ serial_print("TCR=");
+ serial_phex32(RTC_TCR);
+ serial_print("\n");
+
+ if (RTC_SR & RTC_SR_TIF) {
+ // enable the RTC
+ RTC_SR = 0;
+ RTC_TPR = 0;
+ RTC_TSR = TIME_T;
+ RTC_SR = RTC_SR_TCE;
+ }
+}
+#endif
+
+extern void usb_init(void);
+
+
+// create a default PWM at the same 488.28 Hz as Arduino Uno
+
+#if F_BUS == 60000000
+#define DEFAULT_FTM_MOD (61440 - 1)
+#define DEFAULT_FTM_PRESCALE 1
+#elif F_BUS == 56000000
+#define DEFAULT_FTM_MOD (57344 - 1)
+#define DEFAULT_FTM_PRESCALE 1
+#elif F_BUS == 48000000
+#define DEFAULT_FTM_MOD (49152 - 1)
+#define DEFAULT_FTM_PRESCALE 1
+#elif F_BUS == 40000000
+#define DEFAULT_FTM_MOD (40960 - 1)
+#define DEFAULT_FTM_PRESCALE 1
+#elif F_BUS == 36000000
+#define DEFAULT_FTM_MOD (36864 - 1)
+#define DEFAULT_FTM_PRESCALE 1
+#elif F_BUS == 24000000
+#define DEFAULT_FTM_MOD (49152 - 1)
+#define DEFAULT_FTM_PRESCALE 0
+#elif F_BUS == 16000000
+#define DEFAULT_FTM_MOD (32768 - 1)
+#define DEFAULT_FTM_PRESCALE 0
+#elif F_BUS == 8000000
+#define DEFAULT_FTM_MOD (16384 - 1)
+#define DEFAULT_FTM_PRESCALE 0
+#elif F_BUS == 4000000
+#define DEFAULT_FTM_MOD (8192 - 1)
+#define DEFAULT_FTM_PRESCALE 0
+#elif F_BUS == 2000000
+#define DEFAULT_FTM_MOD (4096 - 1)
+#define DEFAULT_FTM_PRESCALE 0
+#endif
+
+//void init_pins(void)
+void _init_Teensyduino_internal_(void)
+{
+ init_pin_interrupts();
+
+ //SIM_SCGC6 |= SIM_SCGC6_FTM0; // TODO: use bitband for atomic read-mod-write
+ //SIM_SCGC6 |= SIM_SCGC6_FTM1;
+ FTM0_CNT = 0;
+ FTM0_MOD = DEFAULT_FTM_MOD;
+ FTM0_C0SC = 0x28; // MSnB:MSnA = 10, ELSnB:ELSnA = 10
+ FTM0_C1SC = 0x28;
+ FTM0_C2SC = 0x28;
+ FTM0_C3SC = 0x28;
+ FTM0_C4SC = 0x28;
+ FTM0_C5SC = 0x28;
+ FTM0_C6SC = 0x28;
+ FTM0_C7SC = 0x28;
+ FTM0_SC = FTM_SC_CLKS(1) | FTM_SC_PS(DEFAULT_FTM_PRESCALE);
+ FTM1_CNT = 0;
+ FTM1_MOD = DEFAULT_FTM_MOD;
+ FTM1_C0SC = 0x28;
+ FTM1_C1SC = 0x28;
+ FTM1_SC = FTM_SC_CLKS(1) | FTM_SC_PS(DEFAULT_FTM_PRESCALE);
+#if defined(__MK20DX256__)
+ FTM2_CNT = 0;
+ FTM2_MOD = DEFAULT_FTM_MOD;
+ FTM2_C0SC = 0x28;
+ FTM2_C1SC = 0x28;
+ FTM2_SC = FTM_SC_CLKS(1) | FTM_SC_PS(DEFAULT_FTM_PRESCALE);
+#endif
+
+ analog_init();
+ //delay(100); // TODO: this is not necessary, right?
+ delay(4);
+ usb_init();
+}
+
+
+
+static uint8_t analog_write_res = 8;
+
+// SOPT4 is SIM select clocks?
+// FTM is clocked by the bus clock, either 24 or 48 MHz
+// input capture can be FTM1_CH0, CMP0 or CMP1 or USB start of frame
+// 24 MHz with reload 49152 to match Arduino's speed = 488.28125 Hz
+
+void analogWrite(uint8_t pin, int val)
+{
+ uint32_t cval, max;
+
+#if defined(__MK20DX256__)
+ if (pin == A14) {
+ uint8_t res = analog_write_res;
+ if (res < 12) {
+ val <<= 12 - res;
+ } else if (res > 12) {
+ val >>= res - 12;
+ }
+ analogWriteDAC0(val);
+ return;
+ }
+#endif
+
+ max = 1 << analog_write_res;
+ if (val <= 0) {
+ digitalWrite(pin, LOW);
+ pinMode(pin, OUTPUT); // TODO: implement OUTPUT_LOW
+ return;
+ } else if (val >= max) {
+ digitalWrite(pin, HIGH);
+ pinMode(pin, OUTPUT); // TODO: implement OUTPUT_HIGH
+ return;
+ }
+
+ //serial_print("analogWrite\n");
+ //serial_print("val = ");
+ //serial_phex32(val);
+ //serial_print("\n");
+ //serial_print("analog_write_res = ");
+ //serial_phex(analog_write_res);
+ //serial_print("\n");
+ if (pin == 3 || pin == 4) {
+ cval = ((uint32_t)val * (uint32_t)(FTM1_MOD + 1)) >> analog_write_res;
+#if defined(__MK20DX256__)
+ } else if (pin == 25 || pin == 32) {
+ cval = ((uint32_t)val * (uint32_t)(FTM2_MOD + 1)) >> analog_write_res;
+#endif
+ } else {
+ cval = ((uint32_t)val * (uint32_t)(FTM0_MOD + 1)) >> analog_write_res;
+ }
+ //serial_print("cval = ");
+ //serial_phex32(cval);
+ //serial_print("\n");
+ switch (pin) {
+ case 3: // PTA12, FTM1_CH0
+ FTM1_C0V = cval;
+ CORE_PIN3_CONFIG = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
+ break;
+ case 4: // PTA13, FTM1_CH1
+ FTM1_C1V = cval;
+ CORE_PIN4_CONFIG = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
+ break;
+ case 5: // PTD7, FTM0_CH7
+ FTM0_C7V = cval;
+ CORE_PIN5_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
+ break;
+ case 6: // PTD4, FTM0_CH4
+ FTM0_C4V = cval;
+ CORE_PIN6_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
+ break;
+ case 9: // PTC3, FTM0_CH2
+ FTM0_C2V = cval;
+ CORE_PIN9_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
+ break;
+ case 10: // PTC4, FTM0_CH3
+ FTM0_C3V = cval;
+ CORE_PIN10_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
+ break;
+ case 20: // PTD5, FTM0_CH5
+ FTM0_C5V = cval;
+ CORE_PIN20_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
+ break;
+ case 21: // PTD6, FTM0_CH6
+ FTM0_C6V = cval;
+ CORE_PIN21_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
+ break;
+ case 22: // PTC1, FTM0_CH0
+ FTM0_C0V = cval;
+ CORE_PIN22_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
+ break;
+ case 23: // PTC2, FTM0_CH1
+ FTM0_C1V = cval;
+ CORE_PIN23_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
+ break;
+#if defined(__MK20DX256__)
+ case 32: // PTB18, FTM2_CH0
+ FTM2_C0V = cval;
+ CORE_PIN32_CONFIG = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
+ break;
+ case 25: // PTB19, FTM1_CH1
+ FTM2_C1V = cval;
+ CORE_PIN25_CONFIG = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
+ break;
+#endif
+ default:
+ digitalWrite(pin, (val > 127) ? HIGH : LOW);
+ pinMode(pin, OUTPUT);
+ }
+}
+
+void analogWriteRes(uint32_t bits)
+{
+ if (bits < 1) {
+ bits = 1;
+ } else if (bits > 16) {
+ bits = 16;
+ }
+ analog_write_res = bits;
+}
+
+void analogWriteFrequency(uint8_t pin, uint32_t frequency)
+{
+ uint32_t minfreq, prescale, mod;
+
+ //serial_print("analogWriteFrequency: pin = ");
+ //serial_phex(pin);
+ //serial_print(", freq = ");
+ //serial_phex32(frequency);
+ //serial_print("\n");
+ for (prescale = 0; prescale < 7; prescale++) {
+ minfreq = (F_BUS >> 16) >> prescale;
+ if (frequency > minfreq) break;
+ }
+ //serial_print("F_BUS = ");
+ //serial_phex32(F_BUS >> prescale);
+ //serial_print("\n");
+ //serial_print("prescale = ");
+ //serial_phex(prescale);
+ //serial_print("\n");
+ //mod = ((F_BUS >> prescale) / frequency) - 1;
+ mod = (((F_BUS >> prescale) + (frequency >> 1)) / frequency) - 1;
+ if (mod > 65535) mod = 65535;
+ //serial_print("mod = ");
+ //serial_phex32(mod);
+ //serial_print("\n");
+ if (pin == 3 || pin == 4) {
+ FTM1_SC = 0;
+ FTM1_CNT = 0;
+ FTM1_MOD = mod;
+ FTM1_SC = FTM_SC_CLKS(1) | FTM_SC_PS(prescale);
+ } else if (pin == 5 || pin == 6 || pin == 9 || pin == 10 ||
+ (pin >= 20 && pin <= 23)) {
+ FTM0_SC = 0;
+ FTM0_CNT = 0;
+ FTM0_MOD = mod;
+ FTM0_SC = FTM_SC_CLKS(1) | FTM_SC_PS(prescale);
+ }
+}
+
+
+
+
+// TODO: startup code needs to initialize all pins to GPIO mode, input by default
+
+void digitalWrite(uint8_t pin, uint8_t val)
+{
+ if (pin >= CORE_NUM_DIGITAL) return;
+ if (*portModeRegister(pin)) {
+ if (val) {
+ *portSetRegister(pin) = 1;
+ } else {
+ *portClearRegister(pin) = 1;
+ }
+ } else {
+ volatile uint32_t *config = portConfigRegister(pin);
+ if (val) {
+ // TODO use bitband for atomic read-mod-write
+ *config |= (PORT_PCR_PE | PORT_PCR_PS);
+ //*config = PORT_PCR_MUX(1) | PORT_PCR_PE | PORT_PCR_PS;
+ } else {
+ // TODO use bitband for atomic read-mod-write
+ *config &= ~(PORT_PCR_PE);
+ //*config = PORT_PCR_MUX(1);
+ }
+ }
+
+}
+
+uint8_t digitalRead(uint8_t pin)
+{
+ if (pin >= CORE_NUM_DIGITAL) return 0;
+ return *portInputRegister(pin);
+}
+
+
+
+void pinMode(uint8_t pin, uint8_t mode)
+{
+ volatile uint32_t *config;
+
+ if (pin >= CORE_NUM_DIGITAL) return;
+ config = portConfigRegister(pin);
+
+ if (mode == OUTPUT) {
+ *portModeRegister(pin) = 1;
+ *config = PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1);
+ } else {
+ *portModeRegister(pin) = 0;
+ if (mode == INPUT) {
+ *config = PORT_PCR_MUX(1);
+ } else {
+ *config = PORT_PCR_MUX(1) | PORT_PCR_PE | PORT_PCR_PS; // pullup
+ }
+ }
+}
+
+
+void _shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t value)
+{
+ if (bitOrder == LSBFIRST) {
+ shiftOut_lsbFirst(dataPin, clockPin, value);
+ } else {
+ shiftOut_msbFirst(dataPin, clockPin, value);
+ }
+}
+
+void shiftOut_lsbFirst(uint8_t dataPin, uint8_t clockPin, uint8_t value)
+{
+ uint8_t mask;
+ for (mask=0x01; mask; mask <<= 1) {
+ digitalWrite(dataPin, value & mask);
+ digitalWrite(clockPin, HIGH);
+ digitalWrite(clockPin, LOW);
+ }
+}
+
+void shiftOut_msbFirst(uint8_t dataPin, uint8_t clockPin, uint8_t value)
+{
+ uint8_t mask;
+ for (mask=0x80; mask; mask >>= 1) {
+ digitalWrite(dataPin, value & mask);
+ digitalWrite(clockPin, HIGH);
+ digitalWrite(clockPin, LOW);
+ }
+}
+
+uint8_t _shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder)
+{
+ if (bitOrder == LSBFIRST) {
+ return shiftIn_lsbFirst(dataPin, clockPin);
+ } else {
+ return shiftIn_msbFirst(dataPin, clockPin);
+ }
+}
+
+uint8_t shiftIn_lsbFirst(uint8_t dataPin, uint8_t clockPin)
+{
+ uint8_t mask, value=0;
+ for (mask=0x01; mask; mask <<= 1) {
+ digitalWrite(clockPin, HIGH);
+ if (digitalRead(dataPin)) value |= mask;
+ digitalWrite(clockPin, LOW);
+ }
+ return value;
+}
+
+uint8_t shiftIn_msbFirst(uint8_t dataPin, uint8_t clockPin)
+{
+ uint8_t mask, value=0;
+ for (mask=0x80; mask; mask >>= 1) {
+ digitalWrite(clockPin, HIGH);
+ if (digitalRead(dataPin)) value |= mask;
+ digitalWrite(clockPin, LOW);
+ }
+ return value;
+}
+
+
+
+// the systick interrupt is supposed to increment this at 1 kHz rate
+volatile uint32_t systick_millis_count = 0;
+
+//uint32_t systick_current, systick_count, systick_istatus; // testing only
+
+uint32_t micros(void)
+{
+ uint32_t count, current, istatus;
+
+ __disable_irq();
+ current = SYST_CVR;
+ count = systick_millis_count;
+ istatus = SCB_ICSR; // bit 26 indicates if systick exception pending
+ __enable_irq();
+ //systick_current = current;
+ //systick_count = count;
+ //systick_istatus = istatus & SCB_ICSR_PENDSTSET ? 1 : 0;
+ if ((istatus & SCB_ICSR_PENDSTSET) && current > 50) count++;
+ current = ((F_CPU / 1000) - 1) - current;
+ return count * 1000 + current / (F_CPU / 1000000);
+}
+
+void delay(uint32_t ms)
+{
+ uint32_t start = micros();
+
+ if (ms > 0) {
+ while (1) {
+ if ((micros() - start) >= 1000) {
+ ms--;
+ if (ms == 0) return;
+ start += 1000;
+ }
+ yield();
+ }
+ }
+}
+
+// TODO: verify these result in correct timeouts...
+#if F_CPU == 168000000
+#define PULSEIN_LOOPS_PER_USEC 25
+#elif F_CPU == 144000000
+#define PULSEIN_LOOPS_PER_USEC 21
+#elif F_CPU == 120000000
+#define PULSEIN_LOOPS_PER_USEC 18
+#elif F_CPU == 96000000
+#define PULSEIN_LOOPS_PER_USEC 14
+#elif F_CPU == 72000000
+#define PULSEIN_LOOPS_PER_USEC 10
+#elif F_CPU == 48000000
+#define PULSEIN_LOOPS_PER_USEC 7
+#elif F_CPU == 24000000
+#define PULSEIN_LOOPS_PER_USEC 4
+#elif F_CPU == 16000000
+#define PULSEIN_LOOPS_PER_USEC 1
+#elif F_CPU == 8000000
+#define PULSEIN_LOOPS_PER_USEC 1
+#elif F_CPU == 4000000
+#define PULSEIN_LOOPS_PER_USEC 1
+#elif F_CPU == 2000000
+#define PULSEIN_LOOPS_PER_USEC 1
+#endif
+
+
+uint32_t pulseIn_high(volatile uint8_t *reg, uint32_t timeout)
+{
+ uint32_t timeout_count = timeout * PULSEIN_LOOPS_PER_USEC;
+ uint32_t usec_start, usec_stop;
+
+ // wait for any previous pulse to end
+ while (*reg) {
+ if (--timeout_count == 0) return 0;
+ }
+ // wait for the pulse to start
+ while (!*reg) {
+ if (--timeout_count == 0) return 0;
+ }
+ usec_start = micros();
+ // wait for the pulse to stop
+ while (*reg) {
+ if (--timeout_count == 0) return 0;
+ }
+ usec_stop = micros();
+ return usec_stop - usec_start;
+}
+
+uint32_t pulseIn_low(volatile uint8_t *reg, uint32_t timeout)
+{
+ uint32_t timeout_count = timeout * PULSEIN_LOOPS_PER_USEC;
+ uint32_t usec_start, usec_stop;
+
+ // wait for any previous pulse to end
+ while (!*reg) {
+ if (--timeout_count == 0) return 0;
+ }
+ // wait for the pulse to start
+ while (*reg) {
+ if (--timeout_count == 0) return 0;
+ }
+ usec_start = micros();
+ // wait for the pulse to stop
+ while (!*reg) {
+ if (--timeout_count == 0) return 0;
+ }
+ usec_stop = micros();
+ return usec_stop - usec_start;
+}
+
+// TODO: an inline version should handle the common case where state is const
+uint32_t pulseIn(uint8_t pin, uint8_t state, uint32_t timeout)
+{
+ if (pin >= CORE_NUM_DIGITAL) return 0;
+ if (state) return pulseIn_high(portInputRegister(pin), timeout);
+ return pulseIn_low(portInputRegister(pin), timeout);;
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/ports/teensy/core/usb_desc.c b/ports/teensy/core/usb_desc.c
new file mode 100644
index 000000000..828a61967
--- /dev/null
+++ b/ports/teensy/core/usb_desc.c
@@ -0,0 +1,895 @@
+/* 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 F_CPU >= 20000000
+
+#include "usb_desc.h"
+#include "usb_names.h"
+#include "mk20dx128.h"
+#include "avr_functions.h"
+
+// USB Descriptors are binary data which the USB host reads to
+// automatically detect a USB device's capabilities. The format
+// and meaning of every field is documented in numerous USB
+// standards. When working with USB descriptors, despite the
+// complexity of the standards and poor writing quality in many
+// of those documents, remember descriptors are nothing more
+// than constant binary data that tells the USB host what the
+// device can do. Computers will load drivers based on this data.
+// Those drivers then communicate on the endpoints specified by
+// the descriptors.
+
+// To configure a new combination of interfaces or make minor
+// changes to existing configuration (eg, change the name or ID
+// numbers), usually you would edit "usb_desc.h". This file
+// is meant to be configured by the header, so generally it is
+// only edited to add completely new USB interfaces or features.
+
+
+
+// **************************************************************
+// USB Device
+// **************************************************************
+
+#define LSB(n) ((n) & 255)
+#define MSB(n) (((n) >> 8) & 255)
+
+// USB Device Descriptor. The USB host reads this first, to learn
+// what type of device is connected.
+static uint8_t device_descriptor[] = {
+ 18, // bLength
+ 1, // bDescriptorType
+ 0x00, 0x02, // bcdUSB
+#ifdef DEVICE_CLASS
+ DEVICE_CLASS, // bDeviceClass
+#else
+ 0,
+#endif
+#ifdef DEVICE_SUBCLASS
+ DEVICE_SUBCLASS, // bDeviceSubClass
+#else
+ 0,
+#endif
+#ifdef DEVICE_PROTOCOL
+ DEVICE_PROTOCOL, // bDeviceProtocol
+#else
+ 0,
+#endif
+ EP0_SIZE, // bMaxPacketSize0
+ LSB(VENDOR_ID), MSB(VENDOR_ID), // idVendor
+ LSB(PRODUCT_ID), MSB(PRODUCT_ID), // idProduct
+ 0x00, 0x01, // bcdDevice
+ 1, // iManufacturer
+ 2, // iProduct
+ 3, // iSerialNumber
+ 1 // bNumConfigurations
+};
+
+// These descriptors must NOT be "const", because the USB DMA
+// has trouble accessing flash memory with enough bandwidth
+// while the processor is executing from flash.
+
+
+
+// **************************************************************
+// HID Report Descriptors
+// **************************************************************
+
+// Each HID interface needs a special report descriptor that tells
+// the meaning and format of the data.
+
+#ifdef KEYBOARD_INTERFACE
+// Keyboard Protocol 1, HID 1.11 spec, Appendix B, page 59-60
+static uint8_t keyboard_report_desc[] = {
+ 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, 0x08, // Report Count (8),
+ 0x75, 0x01, // Report Size (1),
+ 0x15, 0x00, // Logical Minimum (0),
+ 0x25, 0x01, // Logical Maximum (1),
+ 0x05, 0x0C, // Usage Page (Consumer),
+ 0x09, 0xE9, // Usage (Volume Increment),
+ 0x09, 0xEA, // Usage (Volume Decrement),
+ 0x09, 0xE2, // Usage (Mute),
+ 0x09, 0xCD, // Usage (Play/Pause),
+ 0x09, 0xB5, // Usage (Scan Next Track),
+ 0x09, 0xB6, // Usage (Scan Previous Track),
+ 0x09, 0xB7, // Usage (Stop),
+ 0x09, 0xB8, // Usage (Eject),
+ 0x81, 0x02, // Input (Data, Variable, Absolute), ;Media keys
+ 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, 0x06, // Report Count (6),
+ 0x75, 0x08, // Report Size (8),
+ 0x15, 0x00, // Logical Minimum (0),
+ 0x25, 0x7F, // Logical Maximum(104),
+ 0x05, 0x07, // Usage Page (Key Codes),
+ 0x19, 0x00, // Usage Minimum (0),
+ 0x29, 0x7F, // Usage Maximum (104),
+ 0x81, 0x00, // Input (Data, Array), ;Normal keys
+ 0xc0 // End Collection
+};
+#endif
+
+#ifdef MOUSE_INTERFACE
+// Mouse Protocol 1, HID 1.11 spec, Appendix B, page 59-60, with wheel extension
+static uint8_t mouse_report_desc[] = {
+ 0x05, 0x01, // Usage Page (Generic Desktop)
+ 0x09, 0x02, // Usage (Mouse)
+ 0xA1, 0x01, // Collection (Application)
+ 0x85, 0x01, // REPORT_ID (1)
+ 0x05, 0x09, // Usage Page (Button)
+ 0x19, 0x01, // Usage Minimum (Button #1)
+ 0x29, 0x08, // Usage Maximum (Button #8)
+ 0x15, 0x00, // Logical Minimum (0)
+ 0x25, 0x01, // Logical Maximum (1)
+ 0x95, 0x08, // Report Count (8)
+ 0x75, 0x01, // Report Size (1)
+ 0x81, 0x02, // Input (Data, Variable, Absolute)
+ 0x05, 0x01, // Usage Page (Generic Desktop)
+ 0x09, 0x30, // Usage (X)
+ 0x09, 0x31, // Usage (Y)
+ 0x09, 0x38, // Usage (Wheel)
+ 0x15, 0x81, // Logical Minimum (-127)
+ 0x25, 0x7F, // Logical Maximum (127)
+ 0x75, 0x08, // Report Size (8),
+ 0x95, 0x03, // Report Count (3),
+ 0x81, 0x06, // Input (Data, Variable, Relative)
+ 0xC0, // End Collection
+ 0x05, 0x01, // Usage Page (Generic Desktop)
+ 0x09, 0x02, // Usage (Mouse)
+ 0xA1, 0x01, // Collection (Application)
+ 0x85, 0x02, // REPORT_ID (2)
+ 0x05, 0x01, // Usage Page (Generic Desktop)
+ 0x09, 0x30, // Usage (X)
+ 0x09, 0x31, // Usage (Y)
+ 0x15, 0x00, // Logical Minimum (0)
+ 0x26, 0xFF, 0x7F, // Logical Maximum (32767)
+ 0x75, 0x10, // Report Size (16),
+ 0x95, 0x02, // Report Count (2),
+ 0x81, 0x02, // Input (Data, Variable, Absolute)
+ 0xC0 // End Collection
+};
+#endif
+
+#ifdef JOYSTICK_INTERFACE
+static uint8_t joystick_report_desc[] = {
+ 0x05, 0x01, // Usage Page (Generic Desktop)
+ 0x09, 0x04, // Usage (Joystick)
+ 0xA1, 0x01, // Collection (Application)
+ 0x15, 0x00, // Logical Minimum (0)
+ 0x25, 0x01, // Logical Maximum (1)
+ 0x75, 0x01, // Report Size (1)
+ 0x95, 0x20, // Report Count (32)
+ 0x05, 0x09, // Usage Page (Button)
+ 0x19, 0x01, // Usage Minimum (Button #1)
+ 0x29, 0x20, // Usage Maximum (Button #32)
+ 0x81, 0x02, // Input (variable,absolute)
+ 0x15, 0x00, // Logical Minimum (0)
+ 0x25, 0x07, // Logical Maximum (7)
+ 0x35, 0x00, // Physical Minimum (0)
+ 0x46, 0x3B, 0x01, // Physical Maximum (315)
+ 0x75, 0x04, // Report Size (4)
+ 0x95, 0x01, // Report Count (1)
+ 0x65, 0x14, // Unit (20)
+ 0x05, 0x01, // Usage Page (Generic Desktop)
+ 0x09, 0x39, // Usage (Hat switch)
+ 0x81, 0x42, // Input (variable,absolute,null_state)
+ 0x05, 0x01, // Usage Page (Generic Desktop)
+ 0x09, 0x01, // Usage (Pointer)
+ 0xA1, 0x00, // Collection ()
+ 0x15, 0x00, // Logical Minimum (0)
+ 0x26, 0xFF, 0x03, // Logical Maximum (1023)
+ 0x75, 0x0A, // Report Size (10)
+ 0x95, 0x04, // Report Count (4)
+ 0x09, 0x30, // Usage (X)
+ 0x09, 0x31, // Usage (Y)
+ 0x09, 0x32, // Usage (Z)
+ 0x09, 0x35, // Usage (Rz)
+ 0x81, 0x02, // Input (variable,absolute)
+ 0xC0, // End Collection
+ 0x15, 0x00, // Logical Minimum (0)
+ 0x26, 0xFF, 0x03, // Logical Maximum (1023)
+ 0x75, 0x0A, // Report Size (10)
+ 0x95, 0x02, // Report Count (2)
+ 0x09, 0x36, // Usage (Slider)
+ 0x09, 0x36, // Usage (Slider)
+ 0x81, 0x02, // Input (variable,absolute)
+ 0xC0 // End Collection
+};
+#endif
+
+#ifdef SEREMU_INTERFACE
+static uint8_t seremu_report_desc[] = {
+ 0x06, 0xC9, 0xFF, // Usage Page 0xFFC9 (vendor defined)
+ 0x09, 0x04, // Usage 0x04
+ 0xA1, 0x5C, // Collection 0x5C
+ 0x75, 0x08, // report size = 8 bits (global)
+ 0x15, 0x00, // logical minimum = 0 (global)
+ 0x26, 0xFF, 0x00, // logical maximum = 255 (global)
+ 0x95, SEREMU_TX_SIZE, // report count (global)
+ 0x09, 0x75, // usage (local)
+ 0x81, 0x02, // Input
+ 0x95, SEREMU_RX_SIZE, // report count (global)
+ 0x09, 0x76, // usage (local)
+ 0x91, 0x02, // Output
+ 0x95, 0x04, // report count (global)
+ 0x09, 0x76, // usage (local)
+ 0xB1, 0x02, // Feature
+ 0xC0 // end collection
+};
+#endif
+
+#ifdef RAWHID_INTERFACE
+static uint8_t rawhid_report_desc[] = {
+ 0x06, LSB(RAWHID_USAGE_PAGE), MSB(RAWHID_USAGE_PAGE),
+ 0x0A, LSB(RAWHID_USAGE), MSB(RAWHID_USAGE),
+ 0xA1, 0x01, // Collection 0x01
+ 0x75, 0x08, // report size = 8 bits
+ 0x15, 0x00, // logical minimum = 0
+ 0x26, 0xFF, 0x00, // logical maximum = 255
+ 0x95, RAWHID_TX_SIZE, // report count
+ 0x09, 0x01, // usage
+ 0x81, 0x02, // Input (array)
+ 0x95, RAWHID_RX_SIZE, // report count
+ 0x09, 0x02, // usage
+ 0x91, 0x02, // Output (array)
+ 0xC0 // end collection
+};
+#endif
+
+#ifdef FLIGHTSIM_INTERFACE
+static uint8_t flightsim_report_desc[] = {
+ 0x06, 0x1C, 0xFF, // Usage page = 0xFF1C
+ 0x0A, 0x39, 0xA7, // Usage = 0xA739
+ 0xA1, 0x01, // Collection 0x01
+ 0x75, 0x08, // report size = 8 bits
+ 0x15, 0x00, // logical minimum = 0
+ 0x26, 0xFF, 0x00, // logical maximum = 255
+ 0x95, FLIGHTSIM_TX_SIZE, // report count
+ 0x09, 0x01, // usage
+ 0x81, 0x02, // Input (array)
+ 0x95, FLIGHTSIM_RX_SIZE, // report count
+ 0x09, 0x02, // usage
+ 0x91, 0x02, // Output (array)
+ 0xC0 // end collection
+};
+#endif
+
+
+
+// **************************************************************
+// USB Configuration
+// **************************************************************
+
+// USB Configuration Descriptor. This huge descriptor tells all
+// of the devices capbilities.
+static uint8_t config_descriptor[CONFIG_DESC_SIZE] = {
+ // configuration descriptor, USB spec 9.6.3, page 264-266, Table 9-10
+ 9, // bLength;
+ 2, // bDescriptorType;
+ LSB(CONFIG_DESC_SIZE), // wTotalLength
+ MSB(CONFIG_DESC_SIZE),
+ NUM_INTERFACE, // bNumInterfaces
+ 1, // bConfigurationValue
+ 0, // iConfiguration
+ 0xC0, // bmAttributes
+ 50, // bMaxPower
+
+#ifdef CDC_IAD_DESCRIPTOR
+ // interface association descriptor, USB ECN, Table 9-Z
+ 8, // bLength
+ 11, // bDescriptorType
+ CDC_STATUS_INTERFACE, // bFirstInterface
+ 2, // bInterfaceCount
+ 0x02, // bFunctionClass
+ 0x02, // bFunctionSubClass
+ 0x01, // bFunctionProtocol
+ 4, // iFunction
+#endif
+
+#ifdef CDC_DATA_INTERFACE
+ // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
+ 9, // bLength
+ 4, // bDescriptorType
+ CDC_STATUS_INTERFACE, // bInterfaceNumber
+ 0, // bAlternateSetting
+ 1, // bNumEndpoints
+ 0x02, // bInterfaceClass
+ 0x02, // bInterfaceSubClass
+ 0x01, // bInterfaceProtocol
+ 0, // iInterface
+ // CDC Header Functional Descriptor, CDC Spec 5.2.3.1, Table 26
+ 5, // bFunctionLength
+ 0x24, // bDescriptorType
+ 0x00, // bDescriptorSubtype
+ 0x10, 0x01, // bcdCDC
+ // Call Management Functional Descriptor, CDC Spec 5.2.3.2, Table 27
+ 5, // bFunctionLength
+ 0x24, // bDescriptorType
+ 0x01, // bDescriptorSubtype
+ 0x01, // bmCapabilities
+ 1, // bDataInterface
+ // Abstract Control Management Functional Descriptor, CDC Spec 5.2.3.3, Table 28
+ 4, // bFunctionLength
+ 0x24, // bDescriptorType
+ 0x02, // bDescriptorSubtype
+ 0x06, // bmCapabilities
+ // Union Functional Descriptor, CDC Spec 5.2.3.8, Table 33
+ 5, // bFunctionLength
+ 0x24, // bDescriptorType
+ 0x06, // bDescriptorSubtype
+ CDC_STATUS_INTERFACE, // bMasterInterface
+ CDC_DATA_INTERFACE, // bSlaveInterface0
+ // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+ 7, // bLength
+ 5, // bDescriptorType
+ CDC_ACM_ENDPOINT | 0x80, // bEndpointAddress
+ 0x03, // bmAttributes (0x03=intr)
+ CDC_ACM_SIZE, 0, // wMaxPacketSize
+ 64, // bInterval
+ // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
+ 9, // bLength
+ 4, // bDescriptorType
+ CDC_DATA_INTERFACE, // bInterfaceNumber
+ 0, // bAlternateSetting
+ 2, // bNumEndpoints
+ 0x0A, // bInterfaceClass
+ 0x00, // bInterfaceSubClass
+ 0x00, // bInterfaceProtocol
+ 0, // iInterface
+ // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+ 7, // bLength
+ 5, // bDescriptorType
+ CDC_RX_ENDPOINT, // bEndpointAddress
+ 0x02, // bmAttributes (0x02=bulk)
+ CDC_RX_SIZE, 0, // wMaxPacketSize
+ 0, // bInterval
+ // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+ 7, // bLength
+ 5, // bDescriptorType
+ CDC_TX_ENDPOINT | 0x80, // bEndpointAddress
+ 0x02, // bmAttributes (0x02=bulk)
+ CDC_TX_SIZE, 0, // wMaxPacketSize
+ 0, // bInterval
+#endif // CDC_DATA_INTERFACE
+
+#ifdef MIDI_INTERFACE
+ // Standard MS Interface Descriptor,
+ 9, // bLength
+ 4, // bDescriptorType
+ MIDI_INTERFACE, // bInterfaceNumber
+ 0, // bAlternateSetting
+ 2, // bNumEndpoints
+ 0x01, // bInterfaceClass (0x01 = Audio)
+ 0x03, // bInterfaceSubClass (0x03 = MIDI)
+ 0x00, // bInterfaceProtocol (unused for MIDI)
+ 0, // iInterface
+ // MIDI MS Interface Header, USB MIDI 6.1.2.1, page 21, Table 6-2
+ 7, // bLength
+ 0x24, // bDescriptorType = CS_INTERFACE
+ 0x01, // bDescriptorSubtype = MS_HEADER
+ 0x00, 0x01, // bcdMSC = revision 01.00
+ 0x41, 0x00, // wTotalLength
+ // MIDI IN Jack Descriptor, B.4.3, Table B-7 (embedded), page 40
+ 6, // bLength
+ 0x24, // bDescriptorType = CS_INTERFACE
+ 0x02, // bDescriptorSubtype = MIDI_IN_JACK
+ 0x01, // bJackType = EMBEDDED
+ 1, // bJackID, ID = 1
+ 0, // iJack
+ // MIDI IN Jack Descriptor, B.4.3, Table B-8 (external), page 40
+ 6, // bLength
+ 0x24, // bDescriptorType = CS_INTERFACE
+ 0x02, // bDescriptorSubtype = MIDI_IN_JACK
+ 0x02, // bJackType = EXTERNAL
+ 2, // bJackID, ID = 2
+ 0, // iJack
+ // MIDI OUT Jack Descriptor, B.4.4, Table B-9, page 41
+ 9,
+ 0x24, // bDescriptorType = CS_INTERFACE
+ 0x03, // bDescriptorSubtype = MIDI_OUT_JACK
+ 0x01, // bJackType = EMBEDDED
+ 3, // bJackID, ID = 3
+ 1, // bNrInputPins = 1 pin
+ 2, // BaSourceID(1) = 2
+ 1, // BaSourcePin(1) = first pin
+ 0, // iJack
+ // MIDI OUT Jack Descriptor, B.4.4, Table B-10, page 41
+ 9,
+ 0x24, // bDescriptorType = CS_INTERFACE
+ 0x03, // bDescriptorSubtype = MIDI_OUT_JACK
+ 0x02, // bJackType = EXTERNAL
+ 4, // bJackID, ID = 4
+ 1, // bNrInputPins = 1 pin
+ 1, // BaSourceID(1) = 1
+ 1, // BaSourcePin(1) = first pin
+ 0, // iJack
+ // Standard Bulk OUT Endpoint Descriptor, B.5.1, Table B-11, pae 42
+ 9, // bLength
+ 5, // bDescriptorType = ENDPOINT
+ MIDI_RX_ENDPOINT, // bEndpointAddress
+ 0x02, // bmAttributes (0x02=bulk)
+ MIDI_RX_SIZE, 0, // wMaxPacketSize
+ 0, // bInterval
+ 0, // bRefresh
+ 0, // bSynchAddress
+ // Class-specific MS Bulk OUT Endpoint Descriptor, B.5.2, Table B-12, page 42
+ 5, // bLength
+ 0x25, // bDescriptorSubtype = CS_ENDPOINT
+ 0x01, // bJackType = MS_GENERAL
+ 1, // bNumEmbMIDIJack = 1 jack
+ 1, // BaAssocJackID(1) = jack ID #1
+ // Standard Bulk IN Endpoint Descriptor, B.5.1, Table B-11, pae 42
+ 9, // bLength
+ 5, // bDescriptorType = ENDPOINT
+ MIDI_TX_ENDPOINT | 0x80, // bEndpointAddress
+ 0x02, // bmAttributes (0x02=bulk)
+ MIDI_TX_SIZE, 0, // wMaxPacketSize
+ 0, // bInterval
+ 0, // bRefresh
+ 0, // bSynchAddress
+ // Class-specific MS Bulk IN Endpoint Descriptor, B.5.2, Table B-12, page 42
+ 5, // bLength
+ 0x25, // bDescriptorSubtype = CS_ENDPOINT
+ 0x01, // bJackType = MS_GENERAL
+ 1, // bNumEmbMIDIJack = 1 jack
+ 3, // BaAssocJackID(1) = jack ID #3
+#endif // MIDI_INTERFACE
+
+#ifdef KEYBOARD_INTERFACE
+ // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
+ 9, // bLength
+ 4, // bDescriptorType
+ KEYBOARD_INTERFACE, // bInterfaceNumber
+ 0, // bAlternateSetting
+ 1, // bNumEndpoints
+ 0x03, // bInterfaceClass (0x03 = HID)
+ 0x01, // bInterfaceSubClass (0x01 = Boot)
+ 0x01, // bInterfaceProtocol (0x01 = Keyboard)
+ 0, // iInterface
+ // HID interface descriptor, HID 1.11 spec, section 6.2.1
+ 9, // bLength
+ 0x21, // bDescriptorType
+ 0x11, 0x01, // bcdHID
+ 0, // bCountryCode
+ 1, // bNumDescriptors
+ 0x22, // bDescriptorType
+ LSB(sizeof(keyboard_report_desc)), // wDescriptorLength
+ MSB(sizeof(keyboard_report_desc)),
+ // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+ 7, // bLength
+ 5, // bDescriptorType
+ KEYBOARD_ENDPOINT | 0x80, // bEndpointAddress
+ 0x03, // bmAttributes (0x03=intr)
+ KEYBOARD_SIZE, 0, // wMaxPacketSize
+ KEYBOARD_INTERVAL, // bInterval
+#endif // KEYBOARD_INTERFACE
+
+#ifdef MOUSE_INTERFACE
+ // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
+ 9, // bLength
+ 4, // bDescriptorType
+ MOUSE_INTERFACE, // bInterfaceNumber
+ 0, // bAlternateSetting
+ 1, // bNumEndpoints
+ 0x03, // bInterfaceClass (0x03 = HID)
+ 0x00, // bInterfaceSubClass (0x01 = Boot)
+ 0x00, // bInterfaceProtocol (0x02 = Mouse)
+ 0, // iInterface
+ // HID interface descriptor, HID 1.11 spec, section 6.2.1
+ 9, // bLength
+ 0x21, // bDescriptorType
+ 0x11, 0x01, // bcdHID
+ 0, // bCountryCode
+ 1, // bNumDescriptors
+ 0x22, // bDescriptorType
+ LSB(sizeof(mouse_report_desc)), // wDescriptorLength
+ MSB(sizeof(mouse_report_desc)),
+ // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+ 7, // bLength
+ 5, // bDescriptorType
+ MOUSE_ENDPOINT | 0x80, // bEndpointAddress
+ 0x03, // bmAttributes (0x03=intr)
+ MOUSE_SIZE, 0, // wMaxPacketSize
+ MOUSE_INTERVAL, // bInterval
+#endif // MOUSE_INTERFACE
+
+#ifdef RAWHID_INTERFACE
+ // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
+ 9, // bLength
+ 4, // bDescriptorType
+ RAWHID_INTERFACE, // bInterfaceNumber
+ 0, // bAlternateSetting
+ 2, // bNumEndpoints
+ 0x03, // bInterfaceClass (0x03 = HID)
+ 0x00, // bInterfaceSubClass
+ 0x00, // bInterfaceProtocol
+ 0, // iInterface
+ // HID interface descriptor, HID 1.11 spec, section 6.2.1
+ 9, // bLength
+ 0x21, // bDescriptorType
+ 0x11, 0x01, // bcdHID
+ 0, // bCountryCode
+ 1, // bNumDescriptors
+ 0x22, // bDescriptorType
+ LSB(sizeof(rawhid_report_desc)), // wDescriptorLength
+ MSB(sizeof(rawhid_report_desc)),
+ // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+ 7, // bLength
+ 5, // bDescriptorType
+ RAWHID_TX_ENDPOINT | 0x80, // bEndpointAddress
+ 0x03, // bmAttributes (0x03=intr)
+ RAWHID_TX_SIZE, 0, // wMaxPacketSize
+ RAWHID_TX_INTERVAL, // bInterval
+ // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+ 7, // bLength
+ 5, // bDescriptorType
+ RAWHID_RX_ENDPOINT, // bEndpointAddress
+ 0x03, // bmAttributes (0x03=intr)
+ RAWHID_RX_SIZE, 0, // wMaxPacketSize
+ RAWHID_RX_INTERVAL, // bInterval
+#endif // RAWHID_INTERFACE
+
+#ifdef FLIGHTSIM_INTERFACE
+ // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
+ 9, // bLength
+ 4, // bDescriptorType
+ FLIGHTSIM_INTERFACE, // bInterfaceNumber
+ 0, // bAlternateSetting
+ 2, // bNumEndpoints
+ 0x03, // bInterfaceClass (0x03 = HID)
+ 0x00, // bInterfaceSubClass
+ 0x00, // bInterfaceProtocol
+ 0, // iInterface
+ // HID interface descriptor, HID 1.11 spec, section 6.2.1
+ 9, // bLength
+ 0x21, // bDescriptorType
+ 0x11, 0x01, // bcdHID
+ 0, // bCountryCode
+ 1, // bNumDescriptors
+ 0x22, // bDescriptorType
+ LSB(sizeof(flightsim_report_desc)), // wDescriptorLength
+ MSB(sizeof(flightsim_report_desc)),
+ // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+ 7, // bLength
+ 5, // bDescriptorType
+ FLIGHTSIM_TX_ENDPOINT | 0x80, // bEndpointAddress
+ 0x03, // bmAttributes (0x03=intr)
+ FLIGHTSIM_TX_SIZE, 0, // wMaxPacketSize
+ FLIGHTSIM_TX_INTERVAL, // bInterval
+ // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+ 7, // bLength
+ 5, // bDescriptorType
+ FLIGHTSIM_RX_ENDPOINT, // bEndpointAddress
+ 0x03, // bmAttributes (0x03=intr)
+ FLIGHTSIM_RX_SIZE, 0, // wMaxPacketSize
+ FLIGHTSIM_RX_INTERVAL, // bInterval
+#endif // FLIGHTSIM_INTERFACE
+
+#ifdef SEREMU_INTERFACE
+ // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
+ 9, // bLength
+ 4, // bDescriptorType
+ SEREMU_INTERFACE, // bInterfaceNumber
+ 0, // bAlternateSetting
+ 2, // bNumEndpoints
+ 0x03, // bInterfaceClass (0x03 = HID)
+ 0x00, // bInterfaceSubClass
+ 0x00, // bInterfaceProtocol
+ 0, // iInterface
+ // HID interface descriptor, HID 1.11 spec, section 6.2.1
+ 9, // bLength
+ 0x21, // bDescriptorType
+ 0x11, 0x01, // bcdHID
+ 0, // bCountryCode
+ 1, // bNumDescriptors
+ 0x22, // bDescriptorType
+ LSB(sizeof(seremu_report_desc)), // wDescriptorLength
+ MSB(sizeof(seremu_report_desc)),
+ // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+ 7, // bLength
+ 5, // bDescriptorType
+ SEREMU_TX_ENDPOINT | 0x80, // bEndpointAddress
+ 0x03, // bmAttributes (0x03=intr)
+ SEREMU_TX_SIZE, 0, // wMaxPacketSize
+ SEREMU_TX_INTERVAL, // bInterval
+ // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+ 7, // bLength
+ 5, // bDescriptorType
+ SEREMU_RX_ENDPOINT, // bEndpointAddress
+ 0x03, // bmAttributes (0x03=intr)
+ SEREMU_RX_SIZE, 0, // wMaxPacketSize
+ SEREMU_RX_INTERVAL, // bInterval
+#endif // SEREMU_INTERFACE
+
+#ifdef JOYSTICK_INTERFACE
+ // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
+ 9, // bLength
+ 4, // bDescriptorType
+ JOYSTICK_INTERFACE, // bInterfaceNumber
+ 0, // bAlternateSetting
+ 1, // bNumEndpoints
+ 0x03, // bInterfaceClass (0x03 = HID)
+ 0x00, // bInterfaceSubClass
+ 0x00, // bInterfaceProtocol
+ 0, // iInterface
+ // HID interface descriptor, HID 1.11 spec, section 6.2.1
+ 9, // bLength
+ 0x21, // bDescriptorType
+ 0x11, 0x01, // bcdHID
+ 0, // bCountryCode
+ 1, // bNumDescriptors
+ 0x22, // bDescriptorType
+ LSB(sizeof(joystick_report_desc)), // wDescriptorLength
+ MSB(sizeof(joystick_report_desc)),
+ // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+ 7, // bLength
+ 5, // bDescriptorType
+ JOYSTICK_ENDPOINT | 0x80, // bEndpointAddress
+ 0x03, // bmAttributes (0x03=intr)
+ JOYSTICK_SIZE, 0, // wMaxPacketSize
+ JOYSTICK_INTERVAL, // bInterval
+#endif // JOYSTICK_INTERFACE
+
+};
+
+
+// **************************************************************
+// String Descriptors
+// **************************************************************
+
+// The descriptors above can provide human readable strings,
+// referenced by index numbers. These descriptors are the
+// actual string data
+
+/* defined in usb_names.h
+struct usb_string_descriptor_struct {
+ uint8_t bLength;
+ uint8_t bDescriptorType;
+ uint16_t wString[];
+};
+*/
+
+extern struct usb_string_descriptor_struct usb_string_manufacturer_name
+ __attribute__ ((weak, alias("usb_string_manufacturer_name_default")));
+extern struct usb_string_descriptor_struct usb_string_product_name
+ __attribute__ ((weak, alias("usb_string_product_name_default")));
+extern struct usb_string_descriptor_struct usb_string_serial_number
+ __attribute__ ((weak, alias("usb_string_serial_number_default")));
+
+struct usb_string_descriptor_struct string0 = {
+ 4,
+ 3,
+ {0x0409}
+};
+
+struct usb_string_descriptor_struct usb_string_manufacturer_name_default = {
+ 2 + MANUFACTURER_NAME_LEN * 2,
+ 3,
+ MANUFACTURER_NAME
+};
+struct usb_string_descriptor_struct usb_string_product_name_default = {
+ 2 + PRODUCT_NAME_LEN * 2,
+ 3,
+ PRODUCT_NAME
+};
+struct usb_string_descriptor_struct usb_string_serial_number_default = {
+ 12,
+ 3,
+ {0,0,0,0,0,0,0,0,0,0}
+};
+
+void usb_init_serialnumber(void)
+{
+ char buf[11];
+ uint32_t i, num;
+
+ __disable_irq();
+ FTFL_FSTAT = FTFL_FSTAT_RDCOLERR | FTFL_FSTAT_ACCERR | FTFL_FSTAT_FPVIOL;
+ FTFL_FCCOB0 = 0x41;
+ FTFL_FCCOB1 = 15;
+ FTFL_FSTAT = FTFL_FSTAT_CCIF;
+ while (!(FTFL_FSTAT & FTFL_FSTAT_CCIF)) ; // wait
+ num = *(uint32_t *)&FTFL_FCCOB7;
+ __enable_irq();
+ // add extra zero to work around OS-X CDC-ACM driver bug
+ if (num < 10000000) num = num * 10;
+ ultoa(num, buf, 10);
+ for (i=0; i<10; i++) {
+ char c = buf[i];
+ if (!c) break;
+ usb_string_serial_number_default.wString[i] = c;
+ }
+ usb_string_serial_number_default.bLength = i * 2 + 2;
+}
+
+
+// **************************************************************
+// Descriptors List
+// **************************************************************
+
+// This table provides access to all the descriptor data above.
+
+const usb_descriptor_list_t usb_descriptor_list[] = {
+ //wValue, wIndex, address, length
+ {0x0100, 0x0000, device_descriptor, sizeof(device_descriptor)},
+ {0x0200, 0x0000, config_descriptor, sizeof(config_descriptor)},
+#ifdef SEREMU_INTERFACE
+ {0x2200, SEREMU_INTERFACE, seremu_report_desc, sizeof(seremu_report_desc)},
+ {0x2100, SEREMU_INTERFACE, config_descriptor+SEREMU_DESC_OFFSET, 9},
+#endif
+#ifdef KEYBOARD_INTERFACE
+ {0x2200, KEYBOARD_INTERFACE, keyboard_report_desc, sizeof(keyboard_report_desc)},
+ {0x2100, KEYBOARD_INTERFACE, config_descriptor+KEYBOARD_DESC_OFFSET, 9},
+#endif
+#ifdef MOUSE_INTERFACE
+ {0x2200, MOUSE_INTERFACE, mouse_report_desc, sizeof(mouse_report_desc)},
+ {0x2100, MOUSE_INTERFACE, config_descriptor+MOUSE_DESC_OFFSET, 9},
+#endif
+#ifdef JOYSTICK_INTERFACE
+ {0x2200, JOYSTICK_INTERFACE, joystick_report_desc, sizeof(joystick_report_desc)},
+ {0x2100, JOYSTICK_INTERFACE, config_descriptor+JOYSTICK_DESC_OFFSET, 9},
+#endif
+#ifdef RAWHID_INTERFACE
+ {0x2200, RAWHID_INTERFACE, rawhid_report_desc, sizeof(rawhid_report_desc)},
+ {0x2100, RAWHID_INTERFACE, config_descriptor+RAWHID_DESC_OFFSET, 9},
+#endif
+#ifdef FLIGHTSIM_INTERFACE
+ {0x2200, FLIGHTSIM_INTERFACE, flightsim_report_desc, sizeof(flightsim_report_desc)},
+ {0x2100, FLIGHTSIM_INTERFACE, config_descriptor+FLIGHTSIM_DESC_OFFSET, 9},
+#endif
+ {0x0300, 0x0000, (const uint8_t *)&string0, 0},
+ {0x0301, 0x0409, (const uint8_t *)&usb_string_manufacturer_name, 0},
+ {0x0302, 0x0409, (const uint8_t *)&usb_string_product_name, 0},
+ {0x0303, 0x0409, (const uint8_t *)&usb_string_serial_number, 0},
+ //{0x0301, 0x0409, (const uint8_t *)&string1, 0},
+ //{0x0302, 0x0409, (const uint8_t *)&string2, 0},
+ //{0x0303, 0x0409, (const uint8_t *)&string3, 0},
+ {0, 0, NULL, 0}
+};
+
+
+// **************************************************************
+// Endpoint Configuration
+// **************************************************************
+
+#if 0
+// 0x00 = not used
+// 0x19 = Recieve only
+// 0x15 = Transmit only
+// 0x1D = Transmit & Recieve
+//
+const uint8_t usb_endpoint_config_table[NUM_ENDPOINTS] =
+{
+ 0x00, 0x15, 0x19, 0x15, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+};
+#endif
+
+
+const uint8_t usb_endpoint_config_table[NUM_ENDPOINTS] =
+{
+#if (defined(ENDPOINT1_CONFIG) && NUM_ENDPOINTS >= 1)
+ ENDPOINT1_CONFIG,
+#elif (NUM_ENDPOINTS >= 1)
+ ENDPOINT_UNUSED,
+#endif
+#if (defined(ENDPOINT2_CONFIG) && NUM_ENDPOINTS >= 2)
+ ENDPOINT2_CONFIG,
+#elif (NUM_ENDPOINTS >= 2)
+ ENDPOINT_UNUSED,
+#endif
+#if (defined(ENDPOINT3_CONFIG) && NUM_ENDPOINTS >= 3)
+ ENDPOINT3_CONFIG,
+#elif (NUM_ENDPOINTS >= 3)
+ ENDPOINT_UNUSED,
+#endif
+#if (defined(ENDPOINT4_CONFIG) && NUM_ENDPOINTS >= 4)
+ ENDPOINT4_CONFIG,
+#elif (NUM_ENDPOINTS >= 4)
+ ENDPOINT_UNUSED,
+#endif
+#if (defined(ENDPOINT5_CONFIG) && NUM_ENDPOINTS >= 5)
+ ENDPOINT5_CONFIG,
+#elif (NUM_ENDPOINTS >= 5)
+ ENDPOINT_UNUSED,
+#endif
+#if (defined(ENDPOINT6_CONFIG) && NUM_ENDPOINTS >= 6)
+ ENDPOINT6_CONFIG,
+#elif (NUM_ENDPOINTS >= 6)
+ ENDPOINT_UNUSED,
+#endif
+#if (defined(ENDPOINT7_CONFIG) && NUM_ENDPOINTS >= 7)
+ ENDPOINT7_CONFIG,
+#elif (NUM_ENDPOINTS >= 7)
+ ENDPOINT_UNUSED,
+#endif
+#if (defined(ENDPOINT8_CONFIG) && NUM_ENDPOINTS >= 8)
+ ENDPOINT8_CONFIG,
+#elif (NUM_ENDPOINTS >= 8)
+ ENDPOINT_UNUSED,
+#endif
+#if (defined(ENDPOINT9_CONFIG) && NUM_ENDPOINTS >= 9)
+ ENDPOINT9_CONFIG,
+#elif (NUM_ENDPOINTS >= 9)
+ ENDPOINT_UNUSED,
+#endif
+#if (defined(ENDPOINT10_CONFIG) && NUM_ENDPOINTS >= 10)
+ ENDPOINT10_CONFIG,
+#elif (NUM_ENDPOINTS >= 10)
+ ENDPOINT_UNUSED,
+#endif
+#if (defined(ENDPOINT11_CONFIG) && NUM_ENDPOINTS >= 11)
+ ENDPOINT11_CONFIG,
+#elif (NUM_ENDPOINTS >= 11)
+ ENDPOINT_UNUSED,
+#endif
+#if (defined(ENDPOINT12_CONFIG) && NUM_ENDPOINTS >= 12)
+ ENDPOINT12_CONFIG,
+#elif (NUM_ENDPOINTS >= 12)
+ ENDPOINT_UNUSED,
+#endif
+#if (defined(ENDPOINT13_CONFIG) && NUM_ENDPOINTS >= 13)
+ ENDPOINT13_CONFIG,
+#elif (NUM_ENDPOINTS >= 13)
+ ENDPOINT_UNUSED,
+#endif
+#if (defined(ENDPOINT14_CONFIG) && NUM_ENDPOINTS >= 14)
+ ENDPOINT14_CONFIG,
+#elif (NUM_ENDPOINTS >= 14)
+ ENDPOINT_UNUSED,
+#endif
+#if (defined(ENDPOINT15_CONFIG) && NUM_ENDPOINTS >= 15)
+ ENDPOINT15_CONFIG,
+#elif (NUM_ENDPOINTS >= 15)
+ ENDPOINT_UNUSED,
+#endif
+};
+
+
+
+#endif // F_CPU >= 20 MHz
diff --git a/ports/teensy/core/usb_desc.h b/ports/teensy/core/usb_desc.h
new file mode 100644
index 000000000..a951e03f6
--- /dev/null
+++ b/ports/teensy/core/usb_desc.h
@@ -0,0 +1,313 @@
+/* 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.
+ */
+
+#ifndef _usb_desc_h_
+#define _usb_desc_h_
+
+#if F_CPU >= 20000000
+
+// This header is NOT meant to be included when compiling
+// user sketches in Arduino. The low-level functions
+// provided by usb_dev.c are meant to be called only by
+// code which provides higher-level interfaces to the user.
+
+#include <stdint.h>
+#include <stddef.h>
+
+#define ENDPOINT_UNUSED 0x00
+#define ENDPOINT_TRANSIMIT_ONLY 0x15
+#define ENDPOINT_RECEIVE_ONLY 0x19
+#define ENDPOINT_TRANSMIT_AND_RECEIVE 0x1D
+
+/*
+To modify a USB Type to have different interfaces, start in this
+file. Delete the XYZ_INTERFACE lines for any interfaces you
+wish to remove, and copy them from another USB Type for any you
+want to add.
+
+Give each interface a unique number, and edit NUM_INTERFACE to
+reflect the number of interfaces.
+
+Within each interface, make sure it uses a unique set of endpoints.
+Edit NUM_ENDPOINTS to be at least the largest endpoint number used.
+Then edit the ENDPOINT*_CONFIG lines so each endpoint is configured
+the proper way (transmit, receive, or both).
+
+The CONFIG_DESC_SIZE and any XYZ_DESC_OFFSET numbers must be
+edited to the correct sizes. See usb_desc.c for the giant array
+of bytes. Someday these may be done automatically..... (but how?)
+
+If you are using existing interfaces, the code in each file should
+automatically adapt to the changes you specify. If you need to
+create a new type of interface, you'll need to write the code which
+sends and receives packets, and presents an API to the user.
+
+Finally, edit usb_inst.cpp, which creats instances of the C++
+objects for each combination.
+
+Some operating systems, especially Windows, may cache USB device
+info. Changes to the device name may not update on the same
+computer unless the vendor or product ID numbers change, or the
+"bcdDevice" revision code is increased.
+
+If these instructions are missing steps or could be improved, please
+let me know? http://forum.pjrc.com/forums/4-Suggestions-amp-Bug-Reports
+*/
+
+
+
+#if defined(USB_SERIAL)
+ #define VENDOR_ID 0x16C0
+ #define PRODUCT_ID 0x0483
+ #define DEVICE_CLASS 2 // 2 = Communication Class
+ #define MANUFACTURER_NAME {'T','e','e','n','s','y','d','u','i','n','o'}
+ #define MANUFACTURER_NAME_LEN 11
+ #define PRODUCT_NAME {'U','S','B',' ','S','e','r','i','a','l'}
+ #define PRODUCT_NAME_LEN 10
+ #define EP0_SIZE 64
+ #define NUM_ENDPOINTS 4
+ #define NUM_USB_BUFFERS 12
+ #define NUM_INTERFACE 2
+ #define CDC_STATUS_INTERFACE 0
+ #define CDC_DATA_INTERFACE 1
+ #define CDC_ACM_ENDPOINT 2
+ #define CDC_RX_ENDPOINT 3
+ #define CDC_TX_ENDPOINT 4
+ #define CDC_ACM_SIZE 16
+ #define CDC_RX_SIZE 64
+ #define CDC_TX_SIZE 64
+ #define CONFIG_DESC_SIZE (9+9+5+5+4+5+7+9+7+7)
+ #define ENDPOINT2_CONFIG ENDPOINT_TRANSIMIT_ONLY
+ #define ENDPOINT3_CONFIG ENDPOINT_RECEIVE_ONLY
+ #define ENDPOINT4_CONFIG ENDPOINT_TRANSIMIT_ONLY
+
+#elif defined(USB_HID)
+ #define VENDOR_ID 0x16C0
+ #define PRODUCT_ID 0x0482
+ #define MANUFACTURER_NAME {'T','e','e','n','s','y','d','u','i','n','o'}
+ #define MANUFACTURER_NAME_LEN 11
+ #define PRODUCT_NAME {'K','e','y','b','o','a','r','d','/','M','o','u','s','e','/','J','o','y','s','t','i','c','k'}
+ #define PRODUCT_NAME_LEN 23
+ #define EP0_SIZE 64
+ #define NUM_ENDPOINTS 5
+ #define NUM_USB_BUFFERS 24
+ #define NUM_INTERFACE 4
+ #define SEREMU_INTERFACE 2 // Serial emulation
+ #define SEREMU_TX_ENDPOINT 1
+ #define SEREMU_TX_SIZE 64
+ #define SEREMU_TX_INTERVAL 1
+ #define SEREMU_RX_ENDPOINT 2
+ #define SEREMU_RX_SIZE 32
+ #define SEREMU_RX_INTERVAL 2
+ #define KEYBOARD_INTERFACE 0 // Keyboard
+ #define KEYBOARD_ENDPOINT 3
+ #define KEYBOARD_SIZE 8
+ #define KEYBOARD_INTERVAL 1
+ #define MOUSE_INTERFACE 1 // Mouse
+ #define MOUSE_ENDPOINT 5
+ #define MOUSE_SIZE 8
+ #define MOUSE_INTERVAL 1
+ #define JOYSTICK_INTERFACE 3 // Joystick
+ #define JOYSTICK_ENDPOINT 4
+ #define JOYSTICK_SIZE 16
+ #define JOYSTICK_INTERVAL 2
+ #define KEYBOARD_DESC_OFFSET (9 + 9)
+ #define MOUSE_DESC_OFFSET (9 + 9+9+7 + 9)
+ #define SEREMU_DESC_OFFSET (9 + 9+9+7 + 9+9+7 + 9)
+ #define JOYSTICK_DESC_OFFSET (9 + 9+9+7 + 9+9+7 + 9+9+7+7 + 9)
+ #define CONFIG_DESC_SIZE (9 + 9+9+7 + 9+9+7 + 9+9+7+7 + 9+9+7)
+ #define ENDPOINT1_CONFIG ENDPOINT_TRANSIMIT_ONLY
+ #define ENDPOINT2_CONFIG ENDPOINT_RECEIVE_ONLY
+ #define ENDPOINT3_CONFIG ENDPOINT_TRANSIMIT_ONLY
+ #define ENDPOINT4_CONFIG ENDPOINT_TRANSIMIT_ONLY
+ #define ENDPOINT5_CONFIG ENDPOINT_TRANSIMIT_ONLY
+
+#elif defined(USB_SERIAL_HID)
+ #define VENDOR_ID 0x16C0
+ #define PRODUCT_ID 0x0487
+ #define DEVICE_CLASS 0xEF
+ #define DEVICE_SUBCLASS 0x02
+ #define DEVICE_PROTOCOL 0x01
+ #define MANUFACTURER_NAME {'T','e','e','n','s','y','d','u','i','n','o'}
+ #define MANUFACTURER_NAME_LEN 11
+ #define PRODUCT_NAME {'S','e','r','i','a','l','/','K','e','y','b','o','a','r','d','/','M','o','u','s','e','/','J','o','y','s','t','i','c','k'}
+ #define PRODUCT_NAME_LEN 30
+ #define EP0_SIZE 64
+ #define NUM_ENDPOINTS 6
+ #define NUM_USB_BUFFERS 30
+ #define NUM_INTERFACE 5
+ #define CDC_IAD_DESCRIPTOR 1
+ #define CDC_STATUS_INTERFACE 0
+ #define CDC_DATA_INTERFACE 1 // Serial
+ #define CDC_ACM_ENDPOINT 2
+ #define CDC_RX_ENDPOINT 3
+ #define CDC_TX_ENDPOINT 4
+ #define CDC_ACM_SIZE 16
+ #define CDC_RX_SIZE 64
+ #define CDC_TX_SIZE 64
+ #define KEYBOARD_INTERFACE 2 // Keyboard
+ #define KEYBOARD_ENDPOINT 1
+ #define KEYBOARD_SIZE 8
+ #define KEYBOARD_INTERVAL 1
+ #define MOUSE_INTERFACE 3 // Mouse
+ #define MOUSE_ENDPOINT 5
+ #define MOUSE_SIZE 8
+ #define MOUSE_INTERVAL 2
+ #define JOYSTICK_INTERFACE 4 // Joystick
+ #define JOYSTICK_ENDPOINT 6
+ #define JOYSTICK_SIZE 16
+ #define JOYSTICK_INTERVAL 1
+ #define KEYBOARD_DESC_OFFSET (9+8 + 9+5+5+4+5+7+9+7+7 + 9)
+ #define MOUSE_DESC_OFFSET (9+8 + 9+5+5+4+5+7+9+7+7 + 9+9+7 + 9)
+ #define JOYSTICK_DESC_OFFSET (9+8 + 9+5+5+4+5+7+9+7+7 + 9+9+7 + 9+9+7 + 9)
+ #define CONFIG_DESC_SIZE (9+8 + 9+5+5+4+5+7+9+7+7 + 9+9+7 + 9+9+7 + 9+9+7)
+ #define ENDPOINT1_CONFIG ENDPOINT_TRANSIMIT_ONLY
+ #define ENDPOINT2_CONFIG ENDPOINT_TRANSIMIT_ONLY
+ #define ENDPOINT3_CONFIG ENDPOINT_RECEIVE_ONLY
+ #define ENDPOINT4_CONFIG ENDPOINT_TRANSIMIT_ONLY
+ #define ENDPOINT5_CONFIG ENDPOINT_TRANSIMIT_ONLY
+ #define ENDPOINT6_CONFIG ENDPOINT_TRANSIMIT_ONLY
+
+#elif defined(USB_MIDI)
+ #define VENDOR_ID 0x16C0
+ #define PRODUCT_ID 0x0485
+ #define MANUFACTURER_NAME {'T','e','e','n','s','y','d','u','i','n','o'}
+ #define MANUFACTURER_NAME_LEN 11
+ #define PRODUCT_NAME {'T','e','e','n','s','y',' ','M','I','D','I'}
+ #define PRODUCT_NAME_LEN 11
+ #define EP0_SIZE 64
+ #define NUM_ENDPOINTS 4
+ #define NUM_USB_BUFFERS 16
+ #define NUM_INTERFACE 2
+ #define SEREMU_INTERFACE 1 // Serial emulation
+ #define SEREMU_TX_ENDPOINT 1
+ #define SEREMU_TX_SIZE 64
+ #define SEREMU_TX_INTERVAL 1
+ #define SEREMU_RX_ENDPOINT 2
+ #define SEREMU_RX_SIZE 32
+ #define SEREMU_RX_INTERVAL 2
+ #define MIDI_INTERFACE 0 // MIDI
+ #define MIDI_TX_ENDPOINT 3
+ #define MIDI_TX_SIZE 64
+ #define MIDI_RX_ENDPOINT 4
+ #define MIDI_RX_SIZE 64
+ #define SEREMU_DESC_OFFSET (9 + 9+7+6+6+9+9+9+5+9+5 + 9)
+ #define CONFIG_DESC_SIZE (9 + 9+7+6+6+9+9+9+5+9+5 + 9+9+7+7)
+ #define ENDPOINT1_CONFIG ENDPOINT_TRANSIMIT_ONLY
+ #define ENDPOINT2_CONFIG ENDPOINT_RECEIVE_ONLY
+ #define ENDPOINT3_CONFIG ENDPOINT_TRANSIMIT_ONLY
+ #define ENDPOINT4_CONFIG ENDPOINT_RECEIVE_ONLY
+
+#elif defined(USB_RAWHID)
+ #define VENDOR_ID 0x16C0
+ #define PRODUCT_ID 0x0486
+ #define RAWHID_USAGE_PAGE 0xFFAB // recommended: 0xFF00 to 0xFFFF
+ #define RAWHID_USAGE 0x0200 // recommended: 0x0100 to 0xFFFF
+ #define MANUFACTURER_NAME {'T','e','e','n','s','y','d','u','i','n','o'}
+ #define MANUFACTURER_NAME_LEN 11
+ #define PRODUCT_NAME {'T','e','e','n','s','y','d','u','i','n','o',' ','R','a','w','H','I','D'}
+ #define PRODUCT_NAME_LEN 18
+ #define EP0_SIZE 64
+ #define NUM_ENDPOINTS 6
+ #define NUM_USB_BUFFERS 12
+ #define NUM_INTERFACE 2
+ #define RAWHID_INTERFACE 0 // RawHID
+ #define RAWHID_TX_ENDPOINT 3
+ #define RAWHID_TX_SIZE 64
+ #define RAWHID_TX_INTERVAL 1
+ #define RAWHID_RX_ENDPOINT 4
+ #define RAWHID_RX_SIZE 64
+ #define RAWHID_RX_INTERVAL 1
+ #define SEREMU_INTERFACE 1 // Serial emulation
+ #define SEREMU_TX_ENDPOINT 1
+ #define SEREMU_TX_SIZE 64
+ #define SEREMU_TX_INTERVAL 1
+ #define SEREMU_RX_ENDPOINT 2
+ #define SEREMU_RX_SIZE 32
+ #define SEREMU_RX_INTERVAL 2
+ #define RAWHID_DESC_OFFSET (9 + 9)
+ #define SEREMU_DESC_OFFSET (9 + 9+9+7+7 + 9)
+ #define CONFIG_DESC_SIZE (9 + 9+9+7+7 + 9+9+7+7)
+ #define ENDPOINT1_CONFIG ENDPOINT_TRANSIMIT_ONLY
+ #define ENDPOINT2_CONFIG ENDPOINT_RECEIVE_ONLY
+ #define ENDPOINT3_CONFIG ENDPOINT_TRANSIMIT_ONLY
+ #define ENDPOINT4_CONFIG ENDPOINT_RECEIVE_ONLY
+
+#elif defined(USB_FLIGHTSIM)
+ #define VENDOR_ID 0x16C0
+ #define PRODUCT_ID 0x0488
+ #define MANUFACTURER_NAME {'T','e','e','n','s','y','d','u','i','n','o'}
+ #define MANUFACTURER_NAME_LEN 11
+ #define PRODUCT_NAME {'T','e','e','n','s','y',' ','F','l','i','g','h','t',' ','S','i','m',' ','C','o','n','t','r','o','l','s'}
+ #define PRODUCT_NAME_LEN 26
+ #define EP0_SIZE 64
+ #define NUM_ENDPOINTS 4
+ #define NUM_USB_BUFFERS 20
+ #define NUM_INTERFACE 2
+ #define FLIGHTSIM_INTERFACE 0 // Flight Sim Control
+ #define FLIGHTSIM_TX_ENDPOINT 3
+ #define FLIGHTSIM_TX_SIZE 64
+ #define FLIGHTSIM_TX_INTERVAL 1
+ #define FLIGHTSIM_RX_ENDPOINT 4
+ #define FLIGHTSIM_RX_SIZE 64
+ #define FLIGHTSIM_RX_INTERVAL 1
+ #define SEREMU_INTERFACE 1 // Serial emulation
+ #define SEREMU_TX_ENDPOINT 1
+ #define SEREMU_TX_SIZE 64
+ #define SEREMU_TX_INTERVAL 1
+ #define SEREMU_RX_ENDPOINT 2
+ #define SEREMU_RX_SIZE 32
+ #define SEREMU_RX_INTERVAL 2
+ #define FLIGHTSIM_DESC_OFFSET (9 + 9)
+ #define SEREMU_DESC_OFFSET (9 + 9+9+7+7 + 9)
+ #define CONFIG_DESC_SIZE (9 + 9+9+7+7 + 9+9+7+7)
+ #define ENDPOINT1_CONFIG ENDPOINT_TRANSIMIT_ONLY
+ #define ENDPOINT2_CONFIG ENDPOINT_RECEIVE_ONLY
+ #define ENDPOINT3_CONFIG ENDPOINT_TRANSIMIT_ONLY
+ #define ENDPOINT4_CONFIG ENDPOINT_RECEIVE_ONLY
+
+#endif
+
+// NUM_ENDPOINTS = number of non-zero endpoints (0 to 15)
+extern const uint8_t usb_endpoint_config_table[NUM_ENDPOINTS];
+
+typedef struct {
+ uint16_t wValue;
+ uint16_t wIndex;
+ const uint8_t *addr;
+ uint16_t length;
+} usb_descriptor_list_t;
+
+extern const usb_descriptor_list_t usb_descriptor_list[];
+
+
+#endif // F_CPU >= 20 MHz
+
+#endif
diff --git a/ports/teensy/core/usb_dev.c b/ports/teensy/core/usb_dev.c
new file mode 100644
index 000000000..6cf85d3fd
--- /dev/null
+++ b/ports/teensy/core/usb_dev.c
@@ -0,0 +1,980 @@
+/* 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 F_CPU >= 20000000
+
+#include "mk20dx128.h"
+//#include "HardwareSerial.h"
+#include "usb_dev.h"
+#include "usb_mem.h"
+
+// buffer descriptor table
+
+typedef struct {
+ uint32_t desc;
+ void * addr;
+} bdt_t;
+
+__attribute__ ((section(".usbdescriptortable"), used))
+static bdt_t table[(NUM_ENDPOINTS+1)*4];
+
+static usb_packet_t *rx_first[NUM_ENDPOINTS];
+static usb_packet_t *rx_last[NUM_ENDPOINTS];
+static usb_packet_t *tx_first[NUM_ENDPOINTS];
+static usb_packet_t *tx_last[NUM_ENDPOINTS];
+uint16_t usb_rx_byte_count_data[NUM_ENDPOINTS];
+
+static uint8_t tx_state[NUM_ENDPOINTS];
+#define TX_STATE_BOTH_FREE_EVEN_FIRST 0
+#define TX_STATE_BOTH_FREE_ODD_FIRST 1
+#define TX_STATE_EVEN_FREE 2
+#define TX_STATE_ODD_FREE 3
+#define TX_STATE_NONE_FREE_EVEN_FIRST 4
+#define TX_STATE_NONE_FREE_ODD_FIRST 5
+
+#define BDT_OWN 0x80
+#define BDT_DATA1 0x40
+#define BDT_DATA0 0x00
+#define BDT_DTS 0x08
+#define BDT_STALL 0x04
+#define BDT_PID(n) (((n) >> 2) & 15)
+
+#define BDT_DESC(count, data) (BDT_OWN | BDT_DTS \
+ | ((data) ? BDT_DATA1 : BDT_DATA0) \
+ | ((count) << 16))
+
+#define TX 1
+#define RX 0
+#define ODD 1
+#define EVEN 0
+#define DATA0 0
+#define DATA1 1
+#define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
+#define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
+
+
+static union {
+ struct {
+ union {
+ struct {
+ uint8_t bmRequestType;
+ uint8_t bRequest;
+ };
+ uint16_t wRequestAndType;
+ };
+ uint16_t wValue;
+ uint16_t wIndex;
+ uint16_t wLength;
+ };
+ struct {
+ uint32_t word1;
+ uint32_t word2;
+ };
+} setup;
+
+
+#define GET_STATUS 0
+#define CLEAR_FEATURE 1
+#define SET_FEATURE 3
+#define SET_ADDRESS 5
+#define GET_DESCRIPTOR 6
+#define SET_DESCRIPTOR 7
+#define GET_CONFIGURATION 8
+#define SET_CONFIGURATION 9
+#define GET_INTERFACE 10
+#define SET_INTERFACE 11
+#define SYNCH_FRAME 12
+
+// SETUP always uses a DATA0 PID for the data field of the SETUP transaction.
+// transactions in the data phase start with DATA1 and toggle (figure 8-12, USB1.1)
+// Status stage uses a DATA1 PID.
+
+static uint8_t ep0_rx0_buf[EP0_SIZE] __attribute__ ((aligned (4)));
+static uint8_t ep0_rx1_buf[EP0_SIZE] __attribute__ ((aligned (4)));
+static const uint8_t *ep0_tx_ptr = NULL;
+static uint16_t ep0_tx_len;
+static uint8_t ep0_tx_bdt_bank = 0;
+static uint8_t ep0_tx_data_toggle = 0;
+uint8_t usb_rx_memory_needed = 0;
+
+volatile uint8_t usb_configuration = 0;
+volatile uint8_t usb_reboot_timer = 0;
+
+
+static void endpoint0_stall(void)
+{
+ USB0_ENDPT0 = USB_ENDPT_EPSTALL | USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
+}
+
+
+static void endpoint0_transmit(const void *data, uint32_t len)
+{
+#if 0
+ serial_print("tx0:");
+ serial_phex32((uint32_t)data);
+ serial_print(",");
+ serial_phex16(len);
+ serial_print(ep0_tx_bdt_bank ? ", odd" : ", even");
+ serial_print(ep0_tx_data_toggle ? ", d1\n" : ", d0\n");
+#endif
+ table[index(0, TX, ep0_tx_bdt_bank)].addr = (void *)data;
+ table[index(0, TX, ep0_tx_bdt_bank)].desc = BDT_DESC(len, ep0_tx_data_toggle);
+ ep0_tx_data_toggle ^= 1;
+ ep0_tx_bdt_bank ^= 1;
+}
+
+static uint8_t reply_buffer[8];
+
+static void usb_setup(void)
+{
+ const uint8_t *data = NULL;
+ uint32_t datalen = 0;
+ const usb_descriptor_list_t *list;
+ uint32_t size;
+ volatile uint8_t *reg;
+ uint8_t epconf;
+ const uint8_t *cfg;
+ int i;
+
+ switch (setup.wRequestAndType) {
+ case 0x0500: // SET_ADDRESS
+ break;
+ case 0x0900: // SET_CONFIGURATION
+ //serial_print("configure\n");
+ usb_configuration = setup.wValue;
+ reg = &USB0_ENDPT1;
+ cfg = usb_endpoint_config_table;
+ // clear all BDT entries, free any allocated memory...
+ for (i=4; i < (NUM_ENDPOINTS+1)*4; i++) {
+ if (table[i].desc & BDT_OWN) {
+ usb_free((usb_packet_t *)((uint8_t *)(table[i].addr) - 8));
+ }
+ }
+ // free all queued packets
+ for (i=0; i < NUM_ENDPOINTS; i++) {
+ usb_packet_t *p, *n;
+ p = rx_first[i];
+ while (p) {
+ n = p->next;
+ usb_free(p);
+ p = n;
+ }
+ rx_first[i] = NULL;
+ rx_last[i] = NULL;
+ p = tx_first[i];
+ while (p) {
+ n = p->next;
+ usb_free(p);
+ p = n;
+ }
+ tx_first[i] = NULL;
+ tx_last[i] = NULL;
+ usb_rx_byte_count_data[i] = 0;
+ switch (tx_state[i]) {
+ case TX_STATE_EVEN_FREE:
+ case TX_STATE_NONE_FREE_EVEN_FIRST:
+ tx_state[i] = TX_STATE_BOTH_FREE_EVEN_FIRST;
+ break;
+ case TX_STATE_ODD_FREE:
+ case TX_STATE_NONE_FREE_ODD_FIRST:
+ tx_state[i] = TX_STATE_BOTH_FREE_ODD_FIRST;
+ break;
+ default:
+ break;
+ }
+ }
+ usb_rx_memory_needed = 0;
+ for (i=1; i <= NUM_ENDPOINTS; i++) {
+ epconf = *cfg++;
+ *reg = epconf;
+ reg += 4;
+ if (epconf & USB_ENDPT_EPRXEN) {
+ usb_packet_t *p;
+ p = usb_malloc();
+ if (p) {
+ table[index(i, RX, EVEN)].addr = p->buf;
+ table[index(i, RX, EVEN)].desc = BDT_DESC(64, 0);
+ } else {
+ table[index(i, RX, EVEN)].desc = 0;
+ usb_rx_memory_needed++;
+ }
+ p = usb_malloc();
+ if (p) {
+ table[index(i, RX, ODD)].addr = p->buf;
+ table[index(i, RX, ODD)].desc = BDT_DESC(64, 1);
+ } else {
+ table[index(i, RX, ODD)].desc = 0;
+ usb_rx_memory_needed++;
+ }
+ }
+ table[index(i, TX, EVEN)].desc = 0;
+ table[index(i, TX, ODD)].desc = 0;
+ }
+ break;
+ case 0x0880: // GET_CONFIGURATION
+ reply_buffer[0] = usb_configuration;
+ datalen = 1;
+ data = reply_buffer;
+ break;
+ case 0x0080: // GET_STATUS (device)
+ reply_buffer[0] = 0;
+ reply_buffer[1] = 0;
+ datalen = 2;
+ data = reply_buffer;
+ break;
+ case 0x0082: // GET_STATUS (endpoint)
+ if (setup.wIndex > NUM_ENDPOINTS) {
+ // TODO: do we need to handle IN vs OUT here?
+ endpoint0_stall();
+ return;
+ }
+ reply_buffer[0] = 0;
+ reply_buffer[1] = 0;
+ if (*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4) & 0x02) reply_buffer[0] = 1;
+ data = reply_buffer;
+ datalen = 2;
+ break;
+ case 0x0102: // CLEAR_FEATURE (endpoint)
+ i = setup.wIndex & 0x7F;
+ if (i > NUM_ENDPOINTS || setup.wValue != 0) {
+ // TODO: do we need to handle IN vs OUT here?
+ endpoint0_stall();
+ return;
+ }
+ (*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) &= ~0x02;
+ // TODO: do we need to clear the data toggle here?
+ break;
+ case 0x0302: // SET_FEATURE (endpoint)
+ i = setup.wIndex & 0x7F;
+ if (i > NUM_ENDPOINTS || setup.wValue != 0) {
+ // TODO: do we need to handle IN vs OUT here?
+ endpoint0_stall();
+ return;
+ }
+ (*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) |= 0x02;
+ // TODO: do we need to clear the data toggle here?
+ break;
+ case 0x0680: // GET_DESCRIPTOR
+ case 0x0681:
+ //serial_print("desc:");
+ //serial_phex16(setup.wValue);
+ //serial_print("\n");
+ for (list = usb_descriptor_list; 1; list++) {
+ if (list->addr == NULL) break;
+ //if (setup.wValue == list->wValue &&
+ //(setup.wIndex == list->wIndex) || ((setup.wValue >> 8) == 3)) {
+ if (setup.wValue == list->wValue && setup.wIndex == list->wIndex) {
+ data = list->addr;
+ if ((setup.wValue >> 8) == 3) {
+ // for string descriptors, use the descriptor's
+ // length field, allowing runtime configured
+ // length.
+ datalen = *(list->addr);
+ } else {
+ datalen = list->length;
+ }
+#if 0
+ serial_print("Desc found, ");
+ serial_phex32((uint32_t)data);
+ serial_print(",");
+ serial_phex16(datalen);
+ serial_print(",");
+ serial_phex(data[0]);
+ serial_phex(data[1]);
+ serial_phex(data[2]);
+ serial_phex(data[3]);
+ serial_phex(data[4]);
+ serial_phex(data[5]);
+ serial_print("\n");
+#endif
+ goto send;
+ }
+ }
+ //serial_print("desc: not found\n");
+ endpoint0_stall();
+ return;
+#if defined(CDC_STATUS_INTERFACE)
+ case 0x2221: // CDC_SET_CONTROL_LINE_STATE
+ usb_cdc_line_rtsdtr = setup.wValue;
+ //serial_print("set control line state\n");
+ break;
+ case 0x2321: // CDC_SEND_BREAK
+ break;
+ case 0x2021: // CDC_SET_LINE_CODING
+ //serial_print("set coding, waiting...\n");
+ return;
+#endif
+
+// TODO: this does not work... why?
+#if defined(SEREMU_INTERFACE) || defined(KEYBOARD_INTERFACE)
+ case 0x0921: // HID SET_REPORT
+ //serial_print(":)\n");
+ return;
+ case 0x0A21: // HID SET_IDLE
+ break;
+ // case 0xC940:
+#endif
+ default:
+ endpoint0_stall();
+ return;
+ }
+ send:
+ //serial_print("setup send ");
+ //serial_phex32(data);
+ //serial_print(",");
+ //serial_phex16(datalen);
+ //serial_print("\n");
+
+ if (datalen > setup.wLength) datalen = setup.wLength;
+ size = datalen;
+ if (size > EP0_SIZE) size = EP0_SIZE;
+ endpoint0_transmit(data, size);
+ data += size;
+ datalen -= size;
+ if (datalen == 0 && size < EP0_SIZE) return;
+
+ size = datalen;
+ if (size > EP0_SIZE) size = EP0_SIZE;
+ endpoint0_transmit(data, size);
+ data += size;
+ datalen -= size;
+ if (datalen == 0 && size < EP0_SIZE) return;
+
+ ep0_tx_ptr = data;
+ ep0_tx_len = datalen;
+}
+
+
+
+//A bulk endpoint's toggle sequence is initialized to DATA0 when the endpoint
+//experiences any configuration event (configuration events are explained in
+//Sections 9.1.1.5 and 9.4.5).
+
+//Configuring a device or changing an alternate setting causes all of the status
+//and configuration values associated with endpoints in the affected interfaces
+//to be set to their default values. This includes setting the data toggle of
+//any endpoint using data toggles to the value DATA0.
+
+//For endpoints using data toggle, regardless of whether an endpoint has the
+//Halt feature set, a ClearFeature(ENDPOINT_HALT) request always results in the
+//data toggle being reinitialized to DATA0.
+
+
+
+// #define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
+
+static void usb_control(uint32_t stat)
+{
+ bdt_t *b;
+ uint32_t pid, size;
+ uint8_t *buf;
+ const uint8_t *data;
+
+ b = stat2bufferdescriptor(stat);
+ pid = BDT_PID(b->desc);
+ //count = b->desc >> 16;
+ buf = b->addr;
+ //serial_print("pid:");
+ //serial_phex(pid);
+ //serial_print(", count:");
+ //serial_phex(count);
+ //serial_print("\n");
+
+ switch (pid) {
+ case 0x0D: // Setup received from host
+ //serial_print("PID=Setup\n");
+ //if (count != 8) ; // panic?
+ // grab the 8 byte setup info
+ setup.word1 = *(uint32_t *)(buf);
+ setup.word2 = *(uint32_t *)(buf + 4);
+
+ // give the buffer back
+ b->desc = BDT_DESC(EP0_SIZE, DATA1);
+ //table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 1);
+ //table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 1);
+
+ // clear any leftover pending IN transactions
+ ep0_tx_ptr = NULL;
+ if (ep0_tx_data_toggle) {
+ }
+ //if (table[index(0, TX, EVEN)].desc & 0x80) {
+ //serial_print("leftover tx even\n");
+ //}
+ //if (table[index(0, TX, ODD)].desc & 0x80) {
+ //serial_print("leftover tx odd\n");
+ //}
+ table[index(0, TX, EVEN)].desc = 0;
+ table[index(0, TX, ODD)].desc = 0;
+ // first IN after Setup is always DATA1
+ ep0_tx_data_toggle = 1;
+
+#if 0
+ serial_print("bmRequestType:");
+ serial_phex(setup.bmRequestType);
+ serial_print(", bRequest:");
+ serial_phex(setup.bRequest);
+ serial_print(", wValue:");
+ serial_phex16(setup.wValue);
+ serial_print(", wIndex:");
+ serial_phex16(setup.wIndex);
+ serial_print(", len:");
+ serial_phex16(setup.wLength);
+ serial_print("\n");
+#endif
+ // actually "do" the setup request
+ usb_setup();
+ // unfreeze the USB, now that we're ready
+ USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
+ break;
+ case 0x01: // OUT transaction received from host
+ case 0x02:
+ //serial_print("PID=OUT\n");
+#ifdef CDC_STATUS_INTERFACE
+ if (setup.wRequestAndType == 0x2021 /*CDC_SET_LINE_CODING*/) {
+ int i;
+ uint8_t *dst = (uint8_t *)usb_cdc_line_coding;
+ //serial_print("set line coding ");
+ for (i=0; i<7; i++) {
+ //serial_phex(*buf);
+ *dst++ = *buf++;
+ }
+ //serial_phex32(usb_cdc_line_coding[0]);
+ //serial_print("\n");
+ if (usb_cdc_line_coding[0] == 134) usb_reboot_timer = 15;
+ endpoint0_transmit(NULL, 0);
+ }
+#endif
+#ifdef KEYBOARD_INTERFACE
+ if (setup.word1 == 0x02000921 && setup.word2 == ((1<<16)|KEYBOARD_INTERFACE)) {
+ keyboard_leds = buf[0];
+ endpoint0_transmit(NULL, 0);
+ }
+#endif
+#ifdef SEREMU_INTERFACE
+ if (setup.word1 == 0x03000921 && setup.word2 == ((4<<16)|SEREMU_INTERFACE)
+ && buf[0] == 0xA9 && buf[1] == 0x45 && buf[2] == 0xC2 && buf[3] == 0x6B) {
+ usb_reboot_timer = 5;
+ endpoint0_transmit(NULL, 0);
+ }
+#endif
+ // give the buffer back
+ b->desc = BDT_DESC(EP0_SIZE, DATA1);
+ break;
+
+ case 0x09: // IN transaction completed to host
+ //serial_print("PID=IN:");
+ //serial_phex(stat);
+ //serial_print("\n");
+
+ // send remaining data, if any...
+ data = ep0_tx_ptr;
+ if (data) {
+ size = ep0_tx_len;
+ if (size > EP0_SIZE) size = EP0_SIZE;
+ endpoint0_transmit(data, size);
+ data += size;
+ ep0_tx_len -= size;
+ ep0_tx_ptr = (ep0_tx_len > 0 || size == EP0_SIZE) ? data : NULL;
+ }
+
+ if (setup.bRequest == 5 && setup.bmRequestType == 0) {
+ setup.bRequest = 0;
+ //serial_print("set address: ");
+ //serial_phex16(setup.wValue);
+ //serial_print("\n");
+ USB0_ADDR = setup.wValue;
+ }
+
+ break;
+ //default:
+ //serial_print("PID=unknown:");
+ //serial_phex(pid);
+ //serial_print("\n");
+ }
+ USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
+}
+
+
+
+
+
+
+usb_packet_t *usb_rx(uint32_t endpoint)
+{
+ usb_packet_t *ret;
+ endpoint--;
+ if (endpoint >= NUM_ENDPOINTS) return NULL;
+ __disable_irq();
+ ret = rx_first[endpoint];
+ if (ret) {
+ rx_first[endpoint] = ret->next;
+ usb_rx_byte_count_data[endpoint] -= ret->len;
+ }
+ __enable_irq();
+ //serial_print("rx, epidx=");
+ //serial_phex(endpoint);
+ //serial_print(", packet=");
+ //serial_phex32(ret);
+ //serial_print("\n");
+ return ret;
+}
+
+static uint32_t usb_queue_byte_count(const usb_packet_t *p)
+{
+ uint32_t count=0;
+
+ __disable_irq();
+ for ( ; p; p = p->next) {
+ count += p->len;
+ }
+ __enable_irq();
+ return count;
+}
+
+// TODO: make this an inline function...
+/*
+uint32_t usb_rx_byte_count(uint32_t endpoint)
+{
+ endpoint--;
+ if (endpoint >= NUM_ENDPOINTS) return 0;
+ return usb_rx_byte_count_data[endpoint];
+ //return usb_queue_byte_count(rx_first[endpoint]);
+}
+*/
+
+uint32_t usb_tx_byte_count(uint32_t endpoint)
+{
+ endpoint--;
+ if (endpoint >= NUM_ENDPOINTS) return 0;
+ return usb_queue_byte_count(tx_first[endpoint]);
+}
+
+uint32_t usb_tx_packet_count(uint32_t endpoint)
+{
+ const usb_packet_t *p;
+ uint32_t count=0;
+
+ endpoint--;
+ if (endpoint >= NUM_ENDPOINTS) return 0;
+ __disable_irq();
+ for (p = tx_first[endpoint]; p; p = p->next) count++;
+ __enable_irq();
+ return count;
+}
+
+
+// Called from usb_free, but only when usb_rx_memory_needed > 0, indicating
+// receive endpoints are starving for memory. The intention is to give
+// endpoints needing receive memory priority over the user's code, which is
+// likely calling usb_malloc to obtain memory for transmitting. When the
+// user is creating data very quickly, their consumption could starve reception
+// without this prioritization. The packet buffer (input) is assigned to the
+// first endpoint needing memory.
+//
+void usb_rx_memory(usb_packet_t *packet)
+{
+ unsigned int i;
+ const uint8_t *cfg;
+
+ cfg = usb_endpoint_config_table;
+ //serial_print("rx_mem:");
+ __disable_irq();
+ for (i=1; i <= NUM_ENDPOINTS; i++) {
+ if (*cfg++ & USB_ENDPT_EPRXEN) {
+ if (table[index(i, RX, EVEN)].desc == 0) {
+ table[index(i, RX, EVEN)].addr = packet->buf;
+ table[index(i, RX, EVEN)].desc = BDT_DESC(64, 0);
+ usb_rx_memory_needed--;
+ __enable_irq();
+ //serial_phex(i);
+ //serial_print(",even\n");
+ return;
+ }
+ if (table[index(i, RX, ODD)].desc == 0) {
+ table[index(i, RX, ODD)].addr = packet->buf;
+ table[index(i, RX, ODD)].desc = BDT_DESC(64, 1);
+ usb_rx_memory_needed--;
+ __enable_irq();
+ //serial_phex(i);
+ //serial_print(",odd\n");
+ return;
+ }
+ }
+ }
+ __enable_irq();
+ // we should never reach this point. If we get here, it means
+ // usb_rx_memory_needed was set greater than zero, but no memory
+ // was actually needed.
+ usb_rx_memory_needed = 0;
+ usb_free(packet);
+ return;
+}
+
+//#define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
+//#define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
+
+void usb_tx(uint32_t endpoint, usb_packet_t *packet)
+{
+ bdt_t *b = &table[index(endpoint, TX, EVEN)];
+ uint8_t next;
+
+ endpoint--;
+ if (endpoint >= NUM_ENDPOINTS) return;
+ __disable_irq();
+ //serial_print("txstate=");
+ //serial_phex(tx_state[endpoint]);
+ //serial_print("\n");
+ switch (tx_state[endpoint]) {
+ case TX_STATE_BOTH_FREE_EVEN_FIRST:
+ next = TX_STATE_ODD_FREE;
+ break;
+ case TX_STATE_BOTH_FREE_ODD_FIRST:
+ b++;
+ next = TX_STATE_EVEN_FREE;
+ break;
+ case TX_STATE_EVEN_FREE:
+ next = TX_STATE_NONE_FREE_ODD_FIRST;
+ break;
+ case TX_STATE_ODD_FREE:
+ b++;
+ next = TX_STATE_NONE_FREE_EVEN_FIRST;
+ break;
+ default:
+ if (tx_first[endpoint] == NULL) {
+ tx_first[endpoint] = packet;
+ } else {
+ tx_last[endpoint]->next = packet;
+ }
+ tx_last[endpoint] = packet;
+ __enable_irq();
+ return;
+ }
+ tx_state[endpoint] = next;
+ b->addr = packet->buf;
+ b->desc = BDT_DESC(packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0);
+ __enable_irq();
+}
+
+
+
+
+
+
+void _reboot_Teensyduino_(void)
+{
+ // TODO: initialize R0 with a code....
+ __asm__ volatile("bkpt");
+}
+
+
+
+void usb_isr(void)
+{
+ uint8_t status, stat, t;
+
+ //serial_print("isr");
+ //status = USB0_ISTAT;
+ //serial_phex(status);
+ //serial_print("\n");
+ restart:
+ status = USB0_ISTAT;
+
+ if ((status & USB_INTEN_SOFTOKEN /* 04 */ )) {
+ if (usb_configuration) {
+ t = usb_reboot_timer;
+ if (t) {
+ usb_reboot_timer = --t;
+ if (!t) _reboot_Teensyduino_();
+ }
+#ifdef CDC_DATA_INTERFACE
+ t = usb_cdc_transmit_flush_timer;
+ if (t) {
+ usb_cdc_transmit_flush_timer = --t;
+ if (t == 0) usb_serial_flush_callback();
+ }
+#endif
+#ifdef SEREMU_INTERFACE
+ t = usb_seremu_transmit_flush_timer;
+ if (t) {
+ usb_seremu_transmit_flush_timer = --t;
+ if (t == 0) usb_seremu_flush_callback();
+ }
+#endif
+#ifdef MIDI_INTERFACE
+ usb_midi_flush_output();
+#endif
+#ifdef FLIGHTSIM_INTERFACE
+ usb_flightsim_flush_callback();
+#endif
+ }
+ USB0_ISTAT = USB_INTEN_SOFTOKEN;
+ }
+
+ if ((status & USB_ISTAT_TOKDNE /* 08 */ )) {
+ uint8_t endpoint;
+ stat = USB0_STAT;
+ //serial_print("token: ep=");
+ //serial_phex(stat >> 4);
+ //serial_print(stat & 0x08 ? ",tx" : ",rx");
+ //serial_print(stat & 0x04 ? ",odd\n" : ",even\n");
+ endpoint = stat >> 4;
+ if (endpoint == 0) {
+ usb_control(stat);
+ } else {
+ bdt_t *b = stat2bufferdescriptor(stat);
+ usb_packet_t *packet = (usb_packet_t *)((uint8_t *)(b->addr) - 8);
+#if 0
+ serial_print("ep:");
+ serial_phex(endpoint);
+ serial_print(", pid:");
+ serial_phex(BDT_PID(b->desc));
+ serial_print(((uint32_t)b & 8) ? ", odd" : ", even");
+ serial_print(", count:");
+ serial_phex(b->desc >> 16);
+ serial_print("\n");
+#endif
+ endpoint--; // endpoint is index to zero-based arrays
+
+ if (stat & 0x08) { // transmit
+ usb_free(packet);
+ packet = tx_first[endpoint];
+ if (packet) {
+ //serial_print("tx packet\n");
+ tx_first[endpoint] = packet->next;
+ b->addr = packet->buf;
+ switch (tx_state[endpoint]) {
+ case TX_STATE_BOTH_FREE_EVEN_FIRST:
+ tx_state[endpoint] = TX_STATE_ODD_FREE;
+ break;
+ case TX_STATE_BOTH_FREE_ODD_FIRST:
+ tx_state[endpoint] = TX_STATE_EVEN_FREE;
+ break;
+ case TX_STATE_EVEN_FREE:
+ tx_state[endpoint] = TX_STATE_NONE_FREE_ODD_FIRST;
+ break;
+ case TX_STATE_ODD_FREE:
+ tx_state[endpoint] = TX_STATE_NONE_FREE_EVEN_FIRST;
+ break;
+ default:
+ break;
+ }
+ b->desc = BDT_DESC(packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0);
+ } else {
+ //serial_print("tx no packet\n");
+ switch (tx_state[endpoint]) {
+ case TX_STATE_BOTH_FREE_EVEN_FIRST:
+ case TX_STATE_BOTH_FREE_ODD_FIRST:
+ break;
+ case TX_STATE_EVEN_FREE:
+ tx_state[endpoint] = TX_STATE_BOTH_FREE_EVEN_FIRST;
+ break;
+ case TX_STATE_ODD_FREE:
+ tx_state[endpoint] = TX_STATE_BOTH_FREE_ODD_FIRST;
+ break;
+ default:
+ tx_state[endpoint] = ((uint32_t)b & 8) ?
+ TX_STATE_ODD_FREE : TX_STATE_EVEN_FREE;
+ break;
+ }
+ }
+ } else { // receive
+ packet->len = b->desc >> 16;
+ if (packet->len > 0) {
+ packet->index = 0;
+ packet->next = NULL;
+ if (rx_first[endpoint] == NULL) {
+ //serial_print("rx 1st, epidx=");
+ //serial_phex(endpoint);
+ //serial_print(", packet=");
+ //serial_phex32((uint32_t)packet);
+ //serial_print("\n");
+ rx_first[endpoint] = packet;
+ } else {
+ //serial_print("rx Nth, epidx=");
+ //serial_phex(endpoint);
+ //serial_print(", packet=");
+ //serial_phex32((uint32_t)packet);
+ //serial_print("\n");
+ rx_last[endpoint]->next = packet;
+ }
+ rx_last[endpoint] = packet;
+ usb_rx_byte_count_data[endpoint] += packet->len;
+ // TODO: implement a per-endpoint maximum # of allocated packets
+ // so a flood of incoming data on 1 endpoint doesn't starve
+ // the others if the user isn't reading it regularly
+ packet = usb_malloc();
+ if (packet) {
+ b->addr = packet->buf;
+ b->desc = BDT_DESC(64, ((uint32_t)b & 8) ? DATA1 : DATA0);
+ } else {
+ //serial_print("starving ");
+ //serial_phex(endpoint + 1);
+ //serial_print(((uint32_t)b & 8) ? ",odd\n" : ",even\n");
+ b->desc = 0;
+ usb_rx_memory_needed++;
+ }
+ } else {
+ b->desc = BDT_DESC(64, ((uint32_t)b & 8) ? DATA1 : DATA0);
+ }
+ }
+
+
+
+
+ }
+ USB0_ISTAT = USB_ISTAT_TOKDNE;
+ goto restart;
+ }
+
+
+
+ if (status & USB_ISTAT_USBRST /* 01 */ ) {
+ //serial_print("reset\n");
+
+ // initialize BDT toggle bits
+ USB0_CTL = USB_CTL_ODDRST;
+ ep0_tx_bdt_bank = 0;
+
+ // set up buffers to receive Setup and OUT packets
+ table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 0);
+ table[index(0, RX, EVEN)].addr = ep0_rx0_buf;
+ table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 0);
+ table[index(0, RX, ODD)].addr = ep0_rx1_buf;
+ table[index(0, TX, EVEN)].desc = 0;
+ table[index(0, TX, ODD)].desc = 0;
+
+ // activate endpoint 0
+ USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
+
+ // clear all ending interrupts
+ USB0_ERRSTAT = 0xFF;
+ USB0_ISTAT = 0xFF;
+
+ // set the address to zero during enumeration
+ USB0_ADDR = 0;
+
+ // enable other interrupts
+ USB0_ERREN = 0xFF;
+ USB0_INTEN = USB_INTEN_TOKDNEEN |
+ USB_INTEN_SOFTOKEN |
+ USB_INTEN_STALLEN |
+ USB_INTEN_ERROREN |
+ USB_INTEN_USBRSTEN |
+ USB_INTEN_SLEEPEN;
+
+ // is this necessary?
+ USB0_CTL = USB_CTL_USBENSOFEN;
+ return;
+ }
+
+
+ if ((status & USB_ISTAT_STALL /* 80 */ )) {
+ //serial_print("stall:\n");
+ USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
+ USB0_ISTAT = USB_ISTAT_STALL;
+ }
+ if ((status & USB_ISTAT_ERROR /* 02 */ )) {
+ uint8_t err = USB0_ERRSTAT;
+ USB0_ERRSTAT = err;
+ //serial_print("err:");
+ //serial_phex(err);
+ //serial_print("\n");
+ USB0_ISTAT = USB_ISTAT_ERROR;
+ }
+
+ if ((status & USB_ISTAT_SLEEP /* 10 */ )) {
+ //serial_print("sleep\n");
+ USB0_ISTAT = USB_ISTAT_SLEEP;
+ }
+
+}
+
+
+
+void usb_init(void)
+{
+ int i;
+
+ //serial_begin(BAUD2DIV(115200));
+ //serial_print("usb_init\n");
+
+ usb_init_serialnumber();
+
+ for (i=0; i <= NUM_ENDPOINTS*4; i++) {
+ table[i].desc = 0;
+ table[i].addr = 0;
+ }
+
+ // this basically follows the flowchart in the Kinetis
+ // Quick Reference User Guide, Rev. 1, 03/2012, page 141
+
+ // assume 48 MHz clock already running
+ // SIM - enable clock
+ SIM_SCGC4 |= SIM_SCGC4_USBOTG;
+
+ // reset USB module
+ USB0_USBTRC0 = USB_USBTRC_USBRESET;
+ while ((USB0_USBTRC0 & USB_USBTRC_USBRESET) != 0) ; // wait for reset to end
+
+ // set desc table base addr
+ USB0_BDTPAGE1 = ((uint32_t)table) >> 8;
+ USB0_BDTPAGE2 = ((uint32_t)table) >> 16;
+ USB0_BDTPAGE3 = ((uint32_t)table) >> 24;
+
+ // clear all ISR flags
+ USB0_ISTAT = 0xFF;
+ USB0_ERRSTAT = 0xFF;
+ USB0_OTGISTAT = 0xFF;
+
+ USB0_USBTRC0 |= 0x40; // undocumented bit
+
+ // enable USB
+ USB0_CTL = USB_CTL_USBENSOFEN;
+ USB0_USBCTRL = 0;
+
+ // enable reset interrupt
+ USB0_INTEN = USB_INTEN_USBRSTEN;
+
+ // enable interrupt in NVIC...
+ NVIC_SET_PRIORITY(IRQ_USBOTG, 112);
+ NVIC_ENABLE_IRQ(IRQ_USBOTG);
+
+ // enable d+ pullup
+ USB0_CONTROL = USB_CONTROL_DPPULLUPNONOTG;
+}
+
+
+#else // F_CPU < 20 MHz
+
+void usb_init(void)
+{
+}
+
+#endif // F_CPU >= 20 MHz
diff --git a/ports/teensy/core/usb_dev.h b/ports/teensy/core/usb_dev.h
new file mode 100644
index 000000000..211cebec0
--- /dev/null
+++ b/ports/teensy/core/usb_dev.h
@@ -0,0 +1,108 @@
+/* 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.
+ */
+
+#ifndef _usb_dev_h_
+#define _usb_dev_h_
+
+#if F_CPU >= 20000000
+
+// This header is NOT meant to be included when compiling
+// user sketches in Arduino. The low-level functions
+// provided by usb_dev.c are meant to be called only by
+// code which provides higher-level interfaces to the user.
+
+#include "usb_mem.h"
+#include "usb_desc.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void usb_init(void);
+void usb_init_serialnumber(void);
+void usb_isr(void);
+usb_packet_t *usb_rx(uint32_t endpoint);
+uint32_t usb_tx_byte_count(uint32_t endpoint);
+uint32_t usb_tx_packet_count(uint32_t endpoint);
+void usb_tx(uint32_t endpoint, usb_packet_t *packet);
+void usb_tx_isr(uint32_t endpoint, usb_packet_t *packet);
+
+extern volatile uint8_t usb_configuration;
+
+extern uint16_t usb_rx_byte_count_data[NUM_ENDPOINTS];
+static inline uint32_t usb_rx_byte_count(uint32_t endpoint) __attribute__((always_inline));
+static inline uint32_t usb_rx_byte_count(uint32_t endpoint)
+{
+ endpoint--;
+ if (endpoint >= NUM_ENDPOINTS) return 0;
+ return usb_rx_byte_count_data[endpoint];
+}
+
+#ifdef CDC_DATA_INTERFACE
+extern uint32_t usb_cdc_line_coding[2];
+extern volatile uint8_t usb_cdc_line_rtsdtr;
+extern volatile uint8_t usb_cdc_transmit_flush_timer;
+extern void usb_serial_flush_callback(void);
+#endif
+
+#ifdef SEREMU_INTERFACE
+extern volatile uint8_t usb_seremu_transmit_flush_timer;
+extern void usb_seremu_flush_callback(void);
+#endif
+
+#ifdef KEYBOARD_INTERFACE
+extern uint8_t keyboard_modifier_keys;
+extern uint8_t keyboard_keys[6];
+extern uint8_t keyboard_protocol;
+extern uint8_t keyboard_idle_config;
+extern uint8_t keyboard_idle_count;
+extern volatile uint8_t keyboard_leds;
+#endif
+
+#ifdef MIDI_INTERFACE
+extern void usb_midi_flush_output(void);
+#endif
+
+#ifdef FLIGHTSIM_INTERFACE
+extern void usb_flightsim_flush_callback(void);
+#endif
+
+
+
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif // F_CPU >= 20 MHz
+
+#endif
diff --git a/ports/teensy/core/usb_mem.c b/ports/teensy/core/usb_mem.c
new file mode 100644
index 000000000..2424327d3
--- /dev/null
+++ b/ports/teensy/core/usb_mem.c
@@ -0,0 +1,109 @@
+/* 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 F_CPU >= 20000000
+
+#include "mk20dx128.h"
+//#include "HardwareSerial.h"
+#include "usb_dev.h"
+#include "usb_mem.h"
+
+__attribute__ ((section(".usbbuffers"), used))
+unsigned char usb_buffer_memory[NUM_USB_BUFFERS * sizeof(usb_packet_t)];
+
+static uint32_t usb_buffer_available = 0xFFFFFFFF;
+
+// use bitmask and CLZ instruction to implement fast free list
+// http://www.archivum.info/gnu.gcc.help/2006-08/00148/Re-GCC-Inline-Assembly.html
+// http://gcc.gnu.org/ml/gcc/2012-06/msg00015.html
+// __builtin_clz()
+
+usb_packet_t * usb_malloc(void)
+{
+ unsigned int n, avail;
+ uint8_t *p;
+
+ __disable_irq();
+ avail = usb_buffer_available;
+ n = __builtin_clz(avail); // clz = count leading zeros
+ if (n >= NUM_USB_BUFFERS) {
+ __enable_irq();
+ return NULL;
+ }
+ //serial_print("malloc:");
+ //serial_phex(n);
+ //serial_print("\n");
+
+ usb_buffer_available = avail & ~(0x80000000 >> n);
+ __enable_irq();
+ p = usb_buffer_memory + (n * sizeof(usb_packet_t));
+ //serial_print("malloc:");
+ //serial_phex32((int)p);
+ //serial_print("\n");
+ *(uint32_t *)p = 0;
+ *(uint32_t *)(p + 4) = 0;
+ return (usb_packet_t *)p;
+}
+
+// for the receive endpoints to request memory
+extern uint8_t usb_rx_memory_needed;
+extern void usb_rx_memory(usb_packet_t *packet);
+
+void usb_free(usb_packet_t *p)
+{
+ unsigned int n, mask;
+
+ //serial_print("free:");
+ n = ((uint8_t *)p - usb_buffer_memory) / sizeof(usb_packet_t);
+ if (n >= NUM_USB_BUFFERS) return;
+ //serial_phex(n);
+ //serial_print("\n");
+
+ // if any endpoints are starving for memory to receive
+ // packets, give this memory to them immediately!
+ if (usb_rx_memory_needed && usb_configuration) {
+ //serial_print("give to rx:");
+ //serial_phex32((int)p);
+ //serial_print("\n");
+ usb_rx_memory(p);
+ return;
+ }
+
+ mask = (0x80000000 >> n);
+ __disable_irq();
+ usb_buffer_available |= mask;
+ __enable_irq();
+
+ //serial_print("free:");
+ //serial_phex32((int)p);
+ //serial_print("\n");
+}
+
+#endif // F_CPU >= 20 MHz
diff --git a/ports/teensy/core/usb_mem.h b/ports/teensy/core/usb_mem.h
new file mode 100644
index 000000000..94d1eb4d2
--- /dev/null
+++ b/ports/teensy/core/usb_mem.h
@@ -0,0 +1,55 @@
+/* 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.
+ */
+
+#ifndef _usb_mem_h_
+#define _usb_mem_h_
+
+#include <stdint.h>
+
+typedef struct usb_packet_struct {
+ uint16_t len;
+ uint16_t index;
+ struct usb_packet_struct *next;
+ uint8_t buf[64];
+} usb_packet_t;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+usb_packet_t * usb_malloc(void);
+void usb_free(usb_packet_t *p);
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif
diff --git a/ports/teensy/core/usb_names.h b/ports/teensy/core/usb_names.h
new file mode 100644
index 000000000..067cb95e9
--- /dev/null
+++ b/ports/teensy/core/usb_names.h
@@ -0,0 +1,57 @@
+/* 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.
+ */
+
+#ifndef _usb_names_h_
+#define _usb_names_h_
+
+// These definitions are intended to allow users to override the default
+// USB manufacturer, product and serial number strings.
+
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct usb_string_descriptor_struct {
+ uint8_t bLength;
+ uint8_t bDescriptorType;
+ uint16_t wString[];
+};
+
+extern struct usb_string_descriptor_struct usb_string_manufacturer_name;
+extern struct usb_string_descriptor_struct usb_string_product_name;
+extern struct usb_string_descriptor_struct usb_string_serial_number;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/ports/teensy/core/usb_serial.c b/ports/teensy/core/usb_serial.c
new file mode 100644
index 000000000..3b38ec8b6
--- /dev/null
+++ b/ports/teensy/core/usb_serial.c
@@ -0,0 +1,273 @@
+/* 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.
+ */
+
+#include "usb_dev.h"
+#include "usb_serial.h"
+#include "core_pins.h" // for yield()
+//#include "HardwareSerial.h"
+#include <string.h> // for memcpy()
+
+// defined by usb_dev.h -> usb_desc.h
+#if defined(CDC_STATUS_INTERFACE) && defined(CDC_DATA_INTERFACE)
+
+uint32_t usb_cdc_line_coding[2];
+volatile uint8_t usb_cdc_line_rtsdtr=0;
+volatile uint8_t usb_cdc_transmit_flush_timer=0;
+
+static usb_packet_t *rx_packet=NULL;
+static usb_packet_t *tx_packet=NULL;
+static volatile uint8_t tx_noautoflush=0;
+
+#define TRANSMIT_FLUSH_TIMEOUT 5 /* in milliseconds */
+
+// get the next character, or -1 if nothing received
+int usb_serial_getchar(void)
+{
+ unsigned int i;
+ int c;
+
+ if (!rx_packet) {
+ if (!usb_configuration) return -1;
+ rx_packet = usb_rx(CDC_RX_ENDPOINT);
+ if (!rx_packet) return -1;
+ }
+ i = rx_packet->index;
+ c = rx_packet->buf[i++];
+ if (i >= rx_packet->len) {
+ usb_free(rx_packet);
+ rx_packet = NULL;
+ } else {
+ rx_packet->index = i;
+ }
+ return c;
+}
+
+// peek at the next character, or -1 if nothing received
+int usb_serial_peekchar(void)
+{
+ if (!rx_packet) {
+ if (!usb_configuration) return -1;
+ rx_packet = usb_rx(CDC_RX_ENDPOINT);
+ if (!rx_packet) return -1;
+ }
+ if (!rx_packet) return -1;
+ return rx_packet->buf[rx_packet->index];
+}
+
+// number of bytes available in the receive buffer
+int usb_serial_available(void)
+{
+ int count;
+ count = usb_rx_byte_count(CDC_RX_ENDPOINT);
+ if (rx_packet) count += rx_packet->len - rx_packet->index;
+ return count;
+}
+
+// read a block of bytes to a buffer
+int usb_serial_read(void *buffer, uint32_t size)
+{
+ uint8_t *p = (uint8_t *)buffer;
+ uint32_t qty, count=0;
+
+ while (size) {
+ if (!usb_configuration) break;
+ if (!rx_packet) {
+ rx:
+ rx_packet = usb_rx(CDC_RX_ENDPOINT);
+ if (!rx_packet) break;
+ if (rx_packet->len == 0) {
+ usb_free(rx_packet);
+ goto rx;
+ }
+ }
+ qty = rx_packet->len - rx_packet->index;
+ if (qty > size) qty = size;
+ memcpy(p, rx_packet->buf + rx_packet->index, qty);
+ p += qty;
+ count += qty;
+ size -= qty;
+ rx_packet->index += qty;
+ if (rx_packet->index >= rx_packet->len) {
+ usb_free(rx_packet);
+ rx_packet = NULL;
+ }
+ }
+ return count;
+}
+
+// discard any buffered input
+void usb_serial_flush_input(void)
+{
+ usb_packet_t *rx;
+
+ if (!usb_configuration) return;
+ if (rx_packet) {
+ usb_free(rx_packet);
+ rx_packet = NULL;
+ }
+ while (1) {
+ rx = usb_rx(CDC_RX_ENDPOINT);
+ if (!rx) break;
+ usb_free(rx);
+ }
+}
+
+// Maximum number of transmit packets to queue so we don't starve other endpoints for memory
+#define TX_PACKET_LIMIT 8
+
+// When the PC isn't listening, how long do we wait before discarding data? If this is
+// too short, we risk losing data during the stalls that are common with ordinary desktop
+// software. If it's too long, we stall the user's program when no software is running.
+#define TX_TIMEOUT_MSEC 70
+
+#if F_CPU == 168000000
+ #define TX_TIMEOUT (TX_TIMEOUT_MSEC * 1100)
+#elif F_CPU == 144000000
+ #define TX_TIMEOUT (TX_TIMEOUT_MSEC * 932)
+#elif F_CPU == 120000000
+ #define TX_TIMEOUT (TX_TIMEOUT_MSEC * 764)
+#elif F_CPU == 96000000
+ #define TX_TIMEOUT (TX_TIMEOUT_MSEC * 596)
+#elif F_CPU == 72000000
+ #define TX_TIMEOUT (TX_TIMEOUT_MSEC * 512)
+#elif F_CPU == 48000000
+ #define TX_TIMEOUT (TX_TIMEOUT_MSEC * 428)
+#elif F_CPU == 24000000
+ #define TX_TIMEOUT (TX_TIMEOUT_MSEC * 262)
+#endif
+
+// When we've suffered the transmit timeout, don't wait again until the computer
+// begins accepting data. If no software is running to receive, we'll just discard
+// data as rapidly as Serial.print() can generate it, until there's something to
+// actually receive it.
+static uint8_t transmit_previous_timeout=0;
+
+
+// transmit a character. 0 returned on success, -1 on error
+int usb_serial_putchar(uint8_t c)
+{
+ return usb_serial_write(&c, 1);
+}
+
+
+int usb_serial_write(const void *buffer, uint32_t size)
+{
+ uint32_t len;
+ uint32_t wait_count;
+ const uint8_t *src = (const uint8_t *)buffer;
+ uint8_t *dest;
+
+ tx_noautoflush = 1;
+ while (size > 0) {
+ if (!tx_packet) {
+ wait_count = 0;
+ while (1) {
+ if (!usb_configuration) {
+ tx_noautoflush = 0;
+ return -1;
+ }
+ if (usb_tx_packet_count(CDC_TX_ENDPOINT) < TX_PACKET_LIMIT) {
+ tx_noautoflush = 1;
+ tx_packet = usb_malloc();
+ if (tx_packet) break;
+ tx_noautoflush = 0;
+ }
+ if (++wait_count > TX_TIMEOUT || transmit_previous_timeout) {
+ transmit_previous_timeout = 1;
+ return -1;
+ }
+ yield();
+ }
+ }
+ transmit_previous_timeout = 0;
+ len = CDC_TX_SIZE - tx_packet->index;
+ if (len > size) len = size;
+ dest = tx_packet->buf + tx_packet->index;
+ tx_packet->index += len;
+ size -= len;
+ while (len-- > 0) *dest++ = *src++;
+ if (tx_packet->index >= CDC_TX_SIZE) {
+ tx_packet->len = CDC_TX_SIZE;
+ usb_tx(CDC_TX_ENDPOINT, tx_packet);
+ tx_packet = NULL;
+ }
+ usb_cdc_transmit_flush_timer = TRANSMIT_FLUSH_TIMEOUT;
+ }
+ tx_noautoflush = 0;
+ return 0;
+}
+
+void usb_serial_flush_output(void)
+{
+ if (!usb_configuration) return;
+ tx_noautoflush = 1;
+ if (tx_packet) {
+ usb_cdc_transmit_flush_timer = 0;
+ tx_packet->len = tx_packet->index;
+ usb_tx(CDC_TX_ENDPOINT, tx_packet);
+ tx_packet = NULL;
+ } else {
+ usb_packet_t *tx = usb_malloc();
+ if (tx) {
+ usb_cdc_transmit_flush_timer = 0;
+ usb_tx(CDC_TX_ENDPOINT, tx);
+ } else {
+ usb_cdc_transmit_flush_timer = 1;
+ }
+ }
+ tx_noautoflush = 0;
+}
+
+void usb_serial_flush_callback(void)
+{
+ if (tx_noautoflush) return;
+ if (tx_packet) {
+ tx_packet->len = tx_packet->index;
+ usb_tx(CDC_TX_ENDPOINT, tx_packet);
+ tx_packet = NULL;
+ } else {
+ usb_packet_t *tx = usb_malloc();
+ if (tx) {
+ usb_tx(CDC_TX_ENDPOINT, tx);
+ } else {
+ usb_cdc_transmit_flush_timer = 1;
+ }
+ }
+}
+
+
+
+
+
+
+
+
+
+#endif // CDC_STATUS_INTERFACE && CDC_DATA_INTERFACE
diff --git a/ports/teensy/core/usb_serial.h b/ports/teensy/core/usb_serial.h
new file mode 100644
index 000000000..9c0429d19
--- /dev/null
+++ b/ports/teensy/core/usb_serial.h
@@ -0,0 +1,144 @@
+/* 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.
+ */
+
+#ifndef USBserial_h_
+#define USBserial_h_
+
+#if defined(USB_SERIAL) || defined(USB_SERIAL_HID)
+
+#include <inttypes.h>
+
+#if F_CPU >= 20000000
+
+// C language implementation
+#ifdef __cplusplus
+extern "C" {
+#endif
+int usb_serial_getchar(void);
+int usb_serial_peekchar(void);
+int usb_serial_available(void);
+int usb_serial_read(void *buffer, uint32_t size);
+void usb_serial_flush_input(void);
+int usb_serial_putchar(uint8_t c);
+int usb_serial_write(const void *buffer, uint32_t size);
+void usb_serial_flush_output(void);
+extern uint32_t usb_cdc_line_coding[2];
+extern volatile uint8_t usb_cdc_line_rtsdtr;
+extern volatile uint8_t usb_cdc_transmit_flush_timer;
+extern volatile uint8_t usb_configuration;
+#ifdef __cplusplus
+}
+#endif
+
+#define USB_SERIAL_DTR 0x01
+#define USB_SERIAL_RTS 0x02
+
+// C++ interface
+#ifdef __cplusplus
+#include "Stream.h"
+class usb_serial_class : public Stream
+{
+public:
+ void begin(long) { /* TODO: call a function that tries to wait for enumeration */ };
+ void end() { /* TODO: flush output and shut down USB port */ };
+ virtual int available() { return usb_serial_available(); }
+ virtual int read() { return usb_serial_getchar(); }
+ virtual int peek() { return usb_serial_peekchar(); }
+ virtual void flush() { usb_serial_flush_output(); } // TODO: actually wait for data to leave USB...
+ virtual size_t write(uint8_t c) { return usb_serial_putchar(c); }
+ virtual size_t write(const uint8_t *buffer, size_t size) { return usb_serial_write(buffer, size); }
+ size_t write(unsigned long n) { return write((uint8_t)n); }
+ size_t write(long n) { return write((uint8_t)n); }
+ size_t write(unsigned int n) { return write((uint8_t)n); }
+ size_t write(int n) { return write((uint8_t)n); }
+ using Print::write;
+ void send_now(void) { usb_serial_flush_output(); }
+ uint32_t baud(void) { return usb_cdc_line_coding[0]; }
+ uint8_t stopbits(void) { uint8_t b = usb_cdc_line_coding[1]; if (!b) b = 1; return b; }
+ uint8_t paritytype(void) { return usb_cdc_line_coding[1] >> 8; } // 0=none, 1=odd, 2=even
+ uint8_t numbits(void) { return usb_cdc_line_coding[1] >> 16; }
+ uint8_t dtr(void) { return (usb_cdc_line_rtsdtr & USB_SERIAL_DTR) ? 1 : 0; }
+ uint8_t rts(void) { return (usb_cdc_line_rtsdtr & USB_SERIAL_RTS) ? 1 : 0; }
+ operator bool() { return usb_configuration && (usb_cdc_line_rtsdtr & (USB_SERIAL_DTR | USB_SERIAL_RTS)); }
+ size_t readBytes(char *buffer, size_t length) {
+ size_t count=0;
+ unsigned long startMillis = millis();
+ do {
+ count += usb_serial_read(buffer + count, length - count);
+ if (count >= length) return count;
+ } while(millis() - startMillis < _timeout);
+ setReadError();
+ return count;
+ }
+
+};
+extern usb_serial_class Serial;
+#endif // __cplusplus
+
+
+#else // F_CPU < 20 MHz
+
+// Allow Arduino programs using Serial to compile, but Serial will do nothing.
+#ifdef __cplusplus
+#include "Stream.h"
+class usb_serial_class : public Stream
+{
+public:
+ void begin(long) { };
+ void end() { };
+ virtual int available() { return 0; }
+ virtual int read() { return -1; }
+ virtual int peek() { return -1; }
+ virtual void flush() { }
+ virtual size_t write(uint8_t c) { return 1; }
+ virtual size_t write(const uint8_t *buffer, size_t size) { return size; }
+ size_t write(unsigned long n) { return 1; }
+ size_t write(long n) { return 1; }
+ size_t write(unsigned int n) { return 1; }
+ size_t write(int n) { return 1; }
+ using Print::write;
+ void send_now(void) { }
+ uint32_t baud(void) { return 0; }
+ uint8_t stopbits(void) { return 1; }
+ uint8_t paritytype(void) { return 0; }
+ uint8_t numbits(void) { return 8; }
+ uint8_t dtr(void) { return 1; }
+ uint8_t rts(void) { return 1; }
+ operator bool() { return true; }
+};
+
+extern usb_serial_class Serial;
+#endif // __cplusplus
+
+#endif // F_CPU
+
+#endif // USB_SERIAL || USB_SERIAL_HID
+
+#endif // USBserial_h_
diff --git a/ports/teensy/core/yield.c b/ports/teensy/core/yield.c
new file mode 100644
index 000000000..06c741a67
--- /dev/null
+++ b/ports/teensy/core/yield.c
@@ -0,0 +1,32 @@
+/* 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.
+ */
+
+void yield(void) __attribute__ ((weak));
+void yield(void) {};
diff --git a/ports/teensy/hal_ftm.c b/ports/teensy/hal_ftm.c
new file mode 100644
index 000000000..3c031bf6d
--- /dev/null
+++ b/ports/teensy/hal_ftm.c
@@ -0,0 +1,201 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2013, 2014 Damien P. George
+ *
+ * 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 <stdint.h>
+#include <mk20dx128.h>
+#include "teensy_hal.h"
+
+void HAL_FTM_Base_Init(FTM_HandleTypeDef *hftm) {
+ /* Check the parameters */
+ FTM_TypeDef *FTMx = hftm->Instance;
+ assert_param(IS_FTM_INSTANCE(FTMx));
+ assert_param(IS_FTM_PRESCALERSHIFT(hftm->Init.PrescalerShift));
+ assert_param(IS_FTM_COUNTERMODE(hftm->Init.CounterMode));
+ assert_param(IS_FTM_PERIOD(hftm->Init.Period));
+
+ hftm->State = HAL_FTM_STATE_BUSY;
+
+ FTMx->MODE = FTM_MODE_WPDIS;
+ FTMx->SC = 0;
+ FTMx->MOD = hftm->Init.Period;
+ uint32_t sc = FTM_SC_PS(hftm->Init.PrescalerShift);
+ if (hftm->Init.CounterMode == FTM_COUNTERMODE_CENTER) {
+ sc |= FTM_SC_CPWMS;
+ }
+ FTMx->SC = sc;
+
+ hftm->State = HAL_FTM_STATE_READY;
+}
+
+void HAL_FTM_Base_Start(FTM_HandleTypeDef *hftm) {
+ FTM_TypeDef *FTMx = hftm->Instance;
+ assert_param(IS_FTM_INSTANCE(FTMx));
+
+ hftm->State = HAL_FTM_STATE_BUSY;
+
+ FTMx->CNT = 0;
+ FTMx->SC &= ~FTM_SC_CLKS(3);
+ FTMx->SC |= FTM_SC_CLKS(1);
+
+ hftm->State = HAL_FTM_STATE_READY;
+}
+
+void HAL_FTM_Base_Start_IT(FTM_HandleTypeDef *hftm) {
+ FTM_TypeDef *FTMx = hftm->Instance;
+ assert_param(IS_FTM_INSTANCE(FTMx));
+
+ hftm->State = HAL_FTM_STATE_BUSY;
+
+ FTMx->CNT = 0;
+ FTMx->SC |= FTM_SC_CLKS(1) | FTM_SC_TOIE;
+
+ hftm->State = HAL_FTM_STATE_READY;
+}
+
+void HAL_FTM_Base_DeInit(FTM_HandleTypeDef *hftm) {
+ assert_param(IS_FTM_INSTANCE(hftm->Instance));
+
+ hftm->State = HAL_FTM_STATE_BUSY;
+
+ __HAL_FTM_DISABLE_TOF_IT(hftm);
+
+ hftm->State = HAL_FTM_STATE_RESET;
+}
+
+void HAL_FTM_OC_Init(FTM_HandleTypeDef *hftm) {
+ HAL_FTM_Base_Init(hftm);
+}
+
+void HAL_FTM_OC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef* sConfig, uint32_t channel) {
+ FTM_TypeDef *FTMx = hftm->Instance;
+ assert_param(IS_FTM_INSTANCE(FTMx));
+ assert_param(IS_FTM_CHANNEL(channel));
+ assert_param(IS_FTM_OC_MODE(sConfig->OCMode));
+ assert_param(IS_FTM_OC_PULSE(sConfig->Pulse));
+ assert_param(IS_FTM_OC_POLARITY(sConfig->OCPolarity));
+
+ hftm->State = HAL_FTM_STATE_BUSY;
+
+ FTMx->channel[channel].CSC = sConfig->OCMode;
+ FTMx->channel[channel].CV = sConfig->Pulse;
+ if (sConfig->OCPolarity & 1) {
+ FTMx->POL |= (1 << channel);
+ } else {
+ FTMx->POL &= ~(1 << channel);
+ }
+
+ hftm->State = HAL_FTM_STATE_READY;
+}
+
+void HAL_FTM_OC_Start(FTM_HandleTypeDef *hftm, uint32_t channel) {
+ // Nothing else to do
+}
+
+void HAL_FTM_OC_Start_IT(FTM_HandleTypeDef *hftm, uint32_t channel) {
+ FTM_TypeDef *FTMx = hftm->Instance;
+ assert_param(IS_FTM_INSTANCE(FTMx));
+
+ FTMx->channel[channel].CSC |= FTM_CSC_CHIE;
+}
+
+void HAL_FTM_OC_DeInit(FTM_HandleTypeDef *hftm) {
+ HAL_FTM_Base_DeInit(hftm);
+}
+
+void HAL_FTM_PWM_Init(FTM_HandleTypeDef *hftm) {
+ HAL_FTM_Base_Init(hftm);
+}
+
+void HAL_FTM_PWM_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef* sConfig, uint32_t channel) {
+ FTM_TypeDef *FTMx = hftm->Instance;
+ assert_param(IS_FTM_INSTANCE(FTMx));
+ assert_param(IS_FTM_CHANNEL(channel));
+ assert_param(IS_FTM_PWM_MODE(sConfig->OCMode));
+ assert_param(IS_FTM_OC_PULSE(sConfig->Pulse));
+ assert_param(IS_FTM_OC_POLARITY(sConfig->OCPolarity));
+
+ hftm->State = HAL_FTM_STATE_BUSY;
+
+ FTMx->channel[channel].CSC = sConfig->OCMode;
+ FTMx->channel[channel].CV = sConfig->Pulse;
+ if (sConfig->OCPolarity & 1) {
+ FTMx->POL |= (1 << channel);
+ } else {
+ FTMx->POL &= ~(1 << channel);
+ }
+
+ hftm->State = HAL_FTM_STATE_READY;
+}
+
+void HAL_FTM_PWM_Start(FTM_HandleTypeDef *hftm, uint32_t channel) {
+ // Nothing else to do
+}
+
+void HAL_FTM_PWM_Start_IT(FTM_HandleTypeDef *hftm, uint32_t channel) {
+ FTM_TypeDef *FTMx = hftm->Instance;
+ assert_param(IS_FTM_INSTANCE(FTMx));
+
+ FTMx->channel[channel].CSC |= FTM_CSC_CHIE;
+}
+
+void HAL_FTM_PWM_DeInit(FTM_HandleTypeDef *hftm) {
+ HAL_FTM_Base_DeInit(hftm);
+}
+
+void HAL_FTM_IC_Init(FTM_HandleTypeDef *hftm) {
+ HAL_FTM_Base_Init(hftm);
+}
+
+void HAL_FTM_IC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_IC_InitTypeDef* sConfig, uint32_t channel) {
+ FTM_TypeDef *FTMx = hftm->Instance;
+ assert_param(IS_FTM_INSTANCE(FTMx));
+ assert_param(IS_FTM_CHANNEL(channel));
+ assert_param(IS_FTM_IC_POLARITY(sConfig->ICPolarity));
+
+ hftm->State = HAL_FTM_STATE_BUSY;
+
+ FTMx->channel[channel].CSC = sConfig->ICPolarity;
+
+ hftm->State = HAL_FTM_STATE_READY;
+}
+
+void HAL_FTM_IC_Start(FTM_HandleTypeDef *hftm, uint32_t channel) {
+ //FTM_TypeDef *FTMx = hftm->Instance;
+ //assert_param(IS_FTM_INSTANCE(FTMx));
+
+ // Nothing else to do
+}
+
+void HAL_FTM_IC_Start_IT(FTM_HandleTypeDef *hftm, uint32_t channel) {
+ FTM_TypeDef *FTMx = hftm->Instance;
+ assert_param(IS_FTM_INSTANCE(FTMx));
+
+ FTMx->channel[channel].CSC |= FTM_CSC_CHIE;
+}
+
+void HAL_FTM_IC_DeInit(FTM_HandleTypeDef *hftm) {
+ HAL_FTM_Base_DeInit(hftm);
+}
diff --git a/ports/teensy/hal_ftm.h b/ports/teensy/hal_ftm.h
new file mode 100644
index 000000000..84fae8312
--- /dev/null
+++ b/ports/teensy/hal_ftm.h
@@ -0,0 +1,186 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2013, 2014 Damien P. George
+ *
+ * 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 MICROPY_INCLUDED_TEENSY_HAL_FTM_H
+#define MICROPY_INCLUDED_TEENSY_HAL_FTM_H
+
+#define FTM0 ((FTM_TypeDef *)&FTM0_SC)
+#define FTM1 ((FTM_TypeDef *)&FTM1_SC)
+#define FTM2 ((FTM_TypeDef *)&FTM2_SC)
+
+typedef struct {
+ volatile uint32_t CSC; // Channel x Status And Control
+ volatile uint32_t CV; // Channel x Value
+} FTM_ChannelTypeDef;
+
+typedef struct {
+ volatile uint32_t SC; // Status And Control
+ volatile uint32_t CNT; // Counter
+ volatile uint32_t MOD; // Modulo
+ FTM_ChannelTypeDef channel[8];
+ volatile uint32_t CNTIN; // Counter Initial Value
+ volatile uint32_t STATUS; // Capture And Compare Status
+ volatile uint32_t MODE; // Features Mode Selection
+ volatile uint32_t SYNC; // Synchronization
+ volatile uint32_t OUTINIT; // Initial State For Channels Output
+ volatile uint32_t OUTMASK; // Output Mask
+ volatile uint32_t COMBINE; // Function For Linked Channels
+ volatile uint32_t DEADTIME; // Deadtime Insertion Control
+ volatile uint32_t EXTTRIG; // FTM External Trigger
+ volatile uint32_t POL; // Channels Polarity
+ volatile uint32_t FMS; // Fault Mode Status
+ volatile uint32_t FILTER; // Input Capture Filter Control
+ volatile uint32_t FLTCTRL; // Fault Control
+ volatile uint32_t QDCTRL; // Quadrature Decoder Control And Status
+ volatile uint32_t CONF; // Configuration
+ volatile uint32_t FLTPOL; // FTM Fault Input Polarity
+ volatile uint32_t SYNCONF; // Synchronization Configuration
+ volatile uint32_t INVCTRL; // FTM Inverting Control
+ volatile uint32_t SWOCTRL; // FTM Software Output Control
+ volatile uint32_t PWMLOAD; // FTM PWM Load
+} FTM_TypeDef;
+
+typedef struct {
+ uint32_t PrescalerShift; // Sets the prescaler to 1 << PrescalerShift
+ uint32_t CounterMode; // One of FTM_COUNTERMODE_xxx
+ uint32_t Period; // Specifies the Period for determining timer overflow
+} FTM_Base_InitTypeDef;
+
+typedef struct {
+ uint32_t OCMode; // One of FTM_OCMODE_xxx
+ uint32_t Pulse; // Specifies initial pulse width (0-0xffff)
+ uint32_t OCPolarity; // One of FTM_OCPOLRITY_xxx
+} FTM_OC_InitTypeDef;
+
+typedef struct {
+ uint32_t ICPolarity; // Specifies Rising/Falling/Both
+} FTM_IC_InitTypeDef;
+
+#define IS_FTM_INSTANCE(INSTANCE) (((INSTANCE) == FTM0) || \
+ ((INSTANCE) == FTM1) || \
+ ((INSTANCE) == FTM2))
+
+#define IS_FTM_PRESCALERSHIFT(PRESCALERSHIFT) (((PRESCALERSHIFT) & ~7) == 0)
+
+#define FTM_COUNTERMODE_UP (0)
+#define FTM_COUNTERMODE_CENTER (FTM_SC_CPWMS)
+
+#define IS_FTM_COUNTERMODE(MODE) (((MODE) == FTM_COUNTERMODE_UP) ||\
+ ((MODE) == FTM_COUNTERMODE_CENTER))
+
+#define IS_FTM_PERIOD(PERIOD) (((PERIOD) & 0xFFFF0000) == 0)
+
+#define FTM_CSC_CHF 0x80
+#define FTM_CSC_CHIE 0x40
+#define FTM_CSC_MSB 0x20
+#define FTM_CSC_MSA 0x10
+#define FTM_CSC_ELSB 0x08
+#define FTM_CSC_ELSA 0x04
+#define FTM_CSC_DMA 0x01
+
+#define FTM_OCMODE_TIMING (0)
+#define FTM_OCMODE_ACTIVE (FTM_CSC_MSA | FTM_CSC_ELSB | FTM_CSC_ELSA)
+#define FTM_OCMODE_INACTIVE (FTM_CSC_MSA | FTM_CSC_ELSB)
+#define FTM_OCMODE_TOGGLE (FTM_CSC_MSA | FTM_CSC_ELSA)
+#define FTM_OCMODE_PWM1 (FTM_CSC_MSB | FTM_CSC_ELSB)
+#define FTM_OCMODE_PWM2 (FTM_CSC_MSB | FTM_CSC_ELSA)
+
+#define IS_FTM_OC_MODE(mode) ((mode) == FTM_OCMODE_TIMING || \
+ (mode) == FTM_OCMODE_ACTIVE || \
+ (mode) == FTM_OCMODE_INACTIVE || \
+ (mode) == FTM_OCMODE_TOGGLE )
+
+#define IS_FTM_PWM_MODE(mode) ((mode) == FTM_OCMODE_PWM1 || \
+ (mode) == FTM_OCMODE_PWM2)
+
+#define IS_FTM_CHANNEL(channel) (((channel) & ~7) == 0)
+
+#define IS_FTM_PULSE(pulse) (((pulse) & ~0xffff) == 0)
+
+#define FTM_OCPOLARITY_HIGH (0)
+#define FTM_OCPOLARITY_LOW (1)
+
+#define IS_FTM_OC_POLARITY(polarity) ((polarity) == FTM_OCPOLARITY_HIGH || \
+ (polarity) == FTM_OCPOLARITY_LOW)
+
+#define FTM_ICPOLARITY_RISING (FTM_CSC_ELSA)
+#define FTM_ICPOLARITY_FALLING (FTM_CSC_ELSB)
+#define FTM_ICPOLARITY_BOTH (FTM_CSC_ELSA | FTM_CSC_ELSB)
+
+#define IS_FTM_IC_POLARITY(polarity) ((polarity) == FTM_ICPOLARITY_RISING || \
+ (polarity) == FTM_ICPOLARITY_FALLING || \
+ (polarity) == FTM_ICPOLARITY_BOTH)
+
+typedef enum {
+ HAL_FTM_STATE_RESET = 0x00,
+ HAL_FTM_STATE_READY = 0x01,
+ HAL_FTM_STATE_BUSY = 0x02,
+} HAL_FTM_State;
+
+typedef struct {
+ FTM_TypeDef *Instance;
+ FTM_Base_InitTypeDef Init;
+ HAL_FTM_State State;
+
+} FTM_HandleTypeDef;
+
+#define __HAL_FTM_GET_TOF_FLAG(HANDLE) (((HANDLE)->Instance->SC & FTM_SC_TOF) != 0)
+#define __HAL_FTM_CLEAR_TOF_FLAG(HANDLE) ((HANDLE)->Instance->SC &= ~FTM_SC_TOF)
+
+#define __HAL_FTM_GET_TOF_IT(HANDLE) (((HANDLE)->Instance->SC & FTM_SC_TOIE) != 0)
+#define __HAL_FTM_ENABLE_TOF_IT(HANDLE) ((HANDLE)->Instance->SC |= FTM_SC_TOIE)
+#define __HAL_FTM_DISABLE_TOF_IT(HANDLE) ((HANDLE)->Instance->SC &= ~FTM_SC_TOIE)
+
+#define __HAL_FTM_GET_CH_FLAG(HANDLE, CH) (((HANDLE)->Instance->channel[CH].CSC & FTM_CSC_CHF) != 0)
+#define __HAL_FTM_CLEAR_CH_FLAG(HANDLE, CH) ((HANDLE)->Instance->channel[CH].CSC &= ~FTM_CSC_CHF)
+
+#define __HAL_FTM_GET_CH_IT(HANDLE, CH) (((HANDLE)->Instance->channel[CH].CSC & FTM_CSC_CHIE) != 0)
+#define __HAL_FTM_ENABLE_CH_IT(HANDLE, CH) ((HANDLE)->Instance->channel[CH].CSC |= FTM_CSC_CHIE)
+#define __HAL_FTM_DISABLE_CH_IT(HANDLE, CH) ((HANDLE)->Instance->channel[CH].CSC &= ~FTM_CSC_CHIE)
+
+void HAL_FTM_Base_Init(FTM_HandleTypeDef *hftm);
+void HAL_FTM_Base_Start(FTM_HandleTypeDef *hftm);
+void HAL_FTM_Base_Start_IT(FTM_HandleTypeDef *hftm);
+void HAL_FTM_Base_DeInit(FTM_HandleTypeDef *hftm);
+
+void HAL_FTM_OC_Init(FTM_HandleTypeDef *hftm);
+void HAL_FTM_OC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef* sConfig, uint32_t channel);
+void HAL_FTM_OC_Start(FTM_HandleTypeDef *hftm, uint32_t channel);
+void HAL_FTM_OC_Start_IT(FTM_HandleTypeDef *hftm, uint32_t channel);
+void HAL_FTM_OC_DeInit(FTM_HandleTypeDef *hftm);
+
+void HAL_FTM_PWM_Init(FTM_HandleTypeDef *hftm);
+void HAL_FTM_PWM_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef* sConfig, uint32_t channel);
+void HAL_FTM_PWM_Start(FTM_HandleTypeDef *hftm, uint32_t channel);
+void HAL_FTM_PWM_Start_IT(FTM_HandleTypeDef *hftm, uint32_t channel);
+void HAL_FTM_PWM_DeInit(FTM_HandleTypeDef *hftm);
+
+void HAL_FTM_IC_Init(FTM_HandleTypeDef *hftm);
+void HAL_FTM_IC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_IC_InitTypeDef* sConfig, uint32_t channel);
+void HAL_FTM_IC_Start(FTM_HandleTypeDef *hftm, uint32_t channel);
+void HAL_FTM_IC_Start_IT(FTM_HandleTypeDef *hftm, uint32_t channel);
+void HAL_FTM_IC_DeInit(FTM_HandleTypeDef *hftm);
+
+#endif // MICROPY_INCLUDED_TEENSY_HAL_FTM_H
diff --git a/ports/teensy/hal_gpio.c b/ports/teensy/hal_gpio.c
new file mode 100644
index 000000000..e65d03410
--- /dev/null
+++ b/ports/teensy/hal_gpio.c
@@ -0,0 +1,123 @@
+#include <stdint.h>
+#include <mk20dx128.h>
+#include "teensy_hal.h"
+
+#define GPIO_NUMBER 32
+
+void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init)
+{
+ /* Check the parameters */
+ assert_param(IS_GPIO_PIN(GPIO_Init->Pin));
+ assert_param(IS_GPIO_MODE(GPIO_Init->Mode));
+ assert_param(IS_GPIO_PULL(GPIO_Init->Pull));
+
+ /* Configure the port pins */
+ for (uint32_t position = 0; position < GPIO_NUMBER; position++) {
+ uint32_t bitmask = 1 << position;
+ if ((GPIO_Init->Pin & bitmask) == 0) {
+ continue;
+ }
+ volatile uint32_t *port_pcr = GPIO_PIN_TO_PORT_PCR(GPIOx, position);
+
+ /*--------------------- GPIO Mode Configuration ------------------------*/
+ /* In case of Alternate function mode selection */
+ if ((GPIO_Init->Mode == GPIO_MODE_AF_PP) || (GPIO_Init->Mode == GPIO_MODE_AF_OD)) {
+ /* Check the Alternate function parameter */
+ assert_param(IS_GPIO_AF(GPIO_Init->Alternate));
+ }
+ else if (GPIO_Init->Mode == GPIO_MODE_ANALOG) {
+ GPIO_Init->Alternate = 0;
+ }
+ else {
+ GPIO_Init->Alternate = 1;
+ }
+
+ /* Configure Alternate function mapped with the current IO */
+ *port_pcr &= ~PORT_PCR_MUX_MASK;
+ *port_pcr |= PORT_PCR_MUX(GPIO_Init->Alternate);
+
+ /* Configure IO Direction mode (Input, Output, Alternate or Analog) */
+ if (GPIO_Init->Mode == GPIO_MODE_INPUT || GPIO_Init->Mode == GPIO_MODE_ANALOG) {
+ GPIOx->PDDR &= ~bitmask;
+ } else {
+ GPIOx->PDDR |= bitmask;
+ }
+
+ /* In case of Output or Alternate function mode selection */
+ if ((GPIO_Init->Mode == GPIO_MODE_OUTPUT_PP) || (GPIO_Init->Mode == GPIO_MODE_AF_PP) ||
+ (GPIO_Init->Mode == GPIO_MODE_OUTPUT_OD) || (GPIO_Init->Mode == GPIO_MODE_AF_OD)) {
+ /* Check the Speed parameter */
+ assert_param(IS_GPIO_SPEED(GPIO_Init->Speed));
+
+ *port_pcr |= PORT_PCR_DSE;
+
+ /* Configure the IO Speed */
+ if (GPIO_Init->Speed > GPIO_SPEED_MEDIUM) {
+ *port_pcr &= ~PORT_PCR_SRE;
+ } else {
+ *port_pcr |= PORT_PCR_SRE;
+ }
+
+ /* Configure the IO Output Type */
+ if (GPIO_Init->Mode & GPIO_OUTPUT_TYPE) {
+ *port_pcr |= PORT_PCR_ODE; // OD
+ } else {
+ *port_pcr &= ~PORT_PCR_ODE; // PP
+ }
+ } else {
+ *port_pcr &= ~PORT_PCR_DSE;
+ }
+
+ /* Activate the Pull-up or Pull down resistor for the current IO */
+ if (GPIO_Init->Pull == GPIO_NOPULL) {
+ *port_pcr &= ~PORT_PCR_PE;
+ } else {
+ *port_pcr |= PORT_PCR_PE;
+ if (GPIO_Init->Pull == GPIO_PULLDOWN) {
+ *port_pcr &= ~PORT_PCR_PS;
+ } else {
+ *port_pcr |= PORT_PCR_PS;
+ }
+ }
+
+#if 0
+ /*--------------------- EXTI Mode Configuration ------------------------*/
+ /* Configure the External Interrupt or event for the current IO */
+ if((GPIO_Init->Mode & EXTI_MODE) == EXTI_MODE)
+ {
+ /* Enable SYSCFG Clock */
+ __SYSCFG_CLK_ENABLE();
+
+ temp = ((uint32_t)0x0F) << (4 * (position & 0x03));
+ SYSCFG->EXTICR[position >> 2] &= ~temp;
+ SYSCFG->EXTICR[position >> 2] |= ((uint32_t)(__HAL_GET_GPIO_SOURCE(GPIOx)) << (4 * (position & 0x03)));
+
+ /* Clear EXTI line configuration */
+ EXTI->IMR &= ~((uint32_t)iocurrent);
+ EXTI->EMR &= ~((uint32_t)iocurrent);
+
+ if((GPIO_Init->Mode & GPIO_MODE_IT) == GPIO_MODE_IT)
+ {
+ EXTI->IMR |= iocurrent;
+ }
+ if((GPIO_Init->Mode & GPIO_MODE_EVT) == GPIO_MODE_EVT)
+ {
+ EXTI->EMR |= iocurrent;
+ }
+
+ /* Clear Rising Falling edge configuration */
+ EXTI->RTSR &= ~((uint32_t)iocurrent);
+ EXTI->FTSR &= ~((uint32_t)iocurrent);
+
+ if((GPIO_Init->Mode & RISING_EDGE) == RISING_EDGE)
+ {
+ EXTI->RTSR |= iocurrent;
+ }
+ if((GPIO_Init->Mode & FALLING_EDGE) == FALLING_EDGE)
+ {
+ EXTI->FTSR |= iocurrent;
+ }
+ }
+#endif
+ }
+}
diff --git a/ports/teensy/help.c b/ports/teensy/help.c
new file mode 100644
index 000000000..ebe4bed6b
--- /dev/null
+++ b/ports/teensy/help.c
@@ -0,0 +1,69 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2013, 2014 Damien P. George
+ *
+ * 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 "py/builtin.h"
+
+const char *teensy_help_text =
+"Welcome to MicroPython!\n"
+"\n"
+"For online help please visit http://micropython.org/help/.\n"
+"\n"
+"Quick overview of commands for the board:\n"
+" pyb.info() -- print some general information\n"
+" pyb.gc() -- run the garbage collector\n"
+" pyb.delay(n) -- wait for n milliseconds\n"
+" pyb.Switch() -- create a switch object\n"
+" Switch methods: (), callback(f)\n"
+" pyb.LED(n) -- create an LED object for LED n (n=1,2,3,4)\n"
+" LED methods: on(), off(), toggle(), intensity(<n>)\n"
+" pyb.Pin(pin) -- get a pin, eg pyb.Pin('X1')\n"
+" pyb.Pin(pin, m, [p]) -- get a pin and configure it for IO mode m, pull mode p\n"
+" Pin methods: init(..), value([v]), high(), low()\n"
+" pyb.ExtInt(pin, m, p, callback) -- create an external interrupt object\n"
+" pyb.ADC(pin) -- make an analog object from a pin\n"
+" ADC methods: read(), read_timed(buf, freq)\n"
+" pyb.DAC(port) -- make a DAC object\n"
+" DAC methods: triangle(freq), write(n), write_timed(buf, freq)\n"
+" pyb.RTC() -- make an RTC object; methods: datetime([val])\n"
+" pyb.rng() -- get a 30-bit hardware random number\n"
+" pyb.Servo(n) -- create Servo object for servo n (n=1,2,3,4)\n"
+" Servo methods: calibration(..), angle([x, [t]]), speed([x, [t]])\n"
+" pyb.Accel() -- create an Accelerometer object\n"
+" Accelerometer methods: x(), y(), z(), tilt(), filtered_xyz()\n"
+"\n"
+"Pins are numbered X1-X12, X17-X22, Y1-Y12, or by their MCU name\n"
+"Pin IO modes are: pyb.Pin.IN, pyb.Pin.OUT_PP, pyb.Pin.OUT_OD\n"
+"Pin pull modes are: pyb.Pin.PULL_NONE, pyb.Pin.PULL_UP, pyb.Pin.PULL_DOWN\n"
+"Additional serial bus objects: pyb.I2C(n), pyb.SPI(n), pyb.UART(n)\n"
+"\n"
+"Control commands:\n"
+" CTRL-A -- on a blank line, enter raw REPL mode\n"
+" CTRL-B -- on a blank line, enter normal REPL mode\n"
+" CTRL-C -- interrupt a running program\n"
+" CTRL-D -- on a blank line, do a soft reset of the board\n"
+"\n"
+"For further help on a specific object, type help(obj)\n"
+;
diff --git a/ports/teensy/lcd.c b/ports/teensy/lcd.c
new file mode 100644
index 000000000..e79b7d5ac
--- /dev/null
+++ b/ports/teensy/lcd.c
@@ -0,0 +1,14 @@
+#include "py/obj.h"
+#include "../stmhal/lcd.h"
+
+void lcd_init(void) {
+}
+
+void lcd_print_str(const char *str) {
+ (void)str;
+}
+
+void lcd_print_strn(const char *str, unsigned int len) {
+ (void)str;
+ (void)len;
+}
diff --git a/ports/teensy/led.c b/ports/teensy/led.c
new file mode 100644
index 000000000..9159c75ce
--- /dev/null
+++ b/ports/teensy/led.c
@@ -0,0 +1,144 @@
+#include <stdio.h>
+
+#include "Arduino.h"
+
+#include "py/nlr.h"
+#include "py/runtime.h"
+#include "py/mphal.h"
+#include "led.h"
+#include "pin.h"
+#include "genhdr/pins.h"
+
+typedef struct _pyb_led_obj_t {
+ mp_obj_base_t base;
+ mp_uint_t led_id;
+ const pin_obj_t *led_pin;
+} pyb_led_obj_t;
+
+STATIC const pyb_led_obj_t pyb_led_obj[] = {
+ {{&pyb_led_type}, 1, &MICROPY_HW_LED1},
+#if defined(MICROPY_HW_LED2)
+ {{&pyb_led_type}, 2, &MICROPY_HW_LED2},
+#if defined(MICROPY_HW_LED3)
+ {{&pyb_led_type}, 3, &MICROPY_HW_LED3},
+#if defined(MICROPY_HW_LED4)
+ {{&pyb_led_type}, 4, &MICROPY_HW_LED4},
+#endif
+#endif
+#endif
+};
+#define NUM_LEDS MP_ARRAY_SIZE(pyb_led_obj)
+
+void led_init(void) {
+ /* GPIO structure */
+ GPIO_InitTypeDef GPIO_InitStructure;
+
+ /* Configure I/O speed, mode, output type and pull */
+ GPIO_InitStructure.Speed = GPIO_SPEED_LOW;
+ GPIO_InitStructure.Mode = MICROPY_HW_LED_OTYPE;
+ GPIO_InitStructure.Pull = GPIO_NOPULL;
+
+ /* Turn off LEDs and initialize */
+ for (int led = 0; led < NUM_LEDS; led++) {
+ const pin_obj_t *led_pin = pyb_led_obj[led].led_pin;
+ MICROPY_HW_LED_OFF(led_pin);
+ GPIO_InitStructure.Pin = led_pin->pin_mask;
+ HAL_GPIO_Init(led_pin->gpio, &GPIO_InitStructure);
+ }
+}
+
+void led_state(pyb_led_t led, int state) {
+ if (led < 1 || led > NUM_LEDS) {
+ return;
+ }
+ const pin_obj_t *led_pin = pyb_led_obj[led - 1].led_pin;
+ //printf("led_state(%d,%d)\n", led, state);
+ if (state == 0) {
+ // turn LED off
+ MICROPY_HW_LED_OFF(led_pin);
+ } else {
+ // turn LED on
+ MICROPY_HW_LED_ON(led_pin);
+ }
+}
+
+void led_toggle(pyb_led_t led) {
+ if (led < 1 || led > NUM_LEDS) {
+ return;
+ }
+ const pin_obj_t *led_pin = pyb_led_obj[led - 1].led_pin;
+ GPIO_TypeDef *gpio = led_pin->gpio;
+
+ // We don't know if we're turning the LED on or off, but we don't really
+ // care. Just invert the state.
+ if (gpio->PDOR & led_pin->pin_mask) {
+ // pin is high, make it low
+ gpio->PCOR = led_pin->pin_mask;
+ } else {
+ // pin is low, make it high
+ gpio->PSOR = led_pin->pin_mask;
+ }
+}
+
+/******************************************************************************/
+/* MicroPython bindings */
+
+void led_obj_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
+ pyb_led_obj_t *self = self_in;
+ (void)kind;
+ mp_printf(print, "<LED %lu>", self->led_id);
+}
+
+STATIC mp_obj_t led_obj_make_new(const mp_obj_type_t *type, uint n_args, uint n_kw, const mp_obj_t *args) {
+ // check arguments
+ mp_arg_check_num(n_args, n_kw, 1, 1, false);
+
+ // get led number
+ mp_int_t led_id = mp_obj_get_int(args[0]);
+
+ // check led number
+ if (!(1 <= led_id && led_id <= NUM_LEDS)) {
+ nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "LED %d does not exist", led_id));
+ }
+
+ // return static led object
+ return (mp_obj_t)&pyb_led_obj[led_id - 1];
+}
+
+mp_obj_t led_obj_on(mp_obj_t self_in) {
+ pyb_led_obj_t *self = self_in;
+ led_state(self->led_id, 1);
+ return mp_const_none;
+}
+
+mp_obj_t led_obj_off(mp_obj_t self_in) {
+ pyb_led_obj_t *self = self_in;
+ led_state(self->led_id, 0);
+ return mp_const_none;
+}
+
+mp_obj_t led_obj_toggle(mp_obj_t self_in) {
+ pyb_led_obj_t *self = self_in;
+ led_toggle(self->led_id);
+ return mp_const_none;
+}
+
+STATIC MP_DEFINE_CONST_FUN_OBJ_1(led_obj_on_obj, led_obj_on);
+STATIC MP_DEFINE_CONST_FUN_OBJ_1(led_obj_off_obj, led_obj_off);
+STATIC MP_DEFINE_CONST_FUN_OBJ_1(led_obj_toggle_obj, led_obj_toggle);
+
+STATIC const mp_rom_map_elem_t led_locals_dict_table[] = {
+ { MP_ROM_QSTR(MP_QSTR_on), MP_ROM_PTR(&led_obj_on_obj) },
+ { MP_ROM_QSTR(MP_QSTR_off), MP_ROM_PTR(&led_obj_off_obj) },
+ { MP_ROM_QSTR(MP_QSTR_toggle), MP_ROM_PTR(&led_obj_toggle_obj) },
+};
+
+STATIC MP_DEFINE_CONST_DICT(led_locals_dict, led_locals_dict_table);
+
+const mp_obj_type_t pyb_led_type = {
+ { &mp_type_type },
+ .name = MP_QSTR_LED,
+ .print = led_obj_print,
+ .make_new = led_obj_make_new,
+ .locals_dict = (mp_obj_t)&led_locals_dict,
+};
diff --git a/ports/teensy/led.h b/ports/teensy/led.h
new file mode 100644
index 000000000..5c45166ef
--- /dev/null
+++ b/ports/teensy/led.h
@@ -0,0 +1,14 @@
+#ifndef MICROPY_INCLUDED_TEENSY_LED_H
+#define MICROPY_INCLUDED_TEENSY_LED_H
+
+typedef enum {
+ PYB_LED_BUILTIN = 1,
+} pyb_led_t;
+
+void led_init(void);
+void led_state(pyb_led_t led, int state);
+void led_toggle(pyb_led_t led);
+
+extern const mp_obj_type_t pyb_led_type;
+
+#endif // MICROPY_INCLUDED_TEENSY_LED_H
diff --git a/ports/teensy/lexerfrozen.c b/ports/teensy/lexerfrozen.c
new file mode 100644
index 000000000..21e978dc7
--- /dev/null
+++ b/ports/teensy/lexerfrozen.c
@@ -0,0 +1,13 @@
+#include <stdio.h>
+
+#include "py/lexer.h"
+#include "py/runtime.h"
+#include "py/mperrno.h"
+
+mp_import_stat_t mp_import_stat(const char *path) {
+ return MP_IMPORT_STAT_NO_EXIST;
+}
+
+mp_lexer_t *mp_lexer_new_from_file(const char *filename) {
+ mp_raise_OSError(MP_ENOENT);
+}
diff --git a/ports/teensy/lexermemzip.h b/ports/teensy/lexermemzip.h
new file mode 100644
index 000000000..cd7326a43
--- /dev/null
+++ b/ports/teensy/lexermemzip.h
@@ -0,0 +1,6 @@
+#ifndef MICROPY_INCLUDED_TEENSY_LEXERMEMZIP_H
+#define MICROPY_INCLUDED_TEENSY_LEXERMEMZIP_H
+
+mp_lexer_t *mp_lexer_new_from_memzip_file(const char *filename);
+
+#endif // MICROPY_INCLUDED_TEENSY_LEXERMEMZIP_H
diff --git a/ports/teensy/main.c b/ports/teensy/main.c
new file mode 100644
index 000000000..3edaa28a0
--- /dev/null
+++ b/ports/teensy/main.c
@@ -0,0 +1,381 @@
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include "py/lexer.h"
+#include "py/runtime.h"
+#include "py/stackctrl.h"
+#include "py/gc.h"
+#include "py/mphal.h"
+#include "gccollect.h"
+#include "lib/utils/pyexec.h"
+#include "lib/mp-readline/readline.h"
+#include "lexermemzip.h"
+
+#include "Arduino.h"
+
+#include "servo.h"
+#include "led.h"
+#include "uart.h"
+#include "pin.h"
+
+extern uint32_t _heap_start;
+
+void flash_error(int n) {
+ for (int i = 0; i < n; i++) {
+ led_state(PYB_LED_BUILTIN, 1);
+ delay(250);
+ led_state(PYB_LED_BUILTIN, 0);
+ delay(250);
+ }
+}
+
+void NORETURN __fatal_error(const char *msg) {
+ for (volatile uint delay = 0; delay < 10000000; delay++) {
+ }
+ led_state(1, 1);
+ led_state(2, 1);
+ led_state(3, 1);
+ led_state(4, 1);
+ mp_hal_stdout_tx_strn("\nFATAL ERROR:\n", 14);
+ mp_hal_stdout_tx_strn(msg, strlen(msg));
+ for (uint i = 0;;) {
+ led_toggle(((i++) & 3) + 1);
+ for (volatile uint delay = 0; delay < 10000000; delay++) {
+ }
+ if (i >= 16) {
+ // to conserve power
+ __WFI();
+ }
+ }
+}
+
+void nlr_jump_fail(void *val) {
+ printf("FATAL: uncaught exception %p\n", val);
+ __fatal_error("");
+}
+
+void __assert_func(const char *file, int line, const char *func, const char *expr) {
+
+ printf("Assertion failed: %s, file %s, line %d\n", expr, file, line);
+ __fatal_error("");
+}
+
+mp_obj_t pyb_analog_read(mp_obj_t pin_obj) {
+ uint pin = mp_obj_get_int(pin_obj);
+ int val = analogRead(pin);
+ return MP_OBJ_NEW_SMALL_INT(val);
+}
+
+mp_obj_t pyb_analog_write(mp_obj_t pin_obj, mp_obj_t val_obj) {
+ uint pin = mp_obj_get_int(pin_obj);
+ int val = mp_obj_get_int(val_obj);
+ analogWrite(pin, val);
+ return mp_const_none;
+}
+
+mp_obj_t pyb_analog_write_resolution(mp_obj_t res_obj) {
+ int res = mp_obj_get_int(res_obj);
+ analogWriteResolution(res);
+ return mp_const_none;
+}
+
+mp_obj_t pyb_analog_write_frequency(mp_obj_t pin_obj, mp_obj_t freq_obj) {
+ uint pin = mp_obj_get_int(pin_obj);
+ int freq = mp_obj_get_int(freq_obj);
+ analogWriteFrequency(pin, freq);
+ return mp_const_none;
+}
+
+#if 0
+// get lots of info about the board
+static mp_obj_t pyb_info(void) {
+ // get and print unique id; 96 bits
+ {
+ byte *id = (byte*)0x40048058;
+ printf("ID=%02x%02x%02x%02x:%02x%02x%02x%02x:%02x%02x%02x%02x\n", id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7], id[8], id[9], id[10], id[11]);
+ }
+
+ // get and print clock speeds
+ printf("CPU=%u\nBUS=%u\nMEM=%u\n", F_CPU, F_BUS, F_MEM);
+
+ // to print info about memory
+ {
+ printf("_sdata=%p\n", &_sdata);
+ printf("_edata=%p\n", &_edata);
+ printf("_sbss=%p\n", &_sbss);
+ printf("_ebss=%p\n", &_ebss);
+ printf("_estack=%p\n", &_estack);
+ printf("_etext=%p\n", &_etext);
+ printf("_heap_start=%p\n", &_heap_start);
+ }
+
+ // GC info
+ {
+ gc_info_t info;
+ gc_info(&info);
+ printf("GC:\n");
+ printf(" %u total\n", info.total);
+ printf(" %u used %u free\n", info.used, info.free);
+ printf(" 1=%u 2=%u m=%u\n", info.num_1block, info.num_2block, info.max_block);
+ }
+
+#if 0
+ // free space on flash
+ {
+ DWORD nclst;
+ FATFS *fatfs;
+ f_getfree("0:", &nclst, &fatfs);
+ printf("LFS free: %u bytes\n", (uint)(nclst * fatfs->csize * 512));
+ }
+#endif
+
+ return mp_const_none;
+}
+
+#endif
+
+#define RAM_START (0x1FFF8000) // fixed for chip
+#define HEAP_END (0x20006000) // tunable
+#define RAM_END (0x20008000) // fixed for chip
+
+#if 0
+
+void gc_helper_get_regs_and_clean_stack(mp_uint_t *regs, mp_uint_t heap_end);
+
+mp_obj_t pyb_gc(void) {
+ gc_collect();
+ return mp_const_none;
+}
+
+mp_obj_t pyb_gpio(int n_args, mp_obj_t *args) {
+ //assert(1 <= n_args && n_args <= 2);
+
+ uint pin = mp_obj_get_int(args[0]);
+ if (pin > CORE_NUM_DIGITAL) {
+ goto pin_error;
+ }
+
+ if (n_args == 1) {
+ // get pin
+ pinMode(pin, INPUT);
+ return MP_OBJ_NEW_SMALL_INT(digitalRead(pin));
+ }
+
+ // set pin
+ pinMode(pin, OUTPUT);
+ digitalWrite(pin, mp_obj_is_true(args[1]));
+ return mp_const_none;
+
+pin_error:
+ nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "pin %d does not exist", pin));
+}
+
+MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_gpio_obj, 1, 2, pyb_gpio);
+
+#if 0
+mp_obj_t pyb_hid_send_report(mp_obj_t arg) {
+ mp_obj_t *items = mp_obj_get_array_fixed_n(arg, 4);
+ uint8_t data[4];
+ data[0] = mp_obj_get_int(items[0]);
+ data[1] = mp_obj_get_int(items[1]);
+ data[2] = mp_obj_get_int(items[2]);
+ data[3] = mp_obj_get_int(items[3]);
+ usb_hid_send_report(data);
+ return mp_const_none;
+}
+#endif
+
+#endif // 0
+
+STATIC mp_obj_t pyb_config_source_dir = MP_OBJ_NULL;
+STATIC mp_obj_t pyb_config_main = MP_OBJ_NULL;
+STATIC mp_obj_t pyb_config_usb_mode = MP_OBJ_NULL;
+
+mp_obj_t pyb_source_dir(mp_obj_t source_dir) {
+ if (MP_OBJ_IS_STR(source_dir)) {
+ pyb_config_source_dir = source_dir;
+ }
+ return mp_const_none;
+}
+
+MP_DEFINE_CONST_FUN_OBJ_1(pyb_source_dir_obj, pyb_source_dir);
+
+mp_obj_t pyb_main(mp_obj_t main) {
+ if (MP_OBJ_IS_STR(main)) {
+ pyb_config_main = main;
+ }
+ return mp_const_none;
+}
+
+MP_DEFINE_CONST_FUN_OBJ_1(pyb_main_obj, pyb_main);
+
+STATIC mp_obj_t pyb_usb_mode(mp_obj_t usb_mode) {
+ if (MP_OBJ_IS_STR(usb_mode)) {
+ pyb_config_usb_mode = usb_mode;
+ }
+ return mp_const_none;
+}
+
+MP_DEFINE_CONST_FUN_OBJ_1(pyb_usb_mode_obj, pyb_usb_mode);
+
+#if 0
+
+mp_obj_t pyb_delay(mp_obj_t count) {
+ delay(mp_obj_get_int(count));
+ return mp_const_none;
+}
+
+mp_obj_t pyb_led(mp_obj_t state) {
+ led_state(PYB_LED_BUILTIN, mp_obj_is_true(state));
+ return state;
+}
+
+#endif // 0
+
+#if 0
+char *strdup(const char *str) {
+ uint32_t len = strlen(str);
+ char *s2 = m_new(char, len + 1);
+ memcpy(s2, str, len);
+ s2[len] = 0;
+ return s2;
+}
+#endif
+
+int main(void) {
+ // TODO: Put this in a more common initialization function.
+ // Turn on STKALIGN which keeps the stack 8-byte aligned for interrupts
+ // (per EABI)
+ #define SCB_CCR_STKALIGN (1 << 9)
+ SCB_CCR |= SCB_CCR_STKALIGN;
+
+ mp_stack_ctrl_init();
+ mp_stack_set_limit(10240);
+
+ pinMode(LED_BUILTIN, OUTPUT);
+ led_init();
+
+// int first_soft_reset = true;
+
+soft_reset:
+
+ led_state(PYB_LED_BUILTIN, 1);
+
+ // GC init
+ gc_init(&_heap_start, (void*)HEAP_END);
+
+ // MicroPython init
+ mp_init();
+ mp_obj_list_init(mp_sys_path, 0);
+ mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR_)); // current dir (or base dir of the script)
+ mp_obj_list_init(mp_sys_argv, 0);
+
+ readline_init0();
+
+ pin_init0();
+
+#if 0
+ // add some functions to the python namespace
+ {
+ mp_store_name(MP_QSTR_help, mp_make_function_n(0, pyb_help));
+ mp_obj_t m = mp_obj_new_module(MP_QSTR_pyb);
+ mp_store_attr(m, MP_QSTR_info, mp_make_function_n(0, pyb_info));
+ mp_store_attr(m, MP_QSTR_source_dir, mp_make_function_n(1, pyb_source_dir));
+ mp_store_attr(m, MP_QSTR_main, mp_make_function_n(1, pyb_main));
+ mp_store_attr(m, MP_QSTR_gc, mp_make_function_n(0, pyb_gc));
+ mp_store_attr(m, MP_QSTR_delay, mp_make_function_n(1, pyb_delay));
+ mp_store_attr(m, MP_QSTR_led, mp_make_function_n(1, pyb_led));
+ mp_store_attr(m, MP_QSTR_LED, (mp_obj_t)&pyb_led_type);
+ mp_store_attr(m, MP_QSTR_analogRead, mp_make_function_n(1, pyb_analog_read));
+ mp_store_attr(m, MP_QSTR_analogWrite, mp_make_function_n(2, pyb_analog_write));
+ mp_store_attr(m, MP_QSTR_analogWriteResolution, mp_make_function_n(1, pyb_analog_write_resolution));
+ mp_store_attr(m, MP_QSTR_analogWriteFrequency, mp_make_function_n(2, pyb_analog_write_frequency));
+
+ mp_store_attr(m, MP_QSTR_gpio, (mp_obj_t)&pyb_gpio_obj);
+ mp_store_attr(m, MP_QSTR_Servo, mp_make_function_n(0, pyb_Servo));
+ mp_store_name(MP_QSTR_pyb, m);
+ }
+#endif
+
+#if MICROPY_MODULE_FROZEN
+ pyexec_frozen_module("boot.py");
+#else
+ if (!pyexec_file("/boot.py")) {
+ flash_error(4);
+ }
+#endif
+
+ // Turn bootup LED off
+ led_state(PYB_LED_BUILTIN, 0);
+
+ // run main script
+#if MICROPY_MODULE_FROZEN
+ pyexec_frozen_module("main.py");
+#else
+ {
+ vstr_t *vstr = vstr_new(16);
+ vstr_add_str(vstr, "/");
+ if (pyb_config_main == MP_OBJ_NULL) {
+ vstr_add_str(vstr, "main.py");
+ } else {
+ vstr_add_str(vstr, mp_obj_str_get_str(pyb_config_main));
+ }
+ if (!pyexec_file(vstr_null_terminated_str(vstr))) {
+ flash_error(3);
+ }
+ vstr_free(vstr);
+ }
+#endif
+
+ // enter REPL
+ // REPL mode can change, or it can request a soft reset
+ for (;;) {
+ if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
+ if (pyexec_raw_repl() != 0) {
+ break;
+ }
+ } else {
+ if (pyexec_friendly_repl() != 0) {
+ break;
+ }
+ }
+ }
+
+ printf("PYB: soft reboot\n");
+
+// first_soft_reset = false;
+ goto soft_reset;
+}
+
+// stub out __libc_init_array. It's called by mk20dx128.c and is used to call
+// global C++ constructors. Since this is a C-only projects, we don't need to
+// call constructors.
+void __libc_init_array(void) {
+}
+
+// ultoa is used by usb_init_serialnumber. Normally ultoa would be provided
+// by nonstd.c from the teensy core, but it conflicts with some of the
+// MicroPython functions in string0.c, so we provide ultoa here.
+char * ultoa(unsigned long val, char *buf, int radix)
+{
+ unsigned digit;
+ int i=0, j;
+ char t;
+
+ while (1) {
+ digit = val % radix;
+ buf[i] = ((digit < 10) ? '0' + digit : 'A' + digit - 10);
+ val /= radix;
+ if (val == 0) break;
+ i++;
+ }
+ buf[i + 1] = 0;
+ for (j=0; j < i; j++, i--) {
+ t = buf[j];
+ buf[j] = buf[i];
+ buf[i] = t;
+ }
+ return buf;
+}
diff --git a/ports/teensy/make-pins.py b/ports/teensy/make-pins.py
new file mode 100755
index 000000000..0f6c5f28d
--- /dev/null
+++ b/ports/teensy/make-pins.py
@@ -0,0 +1,405 @@
+#!/usr/bin/env python
+"""Creates the pin file for the Teensy."""
+
+from __future__ import print_function
+
+import argparse
+import sys
+import csv
+
+SUPPORTED_FN = {
+ 'FTM' : ['CH0', 'CH1', 'CH2', 'CH3', 'CH4', 'CH5', 'CH6', 'CH7',
+ 'QD_PHA', 'QD_PHB'],
+ 'I2C' : ['SDA', 'SCL'],
+ 'UART' : ['RX', 'TX', 'CTS', 'RTS'],
+ 'SPI' : ['NSS', 'SCK', 'MISO', 'MOSI']
+}
+
+def parse_port_pin(name_str):
+ """Parses a string and returns a (port-num, pin-num) tuple."""
+ if len(name_str) < 4:
+ raise ValueError("Expecting pin name to be at least 4 charcters.")
+ if name_str[0:2] != 'PT':
+ raise ValueError("Expecting pin name to start with PT")
+ if name_str[2] not in ('A', 'B', 'C', 'D', 'E', 'Z'):
+ raise ValueError("Expecting pin port to be between A and E or Z")
+ port = ord(name_str[2]) - ord('A')
+ pin_str = name_str[3:].split('/')[0]
+ if not pin_str.isdigit():
+ raise ValueError("Expecting numeric pin number.")
+ return (port, int(pin_str))
+
+def split_name_num(name_num):
+ num = None
+ for num_idx in range(len(name_num) - 1, -1, -1):
+ if not name_num[num_idx].isdigit():
+ name = name_num[0:num_idx + 1]
+ num_str = name_num[num_idx + 1:]
+ if len(num_str) > 0:
+ num = int(num_str)
+ break
+ return name, num
+
+
+class AlternateFunction(object):
+ """Holds the information associated with a pins alternate function."""
+
+ def __init__(self, idx, af_str):
+ self.idx = idx
+ self.af_str = af_str
+
+ self.func = ''
+ self.fn_num = None
+ self.pin_type = ''
+ self.supported = False
+
+ af_words = af_str.split('_', 1)
+ self.func, self.fn_num = split_name_num(af_words[0])
+ if len(af_words) > 1:
+ self.pin_type = af_words[1]
+ if self.func in SUPPORTED_FN:
+ pin_types = SUPPORTED_FN[self.func]
+ if self.pin_type in pin_types:
+ self.supported = True
+
+ def is_supported(self):
+ return self.supported
+
+ def ptr(self):
+ """Returns the numbered function (i.e. USART6) for this AF."""
+ if self.fn_num is None:
+ return self.func
+ return '{:s}{:d}'.format(self.func, self.fn_num)
+
+ def mux_name(self):
+ return 'AF{:d}_{:s}'.format(self.idx, self.ptr())
+
+ def print(self):
+ """Prints the C representation of this AF."""
+ if self.supported:
+ print(' AF', end='')
+ else:
+ print(' //', end='')
+ fn_num = self.fn_num
+ if fn_num is None:
+ fn_num = 0
+ print('({:2d}, {:8s}, {:2d}, {:10s}, {:8s}), // {:s}'.format(self.idx,
+ self.func, fn_num, self.pin_type, self.ptr(), self.af_str))
+
+ def qstr_list(self):
+ return [self.mux_name()]
+
+
+class Pin(object):
+ """Holds the information associated with a pin."""
+
+ def __init__(self, port, pin):
+ self.port = port
+ self.pin = pin
+ self.alt_fn = []
+ self.alt_fn_count = 0
+ self.adc_num = 0
+ self.adc_channel = 0
+ self.board_pin = False
+
+ def port_letter(self):
+ return chr(self.port + ord('A'))
+
+ def cpu_pin_name(self):
+ return '{:s}{:d}'.format(self.port_letter(), self.pin)
+
+ def is_board_pin(self):
+ return self.board_pin
+
+ def set_is_board_pin(self):
+ self.board_pin = True
+
+ def parse_adc(self, adc_str):
+ if (adc_str[:3] != 'ADC'):
+ return
+ (adc,channel) = adc_str.split('_')
+ for idx in range(3, len(adc)):
+ adc_num = int(adc[idx]) # 1, 2, or 3
+ self.adc_num |= (1 << (adc_num - 1))
+ self.adc_channel = int(channel[2:])
+
+ def parse_af(self, af_idx, af_strs_in):
+ if len(af_strs_in) == 0:
+ return
+ # If there is a slash, then the slash separates 2 aliases for the
+ # same alternate function.
+ af_strs = af_strs_in.split('/')
+ for af_str in af_strs:
+ alt_fn = AlternateFunction(af_idx, af_str)
+ self.alt_fn.append(alt_fn)
+ if alt_fn.is_supported():
+ self.alt_fn_count += 1
+
+ def alt_fn_name(self, null_if_0=False):
+ if null_if_0 and self.alt_fn_count == 0:
+ return 'NULL'
+ return 'pin_{:s}_af'.format(self.cpu_pin_name())
+
+ def adc_num_str(self):
+ str = ''
+ for adc_num in range(1,4):
+ if self.adc_num & (1 << (adc_num - 1)):
+ if len(str) > 0:
+ str += ' | '
+ str += 'PIN_ADC'
+ str += chr(ord('0') + adc_num)
+ if len(str) == 0:
+ str = '0'
+ return str
+
+ def print(self):
+ if self.alt_fn_count == 0:
+ print("// ", end='')
+ print('const pin_af_obj_t {:s}[] = {{'.format(self.alt_fn_name()))
+ for alt_fn in self.alt_fn:
+ alt_fn.print()
+ if self.alt_fn_count == 0:
+ print("// ", end='')
+ print('};')
+ print('')
+ print('const pin_obj_t pin_{:s} = PIN({:s}, {:d}, {:d}, {:s}, {:s}, {:d});'.format(
+ self.cpu_pin_name(), self.port_letter(), self.pin,
+ self.alt_fn_count, self.alt_fn_name(null_if_0=True),
+ self.adc_num_str(), self.adc_channel))
+ print('')
+
+ def print_header(self, hdr_file):
+ hdr_file.write('extern const pin_obj_t pin_{:s};\n'.
+ format(self.cpu_pin_name()))
+ if self.alt_fn_count > 0:
+ hdr_file.write('extern const pin_af_obj_t pin_{:s}_af[];\n'.
+ format(self.cpu_pin_name()))
+
+ def qstr_list(self):
+ result = []
+ for alt_fn in self.alt_fn:
+ if alt_fn.is_supported():
+ result += alt_fn.qstr_list()
+ return result
+
+
+class NamedPin(object):
+
+ def __init__(self, name, pin):
+ self._name = name
+ self._pin = pin
+
+ def pin(self):
+ return self._pin
+
+ def name(self):
+ return self._name
+
+
+class Pins(object):
+
+ def __init__(self):
+ self.cpu_pins = [] # list of NamedPin objects
+ self.board_pins = [] # list of NamedPin objects
+
+ def find_pin(self, port_num, pin_num):
+ for named_pin in self.cpu_pins:
+ pin = named_pin.pin()
+ if pin.port == port_num and pin.pin == pin_num:
+ return pin
+
+ def parse_af_file(self, filename, pinname_col, af_col):
+ with open(filename, 'r') as csvfile:
+ rows = csv.reader(csvfile)
+ for row in rows:
+ try:
+ (port_num, pin_num) = parse_port_pin(row[pinname_col])
+ except:
+ continue
+ pin = Pin(port_num, pin_num)
+ for af_idx in range(af_col, len(row)):
+ if af_idx >= af_col:
+ pin.parse_af(af_idx - af_col, row[af_idx])
+ self.cpu_pins.append(NamedPin(pin.cpu_pin_name(), pin))
+
+ def parse_board_file(self, filename):
+ with open(filename, 'r') as csvfile:
+ rows = csv.reader(csvfile)
+ for row in rows:
+ try:
+ (port_num, pin_num) = parse_port_pin(row[1])
+ except:
+ continue
+ pin = self.find_pin(port_num, pin_num)
+ if pin:
+ pin.set_is_board_pin()
+ self.board_pins.append(NamedPin(row[0], pin))
+
+ def print_named(self, label, named_pins):
+ print('STATIC const mp_rom_map_elem_t pin_{:s}_pins_locals_dict_table[] = {{'.format(label))
+ for named_pin in named_pins:
+ pin = named_pin.pin()
+ if pin.is_board_pin():
+ print(' {{ MP_ROM_QSTR(MP_QSTR_{:s}), MP_ROM_PTR(&pin_{:s}) }},'.format(named_pin.name(), pin.cpu_pin_name()))
+ print('};')
+ print('MP_DEFINE_CONST_DICT(pin_{:s}_pins_locals_dict, pin_{:s}_pins_locals_dict_table);'.format(label, label));
+
+ def print(self):
+ for named_pin in self.cpu_pins:
+ pin = named_pin.pin()
+ if pin.is_board_pin():
+ pin.print()
+ self.print_named('cpu', self.cpu_pins)
+ print('')
+ self.print_named('board', self.board_pins)
+
+ def print_adc(self, adc_num):
+ print('');
+ print('const pin_obj_t * const pin_adc{:d}[] = {{'.format(adc_num))
+ for channel in range(16):
+ adc_found = False
+ for named_pin in self.cpu_pins:
+ pin = named_pin.pin()
+ if (pin.is_board_pin() and
+ (pin.adc_num & (1 << (adc_num - 1))) and (pin.adc_channel == channel)):
+ print(' &pin_{:s}, // {:d}'.format(pin.cpu_pin_name(), channel))
+ adc_found = True
+ break
+ if not adc_found:
+ print(' NULL, // {:d}'.format(channel))
+ print('};')
+
+
+ def print_header(self, hdr_filename):
+ with open(hdr_filename, 'wt') as hdr_file:
+ for named_pin in self.cpu_pins:
+ pin = named_pin.pin()
+ if pin.is_board_pin():
+ pin.print_header(hdr_file)
+ hdr_file.write('extern const pin_obj_t * const pin_adc1[];\n')
+ hdr_file.write('extern const pin_obj_t * const pin_adc2[];\n')
+ hdr_file.write('extern const pin_obj_t * const pin_adc3[];\n')
+
+ def print_qstr(self, qstr_filename):
+ with open(qstr_filename, 'wt') as qstr_file:
+ qstr_set = set([])
+ for named_pin in self.cpu_pins:
+ pin = named_pin.pin()
+ if pin.is_board_pin():
+ qstr_set |= set(pin.qstr_list())
+ qstr_set |= set([named_pin.name()])
+ for named_pin in self.board_pins:
+ qstr_set |= set([named_pin.name()])
+ for qstr in sorted(qstr_set):
+ print('Q({})'.format(qstr), file=qstr_file)
+
+
+ def print_af_hdr(self, af_const_filename):
+ with open(af_const_filename, 'wt') as af_const_file:
+ af_hdr_set = set([])
+ mux_name_width = 0
+ for named_pin in self.cpu_pins:
+ pin = named_pin.pin()
+ if pin.is_board_pin():
+ for af in pin.alt_fn:
+ if af.is_supported():
+ mux_name = af.mux_name()
+ af_hdr_set |= set([mux_name])
+ if len(mux_name) > mux_name_width:
+ mux_name_width = len(mux_name)
+ for mux_name in sorted(af_hdr_set):
+ key = 'MP_OBJ_NEW_QSTR(MP_QSTR_{}),'.format(mux_name)
+ val = 'MP_OBJ_NEW_SMALL_INT(GPIO_{})'.format(mux_name)
+ print(' { %-*s %s },' % (mux_name_width + 26, key, val),
+ file=af_const_file)
+
+ def print_af_py(self, af_py_filename):
+ with open(af_py_filename, 'wt') as af_py_file:
+ print('PINS_AF = (', file=af_py_file);
+ for named_pin in self.board_pins:
+ print(" ('%s', " % named_pin.name(), end='', file=af_py_file)
+ for af in named_pin.pin().alt_fn:
+ if af.is_supported():
+ print("(%d, '%s'), " % (af.idx, af.af_str), end='', file=af_py_file)
+ print('),', file=af_py_file)
+ print(')', file=af_py_file)
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ prog="make-pins.py",
+ usage="%(prog)s [options] [command]",
+ description="Generate board specific pin file"
+ )
+ parser.add_argument(
+ "-a", "--af",
+ dest="af_filename",
+ help="Specifies the alternate function file for the chip",
+ default="mk20dx256_af.csv"
+ )
+ parser.add_argument(
+ "--af-const",
+ dest="af_const_filename",
+ help="Specifies header file for alternate function constants.",
+ default="build/pins_af_const.h"
+ )
+ parser.add_argument(
+ "--af-py",
+ dest="af_py_filename",
+ help="Specifies the filename for the python alternate function mappings.",
+ default="build/pins_af.py"
+ )
+ parser.add_argument(
+ "-b", "--board",
+ dest="board_filename",
+ help="Specifies the board file",
+ )
+ parser.add_argument(
+ "-p", "--prefix",
+ dest="prefix_filename",
+ help="Specifies beginning portion of generated pins file",
+ default="mk20dx256_prefix.c"
+ )
+ parser.add_argument(
+ "-q", "--qstr",
+ dest="qstr_filename",
+ help="Specifies name of generated qstr header file",
+ default="build/pins_qstr.h"
+ )
+ parser.add_argument(
+ "-r", "--hdr",
+ dest="hdr_filename",
+ help="Specifies name of generated pin header file",
+ default="build/pins.h"
+ )
+ args = parser.parse_args(sys.argv[1:])
+
+ pins = Pins()
+
+ print('// This file was automatically generated by make-pins.py')
+ print('//')
+ if args.af_filename:
+ print('// --af {:s}'.format(args.af_filename))
+ pins.parse_af_file(args.af_filename, 4, 3)
+
+ if args.board_filename:
+ print('// --board {:s}'.format(args.board_filename))
+ pins.parse_board_file(args.board_filename)
+
+ if args.prefix_filename:
+ print('// --prefix {:s}'.format(args.prefix_filename))
+ print('')
+ with open(args.prefix_filename, 'r') as prefix_file:
+ print(prefix_file.read())
+ pins.print()
+ pins.print_adc(1)
+ pins.print_adc(2)
+ pins.print_adc(3)
+ pins.print_header(args.hdr_filename)
+ pins.print_qstr(args.qstr_filename)
+ pins.print_af_hdr(args.af_const_filename)
+ pins.print_af_py(args.af_py_filename)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/ports/teensy/memzip_files/boot.py b/ports/teensy/memzip_files/boot.py
new file mode 100644
index 000000000..6dd5516a9
--- /dev/null
+++ b/ports/teensy/memzip_files/boot.py
@@ -0,0 +1,12 @@
+import pyb
+print("Executing boot.py")
+
+def pins():
+ for pin_name in dir(pyb.Pin.board):
+ pin = pyb.Pin(pin_name)
+ print('{:10s} {:s}'.format(pin_name, str(pin)))
+
+def af():
+ for pin_name in dir(pyb.Pin.board):
+ pin = pyb.Pin(pin_name)
+ print('{:10s} {:s}'.format(pin_name, str(pin.af_list())))
diff --git a/ports/teensy/memzip_files/main.py b/ports/teensy/memzip_files/main.py
new file mode 100644
index 000000000..b652377f9
--- /dev/null
+++ b/ports/teensy/memzip_files/main.py
@@ -0,0 +1,15 @@
+import pyb
+
+print("Executing main.py")
+
+led = pyb.LED(1)
+
+led.on()
+pyb.delay(100)
+led.off()
+pyb.delay(100)
+led.on()
+pyb.delay(100)
+led.off()
+
+
diff --git a/ports/teensy/mk20dx256.ld b/ports/teensy/mk20dx256.ld
new file mode 100644
index 000000000..bff0a8c4a
--- /dev/null
+++ b/ports/teensy/mk20dx256.ld
@@ -0,0 +1,176 @@
+/* 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.
+ */
+
+MEMORY
+{
+ FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 256K
+ RAM (rwx) : ORIGIN = 0x1FFF8000, LENGTH = 64K
+}
+
+/* produce a link error if there is not this amount of RAM for these sections */
+_minimum_stack_size = 2K;
+_minimum_heap_size = 16K;
+
+/* INCLUDE common.ld */
+
+/* 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.
+ */
+
+
+
+SECTIONS
+{
+ .text : {
+ . = 0;
+ KEEP(*(.vectors))
+ *(.startup*)
+ /* TODO: does linker detect startup overflow onto flashconfig? */
+ . = 0x400;
+ KEEP(*(.flashconfig*))
+ *(.text*)
+ *(.rodata*)
+ . = ALIGN(4);
+ KEEP(*(.init))
+ . = ALIGN(4);
+ __preinit_array_start = .;
+ KEEP (*(.preinit_array))
+ __preinit_array_end = .;
+ __init_array_start = .;
+ KEEP (*(SORT(.init_array.*)))
+ KEEP (*(.init_array))
+ __init_array_end = .;
+ } > FLASH = 0xFF
+
+ .ARM.exidx : {
+ __exidx_start = .;
+ *(.ARM.exidx* .gnu.linkonce.armexidx.*)
+ __exidx_end = .;
+ } > FLASH
+ _etext = .;
+
+ .usbdescriptortable (NOLOAD) : {
+ /* . = ORIGIN(RAM); */
+ . = ALIGN(512);
+ *(.usbdescriptortable*)
+ } > RAM
+
+ .dmabuffers (NOLOAD) : {
+ . = ALIGN(4);
+ *(.dmabuffers*)
+ } > RAM
+
+ .usbbuffers (NOLOAD) : {
+ . = ALIGN(4);
+ *(.usbbuffers*)
+ } > RAM
+
+ /* used by the startup to initialize data */
+ _sidata = LOADADDR(.data);
+
+ .data : AT (_etext) {
+ . = ALIGN(4);
+ _sdata = .;
+ _ram_start = .;
+ *(.data*)
+ . = ALIGN(4);
+ _edata = .;
+ } > RAM
+
+ /*
+ * _staticfs is the place in flash where the static filesystem which
+ * is concatenated to the .hex file will wind up.
+ */
+ _staticfs = LOADADDR(.data) + SIZEOF(.data);
+
+ .noinit (NOLOAD) : {
+ *(.noinit*)
+ } > RAM
+
+ .bss : {
+ . = ALIGN(4);
+ _sbss = .;
+ *(.bss*)
+ *(COMMON)
+ . = ALIGN(4);
+ _ebss = .;
+ __bss_end = .;
+ } > RAM
+
+ /* this is to define the start of the heap, and make sure we have a minimum size */
+ .heap :
+ {
+ . = ALIGN(4);
+ _heap_start = .; /* define a global symbol at heap start */
+ . = . + _minimum_heap_size;
+ } >RAM
+
+ /* this just checks there is enough RAM for the stack */
+ .stack :
+ {
+ . = ALIGN(4);
+ . = . + _minimum_stack_size;
+ . = ALIGN(4);
+ } >RAM
+
+ _estack = ORIGIN(RAM) + LENGTH(RAM);
+ _ram_end = ORIGIN(RAM) + LENGTH(RAM);
+ _heap_end = ORIGIN(RAM) + 0xe000;
+}
+
+
+
+
diff --git a/ports/teensy/mk20dx256_af.csv b/ports/teensy/mk20dx256_af.csv
new file mode 100644
index 000000000..571587de6
--- /dev/null
+++ b/ports/teensy/mk20dx256_af.csv
@@ -0,0 +1,65 @@
+Pin,Name,Default,ALT0,ALT1,ALT2,ALT3,ALT4,ALT5,ALT6,ALT7,EzPort
+1,PTE0,ADC1_SE4a,ADC1_SE4a,PTE0,SPI1_PCS1,UART1_TX,,,I2C1_SDA,RTC_CLKOUT,
+2,PTE1/LLWU_P0,ADC1_SE5a,ADC1_SE5a,PTE1/LLWU_P0,SPI1_SOUT,UART1_RX,,,I2C1_SCL,SPI1_SIN,
+3,VDD,VDD,VDD,,,,,,,,
+4,VSS,VSS,VSS,,,,,,,,
+5,USB0_DP,USB0_DP,USB0_DP,,,,,,,,
+6,USB0_DM,USB0_DM,USB0_DM,,,,,,,,
+7,VOUT33,VOUT33,VOUT33,,,,,,,,
+8,VREGIN,VREGIN,VREGIN,,,,,,,,
+9,PGA0_DP/ADC0_DP0/ADC1_DP3,PGA0_DP/ADC0_DP0/ADC1_DP3,PGA0_DP/ADC0_DP0/ADC1_DP3,PTZ0,,,,,,,
+10,PGA0_DM/ADC0_DM0/ADC1_DM3,PGA0_DM/ADC0_DM0/ADC1_DM3,PGA0_DM/ADC0_DM0/ADC1_DM3,PTZ1,,,,,,,
+11,PGA1_DP/ADC1_DP0/ADC0_DP3,PGA1_DP/ADC1_DP0/ADC0_DP3,PGA1_DP/ADC1_DP0/ADC0_DP3,PTZ2,,,,,,,
+12,PGA1_DM/ADC1_DM0/ADC0_DM3,PGA1_DM/ADC1_DM0/ADC0_DM3,PGA1_DM/ADC1_DM0/ADC0_DM3,PTZ3,,,,,,,
+13,VDDA,VDDA,VDDA,,,,,,,,
+14,VREFH,VREFH,VREFH,,,,,,,,
+15,VREFL,VREFL,VREFL,,,,,,,,
+16,VSSA,VSSA,VSSA,,,,,,,,
+17,VREF_OUT/CMP1_IN5/CMP0_IN5/ADC1_SE18,VREF_OUT/CMP1_IN5/CMP0_IN5/ADC1_SE18,VREF_OUT/CMP1_IN5/CMP0_IN5/ADC1_SE18,PTZ4,,,,,,,
+18,DAC0_OUT/CMP1_IN3/ADC0_SE23,DAC0_OUT/CMP1_IN3/ADC0_SE23,DAC0_OUT/CMP1_IN3/ADC0_SE23,PTZ5,,,,,,,
+19,XTAL32,XTAL32,XTAL32,,,,,,,,
+20,EXTAL32,EXTAL32,EXTAL32,,,,,,,,
+21,VBAT,VBAT,VBAT,,,,,,,,
+22,PTA0,JTAG_TCLK/SWD_CLK/EZP_CLK,TSI0_CH1,PTA0,UART0_CTS_b/UART0_COL_b,FTM0_CH5,,,,JTAG_TCLK/SWD_CLK,EZP_CLK
+23,PTA1,JTAG_TDI/EZP_DI,TSI0_CH2,PTA1,UART0_RX,FTM0_CH6,,,,JTAG_TDI,EZP_DI
+24,PTA2,JTAG_TDO/TRACE_SWO/EZP_DO,TSI0_CH3,PTA2,UART0_TX,FTM0_CH7,,,,JTAG_TDO/TRACE_SWO,EZP_DO
+25,PTA3,JTAG_TMS/SWD_DIO,TSI0_CH4,PTA3,UART0_RTS_b,FTM0_CH0,,,,JTAG_TMS/SWD_DIO,
+26,PTA4/LLWU_P3,NMI_b/EZP_CS_b,TSI0_CH5,PTA4/LLWU_P3,,FTM0_CH1,,,NMI_b,EZP_CS_b,
+27,PTA5,DISABLED,,PTA5,USB_CLKIN,FTM0_CH2,,CMP2_OUT,I2S0_TX_BCLK,JTAG_TRST_b,
+28,PTA12,CMP2_IN0,CMP2_IN0,PTA12,CAN0_TX,FTM1_CH0,,,I2S0_TXD0,FTM1_QD_PHA,
+29,PTA13/LLWU_P4,CMP2_IN1,CMP2_IN1,PTA13/LLWU_P4,CAN0_RX,FTM1_CH1,,,I2S0_TX_FS,FTM1_QD_PHB,
+30,VDD,VDD,VDD,,,,,,,,
+31,VSS,VSS,VSS,,,,,,,,
+32,PTA18,EXTAL0,EXTAL0,PTA18,,FTM0_FLT2,FTM_CLKIN0,,,,
+33,PTA19,XTAL0,XTAL0,PTA19,,FTM1_FLT0,FTM_CLKIN1,,LPTMR0_ALT1,,
+34,RESET_b,RESET_b,RESET_b,,,,,,,,
+35,PTB0/LLWU_P5,ADC0_SE8/ADC1_SE8/TSI0_CH0,ADC0_SE8/ADC1_SE8/TSI0_CH0,PTB0/LLWU_P5,I2C0_SCL,FTM1_CH0,,,FTM1_QD_PHA,,
+36,PTB1,ADC0_SE9/ADC1_SE9/TSI0_CH6,ADC0_SE9/ADC1_SE9/TSI0_CH6,PTB1,I2C0_SDA,FTM1_CH1,,,FTM1_QD_PHB,,
+37,PTB2,ADC0_SE12/TSI0_CH7,ADC0_SE12/TSI0_CH7,PTB2,I2C0_SCL,UART0_RTS_b,,,FTM0_FLT3,,
+38,PTB3,ADC0_SE13/TSI0_CH8,ADC0_SE13/TSI0_CH8,PTB3,I2C0_SDA,UART0_CTS_b/UART0_COL_b,,,FTM0_FLT0,,
+39,PTB16,TSI0_CH9,TSI0_CH9,PTB16,SPI1_SOUT,UART0_RX,,FB_AD17,EWM_IN,,
+40,PTB17,TSI0_CH10,TSI0_CH10,PTB17,SPI1_SIN,UART0_TX,,FB_AD16,EWM_OUT_b,,
+41,PTB18,TSI0_CH11,TSI0_CH11,PTB18,CAN0_TX,FTM2_CH0,I2S0_TX_BCLK,FB_AD15,FTM2_QD_PHA,,
+42,PTB19,TSI0_CH12,TSI0_CH12,PTB19,CAN0_RX,FTM2_CH1,I2S0_TX_FS,FB_OE_b,FTM2_QD_PHB,,
+43,PTC0,ADC0_SE14/TSI0_CH13,ADC0_SE14/TSI0_CH13,PTC0,SPI0_PCS4,PDB0_EXTRG,,FB_AD14,I2S0_TXD1,,
+44,PTC1/LLWU_P6,ADC0_SE15/TSI0_CH14,ADC0_SE15/TSI0_CH14,PTC1/LLWU_P6,SPI0_PCS3,UART1_RTS_b,FTM0_CH0,FB_AD13,I2S0_TXD0,,
+45,PTC2,ADC0_SE4b/CMP1_IN0/TSI0_CH15,ADC0_SE4b/CMP1_IN0/TSI0_CH15,PTC2,SPI0_PCS2,UART1_CTS_b,FTM0_CH1,FB_AD12,I2S0_TX_FS,,
+46,PTC3/LLWU_P7,CMP1_IN1,CMP1_IN1,PTC3/LLWU_P7,SPI0_PCS1,UART1_RX,FTM0_CH2,CLKOUT,I2S0_TX_BCLK,,
+47,VSS,VSS,VSS,,,,,,,,
+48,VDD,VDD,VDD,,,,,,,,
+49,PTC4/LLWU_P8,DISABLED,,PTC4/LLWU_P8,SPI0_PCS0,UART1_TX,FTM0_CH3,FB_AD11,CMP1_OUT,,
+50,PTC5/LLWU_P9,DISABLED,,PTC5/LLWU_P9,SPI0_SCK,LPTMR0_ALT2,I2S0_RXD0,FB_AD10,CMP0_OUT,,
+51,PTC6/LLWU_P10,CMP0_IN0,CMP0_IN0,PTC6/LLWU_P10,SPI0_SOUT,PDB0_EXTRG,I2S0_RX_BCLK,FB_AD9,I2S0_MCLK,,
+52,PTC7,CMP0_IN1,CMP0_IN1,PTC7,SPI0_SIN,USB_SOF_OUT,I2S0_RX_FS,FB_AD8,,,
+53,PTC8,ADC1_SE4b/CMP0_IN2,ADC1_SE4b/CMP0_IN2,PTC8,,,I2S0_MCLK,FB_AD7,,,
+54,PTC9,ADC1_SE5b/CMP0_IN3,ADC1_SE5b/CMP0_IN3,PTC9,,,I2S0_RX_BCLK,FB_AD6,FTM2_FLT0,,
+55,PTC10,ADC1_SE6b,ADC1_SE6b,PTC10,I2C1_SCL,,I2S0_RX_FS,FB_AD5,,,
+56,PTC11/LLWU_P11,ADC1_SE7b,ADC1_SE7b,PTC11/LLWU_P11,I2C1_SDA,,I2S0_RXD1,FB_RW_b,,,
+57,PTD0/LLWU_P12,DISABLED,,PTD0/LLWU_P12,SPI0_PCS0,UART2_RTS_b,,FB_ALE/FB_CS1_b/FB_TS_b,,,
+58,PTD1,ADC0_SE5b,ADC0_SE5b,PTD1,SPI0_SCK,UART2_CTS_b,,FB_CS0_b,,,
+59,PTD2/LLWU_P13,DISABLED,,PTD2/LLWU_P13,SPI0_SOUT,UART2_RX,,FB_AD4,,,
+60,PTD3,DISABLED,,PTD3,SPI0_SIN,UART2_TX,,FB_AD3,,,
+61,PTD4/LLWU_P14,DISABLED,,PTD4/LLWU_P14,SPI0_PCS1,UART0_RTS_b,FTM0_CH4,FB_AD2,EWM_IN,,
+62,PTD5,ADC0_SE6b,ADC0_SE6b,PTD5,SPI0_PCS2,UART0_CTS_b/UART0_COL_b,FTM0_CH5,FB_AD1,EWM_OUT_b,,
+63,PTD6/LLWU_P15,ADC0_SE7b,ADC0_SE7b,PTD6/LLWU_P15,SPI0_PCS3,UART0_RX,FTM0_CH6,FB_AD0,FTM0_FLT0f,,
+64,PTD7,DISABLED,,PTD7,CMT_IRO,UART0_TX,FTM0_CH7,,FTM0_FLT1,,
diff --git a/ports/teensy/mk20dx256_prefix.c b/ports/teensy/mk20dx256_prefix.c
new file mode 100644
index 000000000..d8e7480b5
--- /dev/null
+++ b/ports/teensy/mk20dx256_prefix.c
@@ -0,0 +1,33 @@
+// stm32fxx-prefix.c becomes the initial portion of the generated pins file.
+
+#include <stdio.h>
+#include <mk20dx128.h>
+
+#include "py/obj.h"
+#include "teensy_hal.h"
+#include "pin.h"
+
+#define AF(af_idx, af_fn, af_unit, af_type, af_ptr) \
+{ \
+ { &pin_af_type }, \
+ .name = MP_QSTR_AF ## af_idx ## _ ## af_fn ## af_unit, \
+ .idx = (af_idx), \
+ .fn = AF_FN_ ## af_fn, \
+ .unit = (af_unit), \
+ .type = AF_PIN_TYPE_ ## af_fn ## _ ## af_type, \
+ .af_fn = (af_ptr) \
+}
+
+#define PIN(p_port, p_pin, p_num_af, p_af, p_adc_num, p_adc_channel) \
+{ \
+ { &pin_type }, \
+ .name = MP_QSTR_ ## p_port ## p_pin, \
+ .port = PORT_ ## p_port, \
+ .pin = (p_pin), \
+ .num_af = (p_num_af), \
+ .pin_mask = (1 << (p_pin)), \
+ .gpio = GPIO ## p_port, \
+ .af = p_af, \
+ .adc_num = p_adc_num, \
+ .adc_channel = p_adc_channel, \
+}
diff --git a/ports/teensy/modpyb.c b/ports/teensy/modpyb.c
new file mode 100644
index 000000000..e4c399fc8
--- /dev/null
+++ b/ports/teensy/modpyb.c
@@ -0,0 +1,358 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2013, 2014 Damien P. George
+ *
+ * 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 <stdint.h>
+#include <stdio.h>
+#include <mk20dx128.h>
+#include "Arduino.h"
+
+#include "py/obj.h"
+#include "py/gc.h"
+#include "py/mphal.h"
+
+#include "lib/utils/pyexec.h"
+
+#include "gccollect.h"
+#include "irq.h"
+#include "systick.h"
+#include "led.h"
+#include "pin.h"
+#include "timer.h"
+#include "extint.h"
+#include "usrsw.h"
+#include "rng.h"
+//#include "rtc.h"
+//#include "i2c.h"
+//#include "spi.h"
+#include "uart.h"
+#include "adc.h"
+#include "storage.h"
+#include "sdcard.h"
+#include "accel.h"
+#include "servo.h"
+#include "dac.h"
+#include "usb.h"
+#include "portmodules.h"
+
+/// \module pyb - functions related to the pyboard
+///
+/// The `pyb` module contains specific functions related to the pyboard.
+
+/// \function bootloader()
+/// Activate the bootloader without BOOT* pins.
+STATIC mp_obj_t pyb_bootloader(void) {
+ printf("bootloader command not current supported\n");
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_0(pyb_bootloader_obj, pyb_bootloader);
+
+/// \function info([dump_alloc_table])
+/// Print out lots of information about the board.
+STATIC mp_obj_t pyb_info(uint n_args, const mp_obj_t *args) {
+ // get and print unique id; 96 bits
+ {
+ byte *id = (byte*)0x40048058;
+ printf("ID=%02x%02x%02x%02x:%02x%02x%02x%02x:%02x%02x%02x%02x\n", id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7], id[8], id[9], id[10], id[11]);
+ }
+
+ // get and print clock speeds
+ printf("CPU=%u\nBUS=%u\nMEM=%u\n", F_CPU, F_BUS, F_MEM);
+
+ // to print info about memory
+ {
+ printf("_etext=%p\n", &_etext);
+ printf("_sidata=%p\n", &_sidata);
+ printf("_sdata=%p\n", &_sdata);
+ printf("_edata=%p\n", &_edata);
+ printf("_sbss=%p\n", &_sbss);
+ printf("_ebss=%p\n", &_ebss);
+ printf("_estack=%p\n", &_estack);
+ printf("_ram_start=%p\n", &_ram_start);
+ printf("_heap_start=%p\n", &_heap_start);
+ printf("_heap_end=%p\n", &_heap_end);
+ printf("_ram_end=%p\n", &_ram_end);
+ }
+
+ // qstr info
+ {
+ uint n_pool, n_qstr, n_str_data_bytes, n_total_bytes;
+ qstr_pool_info(&n_pool, &n_qstr, &n_str_data_bytes, &n_total_bytes);
+ printf("qstr:\n n_pool=%u\n n_qstr=%u\n n_str_data_bytes=%u\n n_total_bytes=%u\n", n_pool, n_qstr, n_str_data_bytes, n_total_bytes);
+ }
+
+ // GC info
+ {
+ gc_info_t info;
+ gc_info(&info);
+ printf("GC:\n");
+ printf(" " UINT_FMT " total\n", info.total);
+ printf(" " UINT_FMT " : " UINT_FMT "\n", info.used, info.free);
+ printf(" 1=" UINT_FMT " 2=" UINT_FMT " m=" UINT_FMT "\n", info.num_1block, info.num_2block, info.max_block);
+ }
+
+ if (n_args == 1) {
+ // arg given means dump gc allocation table
+ gc_dump_alloc_table();
+ }
+
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_info_obj, 0, 1, pyb_info);
+
+/// \function unique_id()
+/// Returns a string of 12 bytes (96 bits), which is the unique ID for the MCU.
+STATIC mp_obj_t pyb_unique_id(void) {
+ byte *id = (byte*)0x40048058;
+ return mp_obj_new_bytes(id, 12);
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_0(pyb_unique_id_obj, pyb_unique_id);
+
+/// \function freq()
+/// Return a tuple of clock frequencies: (SYSCLK, HCLK, PCLK1, PCLK2).
+// TODO should also be able to set frequency via this function
+STATIC mp_obj_t pyb_freq(void) {
+ mp_obj_t tuple[3] = {
+ mp_obj_new_int(F_CPU),
+ mp_obj_new_int(F_BUS),
+ mp_obj_new_int(F_MEM),
+ };
+ return mp_obj_new_tuple(3, tuple);
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_0(pyb_freq_obj, pyb_freq);
+
+/// \function sync()
+/// Sync all file systems.
+STATIC mp_obj_t pyb_sync(void) {
+ printf("sync not currently implemented\n");
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_0(pyb_sync_obj, pyb_sync);
+
+/// \function millis()
+/// Returns the number of milliseconds since the board was last reset.
+///
+/// The result is always a MicroPython smallint (31-bit signed number), so
+/// after 2^30 milliseconds (about 12.4 days) this will start to return
+/// negative numbers.
+STATIC mp_obj_t pyb_millis(void) {
+ // We want to "cast" the 32 bit unsigned into a small-int. This means
+ // copying the MSB down 1 bit (extending the sign down), which is
+ // equivalent to just using the MP_OBJ_NEW_SMALL_INT macro.
+ return MP_OBJ_NEW_SMALL_INT(mp_hal_ticks_ms());
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_0(pyb_millis_obj, pyb_millis);
+
+/// \function elapsed_millis(start)
+/// Returns the number of milliseconds which have elapsed since `start`.
+///
+/// This function takes care of counter wrap, and always returns a positive
+/// number. This means it can be used to measure periods upto about 12.4 days.
+///
+/// Example:
+/// start = pyb.millis()
+/// while pyb.elapsed_millis(start) < 1000:
+/// # Perform some operation
+STATIC mp_obj_t pyb_elapsed_millis(mp_obj_t start) {
+ uint32_t startMillis = mp_obj_get_int(start);
+ uint32_t currMillis = mp_hal_ticks_ms();
+ return MP_OBJ_NEW_SMALL_INT((currMillis - startMillis) & 0x3fffffff);
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_elapsed_millis_obj, pyb_elapsed_millis);
+
+/// \function micros()
+/// Returns the number of microseconds since the board was last reset.
+///
+/// The result is always a MicroPython smallint (31-bit signed number), so
+/// after 2^30 microseconds (about 17.8 minutes) this will start to return
+/// negative numbers.
+STATIC mp_obj_t pyb_micros(void) {
+ // We want to "cast" the 32 bit unsigned into a small-int. This means
+ // copying the MSB down 1 bit (extending the sign down), which is
+ // equivalent to just using the MP_OBJ_NEW_SMALL_INT macro.
+ return MP_OBJ_NEW_SMALL_INT(micros());
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_0(pyb_micros_obj, pyb_micros);
+
+/// \function elapsed_micros(start)
+/// Returns the number of microseconds which have elapsed since `start`.
+///
+/// This function takes care of counter wrap, and always returns a positive
+/// number. This means it can be used to measure periods upto about 17.8 minutes.
+///
+/// Example:
+/// start = pyb.micros()
+/// while pyb.elapsed_micros(start) < 1000:
+/// # Perform some operation
+STATIC mp_obj_t pyb_elapsed_micros(mp_obj_t start) {
+ uint32_t startMicros = mp_obj_get_int(start);
+ uint32_t currMicros = micros();
+ return MP_OBJ_NEW_SMALL_INT((currMicros - startMicros) & 0x3fffffff);
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_elapsed_micros_obj, pyb_elapsed_micros);
+
+/// \function delay(ms)
+/// Delay for the given number of milliseconds.
+STATIC mp_obj_t pyb_delay(mp_obj_t ms_in) {
+ mp_int_t ms = mp_obj_get_int(ms_in);
+ if (ms >= 0) {
+ mp_hal_delay_ms(ms);
+ }
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_delay_obj, pyb_delay);
+
+/// \function udelay(us)
+/// Delay for the given number of microseconds.
+STATIC mp_obj_t pyb_udelay(mp_obj_t usec_in) {
+ mp_int_t usec = mp_obj_get_int(usec_in);
+ delayMicroseconds(usec);
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_udelay_obj, pyb_udelay);
+
+STATIC mp_obj_t pyb_stop(void) {
+ printf("stop not currently implemented\n");
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_0(pyb_stop_obj, pyb_stop);
+
+STATIC mp_obj_t pyb_standby(void) {
+ printf("standby not currently implemented\n");
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_0(pyb_standby_obj, pyb_standby);
+
+/// \function have_cdc()
+/// Return True if USB is connected as a serial device, False otherwise.
+STATIC mp_obj_t pyb_have_cdc(void ) {
+ return mp_obj_new_bool(usb_vcp_is_connected());
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_0(pyb_have_cdc_obj, pyb_have_cdc);
+
+/// \function hid((buttons, x, y, z))
+/// Takes a 4-tuple (or list) and sends it to the USB host (the PC) to
+/// signal a HID mouse-motion event.
+STATIC mp_obj_t pyb_hid_send_report(mp_obj_t arg) {
+#if 1
+ printf("hid_send_report not currently implemented\n");
+#else
+ mp_obj_t *items;
+ mp_obj_get_array_fixed_n(arg, 4, &items);
+ uint8_t data[4];
+ data[0] = mp_obj_get_int(items[0]);
+ data[1] = mp_obj_get_int(items[1]);
+ data[2] = mp_obj_get_int(items[2]);
+ data[3] = mp_obj_get_int(items[3]);
+ usb_hid_send_report(data);
+#endif
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_hid_send_report_obj, pyb_hid_send_report);
+
+MP_DECLARE_CONST_FUN_OBJ_1(pyb_source_dir_obj); // defined in main.c
+MP_DECLARE_CONST_FUN_OBJ_1(pyb_main_obj); // defined in main.c
+MP_DECLARE_CONST_FUN_OBJ_1(pyb_usb_mode_obj); // defined in main.c
+
+STATIC const mp_rom_map_elem_t pyb_module_globals_table[] = {
+ { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_pyb) },
+
+ { MP_ROM_QSTR(MP_QSTR_bootloader), MP_ROM_PTR(&pyb_bootloader_obj) },
+ { MP_ROM_QSTR(MP_QSTR_info), MP_ROM_PTR(&pyb_info_obj) },
+ { MP_ROM_QSTR(MP_QSTR_unique_id), MP_ROM_PTR(&pyb_unique_id_obj) },
+ { MP_ROM_QSTR(MP_QSTR_freq), MP_ROM_PTR(&pyb_freq_obj) },
+ { MP_ROM_QSTR(MP_QSTR_repl_info), MP_ROM_PTR(&pyb_set_repl_info_obj) },
+
+ { MP_ROM_QSTR(MP_QSTR_wfi), MP_ROM_PTR(&pyb_wfi_obj) },
+ { MP_ROM_QSTR(MP_QSTR_disable_irq), MP_ROM_PTR(&pyb_disable_irq_obj) },
+ { MP_ROM_QSTR(MP_QSTR_enable_irq), MP_ROM_PTR(&pyb_enable_irq_obj) },
+
+ { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&pyb_stop_obj) },
+ { MP_ROM_QSTR(MP_QSTR_standby), MP_ROM_PTR(&pyb_standby_obj) },
+ { MP_ROM_QSTR(MP_QSTR_source_dir), MP_ROM_PTR(&pyb_source_dir_obj) },
+ { MP_ROM_QSTR(MP_QSTR_main), MP_ROM_PTR(&pyb_main_obj) },
+ { MP_ROM_QSTR(MP_QSTR_usb_mode), MP_ROM_PTR(&pyb_usb_mode_obj) },
+
+ { MP_ROM_QSTR(MP_QSTR_have_cdc), MP_ROM_PTR(&pyb_have_cdc_obj) },
+ { MP_ROM_QSTR(MP_QSTR_hid), MP_ROM_PTR(&pyb_hid_send_report_obj) },
+
+ { MP_ROM_QSTR(MP_QSTR_millis), MP_ROM_PTR(&pyb_millis_obj) },
+ { MP_ROM_QSTR(MP_QSTR_elapsed_millis), MP_ROM_PTR(&pyb_elapsed_millis_obj) },
+ { MP_ROM_QSTR(MP_QSTR_micros), MP_ROM_PTR(&pyb_micros_obj) },
+ { MP_ROM_QSTR(MP_QSTR_elapsed_micros), MP_ROM_PTR(&pyb_elapsed_micros_obj) },
+ { MP_ROM_QSTR(MP_QSTR_delay), MP_ROM_PTR(&pyb_delay_obj) },
+ { MP_ROM_QSTR(MP_QSTR_udelay), MP_ROM_PTR(&pyb_udelay_obj) },
+ { MP_ROM_QSTR(MP_QSTR_sync), MP_ROM_PTR(&pyb_sync_obj) },
+
+ { MP_ROM_QSTR(MP_QSTR_Timer), MP_ROM_PTR(&pyb_timer_type) },
+
+//#if MICROPY_HW_ENABLE_RNG
+// { MP_ROM_QSTR(MP_QSTR_rng), MP_ROM_PTR(&pyb_rng_get_obj) },
+//#endif
+
+//#if MICROPY_HW_ENABLE_RTC
+// { MP_ROM_QSTR(MP_QSTR_RTC), MP_ROM_PTR(&pyb_rtc_type) },
+//#endif
+
+ { MP_ROM_QSTR(MP_QSTR_Pin), MP_ROM_PTR(&pin_type) },
+// { MP_ROM_QSTR(MP_QSTR_ExtInt), MP_ROM_PTR(&extint_type) },
+
+#if MICROPY_HW_ENABLE_SERVO
+ { MP_ROM_QSTR(MP_QSTR_pwm), MP_ROM_PTR(&pyb_pwm_set_obj) },
+ { MP_ROM_QSTR(MP_QSTR_servo), MP_ROM_PTR(&pyb_servo_set_obj) },
+ { MP_ROM_QSTR(MP_QSTR_Servo), MP_ROM_PTR(&pyb_servo_type) },
+#endif
+
+#if MICROPY_HW_HAS_SWITCH
+ { MP_ROM_QSTR(MP_QSTR_Switch), MP_ROM_PTR(&pyb_switch_type) },
+#endif
+
+//#if MICROPY_HW_HAS_SDCARD
+// { MP_ROM_QSTR(MP_QSTR_SD), MP_ROM_PTR(&pyb_sdcard_obj) },
+//#endif
+
+ { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pyb_led_type) },
+// { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&pyb_i2c_type) },
+// { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&pyb_spi_type) },
+ { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&pyb_uart_type) },
+
+// { MP_ROM_QSTR(MP_QSTR_ADC), MP_ROM_PTR(&pyb_adc_type) },
+// { MP_ROM_QSTR(MP_QSTR_ADCAll), MP_ROM_PTR(&pyb_adc_all_type) },
+
+//#if MICROPY_HW_ENABLE_DAC
+// { MP_ROM_QSTR(MP_QSTR_DAC), MP_ROM_PTR(&pyb_dac_type) },
+//#endif
+
+//#if MICROPY_HW_HAS_MMA7660
+// { MP_ROM_QSTR(MP_QSTR_Accel), MP_ROM_PTR(&pyb_accel_type) },
+//#endif
+};
+
+STATIC MP_DEFINE_CONST_DICT(pyb_module_globals, pyb_module_globals_table);
+
+const mp_obj_module_t pyb_module = {
+ .base = { &mp_type_module },
+ .globals = (mp_obj_dict_t*)&pyb_module_globals,
+};
diff --git a/ports/teensy/mpconfigport.h b/ports/teensy/mpconfigport.h
new file mode 100644
index 000000000..b45b5ad4e
--- /dev/null
+++ b/ports/teensy/mpconfigport.h
@@ -0,0 +1,139 @@
+#include <stdint.h>
+
+// options to control how MicroPython is built
+
+#define MICROPY_ALLOC_PATH_MAX (128)
+#define MICROPY_EMIT_THUMB (1)
+#define MICROPY_EMIT_INLINE_THUMB (1)
+#define MICROPY_ENABLE_GC (1)
+#define MICROPY_ENABLE_FINALISER (1)
+#define MICROPY_STACK_CHECK (1)
+#define MICROPY_HELPER_REPL (1)
+#define MICROPY_ENABLE_SOURCE_LINE (1)
+#define MICROPY_LONGINT_IMPL (MICROPY_LONGINT_IMPL_MPZ)
+#define MICROPY_FLOAT_IMPL (MICROPY_FLOAT_IMPL_FLOAT)
+#define MICROPY_OPT_COMPUTED_GOTO (1)
+
+#define MICROPY_PY_BUILTINS_INPUT (1)
+#define MICROPY_PY_BUILTINS_HELP (1)
+#define MICROPY_PY_BUILTINS_HELP_TEXT teensy_help_text
+
+#define MICROPY_PY_IO (0)
+#define MICROPY_PY_FROZENSET (1)
+#define MICROPY_PY_SYS_EXIT (1)
+#define MICROPY_PY_SYS_STDFILES (1)
+#define MICROPY_PY_CMATH (1)
+
+#define MICROPY_TIMER_REG (0)
+#define MICROPY_REG (MICROPY_TIMER_REG)
+
+#define MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF (1)
+#define MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE (0)
+
+// extra built in names to add to the global namespace
+#define MICROPY_PORT_BUILTINS \
+
+// extra built in modules to add to the list of known ones
+extern const struct _mp_obj_module_t os_module;
+extern const struct _mp_obj_module_t pyb_module;
+extern const struct _mp_obj_module_t time_module;
+#define MICROPY_PORT_BUILTIN_MODULES \
+ { MP_ROM_QSTR(MP_QSTR_pyb), MP_ROM_PTR(&pyb_module) }, \
+
+// extra constants
+#define MICROPY_PORT_CONSTANTS \
+ { MP_ROM_QSTR(MP_QSTR_pyb), MP_ROM_PTR(&pyb_module) }, \
+
+#define MP_STATE_PORT MP_STATE_VM
+
+#define MICROPY_PORT_ROOT_POINTERS \
+ const char *readline_hist[8]; \
+ mp_obj_t pin_class_mapper; \
+ mp_obj_t pin_class_map_dict; \
+ struct _pyb_uart_obj_t *pyb_stdio_uart; \
+
+// type definitions for the specific machine
+
+#define UINT_FMT "%u"
+#define INT_FMT "%d"
+
+typedef int32_t mp_int_t; // must be pointer size
+typedef unsigned int mp_uint_t; // must be pointer size
+typedef long mp_off_t;
+
+#define MP_PLAT_PRINT_STRN(str, len) mp_hal_stdout_tx_strn_cooked(str, len)
+
+// We have inlined IRQ functions for efficiency (they are generally
+// 1 machine instruction).
+//
+// Note on IRQ state: you should not need to know the specific
+// value of the state variable, but rather just pass the return
+// value from disable_irq back to enable_irq. If you really need
+// to know the machine-specific values, see irq.h.
+
+#ifndef __disable_irq
+#define __disable_irq() __asm__ volatile("CPSID i");
+#endif
+
+__attribute__(( always_inline )) static inline uint32_t __get_PRIMASK(void) {
+ uint32_t result;
+ __asm volatile ("MRS %0, primask" : "=r" (result));
+ return(result);
+}
+
+__attribute__(( always_inline )) static inline void __set_PRIMASK(uint32_t priMask) {
+ __asm volatile ("MSR primask, %0" : : "r" (priMask) : "memory");
+}
+
+__attribute__(( always_inline )) static inline void enable_irq(mp_uint_t state) {
+ __set_PRIMASK(state);
+}
+
+__attribute__(( always_inline )) static inline mp_uint_t disable_irq(void) {
+ mp_uint_t state = __get_PRIMASK();
+ __disable_irq();
+ return state;
+}
+
+#define MICROPY_BEGIN_ATOMIC_SECTION() disable_irq()
+#define MICROPY_END_ATOMIC_SECTION(state) enable_irq(state)
+
+// We need to provide a declaration/definition of alloca()
+#include <alloca.h>
+
+// The following would be from a board specific file, if one existed
+
+#define MICROPY_HW_BOARD_NAME "Teensy-3.1"
+#define MICROPY_HW_MCU_NAME "MK20DX256"
+
+#define MICROPY_HW_HAS_SWITCH (0)
+#define MICROPY_HW_HAS_SDCARD (0)
+#define MICROPY_HW_HAS_MMA7660 (0)
+#define MICROPY_HW_HAS_LIS3DSH (0)
+#define MICROPY_HW_HAS_LCD (0)
+#define MICROPY_HW_ENABLE_RNG (0)
+#define MICROPY_HW_ENABLE_RTC (0)
+#define MICROPY_HW_ENABLE_TIMER (0)
+#define MICROPY_HW_ENABLE_SERVO (0)
+#define MICROPY_HW_ENABLE_DAC (0)
+#define MICROPY_HW_ENABLE_I2C1 (0)
+#define MICROPY_HW_ENABLE_SPI1 (0)
+#define MICROPY_HW_ENABLE_SPI3 (0)
+#define MICROPY_HW_ENABLE_CC3K (0)
+
+#define MICROPY_HW_LED1 (pin_C5)
+#define MICROPY_HW_LED_OTYPE (GPIO_MODE_OUTPUT_PP)
+#define MICROPY_HW_LED_ON(pin) (pin->gpio->PSOR = pin->pin_mask)
+#define MICROPY_HW_LED_OFF(pin) (pin->gpio->PCOR = pin->pin_mask)
+
+#if 0
+// SD card detect switch
+#define MICROPY_HW_SDCARD_DETECT_PIN (pin_A8)
+#define MICROPY_HW_SDCARD_DETECT_PULL (GPIO_PULLUP)
+#define MICROPY_HW_SDCARD_DETECT_PRESENT (GPIO_PIN_RESET)
+#endif
+
+#define MICROPY_MATH_SQRT_ASM (1)
+
+#define MICROPY_MPHALPORT_H "teensy_hal.h"
+#define MICROPY_PIN_DEFS_PORT_H "pin_defs_teensy.h"
diff --git a/ports/teensy/pin_defs_teensy.c b/ports/teensy/pin_defs_teensy.c
new file mode 100644
index 000000000..e7af1e969
--- /dev/null
+++ b/ports/teensy/pin_defs_teensy.c
@@ -0,0 +1,71 @@
+#include <stdint.h>
+#include <mk20dx128.h>
+#include "py/runtime.h"
+#include "py/mphal.h"
+#include "pin.h"
+
+// Returns the pin mode. This value returned by this macro should be one of:
+// GPIO_MODE_INPUT, GPIO_MODE_OUTPUT_PP, GPIO_MODE_OUTPUT_OD,
+// GPIO_MODE_AF_PP, GPIO_MODE_AF_OD, or GPIO_MODE_ANALOG.
+
+uint32_t pin_get_mode(const pin_obj_t *pin) {
+ if (pin->gpio == NULL) {
+ // Analog only pin
+ return GPIO_MODE_ANALOG;
+ }
+ volatile uint32_t *port_pcr = GPIO_PIN_TO_PORT_PCR(pin->gpio, pin->pin);
+ uint32_t pcr = *port_pcr;
+ uint32_t af = (pcr & PORT_PCR_MUX_MASK) >> 8;
+ if (af == 0) {
+ return GPIO_MODE_ANALOG;
+ }
+ if (af == 1) {
+ if (pin->gpio->PDDR & (1 << pin->pin)) {
+ if (pcr & PORT_PCR_ODE) {
+ return GPIO_MODE_OUTPUT_OD;
+ }
+ return GPIO_MODE_OUTPUT_PP;
+ }
+ return GPIO_MODE_INPUT;
+ }
+
+ if (pcr & PORT_PCR_ODE) {
+ return GPIO_MODE_AF_OD;
+ }
+ return GPIO_MODE_AF_PP;
+}
+
+// Returns the pin pullup/pulldown. The value returned by this macro should
+// be one of GPIO_NOPULL, GPIO_PULLUP, or GPIO_PULLDOWN.
+
+uint32_t pin_get_pull(const pin_obj_t *pin) {
+ if (pin->gpio == NULL) {
+ // Analog only pin
+ return GPIO_NOPULL;
+ }
+ volatile uint32_t *port_pcr = GPIO_PIN_TO_PORT_PCR(pin->gpio, pin->pin);
+
+ uint32_t pcr = *port_pcr;
+ uint32_t af = (pcr & PORT_PCR_MUX_MASK) >> 8;
+
+ // pull is only valid for digital modes (hence the af > 0 test)
+
+ if (af > 0 && (pcr & PORT_PCR_PE) != 0) {
+ if (pcr & PORT_PCR_PS) {
+ return GPIO_PULLUP;
+ }
+ return GPIO_PULLDOWN;
+ }
+ return GPIO_NOPULL;
+}
+
+// Returns the af (alternate function) index currently set for a pin.
+
+uint32_t pin_get_af(const pin_obj_t *pin) {
+ if (pin->gpio == NULL) {
+ // Analog only pin
+ return 0;
+ }
+ volatile uint32_t *port_pcr = GPIO_PIN_TO_PORT_PCR(pin->gpio, pin->pin);
+ return (*port_pcr & PORT_PCR_MUX_MASK) >> 8;
+}
diff --git a/ports/teensy/pin_defs_teensy.h b/ports/teensy/pin_defs_teensy.h
new file mode 100644
index 000000000..54a6055f1
--- /dev/null
+++ b/ports/teensy/pin_defs_teensy.h
@@ -0,0 +1,49 @@
+enum {
+ PORT_A,
+ PORT_B,
+ PORT_C,
+ PORT_D,
+ PORT_E,
+ PORT_Z,
+};
+
+enum {
+ AF_FN_FTM,
+ AF_FN_I2C,
+ AF_FN_UART,
+ AF_FN_SPI
+};
+
+enum {
+ AF_PIN_TYPE_FTM_CH0 = 0,
+ AF_PIN_TYPE_FTM_CH1,
+ AF_PIN_TYPE_FTM_CH2,
+ AF_PIN_TYPE_FTM_CH3,
+ AF_PIN_TYPE_FTM_CH4,
+ AF_PIN_TYPE_FTM_CH5,
+ AF_PIN_TYPE_FTM_CH6,
+ AF_PIN_TYPE_FTM_CH7,
+ AF_PIN_TYPE_FTM_QD_PHA,
+ AF_PIN_TYPE_FTM_QD_PHB,
+
+ AF_PIN_TYPE_I2C_SDA = 0,
+ AF_PIN_TYPE_I2C_SCL,
+
+ AF_PIN_TYPE_SPI_MOSI = 0,
+ AF_PIN_TYPE_SPI_MISO,
+ AF_PIN_TYPE_SPI_SCK,
+ AF_PIN_TYPE_SPI_NSS,
+
+ AF_PIN_TYPE_UART_TX = 0,
+ AF_PIN_TYPE_UART_RX,
+ AF_PIN_TYPE_UART_CTS,
+ AF_PIN_TYPE_UART_RTS,
+};
+
+#define PIN_DEFS_PORT_AF_UNION \
+ FTM_TypeDef *FTM; \
+ I2C_TypeDef *I2C; \
+ UART_TypeDef *UART; \
+ SPI_TypeDef *SPI;
+
+typedef GPIO_TypeDef pin_gpio_t;
diff --git a/ports/teensy/qstrdefsport.h b/ports/teensy/qstrdefsport.h
new file mode 100644
index 000000000..3ba897069
--- /dev/null
+++ b/ports/teensy/qstrdefsport.h
@@ -0,0 +1 @@
+// qstrs specific to this port
diff --git a/ports/teensy/reg.c b/ports/teensy/reg.c
new file mode 100644
index 000000000..cbc427d87
--- /dev/null
+++ b/ports/teensy/reg.c
@@ -0,0 +1,47 @@
+#include <stdio.h>
+#include <string.h>
+#include "py/runtime.h"
+#include "reg.h"
+
+#if MICROPY_REG
+
+mp_obj_t reg_cmd(void *base, reg_t *reg, mp_uint_t num_regs, uint n_args, const mp_obj_t *args) {
+ if (n_args == 0) {
+ // dump all regs
+
+ for (mp_uint_t reg_idx = 0; reg_idx < num_regs; reg_idx++, reg++) {
+ printf(" %-8s @0x%08x = 0x%08lx\n",
+ reg->name, (mp_uint_t)base + reg->offset, *(uint32_t *)((uint8_t *)base + reg->offset));
+ }
+ return mp_const_none;
+ }
+
+ mp_uint_t addr = 0;
+
+ if (MP_OBJ_IS_STR(args[0])) {
+ const char *name = mp_obj_str_get_str(args[0]);
+ mp_uint_t reg_idx;
+ for (reg_idx = 0; reg_idx < num_regs; reg_idx++, reg++) {
+ if (strcmp(name, reg->name) == 0) {
+ break;
+ }
+ }
+ if (reg_idx >= num_regs) {
+ printf("Unknown register: '%s'\n", name);
+ return mp_const_none;
+ }
+ addr = (mp_uint_t)base + reg->offset;
+ } else {
+ addr = (mp_uint_t)base + mp_obj_get_int(args[0]);
+ }
+
+ if (n_args < 2) {
+ // get
+ printf("0x%08lx\n", *(uint32_t *)addr);
+ } else {
+ *(uint32_t *)addr = mp_obj_get_int(args[1]);
+ }
+ return mp_const_none;
+}
+
+#endif
diff --git a/ports/teensy/reg.h b/ports/teensy/reg.h
new file mode 100644
index 000000000..0da6378ee
--- /dev/null
+++ b/ports/teensy/reg.h
@@ -0,0 +1,13 @@
+#ifndef MICROPY_INCLUDED_TEENSY_REG_H
+#define MICROPY_INCLUDED_TEENSY_REG_H
+
+typedef struct {
+ const char *name;
+ mp_uint_t offset;
+} reg_t;
+
+#define REG_ENTRY(st, name) { #name, offsetof(st, name) }
+
+mp_obj_t reg_cmd(void *base, reg_t *reg, mp_uint_t num_reg, uint n_args, const mp_obj_t *args);
+
+#endif // MICROPY_INCLUDED_TEENSY_REG_H
diff --git a/ports/teensy/servo.c b/ports/teensy/servo.c
new file mode 100644
index 000000000..262daaeb6
--- /dev/null
+++ b/ports/teensy/servo.c
@@ -0,0 +1,265 @@
+#include <stdio.h>
+#include "misc.h"
+#include "mpconfig.h"
+#include "qstr.h"
+#include "nlr.h"
+#include "obj.h"
+#include "servo.h"
+
+#include "Arduino.h"
+
+#define MAX_SERVOS 12
+#define INVALID_SERVO -1
+
+#define MIN_PULSE_WIDTH 544 // the shortest pulse sent to a servo
+#define MAX_PULSE_WIDTH 2400 // the longest pulse sent to a servo
+#define DEFAULT_PULSE_WIDTH 1500 // default pulse width when servo is attached
+#define REFRESH_INTERVAL 20000 // minumim time to refresh servos in microseconds
+
+#define PDB_CONFIG (PDB_SC_TRGSEL(15) | PDB_SC_PDBEN | PDB_SC_PDBIE \
+ | PDB_SC_CONT | PDB_SC_PRESCALER(2) | PDB_SC_MULT(0))
+#define PDB_PRESCALE 4
+#define usToTicks(us) ((us) * (F_BUS / 1000) / PDB_PRESCALE / 1000)
+#define ticksToUs(ticks) ((ticks) * PDB_PRESCALE * 1000 / (F_BUS / 1000))
+
+static uint16_t servo_active_mask = 0;
+static uint16_t servo_allocated_mask = 0;
+static uint8_t servo_pin[MAX_SERVOS];
+static uint16_t servo_ticks[MAX_SERVOS];
+
+typedef struct _pyb_servo_obj_t {
+ mp_obj_base_t base;
+ uint servo_id;
+ uint min_usecs;
+ uint max_usecs;
+} pyb_servo_obj_t;
+
+#define clamp(v, min_val, max_val) ((v) < (min_val) ? (min_val) : (v) > (max_val) ? (max_val) : (v))
+
+static float map_uint_to_float(uint x, uint in_min, uint in_max, float out_min, float out_max)
+{
+ return (float)(x - in_min) * (out_max - out_min) / (float)(in_max - in_min) + (float)out_min;
+}
+
+static uint map_float_to_uint(float x, float in_min, float in_max, uint out_min, uint out_max)
+{
+ return (int)((x - in_min) * (float)(out_max - out_min) / (in_max - in_min) + (float)out_min);
+}
+
+static mp_obj_t servo_obj_attach(mp_obj_t self_in, mp_obj_t pin_obj) {
+ pyb_servo_obj_t *self = self_in;
+ uint pin = mp_obj_get_int(pin_obj);
+ if (pin > CORE_NUM_DIGITAL) {
+ goto pin_error;
+ }
+
+ pinMode(pin, OUTPUT);
+ servo_pin[self->servo_id] = pin;
+ servo_active_mask |= (1 << self->servo_id);
+ if (!(SIM_SCGC6 & SIM_SCGC6_PDB)) {
+ SIM_SCGC6 |= SIM_SCGC6_PDB; // TODO: use bitband for atomic bitset
+ PDB0_MOD = 0xFFFF;
+ PDB0_CNT = 0;
+ PDB0_IDLY = 0;
+ PDB0_SC = PDB_CONFIG;
+ // TODO: maybe this should be a higher priority than most
+ // other interrupts (init all to some default?)
+ PDB0_SC = PDB_CONFIG | PDB_SC_SWTRIG;
+ }
+ NVIC_ENABLE_IRQ(IRQ_PDB);
+ return mp_const_none;
+
+pin_error:
+ nlr_raise(mp_obj_new_exception_msg_varg(MP_QSTR_ValueError, "pin %d does not exist", pin));
+}
+
+static mp_obj_t servo_obj_detach(mp_obj_t self_in) {
+ //pyb_servo_obj_t *self = self_in;
+ return mp_const_none;
+}
+
+static mp_obj_t servo_obj_pin(mp_obj_t self_in) {
+ pyb_servo_obj_t *self = self_in;
+ return MP_OBJ_NEW_SMALL_INT(servo_pin[self->servo_id]);
+}
+
+static mp_obj_t servo_obj_min_usecs(int n_args, const mp_obj_t *args) {
+ pyb_servo_obj_t *self = args[0];
+ if (n_args == 1) {
+ // get min
+ return MP_OBJ_NEW_SMALL_INT(self->min_usecs);
+ }
+ // Set min
+ self->min_usecs = mp_obj_get_int(args[1]);
+ return mp_const_none;
+}
+
+static mp_obj_t servo_obj_max_usecs(int n_args, const mp_obj_t *args) {
+ pyb_servo_obj_t *self = args[0];
+ if (n_args == 1) {
+ // get max
+ return MP_OBJ_NEW_SMALL_INT(self->max_usecs);
+ }
+ // Set max
+ self->max_usecs = mp_obj_get_int(args[1]);
+ return mp_const_none;
+}
+
+static mp_obj_t servo_obj_angle(int n_args, const mp_obj_t *args) {
+ pyb_servo_obj_t *self = args[0];
+ if (n_args == 1) {
+ // get
+ float angle = map_uint_to_float(servo_ticks[self->servo_id],
+ usToTicks(self->min_usecs),
+ usToTicks(self->max_usecs),
+ 0.0, 180.0);
+ return mp_obj_new_float(angle);
+ }
+ // Set
+ float angle = mp_obj_get_float(args[1]);
+ if (angle < 0.0F) {
+ angle = 0.0F;
+ }
+ if (angle > 180.0F) {
+ angle = 180.0F;
+ }
+ servo_ticks[self->servo_id] = map_float_to_uint(angle,
+ 0.0F, 180.0F,
+ usToTicks(self->min_usecs),
+ usToTicks(self->max_usecs));
+ return mp_const_none;
+}
+
+static mp_obj_t servo_obj_usecs(int n_args, const mp_obj_t *args) {
+ pyb_servo_obj_t *self = args[0];
+ uint usecs;
+ if (n_args == 1) {
+ // get
+ return MP_OBJ_NEW_SMALL_INT(ticksToUs(servo_ticks[self->servo_id]));
+ }
+ // Set
+ usecs = mp_obj_get_int(args[1]);
+
+ if (self->min_usecs < self->max_usecs) {
+ usecs = clamp(usecs, self->min_usecs, self->max_usecs);
+ } else {
+ usecs = clamp(usecs, self->max_usecs, self->min_usecs);
+ }
+ servo_ticks[self->servo_id] = usToTicks(usecs);
+ return mp_const_none;
+}
+
+static mp_obj_t servo_obj_attached(mp_obj_t self_in) {
+ pyb_servo_obj_t *self = self_in;
+ uint attached = (servo_active_mask & (1 << self->servo_id)) != 0;
+ return MP_OBJ_NEW_SMALL_INT(attached);
+}
+
+static void servo_obj_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
+ pyb_servo_obj_t *self = self_in;
+ (void)kind;
+ print(env, "<Servo %lu>", self->servo_id);
+}
+
+static MP_DEFINE_CONST_FUN_OBJ_2(servo_obj_attach_obj, servo_obj_attach);
+static MP_DEFINE_CONST_FUN_OBJ_1(servo_obj_detach_obj, servo_obj_detach);
+static MP_DEFINE_CONST_FUN_OBJ_1(servo_obj_pin_obj, servo_obj_pin);
+static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(servo_obj_min_usecs_obj, 1, 2, servo_obj_min_usecs);
+static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(servo_obj_max_usecs_obj, 1, 2, servo_obj_max_usecs);
+static MP_DEFINE_CONST_FUN_OBJ_1(servo_obj_attached_obj, servo_obj_attached);
+static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(servo_obj_angle_obj, 1, 2, servo_obj_angle);
+static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(servo_obj_usecs_obj, 1, 2, servo_obj_usecs);
+
+static const mp_method_t servo_methods[] = {
+ { "attach", &servo_obj_attach_obj },
+ { "detach", &servo_obj_detach_obj },
+ { "pin", &servo_obj_pin_obj },
+ { "min_usecs", &servo_obj_min_usecs_obj },
+ { "max_usecs", &servo_obj_max_usecs_obj },
+ { "attached", &servo_obj_attached_obj },
+ { "angle", &servo_obj_angle_obj },
+ { "usecs", &servo_obj_usecs_obj },
+ { NULL, NULL },
+};
+
+/*
+ * Notes:
+ *
+ * ISR needs to know pin #, ticks
+ */
+
+static const mp_obj_type_t servo_obj_type = {
+ { &mp_type_type },
+ .name = MP_QSTR_Servo,
+ .print = servo_obj_print,
+ .methods = servo_methods,
+};
+
+/* servo = pyb.Servo(pin, [min_uecs, [max_usecs]]) */
+
+mp_obj_t pyb_Servo(void) {
+ uint16_t mask;
+ pyb_servo_obj_t *self = m_new_obj(pyb_servo_obj_t);
+ self->base.type = &servo_obj_type;
+ self->min_usecs = MIN_PULSE_WIDTH;
+ self->max_usecs = MAX_PULSE_WIDTH;
+
+ /* Find an unallocated servo id */
+
+ self->servo_id = 0;
+ for (mask=1; mask < (1<<MAX_SERVOS); mask <<= 1) {
+ if (!(servo_allocated_mask & mask)) {
+ servo_allocated_mask |= mask;
+ servo_active_mask &= ~mask;
+ servo_ticks[self->servo_id] = usToTicks(DEFAULT_PULSE_WIDTH);
+ return self;
+ }
+ self->servo_id++;
+ }
+ m_del_obj(pyb_servo_obj_t, self);
+ mp_raise_ValueError("No available servo ids");
+ return mp_const_none;
+}
+
+void pdb_isr(void)
+{
+ static int8_t channel = 0, channel_high = MAX_SERVOS;
+ static uint32_t tick_accum = 0;
+ uint32_t ticks;
+ int32_t wait_ticks;
+
+ // first, if any channel was left high from the previous
+ // run, now is the time to shut it off
+ if (servo_active_mask & (1 << channel_high)) {
+ digitalWrite(servo_pin[channel_high], LOW);
+ channel_high = MAX_SERVOS;
+ }
+ // search for the next channel to turn on
+ while (channel < MAX_SERVOS) {
+ if (servo_active_mask & (1 << channel)) {
+ digitalWrite(servo_pin[channel], HIGH);
+ channel_high = channel;
+ ticks = servo_ticks[channel];
+ tick_accum += ticks;
+ PDB0_IDLY += ticks;
+ PDB0_SC = PDB_CONFIG | PDB_SC_LDOK;
+ channel++;
+ return;
+ }
+ channel++;
+ }
+ // when all channels have output, wait for the
+ // minimum refresh interval
+ wait_ticks = usToTicks(REFRESH_INTERVAL) - tick_accum;
+ if (wait_ticks < usToTicks(100)) wait_ticks = usToTicks(100);
+ else if (wait_ticks > 60000) wait_ticks = 60000;
+ tick_accum += wait_ticks;
+ PDB0_IDLY += wait_ticks;
+ PDB0_SC = PDB_CONFIG | PDB_SC_LDOK;
+ // if this wait is enough to satisfy the refresh
+ // interval, next time begin again at channel zero
+ if (tick_accum >= usToTicks(REFRESH_INTERVAL)) {
+ tick_accum = 0;
+ channel = 0;
+ }
+}
diff --git a/ports/teensy/servo.h b/ports/teensy/servo.h
new file mode 100644
index 000000000..1ad34353d
--- /dev/null
+++ b/ports/teensy/servo.h
@@ -0,0 +1,11 @@
+#ifndef MICROPY_INCLUDED_TEENSY_SERVO_H
+#define MICROPY_INCLUDED_TEENSY_SERVO_H
+
+void servo_init(void);
+
+extern const mp_obj_type_t pyb_servo_type;
+
+MP_DECLARE_CONST_FUN_OBJ_2(pyb_servo_set_obj);
+MP_DECLARE_CONST_FUN_OBJ_2(pyb_pwm_set_obj);
+
+#endif // MICROPY_INCLUDED_TEENSY_SERVO_H
diff --git a/ports/teensy/std.h b/ports/teensy/std.h
new file mode 100644
index 000000000..ef55d22dd
--- /dev/null
+++ b/ports/teensy/std.h
@@ -0,0 +1,25 @@
+#ifndef MICROPY_INCLUDED_TEENSY_STD_H
+#define MICROPY_INCLUDED_TEENSY_STD_H
+
+typedef unsigned int size_t;
+
+void __assert_func(void);
+
+void *malloc(size_t n);
+void free(void *ptr);
+void *realloc(void *ptr, size_t n);
+
+void *memcpy(void *dest, const void *src, size_t n);
+void *memmove(void *dest, const void *src, size_t n);
+void *memset(void *s, int c, size_t n);
+
+size_t strlen(const char *str);
+int strcmp(const char *s1, const char *s2);
+int strncmp(const char *s1, const char *s2, size_t n);
+char *strcpy(char *dest, const char *src);
+char *strcat(char *dest, const char *src);
+
+int printf(const char *fmt, ...);
+int snprintf(char *str, size_t size, const char *fmt, ...);
+
+#endif // MICROPY_INCLUDED_TEENSY_STD_H
diff --git a/ports/teensy/teensy_hal.c b/ports/teensy/teensy_hal.c
new file mode 100644
index 000000000..439e3380d
--- /dev/null
+++ b/ports/teensy/teensy_hal.c
@@ -0,0 +1,65 @@
+#include <stdio.h>
+#include <string.h>
+
+#include "py/mpstate.h"
+#include "py/runtime.h"
+#include "py/mphal.h"
+#include "usb.h"
+#include "uart.h"
+#include "Arduino.h"
+
+mp_uint_t mp_hal_ticks_ms(void) {
+ return millis();
+}
+
+void mp_hal_delay_ms(mp_uint_t ms) {
+ delay(ms);
+}
+
+void mp_hal_set_interrupt_char(int c) {
+ // The teensy 3.1 usb stack doesn't currently have the notion of generating
+ // an exception when a certain character is received. That just means that
+ // you can't press Control-C and get your python script to stop.
+}
+
+int mp_hal_stdin_rx_chr(void) {
+ for (;;) {
+ byte c;
+ if (usb_vcp_recv_byte(&c) != 0) {
+ return c;
+ } else if (MP_STATE_PORT(pyb_stdio_uart) != NULL && uart_rx_any(MP_STATE_PORT(pyb_stdio_uart))) {
+ return uart_rx_char(MP_STATE_PORT(pyb_stdio_uart));
+ }
+ __WFI();
+ }
+}
+
+void mp_hal_stdout_tx_str(const char *str) {
+ mp_hal_stdout_tx_strn(str, strlen(str));
+}
+
+void mp_hal_stdout_tx_strn(const char *str, size_t len) {
+ if (MP_STATE_PORT(pyb_stdio_uart) != NULL) {
+ uart_tx_strn(MP_STATE_PORT(pyb_stdio_uart), str, len);
+ }
+ if (usb_vcp_is_enabled()) {
+ usb_vcp_send_strn(str, len);
+ }
+}
+
+void mp_hal_stdout_tx_strn_cooked(const char *str, size_t len) {
+ // send stdout to UART and USB CDC VCP
+ if (MP_STATE_PORT(pyb_stdio_uart) != NULL) {
+ uart_tx_strn_cooked(MP_STATE_PORT(pyb_stdio_uart), str, len);
+ }
+ if (usb_vcp_is_enabled()) {
+ usb_vcp_send_strn_cooked(str, len);
+ }
+}
+
+void mp_hal_gpio_clock_enable(GPIO_TypeDef *gpio) {
+}
+
+void extint_register_pin(const void *pin, uint32_t mode, int hard_irq, mp_obj_t callback_obj) {
+ mp_raise_NotImplementedError(NULL);
+}
diff --git a/ports/teensy/teensy_hal.h b/ports/teensy/teensy_hal.h
new file mode 100644
index 000000000..162effa85
--- /dev/null
+++ b/ports/teensy/teensy_hal.h
@@ -0,0 +1,128 @@
+#include <mk20dx128.h>
+#include "hal_ftm.h"
+
+#ifdef USE_FULL_ASSERT
+ #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__))
+ void assert_failed(uint8_t* file, uint32_t line);
+#else
+ #define assert_param(expr) ((void)0)
+#endif /* USE_FULL_ASSERT */
+
+#define HAL_NVIC_EnableIRQ(irq) NVIC_ENABLE_IRQ(irq)
+
+#define GPIOA ((GPIO_TypeDef *)&GPIOA_PDOR)
+#define GPIOB ((GPIO_TypeDef *)&GPIOB_PDOR)
+#define GPIOC ((GPIO_TypeDef *)&GPIOC_PDOR)
+#define GPIOD ((GPIO_TypeDef *)&GPIOD_PDOR)
+#define GPIOE ((GPIO_TypeDef *)&GPIOE_PDOR)
+#define GPIOZ ((GPIO_TypeDef *)NULL)
+
+#define I2C0 ((I2C_TypeDef *)0x40066000)
+#define I2C1 ((I2C_TypeDef *)0x40067000)
+
+#undef SPI0
+#define SPI0 ((SPI_TypeDef *)0x4002C000)
+#define SPI1 ((SPI_TypeDef *)0x4002D000)
+
+#define UART0 ((UART_TypeDef *)&UART0_BDH)
+#define UART1 ((UART_TypeDef *)&UART1_BDH)
+#define UART2 ((UART_TypeDef *)&UART2_BDH)
+
+typedef struct {
+ uint32_t dummy;
+} I2C_TypeDef;
+
+typedef struct {
+ uint32_t dummy;
+} UART_TypeDef;
+
+typedef struct {
+ uint32_t dummy;
+} SPI_TypeDef;
+
+typedef struct {
+ volatile uint32_t PDOR; // Output register
+ volatile uint32_t PSOR; // Set output register
+ volatile uint32_t PCOR; // Clear output register
+ volatile uint32_t PTOR; // Toggle output register
+ volatile uint32_t PDIR; // Data Input register
+ volatile uint32_t PDDR; // Data Direction register
+} GPIO_TypeDef;
+
+#define GPIO_OUTPUT_TYPE ((uint32_t)0x00000010) // Indicates OD
+
+#define GPIO_MODE_INPUT ((uint32_t)0x00000000)
+#define GPIO_MODE_OUTPUT_PP ((uint32_t)0x00000001)
+#define GPIO_MODE_OUTPUT_OD ((uint32_t)0x00000011)
+#define GPIO_MODE_AF_PP ((uint32_t)0x00000002)
+#define GPIO_MODE_AF_OD ((uint32_t)0x00000012)
+#define GPIO_MODE_ANALOG ((uint32_t)0x00000003)
+#define GPIO_MODE_IT_RISING ((uint32_t)1)
+#define GPIO_MODE_IT_FALLING ((uint32_t)2)
+
+#define IS_GPIO_MODE(MODE) (((MODE) == GPIO_MODE_INPUT) ||\
+ ((MODE) == GPIO_MODE_OUTPUT_PP) ||\
+ ((MODE) == GPIO_MODE_OUTPUT_OD) ||\
+ ((MODE) == GPIO_MODE_AF_PP) ||\
+ ((MODE) == GPIO_MODE_AF_OD) ||\
+ ((MODE) == GPIO_MODE_ANALOG))
+
+#define GPIO_NOPULL ((uint32_t)0)
+#define GPIO_PULLUP ((uint32_t)1)
+#define GPIO_PULLDOWN ((uint32_t)2)
+
+#define IS_GPIO_PULL(PULL) (((PULL) == GPIO_NOPULL) || ((PULL) == GPIO_PULLUP) || \
+ ((PULL) == GPIO_PULLDOWN))
+
+#define GPIO_SPEED_LOW ((uint32_t)0)
+#define GPIO_SPEED_MEDIUM ((uint32_t)1)
+#define GPIO_SPEED_FAST ((uint32_t)2)
+#define GPIO_SPEED_HIGH ((uint32_t)3)
+
+#define IS_GPIO_AF(af) ((af) >= 0 && (af) <= 7)
+
+typedef struct {
+ uint32_t Pin;
+ uint32_t Mode;
+ uint32_t Pull;
+ uint32_t Speed;
+ uint32_t Alternate;
+} GPIO_InitTypeDef;
+
+#define GPIO_PORT_TO_PORT_NUM(GPIOx) \
+ ((&GPIOx->PDOR - &GPIOA_PDOR) / (&GPIOB_PDOR - &GPIOA_PDOR))
+
+#define GPIO_PIN_TO_PORT_PCR(GPIOx, pin) \
+ (&PORTA_PCR0 + (GPIO_PORT_TO_PORT_NUM(GPIOx) * 0x400) + (pin))
+
+#define GPIO_AF2_I2C0 2
+#define GPIO_AF2_I2C1 2
+#define GPIO_AF2_SPI0 2
+#define GPIO_AF3_FTM0 3
+#define GPIO_AF3_FTM1 3
+#define GPIO_AF3_FTM2 3
+#define GPIO_AF3_UART0 3
+#define GPIO_AF3_UART1 3
+#define GPIO_AF3_UART2 3
+#define GPIO_AF4_FTM0 4
+#define GPIO_AF6_FTM1 6
+#define GPIO_AF6_FTM2 6
+#define GPIO_AF6_I2C1 6
+#define GPIO_AF7_FTM1 7
+
+__attribute__(( always_inline )) static inline void __WFI(void) {
+ __asm volatile ("wfi");
+}
+
+void mp_hal_set_interrupt_char(int c);
+
+void mp_hal_gpio_clock_enable(GPIO_TypeDef *gpio);
+
+void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *init);
+
+struct _pin_obj_t;
+#define mp_hal_pin_obj_t const struct _pin_obj_t*
+#define mp_hal_pin_high(p) (((p)->gpio->PSOR) = (p)->pin_mask)
+#define mp_hal_pin_low(p) (((p)->gpio->PCOR) = (p)->pin_mask)
+#define mp_hal_pin_read(p) (((p)->gpio->PDIR >> (p)->pin) & 1)
+#define mp_hal_pin_write(p, v) do { if (v) { mp_hal_pin_high(p); } else { mp_hal_pin_low(p); } } while (0)
diff --git a/ports/teensy/teensy_pins.csv b/ports/teensy/teensy_pins.csv
new file mode 100644
index 000000000..10887e212
--- /dev/null
+++ b/ports/teensy/teensy_pins.csv
@@ -0,0 +1,56 @@
+D0,PTB16
+D1,PTB17
+D2,PTD0
+D3,PTA12
+D4,PTA13
+D5,PTD7
+D6,PTD4
+D7,PTD2
+D8,PTD3
+D9,PTC3
+D10,PTC4
+D11,PTC6
+D12,PTC7
+D13,PTC5
+D14,PTD1
+D15,PTC0
+D16,PTB0
+D17,PTB1
+D18,PTB3
+D19,PTB2
+D20,PTD5
+D21,PTD6
+D22,PTC1
+D23,PTC2
+D24,PTA5
+D25,PTB19
+D26,PTE1
+D27,PTC9
+D28,PTC8
+D29,PTC10
+D30,PTC11
+D31,PTE0
+D32,PTB18
+D33,PTA4
+A0,PTD1
+A1,PTC0
+A2,PTB0
+A3,PTB1
+A4,PTB3
+A5,PTB2
+A6,PTD5
+A7,PTD6
+A8,PTC1
+A9,PTC2
+A10,PTZ0
+A11,PTZ1
+A12,PTZ2
+A13,PTZ3
+A14,PTZ5
+A15,PTE1
+A16,PTC9
+A17,PTC8
+A18,PTC10
+A19,PTC11
+A20,PTE0
+LED,PTC5
diff --git a/ports/teensy/timer.c b/ports/teensy/timer.c
new file mode 100644
index 000000000..cdc7a3c54
--- /dev/null
+++ b/ports/teensy/timer.c
@@ -0,0 +1,992 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2013, 2014 Damien P. George
+ *
+ * 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 <stdio.h>
+#include <stdint.h>
+#include <string.h>
+#include <stddef.h>
+
+#include "py/nlr.h"
+#include "py/runtime.h"
+#include "py/gc.h"
+#include "py/mphal.h"
+#include "pin.h"
+#include "reg.h"
+#include "timer.h"
+
+typedef enum {
+ CHANNEL_MODE_PWM_NORMAL,
+ CHANNEL_MODE_PWM_INVERTED,
+ CHANNEL_MODE_OC_TIMING,
+ CHANNEL_MODE_OC_ACTIVE,
+ CHANNEL_MODE_OC_INACTIVE,
+ CHANNEL_MODE_OC_TOGGLE,
+// CHANNEL_MODE_OC_FORCED_ACTIVE,
+// CHANNEL_MODE_OC_FORCED_INACTIVE,
+ CHANNEL_MODE_IC,
+} pyb_channel_mode;
+
+STATIC const struct {
+ qstr name;
+ uint32_t oc_mode;
+} channel_mode_info[] = {
+ { MP_QSTR_PWM, FTM_OCMODE_PWM1 },
+ { MP_QSTR_PWM_INVERTED, FTM_OCMODE_PWM2 },
+ { MP_QSTR_OC_TIMING, FTM_OCMODE_TIMING },
+ { MP_QSTR_OC_ACTIVE, FTM_OCMODE_ACTIVE },
+ { MP_QSTR_OC_INACTIVE, FTM_OCMODE_INACTIVE },
+ { MP_QSTR_OC_TOGGLE, FTM_OCMODE_TOGGLE },
+// { MP_QSTR_OC_FORCED_ACTIVE, FTM_OCMODE_FORCED_ACTIVE },
+// { MP_QSTR_OC_FORCED_INACTIVE, FTM_OCMODE_FORCED_INACTIVE },
+ { MP_QSTR_IC, 0 },
+};
+
+struct _pyb_timer_obj_t;
+
+typedef struct _pyb_timer_channel_obj_t {
+ mp_obj_base_t base;
+ struct _pyb_timer_obj_t *timer;
+ uint8_t channel;
+ uint8_t mode;
+ mp_obj_t callback;
+ struct _pyb_timer_channel_obj_t *next;
+} pyb_timer_channel_obj_t;
+
+typedef struct _pyb_timer_obj_t {
+ mp_obj_base_t base;
+ uint8_t tim_id;
+ uint8_t irqn;
+ mp_obj_t callback;
+ FTM_HandleTypeDef ftm;
+ pyb_timer_channel_obj_t *channel;
+} pyb_timer_obj_t;
+
+// Used to do callbacks to Python code on interrupt
+STATIC pyb_timer_obj_t *pyb_timer_obj_all[3];
+#define PYB_TIMER_OBJ_ALL_NUM MP_ARRAY_SIZE(pyb_timer_obj_all)
+
+STATIC mp_obj_t pyb_timer_deinit(mp_obj_t self_in);
+STATIC mp_obj_t pyb_timer_callback(mp_obj_t self_in, mp_obj_t callback);
+STATIC mp_obj_t pyb_timer_channel_callback(mp_obj_t self_in, mp_obj_t callback);
+
+void timer_init0(void) {
+ for (uint i = 0; i < PYB_TIMER_OBJ_ALL_NUM; i++) {
+ pyb_timer_obj_all[i] = NULL;
+ }
+}
+
+// unregister all interrupt sources
+void timer_deinit(void) {
+ for (uint i = 0; i < PYB_TIMER_OBJ_ALL_NUM; i++) {
+ pyb_timer_obj_t *tim = pyb_timer_obj_all[i];
+ if (tim != NULL) {
+ pyb_timer_deinit(tim);
+ }
+ }
+}
+
+mp_uint_t get_prescaler_shift(mp_int_t prescaler) {
+ mp_uint_t prescaler_shift;
+ for (prescaler_shift = 0; prescaler_shift < 8; prescaler_shift++) {
+ if (prescaler == (1 << prescaler_shift)) {
+ return prescaler_shift;
+ }
+ }
+ nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "prescaler must be a power of 2 between 1 and 128, not %d", prescaler));
+}
+
+/******************************************************************************/
+/* MicroPython bindings */
+
+STATIC const mp_obj_type_t pyb_timer_channel_type;
+
+// Helper function for determining the period used for calculating percent
+STATIC uint32_t compute_period(pyb_timer_obj_t *self) {
+ // In center mode, compare == period corresponds to 100%
+ // In edge mode, compare == (period + 1) corresponds to 100%
+ FTM_TypeDef *FTMx = self->ftm.Instance;
+ uint32_t period = (FTMx->MOD & 0xffff);
+ if ((FTMx->SC & FTM_SC_CPWMS) == 0) {
+ // Edge mode
+ period++;
+ }
+ return period;
+}
+
+// Helper function to compute PWM value from timer period and percent value.
+// 'val' can be an int or a float between 0 and 100 (out of range values are
+// clamped).
+STATIC uint32_t compute_pwm_value_from_percent(uint32_t period, mp_obj_t percent_in) {
+ uint32_t cmp;
+ if (0) {
+ #if MICROPY_PY_BUILTINS_FLOAT
+ } else if (MP_OBJ_IS_TYPE(percent_in, &mp_type_float)) {
+ float percent = mp_obj_get_float(percent_in);
+ if (percent <= 0.0) {
+ cmp = 0;
+ } else if (percent >= 100.0) {
+ cmp = period;
+ } else {
+ cmp = percent / 100.0 * ((float)period);
+ }
+ #endif
+ } else {
+ mp_int_t percent = mp_obj_get_int(percent_in);
+ if (percent <= 0) {
+ cmp = 0;
+ } else if (percent >= 100) {
+ cmp = period;
+ } else {
+ cmp = ((uint32_t)percent * period) / 100;
+ }
+ }
+ return cmp;
+}
+
+// Helper function to compute percentage from timer perion and PWM value.
+STATIC mp_obj_t compute_percent_from_pwm_value(uint32_t period, uint32_t cmp) {
+ #if MICROPY_PY_BUILTINS_FLOAT
+ float percent = (float)cmp * 100.0 / (float)period;
+ if (cmp >= period) {
+ percent = 100.0;
+ } else {
+ percent = (float)cmp * 100.0 / (float)period;
+ }
+ return mp_obj_new_float(percent);
+ #else
+ mp_int_t percent;
+ if (cmp >= period) {
+ percent = 100;
+ } else {
+ percent = cmp * 100 / period;
+ }
+ return mp_obj_new_int(percent);
+ #endif
+}
+
+STATIC void pyb_timer_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
+ pyb_timer_obj_t *self = self_in;
+
+ if (self->ftm.State == HAL_FTM_STATE_RESET) {
+ mp_printf(print, "Timer(%u)", self->tim_id);
+ } else {
+ mp_printf(print, "Timer(%u, prescaler=%u, period=%u, mode=%s)",
+ self->tim_id,
+ 1 << (self->ftm.Instance->SC & 7),
+ self->ftm.Instance->MOD & 0xffff,
+ self->ftm.Init.CounterMode == FTM_COUNTERMODE_UP ? "UP" : "CENTER");
+ }
+}
+
+/// \method init(*, freq, prescaler, period)
+/// Initialise the timer. Initialisation must be either by frequency (in Hz)
+/// or by prescaler and period:
+///
+/// tim.init(freq=100) # set the timer to trigger at 100Hz
+/// tim.init(prescaler=83, period=999) # set the prescaler and period directly
+///
+/// Keyword arguments:
+///
+/// - `freq` - specifies the periodic frequency of the timer. You migh also
+/// view this as the frequency with which the timer goes through
+/// one complete cycle.
+///
+/// - `prescaler` 1, 2, 4, 8 16 32, 64 or 128 - specifies the value to be loaded into the
+/// timer's prescaler. The timer clock source is divided by
+/// (`prescaler`) to arrive at the timer clock.
+///
+/// - `period` [0-0xffff] - Specifies the value to be loaded into the timer's
+/// Modulo Register (MOD). This determines the period of the timer (i.e.
+/// when the counter cycles). The timer counter will roll-over after
+/// `period` timer clock cycles. In center mode, a compare register > 0x7fff
+/// doesn't seem to work properly, so keep this in mind.
+///
+/// - `mode` can be one of:
+/// - `Timer.UP` - configures the timer to count from 0 to MOD (default)
+/// - `Timer.CENTER` - confgures the timer to count from 0 to MOD and
+/// then back down to 0.
+///
+/// - `callback` - as per Timer.callback()
+///
+/// You must either specify freq or both of period and prescaler.
+STATIC const mp_arg_t pyb_timer_init_args[] = {
+ { MP_QSTR_freq, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
+ { MP_QSTR_prescaler, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
+ { MP_QSTR_period, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
+ { MP_QSTR_mode, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = FTM_COUNTERMODE_UP} },
+ { MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
+};
+#define PYB_TIMER_INIT_NUM_ARGS MP_ARRAY_SIZE(pyb_timer_init_args)
+
+STATIC mp_obj_t pyb_timer_init_helper(pyb_timer_obj_t *self, uint n_args, const mp_obj_t *args, mp_map_t *kw_args) {
+ // parse args
+ mp_arg_val_t vals[PYB_TIMER_INIT_NUM_ARGS];
+ mp_arg_parse_all(n_args, args, kw_args, PYB_TIMER_INIT_NUM_ARGS, pyb_timer_init_args, vals);
+
+ FTM_HandleTypeDef *ftm = &self->ftm;
+
+ // set the TIM configuration values
+ FTM_Base_InitTypeDef *init = &ftm->Init;
+
+ if (vals[0].u_int != 0xffffffff) {
+ // set prescaler and period from frequency
+
+ if (vals[0].u_int == 0) {
+ mp_raise_ValueError("can't have 0 frequency");
+ }
+
+ uint32_t period = MAX(1, F_BUS / vals[0].u_int);
+ uint32_t prescaler_shift = 0;
+ while (period > 0xffff && prescaler_shift < 7) {
+ period >>= 1;
+ prescaler_shift++;
+ }
+ if (period > 0xffff) {
+ period = 0xffff;
+ }
+ init->PrescalerShift = prescaler_shift;
+ init->Period = period;
+ } else if (vals[1].u_int != 0xffffffff && vals[2].u_int != 0xffffffff) {
+ // set prescaler and period directly
+ init->PrescalerShift = get_prescaler_shift(vals[1].u_int);
+ init->Period = vals[2].u_int;
+ if (!IS_FTM_PERIOD(init->Period)) {
+ nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "period must be between 0 and 65535, not %d", init->Period));
+ }
+ } else {
+ mp_raise_TypeError("must specify either freq, or prescaler and period");
+ }
+
+ init->CounterMode = vals[3].u_int;
+ if (!IS_FTM_COUNTERMODE(init->CounterMode)) {
+ nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "invalid counter mode: %d", init->CounterMode));
+ }
+
+ // Currently core/mk20dx128.c sets SIM_SCGC6_FTM0, SIM_SCGC6_FTM1, SIM_SCGC3_FTM2
+ // so we don't need to do it here.
+
+ NVIC_SET_PRIORITY(self->irqn, 0xe); // next-to lowest priority
+
+ HAL_FTM_Base_Init(ftm);
+ if (vals[4].u_obj == mp_const_none) {
+ HAL_FTM_Base_Start(ftm);
+ } else {
+ pyb_timer_callback(self, vals[4].u_obj);
+ }
+
+ return mp_const_none;
+}
+
+/// \classmethod \constructor(id, ...)
+/// Construct a new timer object of the given id. If additional
+/// arguments are given, then the timer is initialised by `init(...)`.
+/// `id` can be 1 to 14, excluding 3.
+STATIC mp_obj_t pyb_timer_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
+ // check arguments
+ mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
+
+ // create new Timer object
+ pyb_timer_obj_t *tim = m_new_obj(pyb_timer_obj_t);
+ memset(tim, 0, sizeof(*tim));
+
+ tim->base.type = &pyb_timer_type;
+ tim->callback = mp_const_none;
+ tim->channel = NULL;
+
+ // get FTM number
+ tim->tim_id = mp_obj_get_int(args[0]);
+
+ switch (tim->tim_id) {
+ case 0: tim->ftm.Instance = FTM0; tim->irqn = IRQ_FTM0; break;
+ case 1: tim->ftm.Instance = FTM1; tim->irqn = IRQ_FTM1; break;
+ case 2: tim->ftm.Instance = FTM2; tim->irqn = IRQ_FTM2; break;
+ default: nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Timer %d does not exist", tim->tim_id));
+ }
+
+ if (n_args > 1 || n_kw > 0) {
+ // start the peripheral
+ mp_map_t kw_args;
+ mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
+ pyb_timer_init_helper(tim, n_args - 1, args + 1, &kw_args);
+ }
+
+ // set the global variable for interrupt callbacks
+ if (tim->tim_id < PYB_TIMER_OBJ_ALL_NUM) {
+ pyb_timer_obj_all[tim->tim_id] = tim;
+ }
+
+ return (mp_obj_t)tim;
+}
+
+STATIC mp_obj_t pyb_timer_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
+ return pyb_timer_init_helper(args[0], n_args - 1, args + 1, kw_args);
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_init_obj, 1, pyb_timer_init);
+
+/// \method deinit()
+/// Deinitialises the timer.
+///
+/// Disables the callback (and the associated irq).
+/// Disables any channel callbacks (and the associated irq).
+/// Stops the timer, and disables the timer peripheral.
+STATIC mp_obj_t pyb_timer_deinit(mp_obj_t self_in) {
+ pyb_timer_obj_t *self = self_in;
+
+ // Disable the base interrupt
+ pyb_timer_callback(self_in, mp_const_none);
+
+ pyb_timer_channel_obj_t *chan = self->channel;
+ self->channel = NULL;
+
+ // Disable the channel interrupts
+ while (chan != NULL) {
+ pyb_timer_channel_callback(chan, mp_const_none);
+ pyb_timer_channel_obj_t *prev_chan = chan;
+ chan = chan->next;
+ prev_chan->next = NULL;
+ }
+
+ HAL_FTM_Base_DeInit(&self->ftm);
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_timer_deinit_obj, pyb_timer_deinit);
+
+/// \method channel(channel, mode, ...)
+///
+/// If only a channel number is passed, then a previously initialized channel
+/// object is returned (or `None` if there is no previous channel).
+///
+/// Othwerwise, a TimerChannel object is initialized and returned.
+///
+/// Each channel can be configured to perform pwm, output compare, or
+/// input capture. All channels share the same underlying timer, which means
+/// that they share the same timer clock.
+///
+/// Keyword arguments:
+///
+/// - `mode` can be one of:
+/// - `Timer.PWM` - configure the timer in PWM mode (active high).
+/// - `Timer.PWM_INVERTED` - configure the timer in PWM mode (active low).
+/// - `Timer.OC_TIMING` - indicates that no pin is driven.
+/// - `Timer.OC_ACTIVE` - the pin will be made active when a compare
+/// match occurs (active is determined by polarity)
+/// - `Timer.OC_INACTIVE` - the pin will be made inactive when a compare
+/// match occurs.
+/// - `Timer.OC_TOGGLE` - the pin will be toggled when an compare match occurs.
+/// - `Timer.IC` - configure the timer in Input Capture mode.
+///
+/// - `callback` - as per TimerChannel.callback()
+///
+/// - `pin` None (the default) or a Pin object. If specified (and not None)
+/// this will cause the alternate function of the the indicated pin
+/// to be configured for this timer channel. An error will be raised if
+/// the pin doesn't support any alternate functions for this timer channel.
+///
+/// Keyword arguments for Timer.PWM modes:
+///
+/// - `pulse_width` - determines the initial pulse width value to use.
+/// - `pulse_width_percent` - determines the initial pulse width percentage to use.
+///
+/// Keyword arguments for Timer.OC modes:
+///
+/// - `compare` - determines the initial value of the compare register.
+///
+/// - `polarity` can be one of:
+/// - `Timer.HIGH` - output is active high
+/// - `Timer.LOW` - output is acive low
+///
+/// Optional keyword arguments for Timer.IC modes:
+///
+/// - `polarity` can be one of:
+/// - `Timer.RISING` - captures on rising edge.
+/// - `Timer.FALLING` - captures on falling edge.
+/// - `Timer.BOTH` - captures on both edges.
+///
+/// PWM Example:
+///
+/// timer = pyb.Timer(0, prescaler=128, period=37500, counter_mode=pyb.Timer.COUNTER_MODE_CENTER)
+/// ch0 = t0.channel(0, pyb.Timer.PWM, pin=pyb.Pin.board.D22, pulse_width=(t0.period() + 1) // 4)
+/// ch1 = t0.channel(1, pyb.Timer.PWM, pin=pyb.Pin.board.D23, pulse_width=(t0.period() + 1) // 2)
+STATIC const mp_arg_t pyb_timer_channel_args[] = {
+ { MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
+ { MP_QSTR_pin, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
+ { MP_QSTR_pulse_width, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
+ { MP_QSTR_pulse_width_percent, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
+ { MP_QSTR_compare, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
+ { MP_QSTR_polarity, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
+};
+#define PYB_TIMER_CHANNEL_NUM_ARGS MP_ARRAY_SIZE(pyb_timer_channel_args)
+
+STATIC mp_obj_t pyb_timer_channel(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
+ pyb_timer_obj_t *self = args[0];
+ mp_int_t channel = mp_obj_get_int(args[1]);
+
+ if (channel < 0 || channel > 7) {
+ nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid channel (%d)", channel));
+ }
+
+ pyb_timer_channel_obj_t *chan = self->channel;
+ pyb_timer_channel_obj_t *prev_chan = NULL;
+
+ while (chan != NULL) {
+ if (chan->channel == channel) {
+ break;
+ }
+ prev_chan = chan;
+ chan = chan->next;
+ }
+
+ // If only the channel number is given return the previously allocated
+ // channel (or None if no previous channel).
+ if (n_args == 2) {
+ if (chan) {
+ return chan;
+ }
+ return mp_const_none;
+ }
+
+ // If there was already a channel, then remove it from the list. Note that
+ // the order we do things here is important so as to appear atomic to
+ // the IRQ handler.
+ if (chan) {
+ // Turn off any IRQ associated with the channel.
+ pyb_timer_channel_callback(chan, mp_const_none);
+
+ // Unlink the channel from the list.
+ if (prev_chan) {
+ prev_chan->next = chan->next;
+ }
+ self->channel = chan->next;
+ chan->next = NULL;
+ }
+
+ // Allocate and initialize a new channel
+ mp_arg_val_t vals[PYB_TIMER_CHANNEL_NUM_ARGS];
+ mp_arg_parse_all(n_args - 3, args + 3, kw_args, PYB_TIMER_CHANNEL_NUM_ARGS, pyb_timer_channel_args, vals);
+
+ chan = m_new_obj(pyb_timer_channel_obj_t);
+ memset(chan, 0, sizeof(*chan));
+ chan->base.type = &pyb_timer_channel_type;
+ chan->timer = self;
+ chan->channel = channel;
+ chan->mode = mp_obj_get_int(args[2]);
+ chan->callback = vals[0].u_obj;
+
+ mp_obj_t pin_obj = vals[1].u_obj;
+ if (pin_obj != mp_const_none) {
+ if (!MP_OBJ_IS_TYPE(pin_obj, &pin_type)) {
+ mp_raise_ValueError("pin argument needs to be be a Pin type");
+ }
+ const pin_obj_t *pin = pin_obj;
+ const pin_af_obj_t *af = pin_find_af(pin, AF_FN_FTM, self->tim_id);
+ if (af == NULL) {
+ nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "pin %s doesn't have an af for TIM%d", qstr_str(pin->name), self->tim_id));
+ }
+ // pin.init(mode=AF_PP, af=idx)
+ const mp_obj_t args[6] = {
+ (mp_obj_t)&pin_init_obj,
+ pin_obj,
+ MP_OBJ_NEW_QSTR(MP_QSTR_mode), MP_OBJ_NEW_SMALL_INT(GPIO_MODE_AF_PP),
+ MP_OBJ_NEW_QSTR(MP_QSTR_af), MP_OBJ_NEW_SMALL_INT(af->idx)
+ };
+ mp_call_method_n_kw(0, 2, args);
+ }
+
+ // Link the channel to the timer before we turn the channel on.
+ // Note that this needs to appear atomic to the IRQ handler (the write
+ // to self->channel is atomic, so we're good, but I thought I'd mention
+ // in case this was ever changed in the future).
+ chan->next = self->channel;
+ self->channel = chan;
+
+ switch (chan->mode) {
+
+ case CHANNEL_MODE_PWM_NORMAL:
+ case CHANNEL_MODE_PWM_INVERTED: {
+ FTM_OC_InitTypeDef oc_config;
+ oc_config.OCMode = channel_mode_info[chan->mode].oc_mode;
+ if (vals[3].u_obj != mp_const_none) {
+ // pulse width ratio given
+ uint32_t period = compute_period(self);
+ oc_config.Pulse = compute_pwm_value_from_percent(period, vals[3].u_obj);
+ } else {
+ // use absolute pulse width value (defaults to 0 if nothing given)
+ oc_config.Pulse = vals[2].u_int;
+ }
+ oc_config.OCPolarity = FTM_OCPOLARITY_HIGH;
+
+ HAL_FTM_PWM_ConfigChannel(&self->ftm, &oc_config, channel);
+ if (chan->callback == mp_const_none) {
+ HAL_FTM_PWM_Start(&self->ftm, channel);
+ } else {
+ HAL_FTM_PWM_Start_IT(&self->ftm, channel);
+ }
+ break;
+ }
+
+ case CHANNEL_MODE_OC_TIMING:
+ case CHANNEL_MODE_OC_ACTIVE:
+ case CHANNEL_MODE_OC_INACTIVE:
+ case CHANNEL_MODE_OC_TOGGLE: {
+ FTM_OC_InitTypeDef oc_config;
+ oc_config.OCMode = channel_mode_info[chan->mode].oc_mode;
+ oc_config.Pulse = vals[4].u_int;
+ oc_config.OCPolarity = vals[5].u_int;
+ if (oc_config.OCPolarity == 0xffffffff) {
+ oc_config.OCPolarity = FTM_OCPOLARITY_HIGH;
+ }
+
+ if (!IS_FTM_OC_POLARITY(oc_config.OCPolarity)) {
+ nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid polarity (%d)", oc_config.OCPolarity));
+ }
+ HAL_FTM_OC_ConfigChannel(&self->ftm, &oc_config, channel);
+ if (chan->callback == mp_const_none) {
+ HAL_FTM_OC_Start(&self->ftm, channel);
+ } else {
+ HAL_FTM_OC_Start_IT(&self->ftm, channel);
+ }
+ break;
+ }
+
+ case CHANNEL_MODE_IC: {
+ FTM_IC_InitTypeDef ic_config;
+
+ ic_config.ICPolarity = vals[5].u_int;
+ if (ic_config.ICPolarity == 0xffffffff) {
+ ic_config.ICPolarity = FTM_ICPOLARITY_RISING;
+ }
+
+ if (!IS_FTM_IC_POLARITY(ic_config.ICPolarity)) {
+ nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid polarity (%d)", ic_config.ICPolarity));
+ }
+ HAL_FTM_IC_ConfigChannel(&self->ftm, &ic_config, chan->channel);
+ if (chan->callback == mp_const_none) {
+ HAL_FTM_IC_Start(&self->ftm, channel);
+ } else {
+ HAL_FTM_IC_Start_IT(&self->ftm, channel);
+ }
+ break;
+ }
+
+ default:
+ nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid mode (%d)", chan->mode));
+ }
+
+ return chan;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_channel_obj, 2, pyb_timer_channel);
+
+/// \method counter([value])
+/// Get or set the timer counter.
+STATIC mp_obj_t pyb_timer_counter(size_t n_args, const mp_obj_t *args) {
+ pyb_timer_obj_t *self = args[0];
+ if (n_args == 1) {
+ // get
+ return mp_obj_new_int(self->ftm.Instance->CNT);
+ }
+ // set - In order to write to CNT we need to set CNTIN
+ self->ftm.Instance->CNTIN = mp_obj_get_int(args[1]);
+ self->ftm.Instance->CNT = 0; // write any value to load CNTIN into CNT
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_counter_obj, 1, 2, pyb_timer_counter);
+
+/// \method prescaler([value])
+/// Get or set the prescaler for the timer.
+STATIC mp_obj_t pyb_timer_prescaler(size_t n_args, const mp_obj_t *args) {
+ pyb_timer_obj_t *self = args[0];
+ if (n_args == 1) {
+ // get
+ return mp_obj_new_int(1 << (self->ftm.Instance->SC & 7));
+ }
+
+ // set
+ mp_uint_t prescaler_shift = get_prescaler_shift(mp_obj_get_int(args[1]));
+
+ mp_uint_t sc = self->ftm.Instance->SC;
+ sc &= ~7;
+ sc |= FTM_SC_PS(prescaler_shift);
+ self->ftm.Instance->SC = sc;
+
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_prescaler_obj, 1, 2, pyb_timer_prescaler);
+
+/// \method period([value])
+/// Get or set the period of the timer.
+STATIC mp_obj_t pyb_timer_period(size_t n_args, const mp_obj_t *args) {
+ pyb_timer_obj_t *self = args[0];
+ if (n_args == 1) {
+ // get
+ return mp_obj_new_int(self->ftm.Instance->MOD & 0xffff);
+ }
+
+ // set
+ mp_int_t period = mp_obj_get_int(args[1]) & 0xffff;
+ self->ftm.Instance->CNT = 0;
+ self->ftm.Instance->MOD = period;
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_period_obj, 1, 2, pyb_timer_period);
+
+/// \method callback(fun)
+/// Set the function to be called when the timer triggers.
+/// `fun` is passed 1 argument, the timer object.
+/// If `fun` is `None` then the callback will be disabled.
+STATIC mp_obj_t pyb_timer_callback(mp_obj_t self_in, mp_obj_t callback) {
+ pyb_timer_obj_t *self = self_in;
+ if (callback == mp_const_none) {
+ // stop interrupt (but not timer)
+ __HAL_FTM_DISABLE_TOF_IT(&self->ftm);
+ self->callback = mp_const_none;
+ } else if (mp_obj_is_callable(callback)) {
+ self->callback = callback;
+ HAL_NVIC_EnableIRQ(self->irqn);
+ // start timer, so that it interrupts on overflow
+ HAL_FTM_Base_Start_IT(&self->ftm);
+ } else {
+ mp_raise_ValueError("callback must be None or a callable object");
+ }
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_timer_callback_obj, pyb_timer_callback);
+
+#if MICROPY_TIMER_REG
+reg_t timer_reg[] = {
+ REG_ENTRY(FTM_TypeDef, SC),
+ REG_ENTRY(FTM_TypeDef, CNT),
+ REG_ENTRY(FTM_TypeDef, MOD),
+ REG_ENTRY(FTM_TypeDef, CNTIN),
+ REG_ENTRY(FTM_TypeDef, STATUS),
+ REG_ENTRY(FTM_TypeDef, MODE),
+ REG_ENTRY(FTM_TypeDef, SYNC),
+ REG_ENTRY(FTM_TypeDef, OUTINIT),
+ REG_ENTRY(FTM_TypeDef, OUTMASK),
+ REG_ENTRY(FTM_TypeDef, COMBINE),
+ REG_ENTRY(FTM_TypeDef, DEADTIME),
+ REG_ENTRY(FTM_TypeDef, EXTTRIG),
+ REG_ENTRY(FTM_TypeDef, POL),
+ REG_ENTRY(FTM_TypeDef, FMS),
+ REG_ENTRY(FTM_TypeDef, FILTER),
+ REG_ENTRY(FTM_TypeDef, FLTCTRL),
+ REG_ENTRY(FTM_TypeDef, QDCTRL),
+ REG_ENTRY(FTM_TypeDef, CONF),
+ REG_ENTRY(FTM_TypeDef, FLTPOL),
+ REG_ENTRY(FTM_TypeDef, SYNCONF),
+ REG_ENTRY(FTM_TypeDef, INVCTRL),
+ REG_ENTRY(FTM_TypeDef, SWOCTRL),
+ REG_ENTRY(FTM_TypeDef, PWMLOAD),
+};
+
+mp_obj_t pyb_timer_reg(uint n_args, const mp_obj_t *args) {
+ pyb_timer_obj_t *self = args[0];
+ return reg_cmd(self->ftm.Instance, timer_reg, MP_ARRAY_SIZE(timer_reg), n_args - 1, args + 1);
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_reg_obj, 1, 3, pyb_timer_reg);
+#endif // MICROPY_TIMER_REG
+
+STATIC const mp_rom_map_elem_t pyb_timer_locals_dict_table[] = {
+ // instance methods
+ { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&pyb_timer_init_obj) },
+ { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&pyb_timer_deinit_obj) },
+ { MP_ROM_QSTR(MP_QSTR_channel), MP_ROM_PTR(&pyb_timer_channel_obj) },
+ { MP_ROM_QSTR(MP_QSTR_counter), MP_ROM_PTR(&pyb_timer_counter_obj) },
+ { MP_ROM_QSTR(MP_QSTR_prescaler), MP_ROM_PTR(&pyb_timer_prescaler_obj) },
+ { MP_ROM_QSTR(MP_QSTR_period), MP_ROM_PTR(&pyb_timer_period_obj) },
+ { MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&pyb_timer_callback_obj) },
+#if MICROPY_TIMER_REG
+ { MP_ROM_QSTR(MP_QSTR_reg), MP_ROM_PTR(&pyb_timer_reg_obj) },
+#endif
+ { MP_ROM_QSTR(MP_QSTR_UP), MP_ROM_INT(FTM_COUNTERMODE_UP) },
+ { MP_ROM_QSTR(MP_QSTR_CENTER), MP_ROM_INT(FTM_COUNTERMODE_CENTER) },
+ { MP_ROM_QSTR(MP_QSTR_PWM), MP_ROM_INT(CHANNEL_MODE_PWM_NORMAL) },
+ { MP_ROM_QSTR(MP_QSTR_PWM_INVERTED), MP_ROM_INT(CHANNEL_MODE_PWM_INVERTED) },
+ { MP_ROM_QSTR(MP_QSTR_OC_TIMING), MP_ROM_INT(CHANNEL_MODE_OC_TIMING) },
+ { MP_ROM_QSTR(MP_QSTR_OC_ACTIVE), MP_ROM_INT(CHANNEL_MODE_OC_ACTIVE) },
+ { MP_ROM_QSTR(MP_QSTR_OC_INACTIVE), MP_ROM_INT(CHANNEL_MODE_OC_INACTIVE) },
+ { MP_ROM_QSTR(MP_QSTR_OC_TOGGLE), MP_ROM_INT(CHANNEL_MODE_OC_TOGGLE) },
+ { MP_ROM_QSTR(MP_QSTR_IC), MP_ROM_INT(CHANNEL_MODE_IC) },
+ { MP_ROM_QSTR(MP_QSTR_HIGH), MP_ROM_INT(FTM_OCPOLARITY_HIGH) },
+ { MP_ROM_QSTR(MP_QSTR_LOW), MP_ROM_INT(FTM_OCPOLARITY_LOW) },
+ { MP_ROM_QSTR(MP_QSTR_RISING), MP_ROM_INT(FTM_ICPOLARITY_RISING) },
+ { MP_ROM_QSTR(MP_QSTR_FALLING), MP_ROM_INT(FTM_ICPOLARITY_FALLING) },
+ { MP_ROM_QSTR(MP_QSTR_BOTH), MP_ROM_INT(FTM_ICPOLARITY_BOTH) },
+};
+STATIC MP_DEFINE_CONST_DICT(pyb_timer_locals_dict, pyb_timer_locals_dict_table);
+
+const mp_obj_type_t pyb_timer_type = {
+ { &mp_type_type },
+ .name = MP_QSTR_Timer,
+ .print = pyb_timer_print,
+ .make_new = pyb_timer_make_new,
+ .locals_dict = (mp_obj_t)&pyb_timer_locals_dict,
+};
+
+/// \moduleref pyb
+/// \class TimerChannel - setup a channel for a timer.
+///
+/// Timer channels are used to generate/capture a signal using a timer.
+///
+/// TimerChannel objects are created using the Timer.channel() method.
+STATIC void pyb_timer_channel_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
+ pyb_timer_channel_obj_t *self = self_in;
+
+ mp_printf(print, "TimerChannel(timer=%u, channel=%u, mode=%s)",
+ self->timer->tim_id,
+ self->channel,
+ qstr_str(channel_mode_info[self->mode].name));
+}
+
+/// \method capture([value])
+/// Get or set the capture value associated with a channel.
+/// capture, compare, and pulse_width are all aliases for the same function.
+/// capture is the logical name to use when the channel is in input capture mode.
+
+/// \method compare([value])
+/// Get or set the compare value associated with a channel.
+/// capture, compare, and pulse_width are all aliases for the same function.
+/// compare is the logical name to use when the channel is in output compare mode.
+
+/// \method pulse_width([value])
+/// Get or set the pulse width value associated with a channel.
+/// capture, compare, and pulse_width are all aliases for the same function.
+/// pulse_width is the logical name to use when the channel is in PWM mode.
+///
+/// In edge aligned mode, a pulse_width of `period + 1` corresponds to a duty cycle of 100%
+/// In center aligned mode, a pulse width of `period` corresponds to a duty cycle of 100%
+STATIC mp_obj_t pyb_timer_channel_capture_compare(size_t n_args, const mp_obj_t *args) {
+ pyb_timer_channel_obj_t *self = args[0];
+ FTM_TypeDef *FTMx = self->timer->ftm.Instance;
+ if (n_args == 1) {
+ // get
+ return mp_obj_new_int(FTMx->channel[self->channel].CV & 0xffff);
+ }
+
+ mp_int_t pw = mp_obj_get_int(args[1]);
+
+ // set
+ FTMx->channel[self->channel].CV = pw & 0xffff;
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_channel_capture_compare_obj, 1, 2, pyb_timer_channel_capture_compare);
+
+/// \method pulse_width_percent([value])
+/// Get or set the pulse width percentage associated with a channel. The value
+/// is a number between 0 and 100 and sets the percentage of the timer period
+/// for which the pulse is active. The value can be an integer or
+/// floating-point number for more accuracy. For example, a value of 25 gives
+/// a duty cycle of 25%.
+STATIC mp_obj_t pyb_timer_channel_pulse_width_percent(size_t n_args, const mp_obj_t *args) {
+ pyb_timer_channel_obj_t *self = args[0];
+ FTM_TypeDef *FTMx = self->timer->ftm.Instance;
+ uint32_t period = compute_period(self->timer);
+ if (n_args == 1) {
+ // get
+ uint32_t cmp = FTMx->channel[self->channel].CV & 0xffff;
+ return compute_percent_from_pwm_value(period, cmp);
+ } else {
+ // set
+ uint32_t cmp = compute_pwm_value_from_percent(period, args[1]);
+ FTMx->channel[self->channel].CV = cmp & 0xffff;
+ return mp_const_none;
+ }
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_channel_pulse_width_percent_obj, 1, 2, pyb_timer_channel_pulse_width_percent);
+
+/// \method callback(fun)
+/// Set the function to be called when the timer channel triggers.
+/// `fun` is passed 1 argument, the timer object.
+/// If `fun` is `None` then the callback will be disabled.
+STATIC mp_obj_t pyb_timer_channel_callback(mp_obj_t self_in, mp_obj_t callback) {
+ pyb_timer_channel_obj_t *self = self_in;
+ if (callback == mp_const_none) {
+ // stop interrupt (but not timer)
+ __HAL_FTM_DISABLE_CH_IT(&self->timer->ftm, self->channel);
+ self->callback = mp_const_none;
+ } else if (mp_obj_is_callable(callback)) {
+ self->callback = callback;
+ HAL_NVIC_EnableIRQ(self->timer->irqn);
+ // start timer, so that it interrupts on overflow
+ switch (self->mode) {
+ case CHANNEL_MODE_PWM_NORMAL:
+ case CHANNEL_MODE_PWM_INVERTED:
+ HAL_FTM_PWM_Start_IT(&self->timer->ftm, self->channel);
+ break;
+ case CHANNEL_MODE_OC_TIMING:
+ case CHANNEL_MODE_OC_ACTIVE:
+ case CHANNEL_MODE_OC_INACTIVE:
+ case CHANNEL_MODE_OC_TOGGLE:
+ HAL_FTM_OC_Start_IT(&self->timer->ftm, self->channel);
+ break;
+ case CHANNEL_MODE_IC:
+ HAL_FTM_IC_Start_IT(&self->timer->ftm, self->channel);
+ break;
+ }
+ } else {
+ mp_raise_ValueError("callback must be None or a callable object");
+ }
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_timer_channel_callback_obj, pyb_timer_channel_callback);
+
+#if MICROPY_TIMER_REG
+reg_t timer_channel_reg[] = {
+ REG_ENTRY(FTM_ChannelTypeDef, CSC),
+ REG_ENTRY(FTM_ChannelTypeDef, CV),
+};
+
+mp_obj_t pyb_timer_channel_reg(uint n_args, const mp_obj_t *args) {
+ pyb_timer_channel_obj_t *self = args[0];
+ return reg_cmd(&self->timer->ftm.Instance->channel[self->channel],
+ timer_channel_reg, MP_ARRAY_SIZE(timer_channel_reg),
+ n_args - 1, args + 1);
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_channel_reg_obj, 1, 3, pyb_timer_channel_reg);
+#endif
+
+STATIC const mp_rom_map_elem_t pyb_timer_channel_locals_dict_table[] = {
+ // instance methods
+ { MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&pyb_timer_channel_callback_obj) },
+ { MP_ROM_QSTR(MP_QSTR_pulse_width), MP_ROM_PTR(&pyb_timer_channel_capture_compare_obj) },
+ { MP_ROM_QSTR(MP_QSTR_pulse_width_percent), MP_ROM_PTR(&pyb_timer_channel_pulse_width_percent_obj) },
+ { MP_ROM_QSTR(MP_QSTR_capture), MP_ROM_PTR(&pyb_timer_channel_capture_compare_obj) },
+ { MP_ROM_QSTR(MP_QSTR_compare), MP_ROM_PTR(&pyb_timer_channel_capture_compare_obj) },
+#if MICROPY_TIMER_REG
+ { MP_ROM_QSTR(MP_QSTR_reg), MP_ROM_PTR(&pyb_timer_channel_reg_obj) },
+#endif
+};
+STATIC MP_DEFINE_CONST_DICT(pyb_timer_channel_locals_dict, pyb_timer_channel_locals_dict_table);
+
+STATIC const mp_obj_type_t pyb_timer_channel_type = {
+ { &mp_type_type },
+ .name = MP_QSTR_TimerChannel,
+ .print = pyb_timer_channel_print,
+ .locals_dict = (mp_obj_t)&pyb_timer_channel_locals_dict,
+};
+
+STATIC bool ftm_handle_irq_callback(pyb_timer_obj_t *self, mp_uint_t channel, mp_obj_t callback) {
+ // execute callback if it's set
+ if (callback == mp_const_none) {
+ return false;
+ }
+ bool handled = false;
+
+ // When executing code within a handler we must lock the GC to prevent
+ // any memory allocations. We must also catch any exceptions.
+ gc_lock();
+ nlr_buf_t nlr;
+ if (nlr_push(&nlr) == 0) {
+ mp_call_function_1(callback, self);
+ nlr_pop();
+ handled = true;
+ } else {
+ // Uncaught exception; disable the callback so it doesn't run again.
+ self->callback = mp_const_none;
+ if (channel == 0xffffffff) {
+ printf("Uncaught exception in Timer(" UINT_FMT
+ ") interrupt handler\n", self->tim_id);
+ } else {
+ printf("Uncaught exception in Timer(" UINT_FMT ") channel "
+ UINT_FMT " interrupt handler\n", self->tim_id, channel);
+ }
+ mp_obj_print_exception(&mp_plat_print, (mp_obj_t)nlr.ret_val);
+ }
+ gc_unlock();
+ return handled;
+}
+
+STATIC void ftm_irq_handler(uint tim_id) {
+ if (tim_id >= PYB_TIMER_OBJ_ALL_NUM) {
+ return;
+ }
+ // get the timer object
+ pyb_timer_obj_t *self = pyb_timer_obj_all[tim_id];
+ if (self == NULL) {
+ // timer object has not been set, so we can't do anything
+ printf("No timer object for id=%d\n", tim_id);
+ return;
+ }
+ FTM_HandleTypeDef *hftm = &self->ftm;
+
+ bool handled = false;
+
+ // Check for timer (versus timer channel) interrupt.
+ if (__HAL_FTM_GET_TOF_IT(hftm) && __HAL_FTM_GET_TOF_FLAG(hftm)) {
+ __HAL_FTM_CLEAR_TOF_FLAG(hftm);
+ if (ftm_handle_irq_callback(self, 0xffffffff, self->callback)) {
+ handled = true;
+ } else {
+ __HAL_FTM_DISABLE_TOF_IT(&self->ftm);
+ printf("No callback for Timer %d TOF (now disabled)\n", tim_id);
+ }
+ }
+
+ uint32_t processed = 0;
+
+ // Check to see if a timer channel interrupt is pending
+ pyb_timer_channel_obj_t *chan = self->channel;
+ while (chan != NULL) {
+ processed |= (1 << chan->channel);
+ if (__HAL_FTM_GET_CH_IT(&self->ftm, chan->channel) && __HAL_FTM_GET_CH_FLAG(&self->ftm, chan->channel)) {
+ __HAL_FTM_CLEAR_CH_FLAG(&self->ftm, chan->channel);
+ if (ftm_handle_irq_callback(self, chan->channel, chan->callback)) {
+ handled = true;
+ } else {
+ __HAL_FTM_DISABLE_CH_IT(&self->ftm, chan->channel);
+ printf("No callback for Timer %d channel %u (now disabled)\n",
+ self->tim_id, chan->channel);
+ }
+ }
+ chan = chan->next;
+ }
+
+ if (!handled) {
+ // An interrupt occurred for a channel we didn't process. Find it and
+ // turn it off.
+ for (mp_uint_t channel = 0; channel < 8; channel++) {
+ if ((processed & (1 << channel)) == 0) {
+ if (__HAL_FTM_GET_CH_FLAG(&self->ftm, channel) != 0) {
+ __HAL_FTM_CLEAR_CH_FLAG(&self->ftm, channel);
+ __HAL_FTM_DISABLE_CH_IT(&self->ftm, channel);
+ printf("Unhandled interrupt Timer %d channel %u (now disabled)\n",
+ tim_id, channel);
+ }
+ }
+ }
+ }
+}
+
+void ftm0_isr(void) {
+ ftm_irq_handler(0);
+}
+
+void ftm1_isr(void) {
+ ftm_irq_handler(1);
+}
+
+void ftm2_isr(void) {
+ ftm_irq_handler(2);
+}
diff --git a/ports/teensy/timer.h b/ports/teensy/timer.h
new file mode 100644
index 000000000..75c2e654e
--- /dev/null
+++ b/ports/teensy/timer.h
@@ -0,0 +1,34 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2013, 2014 Damien P. George
+ *
+ * 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 MICROPY_INCLUDED_TEENSY_TIMER_H
+#define MICROPY_INCLUDED_TEENSY_TIMER_H
+
+extern const mp_obj_type_t pyb_timer_type;
+
+void timer_init0(void);
+void timer_deinit(void);
+
+#endif // MICROPY_INCLUDED_TEENSY_TIMER_H
diff --git a/ports/teensy/uart.c b/ports/teensy/uart.c
new file mode 100644
index 000000000..768572aff
--- /dev/null
+++ b/ports/teensy/uart.c
@@ -0,0 +1,488 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2013, 2014 Damien P. George
+ *
+ * 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 <stdio.h>
+#include <string.h>
+
+#include "py/nlr.h"
+#include "py/runtime.h"
+#include "bufhelper.h"
+#include "uart.h"
+
+/// \moduleref pyb
+/// \class UART - duplex serial communication bus
+///
+/// UART implements the standard UART/USART duplex serial communications protocol. At
+/// the physical level it consists of 2 lines: RX and TX.
+///
+/// See usage model of I2C. UART is very similar. Main difference is
+/// parameters to init the UART bus:
+///
+/// from pyb import UART
+///
+/// uart = UART(1, 9600) # init with given baudrate
+/// uart.init(9600, bits=8, stop=1, parity=None) # init with given parameters
+///
+/// Bits can be 8 or 9, stop can be 1 or 2, parity can be None, 0 (even), 1 (odd).
+///
+/// Extra method:
+///
+/// uart.any() # returns True if any characters waiting
+
+struct _pyb_uart_obj_t {
+ mp_obj_base_t base;
+ pyb_uart_t uart_id;
+ bool is_enabled;
+// UART_HandleTypeDef uart;
+};
+
+pyb_uart_obj_t *pyb_uart_global_debug = NULL;
+
+// assumes Init parameters have been set up correctly
+bool uart_init2(pyb_uart_obj_t *uart_obj) {
+#if 0
+ USART_TypeDef *UARTx = NULL;
+
+ uint32_t GPIO_Pin = 0;
+ uint8_t GPIO_AF_UARTx = 0;
+ GPIO_TypeDef* GPIO_Port = NULL;
+
+ switch (uart_obj->uart_id) {
+ // USART1 is on PA9/PA10 (CK on PA8), PB6/PB7
+ case PYB_UART_1:
+ UARTx = USART1;
+ GPIO_AF_UARTx = GPIO_AF7_USART1;
+
+#if defined (PYBV4) || defined(PYBV10)
+ GPIO_Port = GPIOB;
+ GPIO_Pin = GPIO_PIN_6 | GPIO_PIN_7;
+#else
+ GPIO_Port = GPIOA;
+ GPIO_Pin = GPIO_PIN_9 | GPIO_PIN_10;
+#endif
+
+ __USART1_CLK_ENABLE();
+ break;
+
+ // USART2 is on PA2/PA3 (CK on PA4), PD5/PD6 (CK on PD7)
+ case PYB_UART_2:
+ UARTx = USART2;
+ GPIO_AF_UARTx = GPIO_AF7_USART2;
+
+ GPIO_Port = GPIOA;
+ GPIO_Pin = GPIO_PIN_2 | GPIO_PIN_3;
+
+ __USART2_CLK_ENABLE();
+ break;
+
+ // USART3 is on PB10/PB11 (CK on PB12), PC10/PC11 (CK on PC12), PD8/PD9 (CK on PD10)
+ case PYB_UART_3:
+ UARTx = USART3;
+ GPIO_AF_UARTx = GPIO_AF7_USART3;
+
+#if defined(PYBV3) || defined(PYBV4) | defined(PYBV10)
+ GPIO_Port = GPIOB;
+ GPIO_Pin = GPIO_PIN_10 | GPIO_PIN_11;
+#else
+ GPIO_Port = GPIOD;
+ GPIO_Pin = GPIO_PIN_8 | GPIO_PIN_9;
+#endif
+ __USART3_CLK_ENABLE();
+ break;
+
+ // UART4 is on PA0/PA1, PC10/PC11
+ case PYB_UART_4:
+ UARTx = UART4;
+ GPIO_AF_UARTx = GPIO_AF8_UART4;
+
+ GPIO_Port = GPIOA;
+ GPIO_Pin = GPIO_PIN_0 | GPIO_PIN_1;
+
+ __UART4_CLK_ENABLE();
+ break;
+
+ // USART6 is on PC6/PC7 (CK on PC8)
+ case PYB_UART_6:
+ UARTx = USART6;
+ GPIO_AF_UARTx = GPIO_AF8_USART6;
+
+ GPIO_Port = GPIOC;
+ GPIO_Pin = GPIO_PIN_6 | GPIO_PIN_7;
+
+ __USART6_CLK_ENABLE();
+ break;
+
+ default:
+ return false;
+ }
+
+ // init GPIO
+ GPIO_InitTypeDef GPIO_InitStructure;
+ GPIO_InitStructure.Pin = GPIO_Pin;
+ GPIO_InitStructure.Speed = GPIO_SPEED_HIGH;
+ GPIO_InitStructure.Mode = GPIO_MODE_AF_PP;
+ GPIO_InitStructure.Pull = GPIO_PULLUP;
+ GPIO_InitStructure.Alternate = GPIO_AF_UARTx;
+ HAL_GPIO_Init(GPIO_Port, &GPIO_InitStructure);
+
+ // init UARTx
+ uart_obj->uart.Instance = UARTx;
+ HAL_UART_Init(&uart_obj->uart);
+
+ uart_obj->is_enabled = true;
+#endif
+ return true;
+}
+
+bool uart_init(pyb_uart_obj_t *uart_obj, uint32_t baudrate) {
+#if 0
+ UART_HandleTypeDef *uh = &uart_obj->uart;
+ memset(uh, 0, sizeof(*uh));
+ uh->Init.BaudRate = baudrate;
+ uh->Init.WordLength = UART_WORDLENGTH_8B;
+ uh->Init.StopBits = UART_STOPBITS_1;
+ uh->Init.Parity = UART_PARITY_NONE;
+ uh->Init.Mode = UART_MODE_TX_RX;
+ uh->Init.HwFlowCtl = UART_HWCONTROL_NONE;
+ uh->Init.OverSampling = UART_OVERSAMPLING_16;
+#endif
+ return uart_init2(uart_obj);
+}
+
+mp_uint_t uart_rx_any(pyb_uart_obj_t *uart_obj) {
+#if 0
+ return __HAL_UART_GET_FLAG(&uart_obj->uart, UART_FLAG_RXNE);
+#else
+ return 0;
+#endif
+}
+
+int uart_rx_char(pyb_uart_obj_t *uart_obj) {
+ uint8_t ch;
+#if 0
+ if (HAL_UART_Receive(&uart_obj->uart, &ch, 1, 0) != HAL_OK) {
+ ch = 0;
+ }
+#else
+ ch = 'A';
+#endif
+ return ch;
+}
+
+void uart_tx_char(pyb_uart_obj_t *uart_obj, int c) {
+#if 0
+ uint8_t ch = c;
+ HAL_UART_Transmit(&uart_obj->uart, &ch, 1, 100000);
+#endif
+}
+
+void uart_tx_str(pyb_uart_obj_t *uart_obj, const char *str) {
+#if 0
+ HAL_UART_Transmit(&uart_obj->uart, (uint8_t*)str, strlen(str), 100000);
+#endif
+}
+
+void uart_tx_strn(pyb_uart_obj_t *uart_obj, const char *str, uint len) {
+#if 0
+ HAL_UART_Transmit(&uart_obj->uart, (uint8_t*)str, len, 100000);
+#endif
+}
+
+void uart_tx_strn_cooked(pyb_uart_obj_t *uart_obj, const char *str, uint len) {
+ for (const char *top = str + len; str < top; str++) {
+ if (*str == '\n') {
+ uart_tx_char(uart_obj, '\r');
+ }
+ uart_tx_char(uart_obj, *str);
+ }
+}
+
+/******************************************************************************/
+/* MicroPython bindings */
+
+STATIC void pyb_uart_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
+ pyb_uart_obj_t *self = self_in;
+ if (!self->is_enabled) {
+ mp_printf(print, "UART(%lu)", self->uart_id);
+ } else {
+#if 0
+ mp_printf(print, "UART(%lu, baudrate=%u, bits=%u, stop=%u",
+ self->uart_id, self->uart.Init.BaudRate,
+ self->uart.Init.WordLength == UART_WORDLENGTH_8B ? 8 : 9,
+ self->uart.Init.StopBits == UART_STOPBITS_1 ? 1 : 2);
+ if (self->uart.Init.Parity == UART_PARITY_NONE) {
+ mp_print_str(print, ", parity=None)");
+ } else {
+ mp_printf(print, ", parity=%u)", self->uart.Init.Parity == UART_PARITY_EVEN ? 0 : 1);
+ }
+#endif
+ }
+}
+
+/// \method init(baudrate, *, bits=8, stop=1, parity=None)
+///
+/// Initialise the SPI bus with the given parameters:
+///
+/// - `baudrate` is the clock rate.
+/// - `bits` is the number of bits per byte, 8 or 9.
+/// - `stop` is the number of stop bits, 1 or 2.
+/// - `parity` is the parity, `None`, 0 (even) or 1 (odd).
+STATIC const mp_arg_t pyb_uart_init_args[] = {
+ { MP_QSTR_baudrate, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 9600} },
+ { MP_QSTR_bits, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 8} },
+ { MP_QSTR_stop, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} },
+ { MP_QSTR_parity, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
+};
+#define PYB_UART_INIT_NUM_ARGS MP_ARRAY_SIZE(pyb_uart_init_args)
+
+STATIC mp_obj_t pyb_uart_init_helper(pyb_uart_obj_t *self, uint n_args, const mp_obj_t *args, mp_map_t *kw_args) {
+ // parse args
+ mp_arg_val_t vals[PYB_UART_INIT_NUM_ARGS];
+ mp_arg_parse_all(n_args, args, kw_args, PYB_UART_INIT_NUM_ARGS, pyb_uart_init_args, vals);
+#if 0
+ // set the UART configuration values
+ memset(&self->uart, 0, sizeof(self->uart));
+ UART_InitTypeDef *init = &self->uart.Init;
+ init->BaudRate = vals[0].u_int;
+ init->WordLength = vals[1].u_int == 8 ? UART_WORDLENGTH_8B : UART_WORDLENGTH_9B;
+ switch (vals[2].u_int) {
+ case 1: init->StopBits = UART_STOPBITS_1; break;
+ default: init->StopBits = UART_STOPBITS_2; break;
+ }
+ if (vals[3].u_obj == mp_const_none) {
+ init->Parity = UART_PARITY_NONE;
+ } else {
+ mp_int_t parity = mp_obj_get_int(vals[3].u_obj);
+ init->Parity = (parity & 1) ? UART_PARITY_ODD : UART_PARITY_EVEN;
+ }
+ init->Mode = UART_MODE_TX_RX;
+ init->HwFlowCtl = UART_HWCONTROL_NONE;
+ init->OverSampling = UART_OVERSAMPLING_16;
+
+ // init UART (if it fails, it's because the port doesn't exist)
+ if (!uart_init2(self)) {
+ nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART port %d does not exist", self->uart_id));
+ }
+#endif
+
+ return mp_const_none;
+}
+
+/// \classmethod \constructor(bus, ...)
+///
+/// Construct a UART object on the given bus. `bus` can be 1-6, or 'XA', 'XB', 'YA', or 'YB'.
+/// With no additional parameters, the UART object is created but not
+/// initialised (it has the settings from the last initialisation of
+/// the bus, if any). If extra arguments are given, the bus is initialised.
+/// See `init` for parameters of initialisation.
+///
+/// The physical pins of the UART busses are:
+///
+/// - `UART(4)` is on `XA`: `(TX, RX) = (X1, X2) = (PA0, PA1)`
+/// - `UART(1)` is on `XB`: `(TX, RX) = (X9, X10) = (PB6, PB7)`
+/// - `UART(6)` is on `YA`: `(TX, RX) = (Y1, Y2) = (PC6, PC7)`
+/// - `UART(3)` is on `YB`: `(TX, RX) = (Y9, Y10) = (PB10, PB11)`
+/// - `UART(2)` is on: `(TX, RX) = (X3, X4) = (PA2, PA3)`
+STATIC mp_obj_t pyb_uart_make_new(const mp_obj_type_t *type, uint n_args, uint n_kw, const mp_obj_t *args) {
+ // check arguments
+ mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
+
+ // create object
+ pyb_uart_obj_t *o = m_new_obj(pyb_uart_obj_t);
+ o->base.type = &pyb_uart_type;
+
+ // work out port
+ o->uart_id = 0;
+#if 0
+ if (MP_OBJ_IS_STR(args[0])) {
+ const char *port = mp_obj_str_get_str(args[0]);
+ if (0) {
+#if defined(PYBV10)
+ } else if (strcmp(port, "XA") == 0) {
+ o->uart_id = PYB_UART_XA;
+ } else if (strcmp(port, "XB") == 0) {
+ o->uart_id = PYB_UART_XB;
+ } else if (strcmp(port, "YA") == 0) {
+ o->uart_id = PYB_UART_YA;
+ } else if (strcmp(port, "YB") == 0) {
+ o->uart_id = PYB_UART_YB;
+#endif
+ } else {
+ nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART port %s does not exist", port));
+ }
+ } else {
+ o->uart_id = mp_obj_get_int(args[0]);
+ }
+#endif
+
+ if (n_args > 1 || n_kw > 0) {
+ // start the peripheral
+ mp_map_t kw_args;
+ mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
+ pyb_uart_init_helper(o, n_args - 1, args + 1, &kw_args);
+ }
+
+ return o;
+}
+
+STATIC mp_obj_t pyb_uart_init(uint n_args, const mp_obj_t *args, mp_map_t *kw_args) {
+ return pyb_uart_init_helper(args[0], n_args - 1, args + 1, kw_args);
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_uart_init_obj, 1, pyb_uart_init);
+
+/// \method deinit()
+/// Turn off the UART bus.
+STATIC mp_obj_t pyb_uart_deinit(mp_obj_t self_in) {
+ //pyb_uart_obj_t *self = self_in;
+ // TODO
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_deinit_obj, pyb_uart_deinit);
+
+/// \method any()
+/// Return `True` if any characters waiting, else `False`.
+STATIC mp_obj_t pyb_uart_any(mp_obj_t self_in) {
+ pyb_uart_obj_t *self = self_in;
+ if (uart_rx_any(self)) {
+ return mp_const_true;
+ } else {
+ return mp_const_false;
+ }
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_any_obj, pyb_uart_any);
+
+/// \method send(send, *, timeout=5000)
+/// Send data on the bus:
+///
+/// - `send` is the data to send (an integer to send, or a buffer object).
+/// - `timeout` is the timeout in milliseconds to wait for the send.
+///
+/// Return value: `None`.
+STATIC const mp_arg_t pyb_uart_send_args[] = {
+ { MP_QSTR_send, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
+ { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 5000} },
+};
+#define PYB_UART_SEND_NUM_ARGS MP_ARRAY_SIZE(pyb_uart_send_args)
+
+STATIC mp_obj_t pyb_uart_send(uint n_args, const mp_obj_t *args, mp_map_t *kw_args) {
+ // TODO assumes transmission size is 8-bits wide
+
+ pyb_uart_obj_t *self = args[0];
+
+ // parse args
+ mp_arg_val_t vals[PYB_UART_SEND_NUM_ARGS];
+ mp_arg_parse_all(n_args - 1, args + 1, kw_args, PYB_UART_SEND_NUM_ARGS, pyb_uart_send_args, vals);
+
+#if 0
+ // get the buffer to send from
+ mp_buffer_info_t bufinfo;
+ uint8_t data[1];
+ pyb_buf_get_for_send(vals[0].u_obj, &bufinfo, data);
+
+ // send the data
+ HAL_StatusTypeDef status = HAL_UART_Transmit(&self->uart, bufinfo.buf, bufinfo.len, vals[1].u_int);
+
+ if (status != HAL_OK) {
+ // TODO really need a HardwareError object, or something
+ nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_Exception, "HAL_UART_Transmit failed with code %d", status));
+ }
+#else
+ (void)self;
+#endif
+
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_uart_send_obj, 1, pyb_uart_send);
+
+/// \method recv(recv, *, timeout=5000)
+///
+/// Receive data on the bus:
+///
+/// - `recv` can be an integer, which is the number of bytes to receive,
+/// or a mutable buffer, which will be filled with received bytes.
+/// - `timeout` is the timeout in milliseconds to wait for the receive.
+///
+/// Return value: if `recv` is an integer then a new buffer of the bytes received,
+/// otherwise the same buffer that was passed in to `recv`.
+STATIC const mp_arg_t pyb_uart_recv_args[] = {
+ { MP_QSTR_recv, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
+ { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 5000} },
+};
+#define PYB_UART_RECV_NUM_ARGS MP_ARRAY_SIZE(pyb_uart_recv_args)
+
+STATIC mp_obj_t pyb_uart_recv(uint n_args, const mp_obj_t *args, mp_map_t *kw_args) {
+ // TODO assumes transmission size is 8-bits wide
+
+ pyb_uart_obj_t *self = args[0];
+
+#if 0
+ // parse args
+ mp_arg_val_t vals[PYB_UART_RECV_NUM_ARGS];
+ mp_arg_parse_all(n_args - 1, args + 1, kw_args, PYB_UART_RECV_NUM_ARGS, pyb_uart_recv_args, vals);
+
+ // get the buffer to receive into
+ mp_buffer_info_t bufinfo;
+ mp_obj_t o_ret = pyb_buf_get_for_recv(vals[0].u_obj, &bufinfo);
+
+ // receive the data
+ HAL_StatusTypeDef status = HAL_UART_Receive(&self->uart, bufinfo.buf, bufinfo.len, vals[1].u_int);
+
+ if (status != HAL_OK) {
+ // TODO really need a HardwareError object, or something
+ nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_Exception, "HAL_UART_Receive failed with code %d", status));
+ }
+
+ // return the received data
+ if (o_ret == MP_OBJ_NULL) {
+ return vals[0].u_obj;
+ } else {
+ return mp_obj_str_builder_end(o_ret);
+ }
+#else
+ (void)self;
+ return mp_const_none;
+#endif
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_uart_recv_obj, 1, pyb_uart_recv);
+
+STATIC const mp_rom_map_elem_t pyb_uart_locals_dict_table[] = {
+ // instance methods
+ { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&pyb_uart_init_obj) },
+ { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&pyb_uart_deinit_obj) },
+ { MP_ROM_QSTR(MP_QSTR_any), MP_ROM_PTR(&pyb_uart_any_obj) },
+ { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&pyb_uart_send_obj) },
+ { MP_ROM_QSTR(MP_QSTR_recv), MP_ROM_PTR(&pyb_uart_recv_obj) },
+};
+
+STATIC MP_DEFINE_CONST_DICT(pyb_uart_locals_dict, pyb_uart_locals_dict_table);
+
+const mp_obj_type_t pyb_uart_type = {
+ { &mp_type_type },
+ .name = MP_QSTR_UART,
+ .print = pyb_uart_print,
+ .make_new = pyb_uart_make_new,
+ .locals_dict = (mp_obj_t)&pyb_uart_locals_dict,
+};
diff --git a/ports/teensy/usb.c b/ports/teensy/usb.c
new file mode 100644
index 000000000..ed96826b3
--- /dev/null
+++ b/ports/teensy/usb.c
@@ -0,0 +1,52 @@
+#include <string.h>
+
+#include "py/runtime.h"
+
+#include "Arduino.h"
+
+#include "usb.h"
+#include "usb_serial.h"
+
+bool usb_vcp_is_connected(void)
+{
+ return usb_configuration && (usb_cdc_line_rtsdtr & (USB_SERIAL_DTR | USB_SERIAL_RTS));
+}
+
+bool usb_vcp_is_enabled(void)
+{
+ return true;
+}
+
+int usb_vcp_rx_num(void) {
+ return usb_serial_available();
+}
+
+int usb_vcp_recv_byte(uint8_t *ptr)
+{
+ int ch = usb_serial_getchar();
+ if (ch < 0) {
+ return 0;
+ }
+ *ptr = ch;
+ return 1;
+}
+
+void usb_vcp_send_str(const char* str)
+{
+ usb_vcp_send_strn(str, strlen(str));
+}
+
+void usb_vcp_send_strn(const char* str, int len)
+{
+ usb_serial_write(str, len);
+}
+
+void usb_vcp_send_strn_cooked(const char *str, int len)
+{
+ for (const char *top = str + len; str < top; str++) {
+ if (*str == '\n') {
+ usb_serial_putchar('\r');
+ }
+ usb_serial_putchar(*str);
+ }
+}
diff --git a/ports/teensy/usb.h b/ports/teensy/usb.h
new file mode 100644
index 000000000..50fb3ff90
--- /dev/null
+++ b/ports/teensy/usb.h
@@ -0,0 +1,12 @@
+#ifndef MICROPY_INCLUDED_TEENSY_USB_H
+#define MICROPY_INCLUDED_TEENSY_USB_H
+
+bool usb_vcp_is_connected(void);
+bool usb_vcp_is_enabled(void);
+int usb_vcp_rx_num(void);
+int usb_vcp_recv_byte(uint8_t *ptr);
+void usb_vcp_send_str(const char* str);
+void usb_vcp_send_strn(const char* str, int len);
+void usb_vcp_send_strn_cooked(const char *str, int len);
+
+#endif // MICROPY_INCLUDED_TEENSY_USB_H