There seems to be some conflict with the serial port and the LowPower.deepSleep/stop mode of my STM32F103C8. I have already struggled with this using the libMaple core viewtopic.php?f=63&t=464&p=3081#p3081. Since then I switched to the official stm32duino Arduino Core because it has the LowPower library and I thought it would be easier. But I am still struggling with an issue with LowPower.deepSleep and the RX1 serial port (using an FTDI usb->serial converter).
With the sketch below: if I don't add the `Serial.end()` in my_sleep, the device never goes to sleep. The my_sleep function is called, but I am guessing the FTDI converter or Serial library triggers an interrupt that makes it wakeup again straight away.
If I do add the Serial.end(), and put a Serial.begin straight after LowPower.deepSleep (line 42) the same behaviour happens: it never goes to sleep.
With Serial.begin in the alamMatch funciton, the device does go to sleep, and also prints the Sleeping and Wakeup lines (if I comment out lines 52-57), but hangs on line 55, with the backtrace showing it goes all the way down to HardwareSerial::write in HardwareSerial.cpp:474 and freezes there. I am guessing after waking up, the code reaches line 55 before the alarmMatch function is called, so the serial port isn't started yet, causing the code to freeze?
How can I solve this issue?
Code: Select all
#include <Arduino.h>
#include <STM32LowPower.h>
#include <STM32RTC.h>
STM32RTC& rtc = STM32RTC::getInstance();
#define LED_PIN PC13
static uint32_t cnt = 0;
static uint64_t prev_time;
static uint64_t now;
static uint64_t wakeup_time;
static volatile bool woken_up = false;
void alarmMatch(void* data) {
*(uint32_t*)data++;
wakeup_time = rtc.getEpoch();
Serial.begin(115200);
Serial.println("Wakeup");
}
void setup() {
Serial.begin(115200);
Serial.setTimeout(10);
Serial.println("Setup");
rtc.begin();
pinMode(LED_PIN, OUTPUT);
LowPower.begin();
wakeup_time = prev_time = rtc.getEpoch();
}
void my_sleep(uint16_t sleep_time){
Serial.println("Sleeping");
Serial.flush();
Serial.end();
LowPower.enableWakeupFrom(&rtc, alarmMatch, &cnt);
rtc.setAlarmEpoch(rtc.getEpoch() + sleep_time);
LowPower.deepSleep();
//Serial.begin(115200);
}
void loop() {
now = rtc.getEpoch();
if(now - wakeup_time > 20) {
my_sleep(10);
}
if(prev_time != rtc.getEpoch()) {
prev_time = rtc.getEpoch();
if(Serial.availableForWrite()) {
Serial.print("Time: ");
Serial.print(prev_time);
Serial.print(" Cnt: ");
Serial.println(cnt);
}
}
digitalWrite(LED_PIN, !digitalRead(LED_BUILTIN));
}