Merge "Finish pistol grip controller board layout"
diff --git a/NO_BUILD_AMD64 b/NO_BUILD_AMD64
index 69ace36..6189481 100644
--- a/NO_BUILD_AMD64
+++ b/NO_BUILD_AMD64
@@ -27,3 +27,4 @@
 -//y2017:wpilib_interface
 -//y2017:download_stripped
 -//y2017:download
+-//motors/...
diff --git a/NO_BUILD_ROBORIO b/NO_BUILD_ROBORIO
index e7d0de1..780d909 100644
--- a/NO_BUILD_ROBORIO
+++ b/NO_BUILD_ROBORIO
@@ -15,3 +15,4 @@
 -//third_party/protobuf/...
 -//y2016_bot3/...
 -//y2017/control_loops/python/...
+-//motors/...
diff --git a/WORKSPACE b/WORKSPACE
index 4db4ba8..dc5e2da 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -117,3 +117,9 @@
   url = 'http://frc971.org/Build-Dependencies/empty.tar.gz',
   sha256 = '71939a7d75585a57d2e99a33d39f391764d8f930f9a16acf32e00c5d3f432aa0',
 )
+
+new_local_repository(
+  name = 'libusb',
+  path = '/usr',
+  build_file = 'debian/libusb.BUILD',
+)
diff --git a/aos/BUILD b/aos/BUILD
index 5d6831a..89948ab 100644
--- a/aos/BUILD
+++ b/aos/BUILD
@@ -34,3 +34,29 @@
     '//aos/common/logging:binary_log_writer.stripped',
   ],
 )
+
+cc_library(
+  name = 'once',
+  visibility = ['//visibility:public'],
+  hdrs = [
+    'once.h',
+  ],
+  srcs = [
+    'once-tmpl.h',
+  ],
+  deps = [
+    '//aos/common:gtest_prod',
+    '//aos/common:type_traits',
+  ],
+)
+cc_test(
+  name = 'once_test',
+  visibility = ['//visibility:public'],
+  srcs = [
+    'once_test.cc',
+  ],
+  deps = [
+    '//aos/testing:googletest',
+    '//aos:once',
+  ],
+)
diff --git a/aos/build/queues.bzl b/aos/build/queues.bzl
index 91b4978..8696bac 100644
--- a/aos/build/queues.bzl
+++ b/aos/build/queues.bzl
@@ -100,7 +100,7 @@
     srcs = [src + '.cc' for src in srcs],
     hdrs = [src + '.h' for src in srcs],
     deps = deps + [
-      '//aos/common:once',
+      '//aos:once',
       '//aos/common:queues',
       '//aos/common:queue_types',
       '//aos/common/logging:printf_formats',
diff --git a/aos/build/queues/compiler.rb b/aos/build/queues/compiler.rb
index 0b60b0e..5164670 100644
--- a/aos/build/queues/compiler.rb
+++ b/aos/build/queues/compiler.rb
@@ -106,7 +106,7 @@
   cpp_tree.add_cc_include("aos/common/byteorder.h".inspect)
   cpp_tree.add_cc_include("<inttypes.h>")
   cpp_tree.add_cc_include("aos/common/queue_types.h".inspect)
-  cpp_tree.add_cc_include("aos/common/once.h".inspect)
+  cpp_tree.add_cc_include("aos/once.h".inspect)
   cpp_tree.add_cc_include("aos/common/logging/printf_formats.h".inspect)
   cpp_tree.add_cc_using("::aos::to_network")
   cpp_tree.add_cc_using("::aos::to_host")
diff --git a/aos/common/BUILD b/aos/common/BUILD
index f4b57d5..e3160c4 100644
--- a/aos/common/BUILD
+++ b/aos/common/BUILD
@@ -200,31 +200,6 @@
   ],
 )
 
-cc_library(
-  name = 'once',
-  hdrs = [
-    'once.h',
-  ],
-  srcs = [
-    'once-tmpl.h',
-  ],
-  deps = [
-    ':gtest_prod',
-    ':type_traits',
-  ],
-)
-
-cc_test(
-  name = 'once_test',
-  srcs = [
-    'once_test.cc',
-  ],
-  deps = [
-    '//aos/testing:googletest',
-    ':once',
-  ],
-)
-
 cc_test(
   name = 'time_test',
   srcs = [
diff --git a/aos/common/controls/control_loop_test.h b/aos/common/controls/control_loop_test.h
index 88ccfa5..6fae706 100644
--- a/aos/common/controls/control_loop_test.h
+++ b/aos/common/controls/control_loop_test.h
@@ -25,7 +25,9 @@
   // Sends out all of the required queue messages.
   void SendMessages(bool enabled);
   // Ticks time for a single control loop cycle.
-  void TickTime() { ::aos::time::SetMockTime(current_time_ += kTimeTick); }
+  void TickTime(::std::chrono::nanoseconds dt = kTimeTick) {
+    ::aos::time::SetMockTime(current_time_ += dt);
+  }
 
   // Simulates everything that happens during 1 loop time step.
   void SimulateTimestep(bool enabled) {
diff --git a/aos/common/logging/BUILD b/aos/common/logging/BUILD
index 8b28482..cc961b3 100644
--- a/aos/common/logging/BUILD
+++ b/aos/common/logging/BUILD
@@ -182,7 +182,7 @@
   deps = [
     '//aos/common:die',
     '//aos/common:time',
-    '//aos/common:once',
+    '//aos:once',
     '//aos/common:queue_types',
     ':logging',
     '//aos/common:type_traits',
diff --git a/aos/common/logging/implementations.cc b/aos/common/logging/implementations.cc
index 22cd4f4..58359f9 100644
--- a/aos/common/logging/implementations.cc
+++ b/aos/common/logging/implementations.cc
@@ -7,11 +7,11 @@
 #include <chrono>
 
 #include "aos/common/die.h"
-#include "aos/common/once.h"
-#include "aos/common/time.h"
-#include "aos/common/queue_types.h"
 #include "aos/common/logging/printf_formats.h"
+#include "aos/common/queue_types.h"
+#include "aos/common/time.h"
 #include "aos/linux_code/ipc_lib/queue.h"
+#include "aos/once.h"
 
 namespace aos {
 namespace logging {
diff --git a/aos/common/logging/implementations.h b/aos/common/logging/implementations.h
index 48b5f0b..142c6ba 100644
--- a/aos/common/logging/implementations.h
+++ b/aos/common/logging/implementations.h
@@ -13,14 +13,14 @@
 #include <functional>
 #include <atomic>
 
-#include "aos/common/logging/logging.h"
-#include "aos/common/type_traits.h"
-#include "aos/common/mutex.h"
-#include "aos/common/macros.h"
-#include "aos/common/logging/sizes.h"
-#include "aos/common/logging/interface.h"
 #include "aos/common/logging/context.h"
-#include "aos/common/once.h"
+#include "aos/common/logging/interface.h"
+#include "aos/common/logging/logging.h"
+#include "aos/common/logging/sizes.h"
+#include "aos/common/macros.h"
+#include "aos/common/mutex.h"
+#include "aos/common/type_traits.h"
+#include "aos/once.h"
 
 namespace aos {
 
diff --git a/aos/common/network/BUILD b/aos/common/network/BUILD
index 19335ba..c5476b2 100644
--- a/aos/common/network/BUILD
+++ b/aos/common/network/BUILD
@@ -10,7 +10,7 @@
   ],
   deps = [
     '//aos/linux_code:configuration',
-    '//aos/common:once',
+    '//aos:once',
     '//aos/common/logging',
     '//aos/common/util:string_to_num',
   ],
diff --git a/aos/common/network/team_number.cc b/aos/common/network/team_number.cc
index 4aa7626..0669601 100644
--- a/aos/common/network/team_number.cc
+++ b/aos/common/network/team_number.cc
@@ -7,10 +7,10 @@
 
 #include <string>
 
-#include "aos/common/once.h"
-#include "aos/linux_code/configuration.h"
 #include "aos/common/logging/logging.h"
 #include "aos/common/util/string_to_num.h"
+#include "aos/linux_code/configuration.h"
+#include "aos/once.h"
 
 namespace aos {
 namespace network {
diff --git a/aos/linux_code/BUILD b/aos/linux_code/BUILD
index 7adb3d6..0b76e2c 100644
--- a/aos/linux_code/BUILD
+++ b/aos/linux_code/BUILD
@@ -29,7 +29,7 @@
     'complex_thread_local.h',
   ],
   deps = [
-    '//aos/common:once',
+    '//aos:once',
     '//aos/common:die',
     '//debian:libpthread',
   ],
@@ -72,7 +72,7 @@
     'configuration.h',
   ],
   deps = [
-    '//aos/common:once',
+    '//aos:once',
     '//aos/common/logging',
     '//aos/common:unique_malloc_ptr',
   ],
diff --git a/aos/linux_code/complex_thread_local.cc b/aos/linux_code/complex_thread_local.cc
index d57323e..f5ddc9c 100644
--- a/aos/linux_code/complex_thread_local.cc
+++ b/aos/linux_code/complex_thread_local.cc
@@ -2,8 +2,8 @@
 
 #include <pthread.h>
 
-#include "aos/common/once.h"
 #include "aos/common/die.h"
+#include "aos/once.h"
 
 #define SIMPLE_CHECK(call)              \
   do {                                  \
diff --git a/aos/linux_code/configuration.cc b/aos/linux_code/configuration.cc
index e4d5d80..0536e25 100644
--- a/aos/linux_code/configuration.cc
+++ b/aos/linux_code/configuration.cc
@@ -10,7 +10,7 @@
 
 #include "aos/common/logging/logging.h"
 #include "aos/common/unique_malloc_ptr.h"
-#include "aos/common/once.h"
+#include "aos/once.h"
 
 namespace aos {
 namespace configuration {
diff --git a/aos/linux_code/ipc_lib/BUILD b/aos/linux_code/ipc_lib/BUILD
index 95b30ce..b0b58ff 100644
--- a/aos/linux_code/ipc_lib/BUILD
+++ b/aos/linux_code/ipc_lib/BUILD
@@ -13,7 +13,7 @@
   ],
   deps = [
     '//aos/common/logging',
-    '//aos/common:once',
+    '//aos:once',
     '//aos/common:macros',
     '//aos/common/util:compiler_memory_barrier',
   ],
diff --git a/aos/linux_code/ipc_lib/aos_sync.cc b/aos/linux_code/ipc_lib/aos_sync.cc
index b0b560e..3c1debb 100644
--- a/aos/linux_code/ipc_lib/aos_sync.cc
+++ b/aos/linux_code/ipc_lib/aos_sync.cc
@@ -27,9 +27,9 @@
 #include <type_traits>
 
 #include "aos/common/logging/logging.h"
-#include "aos/common/once.h"
 #include "aos/common/macros.h"
 #include "aos/common/util/compiler_memory_barrier.h"
+#include "aos/once.h"
 
 using ::aos::linux_code::ipc_lib::FutexAccessorObserver;
 
diff --git a/aos/linux_code/starter/BUILD b/aos/linux_code/starter/BUILD
index ec6ce7f..74af77d 100644
--- a/aos/linux_code/starter/BUILD
+++ b/aos/linux_code/starter/BUILD
@@ -18,7 +18,7 @@
     '//third_party/libevent',
     '//aos/common/logging',
     '//aos/common/logging:implementations',
-    '//aos/common:once',
+    '//aos:once',
     '//aos/common:time',
     '//aos/common/libc:aos_strsignal',
     '//aos/common/util:run_command',
diff --git a/aos/linux_code/starter/starter.cc b/aos/linux_code/starter/starter.cc
index 57d90dd..62e540b 100644
--- a/aos/linux_code/starter/starter.cc
+++ b/aos/linux_code/starter/starter.cc
@@ -29,14 +29,14 @@
 
 #include "third_party/libevent/event.h"
 
-#include "aos/common/logging/logging.h"
-#include "aos/common/logging/implementations.h"
-#include "aos/linux_code/init.h"
-#include "aos/common/unique_malloc_ptr.h"
-#include "aos/common/time.h"
-#include "aos/common/once.h"
 #include "aos/common/libc/aos_strsignal.h"
+#include "aos/common/logging/implementations.h"
+#include "aos/common/logging/logging.h"
+#include "aos/common/time.h"
+#include "aos/common/unique_malloc_ptr.h"
 #include "aos/common/util/run_command.h"
+#include "aos/linux_code/init.h"
+#include "aos/once.h"
 
 // This is the main piece of code that starts all of the rest of the code and
 // restarts it when the binaries are modified.
diff --git a/aos/common/once-tmpl.h b/aos/once-tmpl.h
similarity index 100%
rename from aos/common/once-tmpl.h
rename to aos/once-tmpl.h
diff --git a/aos/common/once.h b/aos/once.h
similarity index 94%
rename from aos/common/once.h
rename to aos/once.h
index b7fbcb1..f6954f6 100644
--- a/aos/common/once.h
+++ b/aos/once.h
@@ -1,5 +1,5 @@
-#ifndef AOS_COMMON_ONCE_H_
-#define AOS_COMMON_ONCE_H_
+#ifndef AOS_ONCE_H_
+#define AOS_ONCE_H_
 
 #include <stdint.h>
 
@@ -64,6 +64,6 @@
 
 }  // namespace aos
 
-#include "aos/common/once-tmpl.h"
+#include "aos/once-tmpl.h"
 
-#endif  // AOS_COMMON_ONCE_H_
+#endif  // AOS_ONCE_H_
diff --git a/aos/common/once_test.cc b/aos/once_test.cc
similarity index 98%
rename from aos/common/once_test.cc
rename to aos/once_test.cc
index 3773b5b..0a36643 100644
--- a/aos/common/once_test.cc
+++ b/aos/once_test.cc
@@ -1,4 +1,4 @@
-#include "aos/common/once.h"
+#include "aos/once.h"
 
 #include <stdlib.h>
 #include <limits.h>
diff --git a/aos/testing/BUILD b/aos/testing/BUILD
index a8dce04..4f2fc83 100644
--- a/aos/testing/BUILD
+++ b/aos/testing/BUILD
@@ -22,7 +22,7 @@
   deps = [
     ':googletest',
     '//aos/common/logging:implementations',
-    '//aos/common:once',
+    '//aos:once',
     '//aos/common:mutex',
   ],
   testonly = True,
diff --git a/aos/testing/test_logging.cc b/aos/testing/test_logging.cc
index cdbec94..617f02a 100644
--- a/aos/testing/test_logging.cc
+++ b/aos/testing/test_logging.cc
@@ -7,8 +7,8 @@
 #include "gtest/gtest.h"
 
 #include "aos/common/logging/implementations.h"
-#include "aos/common/once.h"
 #include "aos/common/mutex.h"
+#include "aos/once.h"
 
 using ::aos::logging::LogMessage;
 
diff --git a/debian/libusb.BUILD b/debian/libusb.BUILD
new file mode 100644
index 0000000..3ccffe1
--- /dev/null
+++ b/debian/libusb.BUILD
@@ -0,0 +1,13 @@
+cc_library(
+  name = 'libusb',
+  visibility = ['//visibility:public'],
+  srcs = [
+    'lib/x86_64-linux-gnu/libusb.so',
+  ],
+  hdrs = [
+    'include/usb.h',
+  ],
+  includes = [
+    'include',
+  ],
+)
diff --git a/frc971/wpilib/buffered_pcm.cc b/frc971/wpilib/buffered_pcm.cc
index 54174c5..5f1dc67 100644
--- a/frc971/wpilib/buffered_pcm.cc
+++ b/frc971/wpilib/buffered_pcm.cc
@@ -12,7 +12,7 @@
       new BufferedSolenoid(number, this));
 }
 
-void BufferedPcm::Set(int number, bool value) {
+void BufferedPcm::DoSet(int number, bool value) {
   if (value) {
     values_ |= 1 << number;
   } else {
diff --git a/frc971/wpilib/buffered_pcm.h b/frc971/wpilib/buffered_pcm.h
index 09bf95f..4ff625b 100644
--- a/frc971/wpilib/buffered_pcm.h
+++ b/frc971/wpilib/buffered_pcm.h
@@ -33,7 +33,7 @@
   virtual void InitSolenoid() override {}
 #endif
 
-  void Set(int number, bool value);
+  void DoSet(int number, bool value);
 
   uint8_t values_ = 0;
 
diff --git a/frc971/wpilib/buffered_solenoid.cc b/frc971/wpilib/buffered_solenoid.cc
index cd68da8..c07a7cd 100644
--- a/frc971/wpilib/buffered_solenoid.cc
+++ b/frc971/wpilib/buffered_solenoid.cc
@@ -6,7 +6,7 @@
 namespace wpilib {
 
 void BufferedSolenoid::Set(bool value) {
-  pcm_->Set(number_, value);
+  pcm_->DoSet(number_, value);
 }
 
 }  // namespace wpilib
diff --git a/motors/BUILD b/motors/BUILD
new file mode 100644
index 0000000..defd1f9
--- /dev/null
+++ b/motors/BUILD
@@ -0,0 +1,31 @@
+cc_binary(
+  name = 'medium_salsa.elf',
+  srcs = [
+    'medium_salsa.cc',
+  ],
+  deps = [
+    ':util',
+    '//motors/core',
+    '//motors/usb',
+  ],
+)
+
+genrule(
+  name = 'medium_salsa',
+  srcs = [
+    'medium_salsa.elf',
+  ],
+  outs = [
+    'medium_salsa.hex',
+  ],
+  cmd = '$(OBJCOPY) -O ihex $<  $@',
+  executable = True,
+  output_to_bindir = True,
+)
+
+cc_library(
+  name = 'util',
+  hdrs = [
+    'util.h',
+  ],
+)
diff --git a/motors/core/BUILD b/motors/core/BUILD
new file mode 100644
index 0000000..3172461
--- /dev/null
+++ b/motors/core/BUILD
@@ -0,0 +1,20 @@
+filegroup(
+  name = 'linkerscript',
+  visibility = ['//tools/cpp:__pkg__'],
+  srcs = [ 'mk64fx512.ld' ],
+)
+
+cc_library(
+  name = 'core',
+  visibility = ['//visibility:public'],
+  hdrs = [
+    'kinetis.h',
+    'nonstd.h',
+    'time.h',
+  ],
+  srcs = [
+    'mk20dx128.c',
+    'nonstd.c',
+    'time.c',
+  ],
+)
diff --git a/motors/core/kinetis.h b/motors/core/kinetis.h
index b89b350..36ab5f2 100644
--- a/motors/core/kinetis.h
+++ b/motors/core/kinetis.h
@@ -762,100 +762,6 @@
 #endif // end of board-specific definitions
 
 
-#if (F_CPU == 240000000)
- #define F_PLL 240000000
- #ifndef F_BUS
- #define F_BUS 60000000
- //#define F_BUS 80000000   // uncomment these to try peripheral overclocking
- //#define F_BUS 120000000  // all the usual overclocking caveats apply...
- #endif
- #define F_MEM 30000000
-#elif (F_CPU == 216000000)
- #define F_PLL 216000000
- #ifndef F_BUS
- #define F_BUS 54000000
- //#define F_BUS 72000000
- //#define F_BUS 108000000
- #endif
- #define F_MEM 27000000
-#elif (F_CPU == 192000000)
- #define F_PLL 192000000
- #ifndef F_BUS
- #define F_BUS 48000000
- //#define F_BUS 64000000
- //#define F_BUS 96000000
- #endif
- #define F_MEM 27428571
-#elif (F_CPU == 180000000)
- #define F_PLL 180000000
- #ifndef F_BUS
- #define F_BUS 60000000
- //#define F_BUS 90000000
- #endif
- #define F_MEM 25714286
-#elif (F_CPU == 168000000)
- #define F_PLL 168000000
- #define F_BUS 56000000
- #define F_MEM 28000000
-#elif (F_CPU == 144000000)
- #define F_PLL 144000000
- #ifndef F_BUS
- #define F_BUS 48000000
- //#define F_BUS 72000000
- #endif
- #define F_MEM 28800000
-#elif (F_CPU == 120000000)
- #define F_PLL 120000000
- #ifndef F_BUS
- #define F_BUS 60000000
- //#define F_BUS 120000000
- #endif
- #define F_MEM 24000000
-#elif (F_CPU == 96000000)
- #define F_PLL 96000000
- #ifndef F_BUS
- #define F_BUS 48000000
- //#define F_BUS 96000000
- #endif
- #define F_MEM 24000000
-#elif (F_CPU == 72000000)
- #define F_PLL 72000000
- #ifndef F_BUS
- #define F_BUS 36000000
- //#define F_BUS 72000000
- #endif
- #define F_MEM 24000000
-#elif (F_CPU == 48000000)
- #define F_PLL 96000000
- #if defined(KINETISK)
- #define F_BUS 48000000
- #elif defined(KINETISL)
- #define F_BUS 24000000
- #endif
- #define F_MEM 24000000
-#elif (F_CPU == 24000000)
- #define F_PLL 96000000
- #define F_BUS 24000000
- #define F_MEM 24000000
-#elif (F_CPU == 16000000)
- #define F_PLL 16000000
- #define F_BUS 16000000
- #define F_MEM 16000000
-#elif (F_CPU == 8000000)
- #define F_PLL 8000000
- #define F_BUS 8000000
- #define F_MEM 8000000
-#elif (F_CPU == 4000000)
- #define F_PLL 4000000
- #define F_BUS 4000000
- #define F_MEM 4000000
-#elif (F_CPU == 2000000)
- #define F_PLL 2000000
- #define F_BUS 2000000
- #define F_MEM 1000000
-#endif
-
-
 #ifndef NULL
 #define NULL (0)
 #endif
@@ -5650,7 +5556,7 @@
 // Cortex-M0: 0,64,128,192
 #ifdef KINETISK
 #define NVIC_SET_PRIORITY(irqnum, priority)  (*((volatile uint8_t *)0xE000E400 + (irqnum)) = (uint8_t)(priority))
-#define NVIC_GET_PRIORITY(irqnum) (*((uint8_t *)0xE000E400 + (irqnum)))
+#define NVIC_GET_PRIORITY(irqnum) (*((volatile uint8_t *)0xE000E400 + (irqnum)))
 #else
 #define NVIC_SET_PRIORITY(irqnum, priority) (*((uint32_t *)0xE000E400 + ((irqnum) >> 2)) = (*((uint32_t *)0xE000E400 + ((irqnum) >> 2)) & (~(0xFF << (8 * ((irqnum) & 3))))) | (((priority) & 0xFF) << (8 * ((irqnum) & 3))))
 #define NVIC_GET_PRIORITY(irqnum) (*((uint32_t *)0xE000E400 + ((irqnum) >> 2)) >> (8 * ((irqnum) & 3)) & 255)
@@ -5711,7 +5617,6 @@
 #ifdef __cplusplus
 extern "C" {
 #endif
-extern int nvic_execution_priority(void);
 
 #if defined(HAS_KINETIS_HSRUN) && F_CPU > 120000000
 extern int kinetis_hsrun_disable(void);
diff --git a/motors/core/mk20dx128.c b/motors/core/mk20dx128.c
index 5408f87..9709a11 100644
--- a/motors/core/mk20dx128.c
+++ b/motors/core/mk20dx128.c
@@ -28,11 +28,9 @@
  * SOFTWARE.
  */
 
-#include "kinetis.h"
-#include "core_pins.h" // testing only
-#include "ser_print.h" // testing only
-#include <errno.h>
+#include "motors/core/kinetis.h"
 
+#include <errno.h>
 
 // Flash Security Setting. On Teensy 3.2, you can lock the MK20 chip to prevent
 // anyone from reading your code.  You CAN still reprogram your Teensy while
@@ -45,13 +43,13 @@
 // Special care must be used with the Program button, because it must be made
 // accessible to initiate reprogramming, but it must not be accidentally
 // pressed when Teensy Loader is not being used to reprogram.  To set lock the
-// security change this to 0xDC.  Teensy 3.0 and 3.1 do not support security lock.
+// security change this to 0xDC.  Teensy 3.0 and 3.1 do not support security
+// lock.
 #define FSEC 0xDE
 
 // Flash Options
 #define FOPT 0xF9
 
-
 extern unsigned long _stext;
 extern unsigned long _etext;
 extern unsigned long _sdata;
@@ -59,1285 +57,671 @@
 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);
+extern int main(void);
 void ResetHandler(void);
-void _init_Teensyduino_internal_(void) __attribute__((noinline));
 void __libc_init_array(void);
 
-
-void fault_isr(void)
-{
-#if 0
-	uint32_t addr;
-
-	SIM_SCGC4 |= 0x00000400;
-	UART0_BDH = 0;
-	UART0_BDL = 26; // 115200 at 48 MHz
-	UART0_C2 = UART_C2_TE;
-	PORTB_PCR17 = PORT_PCR_MUX(3);
-	ser_print("\nfault: \n??: ");
-        asm("ldr %0, [sp, #52]" : "=r" (addr) ::);
-        ser_print_hex32(addr);
-        ser_print("\n??: ");
-        asm("ldr %0, [sp, #48]" : "=r" (addr) ::);
-        ser_print_hex32(addr);
-        ser_print("\n??: ");
-        asm("ldr %0, [sp, #44]" : "=r" (addr) ::);
-        ser_print_hex32(addr);
-        ser_print("\npsr:");
-        asm("ldr %0, [sp, #40]" : "=r" (addr) ::);
-        ser_print_hex32(addr);
-        ser_print("\nadr:");
-        asm("ldr %0, [sp, #36]" : "=r" (addr) ::);
-        ser_print_hex32(addr);
-        ser_print("\nlr: ");
-        asm("ldr %0, [sp, #32]" : "=r" (addr) ::);
-        ser_print_hex32(addr);
-        ser_print("\nr12:");
-        asm("ldr %0, [sp, #28]" : "=r" (addr) ::);
-        ser_print_hex32(addr);
-        ser_print("\nr3: ");
-        asm("ldr %0, [sp, #24]" : "=r" (addr) ::);
-        ser_print_hex32(addr);
-        ser_print("\nr2: ");
-        asm("ldr %0, [sp, #20]" : "=r" (addr) ::);
-        ser_print_hex32(addr);
-        ser_print("\nr1: ");
-        asm("ldr %0, [sp, #16]" : "=r" (addr) ::);
-        ser_print_hex32(addr);
-        ser_print("\nr0: ");
-        asm("ldr %0, [sp, #12]" : "=r" (addr) ::);
-        ser_print_hex32(addr);
-        ser_print("\nr4: ");
-        asm("ldr %0, [sp, #8]" : "=r" (addr) ::);
-        ser_print_hex32(addr);
-        ser_print("\nlr: ");
-        asm("ldr %0, [sp, #4]" : "=r" (addr) ::);
-        ser_print_hex32(addr);
-        ser_print("\n");
-        asm("ldr %0, [sp, #0]" : "=r" (addr) ::);
-#endif
-	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 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();
-}
+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("fault_isr")));
-void memmanage_fault_isr(void)	__attribute__ ((weak, alias("fault_isr")));
-void bus_fault_isr(void)	__attribute__ ((weak, alias("fault_isr")));
-void usage_fault_isr(void)	__attribute__ ((weak, alias("fault_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 nmi_isr(void) __attribute__((weak, alias("unused_isr")));
+void hard_fault_isr(void) __attribute__((weak, alias("fault_isr")));
+void memmanage_fault_isr(void) __attribute__((weak, alias("fault_isr")));
+void bus_fault_isr(void) __attribute__((weak, alias("fault_isr")));
+void usage_fault_isr(void) __attribute__((weak, alias("fault_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) { systick_millis_count++; }
 
-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 randnum_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 i2c3_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 enet_timer_isr(void)	__attribute__ ((weak, alias("unused_isr")));
-void enet_tx_isr(void)		__attribute__ ((weak, alias("unused_isr")));
-void enet_rx_isr(void)		__attribute__ ((weak, alias("unused_isr")));
-void enet_error_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 can1_message_isr(void)	__attribute__ ((weak, alias("unused_isr")));
-void can1_bus_off_isr(void)	__attribute__ ((weak, alias("unused_isr")));
-void can1_error_isr(void)	__attribute__ ((weak, alias("unused_isr")));
-void can1_tx_warn_isr(void)	__attribute__ ((weak, alias("unused_isr")));
-void can1_rx_warn_isr(void)	__attribute__ ((weak, alias("unused_isr")));
-void can1_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 i2s0_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 lpuart0_status_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 cmp3_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 tpm0_isr(void)		__attribute__ ((weak, alias("unused_isr")));
-void tpm1_isr(void)		__attribute__ ((weak, alias("unused_isr")));
-void tpm2_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 pit_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 usbhs_isr(void)		__attribute__ ((weak, alias("unused_isr")));
-void usbhs_phy_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 portcd_isr(void)		__attribute__ ((weak, alias("unused_isr")));
-void software_isr(void)		__attribute__ ((weak, alias("unused_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 randnum_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 i2c3_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 enet_timer_isr(void) __attribute__((weak, alias("unused_isr")));
+void enet_tx_isr(void) __attribute__((weak, alias("unused_isr")));
+void enet_rx_isr(void) __attribute__((weak, alias("unused_isr")));
+void enet_error_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 can1_message_isr(void) __attribute__((weak, alias("unused_isr")));
+void can1_bus_off_isr(void) __attribute__((weak, alias("unused_isr")));
+void can1_error_isr(void) __attribute__((weak, alias("unused_isr")));
+void can1_tx_warn_isr(void) __attribute__((weak, alias("unused_isr")));
+void can1_rx_warn_isr(void) __attribute__((weak, alias("unused_isr")));
+void can1_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 i2s0_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 lpuart0_status_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 cmp3_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 tpm0_isr(void) __attribute__((weak, alias("unused_isr")));
+void tpm1_isr(void) __attribute__((weak, alias("unused_isr")));
+void tpm2_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 pit_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 usbhs_isr(void) __attribute__((weak, alias("unused_isr")));
+void usbhs_phy_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 portcd_isr(void) __attribute__((weak, alias("unused_isr")));
+void software_isr(void) __attribute__((weak, alias("unused_isr")));
 
-#if defined(__MK20DX128__)
-__attribute__ ((section(".dmabuffers"), used, aligned(256)))
-#elif defined(__MK20DX256__)
-__attribute__ ((section(".dmabuffers"), used, aligned(512)))
-#elif defined(__MKL26Z64__)
-__attribute__ ((section(".dmabuffers"), used, aligned(256)))
+__attribute__((section(".dmabuffers"), used, aligned(512))) void (
+    *_VectorsRam[NVIC_NUM_INTERRUPTS + 16])(void);
+
+__attribute__((section(".vectors"), used)) void (
+    *const _VectorsFlash[NVIC_NUM_INTERRUPTS + 16])(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(__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 11 transfer complete
+    dma_ch12_isr,      // 28 DMA channel 12 transfer complete
+    dma_ch13_isr,      // 29 DMA channel 13 transfer complete
+    dma_ch14_isr,      // 30 DMA channel 14 transfer complete
+    dma_ch15_isr,      // 31 DMA channel 15 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
 #elif defined(__MK64FX512__)
-__attribute__ ((section(".dmabuffers"), used, aligned(512)))
-#elif defined(__MK66FX1M0__)
-__attribute__ ((section(".dmabuffers"), used, aligned(512)))
-#endif
-void (* _VectorsRam[NVIC_NUM_INTERRUPTS+16])(void);
-
-__attribute__ ((section(".vectors"), used))
-void (* const _VectorsFlash[NVIC_NUM_INTERRUPTS+16])(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 11 transfer complete
-	dma_ch12_isr,					// 28 DMA channel 12 transfer complete
-	dma_ch13_isr,					// 29 DMA channel 13 transfer complete
-	dma_ch14_isr,					// 30 DMA channel 14 transfer complete
-	dma_ch15_isr,					// 31 DMA channel 15 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
-#elif defined(__MKL26Z64__)
-	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
-	unused_isr,					// 20 --
-	flash_cmd_isr,					// 21 Flash Memory Command complete
-	low_voltage_isr,				// 22 Low-voltage detect/warning
-	wakeup_isr,					// 23 Low Leakage Wakeup
-	i2c0_isr,					// 24 I2C0
-	i2c1_isr,					// 25 I2C1
-	spi0_isr,					// 26 SPI0
-	spi1_isr,					// 27 SPI1
-	uart0_status_isr,				// 28 UART0 status & error
-	uart1_status_isr,				// 29 UART1 status & error
-	uart2_status_isr,				// 30 UART2 status & error
-	adc0_isr,					// 31 ADC0
-	cmp0_isr,					// 32 CMP0
-	ftm0_isr,					// 33 FTM0
-	ftm1_isr,					// 34 FTM1
-	ftm2_isr,					// 35 FTM2
-	rtc_alarm_isr,					// 36 RTC Alarm interrupt
-	rtc_seconds_isr,				// 37 RTC Seconds interrupt
-	pit_isr,					// 38 PIT Both Channels
-	i2s0_isr,					// 39 I2S0 Transmit & Receive
-	usb_isr,					// 40 USB OTG
-	dac0_isr,					// 41 DAC0
-	tsi0_isr,					// 42 TSI0
-	mcg_isr,					// 43 MCG
-	lptmr_isr,					// 44 Low Power Timer
-	software_isr,					// 45 Software interrupt
-	porta_isr,					// 46 Pin detect (Port A)
-	portcd_isr,					// 47 Pin detect (Port C and D)
-#elif defined(__MK64FX512__)
-	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 11 transfer complete
-	dma_ch12_isr,					// 28 DMA channel 12 transfer complete
-	dma_ch13_isr,					// 29 DMA channel 13 transfer complete
-	dma_ch14_isr,					// 30 DMA channel 14 transfer complete
-	dma_ch15_isr,					// 31 DMA channel 15 transfer complete
-	dma_error_isr,					// 32 DMA error interrupt channel
-	mcm_isr,					// 33 MCM
-	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
-	randnum_isr,					// 39 Random Number Generator
-	i2c0_isr,					// 40 I2C0
-	i2c1_isr,					// 41 I2C1
-	spi0_isr,					// 42 SPI0
-	spi1_isr,					// 43 SPI1
-	i2s0_tx_isr,					// 44 I2S0 Transmit
-	i2s0_rx_isr,					// 45 I2S0 Receive
-	unused_isr,					// 46 --
-	uart0_status_isr,				// 47 UART0 status
-	uart0_error_isr,				// 48 UART0 error
-	uart1_status_isr,				// 49 UART1 status
-	uart1_error_isr,				// 50 UART1 error
-	uart2_status_isr,				// 51 UART2 status
-	uart2_error_isr,				// 52 UART2 error
-	uart3_status_isr,				// 53 UART3 status
-	uart3_error_isr,				// 54 UART3 error
-	adc0_isr,					// 55 ADC0
-	cmp0_isr,					// 56 CMP0
-	cmp1_isr,					// 57 CMP1
-	ftm0_isr,					// 58 FTM0
-	ftm1_isr,					// 59 FTM1
-	ftm2_isr,					// 60 FTM2
-	cmt_isr,					// 61 CMT
-	rtc_alarm_isr,					// 62 RTC Alarm interrupt
-	rtc_seconds_isr,				// 63 RTC Seconds interrupt
-	pit0_isr,					// 64 PIT Channel 0
-	pit1_isr,					// 65 PIT Channel 1
-	pit2_isr,					// 66 PIT Channel 2
-	pit3_isr,					// 67 PIT Channel 3
-	pdb_isr,					// 68 PDB Programmable Delay Block
-	usb_isr,					// 69 USB OTG
-	usb_charge_isr,					// 70 USB Charger Detect
-	unused_isr,					// 71 --
-	dac0_isr,					// 72 DAC0
-	mcg_isr,					// 73 MCG
-	lptmr_isr,					// 74 Low Power Timer
-	porta_isr,					// 75 Pin detect (Port A)
-	portb_isr,					// 76 Pin detect (Port B)
-	portc_isr,					// 77 Pin detect (Port C)
-	portd_isr,					// 78 Pin detect (Port D)
-	porte_isr,					// 79 Pin detect (Port E)
-	software_isr,					// 80 Software interrupt
-	spi2_isr,					// 81 SPI2
-	uart4_status_isr,				// 82 UART4 status
-	uart4_error_isr,				// 83 UART4 error
-	uart5_status_isr,				// 84 UART4 status
-	uart5_error_isr,				// 85 UART4 error
-	cmp2_isr,					// 86 CMP2
-	ftm3_isr,					// 87 FTM3
-	dac1_isr,					// 88 DAC1
-	adc1_isr,					// 89 ADC1
-	i2c2_isr,					// 90 I2C2
-	can0_message_isr,				// 91 CAN OR'ed Message buffer (0-15)
-	can0_bus_off_isr,				// 92 CAN Bus Off
-	can0_error_isr,					// 93 CAN Error
-	can0_tx_warn_isr,				// 94 CAN Transmit Warning
-	can0_rx_warn_isr,				// 95 CAN Receive Warning
-	can0_wakeup_isr,				// 96 CAN Wake Up
-	sdhc_isr,					// 97 SDHC
-	enet_timer_isr,					// 98 Ethernet IEEE1588 Timers
-	enet_tx_isr,					// 99 Ethernet Transmit
-	enet_rx_isr,					// 100 Ethernet Receive
-	enet_error_isr,					// 101 Ethernet Error
-#elif defined(__MK66FX1M0__)
-	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 11 transfer complete
-	dma_ch12_isr,					// 28 DMA channel 12 transfer complete
-	dma_ch13_isr,					// 29 DMA channel 13 transfer complete
-	dma_ch14_isr,					// 30 DMA channel 14 transfer complete
-	dma_ch15_isr,					// 31 DMA channel 15 transfer complete
-	dma_error_isr,					// 32 DMA error interrupt channel
-	mcm_isr,					// 33 MCM
-	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
-	randnum_isr,					// 39 Random Number Generator
-	i2c0_isr,					// 40 I2C0
-	i2c1_isr,					// 41 I2C1
-	spi0_isr,					// 42 SPI0
-	spi1_isr,					// 43 SPI1
-	i2s0_tx_isr,					// 44 I2S0 Transmit
-	i2s0_rx_isr,					// 45 I2S0 Receive
-	unused_isr,					// 46 --
-	uart0_status_isr,				// 47 UART0 status
-	uart0_error_isr,				// 48 UART0 error
-	uart1_status_isr,				// 49 UART1 status
-	uart1_error_isr,				// 50 UART1 error
-	uart2_status_isr,				// 51 UART2 status
-	uart2_error_isr,				// 52 UART2 error
-	uart3_status_isr,				// 53 UART3 status
-	uart3_error_isr,				// 54 UART3 error
-	adc0_isr,					// 55 ADC0
-	cmp0_isr,					// 56 CMP0
-	cmp1_isr,					// 57 CMP1
-	ftm0_isr,					// 58 FTM0
-	ftm1_isr,					// 59 FTM1
-	ftm2_isr,					// 60 FTM2
-	cmt_isr,					// 61 CMT
-	rtc_alarm_isr,					// 62 RTC Alarm interrupt
-	rtc_seconds_isr,				// 63 RTC Seconds interrupt
-	pit0_isr,					// 64 PIT Channel 0
-	pit1_isr,					// 65 PIT Channel 1
-	pit2_isr,					// 66 PIT Channel 2
-	pit3_isr,					// 67 PIT Channel 3
-	pdb_isr,					// 68 PDB Programmable Delay Block
-	usb_isr,					// 69 USB OTG
-	usb_charge_isr,					// 70 USB Charger Detect
-	unused_isr,					// 71 --
-	dac0_isr,					// 72 DAC0
-	mcg_isr,					// 73 MCG
-	lptmr_isr,					// 74 Low Power Timer
-	porta_isr,					// 75 Pin detect (Port A)
-	portb_isr,					// 76 Pin detect (Port B)
-	portc_isr,					// 77 Pin detect (Port C)
-	portd_isr,					// 78 Pin detect (Port D)
-	porte_isr,					// 79 Pin detect (Port E)
-	software_isr,					// 80 Software interrupt
-	spi2_isr,					// 81 SPI2
-	uart4_status_isr,				// 82 UART4 status
-	uart4_error_isr,				// 83 UART4 error
-	unused_isr,					// 84 --
-	unused_isr,					// 85 --
-	cmp2_isr,					// 86 CMP2
-	ftm3_isr,					// 87 FTM3
-	dac1_isr,					// 88 DAC1
-	adc1_isr,					// 89 ADC1
-	i2c2_isr,					// 90 I2C2
-	can0_message_isr,				// 91 CAN OR'ed Message buffer (0-15)
-	can0_bus_off_isr,				// 92 CAN Bus Off
-	can0_error_isr,					// 93 CAN Error
-	can0_tx_warn_isr,				// 94 CAN Transmit Warning
-	can0_rx_warn_isr,				// 95 CAN Receive Warning
-	can0_wakeup_isr,				// 96 CAN Wake Up
-	sdhc_isr,					// 97 SDHC
-	enet_timer_isr,					// 98 Ethernet IEEE1588 Timers
-	enet_tx_isr,					// 99 Ethernet Transmit
-	enet_rx_isr,					// 100 Ethernet Receive
-	enet_error_isr,					// 101 Ethernet Error
-	lpuart0_status_isr,				// 102 LPUART
-	tsi0_isr,					// 103 TSI0
-	tpm1_isr,					// 104 FTM1
-	tpm2_isr,					// 105 FTM2
-	usbhs_phy_isr,					// 106 USB-HS Phy
-	i2c3_isr,					// 107 I2C3
-	cmp3_isr,					// 108 CMP3
-	usbhs_isr,					// 109 USB-HS
-	can1_message_isr,				// 110 CAN OR'ed Message buffer (0-15)
-	can1_bus_off_isr,				// 111 CAN Bus Off
-	can1_error_isr,					// 112 CAN Error
-	can1_tx_warn_isr,				// 113 CAN Transmit Warning
-	can1_rx_warn_isr,				// 114 CAN Receive Warning
-	can1_wakeup_isr,				// 115 CAN Wake Up
+    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 11 transfer complete
+    dma_ch12_isr,      // 28 DMA channel 12 transfer complete
+    dma_ch13_isr,      // 29 DMA channel 13 transfer complete
+    dma_ch14_isr,      // 30 DMA channel 14 transfer complete
+    dma_ch15_isr,      // 31 DMA channel 15 transfer complete
+    dma_error_isr,     // 32 DMA error interrupt channel
+    mcm_isr,           // 33 MCM
+    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
+    randnum_isr,       // 39 Random Number Generator
+    i2c0_isr,          // 40 I2C0
+    i2c1_isr,          // 41 I2C1
+    spi0_isr,          // 42 SPI0
+    spi1_isr,          // 43 SPI1
+    i2s0_tx_isr,       // 44 I2S0 Transmit
+    i2s0_rx_isr,       // 45 I2S0 Receive
+    unused_isr,        // 46 --
+    uart0_status_isr,  // 47 UART0 status
+    uart0_error_isr,   // 48 UART0 error
+    uart1_status_isr,  // 49 UART1 status
+    uart1_error_isr,   // 50 UART1 error
+    uart2_status_isr,  // 51 UART2 status
+    uart2_error_isr,   // 52 UART2 error
+    uart3_status_isr,  // 53 UART3 status
+    uart3_error_isr,   // 54 UART3 error
+    adc0_isr,          // 55 ADC0
+    cmp0_isr,          // 56 CMP0
+    cmp1_isr,          // 57 CMP1
+    ftm0_isr,          // 58 FTM0
+    ftm1_isr,          // 59 FTM1
+    ftm2_isr,          // 60 FTM2
+    cmt_isr,           // 61 CMT
+    rtc_alarm_isr,     // 62 RTC Alarm interrupt
+    rtc_seconds_isr,   // 63 RTC Seconds interrupt
+    pit0_isr,          // 64 PIT Channel 0
+    pit1_isr,          // 65 PIT Channel 1
+    pit2_isr,          // 66 PIT Channel 2
+    pit3_isr,          // 67 PIT Channel 3
+    pdb_isr,           // 68 PDB Programmable Delay Block
+    usb_isr,           // 69 USB OTG
+    usb_charge_isr,    // 70 USB Charger Detect
+    unused_isr,        // 71 --
+    dac0_isr,          // 72 DAC0
+    mcg_isr,           // 73 MCG
+    lptmr_isr,         // 74 Low Power Timer
+    porta_isr,         // 75 Pin detect (Port A)
+    portb_isr,         // 76 Pin detect (Port B)
+    portc_isr,         // 77 Pin detect (Port C)
+    portd_isr,         // 78 Pin detect (Port D)
+    porte_isr,         // 79 Pin detect (Port E)
+    software_isr,      // 80 Software interrupt
+    spi2_isr,          // 81 SPI2
+    uart4_status_isr,  // 82 UART4 status
+    uart4_error_isr,   // 83 UART4 error
+    uart5_status_isr,  // 84 UART4 status
+    uart5_error_isr,   // 85 UART4 error
+    cmp2_isr,          // 86 CMP2
+    ftm3_isr,          // 87 FTM3
+    dac1_isr,          // 88 DAC1
+    adc1_isr,          // 89 ADC1
+    i2c2_isr,          // 90 I2C2
+    can0_message_isr,  // 91 CAN OR'ed Message buffer (0-15)
+    can0_bus_off_isr,  // 92 CAN Bus Off
+    can0_error_isr,    // 93 CAN Error
+    can0_tx_warn_isr,  // 94 CAN Transmit Warning
+    can0_rx_warn_isr,  // 95 CAN Receive Warning
+    can0_wakeup_isr,   // 96 CAN Wake Up
+    sdhc_isr,          // 97 SDHC
+    enet_timer_isr,    // 98 Ethernet IEEE1588 Timers
+    enet_tx_isr,       // 99 Ethernet Transmit
+    enet_rx_isr,       // 100 Ethernet Receive
+    enet_error_isr,    // 101 Ethernet Error
 #endif
 };
 
-
-__attribute__ ((section(".flashconfig"), used))
-const uint8_t flashconfigbytes[16] = {
-	0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
-	0xFF, 0xFF, 0xFF, 0xFF, FSEC, FOPT, 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_localtime; // Arduino build process sets this
-extern void rtc_set(unsigned long t);
-
-
-static void startup_default_early_hook(void) {
-#if defined(KINETISK)
-	WDOG_STCTRLH = WDOG_STCTRLH_ALLOWUPDATE;
-#elif defined(KINETISL)
-	SIM_COPC = 0;  // disable the watchdog
-#endif
-}
-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(".flashconfig"),
+               used)) const uint8_t flashconfigbytes[16] = {
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, FSEC, FOPT, 0xFF, 0xFF};
 
 #ifdef __clang__
 // Clang seems to generate slightly larger code with Os than gcc
-__attribute__ ((optimize("-Os")))
+__attribute__((optimize("-Os")))
 #else
-__attribute__ ((section(".startup"),optimize("-Os")))
+__attribute__((section(".startup"), optimize("-Os")))
 #endif
-void ResetHandler(void)
-{
-	uint32_t *src = &_etext;
-	uint32_t *dest = &_sdata;
-	unsigned int i;
-#if F_CPU <= 2000000
-	volatile int n;
-#endif
-	//volatile int count;
+void ResetHandler(void) {
+  uint32_t *src = &_etext;
+  uint32_t *dest = &_sdata;
+  unsigned int i;
 
-#ifdef KINETISK
-	WDOG_UNLOCK = WDOG_UNLOCK_SEQ1;
-	WDOG_UNLOCK = WDOG_UNLOCK_SEQ2;
-	__asm__ volatile ("nop");
-	__asm__ volatile ("nop");
-#endif
-	// programs using the watchdog timer or needing to initialize hardware as
-	// early as possible can implement startup_early_hook()
-	startup_early_hook();
+  WDOG_UNLOCK = WDOG_UNLOCK_SEQ1;
+  WDOG_UNLOCK = WDOG_UNLOCK_SEQ2;
+  __asm__ volatile("nop");
+  __asm__ volatile("nop");
 
-	// 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;
+  WDOG_STCTRLH = WDOG_STCTRLH_ALLOWUPDATE;
+
+  // enable clocks to always-used peripherals
+#if 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;
 #elif defined(__MK64FX512__) || defined(__MK66FX1M0__)
-	SIM_SCGC3 = SIM_SCGC3_ADC1 | SIM_SCGC3_FTM2 | SIM_SCGC3_FTM3;
-	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;
-	//PORTC_PCR5 = PORT_PCR_MUX(1) | PORT_PCR_DSE | PORT_PCR_SRE;
-	//GPIOC_PDDR |= (1<<5);
-	//GPIOC_PSOR = (1<<5);
-	//while (1);
-#elif defined(__MKL26Z64__)
-	SIM_SCGC4 = SIM_SCGC4_USBOTG | 0xF0000030;
-	SIM_SCGC5 = 0x00003F82;		// clocks active to all GPIO
-	SIM_SCGC6 = SIM_SCGC6_ADC0 | SIM_SCGC6_TPM0 | SIM_SCGC6_TPM1 | SIM_SCGC6_TPM2 | SIM_SCGC6_FTFL;
+  SIM_SCGC3 = SIM_SCGC3_ADC1 | SIM_SCGC3_FTM2 | SIM_SCGC3_FTM3;
+  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;
+  SCB_CPACR = 0x00F00000;
 #endif
-#if defined(__MK64FX512__) || defined(__MK66FX1M0__)
-	SCB_CPACR = 0x00F00000;
-#endif
-#if defined(__MK66FX1M0__)
-	LMEM_PCCCR = 0x85000003;
-#endif
-#if 0
-	// testing only, enable ser_print
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV4(1);
-	MCG_C4 |= MCG_C4_DMX32 | MCG_C4_DRST_DRS(1);
-	SIM_SOPT2 = SIM_SOPT2_UART0SRC(1) | SIM_SOPT2_TPMSRC(1);
-	SIM_SCGC4 |= 0x00000400;
-	UART0_BDH = 0;
-	UART0_BDL = 26; // 115200 at 48 MHz
-	UART0_C2 = UART_C2_TE;
-	PORTB_PCR17 = PORT_PCR_MUX(3);
-#endif
-#ifdef KINETISK
-	// 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;
-	}
-#endif
-	// release I/O pins hold, if we woke up from VLLS mode
-	if (PMC_REGSC & PMC_REGSC_ACKISO) PMC_REGSC |= PMC_REGSC_ACKISO;
+  // 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
-#if defined(__MK66FX1M0__)
-	SMC_PMPROT = SMC_PMPROT_AHSRUN | SMC_PMPROT_AVLP | SMC_PMPROT_ALLS | SMC_PMPROT_AVLLS;
+  // 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;
+
+  // default all interrupts to medium priority level
+  for (i = 0; i < NVIC_NUM_INTERRUPTS + 16; i++)
+    _VectorsRam[i] = _VectorsFlash[i];
+  for (i = 0; i < NVIC_NUM_INTERRUPTS; i++) NVIC_SET_PRIORITY(i, 128);
+  SCB_VTOR = (uint32_t)_VectorsRam;  // use vector table in RAM
+
+  // 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
+  // enable capacitors for crystal
+  OSC0_CR = OSC_SC8P | OSC_SC2P | OSC_ERCLKEN;
+  // 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 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
-	SMC_PMPROT = SMC_PMPROT_AVLP | SMC_PMPROT_ALLS | SMC_PMPROT_AVLLS;
+  MCG_C5 = MCG_C5_PRDIV0(3);               // config PLL input for 16 MHz Crystal / 4 = 4 MHz
 #endif
-    
-	// TODO: do this while the PLL is waiting to lock....
-	while (dest < &_edata) *dest++ = *src++;
-	dest = &_sbss;
-	while (dest < &_ebss) *dest++ = 0;
-
-	// default all interrupts to medium priority level
-	for (i=0; i < NVIC_NUM_INTERRUPTS + 16; i++) _VectorsRam[i] = _VectorsFlash[i];
-	for (i=0; i < NVIC_NUM_INTERRUPTS; i++) NVIC_SET_PRIORITY(i, 128);
-	SCB_VTOR = (uint32_t)_VectorsRam;	// use vector table in RAM
-
-	// 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
-    #if defined(KINETISK)
-    MCG_C1 = MCG_C1_CLKS(1) | MCG_C1_IREFS;
-    #elif defined(KINETISL)
-	// use the internal oscillator
-	MCG_C1 = MCG_C1_CLKS(1) | MCG_C1_IREFS | MCG_C1_IRCLKEN;
-    #endif
-	// 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
-    #if defined(KINETISK)
-    // enable capacitors for crystal
-    OSC0_CR = OSC_SC8P | OSC_SC2P | OSC_ERCLKEN;
-    #elif defined(KINETISL)
-    // enable capacitors for crystal
-    OSC0_CR = OSC_SC8P | OSC_SC2P | OSC_ERCLKEN;
-    #endif
-	// 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 defined(__MK66FX1M0__)
-    #if F_CPU > 120000000
-	SMC_PMCTRL = SMC_PMCTRL_RUNM(3); // enter HSRUN mode
-	while (SMC_PMSTAT != SMC_PMSTAT_HSRUN) ; // wait for HSRUN
-    #endif
-    #if F_CPU == 240000000
-	MCG_C5 = MCG_C5_PRDIV0(0);
-	MCG_C6 = MCG_C6_PLLS | MCG_C6_VDIV0(14);
-    #elif F_CPU == 216000000
-	MCG_C5 = MCG_C5_PRDIV0(0);
-	MCG_C6 = MCG_C6_PLLS | MCG_C6_VDIV0(11);
-    #elif F_CPU == 192000000
-	MCG_C5 = MCG_C5_PRDIV0(0);
-	MCG_C6 = MCG_C6_PLLS | MCG_C6_VDIV0(8);
-    #elif F_CPU == 180000000
-	MCG_C5 = MCG_C5_PRDIV0(1);
-	MCG_C6 = MCG_C6_PLLS | MCG_C6_VDIV0(29);
-    #elif F_CPU == 168000000
-	MCG_C5 = MCG_C5_PRDIV0(0);
-	MCG_C6 = MCG_C6_PLLS | MCG_C6_VDIV0(5);
-    #elif F_CPU == 144000000
-	MCG_C5 = MCG_C5_PRDIV0(0);
-	MCG_C6 = MCG_C6_PLLS | MCG_C6_VDIV0(2);
-    #elif F_CPU == 120000000
-	MCG_C5 = MCG_C5_PRDIV0(1);
-	MCG_C6 = MCG_C6_PLLS | MCG_C6_VDIV0(14);
-    #elif F_CPU == 96000000 || F_CPU == 48000000 || F_CPU == 24000000
-	MCG_C5 = MCG_C5_PRDIV0(1);
-	MCG_C6 = MCG_C6_PLLS | MCG_C6_VDIV0(8);
-    #elif F_CPU == 72000000
-	MCG_C5 = MCG_C5_PRDIV0(1);
-	MCG_C6 = MCG_C6_PLLS | MCG_C6_VDIV0(2);
-    #elif F_CPU > 16000000
-    #error "MK66FX1M0 does not support this clock speed yet...."
-    #endif
-   #else
-    #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
-    #elif F_CPU == 96000000 || F_CPU == 48000000 || F_CPU == 24000000
-	MCG_C6 = MCG_C6_PLLS | MCG_C6_VDIV0(0); // config PLL for 96 MHz output
-    #elif F_CPU > 16000000
-    #error "This clock speed isn't supported..."
-    #endif
-   #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 == 240000000
-	// config divisors: 240 MHz core, 60 MHz bus, 30 MHz flash, USB = 240 / 5
-	// TODO: gradual ramp-up for HSRUN mode
-	#if F_BUS == 60000000
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(3) | SIM_CLKDIV1_OUTDIV4(7);
-	#elif F_BUS == 80000000
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(2) | SIM_CLKDIV1_OUTDIV4(7);
-	#elif F_BUS == 120000000
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(1) | SIM_CLKDIV1_OUTDIV4(7);
-	#else
-	#error "This F_CPU & F_BUS combination is not supported"
-	#endif
-	SIM_CLKDIV2 = SIM_CLKDIV2_USBDIV(4);
-#elif F_CPU == 216000000
-	// config divisors: 216 MHz core, 54 MHz bus, 27 MHz flash, USB = IRC48M
-	// TODO: gradual ramp-up for HSRUN mode
-	#if F_BUS == 54000000
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(3) | SIM_CLKDIV1_OUTDIV4(7);
-	#elif F_BUS == 72000000
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(2) | SIM_CLKDIV1_OUTDIV4(7);
-	#elif F_BUS == 108000000
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(1) | SIM_CLKDIV1_OUTDIV4(7);
-	#else
-	#error "This F_CPU & F_BUS combination is not supported"
-	#endif
-	SIM_CLKDIV2 = SIM_CLKDIV2_USBDIV(0);
-#elif F_CPU == 192000000
-	// config divisors: 192 MHz core, 48 MHz bus, 27.4 MHz flash, USB = 192 / 4
-	// TODO: gradual ramp-up for HSRUN mode
-	#if F_BUS == 48000000
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(3) | SIM_CLKDIV1_OUTDIV4(6);
-	#elif F_BUS == 64000000
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(2) | SIM_CLKDIV1_OUTDIV4(6);
-	#elif F_BUS == 96000000
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(1) | SIM_CLKDIV1_OUTDIV4(6);
-	#else
-	#error "This F_CPU & F_BUS combination is not supported"
-	#endif
-	SIM_CLKDIV2 = SIM_CLKDIV2_USBDIV(3);
-#elif F_CPU == 180000000
-	// config divisors: 180 MHz core, 60 MHz bus, 25.7 MHz flash, USB = IRC48M
-	#if F_BUS == 60000000
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(2) | SIM_CLKDIV1_OUTDIV4(6);
-	#elif F_BUS == 90000000
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(1) | SIM_CLKDIV1_OUTDIV4(6);
-	#else
-	#error "This F_CPU & F_BUS combination is not supported"
-	#endif
-	SIM_CLKDIV2 = SIM_CLKDIV2_USBDIV(0);
-#elif F_CPU == 168000000
-	// config divisors: 168 MHz core, 56 MHz bus, 28 MHz flash, USB = 168 * 2 / 7
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(2) | SIM_CLKDIV1_OUTDIV4(5);
-	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
-	#if F_BUS == 48000000
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(2) | SIM_CLKDIV1_OUTDIV4(4);
-	#elif F_BUS == 72000000
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(1) | SIM_CLKDIV1_OUTDIV4(4);
-	#else
-	#error "This F_CPU & F_BUS combination is not supported"
-	#endif
-	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
-	#if F_BUS == 60000000
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(1) | SIM_CLKDIV1_OUTDIV4(4);
-	#elif F_BUS == 120000000
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(0) | SIM_CLKDIV1_OUTDIV4(4);
-	#else
-	#error "This F_CPU & F_BUS combination is not supported"
-	#endif
-	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
-	#if F_BUS == 48000000
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(1) | SIM_CLKDIV1_OUTDIV4(3);
-	#elif F_BUS == 96000000
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(0) | SIM_CLKDIV1_OUTDIV4(3);
-	#else
-	#error "This F_CPU & F_BUS combination is not supported"
-	#endif
-	SIM_CLKDIV2 = SIM_CLKDIV2_USBDIV(1);
+#if F_CPU == 120000000
+  MCG_C6 = MCG_C6_PLLS | MCG_C6_VDIV0(6);  // config PLL for 120 MHz output
 #elif F_CPU == 72000000
-	// config divisors: 72 MHz core, 36 MHz bus, 24 MHz flash, USB = 72 * 2 / 3
-	#if F_BUS == 36000000
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(1) | SIM_CLKDIV1_OUTDIV4(2);
-	#elif F_BUS == 72000000
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(0) | SIM_CLKDIV1_OUTDIV4(2);
-	#else
-	#error "This F_CPU & F_BUS combination is not supported"
-	#endif
-	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
-  #if defined(KINETISK)
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(1) | SIM_CLKDIV1_OUTDIV2(1) | SIM_CLKDIV1_OUTDIV3(1) |  SIM_CLKDIV1_OUTDIV4(3);
-	SIM_CLKDIV2 = SIM_CLKDIV2_USBDIV(1);
-  #elif defined(KINETISL)
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(1) | SIM_CLKDIV1_OUTDIV4(1);
-  #endif
-#elif F_CPU == 24000000
-	// config divisors: 24 MHz core, 24 MHz bus, 24 MHz flash, USB = 96 / 2
-	#if defined(KINETISK)
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(3) | SIM_CLKDIV1_OUTDIV2(3) | SIM_CLKDIV1_OUTDIV3(3) | SIM_CLKDIV1_OUTDIV4(3);
-	SIM_CLKDIV2 = SIM_CLKDIV2_USBDIV(1);
-	#elif defined(KINETISL)
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(3) | SIM_CLKDIV1_OUTDIV4(0);
-	#endif
-#elif F_CPU == 16000000
-	// config divisors: 16 MHz core, 16 MHz bus, 16 MHz flash
-  #if defined(KINETISK)
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(0) | SIM_CLKDIV1_OUTDIV3(0) | SIM_CLKDIV1_OUTDIV4(0);
-  #elif defined(KINETISL)
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV4(0);
-  #endif
-#elif F_CPU == 8000000
-	// config divisors: 8 MHz core, 8 MHz bus, 8 MHz flash
-  #if defined(KINETISK)
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(1) | SIM_CLKDIV1_OUTDIV2(1) | SIM_CLKDIV1_OUTDIV3(1) | SIM_CLKDIV1_OUTDIV4(1);
-  #elif defined(KINETISL)
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(1) | SIM_CLKDIV1_OUTDIV4(0);
-  #endif
-#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
-  #if defined(KINETISK)
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(3) | SIM_CLKDIV1_OUTDIV2(3) | SIM_CLKDIV1_OUTDIV3(3) | SIM_CLKDIV1_OUTDIV4(3);
-  #elif defined(KINETISL)
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(3) | SIM_CLKDIV1_OUTDIV4(0);
-  #endif
-#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
-  #if defined(KINETISK)
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV2(0) | SIM_CLKDIV1_OUTDIV4(1);
-  #elif defined(KINETISL)
-	// config divisors: 2 MHz core, 1 MHz bus, 1 MHz flash
-	SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1(0) | SIM_CLKDIV1_OUTDIV4(1);
-  #endif
+  MCG_C6 = MCG_C6_PLLS | MCG_C6_VDIV0(3);  // config PLL for 72 MHz output
 #else
-#error "Error, F_CPU must be 192, 180, 168, 144, 120, 96, 72, 48, 24, 16, 8, 4, or 2 MHz"
+#error "Unsupported F_CPU"
 #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
-	#if defined(KINETISK)
-	#if F_CPU == 216000000 || F_CPU == 180000000
-	SIM_SOPT2 = SIM_SOPT2_USBSRC | SIM_SOPT2_IRC48SEL | SIM_SOPT2_TRACECLKSEL | SIM_SOPT2_CLKOUTSEL(6);
-	#else
-	SIM_SOPT2 = SIM_SOPT2_USBSRC | SIM_SOPT2_PLLFLLSEL | SIM_SOPT2_TRACECLKSEL | SIM_SOPT2_CLKOUTSEL(6);
-	#endif
-	#elif defined(KINETISL)
-	SIM_SOPT2 = SIM_SOPT2_USBSRC | SIM_SOPT2_PLLFLLSEL | SIM_SOPT2_CLKOUTSEL(6)
-		| SIM_SOPT2_UART0SRC(1) | SIM_SOPT2_TPMSRC(1);
-	#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
+  // now program the clock dividers
+#if 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 == 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;
 #else
-    
-#if F_CPU == 2000000
-	SIM_SOPT2 = SIM_SOPT2_TRACECLKSEL | SIM_SOPT2_CLKOUTSEL(4) | SIM_SOPT2_UART0SRC(3);
-#else
-    SIM_SOPT2 = SIM_SOPT2_TRACECLKSEL | SIM_SOPT2_CLKOUTSEL(6) | SIM_SOPT2_UART0SRC(2);
-#endif
-    
+#error "Unsupported F_CPU"
 #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
+  // 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);
 
-	// initialize the SysTick counter
-	SYST_RVR = (F_CPU / 1000) - 1;
-	SYST_CVR = 0;
-	SYST_CSR = SYST_CSR_CLKSOURCE | SYST_CSR_TICKINT | SYST_CSR_ENABLE;
-	SCB_SHPR3 = 0x20200000;  // Systick = priority 32
+  // initialize the SysTick counter
+  SYST_RVR = (F_CPU / 1000) - 1;
+  SYST_CVR = 0;
+  SYST_CSR = SYST_CSR_CLKSOURCE | SYST_CSR_TICKINT | SYST_CSR_ENABLE;
+  SCB_SHPR3 = 0x20200000;  // Systick = priority 32
 
-	//init_pins();
-	__enable_irq();
+  __enable_irq();
 
-	_init_Teensyduino_internal_();
+  __libc_init_array();
 
-#if defined(KINETISK)
-	// RTC initialization
-	if (RTC_SR & RTC_SR_TIF) {
-		// this code will normally run on a power-up reset
-		// when VBAT has detected a power-up.  Normally our
-		// compiled-in time will be stale.  Write a special
-		// flag into the VBAT register file indicating the
-		// RTC is set with known-stale time and should be
-		// updated when fresh time is known.
-		#if ARDUINO >= 10600
-		rtc_set((uint32_t)&__rtc_localtime);
-		#else
-		rtc_set(TIME_T);
-		#endif
-		*(uint32_t *)0x4003E01C = 0x5A94C3A5;
-	}
-	if ((RCM_SRS0 & RCM_SRS0_PIN) && (*(uint32_t *)0x4003E01C == 0x5A94C3A5)) {
-		// this code should run immediately after an upload
-		// where the Teensy Loader causes the Mini54 to reset.
-		// Our compiled-in time will be very fresh, so set
-		// the RTC with this, and clear the VBAT resister file
-		// data so we don't mess with the time after it's been
-		// set well.
-		#if ARDUINO >= 10600
-		rtc_set((uint32_t)&__rtc_localtime);
-		#else
-		rtc_set(TIME_T);
-		#endif
-		*(uint32_t *)0x4003E01C = 0;
-	}
-#endif
-
-	__libc_init_array();
-
-	startup_late_hook();
-	main();
-	while (1) ;
+  main();
+  while (1) {
+  }
 }
 
 char *__brkval = (char *)&_ebss;
 
 #ifndef STACK_MARGIN
 #if defined(__MKL26Z64__)
-#define STACK_MARGIN  512
+#define STACK_MARGIN 512
 #elif defined(__MK20DX128__)
-#define STACK_MARGIN  1024
+#define STACK_MARGIN 1024
 #elif defined(__MK20DX256__)
-#define STACK_MARGIN  4096
+#define STACK_MARGIN 4096
 #elif defined(__MK64FX512__) || defined(__MK66FX1M0__)
-#define STACK_MARGIN  8192
+#define STACK_MARGIN 8192
 #endif
 #endif
 
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wunused-parameter"
+void *_sbrk(int incr) {
+  char *prev, *stack;
 
-void * _sbrk(int incr)
-{
-	char *prev, *stack;
-
-	prev = __brkval;
-	if (incr != 0) {
-		__asm__ volatile("mov %0, sp" : "=r" (stack) ::);
-		if (prev + incr >= stack - STACK_MARGIN) {
-			errno = ENOMEM;
-			return (void *)-1;
-		}
-		__brkval = prev + incr;
-	}
-	return prev;
+  prev = __brkval;
+  if (incr != 0) {
+    __asm__ volatile("mov %0, sp" : "=r"(stack)::);
+    if (prev + incr >= stack - STACK_MARGIN) {
+      errno = ENOMEM;
+      return (void *)-1;
+    }
+    __brkval = prev + incr;
+  }
+  return prev;
 }
 
-__attribute__((weak)) 
-int _read(int file, char *ptr, int len)
-{
-	return 0;
+#undef STACK_MARGIN
+
+__attribute__((weak)) int _read(int file, char *ptr, int len) {
+  (void)file;
+  (void)ptr;
+  (void)len;
+  return 0;
 }
 
-__attribute__((weak)) 
-int _close(int fd)
-{
-	return -1;
+__attribute__((weak)) int _close(int fd) {
+  (void)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 _fstat(int fd, struct stat *st) {
+  (void)fd;
+  st->st_mode = S_IFCHR;
+  return 0;
 }
 
-__attribute__((weak)) 
-int _isatty(int fd)
-{
-	return 1;
+__attribute__((weak)) int _isatty(int fd) {
+  (void)fd;
+  return 1;
 }
 
-__attribute__((weak)) 
-int _lseek(int fd, long long offset, int whence)
-{
-	return -1;
+__attribute__((weak)) int _lseek(int fd, long long offset, int whence) {
+  (void)fd;
+  (void)offset;
+  (void)whence;
+  return -1;
 }
 
-__attribute__((weak)) 
-void _exit(int status)
-{
-	while (1);
+__attribute__((weak)) void _exit(int status) {
+  (void)status;
+  while (1) {
+  }
 }
 
-__attribute__((weak)) 
-void __cxa_pure_virtual()
-{
-	while (1);
+__attribute__((weak)) void _kill(pid_t pid, int signal) {
+  (void)pid;
+  (void)signal;
+  while (1) {
+  }
 }
 
-__attribute__((weak)) 
-int __cxa_guard_acquire (char *g) 
-{
-	return !(*g);
+__attribute__((weak)) int _getpid() { return -1; }
+
+__attribute__((weak)) void __cxa_pure_virtual() {
+  while (1) {
+  }
 }
 
-__attribute__((weak)) 
-void __cxa_guard_release(char *g)
-{
-	*g = 1;
-}
+__attribute__((weak)) int __cxa_guard_acquire(char *g) { return !(*g); }
 
-#pragma GCC diagnostic pop
-
-int nvic_execution_priority(void)
-{
-	uint32_t 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;
-}
-
+__attribute__((weak)) void __cxa_guard_release(char *g) { *g = 1; }
 
 #if defined(HAS_KINETIS_HSRUN) && F_CPU > 120000000
-int kinetis_hsrun_disable(void)
-{
-	if (SMC_PMSTAT == SMC_PMSTAT_HSRUN) {
-		// First, reduce the CPU clock speed, but do not change
-		// the peripheral speed (F_BUS).  Serial1 & Serial2 baud
-		// rates will be impacted, but most other peripherals
-		// will continue functioning at the same speed.
-		#if F_CPU == 240000000 && F_BUS == 60000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(1, 3, 1, 7); // ok
-		#elif F_CPU == 240000000 && F_BUS == 80000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(2, 2, 2, 8); // ok
-		#elif F_CPU == 240000000 && F_BUS == 120000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(1, 1, 1, 7); // ok
-		#elif F_CPU == 216000000 && F_BUS == 54000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(1, 3, 1, 7); // ok
-		#elif F_CPU == 216000000 && F_BUS == 72000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(2, 2, 2, 8); // ok
-		#elif F_CPU == 216000000 && F_BUS == 108000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(1, 1, 1, 7); // ok
-		#elif F_CPU == 192000000 && F_BUS == 48000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(1, 3, 1, 7); // ok
-		#elif F_CPU == 192000000 && F_BUS == 64000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(2, 2, 2, 8); // ok
-		#elif F_CPU == 192000000 && F_BUS == 96000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(1, 1, 1, 7); // ok
-		#elif F_CPU == 180000000 && F_BUS == 60000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(2, 2, 2, 8); // ok
-		#elif F_CPU == 180000000 && F_BUS == 90000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(1, 1, 1, 7); // ok
-		#elif F_CPU == 168000000 && F_BUS == 56000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(2, 2, 2, 5); // ok
-		#elif F_CPU == 144000000 && F_BUS == 48000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(2, 2, 2, 5); // ok
-		#elif F_CPU == 144000000 && F_BUS == 72000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(1, 1, 1, 5); // ok
-		#else
-			return 0;
-		#endif
-		// Then turn off HSRUN mode
-		SMC_PMCTRL = SMC_PMCTRL_RUNM(0);
-		while (SMC_PMSTAT == SMC_PMSTAT_HSRUN) ; // wait
-		return 1;
-	}
-	return 0;
+int kinetis_hsrun_disable(void) {
+  if (SMC_PMSTAT == SMC_PMSTAT_HSRUN) {
+// First, reduce the CPU clock speed, but do not change
+// the peripheral speed (F_BUS).  Serial1 & Serial2 baud
+// rates will be impacted, but most other peripherals
+// will continue functioning at the same speed.
+#if F_CPU == 240000000 && F_BUS == 60000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(1, 3, 1, 7);  // ok
+#elif F_CPU == 240000000 && F_BUS == 80000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(2, 2, 2, 8);  // ok
+#elif F_CPU == 240000000 && F_BUS == 120000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(1, 1, 1, 7);  // ok
+#elif F_CPU == 216000000 && F_BUS == 54000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(1, 3, 1, 7);  // ok
+#elif F_CPU == 216000000 && F_BUS == 72000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(2, 2, 2, 8);  // ok
+#elif F_CPU == 216000000 && F_BUS == 108000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(1, 1, 1, 7);  // ok
+#elif F_CPU == 192000000 && F_BUS == 48000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(1, 3, 1, 7);  // ok
+#elif F_CPU == 192000000 && F_BUS == 64000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(2, 2, 2, 8);  // ok
+#elif F_CPU == 192000000 && F_BUS == 96000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(1, 1, 1, 7);  // ok
+#elif F_CPU == 180000000 && F_BUS == 60000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(2, 2, 2, 8);  // ok
+#elif F_CPU == 180000000 && F_BUS == 90000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(1, 1, 1, 7);  // ok
+#elif F_CPU == 168000000 && F_BUS == 56000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(2, 2, 2, 5);  // ok
+#elif F_CPU == 144000000 && F_BUS == 48000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(2, 2, 2, 5);  // ok
+#elif F_CPU == 144000000 && F_BUS == 72000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(1, 1, 1, 5);  // ok
+#else
+    return 0;
+#endif
+    // Then turn off HSRUN mode
+    SMC_PMCTRL = SMC_PMCTRL_RUNM(0);
+    while (SMC_PMSTAT == SMC_PMSTAT_HSRUN)
+      ;  // wait
+    return 1;
+  }
+  return 0;
 }
 
-int kinetis_hsrun_enable(void)
-{
-	if (SMC_PMSTAT == SMC_PMSTAT_RUN) {
-		// Turn HSRUN mode on
-		SMC_PMCTRL = SMC_PMCTRL_RUNM(3);
-		while (SMC_PMSTAT != SMC_PMSTAT_HSRUN) {;} // wait
-		// Then configure clock for full speed
-		#if F_CPU == 240000000 && F_BUS == 60000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 3, 0, 7);
-		#elif F_CPU == 240000000 && F_BUS == 80000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 2, 0, 7);
-		#elif F_CPU == 240000000 && F_BUS == 120000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 1, 0, 7);
-		#elif F_CPU == 216000000 && F_BUS == 54000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 3, 0, 7);
-		#elif F_CPU == 216000000 && F_BUS == 72000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 2, 0, 7);
-		#elif F_CPU == 216000000 && F_BUS == 108000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 1, 0, 7);
-		#elif F_CPU == 192000000 && F_BUS == 48000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 3, 0, 6);
-		#elif F_CPU == 192000000 && F_BUS == 64000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 2, 0, 6);
-		#elif F_CPU == 192000000 && F_BUS == 96000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 1, 0, 6);
-		#elif F_CPU == 180000000 && F_BUS == 60000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 2, 0, 6);
-		#elif F_CPU == 180000000 && F_BUS == 90000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 1, 0, 6);
-		#elif F_CPU == 168000000 && F_BUS == 56000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 2, 0, 5);
-		#elif F_CPU == 144000000 && F_BUS == 48000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 2, 0, 4);
-		#elif F_CPU == 144000000 && F_BUS == 72000000
-			SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 1, 0, 4);
-		#else
-			return 0;
-		#endif
-		return 1;
-	}
-	return 0;
+int kinetis_hsrun_enable(void) {
+  if (SMC_PMSTAT == SMC_PMSTAT_RUN) {
+    // Turn HSRUN mode on
+    SMC_PMCTRL = SMC_PMCTRL_RUNM(3);
+    while (SMC_PMSTAT != SMC_PMSTAT_HSRUN) {
+      ;
+    }  // wait
+// Then configure clock for full speed
+#if F_CPU == 240000000 && F_BUS == 60000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 3, 0, 7);
+#elif F_CPU == 240000000 && F_BUS == 80000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 2, 0, 7);
+#elif F_CPU == 240000000 && F_BUS == 120000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 1, 0, 7);
+#elif F_CPU == 216000000 && F_BUS == 54000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 3, 0, 7);
+#elif F_CPU == 216000000 && F_BUS == 72000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 2, 0, 7);
+#elif F_CPU == 216000000 && F_BUS == 108000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 1, 0, 7);
+#elif F_CPU == 192000000 && F_BUS == 48000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 3, 0, 6);
+#elif F_CPU == 192000000 && F_BUS == 64000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 2, 0, 6);
+#elif F_CPU == 192000000 && F_BUS == 96000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 1, 0, 6);
+#elif F_CPU == 180000000 && F_BUS == 60000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 2, 0, 6);
+#elif F_CPU == 180000000 && F_BUS == 90000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 1, 0, 6);
+#elif F_CPU == 168000000 && F_BUS == 56000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 2, 0, 5);
+#elif F_CPU == 144000000 && F_BUS == 48000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 2, 0, 4);
+#elif F_CPU == 144000000 && F_BUS == 72000000
+    SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIVS(0, 1, 0, 4);
+#else
+    return 0;
+#endif
+    return 1;
+  }
+  return 0;
 }
-#endif // HAS_KINETIS_HSRUN && F_CPU > 120000000
-
+#endif  // HAS_KINETIS_HSRUN && F_CPU > 120000000
diff --git a/motors/core/mk64fx512.ld b/motors/core/mk64fx512.ld
index 92aab68..43a63ad 100644
--- a/motors/core/mk64fx512.ld
+++ b/motors/core/mk64fx512.ld
@@ -30,83 +30,91 @@
 
 MEMORY
 {
-	FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 512K
-	RAM  (rwx) : ORIGIN = 0x1FFF0000, LENGTH = 192K
+  FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 512K
+  RAM  (rwx) : ORIGIN = 0x1FFF0000, LENGTH = 192K
 }
 
 
 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
+  .text : {
+    . = 0;
+    KEEP(*(.vectors))
+    *(.startup*)
+    . = 0x400;
+    KEEP(*(.flashconfig*))
+    *(SORT_BY_ALIGNMENT(.text*))
+    *(SORT_BY_ALIGNMENT(.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 = .;
+  .ARM.exidx : {
+    __exidx_start = .;
+    *(.ARM.exidx* .gnu.linkonce.armexidx.*)
+    __exidx_end = .;
+  } > FLASH
+  _etext = .;
 
-	.usbdescriptortable (NOLOAD) : {
-		/* . = ORIGIN(RAM); */
-		. = ALIGN(512);
-		*(.usbdescriptortable*)
-	} > RAM
+  .usbdescriptortable (NOLOAD) : {
+    /* . = ORIGIN(RAM); */
+    _sram = .;
+    . = ALIGN(512);
+    *(.usbdescriptortable*)
+  } > RAM
 
-	.dmabuffers (NOLOAD) : {
-		. = ALIGN(4);
-		*(.dmabuffers*)
-	} > RAM
+  .dmabuffers (NOLOAD) : {
+    . = ALIGN(4);
+    *(.dmabuffers*)
+  } > RAM
 
-	.usbbuffers (NOLOAD) : {
-		. = ALIGN(4);
-		*(.usbbuffers*)
-	} > RAM
+  .usbbuffers (NOLOAD) : {
+    . = ALIGN(4);
+    *(.usbbuffers*)
+  } > RAM
 
-	.data : AT (_etext) {
-		. = ALIGN(4);
-		_sdata = .; 
-		*(.fastrun*)
-		*(.data*)
-		. = ALIGN(4);
-		_edata = .; 
-	} > RAM
+  .data : AT (_etext) {
+    . = ALIGN(4);
+    _sdata = .; 
+    *(SORT_BY_ALIGNMENT(.data*))
+    . = ALIGN(4);
+    _edata = .; 
+  } > RAM
 
-	.noinit (NOLOAD) : {
-		*(.noinit*)
-	} > RAM
+  .noinit (NOLOAD) : {
+    *(.noinit*)
+  } > RAM
 
-	.bss : {
-		. = ALIGN(4);
-		_sbss = .;
-		__bss_start__ = .;
-		*(.bss*)
-		*(COMMON)
-		. = ALIGN(4);
-		_ebss = .;
-		__bss_end = .;
-		__bss_end__ = .;
-	} > RAM
+  .bss : {
+    . = ALIGN(4);
+    _sbss = .;
+    __bss_start__ = .;
+    *(SORT_BY_ALIGNMENT(.bss*))
+    /* Stupid precompiled libc has common symbols, so stick them in. */
+    */libc_nano.a:*(COMMON)
+    . = ALIGN(4);
+    _ebss = .;
+    __bss_end = .;
+    __bss_end__ = .;
+  } > RAM
 
-	_estack = ORIGIN(RAM) + LENGTH(RAM);
+  /* We don't want any common symbols, so just don't include them which results
+   * in linker errors if any do show up somehow.
+   * Contrary to sanity, even with --orphan-handling=error the linker will still
+   * do normal orphan section handling with COMMON... */
+  /DISCARD/ : {
+    *(COMMON);
+  }
+
+  _estack = ORIGIN(RAM) + LENGTH(RAM);
 }
 
 
diff --git a/motors/core/nonstd.c b/motors/core/nonstd.c
index 286c161..88f35b3 100644
--- a/motors/core/nonstd.c
+++ b/motors/core/nonstd.c
@@ -28,7 +28,7 @@
  * SOFTWARE.
  */
 
-#include "avr_functions.h"
+#include "motors/core/nonstd.h"
 #include <string.h>
 #include <stdlib.h>
 #include <math.h>
@@ -163,7 +163,7 @@
 
 			// shift decimal point
 			while (newPrecision > 0) {
-				val *= 10.0;
+				val *= 10.0f;
 				newPrecision--;
 			}
 
@@ -171,7 +171,7 @@
 			s = fcvtf(val, newPrecision, &newDecimalPoint, &sign);
 
 			// if rounded up to new digit (e.g. 0.09 to 0.1), move decimal point
-			if (newDecimalPoint - decpt == precision + 1) decpt++;
+			if (newDecimalPoint - decpt == (int)precision + 1) decpt++;
 		}
 	}
 
diff --git a/motors/core/nonstd.h b/motors/core/nonstd.h
index 977c5e9..f968c64 100644
--- a/motors/core/nonstd.h
+++ b/motors/core/nonstd.h
@@ -28,8 +28,8 @@
  * SOFTWARE.
  */
 
-#ifndef _avr_functions_h_
-#define _avr_functions_h_
+#ifndef CORE_NONSTD_H_
+#define CORE_NONSTD_H_
 
 #include <inttypes.h>
 
@@ -37,61 +37,6 @@
 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);
 
@@ -104,8 +49,8 @@
 
 char * dtostrf(float val, int width, unsigned int precision, char *buf);
 
-
 #ifdef __cplusplus
 }
 #endif
-#endif
+
+#endif  // CORE_NONSTD_H_
diff --git a/motors/core/time.c b/motors/core/time.c
new file mode 100644
index 0000000..48800a2
--- /dev/null
+++ b/motors/core/time.c
@@ -0,0 +1,34 @@
+#include "motors/core/time.h"
+
+#include "motors/core/kinetis.h"
+
+// The systick interrupt increments this every 1ms.
+volatile uint32_t systick_millis_count = 0;
+
+uint32_t micros(void) {
+  __disable_irq();
+  uint32_t current = SYST_CVR;
+  uint32_t count = systick_millis_count;
+  const uint32_t istatus = SCB_ICSR;
+  __enable_irq();
+  // If the interrupt is pending and the timer has already wrapped from 0 back
+  // up to its max, then add another ms.
+  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) { delay_from(micros(), ms); }
+
+uint32_t delay_from(uint32_t start, uint32_t ms) {
+  if (ms > 0) {
+    while (1) {
+      while ((uint32_t)(micros() - start) >= 1000u) {
+        ms--;
+        start += 1000;
+        if (ms == 0) return start;
+      }
+    }
+  }
+  return start;
+}
diff --git a/motors/core/time.h b/motors/core/time.h
new file mode 100644
index 0000000..9befab6
--- /dev/null
+++ b/motors/core/time.h
@@ -0,0 +1,40 @@
+#ifndef CORE_TIME_H_
+#define CORE_TIME_H_
+
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+// Returns the current number of microseconds. This will wrap naturally.
+uint32_t micros(void);
+
+// Delays for the specified number of milliseconds.
+void delay(uint32_t ms);
+
+// Delays for the specified number of milliseconds relative to the starting
+// microsecond value.  Returns the ending microsecond value.
+//
+// This lets you hit an accurate absolute loop time with variable length
+// calculations in the loop. It will handle wrapping correctly.
+uint32_t delay_from(uint32_t start, uint32_t ms);
+
+// Ways to add and subtract times without weird promotions to make sure wrapping
+// works correctly.
+static inline uint32_t time_add(uint32_t a, uint32_t b) { return a + b; }
+static inline uint32_t time_subtract(uint32_t a, uint32_t b) { return a - b; }
+
+// Returns 1 iff a is "after" b. This will do as well as it can in the presence
+// of wrapping, but comparing times more than a half wrap apart will return the
+// "wrong" answer.
+static inline int time_after(uint32_t a, uint32_t b) {
+  return (a - b - 1) < (uint32_t)(1u << 31);
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  // CORE_TIME_H_
diff --git a/motors/medium_salsa.cc b/motors/medium_salsa.cc
new file mode 100644
index 0000000..1a899b1
--- /dev/null
+++ b/motors/medium_salsa.cc
@@ -0,0 +1,76 @@
+#include "motors/core/kinetis.h"
+
+#include <stdio.h>
+
+#include "motors/core/time.h"
+#include "motors/usb/usb_serial.h"
+#include "motors/util.h"
+
+namespace frc971 {
+namespace salsa {
+
+extern "C" {
+void *__stack_chk_guard = (void *)0x67111971;
+extern void usb_init();
+int _write(int file, char *ptr, int len) {
+  (void)file;
+  return usb_serial_write(0, ptr, len);
+}
+
+void __stack_chk_fail(void);
+
+extern char *__brkval;
+extern unsigned long _ebss;
+extern unsigned long _sram;
+extern unsigned long _estack;
+
+}  // extern "C"
+
+extern "C" int main(void) {
+  // for background about this startup delay, please see these conversations
+  // https://forum.pjrc.com/threads/36606-startup-time-(400ms)?p=113980&viewfull=1#post113980
+  // https://forum.pjrc.com/threads/31290-Teensey-3-2-Teensey-Loader-1-24-Issues?p=87273&viewfull=1#post87273
+  delay(400);
+
+  // Set all interrupts to the second-lowest priority to start with.
+  for (int i = 0; i < NVIC_NUM_INTERRUPTS; i++) NVIC_SET_SANE_PRIORITY(i, 0xD);
+
+  // Now set priorities for all the ones we care about. They only have meaning
+  // relative to each other, which means centralizing them here makes it a lot
+  // more manageable.
+  NVIC_SET_SANE_PRIORITY(IRQ_USBOTG, 0x7);
+
+  // Set the LED's pin to output mode.
+  GPIO_BITBAND(GPIOC_PDDR, 5) = 1;
+  PORTC_PCR5 = PORT_PCR_DSE | PORT_PCR_MUX(1);
+
+  usb_serial_init();
+  usb_descriptor_set_product_id(0x0490);
+  usb_init();
+
+  // Give everything a chance to get going.
+  delay(100);
+
+  printf("Ram start:   %p\n", &_sram);
+  printf("Heap start:  %p\n", &_ebss);
+  printf("Heap end:    %p\n", __brkval);
+  printf("Stack start: %p\n", &_estack);
+
+  GPIOC_PSOR = 1 << 5;
+
+  while (true) {}
+  return 0;
+}
+
+void __stack_chk_fail(void) {
+  while (true) {
+    GPIOC_PSOR = (1 << 5);
+    printf("Stack corruption detected\n");
+    delay(1000);
+    GPIOC_PCOR = (1 << 5);
+    delay(1000);
+  }
+}
+
+}  // namespace salsa
+}  // namespace frc971
diff --git a/motors/usb/BUILD b/motors/usb/BUILD
new file mode 100644
index 0000000..801f926
--- /dev/null
+++ b/motors/usb/BUILD
@@ -0,0 +1,24 @@
+cc_library(
+  name = 'usb',
+  visibility = ['//visibility:public'],
+  hdrs = [
+    'usb_desc.h',
+    'usb_serial.h',
+    'usb_dev.h',
+  ],
+  srcs = [
+    'usb_mem.h',
+    'usb_names.h',
+
+    'usb_desc.c',
+    'usb_serial.c',
+    'usb_dev.c',
+    'usb_mem.c',
+  ],
+  defines = [
+    'USB_SERIAL=1',
+  ],
+  deps = [
+    '//motors/core',
+  ],
+)
diff --git a/motors/usb/usb_desc.c b/motors/usb/usb_desc.c
index efb50a8..62ed242 100644
--- a/motors/usb/usb_desc.c
+++ b/motors/usb/usb_desc.c
@@ -31,11 +31,11 @@
 #if F_CPU >= 20000000
 
 #define USB_DESC_LIST_DEFINE
-#include "usb_desc.h"
+#include "motors/usb/usb_desc.h"
 #ifdef NUM_ENDPOINTS
-#include "usb_names.h"
-#include "kinetis.h"
-#include "avr_functions.h"
+#include "motors/usb/usb_names.h"
+#include "motors/core/kinetis.h"
+#include "motors/core/nonstd.h"
 
 // USB Descriptors are binary data which the USB host reads to
 // automatically detect a USB device's capabilities.  The format
@@ -470,7 +470,14 @@
 #define CDC_DATA_INTERFACE_DESC_SIZE	0
 #endif
 
-#define MIDI_INTERFACE_DESC_POS		CDC_DATA_INTERFACE_DESC_POS+CDC_DATA_INTERFACE_DESC_SIZE
+#define CDC2_DATA_INTERFACE_DESC_POS	CDC_DATA_INTERFACE_DESC_POS+CDC_DATA_INTERFACE_DESC_SIZE
+#ifdef  CDC2_DATA_INTERFACE
+#define CDC2_DATA_INTERFACE_DESC_SIZE	9+5+5+4+5+7+9+7+7
+#else
+#define CDC2_DATA_INTERFACE_DESC_SIZE	0
+#endif
+
+#define MIDI_INTERFACE_DESC_POS		CDC2_DATA_INTERFACE_DESC_POS+CDC2_DATA_INTERFACE_DESC_SIZE
 #ifdef  MIDI_INTERFACE
 #define MIDI_INTERFACE_DESC_SIZE	9+7+6+6+9+9+9+5+9+5
 #else
@@ -655,6 +662,72 @@
         0,                                      // bInterval
 #endif // CDC_DATA_INTERFACE
 
+#ifdef CDC2_DATA_INTERFACE
+        // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
+        9,                                      // bLength
+        4,                                      // bDescriptorType
+        CDC2_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
+        CDC2_STATUS_INTERFACE,                   // bMasterInterface
+        CDC2_DATA_INTERFACE,                     // bSlaveInterface0
+        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+        7,                                      // bLength
+        5,                                      // bDescriptorType
+        CDC2_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
+        CDC2_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
+        CDC2_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
+        CDC2_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
@@ -1310,14 +1383,14 @@
 	FTFL_FCCOB1 = 15;
 	FTFL_FSTAT = FTFL_FSTAT_CCIF;
 	while (!(FTFL_FSTAT & FTFL_FSTAT_CCIF)) ; // wait
-	num = *(uint32_t *)&FTFL_FCCOB7;
+	num = *(volatile uint32_t *)&FTFL_FCCOB7;
 #elif defined(HAS_KINETIS_FLASH_FTFE)
 	kinetis_hsrun_disable();
 	FTFL_FSTAT = FTFL_FSTAT_RDCOLERR | FTFL_FSTAT_ACCERR | FTFL_FSTAT_FPVIOL;
-	*(uint32_t *)&FTFL_FCCOB3 = 0x41070000;
+	*(volatile uint32_t *)&FTFL_FCCOB3 = 0x41070000;
 	FTFL_FSTAT = FTFL_FSTAT_CCIF;
 	while (!(FTFL_FSTAT & FTFL_FSTAT_CCIF)) ; // wait
-	num = *(uint32_t *)&FTFL_FCCOBB;
+	num = *(volatile uint32_t *)&FTFL_FCCOBB;
 	kinetis_hsrun_enable();
 #endif
 	__enable_irq();
@@ -1483,6 +1556,10 @@
 #endif
 };
 
+void usb_descriptor_set_product_id(uint16_t product_id) {
+  device_descriptor[10] = LSB(product_id);
+  device_descriptor[11] = MSB(product_id);
+}
 
 #endif // NUM_ENDPOINTS
 #endif // F_CPU >= 20 MHz
diff --git a/motors/usb/usb_desc.h b/motors/usb/usb_desc.h
index b59640d..e8459ce 100644
--- a/motors/usb/usb_desc.h
+++ b/motors/usb/usb_desc.h
@@ -39,6 +39,11 @@
 #include <stdint.h>
 #include <stddef.h>
 
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
 #define ENDPOINT_UNUSED			0x00
 #define ENDPOINT_TRANSIMIT_ONLY		0x15
 #define ENDPOINT_RECEIVE_ONLY		0x19
@@ -120,23 +125,31 @@
   #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 PRODUCT_NAME		{'U','S','B',' ','S','e','r','i','a','l',' ','x','2'}
+  #define PRODUCT_NAME_LEN	13
   #define EP0_SIZE		64
-  #define NUM_ENDPOINTS		4
-  #define NUM_USB_BUFFERS	12
-  #define NUM_INTERFACE		2
+  #define NUM_ENDPOINTS		7
+  #define NUM_USB_BUFFERS	24
+  #define NUM_INTERFACE		4
   #define CDC_STATUS_INTERFACE	0
   #define CDC_DATA_INTERFACE	1
+  #define CDC2_STATUS_INTERFACE	2
+  #define CDC2_DATA_INTERFACE	3
   #define CDC_ACM_ENDPOINT	2
   #define CDC_RX_ENDPOINT       3
   #define CDC_TX_ENDPOINT       4
+  #define CDC2_ACM_ENDPOINT	5
+  #define CDC2_RX_ENDPOINT       6
+  #define CDC2_TX_ENDPOINT       7
   #define CDC_ACM_SIZE          16
   #define CDC_RX_SIZE           64
   #define CDC_TX_SIZE           64
   #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_RECEIVE_ONLY
+  #define ENDPOINT7_CONFIG	ENDPOINT_TRANSIMIT_ONLY
 
 #elif defined(USB_KEYBOARDONLY)
   #define VENDOR_ID		0x16C0
@@ -708,4 +721,10 @@
 #endif // NUM_ENDPOINTS
 #endif // USB_DESC_LIST_DEFINE
 
+void usb_descriptor_set_product_id(uint16_t product_id);
+
+#ifdef __cplusplus
+}
+#endif
+
 #endif
diff --git a/motors/usb/usb_dev.c b/motors/usb/usb_dev.c
index d57ca5d..8dc8e1f 100644
--- a/motors/usb/usb_dev.c
+++ b/motors/usb/usb_dev.c
@@ -37,19 +37,30 @@
  *   https://github.com/payne92/bare-metal-arm
  */
 
-#include "usb_dev.h"
+#include "motors/usb/usb_dev.h"
 #if F_CPU >= 20000000 && defined(NUM_ENDPOINTS)
 
-#include "kinetis.h"
-//#include "HardwareSerial.h"
-#include "usb_mem.h"
+#include "motors/core/kinetis.h"
+#include "motors/usb/usb_mem.h"
 #include <string.h> // for memset
 
+#ifdef CDC_DATA_INTERFACE
+extern uint32_t usb_cdc_line_coding[2];
+extern volatile uint32_t usb_cdc_line_rtsdtr_millis;
+extern volatile uint32_t systick_millis_count;
+extern volatile uint8_t usb_cdc_line_rtsdtr;
+extern volatile uint8_t *usb_cdc_transmit_flush_timer;
+extern void usb_serial_flush_callback(int);
+#endif
+#ifdef CDC2_DATA_INTERFACE
+extern volatile uint8_t *usb_cdc2_transmit_flush_timer;
+#endif
+
 // buffer descriptor table
 
 typedef struct {
 	uint32_t desc;
-	void * addr;
+	const void * addr;
 } bdt_t;
 
 __attribute__ ((section(".usbdescriptortable"), used))
@@ -146,15 +157,7 @@
 
 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)].addr = (const 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;
@@ -177,14 +180,13 @@
 	  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));
+				usb_free((const usb_packet_t *)((const uint8_t *)(table[i].addr) - 8));
 			}
 		}
 		// free all queued packets
@@ -282,7 +284,9 @@
 		}
 		reply_buffer[0] = 0;
 		reply_buffer[1] = 0;
-		if (*(uint8_t *)(&USB0_ENDPT0 + i * 4) & 0x02) reply_buffer[0] = 1;
+		if (*(volatile uint8_t *)(&USB0_ENDPT0 + i * 4) & 0x02) {
+      reply_buffer[0] = 1;
+    }
 		data = reply_buffer;
 		datalen = 2;
 		break;
@@ -293,7 +297,7 @@
 			endpoint0_stall();
 			return;
 		}
-		(*(uint8_t *)(&USB0_ENDPT0 + i * 4)) &= ~0x02;
+		(*(volatile uint8_t *)(&USB0_ENDPT0 + i * 4)) &= ~0x02;
 		// TODO: do we need to clear the data toggle here?
 		break;
 	  case 0x0302: // SET_FEATURE (endpoint)
@@ -303,18 +307,13 @@
 			endpoint0_stall();
 			return;
 		}
-		(*(uint8_t *)(&USB0_ENDPT0 + i * 4)) |= 0x02;
+		(*(volatile uint8_t *)(&USB0_ENDPT0 + i * 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) {
@@ -325,36 +324,21 @@
 				} 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
+		// TODO(Brian): wIndex is the interface number this is directed at. Pay
+		//              attention to that.
 		usb_cdc_line_rtsdtr_millis = systick_millis_count;
 		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
 
@@ -381,7 +365,6 @@
 // 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;
@@ -472,11 +455,6 @@
 		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;
@@ -520,60 +498,31 @@
 {
 	bdt_t *b;
 	uint32_t pid, size;
-	uint8_t *buf;
+	const 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);
+		setup.word1 = *(const uint32_t *)(buf);
+		setup.word2 = *(const 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
@@ -581,18 +530,15 @@
 		break;
 	case 0x01:  // OUT transaction received from host
 	case 0x02:
-		//serial_print("PID=OUT\n");
 #ifdef CDC_STATUS_INTERFACE
+		// TODO(Brian): wIndex is the interface number this is directed at. Pay
+		//              attention to that.
 		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);
 		}
@@ -620,9 +566,6 @@
 		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;
@@ -637,17 +580,10 @@
 
 		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
 }
@@ -669,11 +605,6 @@
 		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;
 }
 
@@ -689,17 +620,6 @@
 	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--;
@@ -729,13 +649,12 @@
 // without this prioritization.  The packet buffer (input) is assigned to the
 // first endpoint needing memory.
 //
-void usb_rx_memory(usb_packet_t *packet)
+void usb_rx_memory(const 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++) {
 #ifdef AUDIO_INTERFACE
@@ -747,8 +666,6 @@
 				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) {
@@ -756,8 +673,6 @@
 				table[index(i, RX, ODD)].desc = BDT_DESC(64, 1);
 				usb_rx_memory_needed--;
 				__enable_irq();
-				//serial_phex(i);
-				//serial_print(",odd\n");
 				return;
 			}
 		}
@@ -782,9 +697,6 @@
 	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;
@@ -852,10 +764,6 @@
 {
 	uint8_t status, stat, t;
 
-	//serial_print("isr");
-	//status = USB0_ISTAT;
-	//serial_phex(status);
-	//serial_print("\n");
 	restart:
 	status = USB0_ISTAT;
 
@@ -867,10 +775,17 @@
 				if (!t) _reboot_Teensyduino_();
 			}
 #ifdef CDC_DATA_INTERFACE
-			t = usb_cdc_transmit_flush_timer;
+			t = *usb_cdc_transmit_flush_timer;
 			if (t) {
-				usb_cdc_transmit_flush_timer = --t;
-				if (t == 0) usb_serial_flush_callback();
+				*usb_cdc_transmit_flush_timer = --t;
+				if (t == 0) usb_serial_flush_callback(0);
+			}
+#endif
+#ifdef CDC2_DATA_INTERFACE
+			t = *usb_cdc2_transmit_flush_timer;
+			if (t) {
+				*usb_cdc2_transmit_flush_timer = --t;
+				if (t == 0) usb_serial_flush_callback(1);
 			}
 #endif
 #ifdef SEREMU_INTERFACE
@@ -896,26 +811,15 @@
 	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);
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wcast-qual"
 			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
+#pragma GCC diagnostic pop
 			endpoint--;	// endpoint is index to zero-based arrays
 
 #ifdef AUDIO_INTERFACE
@@ -943,7 +847,6 @@
 				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]) {
@@ -965,7 +868,6 @@
 					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:
@@ -988,18 +890,8 @@
 					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;
@@ -1014,8 +906,6 @@
 						b->desc = BDT_DESC(64,
 							((uint32_t)b & 8) ? DATA1 : DATA0);
 					} else {
-						//serial_print("starving ");
-						//serial_phex(endpoint + 1);
 						b->desc = 0;
 						usb_rx_memory_needed++;
 					}
@@ -1032,8 +922,6 @@
 
 
 	if (status & USB_ISTAT_USBRST /* 01 */ ) {
-		//serial_print("reset\n");
-
 		// initialize BDT toggle bits
 		USB0_CTL = USB_CTL_ODDRST;
 		ep0_tx_bdt_bank = 0;
@@ -1072,21 +960,16 @@
 
 
 	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;
 	}
 
@@ -1098,9 +981,6 @@
 {
 	int i;
 
-	//serial_begin(BAUD2DIV(115200));
-	//serial_print("usb_init\n");
-
 	usb_init_serialnumber();
 
 	for (i=0; i <= NUM_ENDPOINTS*4; i++) {
@@ -1147,7 +1027,7 @@
 	USB0_INTEN = USB_INTEN_USBRSTEN;
 
 	// enable interrupt in NVIC...
-	NVIC_SET_PRIORITY(IRQ_USBOTG, 112);
+	//NVIC_SET_PRIORITY(IRQ_USBOTG, 112);
 	NVIC_ENABLE_IRQ(IRQ_USBOTG);
 
 	// enable d+ pullup
diff --git a/motors/usb/usb_dev.h b/motors/usb/usb_dev.h
index 1233d7f..c2e9d18 100644
--- a/motors/usb/usb_dev.h
+++ b/motors/usb/usb_dev.h
@@ -32,16 +32,14 @@
 #define _usb_dev_h_
 
 #define USB_DESC_LIST_DEFINE
-#include "usb_desc.h"
-
-#if F_CPU >= 20000000 && !defined(USB_DISABLED)
+#include "motors/usb/usb_desc.h"
 
 // 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 "motors/usb/usb_mem.h"
 
 #ifdef __cplusplus
 extern "C" {
@@ -67,15 +65,6 @@
         return usb_rx_byte_count_data[endpoint];
 }
 
-#ifdef CDC_DATA_INTERFACE
-extern uint32_t usb_cdc_line_coding[2];
-extern volatile uint32_t usb_cdc_line_rtsdtr_millis;
-extern volatile uint32_t systick_millis_count;
-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);
@@ -114,24 +103,8 @@
 extern void usb_touchscreen_update_callback(void);
 #endif
 
-
 #ifdef __cplusplus
 }
 #endif
 
-#else // F_CPU < 20000000
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-void usb_init(void);
-
-#ifdef __cplusplus
-}
-#endif
-
-
-#endif // F_CPU
-
 #endif
diff --git a/motors/usb/usb_mem.c b/motors/usb/usb_mem.c
index 41b4596..e21e5a9 100644
--- a/motors/usb/usb_mem.c
+++ b/motors/usb/usb_mem.c
@@ -28,12 +28,12 @@
  * SOFTWARE.
  */
 
-#include "usb_dev.h"
+#include "motors/usb/usb_dev.h"
 #if F_CPU >= 20000000 && defined(NUM_ENDPOINTS)
 
-#include "kinetis.h"
+#include "motors/core/kinetis.h"
 //#include "HardwareSerial.h"
-#include "usb_mem.h"
+#include "motors/usb/usb_mem.h"
 
 __attribute__ ((section(".usbbuffers"), used))
 unsigned char usb_buffer_memory[NUM_USB_BUFFERS * sizeof(usb_packet_t)];
@@ -57,16 +57,11 @@
 		__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;
@@ -74,24 +69,18 @@
 
 // for the receive endpoints to request memory
 extern uint8_t usb_rx_memory_needed;
-extern void usb_rx_memory(usb_packet_t *packet);
+extern void usb_rx_memory(const usb_packet_t *packet);
 
-void usb_free(usb_packet_t *p)
+void usb_free(const usb_packet_t *p)
 {
 	unsigned int n, mask;
 
-	//serial_print("free:");
-	n = ((uint8_t *)p - usb_buffer_memory) / sizeof(usb_packet_t);
+	n = ((const 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;
 	}
@@ -100,10 +89,6 @@
 	__disable_irq();
 	usb_buffer_available |= mask;
 	__enable_irq();
-
-	//serial_print("free:");
-	//serial_phex32((int)p);
-	//serial_print("\n");
 }
 
 #endif // F_CPU >= 20 MHz && defined(NUM_ENDPOINTS)
diff --git a/motors/usb/usb_mem.h b/motors/usb/usb_mem.h
index 8064488..b6014b5 100644
--- a/motors/usb/usb_mem.h
+++ b/motors/usb/usb_mem.h
@@ -45,7 +45,7 @@
 #endif
 
 usb_packet_t * usb_malloc(void);
-void usb_free(usb_packet_t *p);
+void usb_free(const usb_packet_t *p);
 
 #ifdef __cplusplus
 }
diff --git a/motors/usb/usb_serial.c b/motors/usb/usb_serial.c
index a312176..e7e6115 100644
--- a/motors/usb/usb_serial.c
+++ b/motors/usb/usb_serial.c
@@ -28,114 +28,124 @@
  * SOFTWARE.
  */
 
-#include "usb_dev.h"
-#include "usb_serial.h"
-#include "core_pins.h" // for yield()
-//#include "HardwareSerial.h"
-#include <string.h> // for memcpy()
+#include "motors/usb/usb_dev.h"
+#include "motors/usb/usb_serial.h"
+#include <string.h>
 
-// defined by usb_dev.h -> usb_desc.h
-#if defined(CDC_STATUS_INTERFACE) && defined(CDC_DATA_INTERFACE)
-#if F_CPU >= 20000000
-
+// These are shared between the two serial ports because they're ignored
+// anyways.
 uint32_t usb_cdc_line_coding[2];
 volatile uint32_t usb_cdc_line_rtsdtr_millis;
 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;
+typedef struct {
+	usb_packet_t *rx_packet;
+	usb_packet_t *tx_packet;
+
+	uint32_t rx_endpoint;
+	uint32_t tx_endpoint;
+
+	volatile uint8_t tx_noautoflush;
+	volatile uint8_t transmit_flush_timer;
+} State;
+State states[2];
+
+volatile uint8_t *usb_cdc_transmit_flush_timer =
+    &states[0].transmit_flush_timer;
+volatile uint8_t *usb_cdc2_transmit_flush_timer =
+    &states[1].transmit_flush_timer;
 
 #define TRANSMIT_FLUSH_TIMEOUT	5   /* in milliseconds */
 
+void usb_serial_init(void) {
+	states[0].rx_endpoint = CDC_RX_ENDPOINT;
+	states[0].tx_endpoint = CDC_TX_ENDPOINT;
+	states[1].rx_endpoint = CDC2_RX_ENDPOINT;
+	states[1].tx_endpoint = CDC2_TX_ENDPOINT;
+}
+
 // get the next character, or -1 if nothing received
-int usb_serial_getchar(void)
+int usb_serial_getchar(int port)
 {
+	State *const state = &states[port];
 	unsigned int i;
 	int c;
 
-	if (!rx_packet) {
+	if (!state->rx_packet) {
 		if (!usb_configuration) return -1;
-		rx_packet = usb_rx(CDC_RX_ENDPOINT);
-		if (!rx_packet) return -1;
+		state->rx_packet = usb_rx(state->rx_endpoint);
+		if (!state->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;
+	i = state->rx_packet->index;
+	c = state->rx_packet->buf[i++];
+	if (i >= state->rx_packet->len) {
+		usb_free(state->rx_packet);
+		state->rx_packet = NULL;
 	} else {
-		rx_packet->index = i;
+		state->rx_packet->index = i;
 	}
 	return c;
 }
 
 // peek at the next character, or -1 if nothing received
-int usb_serial_peekchar(void)
+int usb_serial_peekchar(int port)
 {
-	if (!rx_packet) {
+	State *const state = &states[port];
+	if (!state->rx_packet) {
 		if (!usb_configuration) return -1;
-		rx_packet = usb_rx(CDC_RX_ENDPOINT);
-		if (!rx_packet) return -1;
+		state->rx_packet = usb_rx(state->rx_endpoint);
+		if (!state->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;
+	if (!state->rx_packet) return -1;
+	return state->rx_packet->buf[state->rx_packet->index];
 }
 
 // read a block of bytes to a buffer
-int usb_serial_read(void *buffer, uint32_t size)
+int usb_serial_read(int port, void *buffer, uint32_t size)
 {
+	State *const state = &states[port];
 	uint8_t *p = (uint8_t *)buffer;
 	uint32_t qty, count=0;
 
 	while (size) {
 		if (!usb_configuration) break;
-		if (!rx_packet) {
+		if (!state->rx_packet) {
 			rx:
-			rx_packet = usb_rx(CDC_RX_ENDPOINT);
-			if (!rx_packet) break;
-			if (rx_packet->len == 0) {
-				usb_free(rx_packet);
+			state->rx_packet = usb_rx(state->rx_endpoint);
+			if (!state->rx_packet) break;
+			if (state->rx_packet->len == 0) {
+				usb_free(state->rx_packet);
 				goto rx;
 			}
 		}
-		qty = rx_packet->len - rx_packet->index;
+		qty = state->rx_packet->len - state->rx_packet->index;
 		if (qty > size) qty = size;
-		memcpy(p, rx_packet->buf + rx_packet->index, qty);
+		memcpy(p, state->rx_packet->buf + state->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;
+		state->rx_packet->index += qty;
+		if (state->rx_packet->index >= state->rx_packet->len) {
+			usb_free(state->rx_packet);
+			state->rx_packet = NULL;
 		}
 	}
 	return count;
 }
 
 // discard any buffered input
-void usb_serial_flush_input(void)
+void usb_serial_flush_input(int port)
 {
+	State *const state = &states[port];
 	usb_packet_t *rx;
 
 	if (!usb_configuration) return;
-	if (rx_packet) {
-		usb_free(rx_packet);
-		rx_packet = NULL;
+	if (state->rx_packet) {
+		usb_free(state->rx_packet);
+		state->rx_packet = NULL;
 	}
 	while (1) {
-		rx = usb_rx(CDC_RX_ENDPOINT);
+		rx = usb_rx(state->rx_endpoint);
 		if (!rx) break;
 		usb_free(rx);
 	}
@@ -173,133 +183,83 @@
   #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)
+int usb_serial_write(int port, const void *buffer, uint32_t size)
 {
-	return usb_serial_write(&c, 1);
-}
-
-
-int usb_serial_write(const void *buffer, uint32_t size)
-{
-	uint32_t ret = size;
+	State *const state = &states[port];
 	uint32_t len;
-	uint32_t wait_count;
 	const uint8_t *src = (const uint8_t *)buffer;
 	uint8_t *dest;
 
-	tx_noautoflush = 1;
+	state->tx_noautoflush = 1;
 	while (size > 0) {
-		if (!tx_packet) {
-			wait_count = 0;
+		if (!state->tx_packet) {
 			while (1) {
 				if (!usb_configuration) {
-					tx_noautoflush = 0;
+					state->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 (usb_tx_packet_count(state->tx_endpoint) < TX_PACKET_LIMIT) {
+					state->tx_noautoflush = 1;
+					state->tx_packet = usb_malloc();
+					if (state->tx_packet) break;
+					state->tx_noautoflush = 0;
 				}
-				if (++wait_count > TX_TIMEOUT || transmit_previous_timeout) {
-					transmit_previous_timeout = 1;
-					return -1;
-				}
-				yield();
+				return -1;
 			}
 		}
-		transmit_previous_timeout = 0;
-		len = CDC_TX_SIZE - tx_packet->index;
+		len = CDC_TX_SIZE - state->tx_packet->index;
 		if (len > size) len = size;
-		dest = tx_packet->buf + tx_packet->index;
-		tx_packet->index += len;
+		dest = state->tx_packet->buf + state->tx_packet->index;
+		state->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;
+		if (state->tx_packet->index >= CDC_TX_SIZE) {
+			state->tx_packet->len = CDC_TX_SIZE;
+			usb_tx(state->tx_endpoint, state->tx_packet);
+			state->tx_packet = NULL;
 		}
-		usb_cdc_transmit_flush_timer = TRANSMIT_FLUSH_TIMEOUT;
+		state->transmit_flush_timer = TRANSMIT_FLUSH_TIMEOUT;
 	}
-	tx_noautoflush = 0;
-	return ret;
+	state->tx_noautoflush = 0;
+	return size;
 }
 
-int usb_serial_write_buffer_free(void)
+void usb_serial_flush_output(int port)
 {
-	uint32_t len;
-
-	tx_noautoflush = 1;
-	if (!tx_packet) {
-		if (!usb_configuration ||
-		  usb_tx_packet_count(CDC_TX_ENDPOINT) >= TX_PACKET_LIMIT ||
-		  (tx_packet = usb_malloc()) == NULL) {
-			tx_noautoflush = 0;
-			return 0;
-		}
-	}
-	len = CDC_TX_SIZE - tx_packet->index;
-	// TODO: Perhaps we need "usb_cdc_transmit_flush_timer = TRANSMIT_FLUSH_TIMEOUT"
-	// added here, so the SOF interrupt can't take away the available buffer
-	// space we just promised the user could write without blocking?
-	// But does this come with other performance downsides?  Could it lead to
-	// buffer data never actually transmitting in some usage cases?  More
-	// investigation is needed.
-	// https://github.com/PaulStoffregen/cores/issues/10#issuecomment-61514955
-	tx_noautoflush = 0;
-	return len;
-}
-
-void usb_serial_flush_output(void)
-{
+	State *const state = &states[port];
 	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;
+	state->tx_noautoflush = 1;
+	if (state->tx_packet) {
+		state->transmit_flush_timer = 0;
+		state->tx_packet->len = state->tx_packet->index;
+		usb_tx(state->tx_endpoint, state->tx_packet);
+		state->tx_packet = NULL;
 	} else {
 		usb_packet_t *tx = usb_malloc();
 		if (tx) {
-			usb_cdc_transmit_flush_timer = 0;
-			usb_tx(CDC_TX_ENDPOINT, tx);
+			state->transmit_flush_timer = 0;
+			usb_tx(state->tx_endpoint, tx);
 		} else {
-			usb_cdc_transmit_flush_timer = 1;
+			state->transmit_flush_timer = 1;
 		}
 	}
-	tx_noautoflush = 0;
+	state->tx_noautoflush = 0;
 }
 
-void usb_serial_flush_callback(void)
+void usb_serial_flush_callback(int port)
 {
-	if (tx_noautoflush) return;
-	if (tx_packet) {
-		tx_packet->len = tx_packet->index;
-		usb_tx(CDC_TX_ENDPOINT, tx_packet);
-		tx_packet = NULL;
+	State *const state = &states[port];
+	if (state->tx_noautoflush) return;
+	if (state->tx_packet) {
+		state->tx_packet->len = state->tx_packet->index;
+		usb_tx(state->tx_endpoint, state->tx_packet);
+		state->tx_packet = NULL;
 	} else {
 		usb_packet_t *tx = usb_malloc();
 		if (tx) {
-			usb_tx(CDC_TX_ENDPOINT, tx);
+			usb_tx(state->tx_endpoint, tx);
 		} else {
-			usb_cdc_transmit_flush_timer = 1;
+			state->transmit_flush_timer = 1;
 		}
 	}
 }
-
-
-
-
-#endif // F_CPU
-#endif // CDC_STATUS_INTERFACE && CDC_DATA_INTERFACE
diff --git a/motors/usb/usb_serial.h b/motors/usb/usb_serial.h
index 8367f05..2512adc 100644
--- a/motors/usb/usb_serial.h
+++ b/motors/usb/usb_serial.h
@@ -31,142 +31,48 @@
 #ifndef USBserial_h_
 #define USBserial_h_
 
-#include "usb_desc.h"
-
-#if (defined(CDC_STATUS_INTERFACE) && defined(CDC_DATA_INTERFACE)) || defined(USB_DISABLED)
+#include "motors/usb/usb_desc.h"
 
 #include <inttypes.h>
 
-#if F_CPU >= 20000000 && !defined(USB_DISABLED)
-
 // 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);
-int usb_serial_write_buffer_free(void);
-void usb_serial_flush_output(void);
-extern uint32_t usb_cdc_line_coding[2];
-extern volatile uint32_t usb_cdc_line_rtsdtr_millis;
-extern volatile uint32_t systick_millis_count;
-extern volatile uint8_t usb_cdc_line_rtsdtr;
-extern volatile uint8_t usb_cdc_transmit_flush_timer;
-extern volatile uint8_t usb_configuration;
+
+void usb_serial_init(void);
+
+// Reads the next character (if any) and returns it. Returns -1 if no characters
+// are available.
+int usb_serial_getchar(int port);
+
+// Returns the next character (if any) or -1.
+int usb_serial_peekchar(int port);
+
+// Reads as many bytes (up to size) as are available now. Returns 0 immediately
+// if no bytes are available. Returns the number of bytes read.
+int usb_serial_read(int port, void *buffer, uint32_t size);
+
+// Drops any unread input until the most recent packet sent.
+void usb_serial_flush_input(int port);
+
+// Writes data. Returns -1 if it times out or size if it succeeds.
+//
+// NOTE: This does not send immediately. The data is buffered
+int usb_serial_write(int port, const void *buffer, uint32_t size);
+
+// Writes a single character. Returns -1 if it times out or 1 if it succeeds.
+static inline int usb_serial_putchar(int port, uint8_t c) {
+  return usb_serial_write(port, &c, 1);
+}
+
+// Immediately flushes all written data.
+//
+// TODO(Brian): What exactly are the semantics here?
+void usb_serial_flush_output(int port);
+
 #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:
-	constexpr usb_serial_class() {}
-        void begin(long) {
-		uint32_t millis_begin = systick_millis_count;
-		while (!(*this)) {
-			// wait up to 2.5 seconds for Arduino Serial Monitor
-			// Yes, this is a long time, but some Windows systems open
-			// the port very slowly.  This wait allows programs for
-			// Arduino Uno to "just work" (without forcing a reboot when
-			// the port is opened), and when no PC is connected the user's
-			// sketch still gets to run normally after this wait time.
-			if ((uint32_t)(systick_millis_count - millis_begin) > 2500) break;
-		}
-	}
-        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 void clear(void) { usb_serial_flush_input(); }
-        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); }
-	virtual int availableForWrite() { return usb_serial_write_buffer_free(); }
-	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)) &&
-		((uint32_t)(systick_millis_count - usb_cdc_line_rtsdtr_millis) >= 25);
-	}
-	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;
-extern void serialEvent(void);
-#endif // __cplusplus
-
-
-#else  // F_CPU < 20000000
-
-// Allow Arduino programs using Serial to compile, but Serial will do nothing.
-#ifdef __cplusplus
-#include "Stream.h"
-class usb_serial_class : public Stream
-{
-public:
-	constexpr usb_serial_class() {}
-        void begin(long) { };
-        void end() { };
-        virtual int available() { return 0; }
-        virtual int read() { return -1; }
-        virtual int peek() { return -1; }
-        virtual void flush() { }
-        virtual void clear() { }
-        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; }
-	int availableForWrite() { return 0; }
-	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;
-extern void serialEvent(void);
-#endif // __cplusplus
-
-
-#endif // F_CPU
-
-#endif // CDC_STATUS_INTERFACE && CDC_DATA_INTERFACE
-
 #endif // USBserial_h_
diff --git a/motors/util.h b/motors/util.h
new file mode 100644
index 0000000..05edd9d
--- /dev/null
+++ b/motors/util.h
@@ -0,0 +1,154 @@
+#ifndef MOTORS_UTIL_H_
+#define MOTORS_UTIL_H_
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+// The GPIO bitband register for a specific bit of a given GPIO register.
+//
+// reg really must be one of the GPIO module's addresses
+// (0x400FF000 - 0x400FFFFF).
+#define GPIO_BITBAND(reg, bit)                                             \
+  (*(volatile uint32_t *)(((uint32_t) & (reg)-0x40000000) * 32 + (bit)*4 + \
+                          0x42000000))
+
+#define NVIC_SET_SANE_PRIORITY(irqnum, priority) \
+  NVIC_SET_PRIORITY(irqnum, ((priority)&0xF) << 4)
+#define NVIC_GET_SANE_PRIORITY(irqnum) (NVIC_GET_PRIORITY(irqnum) >> 4)
+
+// Definitions for the bits in some registers that are missing.
+#define CAN_MCR_MDIS ((uint32_t)(1 << 31))
+#define CAN_MCR_FRZ ((uint32_t)(1 << 30))
+#define CAN_MCR_RFEN ((uint32_t)(1 << 29))
+#define CAN_MCR_HALT ((uint32_t)(1 << 28))
+#define CAN_MCR_NOTRDY ((uint32_t)(1 << 27))
+#define CAN_MCR_WAKMSK ((uint32_t)(1 << 26))
+#define CAN_MCR_SOFTRST ((uint32_t)(1 << 25))
+#define CAN_MCR_FRZACK ((uint32_t)(1 << 24))
+#define CAN_MCR_SUPV ((uint32_t)(1 << 23))
+#define CAN_MCR_SLFWAK ((uint32_t)(1 << 22))
+#define CAN_MCR_WRNEN ((uint32_t)(1 << 21))
+#define CAN_MCR_LPMACK ((uint32_t)(1 << 20))
+#define CAN_MCR_WAKSRC ((uint32_t)(1 << 19))
+#define CAN_MCR_SRXDIS ((uint32_t)(1 << 17))
+#define CAN_MCR_IRMQ ((uint32_t)(1 << 16))
+#define CAN_MCR_LPRIOEN ((uint32_t)(1 << 13))
+#define CAN_MCR_AEN ((uint32_t)(1 << 12))
+#define CAN_MCR_IDAM(n) ((uint32_t)(((n) & 3) << 8))
+#define CAN_MCR_MAXMB(n) ((uint32_t)((n) & 0x7F))
+#define CAN_CTRL1_PRESDIV(n) ((uint32_t)(((n) & 0xFF) << 24))
+#define CAN_CTRL1_RJW(n) ((uint32_t)(((n) & 3) << 22))
+#define CAN_CTRL1_PSEG1(n) ((uint32_t)(((n) & 7) << 19))
+#define CAN_CTRL1_PSEG2(n) ((uint32_t)(((n) & 7) << 16))
+#define CAN_CTRL1_BOFFMSK ((uint32_t)(1 << 15))
+#define CAN_CTRL1_ERRMSK ((uint32_t)(1 << 14))
+#define CAN_CTRL1_CLKSRC ((uint32_t)(1 << 13))
+#define CAN_CTRL1_LPB ((uint32_t)(1 << 12))
+#define CAN_CTRL1_TWRNMSK ((uint32_t)((1 << 11))
+#define CAN_CTRL1_RWRNMSK ((uint32_t)((1 << 10))
+#define CAN_CTRL1_SMP ((uint32_t)(1 << 7))
+#define CAN_CTRL1_BOFFREC ((uint32_t)(1 << 6)
+#define CAN_CTRL1_TSYN ((uint32_t)(1 << 5))
+#define CAN_CTRL1_LBUF ((uint32_t)(1 << 4))
+#define CAN_CTRL1_LOM ((uint32_t)(1 << 3))
+#define CAN_CTRL1_PROPSEG(n) ((uint32_t)((n) & 7))
+#define CAN_ESR1_SYNCH ((uint32_t)(1 << 18))
+#define CAN_ESR1_TWRNINT ((uint32_t)(1 << 17))
+#define CAN_ESR1_RWRNINT ((uint32_t)(1 << 16))
+#define CAN_ESR1_BIT1ERR ((uint32_t)(1 << 15))
+#define CAN_ESR1_BIT0ERR ((uint32_t)(1 << 14))
+#define CAN_ESR1_ACKERR ((uint32_t)(1 << 13))
+#define CAN_ESR1_CRCERR ((uint32_t)(1 << 12))
+#define CAN_ESR1_FRMERR ((uint32_t)(1 << 11))
+#define CAN_ESR1_STFERR ((uint32_t)(1 << 10))
+#define CAN_ESR1_TXWRN ((uint32_t)(1 << 9))
+#define CAN_ESR1_RXWRN ((uint32_t)(1 << 8))
+#define CAN_ESR1_IDLE ((uint32_t)(1 << 7))
+#define CAN_ESR1_TX ((uint32_t)(1 << 6))
+#define CAN_ESR1_RX ((uint32_t)(1 << 3))
+#define CAN_ESR1_BOFFINT ((uint32_t)(1 << 2))
+#define CAN_ESR1_ERRINT ((uint32_t)(1 << 1))
+#define CAN_ESR1_WAKINT ((uint32_t)1)
+#define CAN_CTRL2_WRMFRZ ((uint32_t)(1 << 28))
+#define CAN_CTRL2_RFFN(n) ((uint32_t)(((n) & 0xF) << 24))
+#define CAN_CTRL2_TASD(n) ((uint32_t)(((n) & 0x1F) << 19))
+#define CAN_CTRL2_MRP ((uint32_t)(1 << 18))
+#define CAN_CTRL2_RRS ((uint32_t)(1 << 17))
+#define CAN_CTRL2_EACEN ((uint32_t)(1 << 16))
+#define CAN_ESR2_VPS ((uint32_t)(1 << 14))
+#define CAN_ESR2_IMB ((uint32_t)(1 << 13))
+
+typedef struct {
+  // Timestamp is the lower 16 bits.
+  uint32_t control_timestamp;
+  uint32_t prio_id;
+  uint32_t data[2];
+} CanMessageBuffer;
+#define CAN0_MESSAGES ((volatile CanMessageBuffer *)0x40024080)
+#define CAN0_RXIMRS ((volatile uint32_t *)0x40024880)
+#define CAN1_MESSAGES ((volatile CanMessageBuffer *)0x400A4080)
+#define CAN1_RXIMRS ((volatile uint32_t *)0x400A4880)
+#define CAN_MB_CONTROL_INSERT_DLC(dlc) ((uint32_t)(((dlc) & 0xF) << 16))
+#define CAN_MB_CONTROL_EXTRACT_DLC(control_timestamp) \
+  ((control_timestamp >> 16) & 0xF)
+#define CAN_MB_CONTROL_RTR ((uint32_t)(1 << 20))
+#define CAN_MB_CONTROL_IDE ((uint32_t)(1 << 21))
+#define CAN_MB_CONTROL_SRR ((uint32_t)(1 << 22))
+#define CAN_MB_CONTROL_INSERT_CODE(n) ((uint32_t)(((n) & 0xF) << 24))
+#define CAN_MB_CONTROL_CODE_BUSY_MASK CAN_MB_CONTROL_INSERT_CODE(1)
+#define CAN_MB_PRIO_ID_PRIORITY_MASK ((uint32_t)((1 << 29) - 1))
+#define CAN_MB_CODE_RX_INACTIVE 0
+#define CAN_MB_CODE_RX_EMPTY 4
+#define CAN_MB_CODE_RX_FULL 2
+#define CAN_MB_CODE_RX_OVERRUN 6
+#define CAN_MB_CODE_RX_RANSWER 0xA
+#define CAN_MB_CODE_TX_INACTIVE 8
+#define CAN_MB_CODE_TX_ABORT 9
+#define CAN_MB_CODE_TX_DATA 0xC
+#define CAN_MB_CODE_TX_REMOTE 0xC
+#define CAN_MB_CODE_TX_TANSWER 0xE
+#define CAN_MB_CODE_IS_BUSY(code) ((code) & 1)
+
+// We have to define these, and leave them defined, because the C preprocessor
+// is annoying...
+#define REALLY_DO_CONCATENATE(x, y, z) x ## y ## z
+#define DO_CONCATENATE(x, y, z) REALLY_DO_CONCATENATE(x, y, z)
+
+// Index-parameterized access to various registers from various peripherals.
+// This only includes ones somebody thought might be useful; add more if you
+// want them.
+#define DMA_TCDn_SADDR(n) DO_CONCATENATE(DMA_TCD, n, _SADDR)
+#define DMA_TCDn_SOFF(n) DO_CONCATENATE(DMA_TCD, n, _SOFF)
+#define DMA_TCDn_ATTR(n) DO_CONCATENATE(DMA_TCD, n, _ATTR)
+#define DMA_TCDn_NBYTES_MLNO(n) DO_CONCATENATE(DMA_TCD, n, _NBYTES_MLNO)
+#define DMA_TCDn_NBYTES_MLOFFNO(n) DO_CONCATENATE(DMA_TCD, n, _NBYTES_MLOFFNO)
+#define DMA_TCDn_NBYTES_MLOFFYES(n) DO_CONCATENATE(DMA_TCD, n, _NBYTES_MLOFFYES)
+#define DMA_TCDn_SLAST(n) DO_CONCATENATE(DMA_TCD, n, _SLAST)
+#define DMA_TCDn_DADDR(n) DO_CONCATENATE(DMA_TCD, n, _DADDR)
+#define DMA_TCDn_DOFF(n) DO_CONCATENATE(DMA_TCD, n, _DOFF)
+#define DMA_TCDn_CITER_ELINKYES(n) DO_CONCATENATE(DMA_TCD, n, _CITER_ELINKYES)
+#define DMA_TCDn_CITER_ELINKNO(n) DO_CONCATENATE(DMA_TCD, n, _CITER_ELINKNO)
+#define DMA_TCDn_DLASTSGA(n) DO_CONCATENATE(DMA_TCD, n, _DLASTSGA)
+#define DMA_TCDn_CSR(n) DO_CONCATENATE(DMA_TCD, n, _CSR)
+#define DMA_TCDn_BITER_ELINKYES(n) DO_CONCATENATE(DMA_TCD, n, _BITER_ELINKYES)
+#define DMA_TCDn_BITER_ELINKNO(n) DO_CONCATENATE(DMA_TCD, n, _BITER_ELINKNO)
+#define SPIn_MCR(n) DO_CONCATENATE(SPI, n, _MCR)
+#define SPIn_TCR(n) DO_CONCATENATE(SPI, n, _TCR)
+#define SPIn_CTAR0(n) DO_CONCATENATE(SPI, n, _CTAR0)
+#define SPIn_SR(n) DO_CONCATENATE(SPI, n, _SR)
+#define SPIn_RSER(n) DO_CONCATENATE(SPI, n, _RSER)
+#define SPIn_PUSHR(n) DO_CONCATENATE(SPI, n, _PUSHR)
+#define SPIn_POPR(n) DO_CONCATENATE(SPI, n, _POPR)
+#define DMAMUX0_CHCFGn(n) DO_CONCATENATE(DMAMUX0, _CHCFG, n)
+#define DMAMUX_SOURCE_SPIn_RX(n) DO_CONCATENATE(DMAMUX_SOURCE_SPI, n, _RX)
+#define DMAMUX_SOURCE_SPIn_TX(n) DO_CONCATENATE(DMAMUX_SOURCE_SPI, n, _TX)
+#define dma_chN_isr(n) DO_CONCATENATE(dma_ch, n, _isr)
+#define IRQ_DMA_CHn(n) DO_CONCATENATE(IRQ_DMA, _CH, n)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  // MOTORS_UTIL_H_
diff --git a/third_party/gperftools/BUILD b/third_party/gperftools/BUILD
index 4fa332f..b1e1f0f 100644
--- a/third_party/gperftools/BUILD
+++ b/third_party/gperftools/BUILD
@@ -208,6 +208,8 @@
   ],
   copts = common_copts + [
     '-fno-builtin',
+    # Add this back in when we upgrade clang.
+    #'-Wno-mismatched-new-delete',
   ],
   size = 'small',
 )
diff --git a/third_party/gperftools/src/base/basictypes.h b/third_party/gperftools/src/base/basictypes.h
index 4779611..2a0fec1 100644
--- a/third_party/gperftools/src/base/basictypes.h
+++ b/third_party/gperftools/src/base/basictypes.h
@@ -78,12 +78,12 @@
 const  int8  kint8max   = (   (  int8) 0x7F);
 const  int16 kint16max  = (   ( int16) 0x7FFF);
 const  int32 kint32max  = (   ( int32) 0x7FFFFFFF);
-const  int64 kint64max =  ( ((( int64) kint32max) << 32) | kuint32max );
+const  int64 kint64max =  ( ((( uint64) kint32max) << 32) | kuint32max );
 
 const  int8  kint8min   = (   (  int8) 0x80);
 const  int16 kint16min  = (   ( int16) 0x8000);
 const  int32 kint32min  = (   ( int32) 0x80000000);
-const  int64 kint64min =  ( ((( int64) kint32min) << 32) | 0 );
+const  int64 kint64min =  ( ((( uint64) kint32min) << 32) | 0 );
 
 // Define the "portable" printf and scanf macros, if they're not
 // already there (via the inttypes.h we #included above, hopefully).
diff --git a/tools/BUILD b/tools/BUILD
index 8926d08..b8a4f1e 100644
--- a/tools/BUILD
+++ b/tools/BUILD
@@ -20,6 +20,10 @@
   values = {'cpu': 'roborio'},
 )
 config_setting(
+  name = 'cpu_cortex_m4f',
+  values = {'cpu': 'cortex-m4f'},
+)
+config_setting(
   name = 'cpu_armhf',
   values = {'cpu': 'armhf-debian'},
 )
diff --git a/tools/ci/run-tests.sh b/tools/ci/run-tests.sh
new file mode 100755
index 0000000..4de8e30
--- /dev/null
+++ b/tools/ci/run-tests.sh
@@ -0,0 +1,5 @@
+#!/bin/sh
+set -e
+
+bazel --batch test -c opt --curses=no --color=no --jobs=1 //... -- $(cat NO_BUILD_AMD64)
+bazel --batch build -c opt --curses=no --color=no --jobs=1 //... --cpu=roborio -- $(cat NO_BUILD_ROBORIO)
diff --git a/tools/cpp/BUILD b/tools/cpp/BUILD
index a7495d9..f5dfe10 100644
--- a/tools/cpp/BUILD
+++ b/tools/cpp/BUILD
@@ -10,6 +10,7 @@
   deps = select({
     '//tools:has_asan': [],
     '//tools:has_tsan': [],
+    '//tools:cpu_cortex_m4f': [],
     '//conditions:default': ['//third_party/gperftools:tcmalloc'],
   }),
 )
@@ -30,6 +31,7 @@
     'k8|clang': ':cc-compiler-k8',
     'roborio|gcc': ':cc-compiler-roborio',
     'armhf-debian|clang': 'cc-compiler-armhf-debian',
+    'cortex-m4f|gcc': 'cc-compiler-cortex-m4f',
   },
 )
 
@@ -150,3 +152,17 @@
   strip_files = '//tools/cpp/linaro_linux_gcc:strip',
   supports_param_files = 1,
 )
+
+cc_toolchain(
+  name = 'cc-compiler-cortex-m4f',
+  all_files = ':empty',
+  compiler_files = ':empty',
+  cpu = 'cortex-m4',
+  dwp_files = ':empty',
+  dynamic_runtime_libs = [':empty'],
+  linker_files = '//motors/core:linkerscript',
+  objcopy_files = ':empty',
+  static_runtime_libs = [':empty'],
+  strip_files = ':empty',
+  supports_param_files = 0,
+)
diff --git a/tools/cpp/CROSSTOOL b/tools/cpp/CROSSTOOL
index 5a374af..7e6efdb 100644
--- a/tools/cpp/CROSSTOOL
+++ b/tools/cpp/CROSSTOOL
@@ -22,6 +22,11 @@
   toolchain_identifier: "clang_linux_armhf"
 }
 
+default_toolchain {
+  cpu: "cortex-m4f"
+  toolchain_identifier: "cortex-m4f"
+}
+
 toolchain {
   abi_version: "armeabi-v7a"
   abi_libc_version: "armeabi-v7a"
@@ -781,3 +786,223 @@
     linker_flag: "-Wl,--gc-sections"
   }
 }
+
+toolchain {
+  abi_version: "cortex-m4f"
+  abi_libc_version: "cortex-m4f"
+  builtin_sysroot: ""
+  compiler: "gcc"
+  host_system_name: "local"
+  needsPic: false
+  supports_gold_linker: false
+  supports_incremental_linker: false
+  supports_fission: false
+  supports_interface_shared_objects: false
+  supports_normalizing_ar: false
+  supports_start_end_lib: false
+  supports_thin_archives: false
+  target_libc: "cortex-m4f"
+  target_cpu: "cortex-m4f"
+  target_system_name: "cortex-m4f"
+  toolchain_identifier: "cortex-m4f"
+
+  tool_path { name: "ar" path: "/usr/bin/arm-none-eabi-ar" }
+  tool_path { name: "compat-ld" path: "/usr/bin/arm-none-eabi-ld" }
+  tool_path { name: "cpp" path: "/usr/bin/arm-none-eabi-cpp" }
+  tool_path { name: "dwp" path: "/usr/bin/arm-none-eabi-dwp" }
+  tool_path { name: "gcc" path: "/usr/bin/arm-none-eabi-gcc" }
+  tool_path { name: "gcov" path: "/usr/bin/arm-none-eabi-gcov" }
+  # C(++) compiles invoke the compiler (as that is the one knowing where
+  # to find libraries), but we provide LD so other rules can invoke the linker.
+  tool_path { name: "ld" path: "/usr/bin/arm-none-eabi-ld" }
+  tool_path { name: "nm" path: "/usr/bin/arm-none-eabi-nm" }
+  tool_path { name: "objcopy" path: "/usr/bin/arm-none-eabi-objcopy" }
+  objcopy_embed_flag: "-I"
+  objcopy_embed_flag: "binary"
+  tool_path { name: "objdump" path: "/usr/bin/arm-none-eabi-objdump" }
+  tool_path { name: "strip" path: "/usr/bin/arm-none-eabi-strip" }
+  linking_mode_flags { mode: FULLY_STATIC }
+
+  # TODO(bazel-team): In theory, the path here ought to exactly match the path
+  # used by gcc. That works because bazel currently doesn't track files at
+  # absolute locations and has no remote execution, yet. However, this will need
+  # to be fixed, maybe with auto-detection?
+  cxx_builtin_include_directory: '/usr/lib/gcc/arm-none-eabi/4.8/include'
+  cxx_builtin_include_directory: '/usr/lib/gcc/arm-none-eabi/4.8/include-fixed'
+  cxx_builtin_include_directory: '/usr/lib/arm-none-eabi/include'
+  cxx_builtin_include_directory: '/usr/include/newlib',
+
+  feature {
+    name: "dbg"
+    implies: "all_modes"
+    flag_set {
+      action: "preprocess-assemble"
+      action: "c-compile"
+      action: "c++-compile"
+      action: "c++-header-parsing"
+      action: "c++-header-preprocessing"
+      action: "c++-module-compile"
+      flag_group {
+        flag: "-fno-omit-frame-pointer"
+      }
+    }
+  }
+
+  feature {
+    name: "opt"
+    implies: "all_modes"
+  }
+  feature {
+    name: "fastbuild"
+    implies: "all_modes"
+  }
+
+  feature {
+    name: "all_modes"
+    flag_set {
+      action: "preprocess-assemble"
+      action: "assemble"
+      action: "c-compile"
+      flag_group {
+        flag: "--std=gnu99"
+      }
+    }
+    flag_set {
+      action: "c++-compile"
+      action: "c++-header-parsing"
+      action: "c++-header-preprocessing"
+      action: "c++-module-compile"
+      flag_group {
+        flag: "--std=gnu++11"
+        flag: "-fno-exceptions"
+        flag: "-fno-rtti"
+      }
+    }
+  }
+
+  # Anticipated future default.
+  # This makes GCC and Clang do what we want when called through symlinks.
+  unfiltered_cxx_flag: "-no-canonical-prefixes"
+  linker_flag: "-no-canonical-prefixes"
+
+  # Things that the code wants defined.
+  compiler_flag: "-D__STDC_FORMAT_MACROS"
+  compiler_flag: "-D__STDC_CONSTANT_MACROS"
+  compiler_flag: "-D__STDC_LIMIT_MACROS"
+  compiler_flag: "-D__MK64FX512__"
+  compiler_flag: "-DF_CPU=120000000"
+  compiler_flag: "-Wl,--gc-sections"
+
+  # Make C++ compilation deterministic. Use linkstamping instead of these
+  # compiler symbols.
+  unfiltered_cxx_flag: "-Wno-builtin-macro-redefined"
+  unfiltered_cxx_flag: "-D__DATE__=\"redacted\""
+  unfiltered_cxx_flag: "-D__TIMESTAMP__=\"redacted\""
+  unfiltered_cxx_flag: "-D__TIME__=\"redacted\""
+
+  # Security hardening on by default.
+  # Conservative choice; -D_FORTIFY_SOURCE=2 may be unsafe in some cases.
+  # We need to undef it before redefining it as some distributions now have
+  # it enabled by default.
+  compiler_flag: "-fstack-protector"
+  compiler_flag: "-mcpu=cortex-m4"
+  compiler_flag: "-mfpu=fpv4-sp-d16"
+  compiler_flag: "-mthumb"
+  compiler_flag: "-mfloat-abi=hard"
+  compiler_flag: "-fno-strict-aliasing"
+  linker_flag: "-mcpu=cortex-m4"
+  linker_flag: "-mfpu=fpv4-sp-d16"
+  linker_flag: "-mthumb"
+  linker_flag: "-mfloat-abi=hard"
+  linker_flag: "-fno-strict-aliasing"
+  linker_flag: "--specs=nano.specs"
+
+  # Pretty much everything needs this, including parts of the glibc STL...
+  linker_flag: "-lgcc"
+  linker_flag: "-lstdc++"
+  linker_flag: "-lm"
+  linker_flag: "-lc"
+  linker_flag: "-Tmotors/core/mk64fx512.ld"
+
+  compiler_flag: "-fmessage-length=80"
+
+  compiler_flag: "-Wall"
+  compiler_flag: "-Wextra"
+  compiler_flag: "-Wswitch-enum"
+  compiler_flag: "-Wpointer-arith"
+  compiler_flag: "-Wcast-qual"
+  compiler_flag: "-Wwrite-strings"
+  compiler_flag: "-Wtype-limits"
+  compiler_flag: "-Wsign-compare"
+  compiler_flag: "-Wformat=2"
+  compiler_flag: "-Werror"
+  compiler_flag: "-Wstrict-aliasing=2"
+
+  # Be annoying about using doubles places we probably didn't mean to, because
+  # the FPU only does single-precision.
+  compiler_flag: "-Wdouble-promotion"
+
+  # Don't use temp files while compiling.
+  compiler_flag: "-pipe"
+
+  # Stamp the binary with a unique identifier.
+  # TODO(austin): Put these back in.
+  #linker_flag: "-Wl,--build-id=md5"
+  #linker_flag: "-Wl,--hash-style=gnu"
+
+  # Enable debug symbols.
+  compiler_flag: "-g"
+
+  # Commons symbols are weird and not what we want, so just give multiple
+  # declaration errors instead.
+  compiler_flag: "-fno-common"
+
+  compilation_mode_flags {
+    mode: OPT
+
+    # Freescale recommends this combination for reducing cycle count.
+    # http://www.nxp.com/assets/documents/data/en/application-notes/AN4808.pdf
+    compiler_flag: "-O2"
+    compiler_flag: "-finline-functions"
+
+    # This is definitely worth it for us. It makes the FPU a lot more useful,
+    # especially with complex arithmetic, which matters a lot.
+    compiler_flag: "-ffast-math"
+
+    # It seems like this is a good idea, at least for the number crunching code.
+    # Might want to look into moving it to copts on specific rules if the code
+    # size increase becomes a problem.
+    compiler_flag: "-funroll-loops"
+
+    # Disable assertions
+    compiler_flag: "-DNDEBUG"
+
+    # Removal of unused code and data at link time (can this increase binary size in some cases?).
+    compiler_flag: "-ffunction-sections"
+    #compiler_flag: "-fdata-sections"
+    linker_flag: "-Wl,--gc-sections"
+  }
+
+  feature {
+    name: 'include_paths'
+    flag_set {
+      action: 'preprocess-assemble'
+      action: 'c-compile'
+      action: 'c++-compile'
+      action: 'c++-header-parsing'
+      action: 'c++-header-preprocessing'
+      action: 'c++-module-compile'
+      flag_group {
+        flag: '-iquote'
+        flag: '%{quote_include_paths}'
+      }
+      flag_group {
+        flag: '-I%{include_paths}'
+      }
+      flag_group {
+        flag: '-iquote'
+        flag: '%{system_include_paths}'
+      }
+    }
+  }
+}
diff --git a/y2014/BUILD b/y2014/BUILD
index 07b9169..936c0cb 100644
--- a/y2014/BUILD
+++ b/y2014/BUILD
@@ -11,7 +11,7 @@
   ],
   deps = [
     '//aos/common/logging',
-    '//aos/common:once',
+    '//aos:once',
     '//aos/common/network:team_number',
     '//aos/common:mutex',
     '//frc971/control_loops:state_feedback_loop',
diff --git a/y2014/autonomous/auto.cc b/y2014/autonomous/auto.cc
index e7f7697..e443f6b 100644
--- a/y2014/autonomous/auto.cc
+++ b/y2014/autonomous/auto.cc
@@ -212,7 +212,7 @@
       distance - theta * control_loops::drivetrain::kRobotRadius;
   right_initial_position +=
       distance + theta * control_loops::drivetrain::kRobotRadius;
-  return ::std::move(drivetrain_action);
+  return drivetrain_action;
 }
 
 void Shoot() {
diff --git a/y2014/constants.cc b/y2014/constants.cc
index 33d734e..d5a29be 100644
--- a/y2014/constants.cc
+++ b/y2014/constants.cc
@@ -11,9 +11,9 @@
 #endif
 
 #include "aos/common/logging/logging.h"
-#include "aos/common/once.h"
-#include "aos/common/network/team_number.h"
 #include "aos/common/mutex.h"
+#include "aos/common/network/team_number.h"
+#include "aos/once.h"
 
 #include "y2014/control_loops/drivetrain/polydrivetrain_dog_motor_plant.h"
 #include "y2014/control_loops/drivetrain/drivetrain_dog_motor_plant.h"
diff --git a/y2015/BUILD b/y2015/BUILD
index da0db7e..1f3b8a1 100644
--- a/y2015/BUILD
+++ b/y2015/BUILD
@@ -11,7 +11,7 @@
   ],
   deps = [
     '//aos/common/logging',
-    '//aos/common:once',
+    '//aos:once',
     '//aos/common:time',
     '//aos/common/network:team_number',
     '//frc971/control_loops:state_feedback_loop',
diff --git a/y2015/autonomous/auto.cc b/y2015/autonomous/auto.cc
index 4df613d..2a1a7c2 100644
--- a/y2015/autonomous/auto.cc
+++ b/y2015/autonomous/auto.cc
@@ -166,7 +166,7 @@
       distance - theta * constants::GetValues().turn_width / 2.0;
   right_initial_position +=
       distance + theta * constants::GetValues().turn_width / 2.0;
-  return ::std::move(drivetrain_action);
+  return drivetrain_action;
 }
 
 const ProfileParams kFridgeYProfile{1.0, 4.0};
diff --git a/y2015/constants.cc b/y2015/constants.cc
index 5b02a25..ce78344 100644
--- a/y2015/constants.cc
+++ b/y2015/constants.cc
@@ -11,9 +11,9 @@
 #endif
 
 #include "aos/common/logging/logging.h"
-#include "aos/common/once.h"
-#include "aos/common/network/team_number.h"
 #include "aos/common/mutex.h"
+#include "aos/common/network/team_number.h"
+#include "aos/once.h"
 
 #include "y2015/control_loops/drivetrain/polydrivetrain_dog_motor_plant.h"
 #include "y2015/control_loops/drivetrain/drivetrain_dog_motor_plant.h"
diff --git a/y2015_bot3/autonomous/auto.cc b/y2015_bot3/autonomous/auto.cc
index 35ad8d2..f7491f4 100644
--- a/y2015_bot3/autonomous/auto.cc
+++ b/y2015_bot3/autonomous/auto.cc
@@ -91,7 +91,7 @@
       distance - theta * control_loops::drivetrain::kDrivetrainTurnWidth / 2.0;
   right_initial_position +=
       distance + theta * control_loops::drivetrain::kDrivetrainTurnWidth / 2.0;
-  return ::std::move(drivetrain_action);
+  return drivetrain_action;
 }
 void WaitUntilDoneOrCanceled(
     ::std::unique_ptr<aos::common::actions::Action> action) {
diff --git a/y2016/BUILD b/y2016/BUILD
index d3c4a9e..49e864c 100644
--- a/y2016/BUILD
+++ b/y2016/BUILD
@@ -11,7 +11,7 @@
   ],
   deps = [
     '//aos/common/logging',
-    '//aos/common:once',
+    '//aos:once',
     '//aos/common/network:team_number',
     '//aos/common:mutex',
     '//frc971/control_loops:state_feedback_loop',
diff --git a/y2016/actors/autonomous_actor.cc b/y2016/actors/autonomous_actor.cc
index 4646cde..727f5de 100644
--- a/y2016/actors/autonomous_actor.cc
+++ b/y2016/actors/autonomous_actor.cc
@@ -197,7 +197,7 @@
 
 void AutonomousActor::AlignWithVisionGoal() {
   actors::VisionAlignActionParams params;
-  vision_action_ = ::std::move(actors::MakeVisionAlignAction(params));
+  vision_action_ = actors::MakeVisionAlignAction(params);
   vision_action_->Start();
 }
 
diff --git a/y2016/constants.cc b/y2016/constants.cc
index 3e16b0c..8bbda56 100644
--- a/y2016/constants.cc
+++ b/y2016/constants.cc
@@ -11,9 +11,9 @@
 #endif
 
 #include "aos/common/logging/logging.h"
-#include "aos/common/once.h"
-#include "aos/common/network/team_number.h"
 #include "aos/common/mutex.h"
+#include "aos/common/network/team_number.h"
+#include "aos/once.h"
 
 #include "y2016/control_loops/drivetrain/polydrivetrain_dog_motor_plant.h"
 #include "y2016/control_loops/drivetrain/drivetrain_dog_motor_plant.h"
diff --git a/y2017/BUILD b/y2017/BUILD
index 11b965e..4163bd5 100644
--- a/y2017/BUILD
+++ b/y2017/BUILD
@@ -13,7 +13,7 @@
     '//aos/common/logging',
     '//aos/common/network:team_number',
     '//aos/common:mutex',
-    '//aos/common:once',
+    '//aos:once',
     '//frc971:constants',
     '//frc971/shooter_interpolation:interpolation',
     '//y2017/control_loops/drivetrain:polydrivetrain_plants',
diff --git a/y2017/constants.cc b/y2017/constants.cc
index e2b743b..9530e27 100644
--- a/y2017/constants.cc
+++ b/y2017/constants.cc
@@ -13,7 +13,7 @@
 #include "aos/common/logging/logging.h"
 #include "aos/common/mutex.h"
 #include "aos/common/network/team_number.h"
-#include "aos/common/once.h"
+#include "aos/once.h"
 
 #include "y2017/control_loops/drivetrain/drivetrain_dog_motor_plant.h"
 #include "y2017/control_loops/drivetrain/polydrivetrain_dog_motor_plant.h"
diff --git a/y2017/control_loops/superstructure/shooter/shooter.cc b/y2017/control_loops/superstructure/shooter/shooter.cc
index 795a7d4..03abd99 100644
--- a/y2017/control_loops/superstructure/shooter/shooter.cc
+++ b/y2017/control_loops/superstructure/shooter/shooter.cc
@@ -67,10 +67,7 @@
   // Compute the distance moved over that time period.
   average_angular_velocity_ =
       (history_[oldest_history_position] - history_[history_position_]) /
-      (chrono::duration_cast<chrono::duration<double>>(
-           ::aos::controls::kLoopFrequency)
-           .count() *
-       static_cast<double>(kHistoryLength - 1));
+      (0.00505 * static_cast<double>(kHistoryLength - 1));
 
   // Ready if average angular velocity is close to the goal.
   error_ = average_angular_velocity_ - loop_->next_R(2, 0);
diff --git a/y2017/control_loops/superstructure/superstructure_lib_test.cc b/y2017/control_loops/superstructure/superstructure_lib_test.cc
index 7906af4..e4e391c 100644
--- a/y2017/control_loops/superstructure/superstructure_lib_test.cc
+++ b/y2017/control_loops/superstructure/superstructure_lib_test.cc
@@ -492,7 +492,7 @@
     superstructure_.Iterate();
     superstructure_plant_.Simulate();
 
-    TickTime();
+    TickTime(::std::chrono::microseconds(5050));
   }
 
   // Runs iterations until the specified amount of simulated time has elapsed.
@@ -948,7 +948,7 @@
 
   superstructure_plant_.set_hood_voltage_offset(2.0);
 
-  superstructure_plant_.set_turret_voltage_offset(-1.5);
+  superstructure_plant_.set_turret_voltage_offset(-1.0);
   superstructure_plant_.set_indexer_voltage_offset(2.0);
 
   RunForTime(chrono::seconds(1), false);
@@ -1082,12 +1082,13 @@
     }
   }
 
-  // Make sure it took some time, but not too much to detect us not being stuck anymore.
+  // Make sure it took some time, but not too much to detect us not being stuck
+  // anymore.
   const auto unstuck_detection_time = monotonic_clock::now();
   EXPECT_TRUE(unstuck_detection_time - unstuck_start_time <
-              chrono::milliseconds(200));
+              chrono::milliseconds(600));
   EXPECT_TRUE(unstuck_detection_time - unstuck_start_time >
-              chrono::milliseconds(40));
+              chrono::milliseconds(100));
 
   // Verify that it actually moved.
   superstructure_queue_.position.FetchLatest();
@@ -1155,11 +1156,12 @@
   // anymore.
   const auto unstuck_detection_time = monotonic_clock::now();
   EXPECT_TRUE(unstuck_detection_time - unstuck_start_time <
-              chrono::milliseconds(600));
+              chrono::milliseconds(1050));
   EXPECT_TRUE(unstuck_detection_time - unstuck_start_time >
               chrono::milliseconds(400));
-  LOG(INFO, "Unstuck time is %ldms",
-      (unstuck_detection_time - unstuck_start_time).count() / 1000000);
+  LOG(INFO, "Unstuck time is %" PRId64 "ms",
+      static_cast<int64_t>(
+          (unstuck_detection_time - unstuck_start_time).count() / 1000000));
 
   // Now, make sure it transitions to stuck again after a delay.
   const auto restuck_start_time = monotonic_clock::now();