Simple test

From Egbert's Wiki

Compiling and testing your first program

I recommend the small program below that mirrors input pins on output LEDs. It is written for an STK500 and any cpu that has a B and a D port. Here is the source, save it to a file called mirror.c. It comes with a simple makefile but the Universal AVR Makefile by Psychogenic could also be used.

#include <avr/io.h>
#include <avr/wdt.h>

// Note: This is designed to run on an STK500.
// Please connect 10-pin jumpers from:
// PORTD to "SWITCHES"
// PORTB to "LEDS" 

int main(void) {
    // Disable the AVR's internal watchdog timer.
    wdt_disable();

    // Set PORTB as outputs; 
    DDRB = 0xFF;
    // Set the PIND as inputs. 
    DDRD = 0x00; 

    // Turn off all the outputs 
    PORTB = 0; 
    while (1) {
        uint8_t x;
        // Read PIND (switches)
        x = PIND;
        // Write value to PORTB (LEDs)
        PORTB = x; 
    }
}

Simple Makefile:

CC = avr-gcc
OBJCOPY = avr-objcopy
STRIP = avr-strip
PROGRAMMER = avrdude 
OBJDUMP = avr-objdump

# NOTE: Change this to match your AVR chip type. 
MCU = atmega8515
PROG_METHOD = stk500v2

# NOTE: Change this to match the serial port that your STK500 is connected to. 
PORT = /dev/ttyS0

SRECS = mirror.srec 

default: $(SRECS)

mirror: mirror.o

PROGRAMS=$(SRECS:.srec=)
OBJFILES=$(SRECS:.srec=.o)
ASSEMBLY=$(SRECS:.srec=.asm)

clean:
       rm -f $(SRECS) $(PROGRAMS) $(OBJFILES) $(ASSEMBLY)

%.o: %.c
       $(CC) -g -O -mmcu=$(MCU) -c $^ -o $@

%: %.o 
       $(CC) -g -O -mmcu=$(MCU) $^ -o $@

%.asm: %
       $(OBJDUMP) -S -d $^ > $@

%-stripped: %
       $(STRIP) $^ -o $@

%.srec: %-stripped
       $(OBJCOPY) -O srec $^ $@

program-%: %.srec
       $(PROGRAMMER) -c $(PROG_METHOD) -P $(PORT) -p $(MCU) -U flash:w:$^:s 

Alternatively edit some lines in the Universal AVR Makefile to reflect project name and programmer. Here are the settings to make 'mirror' for an at90mega8515, using the STK500 as programmer hardware via the first serial port.

MCU=atmega8515
PROGRAMMER_MCU=m8515 
PROJECTNAME=mirror
PRJSRC=mirror.c
INC=
LIBS=
OPTLEVEL=s
AVRDUDE_PROGRAMMERID=stk500v2
AVRDUDE_PORT=/dev/ttyS0

Next: Debugging Tools, Universal AVR Makefile Back: Building AVR GCC