# vim:set noet:
#
# Makefile
# Copyright (C) Peter Ivanov, 2010
#
# First:
# make dep
# 
# Normal code:
# make
#
# Debugging code:
# make DEBUG=1
#
# Creating documentation:
# make doc

# DEBUG:
# 0: disabled, normal code
# 1: enabled, compiling code with debugging features
DEBUG = 1

GCC_MCU = atmega88p
AVRDUDE_MCU = m88p
# default: LOW_FUSE = 0x62, HIGH_FUSE = 0x19, EXT_FUSE = 0xFF
# external oscillator (8-20 MHz)
LOW_FUSE = 0xE7
# enable SPI programming (!), JTAG disabled
HIGH_FUSE = 0xD9
# brown-out detection enabled at 4.3V. NOT OK. IT CAUSES CONTINUOUS RESTART.
#EXT_FUSE = 0xFC
# brown-out detection enabled at 2.7V
EXT_FUSE = 0x05
# frequency of oscillator
# f = 16 MHz
F_CPU = 16000000ul
# f = 8 MHz
#F_CPU = 8000000ul
CROSS_COMPILE = avr-
CC = $(CROSS_COMPILE)gcc
OBJCOPY = $(CROSS_COMPILE)objcopy
AVRDUDE = avrdude
LDFLAGS = -mmcu=$(GCC_MCU) -lm -Wl,-Map=$(PROG).map,--cref -Wl,-gc-sections
CFLAGS = -mmcu=$(GCC_MCU) -Wall -mcall-prologues -ffunction-sections -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -Wstrict-prototypes -DF_CPU=$(F_CPU) -Wa,-adhlns=$(PROG).lst
ifeq ($(DEBUG), 1)
CFLAGS += -O3 -g -D__DEBUG__
else
CFLAGS += -O3 -s
endif
CXXFLAGS = $(CFLAGS)

PROG = sonar
PROGHEX = $(PROG).hex
PROGELF = $(PROG).elf
SRCS = $(PROG).c usart.c lcdproxima.c
OBJS = $(SRCS:.c=.o)

.PHONY: all
all:    $(PROGHEX)

$(PROGELF):	$(OBJS)

$(PROGHEX): $(PROGELF)

tags:	*.c
		ctags -R -V . /usr/lib/avr/include /usr/avr/include

.PHONY: flash
flash:	$(PROGHEX)
	$(AVRDUDE) -p $(AVRDUDE_MCU) -c usbtiny -U flash:w:$< -U lfuse:w:$(LOW_FUSE):m -U hfuse:w:$(HIGH_FUSE):m -U efuse:w:$(EXT_FUSE):m

.PHONY: doc
doc:	doxygen.cfg *.c *.h
	doxygen $<

#.PHONY: dep
#dep:	.depend

#.depend: *.cc *.h
#	$(CXX) -E -MM *.cc *.h > .depend

.PHONY: dep
dep:	.depend

.depend:
	makedepend -- $(CFLAGS) -- *.c *.h
#	touch $@
#	makedepend -f$@ -- $(CXXFLAGS) -- *.cc

.PHONY: clean cleanobj cleanall
clean:  cleanall

cleanobj:
	@rm -fv $(OBJS) *~

cleanall:
	@rm -rfv $(PROG) $(OBJS) doc/ *~ *.log .depend

DIR = atmega88p_sonar

.PHONY: dist predist
dist:	predist $(DIR).tar.gz $(DIR).zip postdist

predist:
	@rm -fv tags $(OBJS)
	mkdir $(DIR)/
	cp -r README *.c *.h *.hex *.elf Makefile doc/ $(DIR)/

postdist:
	rm -rf $(DIR)/

$(DIR).tar.gz: $(DIR)/

$(DIR).zip: $(DIR)/

%o:     %c
	$(CC) -c $< -o $@ $(CFLAGS)

#%::
%elf:	%o
	$(CC) -o $@ $^ $(LDFLAGS) $(LDLIBS)

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

%.tar.gz:
	tar -cvzf $@ $^

%.zip:
	zip -r $@ $^

# DO NOT DELETE
