
TARG=BDMICRO

ifeq ($(TARG),STK_PROTO)
ARCH = atmega16
UISP_PART = ATmega16
CLOCK_SPEED = 8000000
FUSE_HIGH=0xd9
FUSE_LOW=0xe0
endif

ifeq ($(TARG),ROTOMOTION)
ARCH = atmega32
UISP_PART = ATmega32
CLOCK_SPEED = 16000000
FUSE_HIGH=0xd9 # this disables its bootloader
FUSE_LOW=0xef
endif

ifeq ($(TARG),BDMICRO)
ARCH = atmega128
UISP_PART = ATmega128
CLOCK_SPEED = 16000000
FUSE_HIGH=0x89  # same as BD ships
FUSE_LOW=0x3f   # sams as BD ships
endif


ODIR=build.$(TARG)

CC		= avr-gcc -mmcu=$(ARCH)
LD		= $(CC)
SIZE		= avr-size

UISP		= uisp -v

UISP_FLAGS	=							\
	-dprog=stk500							\
	-dpart=$(UISP_PART)						\
	-dserial=/dev/cuaa0						\
	-dspeed=115200							\

# Generally trade space for speed, since I have 128 kb of RAM and don't use much of it
CFLAGS = -O4 -W -Wall -DCLOCK_SPEED=$(CLOCK_SPEED) -D__$(TARG)__

LDFLAGS	= -lm

all: $(ODIR)/unicycle.dis

install: unicycle.install

.PRECIOUS: $(ODIR)/unicycle.srec $(ODIR)/unicycle.elf

unicycle.srcs = scooter.c uart.c adc.c
unicycle.hdrs = debug.h adc.h uart.h

unicycle.objs = $(unicycle.srcs:%.c=$(ODIR)/%.o)

$(ODIR)/unicycle.elf: $(unicycle.objs)

$(ODIR)/%.elf:
	$(LD) $($(*:.elf=).objs) -o $@ $(LDFLAGS)
	$(SIZE) $@

$(ODIR)/%.o : %.c
	mkdir -p $(ODIR)
	$(CC) $(CFLAGS) -o $@ -c $+

$(ODIR)/%.s : %.c
	mkdir -p $(ODIR)
	$(CC) $(CFLAGS) -o $@ -S $+

$(ODIR)/%.srec: $(ODIR)/%.elf
	avr-objcopy -O srec $< $@

$(ODIR)/%.hex: $(ODIR)/%.elf
	avr-objcopy -O ihex $< $@

$(ODIR)/%.dis : $(ODIR)/%.elf
	avr-objdump -d $+ > $@

%.install: $(ODIR)/%.srec
	$(UISP) $(UISP_FLAGS) --erase --upload if=$<

fuses: 
	$(UISP) $(UISP_FLAGS) --wr_fuse_h=$(FUSE_HIGH) --wr_fuse_l=$(FUSE_LOW)

%.cubeinstall: $(ODIR)/%.srec
	sudo ssh cube "cat >/tmp/$*.srec ; $(UISP) $(UISP_FLAGS) --erase --upload if=/tmp/$*.srec" < $<

%.cubeverify: $(ODIR)/%.srec
	sudo ssh cube "cat >/tmp/$*.srec ; $(UISP) $(UISP_FLAGS) --verify if=/tmp/$*.srec" < $<

cubefuses: 
	sudo ssh cube "$(UISP) $(UISP_FLAGS) --wr_fuse_h=$(FUSE_HIGH) --wr_fuse_l=$(FUSE_LOW)"

clean:
	rm -fr build.*

depend:
	makedepend $(unicycle.srcs)

distname=unicycle-0.1a

dist:	$(distname).tgz
	cp $(distname).tgz $(HOME)/website/tlb

dist.srcs = $(unicycle.srcs) $(unicycle.hdrs) Makefile

$(distname).tgz: $(dist.srcs)
	rm -rf $(distname)
	mkdir -p $(distname)
	cp $(dist.srcs) $(distname)
	tar czf $@ $(distname)
	rm -rf $(distname)

# DO NOT DELETE

scooter.o: debug.h /usr/include/math.h /usr/include/sys/cdefs.h uart.h
scooter.o: /usr/include/inttypes.h /usr/include/machine/ansi.h
scooter.o: /usr/include/string.h adc.h
uart.o: debug.h uart.h /usr/include/inttypes.h /usr/include/machine/ansi.h
adc.o: adc.h /usr/include/inttypes.h /usr/include/machine/ansi.h debug.h
adc.o: uart.h
 