Detecting USB connection on the Funky v2

When designing low-power code for the ATmega32U4-based Funky v2 (code, optimized for running on battery power), it is important to power down all unused peripherals as soon as possible in the code. The USB circuitry draws significant amount of power, so naturally we’d aim to power it off first. What that causes though, is lost USB connectivity with the host system, therefore lost ability to upload new sketch using the usual method. The Caterina bootloader for the Funky v2 is a slightly modded version of the Arduino Fio v3, mainly for the different (and only) LED on the Funky v2. The bootloader also slightly differs from the  “stock” Caterina bootloader because it passes control to the sketch immediately on board power-up and will only go in bootloader mode for 8 seconds on external reset (or if no sketch is present). This is done so that no time is lost between board power-up and the sketch powering down the unused peripherals. This behavior may cause you trouble, if you disable the USB circuitry too soon. You can recover from the situation by connecting briefly a jumper wire between GND and the RESET pin on the Funky’s ISP header, at which point you generate an external reset and enter the bootloader for 8 seconds. There was simply no room for a reset button on a board 22*22 millimeters in size, but you only need the reset in rare cases.

So there has to be a smarter way to deal with such issue, I did research and it turns out that we can detect the USB connection in the code itself. So, if we are being powered from  the micro USB port, we don’t need to be fancy about power saving, nor disable the USB. Here is the code (source) to detect, if we are connected to USB, note that we need at least 150ms delay before we get reliable reading:

void setup(){
  USBCON = USBCON | B00010000;
  pinMode(1,OUTPUT); // The on-board LED

  delay(150);  // Wait at least 150ms (necessary)

  if (UDINT & B00000001){
  // USB Disconnected code here
  else {
      // USB is connected code here

void loop(){

I plan to use this feature to enable configuration menu over the USB serial, if we are running on external power.


Page views: 1917

One thought on “Detecting USB connection on the Funky v2

  1. Pingback: Funky v2 revision 2 | Martin's corner on the web

Comments are closed.