TARGET  = main
SRCS   := $(shell find -name '*.c')
FILES   = $(SRCS:%.c=%)
MCU     = atmega328p
PROGC	= m328p
CC      = avr-gcc
TOOL    = atmelice_isp
#TOOL    = avrispmkii
#TOOL    = usbasp-clone

BUILDDIR = Builds

DEFINES = -DF_CPU=18432000UL
 
CFLAGS  =-mmcu=$(MCU) -O2 -Wall -Wpedantic $(DEFINES) -std=c99 -ffunction-sections -fdata-sections
LDFLAGS =-mmcu=$(MCU) -Wl,--gc-sections

LDFILES = $(foreach FILE,$(FILES),$(BUILDDIR)/$(FILE).o)

all: clean $(BUILDDIR)/$(TARGET).elf

$(BUILDDIR)/%.o: %.c
	mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -c $< -o $(BUILDDIR)/$*.o

$(BUILDDIR)/$(TARGET).elf: $(LDFILES)
	mkdir -p $(dir $@)
	$(CC) $(LDFLAGS) $(LDFILES) -o $(BUILDDIR)/$(TARGET).elf

$(BUILDDIR)/$(TARGET).hex : $(BUILDDIR)/$(TARGET).elf
	 avr-objcopy -j .data -j .text -O ihex $< $@

fuse: 
	avrdude -p $(PROGC) -c $(TOOL) -U lfuse:w:0xff:m -U hfuse:w:0xd9:m -U efuse:w:0xff:m 

load: $(BUILDDIR)/$(TARGET).hex
	avrdude -p $(PROGC) -c $(TOOL) -U flash:w:$(BUILDDIR)/$(TARGET).hex -v -B 250kHz

program: clean load
	
size: $(BUILDDIR)/$(TARGET).elf
	avr-size -C --mcu=$(MCU) $(BUILDDIR)/$(TARGET).elf

.PHONY=clean
clean:
	rm -rf $(BUILDDIR)

