# Author: Jake Goodwin
# DATE: 2023-12-07
# Descripion: A simple makefile for building and flashing hex files

# Makefile for ATtiny13A

# Compiler
CC = avr-gcc

#Default cpu frequency is 9.8Mhz, 4.8 gives us less power consumption
#F_CPU = 1000000UL
F_CPU = 4800000UL
#F_CPU = 9800000UL
MCU = attiny13a

# Flags
CFLAGS = -g -Os -mmcu=$(MCU) -DF_CPU=$(F_CPU)
LDFLAGS = -Wl,-Map,$(TARGET).map

# Source files
SRC = main.c

# Object files
OBJ = $(SRC:.c=.o)

# Target HEX file
TARGET = main

# Flashing options
AVRDUDE = avrdude
AVRDUDE_PROGRAMMER = -c usbasp
BUADRATE = -B 125kHz
AVRDUDE_PORT = -P /dev/ttyUSB0
AVRDUDE_MCU = -p $(MCU)


# Compile and generate HEX file
all: $(TARGET).hex

$(TARGET).hex: $(TARGET).elf
	avr-objcopy -j .text -j .data -O ihex $< $@

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

%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@
size: $(TARGET).o
	avr-size --mcu=$(MCU) -t ./$(TARGET).o	
# Default for the attiny13a is going to be 9.6Mhz
flash_defualt_fuses:
	$(AVRDUDE) $(AVRDUDE_PROGRAMMER) $(AVRDUDE_PORT) $(AVRDUDE_MCU) $(BUADRATE) -U lfuse:w:0x6A:m -U hfuse:w:0xFF:m -U lock:w:0xFF:m
# This is for 4.8Mhz
flash_slow_fuse:
	$(AVRDUDE) $(AVRDUDE_PROGRAMMER) $(AVRDUDE_PORT) $(AVRDUDE_MCU) $(BUADRATE) -U lfuse:w:0x69:m -U hfuse:w:0xFF:m -U lock:w:0xFF:m
flash_slow_nodiv8:
	$(AVRDUDE) $(AVRDUDE_PROGRAMMER) $(AVRDUDE_PORT) $(AVRDUDE_MCU) $(BUADRATE) -U lfuse:w:0x79:m -U hfuse:w:0xFF:m -U lock:w:0xFF:m
flash: $(TARGET).hex
	$(AVRDUDE) $(AVRDUDE_PROGRAMMER) $(AVRDUDE_PORT) $(AVRDUDE_MCU) $(BUADRATE) -U flash:w:$(TARGET).hex:i

clean:
	rm -f $(OBJ) $(TARGET).elf $(TARGET).hex $(TARGET).map

.PHONY: all clean