/* * port_pwr.c * * Created Oct 16, 2024 * * power control for GAT and USB ports. */ #include #include "port_pwr.h" #define PORT_PWR_STATE_DR BKP_DR3 #define GAT_ON_FLAG (1 << 0) #define USB2_ON_FLAG (1 << 1) #define INIT_FLAG (0xa0 << 8) static uint8_t port_pwr_state; static uint8_t gat_oc_state_latch = 0; void gat_on() { if (gat_oc_state_latch) return; GAT_EN_PORT->BSHR = GAT_EN_PIN; port_pwr_state |= GAT_ON_FLAG; BKP_WriteBackupRegister(PORT_PWR_STATE_DR, port_pwr_state); } void gat_off() { GAT_EN_PORT->BCR = GAT_EN_PIN; port_pwr_state &= ~GAT_ON_FLAG; BKP_WriteBackupRegister(PORT_PWR_STATE_DR, port_pwr_state); } uint8_t gat_pwr_state() { return (GAT_EN_PORT->OUTDR & GAT_EN_PIN) ? 1 : 0; } uint8_t gat_oc_state() { if (!(GAT_OC_PORT->INDR & GAT_OC_PIN)) { gat_oc_state_latch = 1; gat_off(); } return gat_oc_state_latch; } void gat_toggle() { if (gat_pwr_state()) gat_off(); else gat_on(); } void usb2_on() { port_pwr_state |= USB2_ON_FLAG; BKP_WriteBackupRegister(PORT_PWR_STATE_DR, port_pwr_state); } void usb2_off() { port_pwr_state &= ~USB2_ON_FLAG; BKP_WriteBackupRegister(PORT_PWR_STATE_DR, port_pwr_state); } uint8_t usb2_pwr_state() { return (USB2_EN_PORT->OUTDR & USB2_EN_PIN) ? 1 : 0; } void usb2_toggle() { if (usb2_pwr_state()) gat_off(); else gat_on(); } void port_pwr_init() { port_pwr_state = BKP_ReadBackupRegister(PORT_PWR_STATE_DR); if ((port_pwr_state & INIT_FLAG) != INIT_FLAG) { // no battery retention. // automatically turn on all outputs port_pwr_state |= INIT_FLAG; gat_on(); usb2_on(); } }