# AVR GCC excecutable
CC = avr-gcc
# AVR Objcopy excecutable
OBJCOPY = avr-objcopy
# AVRDude excecutable
AVRDUDE = avrdude
# optional compiler flags
CFLAGS = 
# optimization level (0, 1, 2, s)
OPT = s
# target cpu frequency
F_CPU = 16000000
# target mcu for avr-gcc
MCU = atmega328p
# defines for c code
CDEFS = -DF_CPU=$(F_CPU)UL
# name of the project (used for naming the elf and hex file)
NAME = blink
# directory to save .o files to
OBJDIR = obj
# target to compile
TARGET = main.c
# usb port to arduino
PORT = /dev/ttyACM0
# baud rate of the arduino
BAUD = 115200
# part number for avrdude
AVRDUDEPART = ATMEGA328P
# AVRDude flags
AVRDUDEFLAGS = 
#AVRDUDEFLAGS += -F -V

#==============================================================================

ALLCFLAGS = -O$(OPT) $(CDEFS) -mmcu=$(MCU) $(CFLAGS) -L$(ARDUINO_LIB)
SRC = $(TARGET)
OBJ = $(SRC:%.c=$(OBJDIR)/%.o)
DEPENDFILE = .depend

all: dep $(NAME).hex upload

build: $(OBJ)

dep: $(SRC)
	$(CC) -MM $(SRC) > $(DEPENDFILE)

-include $(DEPENDFILE)

$(OBJDIR)/%.o: %.c
	$(CC) -c $(ALLCFLAGS) -o $@ $<

%.elf: $(OBJ)
	$(CC) $(ALLCFLAGS) -o $@ $(OBJ)

%.hex: %.elf
	$(OBJCOPY) -O ihex -R .eeprom $< $@

upload: $(NAME).hex
	$(AVRDUDE) $(AVRDUDEFLAGS) -c arduino -p $(AVRDUDEPART) -P $(PORT) -b $(BAUD) -U flash:w:$(NAME).hex

clean:
	rm -f .depend
	rm -f blink.hex
	rm -rf $(OBJDIR)

$(shell mkdir $(OBJDIR) 2>/dev/null)
