MCU = attiny85
F_CPU = 16000000
RM = rm -rf
MKDIR = mkdir -p
EXTRAINCDIR = include
CSTANDARD = gnu99
BUILDDIR = build

GCC = avr-gcc
SIZE = avr-size
OBJCOPY = avr-objcopy
OBJDUMP = avr-objdump
AVRDUDE = avrdude

SRC = src/main.c
SRC += src/timer.c
SRC += src/spi.c
SRC += src/cc2500.c
SRC += src/rx.c
SRC += src/cppm.c

OBJ = $(addprefix $(BUILDDIR)/, $(SRC:.c=.o))

CARGS = -mmcu=$(MCU)
CARGS += -I$(EXTRAINCDIR)
CARGS += -Os
CARGS += -funsigned-char
CARGS += -funsigned-bitfields
CARGS += -fpack-struct
CARGS += -fshort-enums
CARGS += -Wall -pedantic -Wstrict-prototypes -Wshadow
CARGS += -Wpointer-arith -Wcast-qual -Wextra
CARGS += -Wno-main -Wno-write-strings -Wno-unused-parameter
CARGS += -std=$(CSTANDARD)
CARGS += -DF_CPU=$(F_CPU)
CARGS += -ffunction-sections

LINKER = -Wl,--relax

PROGRAMMER = avrisp2
ISPPORT = usb

TARGET = rx

all: $(BUILDDIR)/$(TARGET).hex

$(BUILDDIR)/%.o: %.c
	@$(MKDIR) $(BUILDDIR)/$(dir $<)
	$(GCC) -c $< -o $@ $(CARGS)

$(BUILDDIR)/$(TARGET).elf: $(OBJ)
	$(GCC) $(CARGS) $(OBJ) --output $@ $(LINKER) -Wl,-Map -Wl,$(@:.elf=.map)
	$(SIZE) $@

$(BUILDDIR)/$(TARGET).hex: $(BUILDDIR)/$(TARGET).elf
	$(OBJCOPY) -O ihex $< $@
	$(OBJDUMP) -h -S $< > $(@:.hex=.lss)

program: $(BUILDDIR)/$(TARGET).hex
	$(AVRDUDE) -p $(MCU) -c $(PROGRAMMER) -P $(ISPPORT) -e -U $(TARGET).hex

clean:
	$(RM) $(BUILDDIR)