AVR_CC			= avr-gcc
AVR_LD			= $(AVR_CC)
AVR_OBJCOPY		= avr-objcopy
AVR_SIZE		= avr-size
MCU			= atmega32
CFLAGS			= -c -Wall -g -$(OPTIMIZE) -mmcu=$(MCU) -fdata-sections -ffunction-sections -fdiagnostics-color=always -std=gnu99
OPTIMIZE		= O2
LDFLAGS			= -fdiagnostics-color=always -Wl,--gc-sections
TARGET			= main

OBJECTS = $(patsubst %.c, %.o, $(wildcard *.c))

all: $(TARGET).hex

$(TARGET):  $(OBJECTS)
	$(AVR_LD) -o $@.elf $^ $(LDFLAGS) -mmcu=$(MCU)

# You don't even need to be explicit here,
# compiling C files is handled automagically by Make.

%.o: %.c
	$(AVR_CC) $(CFLAGS) $^ -o $@

%.hex: $(TARGET) size
	$(AVR_OBJCOPY) -j .text -j .data -O ihex $<.elf $@

.PHONY: clean
clean:
	rm -rf *.o $(TARGET).elf $(TARGET).hex

size: $(TARGET)
	$(AVR_SIZE) -C --mcu=$(MCU) $(TARGET).elf

install: $(TARGET).hex reset
	sudo avrdude -V -p m32 -c stk500v2 -b 57600 -P /dev/ttyUSB0 -U flash:w:$<

reset:
	@echo "Resetting MCU..."
	@stty -F /dev/ttyUSB0 9600 cs8 cread clocal
	@echo "R" > /dev/ttyUSB0
	@sleep 0.1
