Skip to content

Commit

Permalink
Make F_CPU a compile-time constant (MarlinFirmware#21051)
Browse files Browse the repository at this point in the history
  • Loading branch information
X-Ryl669 authored and vyacheslav-shubin committed Mar 10, 2021
1 parent bc65d92 commit ad51a4f
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
6 changes: 6 additions & 0 deletions Marlin/src/HAL/STM32/HAL.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ TERN_(POSTMORTEM_DEBUGGING, extern void install_min_serial());
void HAL_init() {
FastIO_init();

// Ensure F_CPU is a constant expression.
// If the compiler breaks here, it means that delay code that should compute at compile time will not work.
// So better safe than sorry here.
constexpr int cpuFreq = F_CPU;
UNUSED(cpuFreq);

#if ENABLED(SDSUPPORT) && DISABLED(SDIO_SUPPORT) && (defined(SDSS) && SDSS != -1)
OUT_WRITE(SDSS, HIGH); // Try to set SDSS inactive before any other SPI users start up
#endif
Expand Down
6 changes: 6 additions & 0 deletions Marlin/src/HAL/STM32/inc/Conditionals_adv.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,9 @@
#if defined(USBD_USE_CDC_MSC) && DISABLED(NO_SD_HOST_DRIVE)
#define HAS_SD_HOST_DRIVE 1
#endif

// Fix F_CPU not being a compile-time constant in STSTM32 framework
#ifdef BOARD_F_CPU
#undef F_CPU
#define F_CPU BOARD_F_CPU
#endif
13 changes: 13 additions & 0 deletions buildroot/share/PlatformIO/scripts/common-cxxflags.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@
#"-Wno-sign-compare"
])

#
# Add CPU frequency as a compile time constant instead of a runtime variable
#
def add_cpu_freq():
if 'BOARD_F_CPU' in env:
env['BUILD_FLAGS'].append('-DBOARD_F_CPU=' + env['BOARD_F_CPU'])

# Useful for JTAG debugging
#
# It will separe release and debug build folders.
Expand All @@ -20,3 +27,9 @@
#
if env.GetBuildType() == "debug":
env['BUILD_DIR'] = '$PROJECT_BUILD_DIR/$PIOENV/debug'

# On some platform, F_CPU is a runtime variable. Since it's used to convert from ns
# to CPU cycles, this adds overhead preventing small delay (in the order of less than
# 30 cycles) to be generated correctly. By using a compile time constant instead
# the compiler will perform the computation and this overhead will be avoided
add_cpu_freq()

0 comments on commit ad51a4f

Please sign in to comment.