# -----------------------------------------------------------------------------
# makefile for the ergoDOX firmware
# -----------------------------------------------------------------------------

CFLAGS := -mmcu=atmega32u4   	# processor type (teensy 2.0); must match real life
CFLAGS += -DF_CPU=16000000   	# processor frequency; must match initialization in source
CFLAGS += -std=gnu99         	# use C99 plus GCC extensions
CFLAGS += -Os  -flto         	# optimize for size
CFLAGS += -Wall -Werror      	# enable lots of common warnings
CFLAGS += -fpack-struct      	# pack all structure members together without holes
CFLAGS += -fshort-enums      	# allocate compact enums
CFLAGS += -ffunction-sections	# \ place each function or data into its own
CFLAGS += -fdata-sections    	# / section in the output file
CFLAGS += -pipe              	# faster build
LDFLAGS += -Wl,--relax       	# for some linker optimizations
LDFLAGS += -Wl,--gc-sections 	# discard unused functions and data

SRC := main.c

CC         	:= avr-gcc
OBJCOPY    	:= avr-objcopy
SIZE       	:= avr-size
CHKSUM     	:= md5sum
MAKEHEADERS	:= makeheaders

# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------

.PHONY: all clean

all: firmware.hex firmware.eep
	@echo
	@echo '---------------------------------------------------------------'
	@echo
	$(SIZE) --target=ihex firmware.hex
	@echo
	$(SIZE) --target=ihex firmware.eep
	@echo
	$(CHKSUM) firmware.hex firmware.eep
	@echo
	@echo '---------------------------------------------------------------'
	@echo

clean:
	@echo
	@echo --- cleaning ---
	git clean -dX -f # remove ignored files and directories

# -----------------------------------------------------------------------------

.SECONDARY:

firmware.hex: firmware.elf
	@echo
	@echo --- making $@ ---
	$(OBJCOPY) -O ihex \
		-R .eeprom -R .fuse -R .lock -R .signature \
		$< $@

firmware.eep: firmware.elf
	@echo
	@echo --- making $@ ---
	-$(OBJCOPY) -O ihex \
		-j .eeprom \
		--set-section-flags=.eeprom="alloc,load" \
		--change-section-lma .eeprom=0 \
		--no-change-warnings \
		$< $@ || exit 0

firmware.elf:
	@echo
	@echo --- making $@ ---
	$(MAKEHEADERS) $(SRC)
	$(CC) $(strip $(CFLAGS)) $(strip $(LDFLAGS)) $(SRC) --output $@
