MCU      = atmega8u2
F_CPU    = 16000000UL
TARGET   = usbi2c
SRC      = main.c usb.c i2c.c
# Set to 1 to attach to USB only while PB6 (external VBUS divider/sense) is high
VBUS     ?= 0

CFLAGS   = -mmcu=$(MCU) -DF_CPU=$(F_CPU) -DUSE_VBUS_DETECT=$(VBUS) -Os -std=gnu11 \
           -Wall -Wextra -ffunction-sections -fdata-sections -fshort-enums
LDFLAGS  = -mmcu=$(MCU) -Wl,--gc-sections

all: $(TARGET).hex size

$(TARGET).elf: $(SRC) usb.h i2c.h
	avr-gcc $(CFLAGS) $(SRC) -o $@ $(LDFLAGS)

$(TARGET).hex: $(TARGET).elf
	avr-objcopy -O ihex -R .eeprom $< $@

size: $(TARGET).elf
	avr-size $<

# Flash through USBasp
flash: $(TARGET).hex
	avrdude -c usbasp -p m8u2 -U flash:w:$(TARGET).hex:i

# Crystal oscillator, CKDIV8 off (same values as Arduino Uno R3 8U2). Needed once.
fuses:
	avrdude -c usbasp -p m8u2 -U lfuse:w:0xFF:m -U hfuse:w:0xD9:m -U efuse:w:0xF4:m

clean:
	rm -f *.elf *.hex

.PHONY: all size flash fuses clean
