/* * port_pwr.c * * Created Oct 16, 2024 * * power control for GAT and USB ports. */ #include #include "periph/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 (0xaf << 8) static uint16_t port_pwr_state; static uint8_t gat_oc_state_latch = 0; void port_pwr_state_commit_bkp() { BKP_WriteBackupRegister(PORT_PWR_STATE_DR, port_pwr_state); RTC_WaitForLastTask(); } void gat_on() { if (gat_oc_state_latch) return; GAT_EN_PORT->BSHR = GAT_EN_PIN; port_pwr_state |= GAT_ON_FLAG; port_pwr_state_commit_bkp(); } void gat_off() { GAT_EN_PORT->BCR = GAT_EN_PIN; port_pwr_state &= ~GAT_ON_FLAG; port_pwr_state_commit_bkp(); } 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() { USB2_EN_PORT->BSHR = USB2_EN_PIN; port_pwr_state |= USB2_ON_FLAG; port_pwr_state_commit_bkp(); } void usb2_off() { USB2_EN_PORT->BCR = USB2_EN_PIN; port_pwr_state &= ~USB2_ON_FLAG; port_pwr_state_commit_bkp(); } uint8_t usb2_pwr_state() { return (USB2_EN_PORT->OUTDR & USB2_EN_PIN) ? 1 : 0; } void usb2_toggle() { if (usb2_pwr_state()) usb2_off(); else usb2_on(); } void port_pwr_init() { port_pwr_state = BKP_ReadBackupRegister(PORT_PWR_STATE_DR); RTC_WaitForLastTask(); if ((port_pwr_state & INIT_FLAG) != INIT_FLAG) { // no battery retention. // automatically turn on all outputs port_pwr_state = INIT_FLAG | USB2_ON_FLAG | GAT_ON_FLAG; // and commit state flags port_pwr_state_commit_bkp(); } if (port_pwr_state & GAT_ON_FLAG) gat_on(); if (port_pwr_state & USB2_ON_FLAG) usb2_on(); }