# AVR-GCC compiler
CC = avr-gcc

# Programmer (change it according to your programmer)
PROGRAMMER = usbasp

# MCU
MCU = atmega328p
QEMU_MACHINE_NAME = uno

# Compiler flags
CFLAGS = -std=c2x -Wall -Wno-array-bounds -mmcu=$(MCU) -DF_CPU=16000000UL -O3

# Comment the following line to disable UART debugging (see uart.h)
CFLAGS += -DDEBUG_UART_ENABLED

# Source files
SRCS = $(wildcard *.c)

# Object files directory
OBJDIR = build

# Object files
OBJS = $(addprefix $(OBJDIR)/,$(SRCS:.c=.o))

# Target file
TARGET = main

# Default target
all: $(OBJDIR) $(TARGET).hex

# Compile C files
$(OBJDIR)/%.o: %.c | $(OBJDIR)
	$(CC) $(CFLAGS) -c $< -o $@

# Link object files
$(OBJDIR)/$(TARGET).elf: $(OBJS)
	$(CC) $(CFLAGS) $(OBJS) -o $(OBJDIR)/$(TARGET).elf
	avr-strip $(OBJDIR)/$(TARGET).elf

# Convert ELF to HEX
$(TARGET).hex: $(OBJDIR)/$(TARGET).elf
	avr-objcopy -O ihex -R .eeprom $(OBJDIR)/$(TARGET).elf $(TARGET).hex

# Flash the program
flash: $(TARGET).hex
	avrdude -p $(MCU) -c $(PROGRAMMER) -U flash:w:$(TARGET).hex

# Run the program in QEMU
qemu: $(TARGET).elf
	qemu-system-avr -machine $(QEMU_MACHINE_NAME) -bios $(OBJDIR)/$(TARGET).elf

# View the generated assembly
asm: $(TARGET).hex
	avr-objdump -S $(OBJDIR)/$(TARGET).elf

serial:
	picocom -b 9600 /dev/ttyUSB0

# Create build directory
$(OBJDIR):
	mkdir -p $(OBJDIR)

# Clean
clean:
	rm -rf $(OBJDIR) $(TARGET).hex

size: $(TARGET).hex
	avr-size --mcu=atmega328p $(TARGET).hex

# Reset target
reset:
	avrdude -p $(MCU) -c $(PROGRAMMER) -E reset