export CC = avr-gcc

export MCU = atmega328p
export TARGET_ARCH = -mmcu=$(MCU)

export CFLAGS =  -Wall -I. -DF_CPU=16000000 -Os #-pedantic -std=c99#-g
export LDFLAGS = -g $(TARGET_ARCH) -lm -Wl,--gc-sections #	-Os

TARGET = main
TERM0 = /dev/ttyPR0
TERM1 = /dev/ttyPR1
CPPFLAGS = -mmcu=$(MCU)
#PGMER = -c stk500v1 -b 57600 -P $(TERM)

#Dans le cas de l'upload par USB (selon le port)
PGMERISP0 = -c stk500v1 -b 115200 -P $(TERM0)
PGMERISP1 = -c stk500v1 -b 115200 -P $(TERM1)
ARVDUDECONF= -C /etc/avrdude.conf
export DUDE = /usr/bin/avrdude -F -v -p $(MCU) $(AVRDUDECONF)

#Dans le cas de l'upload par SPI depuis la raspberry
PGMERISP_RPI = -c pi_3
ARVDUDECONF_RPI = -C ~/avrdude_gpio.conf
export DUDE_RPI = /usr/bin/avrdude -F -v -p $(MCU) $(AVRDUDECONF_RPI)

C_SRC = $(wildcard *.c)
OBJS = $(C_SRC:.c=.o)

all: $(TARGET).hex

clean:
	rm -f *.o *.hex *.elf

%.o:%.c
	$(CC) -c $< $(CPPFLAGS) $(CFLAGS)

$(TARGET).elf: $(OBJS)
	$(CC) -o $@ $^ $(LDFLAGS)

$(TARGET).hex: $(TARGET).elf
	avr-objcopy -j .text -j .data -O ihex $(TARGET).elf $(TARGET).hex
	avr-objcopy -j .eeprom --set-section-flags=.eeprom="alloc,load" --change-section-lma .eeprom=0 -O ihex $(TARGET).elf eeprom.hex

#UPLOAD CONDITIONNEL
FOLDER = $(notdir $(CURDIR))

upload: $(TARGET).hex
#CAPTEUR 1 connecté en USB
ifeq ($(FOLDER), capteur1-0)

	stty -F $(TERM0) hupcl # reset
	#	$(DUDE) $(PGMER) -U flash:w:$(TARGET).hex
	$(DUDE) $(PGMERISP0) -U flash:w:$(TARGET).hex
endif

#CAPTEUR 1 connecté en SPI
ifeq ($(FOLDER), capteur1-1)

	stty -F $(TERM0) hupcl # reset
	#	$(DUDE) $(PGMER) -U flash:w:$(TARGET).hex
	$(DUDE_RPI) $(PGMERISP_RPI) -U flash:w:$(TARGET).hex
endif

#CAPTEUR 2 connecté en USB
ifeq ($(FOLDER), capteur2-0)

	stty -F $(TERM1) hupcl # reset
	#	$(DUDE) $(PGMER) -U flash:w:$(TARGET).hex
	$(DUDE) $(PGMERISP1) -U flash:w:$(TARGET).hex
endif

#CAPTEUR 2 connecté en SPI
ifeq ($(FOLDER), capteur2-1)

	stty -F $(TERM1) hupcl # reset
	#	$(DUDE) $(PGMER) -U flash:w:$(TARGET).hex
	$(DUDE_RPI) $(PGMERISP_RPI) -U flash:w:$(TARGET).hex
endif

size: $(TARGET).elf
	avr-size --format=avr --mcu=$(MCU) $(TARGET).elf

