Das bekannte RN-Control Demoprogramm in einer C Variante, bereitgestellt von Georg Richter.

RNControl-Test.c
Code:
/*
###################################################
RNControl-Test.c
Aufgabe:
 Dieses Testprogramm testet gleich mehrere Eigenschaften auf dem Board
 Den verschiedenen Tasten sind bestimmte Funktionen zugeordnet
 Taste 1: Zeigt Batteriespannung über RS232 an
 Taste 2: Angeschlossene Motoren beschleunigen und abbremsen
 Taste 3: Einige Male Lauflicht über LED´s anzeigen. Am I2C-Bus
          darf in diesem Moment nichts angeschlossen sein
 Taste 4: Zeigt analoge Messwerte an allen Port A PIN´s über RS232 an
 Taste 5: Zeigt digitalen I/O Zustand von PA0 bis PA5 an

 Sehr gut kann man aus dem Demo auch entnehmen wie Sound ausgegeben wird,
 wie Tasten abgefragt werden und wie Subroutinen und Funktionen angelegt werden
Autor: Georg Richter
#######################################################
*/
 
 
#include <stdlib.h> 
#include <avr/io.h>
#include <rncontrol.h>
 
 
/*### Variablen ###*/
const float referenzspannung = 0.0048828125; //Referenzwert zur Multiplikation mit den Werten der Analogports (0...1023), um auf die Voltzahl zu kommen (0...5). Ergibt sich aus 5/1024.
uint16_t analog;        //Variable für jeweils an einem Analogport gemessenen Wert, um nicht für eine Ausgabe mehrere Messungen durchführen zu müssen.
char wort[5];         //Zahlen (Integer und Float) müssen vor der Ausgabe per RS232 in ASCII-Zeichen konvertiert werden, für die ein Speicher benötigt wird.
 
 
/*### Batteriespannung ###*/
void Batteriespannung(void)
{
 sendUSART("Analog6 = "); analog = adcwert(6);
 utoa(analog, wort, 10); sendUSART(wort); sendUSART(" = ");
 dtostrf(analog*referenzspannung, 11, 8, wort); sendUSART(wort); sendUSART(" Volt\r\n");
 dtostrf(adcwert(6)*referenzspannung*5.66804, 11, 8, wort);
 sendUSART("Batteriespannung = "); sendUSART(wort); sendUSART(" Volt\r\n\n\n\n");
 waitms(300);
}
 
 
/*### Motortest ###*/
void Motortest(void)
{
 Mlinksvor();
 Mrechtsvor();
 setPWMlinks(0);
 setPWMrechts(0);
 waitms(40);
 for(uint8_t i=0; i<255; i=i+5)
 {
  setPWMlinks(i);
  setPWMrechts(i);
  waitms(40);
 }
 setPWMlinks(255);
 setPWMrechts(255);
 waitms(40);
 for(uint8_t i=255; i>0; i=i-5)
 {
  setPWMlinks(i);
  setPWMrechts(i);
  waitms(40);
 }
 setPWMlinks(0);
 setPWMrechts(0);
 Mlinksstop();
 Mrechtsstop();
 waitms(300);
}
 
 
/*### LED-Lauflicht ###*/
void Lauflicht(void)
{
 for(uint8_t i=0; i<10; i++)
 {
 setportcoff(0);
 waitms(150);
 setportcon(0);
 setportcoff(1);
 waitms(150);
 setportcon(1);
 setportcoff(2);
 waitms(150);
 setportcon(2);
 setportcoff(3);
 waitms(150);
 setportcon(3);
 setportcoff(4);
 waitms(150);
 setportcon(4);
 setportcoff(5);
 waitms(150);
 setportcon(5);
 waitms(300);
 }
}
 
 
/*### Analogwerte ###*/
void Analogwerte(void)
{
 //Alle internen Pullups an, ausgenommen Port A3 und Batteriespannung/Taster (A6 und A7). Da A3 aber nun auch nicht auf GND liegt, ergibt sich ein "Rauschen", der Wert variiert mit jeder Messung mehr oder weniger stark.
 setportaon(0);
 setportaon(1);
 setportaon(2);
 setportaoff(3);
 setportaon(4);
 setportaon(5);
 
 for(uint8_t i=0; i<8; i++)
 {
  analog = adcwert(i);                  //Messung Analogport [i]
  utoa(i, wort, 10); sendUSART("Analog"); sendUSART(wort); sendUSART(" = ");    //Ausgabe: "Analog[i] = "
  utoa(analog, wort, 10); sendUSART(wort); sendUSART(" = ");         //Ausgabe: "[Analogwert] = "
  dtostrf(analog*referenzspannung, 11, 8, wort); sendUSART(wort); sendUSART(" Volt\r\n"); //AUsgabe: "[Reale Voltzahl] Volt[Umbruch]"
 }
 
 sendUSART("\n\n\n");
 waitms(300);
}
 
 
/*### Digitalwerte ###*/
void Digitalwerte(void)
{
 //Einige interne Pullups an, andere aus -> gibt bei einigen "Rauscheffekt", mal misst er "high", mal "low" und mal irgendwas dazwischen "?".
 //Ein kleines Stückchen Draht an einem der Ports wirkt wahre Wunder, was das Rauschen betrifft -> viel öfter "low" dabei als ohne. Nachteil: Die Tastenerkennung funktioniert kaum noch.
 setportaoff(0);
 setportaon(1);
 setportaoff(2);
 setportaon(3);
 setportaon(4);
 setportaon(5);
 
 for(uint8_t i=0; i<8; i++)
 {
  utoa(i, wort, 10); sendUSART("Digital"); sendUSART(wort); sendUSART(" = "); //Ausgabe: "Digital[i] = "
  if (PINA & (1<<PINA0)) {sendUSART("high");} else {sendUSART("low");}   //Abgleich des Zustandes - Ausgabe: "high" oder "low"
  sendUSART("\r\n");
 }
 
 sendUSART("\n\n\n");
 waitms(300);
}
 
 
/*### Hauptschleife ###*/
int main(void)
{
 /*###Initialisierungsphase###*/
 //Pins bzw. Ports als Ein-/Ausgänge konfigurieren
 DDRA |= 0x00; //00000000 -> alle Analogports als Eingänge
 DDRB |= 0x03; //00000011 -> PORTB.0 und PORTB.1 sind Kanäle des rechten Motors
 DDRC |= 0xFF; //11111111 -> PORTC.6 und PORTC.7 sind Kanäle des linken Motors, Rest sind LEDs für Lauflicht
 DDRD |= 0xB0; //10110000 -> PORTD.4 ist PWM-Kanal des linken Motors, PORTD.5 des rechten
 
 //Initialisierungen
 setportcon(0); setportcon(1); setportcon(2); setportcon(3); setportcon(4); setportcon(5); //LEDs ausschalten
 setportdoff(7); //Speaker aus
 init_timer1(); //Initialisierung Timer für PWM
 init_USART(); //USART konfigurieren
 
 /*###Hauptschleife###*/
 sound(6, 270); //Startmelodie
 sound(8, 270);
 sound(11, 270);
 sound(7, 270);
 waitms(10);
 sound(7, 270);
 sound(6, 270);
 sound(11, 540);
 sendUSART("\r\n\n\n"); //Sendet einen kleinen Begrüßungstext. "\r" setzt den Cursor wieder auf Zeilenanfag, "\n" beginnt dann die nächste Zeile
 sendUSART("**** RN-Control 1.4 *****\r\n");
 sendUSART(" \r\n");
 sendUSART("Fuer C umgeschrieben Version des mitgelieferten\r\n");
 sendUSART("Bascom-BASIC Beispielprogramms inkl. eigener\r\n"); 
 sendUSART("Header-Datei mit wichtigen Grundfunktionen.\r\n");
 sendUSART(" \r\n");
 sendUSART("Vielen Dank an die RN-Community fuer ihre Hilfe!\r\n\n\n\n");
 
 Mlinksstop();
 Mrechtsstop();

 setPWMlinks(0);
 setPWMrechts(0);

 while(1)
 {
  switch(button())
  {
   case 1: Batteriespannung(); break;
   case 2: Motortest(); break;
   case 3: Lauflicht(); break;
   case 4: Analogwerte(); break;
   case 5: Digitalwerte(); break;
   default: break;
  }
 }
 
 
 return 0;
}


rncontrol.h
Code:
/*
###################################################
rncontrol.h
Diese Header-Datei stellt grundlegende Funktionen für das RN-Control 1.4 in C zur Verfügung.
Autor: Georg Richter
#######################################################
*/

#include <util/delay.h>
 
/*### waitms - Programm pausieren lassen ###*/
/*Die Funktion lässt circa so viele Millisekunden verstreichen, wie angegeben werden.
Angepasst auf das RN-Control 1.4 mit 16 MHz-Quarz!
Vorsicht, Wert ist nur experimentell angenähert, nicht exakt berechnet!*/
void waitms(uint16_t ms)
{
 for(; ms>0; ms--)
 {
  uint16_t __c = 4000;
  __asm__ volatile (
   "1: sbiw %0,1" "\n\t"
   "brne 1b"
   : "=w" (__c)
   : "0" (__c)
  );
 }
}
 

/*### Ports setzen ###*/
//Ports auf HIGH setzen
static inline void setportaon(const uint8_t n)
{PORTA |= (1<<n);} //set PORTA.n high
static inline void setportbon(const uint8_t n)
{PORTB |= (1<<n);} //set PORTB.n high
static inline void setportcon(const uint8_t n)
{PORTC |= (1<<n);} //set PORTC.n high
static inline void setportdon(const uint8_t n)
{PORTD |= (1<<n);} //set PORTD.n high
 
//Ports auf LOW setzen
static inline void setportaoff(const uint8_t n)
{PORTA &= ~(1<<n);} //set PORTA.n low
static inline void setportboff(const uint8_t n)
{PORTB &= ~(1<<n);} //set PORTB.n low
static inline void setportcoff(const uint8_t n)
{PORTC &= ~(1<<n);} //set PORTC.n low
static inline void setportdoff(const uint8_t n)
{PORTD &= ~(1<<n);} //set PORTD.n low
 
 
/*### Senden per USART - RS232-Kommunikation ###*/
/*Zum senden von Zeichen im Hauptprogramm entweder
char irgendwas[] = "meintext";
sendUSART(irgendwas);
oder direkt
sendUSART("meinText");
verwenden.*/ 
void init_USART(void)
{
 UCSRB |= (1<<TXEN); //UART TX (Transmit - senden) einschalten
 UCSRC |= (1<<URSEL)|(3<<UCSZ0); //Modus Asynchron 8N1 (8 Datenbits, No Parity, 1 Stopbit)
 UBRRH = 0;    //Highbyte ist 0
 UBRRL = 103;   //Lowbyte ist 103 (dezimal) -> (Frequenz_in_Hz / (Baudrate * 16)) - 1 <- Quarfrequenz = 16*1000*1000 Hz!!!!
}
 
void sendchar(unsigned char c)
{
 while(!(UCSRA & (1<<UDRE))) //Warten, bis Senden möglich ist
 {
 }
 
 UDR = c; //schreibt das Zeichen aus 'c' auf die Schnittstelle
}
 
void sendUSART(char *s) //*s funktiniert wie eine Art Array - auch bei einem String werden die Zeichen (char) einzeln ausgelesen - und hier dann auf die Sendeschnittstelle übertragen
{
 while(*s)
 {
 sendchar(*s);
 s++;
 }
}
 
 
/*### ADC-Ansteuerung ###*/
uint16_t adcwert(uint8_t kanal)
{
 uint16_t wert = 0;          //Variable für Ergebnis deklarieren
 ADCSRA = (1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0); //ADEN aktiviert überhaupt erst den internen ADC-Wandler, ADPS2 bis ADPS0 stellen den verwendeten Prescaler ein, denn die Wandlerfrequenz muss immer zwischen 50 und 200 kHz liegen! Der Prescaler muss bei 16MHz also zwischen 80 und 320 eingestellt werden, als einzige Möglichkeit bleibt hier 128 (=alle auf 1).   
 ADMUX = kanal;
 //ADMUX = (1<<REFS1)|(1<<REFS0);      //Einstellen der Referenzspannung auf "extern", also REFS1 und REFS0 auf "0" - daher auskommentierte Zeile
 
 ADCSRA |= (1<<ADSC);         //nach Aktivierung des ADC wird ein "Dummy-Readout" empfohlen, man liest also einen Wert und verwirft diesen, um den ADC "warmlaufen zu lassen"      
    while(ADCSRA & (1<<ADSC)) {}       //auf Abschluss der Konvertierung warten
 wert = ADCW;           //ADCW muss einmal gelesen werden, sonst wird Ergebnis der nächsten Wandlung nicht übernommen.
 
 /* Eigentliche Messung - Mittelwert aus 4 aufeinanderfolgenden Wandlungen */
 wert = 0; 
 for(uint8_t i=0; i<4; i++)
 {
  ADCSRA |= (1<<ADSC);    //eine Wandlung "single conversion" starten
  while(ADCSRA & (1<<ADSC)) {}  //auf Abschluss der Konvertierung warten
  wert = wert + ADCW;        //Wandlungsergebnisse aufaddieren
    }
 
 ADCSRA &= ~(1<<ADEN);     //ADC deaktivieren
 
 wert = wert/4;       //Durchschnittswert bilden
 
 return wert;
}
 
 
/*### Buttonabfrage ###*/
uint8_t button(void)
{
 uint8_t taste = 0;    //Variable für Nummer des Tasters
 uint16_t analog7 = adcwert(7); //Wert des Ports
 
 setportaon(7);     //Ohne das hier "flackern" die Werte aus irgend einem Grund -> es werden mitunter Tasten erkannt, die gar nicht gedrückt wurden oder das Programm bleibt für einige Sekunden "hängen"
 waitms(1);
 setportaoff(7);
 
 //Abfrage des gedrückten Tasters - um Störungen zu vermeiden wurden die Bereiche sehr eng gefasst, sollten bei Bedarf an jedes Board extra angepasst werden.
 if((analog7>=337) && (analog7<=343)) {taste = 1;}
 else if((analog7>=268) && (analog7<=274)) {taste = 2;}
 else if((analog7>=200) && (analog7<=206)) {taste = 3;}
 else if((analog7>=132) && (analog7<=138)) {taste = 4;}
 else if((analog7>=64) && (analog7<=70)) {taste = 5;}
 else {}
 
 return taste;
}
 
 
/*### Sound durch den Speaker ausgeben ###*/
/*i wird immer um das doppelte der Tonhöhe hochgezählt. Grund: Um so tiefer
der Ton, desto größer ist "hoehe" -> desto länger sind die Pausenzeiten pro
"Tonschwingung". Dadurch würden tiefe Töne immer länger werden, was durch
diese Funktion abgefangen wird. Alle Töne mit der Länge x werden auch
ca x ms lang gespielt. Vernachlässigt wird hierbei jedoch die benötigte Zeit
zum Umschalten der Pins und Hochzählen der Schleife, um so höher der Ton, 
desto länger wird er also real gespielt, weil öfter gezählt und umgeschaltet
werden muss. Bei hoehe=1 benötigt ein Ton etwa das 1,733-fache der Zeit, die
als Dauer angegeben wird; bei hoehe=30 wird sie hingegen beinahe eingehalten.
Der Multiplikator von 15 in der Länge gleicht die seltsame Dauer, die die
Delay-Schleife hat, aus (die kommt aus irgend einem Grund nicht mal annähernd
an Millisekunden heran).*/
void sound(uint8_t hoehe, uint16_t laenge)
{
 for(uint16_t i=0; i<laenge*15; i=i+(2*hoehe))
 {
 setportdon(7);
 _delay_ms(hoehe);
 setportdoff(7);
 _delay_ms(hoehe);
 }
}
 
 
/*### PWM-Routinen zur Motoransteuerung ###*/
void init_timer1(void) //Initialisierung des Timers für Erzeugung des PWM-Signals
{
   /* normale 8-bit PWM aktivieren (nicht invertiert),
   Das Bit WGM10 wird im Datenblatt auch als PWM10 bezeichnet */
   TCCR1A = (1<<COM1A1)|(1<<COM1B1)|(1<<WGM10);
   /* Einstellen der PWM-Frequenz auf 14 kHz ( Prescaler = 1 ) */
   TCCR1B = (1<<CS10);
   /* Interrupts für Timer1 deaktivieren
   Achtung : Auch die Interrupts für die anderen Timer stehen in diesem Register */
   TIMSK &= ~0x3c;
}
 
void setPWMlinks(uint8_t speed) //Geschwindigkeit linker Motor
{OCR1BL = speed;}
void setPWMrechts(uint8_t speed) //Geschwindigkeit rechter Motor
{OCR1AL = speed;}
 
void Mlinkszur(void) //Uhrzeigersinn
{PORTC |= (1<<PC6); PORTC &= ~(1<<PC7);}
void Mlinksvor(void) //mathematischer Drehsinn
{PORTC &= ~(1<<PC6); PORTC |= (1<<PC7);}
void Mlinksstop(void) //aus
{ PORTC &= ~(1<<PC6); PORTC &= ~(1<<PC7);}
 
void Mrechtsvor(void) //Uhrzeigersinn
{PORTB |= (1<<PB0); PORTB &= ~(1<<PB1);}
void Mrechtszur(void) //mathematischer Drehsinn
{PORTB &= ~(1<<PB0); PORTB |= (1<<PB1);}
void Mrechtsstop(void) //aus
{ PORTB &= ~(1<<PB0); PORTB &= ~(1<<PB1);}

Makefile
Code:
# Hey Emacs, this is a -*- makefile -*-
#
# WinAVR Sample makefile written by Eric B. Weddington, Jörg Wunsch, et al.
# Released to the Public Domain
# Please read the make user manual!
#
# Additional material for this makefile was submitted by:
#  Tim Henigan
#  Peter Fleury
#  Reiner Patommel
#  Sander Pool
#  Frederik Rouleau
#  Markus Pfaff
#
# On command line:
#
# make all = Make software.
#
# make clean = Clean out built project files.
#
# make coff = Convert ELF to AVR COFF (for use with AVR Studio 3.x or VMLAB).
#
# make extcoff = Convert ELF to AVR Extended COFF (for use with AVR Studio
#                4.07 or greater).
#
# make program = Download the hex file to the device, using avrdude.  Please
#                customize the avrdude settings below first!
#
# make filename.s = Just compile filename.c into the assembler code only
#
# To rebuild project do "make clean" then "make all".
#

# MCU name
MCU = atmega16
# Output format. (can be srec, ihex, binary)
FORMAT = ihex
# Target file name (without extension).
TARGET = RNControl

# List C source files here. (C dependencies are automatically generated.)
SRC = $(TARGET).c

# List Assembler source files here.
# Make them always end in a capital .S.  Files ending in a lowercase .s
# will not be considered source files but generated files (assembler
# output from the compiler), and will be deleted upon "make clean"!
# Even though the DOS/Win* filesystem matches both .s and .S the same,
# it will preserve the spelling of the filenames, and GCC itself does
# care about how the name is spelled on its command-line.
ASRC = 
 
# Optimization level, can be [0, 1, 2, 3, s]. 
# 0 = turn off optimization. s = optimize for size.
# (Note: 3 is not always the best optimization level. See avr-libc FAQ.)
OPT = s
# Debugging format.
# Native formats for AVR-GCC's -g are stabs [default], or dwarf-2.
# AVR (extended) COFF requires stabs, plus an avr-objcopy run.
DEBUG = stabs
# List any extra directories to look for include files here.
#     Each directory must be seperated by a space.
EXTRAINCDIRS = 

# Compiler flag to set the C Standard level.
# c89   - "ANSI" C
# gnu89 - c89 plus GCC extensions
# c99   - ISO C99 standard (not yet fully implemented)
# gnu99 - c99 plus GCC extensions
CSTANDARD = -std=gnu99
# Place -D or -U options here
CDEFS =
# Place -I options here
CINCS =

# Compiler flags.
#  -g*:          generate debugging information
#  -O*:          optimization level
#  -f...:        tuning, see GCC manual and avr-libc documentation
#  -Wall...:     warning level
#  -Wa,...:      tell GCC to pass this to the assembler.
#    -adhlns...: create assembler listing
CFLAGS = -g$(DEBUG)
CFLAGS += $(CDEFS) $(CINCS)
CFLAGS += -O$(OPT)
CFLAGS += -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums
CFLAGS += -Wall -Wstrict-prototypes
CFLAGS += -Wa,-adhlns=$(<:.c=.lst)
CFLAGS += $(patsubst %,-I%,$(EXTRAINCDIRS))
CFLAGS += $(CSTANDARD)
 
# Assembler flags.
#  -Wa,...:   tell GCC to pass this to the assembler.
#  -ahlms:    create listing
#  -gstabs:   have the assembler create line number information; note that
#             for use in COFF files, additional information about filenames
#             and function names needs to be present in the assembler source
#             files -- see avr-libc docs [FIXME: not yet described there]
ASFLAGS = -Wa,-adhlns=$(<:.S=.lst),-gstabs 
 
#Additional libraries.
# Minimalistic printf version
PRINTF_LIB_MIN = -Wl,-u,vfprintf -lprintf_min
# Floating point printf version (requires MATH_LIB = -lm below)
PRINTF_LIB_FLOAT = -Wl,-u,vfprintf -lprintf_flt
PRINTF_LIB = 
# Minimalistic scanf version
SCANF_LIB_MIN = -Wl,-u,vfscanf -lscanf_min
# Floating point + %[ scanf version (requires MATH_LIB = -lm below)
SCANF_LIB_FLOAT = -Wl,-u,vfscanf -lscanf_flt
SCANF_LIB = 
MATH_LIB = -lm
# External memory options
# 64 KB of external RAM, starting after internal RAM (ATmega128!),
# used for variables (.data/.bss) and heap (malloc()).
#EXTMEMOPTS = -Wl,-Tdata=0x801100,--defsym=__heap_end=0x80ffff
# 64 KB of external RAM, starting after internal RAM (ATmega128!),
# only used for heap (malloc()).
#EXTMEMOPTS = -Wl,--defsym=__heap_start=0x801100,--defsym=__heap_end=0x80ffff
EXTMEMOPTS =
# Linker flags.
#  -Wl,...:     tell GCC to pass this to linker.
#    -Map:      create map file
#    --cref:    add cross reference to  map file
LDFLAGS = -Wl,-Map=$(TARGET).map,--cref
LDFLAGS += $(EXTMEMOPTS)
LDFLAGS += $(PRINTF_LIB) $(SCANF_LIB) $(MATH_LIB)
 

# Programming support using avrdude. Settings and variables.
# Programming hardware: alf AVR910 avrisp Bascom bsd 
# dt006 pavr picoweb pony-stk200 sp12 stk200 stk500
#
# Type: avrdude -c ?
# to get a full listing.
#
AVRDUDE_PROGRAMMER = stk200
# com1 = serial port. Use lpt1 to connect to parallel port.
AVRDUDE_PORT = lpt1
AVRDUDE_WRITE_FLASH = -U flash:w:$(TARGET).hex
#AVRDUDE_WRITE_EEPROM = -U eeprom:w:$(TARGET).eep

# Uncomment the following if you want avrdude's erase cycle counter.
# Note that this counter needs to be initialized first using -Yn,
# see avrdude manual.
#AVRDUDE_ERASE_COUNTER = -y
# Uncomment the following if you do /not/ wish a verification to be
# performed after programming the device.
#AVRDUDE_NO_VERIFY = -V
# Increase verbosity level.  Please use this when submitting bug
# reports about avrdude. See <http://savannah.nongnu.org/projects/avrdude> 
# to submit bug reports.
#AVRDUDE_VERBOSE = -v -v
AVRDUDE_FLAGS = -p $(MCU) -P $(AVRDUDE_PORT) -c $(AVRDUDE_PROGRAMMER)
AVRDUDE_FLAGS += $(AVRDUDE_NO_VERIFY)
AVRDUDE_FLAGS += $(AVRDUDE_VERBOSE)
AVRDUDE_FLAGS += $(AVRDUDE_ERASE_COUNTER)
 
# ---------------------------------------------------------------------------
# Define directories, if needed.
DIRAVR = c:/winavr
DIRAVRBIN = $(DIRAVR)/bin
DIRAVRUTILS = $(DIRAVR)/utils/bin
DIRINC = .
DIRLIB = $(DIRAVR)/avr/lib

# Define programs and commands.
SHELL = sh
CC = avr-gcc
OBJCOPY = avr-objcopy
OBJDUMP = avr-objdump
SIZE = avr-size
NM = avr-nm
AVRDUDE = avrdude
REMOVE = rm -f
COPY = cp
 

# Define Messages
# English
MSG_ERRORS_NONE = Errors: none
MSG_BEGIN = -------- begin --------
MSG_END = --------  end  --------
MSG_SIZE_BEFORE = Size before: 
MSG_SIZE_AFTER = Size after:
MSG_COFF = Converting to AVR COFF:
MSG_EXTENDED_COFF = Converting to AVR Extended COFF:
MSG_FLASH = Creating load file for Flash:
MSG_EEPROM = Creating load file for EEPROM:
MSG_EXTENDED_LISTING = Creating Extended Listing:
MSG_SYMBOL_TABLE = Creating Symbol Table:
MSG_LINKING = Linking:
MSG_COMPILING = Compiling:
MSG_ASSEMBLING = Assembling:
MSG_CLEANING = Cleaning project:
 

# Define all object files.
OBJ = $(SRC:.c=.o) $(ASRC:.S=.o) 
# Define all listing files.
LST = $(ASRC:.S=.lst) $(SRC:.c=.lst)

# Compiler flags to generate dependency files.
GENDEPFLAGS = -Wp,-M,-MP,-MT,$(*F).o,-MF,.dep/$(@F).d

# Combine all necessary flags and optional flags.
# Add target processor to flags.
ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) $(GENDEPFLAGS)
ALL_ASFLAGS = -mmcu=$(MCU) -I. -x assembler-with-cpp $(ASFLAGS)
 
 
# Default target.
all: begin gccversion sizebefore build sizeafter finished end
build: elf hex eep lss sym extcoff
elf: $(TARGET).elf
hex: $(TARGET).hex
eep: $(TARGET).eep
lss: $(TARGET).lss 
sym: $(TARGET).sym
 
# Eye candy.
# AVR Studio 3.x does not check make's exit code but relies on
# the following magic strings to be generated by the compile job.
begin:
 @echo
 @echo $(MSG_BEGIN)
finished:
 @echo $(MSG_ERRORS_NONE)
end:
 @echo $(MSG_END)
 @echo

# Display size of file.
HEXSIZE = $(SIZE) --target=$(FORMAT) $(TARGET).hex
ELFSIZE = $(SIZE) -A $(TARGET).elf
sizebefore:
 @if [ -f $(TARGET).elf ]; then echo; echo $(MSG_SIZE_BEFORE); $(ELFSIZE); echo; fi
sizeafter:
 @if [ -f $(TARGET).elf ]; then echo; echo $(MSG_SIZE_AFTER); $(ELFSIZE); echo; fi
 
# Display compiler version information.
gccversion : 
 @$(CC) --version
 
# Program the device.  
program: $(TARGET).hex $(TARGET).eep
 $(AVRDUDE) $(AVRDUDE_FLAGS) $(AVRDUDE_WRITE_FLASH) $(AVRDUDE_WRITE_EEPROM)
 

# Convert ELF to COFF for use in debugging / simulating in AVR Studio or VMLAB.
COFFCONVERT=$(OBJCOPY) --debugging \
--change-section-address .data-0x800000 \
--change-section-address .bss-0x800000 \
--change-section-address .noinit-0x800000 \
--change-section-address .eeprom-0x810000 

coff: $(TARGET).elf
 @echo
 @echo $(MSG_COFF) $(TARGET).cof
 $(COFFCONVERT) -O coff-avr $< $(TARGET).cof

extcoff: $(TARGET).elf
 @echo
 @echo $(MSG_EXTENDED_COFF) $(TARGET).cof
 $(COFFCONVERT) -O coff-ext-avr $< $(TARGET).cof
 
# Create final output files (.hex, .eep) from ELF output file.
%.hex: %.elf
 @echo
 @echo $(MSG_FLASH) $@
 $(OBJCOPY) -O $(FORMAT) -R .eeprom $< $@
%.eep: %.elf
 @echo
 @echo $(MSG_EEPROM) $@
 -$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \
 --change-section-lma .eeprom=0 -O $(FORMAT) $< $@
# Create extended listing file from ELF output file.
%.lss: %.elf
 @echo
 @echo $(MSG_EXTENDED_LISTING) $@
 $(OBJDUMP) -h -S $< > $@
# Create a symbol table from ELF output file.
%.sym: %.elf
 @echo
 @echo $(MSG_SYMBOL_TABLE) $@
 $(NM) -n $< > $@
 
# Link: create ELF output file from object files.
.SECONDARY : $(TARGET).elf
.PRECIOUS : $(OBJ)
%.elf: $(OBJ)
 @echo
 @echo $(MSG_LINKING) $@
 $(CC) $(ALL_CFLAGS) $(OBJ) --output $@ $(LDFLAGS)

# Compile: create object files from C source files.
%.o : %.c
 @echo
 @echo $(MSG_COMPILING) $<
 $(CC) -c $(ALL_CFLAGS) $< -o $@ 

# Compile: create assembler files from C source files.
%.s : %.c
 $(CC) -S $(ALL_CFLAGS) $< -o $@

# Assemble: create object files from assembler source files.
%.o : %.S
 @echo
 @echo $(MSG_ASSEMBLING) $<
 $(CC) -c $(ALL_ASFLAGS) $< -o $@
 
# Target: clean project.
clean: begin clean_list finished end
clean_list :
 @echo
 @echo $(MSG_CLEANING)
 $(REMOVE) $(TARGET).hex
 $(REMOVE) $(TARGET).eep
 $(REMOVE) $(TARGET).obj
 $(REMOVE) $(TARGET).cof
 $(REMOVE) $(TARGET).elf
 $(REMOVE) $(TARGET).map
 $(REMOVE) $(TARGET).obj
 $(REMOVE) $(TARGET).a90
 $(REMOVE) $(TARGET).sym
 $(REMOVE) $(TARGET).lnk
 $(REMOVE) $(TARGET).lss
 $(REMOVE) $(OBJ)
 $(REMOVE) $(LST)
 $(REMOVE) $(SRC:.c=.s)
 $(REMOVE) $(SRC:.c=.d)
 $(REMOVE) .dep/*
 
# Include the dependency files.
-include $(shell mkdir .dep 2>/dev/null) $(wildcard .dep/*)

# Listing of phony targets.
.PHONY : all begin finish end sizebefore sizeafter gccversion \
build elf hex eep lss sym coff extcoff \
clean clean_list program