CC=arm-none-eabi-gcc
CPU=-mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=hard
INC=-Iinclude -Ideps/hal/Inc -Ideps/device/Include -Ideps/cmsis/CMSIS/Core/Include -Ideps/freertos/include -Ideps/freertos/portable/GCC/ARM_CM4F
CFLAGS=$(CPU) $(INC) -DSTM32G474xx -DUSE_HAL_DRIVER -Os -g3 -std=c11 -Wall -Wextra -Wshadow -Wdouble-promotion -ffunction-sections -fdata-sections -fno-common
HAL=$(addprefix deps/hal/Src/stm32g4xx_hal, .c _adc.c _adc_ex.c _cortex.c _dma.c _dma_ex.c _flash.c _flash_ex.c _flash_ramfunc.c _gpio.c _pwr.c _pwr_ex.c _rcc.c _rcc_ex.c _tim.c _tim_ex.c)
SRC=$(wildcard src/*.c) $(HAL) deps/device/Source/Templates/system_stm32g4xx.c deps/freertos/tasks.c deps/freertos/list.c deps/freertos/queue.c deps/freertos/portable/GCC/ARM_CM4F/port.c
ASM=deps/device/Source/Templates/gcc/startup_stm32g474xx.s
OBJ=$(addprefix build/,$(SRC:.c=.o)) build/startup.o
all: build/firmware.elf build/firmware.bin
build/%.o: %.c
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -MMD -MP -c $< -o $@
build/startup.o: $(ASM)
	@mkdir -p build
	$(CC) $(CPU) -c $< -o $@
build/firmware.elf: $(OBJ) linker.ld
	$(CC) $(CPU) --specs=nano.specs --specs=nosys.specs -nostartfiles $(OBJ) -Tlinker.ld -Wl,--gc-sections,-Map=build/firmware.map -Wl,--print-memory-usage -lm -lc -o $@
build/firmware.bin: build/firmware.elf
	arm-none-eabi-objcopy -O binary $< $@
test:
	clang -Iinclude -g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer -Wall -Wextra tests/test_pi.c src/pi_control.c src/safety_logic.c -lm -o build/test_pi
	./build/test_pi
clean:
	rm -rf build
-include $(OBJ:.o=.d)
.PHONY: all test clean
