
PROGRAM=lights
SRC=version.c main.c logging.c pwm.c adc.c pwmled.c pattern.c buttons.c \
	control.c battery.c wdt.c
OBJ=$(SRC:.c=.o)


MCU=attiny45
AVRDUDE_MCU=$(MCU)
AVRDUDE_PROGRAMMER=usbasp

CFLAGS=-Wall -Os -mmcu=$(MCU) -DUSE_LOGGING=1 -DF_CPU=1000000UL -std=gnu99
LDFLAGS=
AVRDUDE_FLAGS= -p$(AVRDUDE_MCU) -c $(AVRDUDE_PROGRAMMER)

FORMAT=ihex

CC=avr-gcc
OBJCOPY=avr-objcopy
OBJDUMP=avr-objdump
AVRDUDE=avrdude

all: $(PROGRAM).hex $(PROGRAM).eep

program: $(PROGRAM).hex $(PROGRAM).eep
	$(AVRDUDE) $(AVRDUDE_FLAGS) -U flash:w:$(PROGRAM).hex:i -U eeprom:w:$(PROGRAM).eep:i

program_flash: $(PROGRAM).hex
	$(AVRDUDE) $(AVRDUDE_FLAGS) -U flash:w:$(PROGRAM).hex:i

program_eeprom: $(PROGRAM).eep
	$(AVRDUDE) $(AVRDUDE_FLAGS) eeprom:w:$(PROGRAM).eep:i

dump_eeprom:
	$(AVRDUDE) $(AVRDUDE_FLAGS) -U eeprom:r:eeprom.raw:r
	od -tx1 eeprom.raw

objdump: $(PROGRAM).elf
	$(OBJDUMP) --disassemble $<

.PRECIOUS : $(OBJ) $(PROGRAM).elf

%.hex: %.elf
	$(OBJCOPY) -O $(FORMAT) -R .eeprom $< $@

%.eep: %.elf
	$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \
		--change-section-lma .eeprom=0 -O $(FORMAT) $< $@

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

%.o: %.c lights.h Makefile
	$(CC) -c $(CFLAGS) $< -o $@

%.s: %.c lights.h Makefile
	$(CC) -S -c $(CFLAGS) $< -o $@

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

clean:
	rm -f $(PROGRAM).hex $(PROGRAM).eep $(PROGRAM).elf *.o *.s eeprom.raw

version.c:
	./version.pl > version.c

.PHONY: all clean dump_eeprom program program_flash program_eeprom objdump version.c

