# src/Makefile

# Autostart module for EVBox G2/G3 chargers
# Written 2026 by Maarten Tromp <maarten@geekabit.nl>
# Website: https://www.geekabit.nl/projects/evbox-charger-autostart-module/
# License: Public Domain (CC0)
# For more info see README


PROGRAMMER		:= /dev/ttyUSB0

CORE_SRC_DIR	:= ../core
HW_SRC_DIR		:= .
BUILD_DIR		:= ../../build/avr-gcc

CORE_SRCS		:= $(wildcard $(CORE_SRC_DIR)/*.c)
HW_SRCS			:= $(wildcard $(HW_SRC_DIR)/*.c)
ALL_SRCS		:= $(CORE_SRCS) $(HW_SRCS)
#OBJS			:= $(patsubst %.c,$(BUILD_DIR)/%.o,$(ALL_SRCS))
OBJS			:= $(patsubst %.c,$(BUILD_DIR)/%.o,$(notdir $(ALL_SRCS)))
DEPS			:= $(OBJS:.o=.d)
TARGET			:= $(BUILD_DIR)/firmware.elf
MAP				:= $(TARGET).map
CHK				:= $(TARGET).sha1sum

MCU				:= attiny402
F_CPU			:= 16000000 # 16 MHz

CC				:= avr-gcc
CPPFLAGS		:= -DF_CPU=$(F_CPU) -I/usr/lib/avr/include
CFLAGS			:= -std=c11 -Os -mmcu=$(MCU) -Wall -Wextra -Wconversion -Wsign-conversion -Wshadow -Wstrict-prototypes -Wundef -Wcast-align -fdata-sections -ffunction-sections -fno-common -fno-builtin -Werror=implicit-function-declaration -fstack-usage -fshort-enums -fstack-usage -Wstack-usage=64 -MMD -MP
#CFLAGS			+= -DTEST_FIRMWARE
LD				:= $(CC)
LDFLAGS			:= -mmcu=$(MCU) -Wl,--gc-sections -Wl,-Map=$(MAP)
AVRSIZE			:= avr-size
CHECKSUM		:= sha1sum
AVRDUDE			:= avrdude
AVRDUDEFLAGS	:= -p t402 -c serialupdi -P $(PROGRAMMER) -b 115200
MKDIR			:= mkdir
MKDIR_FLAGS		:= -p


.PHONY: all clean dirs fuses prog

all: $(TARGET)

$(BUILD_DIR):
	$(MKDIR) $(MKDIR_FLAGS) $@

$(TARGET): $(OBJS)
	$(LD) $(LDFLAGS) $^ -o $@
	$(CHECKSUM) $@ > $(CHK)
	$(AVRSIZE) $@

$(BUILD_DIR)/%.o: $(CORE_SRC_DIR)/%.c | $(BUILD_DIR)
	$(CC) $(CFLAGS) -c $< -o $@

$(BUILD_DIR)/%.o: $(HW_SRC_DIR)/%.c | $(BUILD_DIR)
	$(CC) $(CFLAGS) -c $< -o $@

$(BUILD_DIR)/%.o: %.c | $(BUILD_DIR)
	$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@

prog: $(TARGET)
	# these fuse settings set pin PA0 to GPIO. You'll need a HV programmer to program once this is done.
	$(AVRDUDE) $(AVRDUDEFLAGS) -U flash:w:$< -U wdtcfg:w:0x08:m -U bodcfg:w:0x45:m -U osccfg:w:0x01:m -U syscfg0:w:0xf2:m -U syscfg1:w:0x07:m -U append:w:0x00:m -U bootend:w:0x00:m -U lock:w:0xc5:m

clean:
	- $(RM) -r $(BUILD_DIR)/

-include $(DEPS)
