# AVR-GCC Makefile
#**************************************************************
.SUFFIXES:
.SUFFIXES:	.S .c .o .elf .eep .bin

#--- define some variables based on the AVR base path in $(AVR)
CC	= avr-gcc
AS	= avr-gcc
RM	= rm -f
RN	= mv
CP      = cp
BIN	= avr-objcopy
INCDIR	= .
LIB    	=
OPTIMIZE = -O2

#If all other steps compile ok then echo "Errors: none".
#Necessary for AVR Studio to understand that everything went ok.
DONE    = @echo Errors: none


#--- default mcu type
MCU = atmega8

#--- default compiler flags -ahlmsn
CPFLAGS = -g -Wall $(OPTIMIZE) -mmcu=$(MCU)

#--- default assembler flags 
ASFLAGS = -mmcu=$(MCU) -Wa,-mmcu=$(MCU),-gstabs

#--- default linker flags
LDFLAGS = -Wl,-Map=$(<:.o=.map),--cref -mmcu=$(MCU)

#--- output format can be srec (Motorola), ihex (Intel HEX) or binary
ROMFORMAT 	= binary
EEPROMFORMAT    = binary


#--- compile: instructions to create assembler and/or object files from C source
#.c.o:
%o : %c 
	$(CC) -c $(CPFLAGS) -I$(INCDIR) $< -o $@

%s : %c
	$(CC) -s $(CPFLAGS) -I$(INCDIR) $< -o $@


#--- assemble: instructions to create object file from assembler source
%o : %S
	$(AS) -x assembler-with-cpp $(ASFLAGS) -I$(INCDIR) -c $< -o $@

%: %.c
	@echo "Error: target $@ not defined in Makefile"
	@exit 1


#--- link: instructions to create elf output file from object files
%elf:	%o
	$(CC) $^ $(LIB) $(LDFLAGS) -o $@

#--- create flash and eeprom bin file (ihex, srec) from elf output file
%bin: %elf
	$(BIN) -O $(ROMFORMAT) -R .eeprom $< $@

%eep: %elf
	$(BIN) -j .eeprom --set-section-flags=.eeprom="alloc,load" --change-section-lma .eeprom=0 -O $(EEPROMFORMAT) $< $(@:.elf=.eep)


#*************************** add your projects below **************************************


#--- this defines the aims of the make process
all:	BlinkLED

clean:
	$(RM) *.eep
	$(RM) *.o
	$(RM) *.elf
	$(RM) *.lst 
	$(RM) *.map

BlinkLED:	BlinkLED.bin
	$(DONE)
BlinkLED.elf:	BlinkLED.o
BlinkLED.o:	BlinkLED.c 


# Convert ELF to COFF for use in debugging / simulating in AVR Studio or VMLAB.
OBJCOPY = avr-objcopy
TARGET = BlinkLED
COFFCONVERT=$(OBJCOPY) --debugging \
--change-section-address .data-0x800000 \
--change-section-address .bss-0x800000 \
--change-section-address .noinit-0x800000 \
--change-section-address .eeprom-0x810000 


coff: $(TARGET).elf
	$(COFFCONVERT) -O coff-avr $< $(TARGET).cof


extcoff: $(TARGET).elf
	$(COFFCONVERT) -O coff-ext-avr $< $(TARGET).cof
