
CC = avr-gcc
OBJCOPY = avr-objcopy
SIZE = avr-size

F_CPU = 16000000UL
MCU = atmega328p

CFLAGS += -DF_CPU=$(F_CPU) -mmcu=$(MCU)
CFLAGS += -I. -O2 --std=c99
CFLAGS += -ffunction-sections -fdata-sections

LDFLAGS += -s -mmcu=$(MCU)
LDFLAGS += -Wl,--gc-sections
LDFLAGS += -Wl,-u,vfprintf -lprintf_flt

MAIN_OBJS += main.o
MAIN_OBJS += contr.o
MAIN_OBJS += relay.o
MAIN_OBJS += timer.o
MAIN_OBJS += adc.o
MAIN_OBJS += eeprom.o
MAIN_OBJS += i2c.o
MAIN_OBJS += disp.o
MAIN_OBJS += fifo.o
MAIN_OBJS += uart.o
MAIN_OBJS += tool.o
MAIN_OBJS += temp.o


MAIN_ELF = main.elf
MAIN_HEX = main.hex

all: $(MAIN_HEX)

$(MAIN_ELF): $(MAIN_OBJS)
	$(CC) $(LDFLAGS) -o $(MAIN_ELF) $(MAIN_OBJS)
	$(SIZE) --format=berkeley $@

DEPENDS_DIR = .dep

%.o: %.c
	@mkdir -p $(DEPENDS_DIR)
	$(CC) $(CFLAGS) -c $*.c -o $*.o
	@$(CC) -MM $(CFLAGS) $*.c > $(DEPENDS_DIR)/$*.d


$(MAIN_HEX): $(MAIN_ELF)
	$(OBJCOPY) -O ihex -R .eeprom $< $@

AVRDUDE = sudo avrdude
TTY_PORT =  /dev/ttyUSB0
TTY_SPEED = 115200
BACKUP = $(MAIN_HEX).bak

upload: $(MAIN_HEX)
	$(AVRDUDE) -c arduino -p ATMEGA328P -P $(TTY_PORT) -b $(TTY_SPEED) -U flash:w:$<

download:
	$(AVRDUDE) -F -V -c arduino -p m328p -P $(TTY_PORT) -b $(TTY_SPEED) -U flash:r:$(BACKUP):i

clean:
	rm -f *.i *.o *.s
	rm -f *.hex *.elf *.bin
	rm -f *~ *.d
	rm -rf $(DEPENDS_DIR)

-include $(DEPENDS_DIR)/$(MAIN_OBJS:.o=.d)

#EOF
