3

I need help in writing some code that will allow for the ATMega32u4 to be aware of when it's plugged into a USB port. I'm not really familiar with the ATMega32 or with it's function in Arduino, so I'm lost in the dark on this one.

Update: So in my circuit, the uC will be powered by Lithium Ion Batteries. On my PCB, their is a battery charging circuit that is powered through a USB C cable. My goal is to implement some type of firmware that can differentiate when the board is plugged into a wall outlet and a USB port on a computer. The reason for this is because I don't want the batteries to charge when the USB C cable is plugged into a laptop.

Second Update: Added pictures of the ATMega32 along with the charging circuit mentioned. I'll be the 5V voltage from USBC to charge the batteries. I'll have the data lines on the USB C cable connected so I can program the microcontroller through a USB cable. My goal here is for the microcontroller to recognize when it's connected to a computer. When this happens, I'll talk to the battery charging IC and tell it to not charge. enter image description here

enter image description here

Jay
  • 135
  • 1
  • 6

1 Answers1

3

I imagine (haven't really tried it) this would work, with some minor adaptation to match your code structure.

//  VBUS or counting frames
//  Any frame counting?
u8 USBConnected()
{
    u8 f = UDFNUML;
    delay(3);
    return f != UDFNUML;
}

The method reads the UDFNUML - usb data frame number lower (byte) register, waits 3 milliseconds, which would be sufficient time get at least 1 more USB frame if the device was really connected to a USB host, reads the register again and checks if it some USB activity had happened.

Personally, I am not a big fan of busy wait delays like that because the CPU could be better utilized doing something useful in that period (3 milliseconds on a 16Mhz CPU = 48000 clocks ~= 48000 instructions) I'd probably use 1 millisecond timer to sample the register and keep track of the USB status

An alternative would be to use the bool USBDevice_::configured() method which is implemented like so

bool USBDevice_::configured()
{
    return _usbConfiguration;
}

// Endpoint 0 interrupt ISR(USB_COM_vect) { // ... snip ... else if (SET_CONFIGURATION == r) { if (REQUEST_DEVICE == (requestType & REQUEST_RECIPIENT)) { InitEndpoints(); _usbConfiguration = setup.wValueL; } else ok = false; // ... snip .... }

Hopefully one of the two approaches work for you...