So, I placed diode and big capacitor to MCU, so MCU can work without main power and can detect this situation via EXTI interrupt.
After this was detected, I want to change detection polarity, run AWU and wait... After I detect that power was restored, I should run again.
How to properly handle this in ChibiOS?
Code is:
Code: Select all
volatile unsigned char wait_timeout = 0;
volatile unsigned char pckenr1_save = 0;
volatile unsigned char pckenr2_save = 0;
void p_init() {
GPIO_output_pushpull(M_PWM);
GPIO_output_pushpull(M_LED);
GPIO_output_pushpull(M_ENA);
UART1_CR2_bit.TEN = 1;
UART1_CR2_bit.REN = 1;
UART3_CR2_bit.TEN = 1;
UART3_CR2_bit.REN = 1;
CLK->PCKENR1 = pckenr1_save;
CLK->PCKENR2 = pckenr2_save;
}
void p_deinit() {
GPIO_input_floating(M_LED);
GPIO_input_floating(M_PWM);
GPIO_input_floating(M_ENA);
UART1_CR2_bit.TEN = 0;
UART1_CR2_bit.REN = 0;
UART3_CR2_bit.TEN = 0;
UART3_CR2_bit.REN = 0;
pckenr1_save = CLK->PCKENR1;
pckenr2_save = CLK->PCKENR2;
CLK->PCKENR1 = 0;
CLK->PCKENR2 = 0x04; // enable AWU clock
}
volatile unsigned char wait_mode = 0;
#pragma vector=9 // Ãðåðûâà Ãèå ïî ïðîïà äà Ãèþ ïèòà Ãèÿ
__interrupt void VCC_lost(void) {
if (wait_mode==0) { // halt
GPIO_set1(M_TEST);
p_deinit();
wait_timeout = 20; // we will wait for 20 seconds
wait_mode = 1;
AWU_APR_bit.APR = 0x3C;
AWU_TBR_bit.AWUTB = 0x0C;
AWU_CSR1_bit.AWUEN = 1;
EXTI_CR2_bit.PEIS = 0x01; // raising edge interrupt
__halt();
} else { // wakeup, Neo!
if (wait_mode == 1) {
wait_mode = 0;
AWU_CSR1_bit.AWUEN = 0;
GPIO_set0(M_TEST);
p_init();
EXTI_CR2_bit.PEIS = 0x02; // raising edge interrupt
}
}
}
#pragma vector=3
__interrupt void AWU_IF(void) {
AWU_CSR1_bit.AWUF;
if (wait_mode != 1) return;
if (wait_timeout) wait_timeout--;
if (wait_timeout) {
GPIO_set0(M_TEST);
GPIO_set1(M_TEST);
} else {
GPIO_set1(M_TEST);
GPIO_set0(M_TEST);
}
__halt();
}
Sometimes THIS code work as expected, when MCU lost power, it brings M_TEST pin high, then do pulses every second, after 20 seconds it inverts pulses polarity. But after restoring power it sometimes continues working wirh ChibiOS threads, sometimes not.
I want to check at start wait_timeout value, if it zero, all is OK, and I can start device, but if it not 0, I should wait more (but communicate with other devices).
I know that maybe I should add some ChibiOS related calls inside interrupts, but I do not know which and how.
Can you help me with this?
Thanks!