# frequency of the CPU (in Hz)
F_CPU = 16000000UL
TARGET = main
CC = avr-gcc

AVRGCC_MCU_TYPE = atmega328p
AVRDUDE_MCU_TYPE = m328p
BAUD_RATE = 115200
SERIAL_PORT = /dev/ttyUSB0
PROGRAMMER_ID = arduino
DUMP_ORI = ../../ressources/dump_atmega328p_ori.hex


all: hex flash


hex: $(TARGET).hex


# https://gcc.gnu.org/onlinedocs/gcc/AVR-Options.html
$(TARGET).bin: $(TARGET).c
	$(CC) -mmcu=$(AVRGCC_MCU_TYPE) -D F_CPU=$(F_CPU) $(TARGET).c -Os -o $(TARGET).bin


# https://linux.die.net/man/1/avr-objcopy
$(TARGET).hex: $(TARGET).bin
	avr-objcopy -O ihex $(TARGET).bin $(TARGET).hex


# AVR Downloader/UploaDEr https://avrdudes.github.io/avrdude (v6.3 https://download-mirror.savannah.gnu.org/releases/avrdude/avrdude-doc-6.3.pdf)
flash:
	avrdude -p $(AVRDUDE_MCU_TYPE) -c $(PROGRAMMER_ID) -b $(BAUD_RATE) -P $(SERIAL_PORT) -U flash:w:$(TARGET).hex


restore:
	avrdude -p $(AVRDUDE_MCU_TYPE) -c $(PROGRAMMER_ID) -b $(BAUD_RATE) -P $(SERIAL_PORT) -U flash:w:$(DUMP_ORI)


clean:
	rm -f main.hex main.bin


.PHONY : all clean hex flash restore