# WinAVR cross-compiler toolchain is used here
CC = avr-gcc
C++ = avr-g++
OBJCOPY = avr-objcopy
OBJDUMP = avr-objdump
SIZE := avr-size
DUDE = avrdude
BMP2HEX = bmp2hex-master/bmp2hex

# CPU specific options
MCU = attiny85
F_CPU = 1000000

#MCU = atmega328p
#F_CPU = 8000000

#MCU = attiny13
#F_CPU = 9600000

# If you are not using ATtiny2313 and the USBtiny programmer, 
# update the lines below to match your configuration
CFLAGS = -Wall -Os -mmcu=$(MCU) -DF_CPU=$(F_CPU) -std=gnu99
OBJFLAGS = -j .text -j .data -O ihex
PROGRAMMER = avrisp
#PROGRAMMER = usbasp
#DUDEFLAGS = -p attiny2313 -c usbtiny -v
DUDEFLAGS = -q -V -p $(MCU) -c $(PROGRAMMER) -F -b 19200 -P /dev/ttyUSB3
FUSEFLAGS = -U lfuse:w:0xe2:m -U hfuse:w:0xde:m

# Object files for the firmware (usbdrv/oddebug.o not strictly needed I think)
OBJECTS = main.o

# By default, build the firmware and command-line client, but do not flash
all: main.hex

# With this, you can flash the firmware by just typing "make flash" on command-line
flash: main.hex
	$(DUDE) $(DUDEFLAGS) -U flash:w:$<

fuse:
	$(DUDE) $(DUDEFLAGS) $(FUSEFLAGS)

readfuse:
	$(DUDE) $(DUDEFLAGS) -v -U lfuse:r:-:i

disassemble: main.hex
	$(OBJDUMP) -j .text -d -m avr5 main.elf
#	$(OBJDUMP) -j .sec1 -d -m avr5 main.hex

# Housekeeping if you want it
clean:
	$(RM) *.o *.hex *.elf

# From .elf file to .hex
%.hex: %.elf
	$(OBJCOPY) $(OBJFLAGS) $< $@

# Main.elf requires additional objects to the firmware, not just main.o
main.elf: $(OBJECTS)
	$(CC) $(CFLAGS) $(OBJECTS) -o $@
	@$(SIZE) --mcu=$(MCU) --format=avr $@

# From C source to .o object file
%.o: %.c	
	$(CC) $(CFLAGS) -c $< -o $@

# From C++ source to .o object file
%.o: %.cpp
	$(C++) $(CFLAGS) -c $< -o $@

# From assembler source to .o object file
%.o: %.S
	$(CC) $(CFLAGS) -x assembler-with-cpp -c $< -o $@
