Added VERY old code. Very cringy to look at, but hey, we all had to start somewhere...

This commit is contained in:
2018-01-08 23:37:31 -08:00
parent 7b18f6a807
commit df19ed7631
141 changed files with 26107 additions and 0 deletions

View File

@@ -0,0 +1,336 @@
#----------------------------------------------------------------------------
# Wunderboard Makefile Template written by Dan Albert
#----------------------------------------------------------------------------
#
# make all = Make software.
#
# make clean = Clean out built project files.
#
# make filename.s = Just compile filename.c into the assembler code only.
#
# To rebuild project do "make clean" then "make all".
#----------------------------------------------------------------------------
# Target file name.
TARGET = main
# List C source files here.
SRC = $(TARGET).c \
adc.c
# MCU name, you MUST set this to match the board you are using
# type "make clean" after changing this, so all files will be rebuilt
MCU = at90usb646
# Detect platform
UNAME = $(shell uname)
ifeq ($(UNAME),Linux)
ENV=unix
endif
ifeq ($(UNAME),Darwin)
ENV=unix
endif
ifndef ENV
ENV=windows
endif
ifeq ($(ENV),unix)
PROGRAM = dfu-programmer
PROGRAMFLAGS = $(MCU)
ERASE = erase
FLASH = flash "$(TARGET).hex"
START = start
else
PROGRAM = "C:/Program Files (x86)/Atmel/Flip 3.4.1/bin/batchisp.exe"
PROGRAMFLAGS = -device at90usb646 -hardware USB
ERASE = -operation erase F
FLASH = -operation loadbuffer "$(TARGET).hex" program verify
START = -operation start noreset 0
endif
# Processor frequency.
# Normally the first thing your program should do is set the clock prescaler,
# so your program will run at the correct speed. You should also set this
# variable to same clock speed. The _delay_ms() macro uses this, and many
# examples use this variable to calculate timings. Do not add a "UL" here.
F_CPU = 8000000
# Output format. (can be srec, ihex, binary)
FORMAT = ihex
# Object files directory
# To put object files in current directory, use a dot (.), do NOT make
# this an empty or blank macro!
OBJDIR = obj
# 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
# List any extra directories to look for include files here.
# Each directory must be seperated by a space.
# Use forward slashes for directory separators.
# For a directory that has spaces, enclose it in quotes.
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 for C sources
CDEFS = -DF_CPU=$(F_CPU)UL
#---------------- Compiler Options C ----------------
# -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 += $(CDEFS)
CFLAGS += -O$(OPT)
CFLAGS += -funsigned-char
CFLAGS += -funsigned-bitfields
CFLAGS += -ffunction-sections
CFLAGS += -fpack-struct
CFLAGS += -fshort-enums
CFLAGS += -Wall
CFLAGS += -Wstrict-prototypes
#CFLAGS += -mshort-calls
#CFLAGS += -fno-unit-at-a-time
#CFLAGS += -Wundef
#CFLAGS += -Wunreachable-code
#CFLAGS += -Wsign-compare
CFLAGS += -Wa,-adhlns=$(<:%.c=$(OBJDIR)/%.lst)
CFLAGS += $(patsubst %,-I%,$(EXTRAINCDIRS))
CFLAGS += $(CSTANDARD)
#---------------- Library Options ----------------
# 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
# If this is left blank, then it will use the Standard printf version.
PRINTF_LIB =
#PRINTF_LIB = $(PRINTF_LIB_MIN)
#PRINTF_LIB = $(PRINTF_LIB_FLOAT)
# 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
# If this is left blank, then it will use the Standard scanf version.
SCANF_LIB =
#SCANF_LIB = $(SCANF_LIB_MIN)
#SCANF_LIB = $(SCANF_LIB_FLOAT)
MATH_LIB = -lm
# List any extra directories to look for libraries here.
# Each directory must be seperated by a space.
# Use forward slashes for directory separators.
# For a directory that has spaces, enclose it in quotes.
EXTRALIBDIRS =
#---------------- Linker Options ----------------
# -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 += -Wl,--relax
LDFLAGS += -Wl,--gc-sections
LDFLAGS += $(patsubst %,-L%,$(EXTRALIBDIRS))
LDFLAGS += $(PRINTF_LIB) $(SCANF_LIB) $(MATH_LIB)
#LDFLAGS += -T linker_script.x
#============================================================================
# Define programs and commands.
SHELL = sh
CC = avr-gcc
OBJCOPY = avr-objcopy
OBJDUMP = avr-objdump
SIZE = avr-size
AR = avr-ar rcs
NM = avr-nm
REMOVE = rm -f
REMOVEDIR = rm -rf
COPY = cp
WINSHELL = cmd
# 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_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 C:
MSG_ASSEMBLING = Assembling:
MSG_CLEANING = Cleaning project:
MSG_CREATING_LIBRARY = Creating library:
# Define all object files.
OBJ = $(SRC:%.c=$(OBJDIR)/%.o)
# Define all listing files.
LST = $(SRC:%.c=$(OBJDIR)/%.lst)
# Compiler flags to generate dependency files.
GENDEPFLAGS = -MMD -MP -MF .dep/$(@F).d
# Combine all necessary flags and optional flags.
# Add target processor to flags.
ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) $(GENDEPFLAGS)
# Default target.
all: begin gccversion sizebefore build sizeafter end
# Change the build target to build a HEX file or a library.
build: elf hex eep lss sym
#build: lib
elf: $(TARGET).elf
hex: $(TARGET).hex
eep: $(TARGET).eep
lss: $(TARGET).lss
sym: $(TARGET).sym
LIBNAME=lib$(TARGET).a
lib: $(LIBNAME)
# 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)
end:
@echo $(MSG_END)
@echo
# Display size of file.
HEXSIZE = $(SIZE) --target=$(FORMAT) $(TARGET).hex
ELFSIZE = $(SIZE) --mcu=$(MCU) --format=avr $(TARGET).elf
sizebefore:
@if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_BEFORE); $(ELFSIZE); \
2>/dev/null; echo; fi
sizeafter:
@if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_AFTER); $(ELFSIZE); \
2>/dev/null; echo; fi
# Display compiler version information.
gccversion :
@$(CC) --version
# Create final output files (.hex, .eep) from ELF output file.
%.hex: %.elf
@echo
@echo $(MSG_FLASH) $@
$(OBJCOPY) -O $(FORMAT) -R .eeprom -R .fuse -R .lock -R .signature $< $@
%.eep: %.elf
@echo
@echo $(MSG_EEPROM) $@
-$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \
--change-section-lma .eeprom=0 --no-change-warnings -O $(FORMAT) $< $@ || exit 0
# Create extended listing file from ELF output file.
%.lss: %.elf
@echo
@echo $(MSG_EXTENDED_LISTING) $@
$(OBJDUMP) -h -S -z $< > $@
# Create a symbol table from ELF output file.
%.sym: %.elf
@echo
@echo $(MSG_SYMBOL_TABLE) $@
$(NM) -n $< > $@
# Create library from object files.
.SECONDARY : $(TARGET).a
.PRECIOUS : $(OBJ)
%.a: $(OBJ)
@echo
@echo $(MSG_CREATING_LIBRARY) $@
$(AR) $@ $(OBJ)
# Link: create ELF output file from object files.
.SECONDARY : $(TARGET).elf
.PRECIOUS : $(OBJ)
%.elf: $(OBJ)
@echo
@echo $(MSG_LINKING) $@
$(CC) $(ALL_CFLAGS) $^ --output $@ $(LDFLAGS)
# Compile: create object files from C source files.
$(OBJDIR)/%.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 $@
## Program
.PHONY: program
program: all
$(PROGRAM) $(PROGRAMFLAGS) $(ERASE)
$(PROGRAM) $(PROGRAMFLAGS) $(FLASH)
$(PROGRAM) $(PROGRAMFLAGS) $(START)
doxygen:
doxygen
# Target: clean project.
clean: begin clean_list end
clean_list :
@echo
@echo $(MSG_CLEANING)
$(REMOVE) $(TARGET).hex
$(REMOVE) $(TARGET).eep
$(REMOVE) $(TARGET).elf
$(REMOVE) $(TARGET).map
$(REMOVE) $(TARGET).sym
$(REMOVE) $(TARGET).lss
$(REMOVE) $(SRC:%.c=$(OBJDIR)/%.o)
$(REMOVE) $(SRC:%.c=$(OBJDIR)/%.lst)
$(REMOVE) $(SRC:.c=.s)
$(REMOVE) $(SRC:.c=.d)
$(REMOVEDIR) .dep
$(REMOVEDIR) $(OBJDIR)
# Create object files directory
$(shell mkdir $(OBJDIR) 2>/dev/null)
# 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 \
clean clean_list

View File

@@ -0,0 +1,28 @@
/**
@file adc.c
@brief Wunderboard ADC Helper Functions
@version .01
@section intro Code Overview
This is the code for the Wunderboard ADC helper functions.
*/
#include "adc.h"
unsigned char read_adc(uint8_t channel){
unsigned char test;
ADMUX = 0x60 | channel; // Set the channel to the one we want
ADCSRA = 0b11000110; // Start a new sample.
while ((ADCSRA & 0b00010000) == 0 ); // Wait for a Valid Sample
ADCSRA |= 0b00010000; // Tell ADC you have the sample you want.
ADCSRA |= 0b01000000; // Start a new sample.
while ((ADCSRA & 0b00010000) == 0 ); // Wait for a Valid Sample
ADCSRA |= 0b00010000; // Tell ADC you have the sample you want.
test = ADCH;
ADCSRA = 0x00; // Disable the ADC
return (test);
}

View File

@@ -0,0 +1,19 @@
/**
@file adc.h
@brief Wunderboard ADC Helper Functions
@version .01
@section intro Code Overview
This is the code for the Wunderboard ADC helper functions.
*/
#include <avr/io.h>
/**
The read_adc() function allows for taking 8 bit measurements from any of the single ended ADC inputs. The function call is blocking. eg. read_adc(5) would read from ADC channel 5.
@param channel This is the channel to be read.
@return This is the return value from the ADC.
*/
unsigned char read_adc(uint8_t channel);

View File

@@ -0,0 +1,228 @@
/**
@file main.c
@brief Lab 8 Starter Code
@version .01
@mainpage Lab 8 Starter Code
@section intro Code Overview
@section hw Hardware Pin Out
Port A:
A0 - A3 : Push Buttons
A4 - A7 : Slide Switches
Port B:
B0 - B3 : SPI (SD Card)
B4 : Nothing
B5 : Audio Out
B6 : Red Enable
B7 : Green Enable
Port C:
C0 - C7 : LED Array (Row)
Port D:
D0 - D1 : Nothing
D2 : Serial RX
D3 : Serial TX
D4 - D7 : Nothing
Port E:
E0 - E2 : LED Array (Column)
E3 : USB (UID)
E4 - E5 : Nothing
E6 : Relay
E7 : Nothing
Port F:
F0 : ADC Channel 0
F1 : ADC Channel 1
F2 : ADC Channel 2
F3 : ADC Channel 3
F4 : ADC Channel 4 (Audio In)
F5 : ADC Channel 5 (Accel X Axis)
F6 : ADC Channel 6 (Accel Y Axis)
F7 : ADC Channel 7 (Accel Z Axis (if installed))
*/
/** Includes */
#include <avr/io.h>
#include <util/delay.h>
#include "adc.h"
#include <stdlib.h>
#include <math.h>
/** Constants */
#define F_CPU 1000000U
#define DELAY .02
#define YMIN 180.0
#define STEPSIZE 2.75
#define SLOW 50
#define FAST 25
#define FASTEST 10
/** Global Variables */
/** Functions */
/** The initialize() function initializes all of the Data Direction Registers for the Wunderboard. Before making changes to DDRx registers, ensure that you have read the peripherals section of the Wunderboard user guide.*/
void initialize (void) {
/** Port A is the switches and buttons. They should always be inputs. ( 0 = Input and 1 = Output )*/
DDRA=0b00000000;
/** Port B has the LED Array color control, SD card, and audio-out on it. Leave DDRB alone. ( 0 = Input and 1 = Output )*/
DDRB=0b11000000;
/** Port C is for the 'row' of the LED array. They should always be outputs. ( 0 = Input and 1 = Output )*/
DDRC=0b11111111;
/** Port D has the Serial on it. Leave DDRB alone. ( 0 = Input and 1 = Output )*/
DDRD=0b00000000;
/** Port E has the LED Array Column control out on it. Leave DDRE alone. ( 0 = Input and 1 = Output )*/
DDRE=0b00000111;
/** Port F has the accelerometer and audio-in on it. Leave DDRF alone. ( 0 = Input and 1 = Output )*/
DDRF=0b00000000;
}
void clearArray(void)
{
PORTB &= ~((1 << PB6) | (1 << PB7)); // Disable latches
PORTC = 0x00;
PORTB |= (1 << PB6) | (1 << PB7); // Enable latches
PORTB &= ~((1 << PB6) | (1 << PB7)); // Disable latches
}
int readadcval(void){
char adcread = read_adc(5);
if(adcread <= 181){
return 0;
}else if((adcread == 182) | (adcread == 183)){
return 1;
}else if((adcread == 184) | (adcread == 185) | (adcread == 186)){
return 2;
}else if((adcread >= 187) & (adcread <= 191)){
return 4;
}else if((adcread == 192) | (adcread == 193) | (adcread == 194)){
return 6;
}else if((adcread == 195) | (adcread == 196) | (adcread == 197)){
return 7;
}else if(adcread >= 198){
return 8;
}
}
void printscreen(int loop, int loop3, const int *Red, const int *Green){
int arrval;
clearArray();
PORTE = loop3;
arrval = (loop+loop3);
PORTB = 0b10000000;
PORTC = Green[arrval];
_delay_ms(DELAY);
clearArray();
PORTB= 0b01000000;
PORTC = Red[arrval];
_delay_ms(DELAY);
clearArray();
}
/** Main Function */
int main (void) {
/** Local Varibles */
int loop = 0;
int *looppoint = &loop;
int loop2;
int loop3;
int speed = 20;
int adcreturn;
const int Red[136] = {0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00001000,0b00000000,0b00001000,0b00101000,0b00001000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00001000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000100,0b00000100,0b00010000,0b00010000,0b00010000,0b00010000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00010000,0b00010100,0b00000000,0b00000000,0b00001000,0b00001000,0b00000000,0b00000000,0b00001000,0b00000000,0b00101000,0b00000000,0b00001000,0b00000000,0b00000000,0b00100000,0b00100000,0b00000000,0b00000000,0b00101000,0b00100000,0b00000000,0b00000000,0b00000010,0b00000110,0b00001110,0b00000000,0b00001110,0b00000110,0b00000010,0b0000000,0b00000000,0b00000010,0b00000110,0b00001110,0b00001110,0b00000000,0b00001110,0b00000110,0b00000010,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00001000,0b00001000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000010,0b00000110,0b00001110,0b00011110,0b00011110,0b00000000,0b00000000,0b00000000,0b00000010,0b00000000,0b00000000,0b00001110,0b00111110,0b00011000,0b00111110,0b00001110,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000};
const int Green[136] = {0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000001,0b00000001,0b01000001,0b11000001,0b01000001,0b00000001,0b00000001,0b00001001,0b00000001,0b00001001,0b00101001,0b00001001,0b00000001,0b00000001,0b00000001,0b00000001,0b10000111,0b11000111,0b01000001,0b00000001,0b00000001,0b00001111,0b00001111,0b00000001,0b00000001,0b00001111,0b00001111,0b00000001,0b00000001,0b00001111,0b00001111,0b00000001,0b00000001,0b00001001,0b00000001,0b00000001,0b01000001,0b11100001,0b11100000,0b01000000,0b00000001,0b00000101,0b00000101,0b00010001,0b00010001,0b00010001,0b00010001,0b00000001,0b00000001,0b00000000,0b00000000,0b00000000,0b00010001,0b00010101,0b00000001,0b00000001,0b01001001,0b11001001,0b11000001,0b10000001,0b00001001,0b00000001,0b00101001,0b00000001,0b00001001,0b00000001,0b00000001,0b00100001,0b00100001,0b00000001,0b00000001,0b00101001,0b00100001,0b00000001,0b00000001,0b00000011,0b00000111,0b00001111,0b00000001,0b00001111,0b00000111,0b01000011,0b11000001,0b01000001,0b00000011,0b00000111,0b00001111,0b00001111,0b00000000,0b00001111,0b00000111,0b00000011,0b00000001,0b00000111,0b00000111,0b00000001,0b00000001,0b00001001,0b00001001,0b00000001,0b00000001,0b00000001,0b00000111,0b00000111,0b00000011,0b00000111,0b00001111,0b00011111,0b00011111,0b00000001,0b01000001,0b11100001,0b11100011,0b01000001,0b00000001,0b00000001,0b00000001,0b00000001,0b00000001,0b00000001,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000};
initialize();
clearArray();
while(1){
adcreturn = readadcval();
if(adcreturn == 4){
for(loop2 = 0; loop2 < 50 ; loop2++){
for(loop3 = 7 ; loop3 > -1 ; loop3--){
printscreen(loop, loop3, Red, Green);
}
}
}else if(adcreturn < 4){
for(loop ; loop >= 0 ; loop--){
if(adcreturn == 2){
speed = SLOW;
}else if(adcreturn == 1){
speed = FAST;
}else if(adcreturn == 0){
speed = FASTEST;
}
for(loop2 = 0 ; loop2 < speed ; loop2++){
for(loop3 = 7 ; loop3 > -1 ; loop3--){
printscreen(loop, loop3, Red, Green);
if(loop == 0){
loop = 128;
}
}
}
adcreturn = readadcval();
if((adcreturn < 4) != 1){
break;
}
}
}else if(adcreturn > 4){
for(loop ; loop <= 128 ; loop++){
if(adcreturn == 6){
speed = SLOW;
}else if(adcreturn == 7){
speed = FAST;
}else if(adcreturn == 8){
speed = FASTEST;
}
for(loop2 = 0 ; loop2 < speed ; loop2++){
for(loop3 = 7 ; loop3 > -1 ; loop3--){
printscreen(loop, loop3, Red, Green);
if(loop == 128){
loop = 0;
}
}
}
adcreturn = readadcval();
if((adcreturn > 4) != 1){
break;
}
}
}
}
}

View File

@@ -0,0 +1,335 @@
#----------------------------------------------------------------------------
# Wunderboard Makefile Template written by Dan Albert
#----------------------------------------------------------------------------
#
# make all = Make software.
#
# make clean = Clean out built project files.
#
# make filename.s = Just compile filename.c into the assembler code only.
#
# To rebuild project do "make clean" then "make all".
#----------------------------------------------------------------------------
# Target file name.
TARGET = main
# List C source files here.
SRC = $(TARGET).c \
# MCU name, you MUST set this to match the board you are using
# type "make clean" after changing this, so all files will be rebuilt
MCU = at90usb646
# Detect platform
UNAME = $(shell uname)
ifeq ($(UNAME),Linux)
ENV=unix
endif
ifeq ($(UNAME),Darwin)
ENV=unix
endif
ifndef ENV
ENV=windows
endif
ifeq ($(ENV),unix)
PROGRAM = dfu-programmer
PROGRAMFLAGS = $(MCU)
ERASE = erase
FLASH = flash "$(TARGET).hex"
START = start
else
PROGRAM = "C:/Program Files (x86)/Atmel/Flip 3.4.1/bin/batchisp.exe"
PROGRAMFLAGS = -device at90usb646 -hardware USB
ERASE = -operation erase F
FLASH = -operation loadbuffer "$(TARGET).hex" program verify
START = -operation start noreset 0
endif
# Processor frequency.
# Normally the first thing your program should do is set the clock prescaler,
# so your program will run at the correct speed. You should also set this
# variable to same clock speed. The _delay_ms() macro uses this, and many
# examples use this variable to calculate timings. Do not add a "UL" here.
F_CPU = 8000000
# Output format. (can be srec, ihex, binary)
FORMAT = ihex
# Object files directory
# To put object files in current directory, use a dot (.), do NOT make
# this an empty or blank macro!
OBJDIR = obj
# 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
# List any extra directories to look for include files here.
# Each directory must be seperated by a space.
# Use forward slashes for directory separators.
# For a directory that has spaces, enclose it in quotes.
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 for C sources
CDEFS = -DF_CPU=$(F_CPU)UL
#---------------- Compiler Options C ----------------
# -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 += $(CDEFS)
CFLAGS += -O$(OPT)
CFLAGS += -funsigned-char
CFLAGS += -funsigned-bitfields
CFLAGS += -ffunction-sections
CFLAGS += -fpack-struct
CFLAGS += -fshort-enums
CFLAGS += -Wall
CFLAGS += -Wstrict-prototypes
#CFLAGS += -mshort-calls
#CFLAGS += -fno-unit-at-a-time
#CFLAGS += -Wundef
#CFLAGS += -Wunreachable-code
#CFLAGS += -Wsign-compare
CFLAGS += -Wa,-adhlns=$(<:%.c=$(OBJDIR)/%.lst)
CFLAGS += $(patsubst %,-I%,$(EXTRAINCDIRS))
CFLAGS += $(CSTANDARD)
#---------------- Library Options ----------------
# 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
# If this is left blank, then it will use the Standard printf version.
PRINTF_LIB =
#PRINTF_LIB = $(PRINTF_LIB_MIN)
#PRINTF_LIB = $(PRINTF_LIB_FLOAT)
# 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
# If this is left blank, then it will use the Standard scanf version.
SCANF_LIB =
#SCANF_LIB = $(SCANF_LIB_MIN)
#SCANF_LIB = $(SCANF_LIB_FLOAT)
MATH_LIB = -lm
# List any extra directories to look for libraries here.
# Each directory must be seperated by a space.
# Use forward slashes for directory separators.
# For a directory that has spaces, enclose it in quotes.
EXTRALIBDIRS =
#---------------- Linker Options ----------------
# -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 += -Wl,--relax
LDFLAGS += -Wl,--gc-sections
LDFLAGS += $(patsubst %,-L%,$(EXTRALIBDIRS))
LDFLAGS += $(PRINTF_LIB) $(SCANF_LIB) $(MATH_LIB)
#LDFLAGS += -T linker_script.x
#============================================================================
# Define programs and commands.
SHELL = sh
CC = avr-gcc
OBJCOPY = avr-objcopy
OBJDUMP = avr-objdump
SIZE = avr-size
AR = avr-ar rcs
NM = avr-nm
REMOVE = rm -f
REMOVEDIR = rm -rf
COPY = cp
WINSHELL = cmd
# 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_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 C:
MSG_ASSEMBLING = Assembling:
MSG_CLEANING = Cleaning project:
MSG_CREATING_LIBRARY = Creating library:
# Define all object files.
OBJ = $(SRC:%.c=$(OBJDIR)/%.o)
# Define all listing files.
LST = $(SRC:%.c=$(OBJDIR)/%.lst)
# Compiler flags to generate dependency files.
GENDEPFLAGS = -MMD -MP -MF .dep/$(@F).d
# Combine all necessary flags and optional flags.
# Add target processor to flags.
ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) $(GENDEPFLAGS)
# Default target.
all: begin gccversion sizebefore build sizeafter end
# Change the build target to build a HEX file or a library.
build: elf hex eep lss sym
#build: lib
elf: $(TARGET).elf
hex: $(TARGET).hex
eep: $(TARGET).eep
lss: $(TARGET).lss
sym: $(TARGET).sym
LIBNAME=lib$(TARGET).a
lib: $(LIBNAME)
# 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)
end:
@echo $(MSG_END)
@echo
# Display size of file.
HEXSIZE = $(SIZE) --target=$(FORMAT) $(TARGET).hex
ELFSIZE = $(SIZE) --mcu=$(MCU) --format=avr $(TARGET).elf
sizebefore:
@if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_BEFORE); $(ELFSIZE); \
2>/dev/null; echo; fi
sizeafter:
@if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_AFTER); $(ELFSIZE); \
2>/dev/null; echo; fi
# Display compiler version information.
gccversion :
@$(CC) --version
# Create final output files (.hex, .eep) from ELF output file.
%.hex: %.elf
@echo
@echo $(MSG_FLASH) $@
$(OBJCOPY) -O $(FORMAT) -R .eeprom -R .fuse -R .lock -R .signature $< $@
%.eep: %.elf
@echo
@echo $(MSG_EEPROM) $@
-$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \
--change-section-lma .eeprom=0 --no-change-warnings -O $(FORMAT) $< $@ || exit 0
# Create extended listing file from ELF output file.
%.lss: %.elf
@echo
@echo $(MSG_EXTENDED_LISTING) $@
$(OBJDUMP) -h -S -z $< > $@
# Create a symbol table from ELF output file.
%.sym: %.elf
@echo
@echo $(MSG_SYMBOL_TABLE) $@
$(NM) -n $< > $@
# Create library from object files.
.SECONDARY : $(TARGET).a
.PRECIOUS : $(OBJ)
%.a: $(OBJ)
@echo
@echo $(MSG_CREATING_LIBRARY) $@
$(AR) $@ $(OBJ)
# Link: create ELF output file from object files.
.SECONDARY : $(TARGET).elf
.PRECIOUS : $(OBJ)
%.elf: $(OBJ)
@echo
@echo $(MSG_LINKING) $@
$(CC) $(ALL_CFLAGS) $^ --output $@ $(LDFLAGS)
# Compile: create object files from C source files.
$(OBJDIR)/%.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 $@
## Program
.PHONY: program
program: all
$(PROGRAM) $(PROGRAMFLAGS) $(ERASE)
$(PROGRAM) $(PROGRAMFLAGS) $(FLASH)
$(PROGRAM) $(PROGRAMFLAGS) $(START)
doxygen:
doxygen
# Target: clean project.
clean: begin clean_list end
clean_list :
@echo
@echo $(MSG_CLEANING)
$(REMOVE) $(TARGET).hex
$(REMOVE) $(TARGET).eep
$(REMOVE) $(TARGET).elf
$(REMOVE) $(TARGET).map
$(REMOVE) $(TARGET).sym
$(REMOVE) $(TARGET).lss
$(REMOVE) $(SRC:%.c=$(OBJDIR)/%.o)
$(REMOVE) $(SRC:%.c=$(OBJDIR)/%.lst)
$(REMOVE) $(SRC:.c=.s)
$(REMOVE) $(SRC:.c=.d)
$(REMOVEDIR) .dep
$(REMOVEDIR) $(OBJDIR)
# Create object files directory
$(shell mkdir $(OBJDIR) 2>/dev/null)
# 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 \
clean clean_list

View File

@@ -0,0 +1,75 @@
/**
@file main.c
@brief Lab 6 Starter Code
@version .01
@mainpage Lab 6 Starter Code
@section intro Code Overview
This first lab allows outputs to the LED array and single patteren of lights. You need to revise it so that it outputs lights based on the input from the switches.
@section hw Hardware Pin Out
PORTA:
Switches A7 - A0
PORTB:
*/
/** Includes */
#include <avr/io.h>
#include <util/delay.h>
/** Constants */
#define F_CPU 1000000U
/** Global Variables */
/** Functions */
/** The initialize() function initializes all of the Data Direction Registers for the Wunderboard. Before making changes to DDRx registers, ensure that you have read the peripherals section of the Wunderboard user guide.*/
void initialize (void) {
/** Port A is the switches and buttons. They should always be inputs. ( 0 = Input and 1 = Output )*/
DDRA=0b00000000;
/** Port B has the LED Array color control, SD card, and audio-out on it. Leave DDRB alone. ( 0 = Input and 1 = Output )*/
DDRB=0b11000000;
/** Port C is for the 'row' of the LED array. They should always be outputs. ( 0 = Input and 1 = Output )*/
DDRC=0b11111111;
/** Port D has the Serial on it. Leave DDRB alone. ( 0 = Input and 1 = Output )*/
DDRD=0b00000000;
/** Port E has the LED Array Column control out on it. Leave DDRE alone. ( 0 = Input and 1 = Output )*/
DDRE=0b00000111;
/** Port F has the accelerometer and audio-in on it. Leave DDRF alone. ( 0 = Input and 1 = Output )*/
DDRF=0b00000000;
}
void clearArray(void)
{
PORTB &= ~((1 << PB6) | (1 << PB7)); // Disable latches
PORTC = 0x00;
PORTB |= (1 << PB6) | (1 << PB7); // Enable latches
PORTB &= ~((1 << PB6) | (1 << PB7)); // Disable latches
}
/** Main Function */
int main (void) {
/** Local Varibles */
unsigned char temp;
unsigned char switches;
initialize();
clearArray();
while(1){
PORTB = 0b10000000; //Sets the green leds on
PORTC = PINA; //Sets led values to the switch values
}
}//main

View File

@@ -0,0 +1,335 @@
#----------------------------------------------------------------------------
# Wunderboard Makefile Template written by Dan Albert
#----------------------------------------------------------------------------
#
# make all = Make software.
#
# make clean = Clean out built project files.
#
# make filename.s = Just compile filename.c into the assembler code only.
#
# To rebuild project do "make clean" then "make all".
#----------------------------------------------------------------------------
# Target file name.
TARGET = main
# List C source files here.
SRC = $(TARGET).c \
# MCU name, you MUST set this to match the board you are using
# type "make clean" after changing this, so all files will be rebuilt
MCU = at90usb646
# Detect platform
UNAME = $(shell uname)
ifeq ($(UNAME),Linux)
ENV=unix
endif
ifeq ($(UNAME),Darwin)
ENV=unix
endif
ifndef ENV
ENV=windows
endif
ifeq ($(ENV),unix)
PROGRAM = dfu-programmer
PROGRAMFLAGS = $(MCU)
ERASE = erase
FLASH = flash "$(TARGET).hex"
START = start
else
PROGRAM = "C:/Program Files (x86)/Atmel/Flip 3.4.1/bin/batchisp.exe"
PROGRAMFLAGS = -device at90usb646 -hardware USB
ERASE = -operation erase F
FLASH = -operation loadbuffer "$(TARGET).hex" program verify
START = -operation start noreset 0
endif
# Processor frequency.
# Normally the first thing your program should do is set the clock prescaler,
# so your program will run at the correct speed. You should also set this
# variable to same clock speed. The _delay_ms() macro uses this, and many
# examples use this variable to calculate timings. Do not add a "UL" here.
F_CPU = 8000000
# Output format. (can be srec, ihex, binary)
FORMAT = ihex
# Object files directory
# To put object files in current directory, use a dot (.), do NOT make
# this an empty or blank macro!
OBJDIR = obj
# 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
# List any extra directories to look for include files here.
# Each directory must be seperated by a space.
# Use forward slashes for directory separators.
# For a directory that has spaces, enclose it in quotes.
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 for C sources
CDEFS = -DF_CPU=$(F_CPU)UL
#---------------- Compiler Options C ----------------
# -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 += $(CDEFS)
CFLAGS += -O$(OPT)
CFLAGS += -funsigned-char
CFLAGS += -funsigned-bitfields
CFLAGS += -ffunction-sections
CFLAGS += -fpack-struct
CFLAGS += -fshort-enums
CFLAGS += -Wall
CFLAGS += -Wstrict-prototypes
#CFLAGS += -mshort-calls
#CFLAGS += -fno-unit-at-a-time
#CFLAGS += -Wundef
#CFLAGS += -Wunreachable-code
#CFLAGS += -Wsign-compare
CFLAGS += -Wa,-adhlns=$(<:%.c=$(OBJDIR)/%.lst)
CFLAGS += $(patsubst %,-I%,$(EXTRAINCDIRS))
CFLAGS += $(CSTANDARD)
#---------------- Library Options ----------------
# 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
# If this is left blank, then it will use the Standard printf version.
PRINTF_LIB =
#PRINTF_LIB = $(PRINTF_LIB_MIN)
#PRINTF_LIB = $(PRINTF_LIB_FLOAT)
# 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
# If this is left blank, then it will use the Standard scanf version.
SCANF_LIB =
#SCANF_LIB = $(SCANF_LIB_MIN)
#SCANF_LIB = $(SCANF_LIB_FLOAT)
MATH_LIB = -lm
# List any extra directories to look for libraries here.
# Each directory must be seperated by a space.
# Use forward slashes for directory separators.
# For a directory that has spaces, enclose it in quotes.
EXTRALIBDIRS =
#---------------- Linker Options ----------------
# -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 += -Wl,--relax
LDFLAGS += -Wl,--gc-sections
LDFLAGS += $(patsubst %,-L%,$(EXTRALIBDIRS))
LDFLAGS += $(PRINTF_LIB) $(SCANF_LIB) $(MATH_LIB)
#LDFLAGS += -T linker_script.x
#============================================================================
# Define programs and commands.
SHELL = sh
CC = avr-gcc
OBJCOPY = avr-objcopy
OBJDUMP = avr-objdump
SIZE = avr-size
AR = avr-ar rcs
NM = avr-nm
REMOVE = rm -f
REMOVEDIR = rm -rf
COPY = cp
WINSHELL = cmd
# 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_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 C:
MSG_ASSEMBLING = Assembling:
MSG_CLEANING = Cleaning project:
MSG_CREATING_LIBRARY = Creating library:
# Define all object files.
OBJ = $(SRC:%.c=$(OBJDIR)/%.o)
# Define all listing files.
LST = $(SRC:%.c=$(OBJDIR)/%.lst)
# Compiler flags to generate dependency files.
GENDEPFLAGS = -MMD -MP -MF .dep/$(@F).d
# Combine all necessary flags and optional flags.
# Add target processor to flags.
ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) $(GENDEPFLAGS)
# Default target.
all: begin gccversion sizebefore build sizeafter end
# Change the build target to build a HEX file or a library.
build: elf hex eep lss sym
#build: lib
elf: $(TARGET).elf
hex: $(TARGET).hex
eep: $(TARGET).eep
lss: $(TARGET).lss
sym: $(TARGET).sym
LIBNAME=lib$(TARGET).a
lib: $(LIBNAME)
# 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)
end:
@echo $(MSG_END)
@echo
# Display size of file.
HEXSIZE = $(SIZE) --target=$(FORMAT) $(TARGET).hex
ELFSIZE = $(SIZE) --mcu=$(MCU) --format=avr $(TARGET).elf
sizebefore:
@if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_BEFORE); $(ELFSIZE); \
2>/dev/null; echo; fi
sizeafter:
@if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_AFTER); $(ELFSIZE); \
2>/dev/null; echo; fi
# Display compiler version information.
gccversion :
@$(CC) --version
# Create final output files (.hex, .eep) from ELF output file.
%.hex: %.elf
@echo
@echo $(MSG_FLASH) $@
$(OBJCOPY) -O $(FORMAT) -R .eeprom -R .fuse -R .lock -R .signature $< $@
%.eep: %.elf
@echo
@echo $(MSG_EEPROM) $@
-$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \
--change-section-lma .eeprom=0 --no-change-warnings -O $(FORMAT) $< $@ || exit 0
# Create extended listing file from ELF output file.
%.lss: %.elf
@echo
@echo $(MSG_EXTENDED_LISTING) $@
$(OBJDUMP) -h -S -z $< > $@
# Create a symbol table from ELF output file.
%.sym: %.elf
@echo
@echo $(MSG_SYMBOL_TABLE) $@
$(NM) -n $< > $@
# Create library from object files.
.SECONDARY : $(TARGET).a
.PRECIOUS : $(OBJ)
%.a: $(OBJ)
@echo
@echo $(MSG_CREATING_LIBRARY) $@
$(AR) $@ $(OBJ)
# Link: create ELF output file from object files.
.SECONDARY : $(TARGET).elf
.PRECIOUS : $(OBJ)
%.elf: $(OBJ)
@echo
@echo $(MSG_LINKING) $@
$(CC) $(ALL_CFLAGS) $^ --output $@ $(LDFLAGS)
# Compile: create object files from C source files.
$(OBJDIR)/%.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 $@
## Program
.PHONY: program
program: all
$(PROGRAM) $(PROGRAMFLAGS) $(ERASE)
$(PROGRAM) $(PROGRAMFLAGS) $(FLASH)
$(PROGRAM) $(PROGRAMFLAGS) $(START)
doxygen:
doxygen
# Target: clean project.
clean: begin clean_list end
clean_list :
@echo
@echo $(MSG_CLEANING)
$(REMOVE) $(TARGET).hex
$(REMOVE) $(TARGET).eep
$(REMOVE) $(TARGET).elf
$(REMOVE) $(TARGET).map
$(REMOVE) $(TARGET).sym
$(REMOVE) $(TARGET).lss
$(REMOVE) $(SRC:%.c=$(OBJDIR)/%.o)
$(REMOVE) $(SRC:%.c=$(OBJDIR)/%.lst)
$(REMOVE) $(SRC:.c=.s)
$(REMOVE) $(SRC:.c=.d)
$(REMOVEDIR) .dep
$(REMOVEDIR) $(OBJDIR)
# Create object files directory
$(shell mkdir $(OBJDIR) 2>/dev/null)
# 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 \
clean clean_list

View File

@@ -0,0 +1,177 @@
/**
@file main.c
@brief Lab 6 Starter Code
@version .01
@mainpage Lab 6 Starter Code
@section intro Code Overview
This first lab allows outputs to the LED array and single patteren of lights. You need to revise it so that it outputs lights based on the input from the switches.
@section hw Hardware Pin Out
PORTA:
Switches A7 - A0
PORTB:
*/
/** Includes */
#include <avr/io.h>
#include <util/delay.h>
/** Constants */
#define F_CPU 1000000U
#define DELAY .01
/** Global Variables */
/** Functions */
/** The initialize() function initializes all of the Data Direction Registers for the Wunderboard. Before making changes to DDRx registers, ensure that you have read the peripherals section of the Wunderboard user guide.*/
void initialize (void) {
/** Port A is the switches and buttons. They should always be inputs. ( 0 = Input and 1 = Output )*/
DDRA=0b00000000;
/** Port B has the LED Array color control, SD card, and audio-out on it. Leave DDRB alone. ( 0 = Input and 1 = Output )*/
DDRB=0b11000000;
/** Port C is for the 'row' of the LED array. They should always be outputs. ( 0 = Input and 1 = Output )*/
DDRC=0b11111111;
/** Port D has the Serial on it. Leave DDRB alone. ( 0 = Input and 1 = Output )*/
DDRD=0b00000000;
/** Port E has the LED Array Column control out on it. Leave DDRE alone. ( 0 = Input and 1 = Output )*/
DDRE=0b00000111;
/** Port F has the accelerometer and audio-in on it. Leave DDRF alone. ( 0 = Input and 1 = Output )*/
DDRF=0b00000000;
}
void clearArray(void)
{
PORTB &= ~((1 << PB6) | (1 << PB7)); // Disable latches
PORTC = 0x00;
PORTB |= (1 << PB6) | (1 << PB7); // Enable latches
PORTB &= ~((1 << PB6) | (1 << PB7)); // Disable latches
}
/** Main Function */
int main (void) {
/** Local Varibles */
//char red[8];
//char green[8];
char loop;
initialize();
clearArray();
while(1){
if (PINA == 0b01110000){
clearArray();
PORTB = 0b11000000;
PORTE = 0b00000011;
PORTC = 0b11011010;
_delay_ms(DELAY);
clearArray();
}else if (PINA == 0b10110000){
clearArray();
PORTB = 0b11000000;
PORTE = 0b00000011;
PORTC = 0b01010101;
_delay_ms(DELAY);
clearArray();
PORTB = 0b11000000;
PORTE = 0b00000110;
PORTC = 0b10101010;
_delay_ms(DELAY);
clearArray();
}else if (PINA == 0b11010000){
clearArray();
PORTB = 0b10000000;
PORTE = 0b00000011;
PORTC = 0b01010101;
_delay_ms(DELAY);
clearArray();
PORTB = 0b01000000;
PORTE = 0b00000110;
PORTC = 0b10101010;
_delay_ms(DELAY);
clearArray();
}else if (PINA == 0b11111000){
char red[8] = {0b10000000, 0b01000000, 0b00100000, 0b00010000, 0b00001000, 0b00000100, 0b00000010, 0b00000001};
char green[8] = {0b01111000, 0b10111100, 0b11011110, 0b11101111, 0b11110111, 0b01111011, 0b00111101, 0b00011110};
char orange[8] = {0b00000111, 0b00000011, 0b00000001, 0b00000000, 0b00000000, 0b10000000, 0b11000000, 0b11100000};
clearArray();
for ( loop = 0 ; loop < 8 ; loop++ ){
PORTB = 0b01000000;
PORTE = loop;
PORTC = red[loop];
_delay_ms(DELAY);
clearArray();
PORTB = 0b10000000;
PORTC = green[loop];
_delay_ms(DELAY);
clearArray();
PORTB = 0b11000000;
PORTC = orange[loop];
_delay_ms(DELAY);
clearArray();
}
}else if (PINA == 0b11100000){
char red[8] = {0b11111111, 0b01110111, 0b00100010,0b00000000, 0b00000000, 0b00100010, 0b01110111, 0b11111111};
char green[8] = {0b00000000, 0b10001000, 0b11011101, 0b11111111, 0b11111111, 0b11011101, 0b10001000, 0b00000000};
clearArray();
for ( loop = 0 ; loop < 8 ; loop++ ){
PORTB = 0b01000000;
PORTE = loop;
PORTC = red[loop];
_delay_ms(DELAY);
clearArray();
PORTB = 0b10000000;
PORTC = green[loop];
_delay_ms(DELAY);
clearArray();
}
}
}
}//main

View File

@@ -0,0 +1,336 @@
#----------------------------------------------------------------------------
# Wunderboard Makefile Template written by Dan Albert
#----------------------------------------------------------------------------
#
# make all = Make software.
#
# make clean = Clean out built project files.
#
# make filename.s = Just compile filename.c into the assembler code only.
#
# To rebuild project do "make clean" then "make all".
#----------------------------------------------------------------------------
# Target file name.
TARGET = main
# List C source files here.
SRC = $(TARGET).c \
adc.c
# MCU name, you MUST set this to match the board you are using
# type "make clean" after changing this, so all files will be rebuilt
MCU = at90usb646
# Detect platform
UNAME = $(shell uname)
ifeq ($(UNAME),Linux)
ENV=unix
endif
ifeq ($(UNAME),Darwin)
ENV=unix
endif
ifndef ENV
ENV=windows
endif
ifeq ($(ENV),unix)
PROGRAM = dfu-programmer
PROGRAMFLAGS = $(MCU)
ERASE = erase
FLASH = flash "$(TARGET).hex"
START = start
else
PROGRAM = "C:/Program Files (x86)/Atmel/Flip 3.4.1/bin/batchisp.exe"
PROGRAMFLAGS = -device at90usb646 -hardware USB
ERASE = -operation erase F
FLASH = -operation loadbuffer "$(TARGET).hex" program verify
START = -operation start noreset 0
endif
# Processor frequency.
# Normally the first thing your program should do is set the clock prescaler,
# so your program will run at the correct speed. You should also set this
# variable to same clock speed. The _delay_ms() macro uses this, and many
# examples use this variable to calculate timings. Do not add a "UL" here.
F_CPU = 8000000
# Output format. (can be srec, ihex, binary)
FORMAT = ihex
# Object files directory
# To put object files in current directory, use a dot (.), do NOT make
# this an empty or blank macro!
OBJDIR = obj
# 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
# List any extra directories to look for include files here.
# Each directory must be seperated by a space.
# Use forward slashes for directory separators.
# For a directory that has spaces, enclose it in quotes.
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 for C sources
CDEFS = -DF_CPU=$(F_CPU)UL
#---------------- Compiler Options C ----------------
# -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 += $(CDEFS)
CFLAGS += -O$(OPT)
CFLAGS += -funsigned-char
CFLAGS += -funsigned-bitfields
CFLAGS += -ffunction-sections
CFLAGS += -fpack-struct
CFLAGS += -fshort-enums
CFLAGS += -Wall
CFLAGS += -Wstrict-prototypes
#CFLAGS += -mshort-calls
#CFLAGS += -fno-unit-at-a-time
#CFLAGS += -Wundef
#CFLAGS += -Wunreachable-code
#CFLAGS += -Wsign-compare
CFLAGS += -Wa,-adhlns=$(<:%.c=$(OBJDIR)/%.lst)
CFLAGS += $(patsubst %,-I%,$(EXTRAINCDIRS))
CFLAGS += $(CSTANDARD)
#---------------- Library Options ----------------
# 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
# If this is left blank, then it will use the Standard printf version.
PRINTF_LIB =
#PRINTF_LIB = $(PRINTF_LIB_MIN)
#PRINTF_LIB = $(PRINTF_LIB_FLOAT)
# 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
# If this is left blank, then it will use the Standard scanf version.
SCANF_LIB =
#SCANF_LIB = $(SCANF_LIB_MIN)
#SCANF_LIB = $(SCANF_LIB_FLOAT)
MATH_LIB = -lm
# List any extra directories to look for libraries here.
# Each directory must be seperated by a space.
# Use forward slashes for directory separators.
# For a directory that has spaces, enclose it in quotes.
EXTRALIBDIRS =
#---------------- Linker Options ----------------
# -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 += -Wl,--relax
LDFLAGS += -Wl,--gc-sections
LDFLAGS += $(patsubst %,-L%,$(EXTRALIBDIRS))
LDFLAGS += $(PRINTF_LIB) $(SCANF_LIB) $(MATH_LIB)
#LDFLAGS += -T linker_script.x
#============================================================================
# Define programs and commands.
SHELL = sh
CC = avr-gcc
OBJCOPY = avr-objcopy
OBJDUMP = avr-objdump
SIZE = avr-size
AR = avr-ar rcs
NM = avr-nm
REMOVE = rm -f
REMOVEDIR = rm -rf
COPY = cp
WINSHELL = cmd
# 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_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 C:
MSG_ASSEMBLING = Assembling:
MSG_CLEANING = Cleaning project:
MSG_CREATING_LIBRARY = Creating library:
# Define all object files.
OBJ = $(SRC:%.c=$(OBJDIR)/%.o)
# Define all listing files.
LST = $(SRC:%.c=$(OBJDIR)/%.lst)
# Compiler flags to generate dependency files.
GENDEPFLAGS = -MMD -MP -MF .dep/$(@F).d
# Combine all necessary flags and optional flags.
# Add target processor to flags.
ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) $(GENDEPFLAGS)
# Default target.
all: begin gccversion sizebefore build sizeafter end
# Change the build target to build a HEX file or a library.
build: elf hex eep lss sym
#build: lib
elf: $(TARGET).elf
hex: $(TARGET).hex
eep: $(TARGET).eep
lss: $(TARGET).lss
sym: $(TARGET).sym
LIBNAME=lib$(TARGET).a
lib: $(LIBNAME)
# 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)
end:
@echo $(MSG_END)
@echo
# Display size of file.
HEXSIZE = $(SIZE) --target=$(FORMAT) $(TARGET).hex
ELFSIZE = $(SIZE) --mcu=$(MCU) --format=avr $(TARGET).elf
sizebefore:
@if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_BEFORE); $(ELFSIZE); \
2>/dev/null; echo; fi
sizeafter:
@if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_AFTER); $(ELFSIZE); \
2>/dev/null; echo; fi
# Display compiler version information.
gccversion :
@$(CC) --version
# Create final output files (.hex, .eep) from ELF output file.
%.hex: %.elf
@echo
@echo $(MSG_FLASH) $@
$(OBJCOPY) -O $(FORMAT) -R .eeprom -R .fuse -R .lock -R .signature $< $@
%.eep: %.elf
@echo
@echo $(MSG_EEPROM) $@
-$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \
--change-section-lma .eeprom=0 --no-change-warnings -O $(FORMAT) $< $@ || exit 0
# Create extended listing file from ELF output file.
%.lss: %.elf
@echo
@echo $(MSG_EXTENDED_LISTING) $@
$(OBJDUMP) -h -S -z $< > $@
# Create a symbol table from ELF output file.
%.sym: %.elf
@echo
@echo $(MSG_SYMBOL_TABLE) $@
$(NM) -n $< > $@
# Create library from object files.
.SECONDARY : $(TARGET).a
.PRECIOUS : $(OBJ)
%.a: $(OBJ)
@echo
@echo $(MSG_CREATING_LIBRARY) $@
$(AR) $@ $(OBJ)
# Link: create ELF output file from object files.
.SECONDARY : $(TARGET).elf
.PRECIOUS : $(OBJ)
%.elf: $(OBJ)
@echo
@echo $(MSG_LINKING) $@
$(CC) $(ALL_CFLAGS) $^ --output $@ $(LDFLAGS)
# Compile: create object files from C source files.
$(OBJDIR)/%.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 $@
## Program
.PHONY: program
program: all
$(PROGRAM) $(PROGRAMFLAGS) $(ERASE)
$(PROGRAM) $(PROGRAMFLAGS) $(FLASH)
$(PROGRAM) $(PROGRAMFLAGS) $(START)
doxygen:
doxygen
# Target: clean project.
clean: begin clean_list end
clean_list :
@echo
@echo $(MSG_CLEANING)
$(REMOVE) $(TARGET).hex
$(REMOVE) $(TARGET).eep
$(REMOVE) $(TARGET).elf
$(REMOVE) $(TARGET).map
$(REMOVE) $(TARGET).sym
$(REMOVE) $(TARGET).lss
$(REMOVE) $(SRC:%.c=$(OBJDIR)/%.o)
$(REMOVE) $(SRC:%.c=$(OBJDIR)/%.lst)
$(REMOVE) $(SRC:.c=.s)
$(REMOVE) $(SRC:.c=.d)
$(REMOVEDIR) .dep
$(REMOVEDIR) $(OBJDIR)
# Create object files directory
$(shell mkdir $(OBJDIR) 2>/dev/null)
# 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 \
clean clean_list

View File

@@ -0,0 +1,28 @@
/**
@file adc.c
@brief Wunderboard ADC Helper Functions
@version .01
@section intro Code Overview
This is the code for the Wunderboard ADC helper functions.
*/
#include "adc.h"
unsigned char read_adc(uint8_t channel){
unsigned char test;
ADMUX = 0x60 | channel; // Set the channel to the one we want
ADCSRA = 0b11000110; // Start a new sample.
while ((ADCSRA & 0b00010000) == 0 ); // Wait for a Valid Sample
ADCSRA |= 0b00010000; // Tell ADC you have the sample you want.
ADCSRA |= 0b01000000; // Start a new sample.
while ((ADCSRA & 0b00010000) == 0 ); // Wait for a Valid Sample
ADCSRA |= 0b00010000; // Tell ADC you have the sample you want.
test = ADCH;
ADCSRA = 0x00; // Disable the ADC
return (test);
}

View File

@@ -0,0 +1,19 @@
/**
@file adc.h
@brief Wunderboard ADC Helper Functions
@version .01
@section intro Code Overview
This is the code for the Wunderboard ADC helper functions.
*/
#include <avr/io.h>
/**
The read_adc() function allows for taking 8 bit measurements from any of the single ended ADC inputs. The function call is blocking. eg. read_adc(5) would read from ADC channel 5.
@param channel This is the channel to be read.
@return This is the return value from the ADC.
*/
unsigned char read_adc(uint8_t channel);

View File

@@ -0,0 +1,189 @@
/**
@file main.c
@brief Lab 8 Starter Code
@version .01
@mainpage Lab 8 Starter Code
@section intro Code Overview
@section hw Hardware Pin Out
Port A:
A0 - A3 : Push Buttons
A4 - A7 : Slide Switches
Port B:
B0 - B3 : SPI (SD Card)
B4 : Nothing
B5 : Audio Out
B6 : Red Enable
B7 : Green Enable
Port C:
C0 - C7 : LED Array (Row)
Port D:
D0 - D1 : Nothing
D2 : Serial RX
D3 : Serial TX
D4 - D7 : Nothing
Port E:
E0 - E2 : LED Array (Column)
E3 : USB (UID)
E4 - E5 : Nothing
E6 : Relay
E7 : Nothing
Port F:
F0 : ADC Channel 0
F1 : ADC Channel 1
F2 : ADC Channel 2
F3 : ADC Channel 3
F4 : ADC Channel 4 (Audio In)
F5 : ADC Channel 5 (Accel X Axis)
F6 : ADC Channel 6 (Accel Y Axis)
F7 : ADC Channel 7 (Accel Z Axis (if installed))
*/
/** Includes */
#include <avr/io.h>
#include <util/delay.h>
#include "adc.h"
#include <stdlib.h>
#include <math.h>
/** Constants */
#define F_CPU 1000000U
#define DELAY .02
#define YMIN 180.0
#define STEPSIZE 1.375
/** Global Variables */
/** Functions */
/** The initialize() function initializes all of the Data Direction Registers for the Wunderboard. Before making changes to DDRx registers, ensure that you have read the peripherals section of the Wunderboard user guide.*/
void initialize (void) {
/** Port A is the switches and buttons. They should always be inputs. ( 0 = Input and 1 = Output )*/
DDRA=0b00000000;
/** Port B has the LED Array color control, SD card, and audio-out on it. Leave DDRB alone. ( 0 = Input and 1 = Output )*/
DDRB=0b11000000;
/** Port C is for the 'row' of the LED array. They should always be outputs. ( 0 = Input and 1 = Output )*/
DDRC=0b11111111;
/** Port D has the Serial on it. Leave DDRB alone. ( 0 = Input and 1 = Output )*/
DDRD=0b00000000;
/** Port E has the LED Array Column control out on it. Leave DDRE alone. ( 0 = Input and 1 = Output )*/
DDRE=0b00000111;
/** Port F has the accelerometer and audio-in on it. Leave DDRF alone. ( 0 = Input and 1 = Output )*/
DDRF=0b00000000;
}
void clearArray(void)
{
PORTB &= ~((1 << PB6) | (1 << PB7)); // Disable latches
PORTC = 0x00;
PORTB |= (1 << PB6) | (1 << PB7); // Enable latches
PORTB &= ~((1 << PB6) | (1 << PB7)); // Disable latches
}
int readadcval(void){
int loop4;
int adcreturn;
char adcread = read_adc(5);
for(loop4 = 0 ; loop4 < 16 ; loop4++){
if(((YMIN + (loop4*STEPSIZE)) <= adcread) & (adcread < (YMIN + ((loop4 + 1)*STEPSIZE)))){
adcreturn = 2*loop4;
}
}
return adcreturn;
}
/** Main Function */
int main (void) {
/** Local Varibles */
int loop = 50;
int loop2;
int loop3;
int speed = 20;
int *speedpoint = &speed;
const int Red[120] = {0b00000000, 0b00000000, 0b01000000, 0b11000000, 0b01000000, 0b00000000, 0b00000000, 0b00001000, 0b00000000, 0b00001000, 0b00101000, 0b00001000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b10000000, 0b11000000, 0b01000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00001000, 0b00000000, 0b00000000, 0b01000000, 0b11000000, 0b11100000, 0b01000000, 0b00000000, 0b00000100, 0b00000100, 0b00010000, 0b00010000, 0b00010000, 0b00010000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00010000, 0b00010100, 0b00000000, 0b00000000, 0b01001000, 0b11001000, 0b11000000, 0b10000000, 0b00001000, 0b00000000, 0b00101000, 0b00000000, 0b00001000, 0b00000000, 0b00000000, 0b00100000, 0b00100000, 0b00000000, 0b00000000, 0b00101000, 0b00100000, 0b00000000, 0b00000000, 0b00000010, 0b00000110, 0b00001110, 0b00000000, 0b00001110, 0b00000110, 0b01000010, 0b11000000, 0b01000000, 0b00000010, 0b00000110, 0b00001110, 0b00001110, 0b00000000, 0b00001110, 0b00000110, 0b00000010, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00001000, 0b00001000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000010, 0b00000110, 0b00001110, 0b00011110, 0b00011110, 0b00000000, 0b01000000, 0b11100000, 0b11100010, 0b01000000, 0b00000000, 0b00001110, 0b00111110, 0b00011000, 0b00111110, 0b00001110};
const int Green[120] = {0b00000001, 0b00000001, 0b01000001, 0b11000001, 0b01000001, 0b00000001, 0b00000001, 0b00001001, 0b00000001, 0b00001001, 0b00101001, 0b00001001, 0b00000001, 0b00000001, 0b00000001, 0b00000001, 0b10000111, 0b11000111, 0b01000001, 0b00000001, 0b00000001, 0b00001111, 0b00001111, 0b00000001, 0b00000001, 0b00001111, 0b00001111, 0b00000001, 0b00000001, 0b00001111, 0b00001111, 0b00000001, 0b00000001, 0b00001001, 0b00000001, 0b00000001, 0b01000001, 0b11000001, 0b11100000, 0b01000000, 0b00000001, 0b00000101, 0b00000101, 0b00010001, 0b00010001, 0b00010001, 0b00010001, 0b00000001, 0b00000001, 0b00000000, 0b00000000, 0b00000000, 0b00010001, 0b00010101, 0b00000001, 0b00000001, 0b01001001, 0b11001001, 0b11000001, 0b10000001, 0b00001001, 0b00000001, 0b00101001, 0b00000001, 0b00001001, 0b00000001, 0b00000001, 0b00100001, 0b00100001, 0b00000001, 0b00000001, 0b00101001, 0b00100001, 0b00000001, 0b00000001, 0b00000011, 0b00000111, 0b00001111, 0b00000001, 0b00001111, 0b00000111, 0b01000011, 0b11000001, 0b01000001, 0b00000011, 0b00000111, 0b00001111, 0b00001111, 0b00000000, 0b00001111, 0b00000111, 0b00000011, 0b00000001, 0b00000111, 0b00000111, 0b00000001, 0b00000001, 0b00001001, 0b00001001, 0b00000001, 0b00000001, 0b00000001, 0b00000111, 0b00000111, 0b00000011, 0b00000111, 0b00001111, 0b00011111, 0b00011111, 0b00000001, 0b01000001, 0b11100001, 0b11100011, 0b01000001, 0b00000001, 0b00000001, 0b00000001, 0b00000001, 0b00000001, 0b00000001};
initialize();
clearArray();
while(1){
speedpoint = 25;
for(loop ; loop >= 0 ; loop--){
speedpoint = readadcval();
if(speedpoint == 0){
while(speedpoint == 0){
for(loop2 = 0 ; loop2 < 150 ; loop2++){
for(loop3 = 7 ; loop3 > -1 ; loop3--){
int arrval;
clearArray();
PORTE = loop3;
arrval = (loop+loop3);
PORTB = 0b10000000;
PORTC = Green[arrval];
_delay_ms(DELAY);
clearArray();
PORTB= 0b01000000;
PORTC = Red[arrval];
_delay_ms(DELAY);
clearArray();
}
}
speedpoint = readadcval();
}
}else{
for(loop2 = 0 ; loop2 < speedpoint ; loop2++){
for(loop3 = 7 ; loop3 > -1 ; loop3--){
int arrval;
clearArray();
PORTE = loop3;
arrval = (loop+loop3);
PORTB = 0b10000000;
PORTC = Green[arrval];
_delay_ms(DELAY);
clearArray();
PORTB= 0b01000000;
PORTC = Red[arrval];
_delay_ms(DELAY);
clearArray();
}
}
}
if(loop == 0){
loop = 112;
}
}
}
}

View File

@@ -0,0 +1,66 @@
#include <iostream>
#include <string>
using namespace std;
int main(void){
unsigned char exit;
string response;
enum question{
first,
second,
third
} currentquestion = first;
while(exit != 1){
switch(currentquestion){
case first:
cout << "First Question: Which is NOT an internal component of a desktop computer?\n\nA: Ram Module\nB: Power Supply\nC: Hard Drive\nD: Monitor\nPlease enter your selection: ";
cin >> response;
if((response.compare("a") == 0) | (response.compare("A") == 0)){
cout << "\nIncorrect. Ram modules are an internal component.\nPlease try again..." << endl;
cout << string(2, '\n');
}else if((response.compare("b") == 0) | (response.compare("B") == 0)){
cout << "\nIncorrect. Power supplies are an internal component.\nPlease try again..." << endl;
cout << string(2, '\n');
}else if((response.compare("c") == 0) | (response.compare("C") == 0)){
cout << "\nIncorrect. Hard drives are an internal component.\nPlease try again..." << endl;
cout << string(2, '\n');
}else if((response.compare("d") == 0) | (response.compare("D") == 0)){
cout << "\nCorrect! Monitor's are external components on desktops." << endl;
cout << string(2, '\n');
currentquestion = second;
}else{
cout << "You have entered an invalid response, please try again..." << endl;
cout << string(2, '\n');
}
break;
case second:
cout << "Second Question: Which is a model number for an ivy bridge processor?\nA: i5-3570K\nB: i7-2600K\nC: i3-2120\nD: i5-2400\nPlease enter your selection: ";
cin >> response;
if((response.compare("a") == 0) | (response.compare("A") == 0)){
cout << "\nCorrect!. This is an ivy bridge processor!" << endl;
cout << string(2, '\n');
return 0;
}else if((response.compare("b") == 0) | (response.compare("B") == 0)){
cout << "\nIncorrect. This is a Sandy Bridge processor.\nPlease try again..." << endl;
cout << string(2, '\n');
}else if((response.compare("c") == 0) | (response.compare("C") == 0)){
cout << "\nIncorrect. This is a Sandy Bridge processor.\nPlease try again..." << endl;
cout << string(2, '\n');
}else if((response.compare("d") == 0) | (response.compare("D") == 0)){
cout << "\nIncorrect. This is a Sandy Bridge processor.\nPlease try again..." << endl;
cout << string(2, '\n');
}else{
cout << "\nYou have entered an invalid response, please try again..." << endl;
cout << string(2, '\n');
}
break;
default:
cerr << "You should never see this. There has been an enum error." << endl;
}
}
return 0;
}

View File

@@ -0,0 +1,13 @@
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include "rps.h"
using namespace std;
int main()
{
Rps game;
game.newgame();
return 0;
}

View File

@@ -0,0 +1,60 @@
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Player{
public:
friend class Rps;
Player(){
srand ( time(NULL) );
wins(0);
losses(0);
}
Player
string guess(){
int number;
number = ((int)(rand() * 10))%3;
if (number == 0){
return "Rock";
}
else if (number == 1){
return "Paper";
}
else if (number == 2){
return "Scissors";
}
else {
return "Dynamite";
}
}
string userguess(){
/*Extra Challenge 1:
Get User input for one of the guesses*/
}
string wunderguess(){
try{
SimpleSerial wunderboard("COM3", 9600);
string mystr = wunderboard.readLine();
cout << "Wunderboard says: " << mystr << endl;
}catch(boost::system::system_error& e){
cout << "Error. << e.what() << endl;
}
/*Extra Challenge 2:
Add the Players name to the object and it constructor. Add a function to get the name/change it*/
private:
int wins;
int losses;
};

View File

@@ -0,0 +1,61 @@
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include "player.h"
using namespace std;
class Rps{
public:
void newgame(){
/*Extra Challenge 5:
Make this program a 3 player game*/
Player player1;
Player player2;
string player1guess;
string player2guess;
/*Extra Challenge 3
Make this program Rock, Paper, Scissors, Lizard, Spock*/
/*Extra Challenge 4
Make this program best 2 out of 3*/
cout << "Welcome to RPS (Rock, Paper, Scissors) v1.0" << endl;
cout << "Preparing to run the guess() method on both player objects" << endl;
/*Extra Challenge 1
Get User input for one of the guesses*/
player1guess = player1.guess();
player2guess = player2.guess();
while (player1guess.compare(player2guess) == 0){
player1guess = player1.guess();
player2guess = player2.guess();
}
if ((player1guess.compare("Rock") == 0) && (player2guess.compare("Scissors") == 0) )
cout << "Player 1 smashes the heck out of player 2 with a rock! Die scissors die!" << endl;
if ((player1guess.compare("Scissors") == 0) && (player2guess.compare("Rock") == 0) )
cout << "Player 2 smashes the heck out of player 1 with a rock! Die scissors die!" << endl;
if ((player1guess.compare("Paper") == 0) && (player2guess.compare("Rock") == 0) )
cout << "Player 1 smothers player 2 with paper! Die rock die!" << endl;
if ((player1guess.compare("Rock") == 0) && (player2guess.compare("Paper") == 0) )
cout << "Player 2 smothers player 1 with paper! Die rock die!" << endl;
if ((player1guess.compare("Scissors") == 0) && (player2guess.compare("Paper") == 0) )
cout << "Player 1 slices and dices player 2 with scissors! Die paper die!" << endl;
if ((player1guess.compare("Paper") == 0) && (player2guess.compare("Scissors") == 0) )
cout << "Player 2 slices and dices player 1 with scissors! Die paper die!" << endl;
/*Extra Challenge 6
Actually declare a winner*/
}
/*Extra Challenge 7
Keep track of number of wins and number of losses for each object of this class*/
};

View File

@@ -0,0 +1,30 @@
# Detect platform
UNAME = $(shell uname)
ifeq ($(UNAME),Linux)
ENV=unix
endif
ifeq ($(UNAME),Darwin)
ENV=unix
endif
ifndef ENV
ENV=windows
endif
ifeq ($(ENV),unix)
CC = g++
BOOSTFLAGS = -lboost_system
else
CC = g++
BOOSTFLAGS = -lboost_system -lws2_32 -D _WIN32_WINNT=0x0501
endif
all:
$(CC) lab5.cpp -Wall $(BOOSTFLAGS)
clean:
rm -f *.exe
rm -f *.o

View File

@@ -0,0 +1,66 @@
#include <boost/asio.hpp>
/** This code requires 'boost' to be successfully installed and when compiled will require the boost libaries to be included.
The original code source as of this writting was found here:
http://www.webalice.it/fede.tft/serial_port/serial_port.html
*/
class SimpleSerial
{
public:
/**
* Constructor.
* \param port device name, example "/dev/ttyUSB0" or "COM4"
* \param baud_rate communication speed, example 9600 or 115200
* \throws boost::system::system_error if cannot open the
* serial device
*/
SimpleSerial(std::string port, unsigned int baud_rate)
: io(), serial(io,port)
{
serial.set_option(boost::asio::serial_port_base::baud_rate(baud_rate));
}
/**
* Write a string to the serial device.
* \param s string to write
* \throws boost::system::system_error on failure
*/
void writeString(std::string s)
{
boost::asio::write(serial,boost::asio::buffer(s.c_str(),s.size()));
}
/**
* Blocks until a line is received from the serial device. A line is denoted by a final '\n' character
* Eventual '\n' or '\r\n' characters at the end of the string are removed.
* \return a string containing the received line
* \throws boost::system::system_error on failure
*/
std::string readLine()
{
//Reading data char by char, code is optimized for simplicity, not speed
using namespace boost;
char c;
std::string result;
for(;;)
{
asio::read(serial,asio::buffer(&c,1));
switch(c)
{
case '\r':
break;
case '\n':
return result;
default:
result+=c;
}
}
}
private:
boost::asio::io_service io;
boost::asio::serial_port serial;
};

View File

@@ -0,0 +1,53 @@
/*
* conio.h
* This file has no copyright assigned and is placed in the Public Domain.
* This file is a part of the mingw-runtime package.
* No warranty is given; refer to the file DISCLAIMER within the package.
*
* Low level console I/O functions. Pretty please try to use the ANSI
* standard ones if you are writing new code.
*
*/
#ifndef _CONIO_H_
#define _CONIO_H_
/* All the headers include this file. */
#include <_mingw.h>
#ifndef RC_INVOKED
#ifdef __cplusplus
extern "C" {
#endif
_CRTIMP char* __cdecl __MINGW_NOTHROW _cgets (char*);
_CRTIMP int __cdecl __MINGW_NOTHROW _cprintf (const char*, ...);
_CRTIMP int __cdecl __MINGW_NOTHROW _cputs (const char*);
_CRTIMP int __cdecl __MINGW_NOTHROW _cscanf (char*, ...);
_CRTIMP int __cdecl __MINGW_NOTHROW _getch (void);
_CRTIMP int __cdecl __MINGW_NOTHROW _getche (void);
_CRTIMP int __cdecl __MINGW_NOTHROW _kbhit (void);
_CRTIMP int __cdecl __MINGW_NOTHROW _putch (int);
_CRTIMP int __cdecl __MINGW_NOTHROW _ungetch (int);
#ifndef _NO_OLDNAMES
_CRTIMP int __cdecl __MINGW_NOTHROW getch (void);
_CRTIMP int __cdecl __MINGW_NOTHROW getche (void);
_CRTIMP int __cdecl __MINGW_NOTHROW kbhit (void);
_CRTIMP int __cdecl __MINGW_NOTHROW putch (int);
_CRTIMP int __cdecl __MINGW_NOTHROW ungetch (int);
#endif /* Not _NO_OLDNAMES */
#ifdef __cplusplus
}
#endif
#endif /* Not RC_INVOKED */
#endif /* Not _CONIO_H_ */

View File

@@ -0,0 +1,35 @@
// g++ serial.c++ -lboost_system -lws2_32 -D _WIN32_WINNT=0x0501
#include <iostream>
#include "SimpleSerial.h"
#include "conio.h"
using namespace std;
using namespace boost;
int main(int argc, char* argv[])
{
string inputstr;
cout << "Lab 5 Code Started" << endl;
SimpleSerial wunderboard("COM5", 9600);
while(1){
try {
cout << wunderboard.readLine() << endl;
if(kbhit()){
cin >> inputstr;
wunderboard.writeString(inputstr);
if((inputstr.compare("Exit") == 0) | (inputstr.compare("EXIT") == 0) | (inputstr.compare("exit") == 0)){
return 0;
}
}
} catch(boost::system::system_error& e)
{
cout<<"Error: "<<e.what()<<endl;
return 1;
}
}
}

View File

@@ -0,0 +1,335 @@
#----------------------------------------------------------------------------
# Wunderboard Makefile Template written by Dan Albert
#----------------------------------------------------------------------------
#
# make all = Make software.
#
# make clean = Clean out built project files.
#
# make filename.s = Just compile filename.c into the assembler code only.
#
# To rebuild project do "make clean" then "make all".
#----------------------------------------------------------------------------
# Target file name.
TARGET = main
# List C source files here.
SRC = $(TARGET).c \
# MCU name, you MUST set this to match the board you are using
# type "make clean" after changing this, so all files will be rebuilt
MCU = at90usb646
# Detect platform
UNAME = $(shell uname)
ifeq ($(UNAME),Linux)
ENV=unix
endif
ifeq ($(UNAME),Darwin)
ENV=unix
endif
ifndef ENV
ENV=windows
endif
ifeq ($(ENV),unix)
PROGRAM = dfu-programmer
PROGRAMFLAGS = $(MCU)
ERASE = erase
FLASH = flash "$(TARGET).hex"
START = start
else
PROGRAM = "C:/Program Files (x86)/Atmel/Flip 3.4.1/bin/batchisp.exe"
PROGRAMFLAGS = -device at90usb646 -hardware USB
ERASE = -operation erase F
FLASH = -operation loadbuffer "$(TARGET).hex" program verify
START = -operation start noreset 0
endif
# Processor frequency.
# Normally the first thing your program should do is set the clock prescaler,
# so your program will run at the correct speed. You should also set this
# variable to same clock speed. The _delay_ms() macro uses this, and many
# examples use this variable to calculate timings. Do not add a "UL" here.
F_CPU = 8000000
# Output format. (can be srec, ihex, binary)
FORMAT = ihex
# Object files directory
# To put object files in current directory, use a dot (.), do NOT make
# this an empty or blank macro!
OBJDIR = obj
# 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
# List any extra directories to look for include files here.
# Each directory must be seperated by a space.
# Use forward slashes for directory separators.
# For a directory that has spaces, enclose it in quotes.
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 for C sources
CDEFS = -DF_CPU=$(F_CPU)UL
#---------------- Compiler Options C ----------------
# -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 += $(CDEFS)
CFLAGS += -O$(OPT)
CFLAGS += -funsigned-char
CFLAGS += -funsigned-bitfields
CFLAGS += -ffunction-sections
CFLAGS += -fpack-struct
CFLAGS += -fshort-enums
CFLAGS += -Wall
CFLAGS += -Wstrict-prototypes
#CFLAGS += -mshort-calls
#CFLAGS += -fno-unit-at-a-time
#CFLAGS += -Wundef
#CFLAGS += -Wunreachable-code
#CFLAGS += -Wsign-compare
CFLAGS += -Wa,-adhlns=$(<:%.c=$(OBJDIR)/%.lst)
CFLAGS += $(patsubst %,-I%,$(EXTRAINCDIRS))
CFLAGS += $(CSTANDARD)
#---------------- Library Options ----------------
# 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
# If this is left blank, then it will use the Standard printf version.
PRINTF_LIB =
#PRINTF_LIB = $(PRINTF_LIB_MIN)
#PRINTF_LIB = $(PRINTF_LIB_FLOAT)
# 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
# If this is left blank, then it will use the Standard scanf version.
SCANF_LIB =
#SCANF_LIB = $(SCANF_LIB_MIN)
#SCANF_LIB = $(SCANF_LIB_FLOAT)
MATH_LIB = -lm
# List any extra directories to look for libraries here.
# Each directory must be seperated by a space.
# Use forward slashes for directory separators.
# For a directory that has spaces, enclose it in quotes.
EXTRALIBDIRS =
#---------------- Linker Options ----------------
# -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 += -Wl,--relax
LDFLAGS += -Wl,--gc-sections
LDFLAGS += $(patsubst %,-L%,$(EXTRALIBDIRS))
LDFLAGS += $(PRINTF_LIB) $(SCANF_LIB) $(MATH_LIB)
#LDFLAGS += -T linker_script.x
#============================================================================
# Define programs and commands.
SHELL = sh
CC = avr-gcc
OBJCOPY = avr-objcopy
OBJDUMP = avr-objdump
SIZE = avr-size
AR = avr-ar rcs
NM = avr-nm
REMOVE = rm -f
REMOVEDIR = rm -rf
COPY = cp
WINSHELL = cmd
# 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_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 C:
MSG_ASSEMBLING = Assembling:
MSG_CLEANING = Cleaning project:
MSG_CREATING_LIBRARY = Creating library:
# Define all object files.
OBJ = $(SRC:%.c=$(OBJDIR)/%.o)
# Define all listing files.
LST = $(SRC:%.c=$(OBJDIR)/%.lst)
# Compiler flags to generate dependency files.
GENDEPFLAGS = -MMD -MP -MF .dep/$(@F).d
# Combine all necessary flags and optional flags.
# Add target processor to flags.
ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) $(GENDEPFLAGS)
# Default target.
all: begin gccversion sizebefore build sizeafter end
# Change the build target to build a HEX file or a library.
build: elf hex eep lss sym
#build: lib
elf: $(TARGET).elf
hex: $(TARGET).hex
eep: $(TARGET).eep
lss: $(TARGET).lss
sym: $(TARGET).sym
LIBNAME=lib$(TARGET).a
lib: $(LIBNAME)
# 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)
end:
@echo $(MSG_END)
@echo
# Display size of file.
HEXSIZE = $(SIZE) --target=$(FORMAT) $(TARGET).hex
ELFSIZE = $(SIZE) --mcu=$(MCU) --format=avr $(TARGET).elf
sizebefore:
@if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_BEFORE); $(ELFSIZE); \
2>/dev/null; echo; fi
sizeafter:
@if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_AFTER); $(ELFSIZE); \
2>/dev/null; echo; fi
# Display compiler version information.
gccversion :
@$(CC) --version
# Create final output files (.hex, .eep) from ELF output file.
%.hex: %.elf
@echo
@echo $(MSG_FLASH) $@
$(OBJCOPY) -O $(FORMAT) -R .eeprom -R .fuse -R .lock -R .signature $< $@
%.eep: %.elf
@echo
@echo $(MSG_EEPROM) $@
-$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \
--change-section-lma .eeprom=0 --no-change-warnings -O $(FORMAT) $< $@ || exit 0
# Create extended listing file from ELF output file.
%.lss: %.elf
@echo
@echo $(MSG_EXTENDED_LISTING) $@
$(OBJDUMP) -h -S -z $< > $@
# Create a symbol table from ELF output file.
%.sym: %.elf
@echo
@echo $(MSG_SYMBOL_TABLE) $@
$(NM) -n $< > $@
# Create library from object files.
.SECONDARY : $(TARGET).a
.PRECIOUS : $(OBJ)
%.a: $(OBJ)
@echo
@echo $(MSG_CREATING_LIBRARY) $@
$(AR) $@ $(OBJ)
# Link: create ELF output file from object files.
.SECONDARY : $(TARGET).elf
.PRECIOUS : $(OBJ)
%.elf: $(OBJ)
@echo
@echo $(MSG_LINKING) $@
$(CC) $(ALL_CFLAGS) $^ --output $@ $(LDFLAGS)
# Compile: create object files from C source files.
$(OBJDIR)/%.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 $@
## Program
.PHONY: program
program: all
$(PROGRAM) $(PROGRAMFLAGS) $(ERASE)
$(PROGRAM) $(PROGRAMFLAGS) $(FLASH)
$(PROGRAM) $(PROGRAMFLAGS) $(START)
doxygen:
doxygen
# Target: clean project.
clean: begin clean_list end
clean_list :
@echo
@echo $(MSG_CLEANING)
$(REMOVE) $(TARGET).hex
$(REMOVE) $(TARGET).eep
$(REMOVE) $(TARGET).elf
$(REMOVE) $(TARGET).map
$(REMOVE) $(TARGET).sym
$(REMOVE) $(TARGET).lss
$(REMOVE) $(SRC:%.c=$(OBJDIR)/%.o)
$(REMOVE) $(SRC:%.c=$(OBJDIR)/%.lst)
$(REMOVE) $(SRC:.c=.s)
$(REMOVE) $(SRC:.c=.d)
$(REMOVEDIR) .dep
$(REMOVEDIR) $(OBJDIR)
# Create object files directory
$(shell mkdir $(OBJDIR) 2>/dev/null)
# 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 \
clean clean_list

View File

@@ -0,0 +1,289 @@
/**
@file main.`
@brief Lab 3 Starter Code
@version .01
@mainpage Lab 3 Starter Code
@section intro Code Overview
@section hw Hardware Pin Out
Port A:
A0 - A3 : Push Buttons
A4 - A7 : Slide Switches
Port B:
B0 - B3 : SPI (SD Card)
B4 : Nothing
B5 : Audio Out
B6 : Red Enable
B7 : Green Enable
Port C:
C0 - C7 : LED Array (Row)
Port D:
D0 - D1 : Nothing
D2 : Serial RX
D3 : Serial TX
D4 - D7 : Nothing
Port E:
E0 - E2 : LED Array (Column)
E3 : USB (UID)
E4 - E5 : Nothing
E6 : Relay
E7 : Nothing
Port F:
F0 : ADC Channel 0
F1 : ADC Channel 1
F2 : ADC Channel 2
F3 : ADC Channel 3
F4 : ADC Channel 4 (Audio In)
F5 : ADC Channel 5 (Accel X Axis)
F6 : ADC Channel 6 (Accel Y Axis)
F7 : ADC Channel 7 (Accel Z Axis (if installed))
*/
/** Includes */
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
/** Constants */
#define F_CPU 1000000UL
#define DEBUG 1
#ifdef DEBUG == 1
#define SENDSPEED 3 //If less than .12, there are problems
#endif
/** Global Variables */
volatile unsigned char loop = 0;
volatile unsigned char throwaway = 0;
volatile unsigned char loopdir = 0;
/** Functions */
/** Prototypes **/
unsigned char InitializeUART(void);
unsigned char SendByteUART (unsigned char data);
unsigned char SendStringUART (unsigned char *data);
void initialize(void);
void clearArray(void);
unsigned char initializeTIMER0(void);
unsigned char setTIMER0(unsigned char clock, unsigned char count);
ISR(TIMER0_COMPA_vect);
unsigned char myitoa(unsigned char received, unsigned char *send);
#ifdef DEBUG == 1
/** This function needs to setup the variables used by the UART to enable the UART and tramsmit at 9600bps. This
function should always return 0. Remember, by defualt the Wunderboard runs at 1mHz for its system clock.*/
unsigned char InitializeUART (void){
unsigned char baud = ((F_CPU/(9600*8UL))-1);
/* Set baud rate */
UBRR1H = (baud >> 8);
UBRR1L = baud;
/* Set the U2X1 bit */
UCSR1A = (1 << U2X1);
/* Enable transmitter */
UCSR1B = ((1 << TXEN1) | (1 << RXEN1));
/* Set frame format: 8data, 1stop bit */
UCSR1C = (3 << UCSZ10);
return 0;
}
/** This function needs to write a single byte to the UART. It must check that the UART is ready for a new byte
and return a 1 if the byte was not sent.
@param [in] data This is the data byte to be sent.
@return The function returns a 1 or error and 0 on successful completion.*/
unsigned char SendByteUART (unsigned char data){
/*
** Checks the buffer empty bit so that data can either be placed in the buffer
** or else reuturn a 1
*/
if((UCSR1A & (1 << UDRE1)) == (1 << UDRE1)){
UDR1 = data; //Places data into the UDR1 8-bit data buffer
}else {
return 1;
}
return 0;
}
/** This function needs to writes a string to the UART. It must check that the UART is ready for a new byte and
return a 1 if the string was not sent.
@param [in] data This is a pointer to the data to be sent.
@return The function returns a 1 or error and 0 on successful completion.*/
unsigned char SendStringUART (unsigned char *data){
for (int loop = 0 ; data[loop] != '\0'; loop++){
/* Sends the current byte based on the loop umber to SendByte */
while(SendByteUART(data[loop]));
}
return 0;
}
unsigned char GetByteUART(){
if (UCSR1A & (1 << RXC1)){
return(UDR1);
} else{
return(-1);
}
}
#endif
/** The initialize() function initializes all of the Data Direction Registers for the Wunderboard. Before making changes to DDRx registers, ensure that you have read the peripherals section of the Wunderboard user guide.*/
void initialize(void){
/** Port A is the switches and buttons. They should always be inputs. ( 0 = Input and 1 = Output )*/
DDRA=0b00000000;
/** Port B has the LED Array color control, SD card, and audio-out on it. Leave DDRB alone. ( 0 = Input and 1 = Output )*/
DDRB=0b11000111;
/** Port C is for the 'row' of the LED array. They should always be outputs. ( 0 = Input and 1 = Output )*/
DDRC=0b11111111;
/** Port D has the Serial on it. Leave DDRB alone. ( 0 = Input and 1 = Output )*/
DDRD=0b00001000;
/** Port E has the LED Array Column control out on it. Leave DDRE alone. ( 0 = Input and 1 = Output )*/
DDRE=0b00000111;
/** Port F has the accelerometer and audio-in on it. Leave DDRF alone. ( 0 = Input and 1 = Output )*/
DDRF=0b00000000;
}
void clearArray(void){
PORTC = 0x00;
PORTB |= (1 << PB6) | (1 << PB7); /** Enable latches*/
PORTB &= ~((1 << PB6) | (1 << PB7)); /** Disable latches*/
}
/** This function needs to setup the variables used by TIMER0 Compare Match (CTC) mode with
a base clock frequency of clk/1024. This function should return a 1 if it fails and a 0 if it
does not. Remember, by default the Wunderboard runs at 1mHz for its system clock.
@return This function returns a 1 is unsuccessful, else return 0.*/
unsigned char initializeTIMER0(void){
/* Set the CTC mode */
TCCR0A = (1 << WGM01);
/* Set the Clock Frequency */
TCCR0B = ((1 << CS02) | (1 << CS00));
/* Set initial count value */
OCR0A = 0;
return 0;
}
/** This function takes two values, clock and count. The value of count should be copied into OCR0A and the value of clock should be used to set CS02:0. The TCNT0 variable should also be reset to 0 so that the new timer rate starts from 0.
@param [in] clock Insert Comment
@param [in] count Insert Comment
@return The function returns a 1 or error and 0 on successful completion.*/
unsigned char setTIMER0(unsigned char clock, unsigned char count){
if(clock > 7){
return 1;
}
TCCR0B &= 0b11111000; //Zeros out last three bits
TCCR0B |= clock;
OCR0A = count;
TIMSK0 = 2;
TCNT0 = 0;
return 0;
}
ISR(TIMER0_COMPA_vect){
if(throwaway == 1){
volatile unsigned char send[4];
myitoa(loop, &send);
SendStringUART(send);
SendStringUART("\n");
throwaway = 0;
if(loop == 50){
loopdir = 1;
}else if(loop == 0){
loopdir = 0;
}
if(loopdir == 0){
loop++;
}else{
loop--;
}
}else{
throwaway++;
}
}
unsigned char myitoa(unsigned char received, unsigned char *send){
unsigned char tmp;
if(received > 99){
tmp = (received / 100);
send[0] = (tmp+48);
tmp = ((received % 100)/10);
send[1] = (tmp+48);
tmp = ((received % 100) % 10);
send[2] = (tmp+48);
send[3] = '\0';
return 0;
}else if(received > 9){
tmp = ((received % 100)/10);
send[0] = (tmp+48);
tmp = ((received % 100) % 10);
send[1] = (tmp+48);
send[2] = '\0';
return 0;
}else if(received < 10){
tmp = ((received % 100) % 10);
send[0] = (tmp+48);
send[1] = '\0';
return 0;
}
}
/** Main Function */
int main (void){
enum states{
setup,
running
} state = setup;
while(1){
switch(state){
case setup:
initialize();
initializeTIMER0();
InitializeUART();
setTIMER0(5,120);
clearArray();
sei();
state = running;
SendStringUART("Initialized...\n");
break;
case running:
break;
}
}
}

View File

@@ -0,0 +1,335 @@
#----------------------------------------------------------------------------
# Wunderboard Makefile Template written by Dan Albert
#----------------------------------------------------------------------------
#
# make all = Make software.
#
# make clean = Clean out built project files.
#
# make filename.s = Just compile filename.c into the assembler code only.
#
# To rebuild project do "make clean" then "make all".
#----------------------------------------------------------------------------
# Target file name.
TARGET = main
# List C source files here.
SRC = $(TARGET).c \
# MCU name, you MUST set this to match the board you are using
# type "make clean" after changing this, so all files will be rebuilt
MCU = at90usb646
# Detect platform
UNAME = $(shell uname)
ifeq ($(UNAME),Linux)
ENV=unix
endif
ifeq ($(UNAME),Darwin)
ENV=unix
endif
ifndef ENV
ENV=windows
endif
ifeq ($(ENV),unix)
PROGRAM = dfu-programmer
PROGRAMFLAGS = $(MCU)
ERASE = erase
FLASH = flash "$(TARGET).hex"
START = start
else
PROGRAM = "C:/Program Files (x86)/Atmel/Flip 3.4.1/bin/batchisp.exe"
PROGRAMFLAGS = -device at90usb646 -hardware USB
ERASE = -operation erase F
FLASH = -operation loadbuffer "$(TARGET).hex" program verify
START = -operation start noreset 0
endif
# Processor frequency.
# Normally the first thing your program should do is set the clock prescaler,
# so your program will run at the correct speed. You should also set this
# variable to same clock speed. The _delay_ms() macro uses this, and many
# examples use this variable to calculate timings. Do not add a "UL" here.
F_CPU = 8000000
# Output format. (can be srec, ihex, binary)
FORMAT = ihex
# Object files directory
# To put object files in current directory, use a dot (.), do NOT make
# this an empty or blank macro!
OBJDIR = obj
# 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
# List any extra directories to look for include files here.
# Each directory must be seperated by a space.
# Use forward slashes for directory separators.
# For a directory that has spaces, enclose it in quotes.
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 for C sources
CDEFS = -DF_CPU=$(F_CPU)UL
#---------------- Compiler Options C ----------------
# -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 += $(CDEFS)
CFLAGS += -O$(OPT)
CFLAGS += -funsigned-char
CFLAGS += -funsigned-bitfields
CFLAGS += -ffunction-sections
CFLAGS += -fpack-struct
CFLAGS += -fshort-enums
CFLAGS += -Wall
CFLAGS += -Wstrict-prototypes
#CFLAGS += -mshort-calls
#CFLAGS += -fno-unit-at-a-time
#CFLAGS += -Wundef
#CFLAGS += -Wunreachable-code
#CFLAGS += -Wsign-compare
CFLAGS += -Wa,-adhlns=$(<:%.c=$(OBJDIR)/%.lst)
CFLAGS += $(patsubst %,-I%,$(EXTRAINCDIRS))
CFLAGS += $(CSTANDARD)
#---------------- Library Options ----------------
# 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
# If this is left blank, then it will use the Standard printf version.
PRINTF_LIB =
#PRINTF_LIB = $(PRINTF_LIB_MIN)
#PRINTF_LIB = $(PRINTF_LIB_FLOAT)
# 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
# If this is left blank, then it will use the Standard scanf version.
SCANF_LIB =
#SCANF_LIB = $(SCANF_LIB_MIN)
#SCANF_LIB = $(SCANF_LIB_FLOAT)
MATH_LIB = -lm
# List any extra directories to look for libraries here.
# Each directory must be seperated by a space.
# Use forward slashes for directory separators.
# For a directory that has spaces, enclose it in quotes.
EXTRALIBDIRS =
#---------------- Linker Options ----------------
# -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 += -Wl,--relax
LDFLAGS += -Wl,--gc-sections
LDFLAGS += $(patsubst %,-L%,$(EXTRALIBDIRS))
LDFLAGS += $(PRINTF_LIB) $(SCANF_LIB) $(MATH_LIB)
#LDFLAGS += -T linker_script.x
#============================================================================
# Define programs and commands.
SHELL = sh
CC = avr-gcc
OBJCOPY = avr-objcopy
OBJDUMP = avr-objdump
SIZE = avr-size
AR = avr-ar rcs
NM = avr-nm
REMOVE = rm -f
REMOVEDIR = rm -rf
COPY = cp
WINSHELL = cmd
# 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_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 C:
MSG_ASSEMBLING = Assembling:
MSG_CLEANING = Cleaning project:
MSG_CREATING_LIBRARY = Creating library:
# Define all object files.
OBJ = $(SRC:%.c=$(OBJDIR)/%.o)
# Define all listing files.
LST = $(SRC:%.c=$(OBJDIR)/%.lst)
# Compiler flags to generate dependency files.
GENDEPFLAGS = -MMD -MP -MF .dep/$(@F).d
# Combine all necessary flags and optional flags.
# Add target processor to flags.
ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) $(GENDEPFLAGS)
# Default target.
all: begin gccversion sizebefore build sizeafter end
# Change the build target to build a HEX file or a library.
build: elf hex eep lss sym
#build: lib
elf: $(TARGET).elf
hex: $(TARGET).hex
eep: $(TARGET).eep
lss: $(TARGET).lss
sym: $(TARGET).sym
LIBNAME=lib$(TARGET).a
lib: $(LIBNAME)
# 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)
end:
@echo $(MSG_END)
@echo
# Display size of file.
HEXSIZE = $(SIZE) --target=$(FORMAT) $(TARGET).hex
ELFSIZE = $(SIZE) --mcu=$(MCU) --format=avr $(TARGET).elf
sizebefore:
@if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_BEFORE); $(ELFSIZE); \
2>/dev/null; echo; fi
sizeafter:
@if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_AFTER); $(ELFSIZE); \
2>/dev/null; echo; fi
# Display compiler version information.
gccversion :
@$(CC) --version
# Create final output files (.hex, .eep) from ELF output file.
%.hex: %.elf
@echo
@echo $(MSG_FLASH) $@
$(OBJCOPY) -O $(FORMAT) -R .eeprom -R .fuse -R .lock -R .signature $< $@
%.eep: %.elf
@echo
@echo $(MSG_EEPROM) $@
-$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \
--change-section-lma .eeprom=0 --no-change-warnings -O $(FORMAT) $< $@ || exit 0
# Create extended listing file from ELF output file.
%.lss: %.elf
@echo
@echo $(MSG_EXTENDED_LISTING) $@
$(OBJDUMP) -h -S -z $< > $@
# Create a symbol table from ELF output file.
%.sym: %.elf
@echo
@echo $(MSG_SYMBOL_TABLE) $@
$(NM) -n $< > $@
# Create library from object files.
.SECONDARY : $(TARGET).a
.PRECIOUS : $(OBJ)
%.a: $(OBJ)
@echo
@echo $(MSG_CREATING_LIBRARY) $@
$(AR) $@ $(OBJ)
# Link: create ELF output file from object files.
.SECONDARY : $(TARGET).elf
.PRECIOUS : $(OBJ)
%.elf: $(OBJ)
@echo
@echo $(MSG_LINKING) $@
$(CC) $(ALL_CFLAGS) $^ --output $@ $(LDFLAGS)
# Compile: create object files from C source files.
$(OBJDIR)/%.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 $@
## Program
.PHONY: program
program: all
$(PROGRAM) $(PROGRAMFLAGS) $(ERASE)
$(PROGRAM) $(PROGRAMFLAGS) $(FLASH)
$(PROGRAM) $(PROGRAMFLAGS) $(START)
doxygen:
doxygen
# Target: clean project.
clean: begin clean_list end
clean_list :
@echo
@echo $(MSG_CLEANING)
$(REMOVE) $(TARGET).hex
$(REMOVE) $(TARGET).eep
$(REMOVE) $(TARGET).elf
$(REMOVE) $(TARGET).map
$(REMOVE) $(TARGET).sym
$(REMOVE) $(TARGET).lss
$(REMOVE) $(SRC:%.c=$(OBJDIR)/%.o)
$(REMOVE) $(SRC:%.c=$(OBJDIR)/%.lst)
$(REMOVE) $(SRC:.c=.s)
$(REMOVE) $(SRC:.c=.d)
$(REMOVEDIR) .dep
$(REMOVEDIR) $(OBJDIR)
# Create object files directory
$(shell mkdir $(OBJDIR) 2>/dev/null)
# 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 \
clean clean_list

View File

@@ -0,0 +1,192 @@
/**
@file main.c
@brief Lab 2 Starter Code
@version .01
@mainpage Lab 2 Starter Code
@section intro Code Overview
@section hw Hardware Pin Out
Port A:
A0 - A3 : Push Buttons
A4 - A7 : Slide Switches
Port B:
B0 - B3 : SPI (SD Card)
B4 : Nothing
B5 : Audio Out
B6 : Red Enable
B7 : Green Enable
Port C:
C0 - C7 : LED Array (Row)
Port D:
D0 - D1 : Nothing
D2 : Serial RX
D3 : Serial TX
D4 - D7 : Nothing
Port E:
E0 - E2 : LED Array (Column)
E3 : USB (UID)
E4 - E5 : Nothing
E6 : Relay
E7 : Nothing
Port F:
F0 : ADC Channel 0
F1 : ADC Channel 1
F2 : ADC Channel 2
F3 : ADC Channel 3
F4 : ADC Channel 4 (Audio In)
F5 : ADC Channel 5 (Accel X Axis)
F6 : ADC Channel 6 (Accel Y Axis)
F7 : ADC Channel 7 (Accel Z Axis (if installed))
*/
/** Includes */
#include <avr/io.h>
#include <util/delay.h>
/** Constants */
#define DEBUG //Comment or uncomment this to enable/disable debugging
#define F_CPU 1000000U
/** Sets the string send speed for debugging when defined */
#ifdef DEBUG
#define SENDSPEED .2 //If less than .2, there are problems
#endif
/** Global Variables */
/** Functions */
/** When DEBUG is defined, this provides the functions needed to debug over serial */
#ifdef DEBUG
/** This function needs to setup the variables used by the UART to enable the UART and tramsmit at 9600bps. This
function should always return 0. Remember, by defualt the Wunderboard runs at 1mHz for its system clock.*/
unsigned char InitializeUART (){
unsigned char baud = ((F_CPU/(9600*8UL))-1);
/* Set baud rate */
UBRR1H = (baud >> 8);
UBRR1L = baud;
/* Set the U2X1 bit */
UCSR1A = (1 << U2X1);
/* Enable transmitter */
UCSR1B = (1 << TXEN1);
/* Set frame format: 8data, 1stop bit */
UCSR1C = (3 << UCSZ10);
return 0;
}
/** This function needs to write a single byte to the UART. It must check that the UART is ready for a new byte
and return a 1 if the byte was not sent.
@param [in] data This is the data byte to be sent.
@return The function returns a 1 or error and 0 on successful completion.*/
unsigned char SendByteUART (unsigned char data){
/*
** Checks the buffer empty bit so that data can either be placed in the buffer
** or else reuturn a 1
*/
if((UCSR1A & (1 << UDRE1)) == (1 << UDRE1)){
UDR1 = data;
_delay_ms(SENDSPEED); //Places data into the UDR1 8-bit data buffer
}else {
return 1;
}
return 0;
}
/** This function needs to writes a string to the UART. It must check that the UART is ready for a new byte and
return a 1 if the string was not sent.
@param [in] data This is a pointer to the data to be sent.
@return The function returns a 1 or error and 0 on successful completion.*/
unsigned char SendStringUART (unsigned char *data){
for (int loop = 0 ; data[loop] != '\0'; loop++){
unsigned char bytereturn; //Storage for return value of SendByteUART
/* Sends the current byte based on the loop umber to SendByte */
bytereturn = SendByteUART(data[loop]);
/* Stops sending if SendByteUART had an error */
if(bytereturn == 1){
return 1;
}
}
return 0;
}
#endif
/** The initialize() function initializes all of the Data Direction Registers for the Wunderboard. Before making changes to DDRx registers, ensure that you have read the peripherals section of the Wunderboard user guide.*/
void initialize (void) {
/** Port A is the switches and buttons. They should always be inputs. ( 0 = Input and 1 = Output )*/
DDRA=0b00000000;
/** Port B has the LED Array color control, SD card, and audio-out on it. Leave DDRB alone. ( 0 = Input and 1 = Output )*/
DDRB=0b11000000;
/** Port C is for the 'row' of the LED array. They should always be outputs. ( 0 = Input and 1 = Output )*/
DDRC=0b11111111;
/** Port D has the Serial on it. Leave DDRB alone. ( 0 = Input and 1 = Output )*/
DDRD=0b00001000;
/** Port E has the LED Array Column control out on it. Leave DDRE alone. ( 0 = Input and 1 = Output )*/
DDRE=0b00000111;
/** Port F has the accelerometer and audio-in on it. Leave DDRF alone. ( 0 = Input and 1 = Output )*/
DDRF=0b00000000;
}
/** The clearArray() function turns off all LEDS on the Wunderboard array. It accepts no inputs and returns nothing*/
void clearArray(void) {
PORTC = 0x00;
PORTB |= (1 << PB6) | (1 << PB7); /** Enable latches*/
PORTB &= ~((1 << PB6) | (1 << PB7)); /** Disable latches*/
}
/** Main Function */
int main (void) {
/** Local Varibles */
initialize();
clearArray();
/** Initializes the serial interface if debugging is enabled */
#ifdef DEBUG
InitializeUART();
#endif
PORTB = 0b10000000;
while(1){
unsigned char pinastatus = PINA;
unsigned char debugstring[50];
#ifdef DEBUG
sprintf(debugstring, "Port A is: %d.\n", pinastatus);
SendStringUART(debugstring);
#endif
for (unsigned char loop = 0 ; loop < 8 ; loop++){
PORTB = 0b10000000;
PORTE = loop;
PORTC = pinastatus;
_delay_ms(.07);
clearArray();
}
}//while
}//main

View File

@@ -0,0 +1,337 @@
#----------------------------------------------------------------------------
# Wunderboard Makefile Template written by Dan Albert
#----------------------------------------------------------------------------
#
# make all = Make software.
#
# make clean = Clean out built project files.
#
# make filename.s = Just compile filename.c into the assembler code only.
#
# To rebuild project do "make clean" then "make all".
#----------------------------------------------------------------------------
# Target file name.
TARGET = main
# List C source files here.
SRC = $(TARGET).c \
ff.c \
diskio.c \
# MCU name, you MUST set this to match the board you are using
# type "make clean" after changing this, so all files will be rebuilt
MCU = at90usb646
# Detect platform
UNAME = $(shell uname)
ifeq ($(UNAME),Linux)
ENV=unix
endif
ifeq ($(UNAME),Darwin)
ENV=unix
endif
ifndef ENV
ENV=windows
endif
ifeq ($(ENV),unix)
PROGRAM = dfu-programmer
PROGRAMFLAGS = $(MCU)
ERASE = erase
FLASH = flash "$(TARGET).hex"
START = start
else
PROGRAM = "batchisp.exe"
PROGRAMFLAGS = -device at90usb646 -hardware USB
ERASE = -operation erase F
FLASH = -operation loadbuffer "$(TARGET).hex" program verify
START = -operation start noreset 0
endif
# Processor frequency.
# Normally the first thing your program should do is set the clock prescaler,
# so your program will run at the correct speed. You should also set this
# variable to same clock speed. The _delay_ms() macro uses this, and many
# examples use this variable to calculate timings. Do not add a "UL" here.
F_CPU = 1000000
# Output format. (can be srec, ihex, binary)
FORMAT = ihex
# Object files directory
# To put object files in current directory, use a dot (.), do NOT make
# this an empty or blank macro!
OBJDIR = obj
# 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
# List any extra directories to look for include files here.
# Each directory must be seperated by a space.
# Use forward slashes for directory separators.
# For a directory that has spaces, enclose it in quotes.
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 for C sources
CDEFS = -DF_CPU=$(F_CPU)UL
#---------------- Compiler Options C ----------------
# -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 += $(CDEFS)
CFLAGS += -O$(OPT)
CFLAGS += -funsigned-char
CFLAGS += -funsigned-bitfields
CFLAGS += -ffunction-sections
CFLAGS += -fpack-struct
CFLAGS += -fshort-enums
CFLAGS += -Wall
CFLAGS += -Wstrict-prototypes
#CFLAGS += -mshort-calls
#CFLAGS += -fno-unit-at-a-time
#CFLAGS += -Wundef
#CFLAGS += -Wunreachable-code
#CFLAGS += -Wsign-compare
CFLAGS += -Wa,-adhlns=$(<:%.c=$(OBJDIR)/%.lst)
CFLAGS += $(patsubst %,-I%,$(EXTRAINCDIRS))
CFLAGS += $(CSTANDARD)
#---------------- Library Options ----------------
# 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
# If this is left blank, then it will use the Standard printf version.
PRINTF_LIB =
#PRINTF_LIB = $(PRINTF_LIB_MIN)
#PRINTF_LIB = $(PRINTF_LIB_FLOAT)
# 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
# If this is left blank, then it will use the Standard scanf version.
SCANF_LIB =
#SCANF_LIB = $(SCANF_LIB_MIN)
#SCANF_LIB = $(SCANF_LIB_FLOAT)
MATH_LIB = -lm
# List any extra directories to look for libraries here.
# Each directory must be seperated by a space.
# Use forward slashes for directory separators.
# For a directory that has spaces, enclose it in quotes.
EXTRALIBDIRS =
#---------------- Linker Options ----------------
# -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 += -Wl,--relax
LDFLAGS += -Wl,--gc-sections
LDFLAGS += $(patsubst %,-L%,$(EXTRALIBDIRS))
LDFLAGS += $(PRINTF_LIB) $(SCANF_LIB) $(MATH_LIB)
#LDFLAGS += -T linker_script.x
#============================================================================
# Define programs and commands.
SHELL = sh
CC = avr-gcc
OBJCOPY = avr-objcopy
OBJDUMP = avr-objdump
SIZE = avr-size
AR = avr-ar rcs
NM = avr-nm
REMOVE = rm -f
REMOVEDIR = rm -rf
COPY = cp
WINSHELL = cmd
# 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_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 C:
MSG_ASSEMBLING = Assembling:
MSG_CLEANING = Cleaning project:
MSG_CREATING_LIBRARY = Creating library:
# Define all object files.
OBJ = $(SRC:%.c=$(OBJDIR)/%.o)
# Define all listing files.
LST = $(SRC:%.c=$(OBJDIR)/%.lst)
# Compiler flags to generate dependency files.
GENDEPFLAGS = -MMD -MP -MF .dep/$(@F).d
# Combine all necessary flags and optional flags.
# Add target processor to flags.
ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) $(GENDEPFLAGS)
# Default target.
all: begin gccversion sizebefore build sizeafter end
# Change the build target to build a HEX file or a library.
build: elf hex eep lss sym
#build: lib
elf: $(TARGET).elf
hex: $(TARGET).hex
eep: $(TARGET).eep
lss: $(TARGET).lss
sym: $(TARGET).sym
LIBNAME=lib$(TARGET).a
lib: $(LIBNAME)
# 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)
end:
@echo $(MSG_END)
@echo
# Display size of file.
HEXSIZE = $(SIZE) --target=$(FORMAT) $(TARGET).hex
ELFSIZE = $(SIZE) --mcu=$(MCU) --format=avr $(TARGET).elf
sizebefore:
@if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_BEFORE); $(ELFSIZE); \
2>/dev/null; echo; fi
sizeafter:
@if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_AFTER); $(ELFSIZE); \
2>/dev/null; echo; fi
# Display compiler version information.
gccversion :
@$(CC) --version
# Create final output files (.hex, .eep) from ELF output file.
%.hex: %.elf
@echo
@echo $(MSG_FLASH) $@
$(OBJCOPY) -O $(FORMAT) -R .eeprom -R .fuse -R .lock -R .signature $< $@
%.eep: %.elf
@echo
@echo $(MSG_EEPROM) $@
-$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \
--change-section-lma .eeprom=0 --no-change-warnings -O $(FORMAT) $< $@ || exit 0
# Create extended listing file from ELF output file.
%.lss: %.elf
@echo
@echo $(MSG_EXTENDED_LISTING) $@
$(OBJDUMP) -h -S -z $< > $@
# Create a symbol table from ELF output file.
%.sym: %.elf
@echo
@echo $(MSG_SYMBOL_TABLE) $@
$(NM) -n $< > $@
# Create library from object files.
.SECONDARY : $(TARGET).a
.PRECIOUS : $(OBJ)
%.a: $(OBJ)
@echo
@echo $(MSG_CREATING_LIBRARY) $@
$(AR) $@ $(OBJ)
# Link: create ELF output file from object files.
.SECONDARY : $(TARGET).elf
.PRECIOUS : $(OBJ)
%.elf: $(OBJ)
@echo
@echo $(MSG_LINKING) $@
$(CC) $(ALL_CFLAGS) $^ --output $@ $(LDFLAGS)
# Compile: create object files from C source files.
$(OBJDIR)/%.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 $@
## Program
.PHONY: program
program: all
$(PROGRAM) $(PROGRAMFLAGS) $(ERASE)
$(PROGRAM) $(PROGRAMFLAGS) $(FLASH)
$(PROGRAM) $(PROGRAMFLAGS) $(START)
doxygen:
doxygen
# Target: clean project.
clean: begin clean_list end
clean_list :
@echo
@echo $(MSG_CLEANING)
$(REMOVE) $(TARGET).hex
$(REMOVE) $(TARGET).eep
$(REMOVE) $(TARGET).elf
$(REMOVE) $(TARGET).map
$(REMOVE) $(TARGET).sym
$(REMOVE) $(TARGET).lss
$(REMOVE) $(SRC:%.c=$(OBJDIR)/%.o)
$(REMOVE) $(SRC:%.c=$(OBJDIR)/%.lst)
$(REMOVE) $(SRC:.c=.s)
$(REMOVE) $(SRC:.c=.d)
$(REMOVEDIR) .dep
$(REMOVEDIR) $(OBJDIR)
# Create object files directory
$(shell mkdir $(OBJDIR) 2>/dev/null)
# 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 \
clean clean_list

View File

@@ -0,0 +1,623 @@
/*-----------------------------------------------------------------------*/
/* MMCv3/SDv1/SDv2 (in SPI mode) control module (C)ChaN, 2007 */
/*-----------------------------------------------------------------------*/
/* Only rcvr_spi(), xmit_spi(), disk_timerproc() and some macros */
/* are platform dependent. */
/*-----------------------------------------------------------------------*/
#include <avr/io.h>
#include <avr/interrupt.h>
#include "diskio.h"
/* Definitions for MMC/SDC command */
#define CMD0 (0) /* GO_IDLE_STATE */
#define CMD1 (1) /* SEND_OP_COND (MMC) */
#define ACMD41 (0x80+41) /* SEND_OP_COND (SDC) */
#define CMD8 (8) /* SEND_IF_COND */
#define CMD9 (9) /* SEND_CSD */
#define CMD10 (10) /* SEND_CID */
#define CMD12 (12) /* STOP_TRANSMISSION */
#define ACMD13 (0x80+13) /* SD_STATUS (SDC) */
#define CMD16 (16) /* SET_BLOCKLEN */
#define CMD17 (17) /* READ_SINGLE_BLOCK */
#define CMD18 (18) /* READ_MULTIPLE_BLOCK */
#define CMD23 (23) /* SET_BLOCK_COUNT (MMC) */
#define ACMD23 (0x80+23) /* SET_WR_BLK_ERASE_COUNT (SDC) */
#define CMD24 (24) /* WRITE_BLOCK */
#define CMD25 (25) /* WRITE_MULTIPLE_BLOCK */
#define CMD55 (55) /* APP_CMD */
#define CMD58 (58) /* READ_OCR */
/* Port Controls (Platform dependent) */
#define CS_LOW() PORTB &= ~1 /* MMC CS = L */
#define CS_HIGH() PORTB |= 1 /* MMC CS = H */
#define SOCKPORT PINB /* Socket contact port */
#define SOCKWP 0x20 /* Write protect switch (PB5) */
#define SOCKINS 0x10 /* Card detect switch (PB4) */
#define FCLK_SLOW() SPCR = 0x52 /* Set slow clock (100k-400k) */
#define FCLK_FAST() SPCR = 0x50 /* Set fast clock (depends on the CSD) */
/*--------------------------------------------------------------------------
Module Private Functions
---------------------------------------------------------------------------*/
static volatile
DSTATUS Stat = STA_NOINIT; /* Disk status */
static volatile
BYTE Timer1, Timer2; /* 100Hz decrement timer */
static
BYTE CardType; /* Card type flags */
/*-----------------------------------------------------------------------*/
/* Transmit a byte to MMC via SPI (Platform dependent) */
/*-----------------------------------------------------------------------*/
#define xmit_spi(dat) cli(); SPDR=(dat); loop_until_bit_is_set(SPSR,SPIF); sei()
/*-----------------------------------------------------------------------*/
/* Receive a byte from MMC via SPI (Platform dependent) */
/*-----------------------------------------------------------------------*/
static
BYTE rcvr_spi (void)
{
cli();
SPDR = 0xFF;
loop_until_bit_is_set(SPSR, SPIF);
sei();
return SPDR;
}
/* Alternative macro to receive data fast */
#define rcvr_spi_m(dst) SPDR=0xFF; loop_until_bit_is_set(SPSR,SPIF); *(dst)=SPDR
/*-----------------------------------------------------------------------*/
/* Wait for card ready */
/*-----------------------------------------------------------------------*/
static
int wait_ready (void) /* 1:OK, 0:Timeout */
{
Timer2 = 50; /* Wait for ready in timeout of 500ms */
rcvr_spi();
do
if (rcvr_spi() == 0xFF) return 1;
while (Timer2);
return 0;
}
/*-----------------------------------------------------------------------*/
/* Deselect the card and release SPI bus */
/*-----------------------------------------------------------------------*/
static
void deselect (void)
{
CS_HIGH();
rcvr_spi();
}
/*-----------------------------------------------------------------------*/
/* Select the card and wait for ready */
/*-----------------------------------------------------------------------*/
static
int select (void) /* 1:Successful, 0:Timeout */
{
CS_LOW();
if (!wait_ready()) {
deselect();
return 0;
}
return 1;
}
/*-----------------------------------------------------------------------*/
/* Power Control (Platform dependent) */
/*-----------------------------------------------------------------------*/
/* When the target system does not support socket power control, there */
/* is nothing to do in these functions and chk_power always returns 1. */
/*
static
void power_on (void)
{
PORTE &= ~0x80; // Socket power ON *
for (Timer1 = 3; Timer1; ); // Wait for 30ms *
PORTB = 0b10110101; //Enable drivers *
DDRB = 0b11000111;
SPCR = 0x52; // Enable SPI function in mode 0 *
SPSR = 0x01; // 2x mode *
}
static
void power_off (void)
{
select(); // Wait for card ready *
deselect();
SPCR = 0; // Disable SPI function *
DDRB = 0b11000000; // Disable drivers *
PORTB = 0b10110000;
PORTE |= 0x80; // Socket power OFF *
Stat |= STA_NOINIT; // Set STA_NOINIT *
}
*/
static
int chk_power(void) /* Socket power state: 0=off, 1=on */
{
return 1;
}
/*-----------------------------------------------------------------------*/
/* Receive a data packet from MMC */
/*-----------------------------------------------------------------------*/
static
int rcvr_datablock (
BYTE *buff, /* Data buffer to store received data */
UINT btr /* Byte count (must be multiple of 4) */
)
{
BYTE token;
Timer1 = 20;
do { /* Wait for data packet in timeout of 200ms */
token = rcvr_spi();
} while ((token == 0xFF) && Timer1);
if(token != 0xFE) return 0; /* If not valid data token, retutn with error */
do { /* Receive the data block into buffer */
rcvr_spi_m(buff++);
rcvr_spi_m(buff++);
rcvr_spi_m(buff++);
rcvr_spi_m(buff++);
} while (btr -= 4);
rcvr_spi(); /* Discard CRC */
rcvr_spi();
return 1; /* Return with success */
}
/*-----------------------------------------------------------------------*/
/* Send a data packet to MMC */
/*-----------------------------------------------------------------------*/
#if _READONLY == 0
static
int xmit_datablock (
const BYTE *buff, /* 512 byte data block to be transmitted */
BYTE token /* Data/Stop token */
)
{
BYTE resp, wc;
if (!wait_ready()) return 0;
xmit_spi(token); /* Xmit data token */
if (token != 0xFD) { /* Is data token */
wc = 0;
do { /* Xmit the 512 byte data block to MMC */
xmit_spi(*buff++);
xmit_spi(*buff++);
} while (--wc);
xmit_spi(0xFF); /* CRC (Dummy) */
xmit_spi(0xFF);
resp = rcvr_spi(); /* Reveive data response */
if ((resp & 0x1F) != 0x05) /* If not accepted, return with error */
return 0;
}
return 1;
}
#endif /* _READONLY */
/*-----------------------------------------------------------------------*/
/* Send a command packet to MMC */
/*-----------------------------------------------------------------------*/
static
BYTE send_cmd ( /* Returns R1 resp (bit7==1:Send failed) */
BYTE cmd, /* Command index */
DWORD arg /* Argument */
)
{
BYTE n, res;
if (cmd & 0x80) { /* ACMD<n> is the command sequense of CMD55-CMD<n> */
cmd &= 0x7F;
res = send_cmd(CMD55, 0);
if (res > 1) return res;
}
/* Select the card and wait for ready */
deselect();
if (!select()) return 0xFF;
/* Send command packet */
xmit_spi(0x40 | cmd); /* Start + Command index */
xmit_spi((BYTE)(arg >> 24)); /* Argument[31..24] */
xmit_spi((BYTE)(arg >> 16)); /* Argument[23..16] */
xmit_spi((BYTE)(arg >> 8)); /* Argument[15..8] */
xmit_spi((BYTE)arg); /* Argument[7..0] */
n = 0x01; /* Dummy CRC + Stop */
if (cmd == CMD0) n = 0x95; /* Valid CRC for CMD0(0) */
if (cmd == CMD8) n = 0x87; /* Valid CRC for CMD8(0x1AA) */
xmit_spi(n);
/* Receive command response */
if (cmd == CMD12) rcvr_spi(); /* Skip a stuff byte when stop reading */
n = 10; /* Wait for a valid response in timeout of 10 attempts */
do
res = rcvr_spi();
while ((res & 0x80) && --n);
return res; /* Return with the response value */
}
/*--------------------------------------------------------------------------
Public Functions
---------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------*/
/* Initialize Disk Drive */
/*-----------------------------------------------------------------------*/
DSTATUS disk_initialize (BYTE drv) /* Physical drive nmuber (0) */
{
BYTE n, cmd, ty, ocr[4];
if (drv) return STA_NOINIT; /* Supports only single drive */
if (Stat & STA_NODISK) return Stat; /* No card in the socket */
//power_on(); /* Force socket power on */
PORTB |= 0b11000000;
FCLK_SLOW();
for (n = 10; n; n--) rcvr_spi(); /* 80 dummy clocks */
ty = 0;
if (send_cmd(CMD0, 0) == 1) { /* Enter Idle state */
Timer1 = 200; /* Initialization timeout of 1000 msec */
if (send_cmd(CMD8, 0x1AA) == 1) { /* SDv2? */
for (n = 0; n < 4; n++) ocr[n] = rcvr_spi(); /* Get trailing return value of R7 resp */
if (ocr[2] == 0x01 && ocr[3] == 0xAA) { /* The card can work at vdd range of 2.7-3.6V */
while (Timer1 && send_cmd(ACMD41, 1UL << 30)); /* Wait for leaving idle state (ACMD41 with HCS bit) */
if (Timer1 && send_cmd(CMD58, 0) == 0) { /* Check CCS bit in the OCR */
for (n = 0; n < 4; n++) ocr[n] = rcvr_spi();
ty = (ocr[0] & 0x40) ? CT_SD2 | CT_BLOCK : CT_SD2; /* SDv2 */
}
}
} else { /* SDv1 or MMCv3 */
if (send_cmd(ACMD41, 0) <= 1) {
ty = CT_SD1; cmd = ACMD41; /* SDv1 */
} else {
ty = CT_MMC; cmd = CMD1; /* MMCv3 */
}
while (Timer1 && send_cmd(cmd, 0)); /* Wait for leaving idle state */
if (!Timer1 || send_cmd(CMD16, 512) != 0) /* Set R/W block length to 512 */
ty = 0;
}
}
CardType = ty;
deselect();
if (ty) { /* Initialization succeded */
Stat &= ~STA_NOINIT; /* Clear STA_NOINIT */
FCLK_FAST();
} else { /* Initialization failed */
//power_off();
}
return Stat;
}
/*-----------------------------------------------------------------------*/
/* Get Disk Status */
/*-----------------------------------------------------------------------*/
DSTATUS disk_status (
BYTE drv /* Physical drive nmuber (0) */
)
{
if (drv) return STA_NOINIT; /* Supports only single drive */
return Stat;
}
/*-----------------------------------------------------------------------*/
/* Read Sector(s) */
/*-----------------------------------------------------------------------*/
DRESULT disk_read (
BYTE drv, /* Physical drive nmuber (0) */
BYTE *buff, /* Pointer to the data buffer to store read data */
DWORD sector, /* Start sector number (LBA) */
BYTE count /* Sector count (1..255) */
)
{
if (drv || !count) return RES_PARERR;
if (Stat & STA_NOINIT) return RES_NOTRDY;
if (!(CardType & CT_BLOCK)) sector *= 512; /* Convert to byte address if needed */
if (count == 1) { /* Single block read */
if ((send_cmd(CMD17, sector) == 0) /* READ_SINGLE_BLOCK */
&& rcvr_datablock(buff, 512))
count = 0;
}
else { /* Multiple block read */
if (send_cmd(CMD18, sector) == 0) { /* READ_MULTIPLE_BLOCK */
do {
if (!rcvr_datablock(buff, 512)) break;
buff += 512;
} while (--count);
send_cmd(CMD12, 0); /* STOP_TRANSMISSION */
}
}
deselect();
return count ? RES_ERROR : RES_OK;
}
/*-----------------------------------------------------------------------*/
/* Write Sector(s) */
/*-----------------------------------------------------------------------*/
#if _READONLY == 0
DRESULT disk_write (
BYTE drv, /* Physical drive nmuber (0) */
const BYTE *buff, /* Pointer to the data to be written */
DWORD sector, /* Start sector number (LBA) */
BYTE count /* Sector count (1..255) */
)
{
if (drv || !count) return RES_PARERR;
if (Stat & STA_NOINIT) return RES_NOTRDY;
if (Stat & STA_PROTECT) return RES_WRPRT;
if (!(CardType & CT_BLOCK)) sector *= 512; /* Convert to byte address if needed */
if (count == 1) { /* Single block write */
if ((send_cmd(CMD24, sector) == 0) /* WRITE_BLOCK */
&& xmit_datablock(buff, 0xFE))
count = 0;
}
else { /* Multiple block write */
if (CardType & CT_SDC) send_cmd(ACMD23, count);
if (send_cmd(CMD25, sector) == 0) { /* WRITE_MULTIPLE_BLOCK */
do {
if (!xmit_datablock(buff, 0xFC)) break;
buff += 512;
} while (--count);
if (!xmit_datablock(0, 0xFD)) /* STOP_TRAN token */
count = 1;
}
}
deselect();
return count ? RES_ERROR : RES_OK;
}
#endif /* _READONLY == 0 */
/*-----------------------------------------------------------------------*/
/* Miscellaneous Functions */
/*-----------------------------------------------------------------------*/
#if _USE_IOCTL != 0
DRESULT disk_ioctl (
BYTE drv, /* Physical drive nmuber (0) */
BYTE ctrl, /* Control code */
void *buff /* Buffer to send/receive control data */
)
{
DRESULT res;
BYTE n, csd[16], *ptr = buff;
WORD csize;
if (drv) return RES_PARERR;
res = RES_ERROR;
if (ctrl == CTRL_POWER) {
switch (*ptr) {
case 0: /* Sub control code == 0 (POWER_OFF) */
if (chk_power())
//power_off(); // Power off */
res = RES_OK;
break;
case 1: /* Sub control code == 1 (POWER_ON) */
//power_on(); // Power on */
res = RES_OK;
break;
case 2: /* Sub control code == 2 (POWER_GET) */
*(ptr+1) = (BYTE)chk_power();
res = RES_OK;
break;
default :
res = RES_PARERR;
}
}
else {
if (Stat & STA_NOINIT) return RES_NOTRDY;
switch (ctrl) {
case CTRL_SYNC : /* Make sure that no pending write process. Do not remove this or written sector might not left updated. */
if (select()) {
deselect();
res = RES_OK;
}
break;
case GET_SECTOR_COUNT : /* Get number of sectors on the disk (DWORD) */
if ((send_cmd(CMD9, 0) == 0) && rcvr_datablock(csd, 16)) {
if ((csd[0] >> 6) == 1) { /* SDC ver 2.00 */
csize = csd[9] + ((WORD)csd[8] << 8) + 1;
*(DWORD*)buff = (DWORD)csize << 10;
} else { /* SDC ver 1.XX or MMC*/
n = (csd[5] & 15) + ((csd[10] & 128) >> 7) + ((csd[9] & 3) << 1) + 2;
csize = (csd[8] >> 6) + ((WORD)csd[7] << 2) + ((WORD)(csd[6] & 3) << 10) + 1;
*(DWORD*)buff = (DWORD)csize << (n - 9);
}
res = RES_OK;
}
break;
case GET_SECTOR_SIZE : /* Get R/W sector size (WORD) */
*(WORD*)buff = 512;
res = RES_OK;
break;
case GET_BLOCK_SIZE : /* Get erase block size in unit of sector (DWORD) */
if (CardType & CT_SD2) { /* SDv2? */
if (send_cmd(ACMD13, 0) == 0) { /* Read SD status */
rcvr_spi();
if (rcvr_datablock(csd, 16)) { /* Read partial block */
for (n = 64 - 16; n; n--) rcvr_spi(); /* Purge trailing data */
*(DWORD*)buff = 16UL << (csd[10] >> 4);
res = RES_OK;
}
}
} else { /* SDv1 or MMCv3 */
if ((send_cmd(CMD9, 0) == 0) && rcvr_datablock(csd, 16)) { /* Read CSD */
if (CardType & CT_SD1) { /* SDv1 */
*(DWORD*)buff = (((csd[10] & 63) << 1) + ((WORD)(csd[11] & 128) >> 7) + 1) << ((csd[13] >> 6) - 1);
} else { /* MMCv3 */
*(DWORD*)buff = ((WORD)((csd[10] & 124) >> 2) + 1) * (((csd[11] & 3) << 3) + ((csd[11] & 224) >> 5) + 1);
}
res = RES_OK;
}
}
break;
case MMC_GET_TYPE : /* Get card type flags (1 byte) */
*ptr = CardType;
res = RES_OK;
break;
case MMC_GET_CSD : /* Receive CSD as a data block (16 bytes) */
if (send_cmd(CMD9, 0) == 0 /* READ_CSD */
&& rcvr_datablock(ptr, 16))
res = RES_OK;
break;
case MMC_GET_CID : /* Receive CID as a data block (16 bytes) */
if (send_cmd(CMD10, 0) == 0 /* READ_CID */
&& rcvr_datablock(ptr, 16))
res = RES_OK;
break;
case MMC_GET_OCR : /* Receive OCR as an R3 resp (4 bytes) */
if (send_cmd(CMD58, 0) == 0) { /* READ_OCR */
for (n = 4; n; n--) *ptr++ = rcvr_spi();
res = RES_OK;
}
break;
case MMC_GET_SDSTAT : /* Receive SD statsu as a data block (64 bytes) */
if (send_cmd(ACMD13, 0) == 0) { /* SD_STATUS */
rcvr_spi();
if (rcvr_datablock(ptr, 64))
res = RES_OK;
}
break;
default:
res = RES_PARERR;
}
deselect();
}
return res;
}
#endif /* _USE_IOCTL != 0 */
/*-----------------------------------------------------------------------*/
/* Device Timer Interrupt Procedure (Platform dependent) */
/*-----------------------------------------------------------------------*/
/* This function must be called in period of 10ms */
void disk_timerproc (void)
{
static BYTE pv;
BYTE n, s;
n = Timer1; /* 100Hz decrement timer */
if (n) Timer1 = --n;
n = Timer2;
if (n) Timer2 = --n;
n = pv;
pv = SOCKPORT & (SOCKWP | SOCKINS); /* Sample socket switch */
if (n == pv) { /* Have contacts stabled? */
s = Stat;
if (pv & SOCKWP) /* WP is H (write protected) */
s |= STA_PROTECT;
else /* WP is L (write enabled) */
s &= ~STA_PROTECT;
if (pv & SOCKINS) /* INS = H (Socket empty) */
s |= (STA_NODISK | STA_NOINIT);
else /* INS = L (Card inserted) */
s &= ~STA_NODISK;
Stat = s;
}
}
DWORD get_fattime ()
{
return 0;
}

View File

@@ -0,0 +1,76 @@
/*-----------------------------------------------------------------------
/ Low level disk interface modlue include file R0.07 (C)ChaN, 2009
/-----------------------------------------------------------------------*/
#ifndef _DISKIO
#define _READONLY 0 /* 1: Read-only mode */
#define _USE_IOCTL 1
#include "integer.h"
/* Status of Disk Functions */
typedef BYTE DSTATUS;
/* Results of Disk Functions */
typedef enum {
RES_OK = 0, /* 0: Successful */
RES_ERROR, /* 1: R/W Error */
RES_WRPRT, /* 2: Write Protected */
RES_NOTRDY, /* 3: Not Ready */
RES_PARERR /* 4: Invalid Parameter */
} DRESULT;
/*---------------------------------------*/
/* Prototypes for disk control functions */
DSTATUS disk_initialize (BYTE);
DSTATUS disk_status (BYTE);
DRESULT disk_read (BYTE, BYTE*, DWORD, BYTE);
#if _READONLY == 0
DRESULT disk_write (BYTE, const BYTE*, DWORD, BYTE);
#endif
DRESULT disk_ioctl (BYTE, BYTE, void*);
/* Disk Status Bits (DSTATUS) */
#define STA_NOINIT 0x01 /* Drive not initialized */
#define STA_NODISK 0x02 /* No medium in the drive */
#define STA_PROTECT 0x04 /* Write protected */
/* Card type flags (CardType) */
#define CT_MMC 0x01
#define CT_SD1 0x02
#define CT_SD2 0x04
#define CT_SDC (CT_SD1|CT_SD2)
#define CT_BLOCK 0x08
/* Command code for disk_ioctrl() */
/* Generic command */
#define CTRL_SYNC 0 /* Mandatory for write functions */
#define GET_SECTOR_COUNT 1 /* Mandatory for only f_mkfs() */
#define GET_SECTOR_SIZE 2 /* Mandatory for multiple sector size cfg */
#define GET_BLOCK_SIZE 3 /* Mandatory for only f_mkfs() */
#define CTRL_POWER 4
#define CTRL_LOCK 5
#define CTRL_EJECT 6
/* MMC/SDC command */
#define MMC_GET_TYPE 10
#define MMC_GET_CSD 11
#define MMC_GET_CID 12
#define MMC_GET_OCR 13
#define MMC_GET_SDSTAT 14
/* ATA/CF command */
#define ATA_GET_REV 20
#define ATA_GET_MODEL 21
#define ATA_GET_SN 22
#define _DISKIO
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,613 @@
/*---------------------------------------------------------------------------/
/ FatFs - FAT file system module include file R0.08 (C)ChaN, 2010
/----------------------------------------------------------------------------/
/ FatFs module is a generic FAT file system module for small embedded systems.
/ This is a free software that opened for education, research and commercial
/ developments under license policy of following trems.
/
/ Copyright (C) 2010, ChaN, all right reserved.
/
/ * The FatFs module is a free software and there is NO WARRANTY.
/ * No restriction on use. You can use, modify and redistribute it for
/ personal, non-profit or commercial product UNDER YOUR RESPONSIBILITY.
/ * Redistributions of source code must retain the above copyright notice.
/
/----------------------------------------------------------------------------*/
#ifndef _FATFS
#define _FATFS 8085 /* Revision ID */
#ifdef __cplusplus
extern "C" {
#endif
#include "integer.h" /* Basic integer types */
#include "ffconf.h" /* FatFs configuration options */
#if _FATFS != _FFCONF
#error Wrong configuration file (ffconf.h).
#endif
/* DBCS code ranges and SBCS extend char conversion table */
#if _CODE_PAGE == 932 /* Japanese Shift-JIS */
#define _DF1S 0x81 /* DBC 1st byte range 1 start */
#define _DF1E 0x9F /* DBC 1st byte range 1 end */
#define _DF2S 0xE0 /* DBC 1st byte range 2 start */
#define _DF2E 0xFC /* DBC 1st byte range 2 end */
#define _DS1S 0x40 /* DBC 2nd byte range 1 start */
#define _DS1E 0x7E /* DBC 2nd byte range 1 end */
#define _DS2S 0x80 /* DBC 2nd byte range 2 start */
#define _DS2E 0xFC /* DBC 2nd byte range 2 end */
#elif _CODE_PAGE == 936 /* Simplified Chinese GBK */
#define _DF1S 0x81
#define _DF1E 0xFE
#define _DS1S 0x40
#define _DS1E 0x7E
#define _DS2S 0x80
#define _DS2E 0xFE
#elif _CODE_PAGE == 949 /* Korean */
#define _DF1S 0x81
#define _DF1E 0xFE
#define _DS1S 0x41
#define _DS1E 0x5A
#define _DS2S 0x61
#define _DS2E 0x7A
#define _DS3S 0x81
#define _DS3E 0xFE
#elif _CODE_PAGE == 950 /* Traditional Chinese Big5 */
#define _DF1S 0x81
#define _DF1E 0xFE
#define _DS1S 0x40
#define _DS1E 0x7E
#define _DS2S 0xA1
#define _DS2E 0xFE
#elif _CODE_PAGE == 437 /* U.S. (OEM) */
#define _DF1S 0
#define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F,0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
#elif _CODE_PAGE == 720 /* Arabic (OEM) */
#define _DF1S 0
#define _EXCVT {0x80,0x81,0x45,0x41,0x84,0x41,0x86,0x43,0x45,0x45,0x45,0x49,0x49,0x8D,0x8E,0x8F,0x90,0x92,0x92,0x93,0x94,0x95,0x49,0x49,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
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E6,0xE7,0xE7,0xE9,0xEA,0xEB,0xED,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
#elif _CODE_PAGE == 862 /* Hebrew (OEM) */
#define _DF1S 0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
#elif _CODE_PAGE == 866 /* Russian (OEM) */
#define _DF1S 0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0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,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
#elif _CODE_PAGE == 1250 /* Central Europe (Windows) */
#define _DF1S 0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x8D,0x8E,0x8F, \
0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xA3,0xB4,0xB5,0xB6,0xB7,0xB8,0xA5,0xAA,0xBB,0xBC,0xBD,0xBC,0xAF, \
0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xFF}
#elif _CODE_PAGE == 1251 /* Cyrillic (Windows) */
#define _DF1S 0
#define _EXCVT {0x80,0x81,0x82,0x82,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x80,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x8D,0x8E,0x8F, \
0xA0,0xA2,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0x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0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0x9F}
#elif _CODE_PAGE == 1253 /* Greek (Windows) */
#define _DF1S 0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xA2,0xB8,0xB9,0xBA, \
0xE0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xF2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xFB,0xBC,0xFD,0xBF,0xFF}
#elif _CODE_PAGE == 1254 /* Turkish (Windows) */
#define _DF1S 0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x9D,0x9E,0x9F, \
0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB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7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
#elif _CODE_PAGE == 1256 /* Arabic (Windows) */
#define _DF1S 0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x8C,0x9D,0x9E,0x9F, \
0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
0x41,0xE1,0x41,0xE3,0xE4,0xE5,0xE6,0x43,0x45,0x45,0x45,0x45,0xEC,0xED,0x49,0x49,0xF0,0xF1,0xF2,0xF3,0x4F,0xF5,0xF6,0xF7,0xF8,0x55,0xFA,0x55,0x55,0xFD,0xFE,0xFF}
#elif _CODE_PAGE == 1257 /* Baltic (Windows) */
#define _DF1S 0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xA8,0x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DD,0xFE,0x9F}
#elif _CODE_PAGE == 1 /* ASCII (for only non-LFN cfg) */
#define _DF1S 0
#else
#error Unknown code page
#endif
/* Definitions corresponds to volume management */
#if _MULTI_PARTITION /* Multiple partition configuration */
#define LD2PD(drv) (Drives[drv].pd) /* Get physical drive# */
#define LD2PT(drv) (Drives[drv].pt) /* Get partition# */
typedef struct {
BYTE pd; /* Physical drive# */
BYTE pt; /* Partition # (0-3) */
} PARTITION;
extern const PARTITION Drives[]; /* Logical drive# to physical location conversion table */
#else /* Single partition configuration */
#define LD2PD(drv) (drv) /* Physical drive# is equal to the logical drive# */
#define LD2PT(drv) 0 /* Always mounts the 1st partition */
#endif
/* Type of path name strings on FatFs API */
#if _LFN_UNICODE /* Unicode string */
#if !_USE_LFN
#error _LFN_UNICODE must be 0 in non-LFN cfg.
#endif
#ifndef _INC_TCHAR
typedef WCHAR TCHAR;
#define _T(x) L ## x
#define _TEXT(x) L ## x
#endif
#else /* ANSI/OEM string */
#ifndef _INC_TCHAR
typedef char TCHAR;
#define _T(x) x
#define _TEXT(x) x
#endif
#endif
/* Definitions corresponds to file shareing feature */
#if _FS_SHARE
#if _FS_READONLY
#error _FS_SHARE must be 0 on R/O cfg.
#endif
typedef struct {
DWORD clu; /* File ID 1, directory */
WORD idx; /* File ID 2, index in the directory */
WORD ctr; /* File open counter, 0:none, 0x01..0xFF:read open count, 0x100:in write open */
} FILESEM;
#endif
/* File system object structure (FATFS) */
typedef struct {
BYTE fs_type; /* FAT sub-type (0:Not mounted) */
BYTE drv; /* Physical drive number */
BYTE csize; /* Sectors per cluster (1,2,4...128) */
BYTE n_fats; /* Number of FAT copies (1,2) */
BYTE wflag; /* win[] dirty flag (1:must be written back) */
BYTE fsi_flag; /* fsinfo dirty flag (1:must be written back) */
WORD id; /* File system mount ID */
WORD n_rootdir; /* Number of root directory entries (FAT12/16) */
#if _MAX_SS != 512
WORD ssize; /* Bytes per sector (512,1024,2048,4096) */
#endif
#if _FS_REENTRANT
_SYNC_t sobj; /* Identifier of sync object */
#endif
#if !_FS_READONLY
DWORD last_clust; /* Last allocated cluster */
DWORD free_clust; /* Number of free clusters */
DWORD fsi_sector; /* fsinfo sector (FAT32) */
#endif
#if _FS_RPATH
DWORD cdir; /* Current directory start cluster (0:root) */
#endif
DWORD n_fatent; /* Number of FAT entries (= number of clusters + 2) */
DWORD fsize; /* Sectors per FAT */
DWORD fatbase; /* FAT start sector */
DWORD dirbase; /* Root directory start sector (FAT32:Cluster#) */
DWORD database; /* Data start sector */
DWORD winsect; /* Current sector appearing in the win[] */
BYTE win[_MAX_SS]; /* Disk access window for Directory, FAT (and Data on tiny cfg) */
#if _FS_SHARE
FILESEM flsem[_FS_SHARE]; /* File lock semaphores */
#endif
} FATFS;
/* File object structure (FIL) */
typedef struct {
FATFS* fs; /* Pointer to the owner file system object */
WORD id; /* Owner file system mount ID */
BYTE flag; /* File status flags */
BYTE pad1;
DWORD fptr; /* File read/write pointer */
DWORD fsize; /* File size */
DWORD org_clust; /* File start cluster (0 when fsize==0) */
DWORD curr_clust; /* Current cluster */
DWORD dsect; /* Current data sector */
#if !_FS_READONLY
DWORD dir_sect; /* Sector containing the directory entry */
BYTE* dir_ptr; /* Ponter to the directory entry in the window */
#endif
#if _USE_FASTSEEK
DWORD* cltbl; /* Pointer to the cluster link map table */
#endif
#if _FS_SHARE
UINT lockid; /* File lock ID */
#endif
#if !_FS_TINY
BYTE buf[_MAX_SS]; /* File data read/write buffer */
#endif
} FIL;
/* Directory object structure (DIR) */
typedef struct {
FATFS* fs; /* Pointer to the owner file system object */
WORD id; /* Owner file system mount ID */
WORD index; /* Current read/write index number */
DWORD sclust; /* Table start cluster (0:Root dir) */
DWORD clust; /* Current cluster */
DWORD sect; /* Current sector */
BYTE* dir; /* Pointer to the current SFN entry in the win[] */
BYTE* fn; /* Pointer to the SFN (in/out) {file[8],ext[3],status[1]} */
#if _USE_LFN
WCHAR* lfn; /* Pointer to the LFN working buffer */
WORD lfn_idx; /* Last matched LFN index number (0xFFFF:No LFN) */
#endif
} DIR;
/* File status structure (FILINFO) */
typedef struct {
DWORD fsize; /* File size */
WORD fdate; /* Last modified date */
WORD ftime; /* Last modified time */
BYTE fattrib; /* Attribute */
TCHAR fname[13]; /* Short file name (8.3 format) */
#if _USE_LFN
TCHAR* lfname; /* Pointer to the LFN buffer */
int lfsize; /* Size of LFN buffer [chrs] */
#endif
} FILINFO;
/* File function return code (FRESULT) */
typedef enum {
FR_OK = 0, /* (0) Succeeded */
FR_DISK_ERR, /* (1) A hard error occured in the low level disk I/O layer */
FR_INT_ERR, /* (2) Assertion failed */
FR_NOT_READY, /* (3) The physical drive cannot work */
FR_NO_FILE, /* (4) Could not find the file */
FR_NO_PATH, /* (5) Could not find the path */
FR_INVALID_NAME, /* (6) The path name format is invalid */
FR_DENIED, /* (7) Acces denied due to prohibited access or directory full */
FR_EXIST, /* (8) Acces denied due to prohibited access */
FR_INVALID_OBJECT, /* (9) The file/directory object is invalid */
FR_WRITE_PROTECTED, /* (10) The physical drive is write protected */
FR_INVALID_DRIVE, /* (11) The logical drive number is invalid */
FR_NOT_ENABLED, /* (12) The volume has no work area */
FR_NO_FILESYSTEM, /* (13) There is no valid FAT volume on the physical drive */
FR_MKFS_ABORTED, /* (14) The f_mkfs() aborted due to any parameter error */
FR_TIMEOUT, /* (15) Could not get a grant to access the volume within defined period */
FR_LOCKED, /* (16) The operation is rejected according to the file shareing policy */
FR_NOT_ENOUGH_CORE, /* (17) LFN working buffer could not be allocated */
FR_TOO_MANY_OPEN_FILES /* (18) Number of open files > _FS_SHARE */
} FRESULT;
/*--------------------------------------------------------------*/
/* FatFs module application interface */
FRESULT f_mount (BYTE, FATFS*); /* Mount/Unmount a logical drive */
FRESULT f_open (FIL*, const TCHAR*, BYTE); /* Open or create a file */
FRESULT f_read (FIL*, void*, UINT, UINT*); /* Read data from a file */
FRESULT f_lseek (FIL*, DWORD); /* Move file pointer of a file object */
FRESULT f_close (FIL*); /* Close an open file object */
FRESULT f_opendir (DIR*, const TCHAR*); /* Open an existing directory */
FRESULT f_readdir (DIR*, FILINFO*); /* Read a directory item */
FRESULT f_stat (const TCHAR*, FILINFO*); /* Get file status */
#if !_FS_READONLY
FRESULT f_write (FIL*, const void*, UINT, UINT*); /* Write data to a file */
FRESULT f_getfree (const TCHAR*, DWORD*, FATFS**); /* Get number of free clusters on the drive */
FRESULT f_truncate (FIL*); /* Truncate file */
FRESULT f_sync (FIL*); /* Flush cached data of a writing file */
FRESULT f_unlink (const TCHAR*); /* Delete an existing file or directory */
FRESULT f_mkdir (const TCHAR*); /* Create a new directory */
FRESULT f_chmod (const TCHAR*, BYTE, BYTE); /* Change attriburte of the file/dir */
FRESULT f_utime (const TCHAR*, const FILINFO*); /* Change timestamp of the file/dir */
FRESULT f_rename (const TCHAR*, const TCHAR*); /* Rename/Move a file or directory */
#endif
#if _USE_FORWARD
FRESULT f_forward (FIL*, UINT(*)(const BYTE*,UINT), UINT, UINT*); /* Forward data to the stream */
#endif
#if _USE_MKFS
FRESULT f_mkfs (BYTE, BYTE, UINT); /* Create a file system on the drive */
#endif
#if _FS_RPATH
FRESULT f_chdir (const TCHAR*); /* Change current directory */
FRESULT f_chdrive (BYTE); /* Change current drive */
#endif
#if _USE_STRFUNC
int f_putc (TCHAR, FIL*); /* Put a character to the file */
int f_puts (const TCHAR*, FIL*); /* Put a string to the file */
int f_printf (FIL*, const TCHAR*, ...); /* Put a formatted string to the file */
TCHAR* f_gets (TCHAR*, int, FIL*); /* Get a string from the file */
#define f_eof(fp) (((fp)->fptr == (fp)->fsize) ? 1 : 0)
#define f_error(fp) (((fp)->flag & FA__ERROR) ? 1 : 0)
#ifndef EOF
#define EOF (-1)
#endif
#endif
/*--------------------------------------------------------------*/
/* Additional user defined functions */
/* RTC function */
#if !_FS_READONLY
DWORD get_fattime (void);
#endif
/* Unicode support functions */
#if _USE_LFN /* Unicode - OEM code conversion */
WCHAR ff_convert (WCHAR, UINT); /* OEM-Unicode bidirectional conversion */
WCHAR ff_wtoupper (WCHAR); /* Unicode upper-case conversion */
#if _USE_LFN == 3 /* Memory functions */
void* ff_memalloc (UINT); /* Allocate memory block */
void ff_memfree (void*); /* Free memory block */
#endif
#endif
/* Sync functions */
#if _FS_REENTRANT
int ff_cre_syncobj (BYTE, _SYNC_t*);/* Create a sync object */
int ff_del_syncobj (_SYNC_t); /* Delete a sync object */
int ff_req_grant (_SYNC_t); /* Lock sync object */
void ff_rel_grant (_SYNC_t); /* Unlock sync object */
#endif
/*--------------------------------------------------------------*/
/* Flags and offset address */
/* File access control and file status flags (FIL.flag) */
#define FA_READ 0x01
#define FA_OPEN_EXISTING 0x00
#define FA__ERROR 0x80
#if !_FS_READONLY
#define FA_WRITE 0x02
#define FA_CREATE_NEW 0x04
#define FA_CREATE_ALWAYS 0x08
#define FA_OPEN_ALWAYS 0x10
#define FA__WRITTEN 0x20
#define FA__DIRTY 0x40
#endif
/* FAT sub type (FATFS.fs_type) */
#define FS_FAT12 1
#define FS_FAT16 2
#define FS_FAT32 3
/* File attribute bits for directory entry */
#define AM_RDO 0x01 /* Read only */
#define AM_HID 0x02 /* Hidden */
#define AM_SYS 0x04 /* System */
#define AM_VOL 0x08 /* Volume label */
#define AM_LFN 0x0F /* LFN entry */
#define AM_DIR 0x10 /* Directory */
#define AM_ARC 0x20 /* Archive */
#define AM_MASK 0x3F /* Mask of defined bits */
/* Fast seek function */
#define CREATE_LINKMAP 0xFFFFFFFF
/* FatFs refers the members in the FAT structures with byte offset instead of
/ structure member because there are incompatibility of the packing option
/ between various compilers. */
#define BS_jmpBoot 0
#define BS_OEMName 3
#define BPB_BytsPerSec 11
#define BPB_SecPerClus 13
#define BPB_RsvdSecCnt 14
#define BPB_NumFATs 16
#define BPB_RootEntCnt 17
#define BPB_TotSec16 19
#define BPB_Media 21
#define BPB_FATSz16 22
#define BPB_SecPerTrk 24
#define BPB_NumHeads 26
#define BPB_HiddSec 28
#define BPB_TotSec32 32
#define BS_55AA 510
#define BS_DrvNum 36
#define BS_BootSig 38
#define BS_VolID 39
#define BS_VolLab 43
#define BS_FilSysType 54
#define BPB_FATSz32 36
#define BPB_ExtFlags 40
#define BPB_FSVer 42
#define BPB_RootClus 44
#define BPB_FSInfo 48
#define BPB_BkBootSec 50
#define BS_DrvNum32 64
#define BS_BootSig32 66
#define BS_VolID32 67
#define BS_VolLab32 71
#define BS_FilSysType32 82
#define FSI_LeadSig 0
#define FSI_StrucSig 484
#define FSI_Free_Count 488
#define FSI_Nxt_Free 492
#define MBR_Table 446
#define DIR_Name 0
#define DIR_Attr 11
#define DIR_NTres 12
#define DIR_CrtTime 14
#define DIR_CrtDate 16
#define DIR_FstClusHI 20
#define DIR_WrtTime 22
#define DIR_WrtDate 24
#define DIR_FstClusLO 26
#define DIR_FileSize 28
#define LDIR_Ord 0
#define LDIR_Attr 11
#define LDIR_Type 12
#define LDIR_Chksum 13
#define LDIR_FstClusLO 26
/*--------------------------------*/
/* Multi-byte word access macros */
#if _WORD_ACCESS == 1 /* Enable word access to the FAT structure */
#define LD_WORD(ptr) (WORD)(*(WORD*)(BYTE*)(ptr))
#define LD_DWORD(ptr) (DWORD)(*(DWORD*)(BYTE*)(ptr))
#define ST_WORD(ptr,val) *(WORD*)(BYTE*)(ptr)=(WORD)(val)
#define ST_DWORD(ptr,val) *(DWORD*)(BYTE*)(ptr)=(DWORD)(val)
#else /* Use byte-by-byte access to the FAT structure */
#define LD_WORD(ptr) (WORD)(((WORD)*(BYTE*)((ptr)+1)<<8)|(WORD)*(BYTE*)(ptr))
#define LD_DWORD(ptr) (DWORD)(((DWORD)*(BYTE*)((ptr)+3)<<24)|((DWORD)*(BYTE*)((ptr)+2)<<16)|((WORD)*(BYTE*)((ptr)+1)<<8)|*(BYTE*)(ptr))
#define ST_WORD(ptr,val) *(BYTE*)(ptr)=(BYTE)(val); *(BYTE*)((ptr)+1)=(BYTE)((WORD)(val)>>8)
#define ST_DWORD(ptr,val) *(BYTE*)(ptr)=(BYTE)(val); *(BYTE*)((ptr)+1)=(BYTE)((WORD)(val)>>8); *(BYTE*)((ptr)+2)=(BYTE)((DWORD)(val)>>16); *(BYTE*)((ptr)+3)=(BYTE)((DWORD)(val)>>24)
#endif
#ifdef __cplusplus
}
#endif
#endif /* _FATFS */

View File

@@ -0,0 +1,179 @@
/*---------------------------------------------------------------------------/
/ FatFs - FAT file system module configuration file R0.08 (C)ChaN, 2010
/----------------------------------------------------------------------------/
/
/ CAUTION! Do not forget to make clean the project after any changes to
/ the configuration options.
/
/----------------------------------------------------------------------------*/
#ifndef _FFCONF
#define _FFCONF 8085 /* Revision ID */
/*---------------------------------------------------------------------------/
/ Function and Buffer Configurations
/----------------------------------------------------------------------------*/
#define _FS_TINY 1 /* 0 or 1 */
/* When _FS_TINY is set to 1, FatFs uses the sector buffer in the file system
/ object instead of the sector buffer in the individual file object for file
/ data transfer. This reduces memory consumption 512 bytes each file object. */
#define _FS_READONLY 0 /* 0 or 1 */
/* Setting _FS_READONLY to 1 defines read only configuration. This removes
/ writing functions, f_write, f_sync, f_unlink, f_mkdir, f_chmod, f_rename,
/ f_truncate and useless f_getfree. */
#define _FS_MINIMIZE 0 /* 0, 1, 2 or 3 */
/* The _FS_MINIMIZE option defines minimization level to remove some functions.
/
/ 0: Full function.
/ 1: f_stat, f_getfree, f_unlink, f_mkdir, f_chmod, f_truncate and f_rename
/ are removed.
/ 2: f_opendir and f_readdir are removed in addition to level 1.
/ 3: f_lseek is removed in addition to level 2. */
#define _USE_STRFUNC 0 /* 0, 1 or 2 */
/* To enable string functions, set _USE_STRFUNC to 1 or 2. */
#define _USE_MKFS 1 /* 0 or 1 */
/* To enable f_mkfs function, set _USE_MKFS to 1 and set _FS_READONLY to 0 */
#define _USE_FORWARD 0 /* 0 or 1 */
/* To enable f_forward function, set _USE_FORWARD to 1 and set _FS_TINY to 1. */
#define _USE_FASTSEEK 0 /* 0 or 1 */
/* To enable f_fastseek function, set _USE_FASTSEEK to 1. */
/*---------------------------------------------------------------------------/
/ Locale and Namespace Configurations
/----------------------------------------------------------------------------*/
#define _CODE_PAGE 1
/* The _CODE_PAGE specifies the OEM code page to be used on the target system.
/ Incorrect setting of the code page can cause a file open failure.
/
/ 932 - Japanese Shift-JIS (DBCS, OEM, Windows)
/ 936 - Simplified Chinese GBK (DBCS, OEM, Windows)
/ 949 - Korean (DBCS, OEM, Windows)
/ 950 - Traditional Chinese Big5 (DBCS, OEM, Windows)
/ 1250 - Central Europe (Windows)
/ 1251 - Cyrillic (Windows)
/ 1252 - Latin 1 (Windows)
/ 1253 - Greek (Windows)
/ 1254 - Turkish (Windows)
/ 1255 - Hebrew (Windows)
/ 1256 - Arabic (Windows)
/ 1257 - Baltic (Windows)
/ 1258 - Vietnam (OEM, Windows)
/ 437 - U.S. (OEM)
/ 720 - Arabic (OEM)
/ 737 - Greek (OEM)
/ 775 - Baltic (OEM)
/ 850 - Multilingual Latin 1 (OEM)
/ 858 - Multilingual Latin 1 + Euro (OEM)
/ 852 - Latin 2 (OEM)
/ 855 - Cyrillic (OEM)
/ 866 - Russian (OEM)
/ 857 - Turkish (OEM)
/ 862 - Hebrew (OEM)
/ 874 - Thai (OEM, Windows)
/ 1 - ASCII only (Valid for non LFN cfg.)
*/
#define _USE_LFN 0 /* 0 to 3 */
#define _MAX_LFN 128 /* Maximum LFN length to handle (12 to 255) */
/* The _USE_LFN option switches the LFN support.
/
/ 0: Disable LFN. _MAX_LFN and _LFN_UNICODE have no effect.
/ 1: Enable LFN with static working buffer on the bss. NOT REENTRANT.
/ 2: Enable LFN with dynamic working buffer on the STACK.
/ 3: Enable LFN with dynamic working buffer on the HEAP.
/
/ The LFN working buffer occupies (_MAX_LFN + 1) * 2 bytes. When enable LFN,
/ Unicode handling functions ff_convert() and ff_wtoupper() must be added
/ to the project. When enable to use heap, memory control functions
/ ff_memalloc() and ff_memfree() must be added to the project. */
#define _LFN_UNICODE 0 /* 0 or 1 */
/* To switch the character code set on FatFs API to Unicode,
/ enable LFN feature and set _LFN_UNICODE to 1.
*/
#define _FS_RPATH 1 /* 0 or 1 */
/* When _FS_RPATH is set to 1, relative path feature is enabled and f_chdir,
/ f_chdrive function are available.
/ Note that output of the f_readdir fnction is affected by this option. */
/*---------------------------------------------------------------------------/
/ Physical Drive Configurations
/----------------------------------------------------------------------------*/
#define _DRIVES 2
/* Number of volumes (logical drives) to be used. */
#define _MAX_SS 512 /* 512, 1024, 2048 or 4096 */
/* Maximum sector size to be handled.
/ Always set 512 for memory card and hard disk but a larger value may be
/ required for floppy disk (512/1024) and optical disk (512/2048).
/ When _MAX_SS is larger than 512, GET_SECTOR_SIZE command must be implememted
/ to the disk_ioctl function. */
#define _MULTI_PARTITION 0 /* 0 or 1 */
/* When _MULTI_PARTITION is set to 0, each volume is bound to the same physical
/ drive number and can mount only first primaly partition. When it is set to 1,
/ each volume is tied to the partitions listed in Drives[]. */
/*---------------------------------------------------------------------------/
/ System Configurations
/----------------------------------------------------------------------------*/
#define _WORD_ACCESS 1 /* 0 or 1 */
/* Set 0 first and it is always compatible with all platforms. The _WORD_ACCESS
/ option defines which access method is used to the word data on the FAT volume.
/
/ 0: Byte-by-byte access.
/ 1: Word access. Do not choose this unless following condition is met.
/
/ When the byte order on the memory is big-endian or address miss-aligned word
/ access results incorrect behavior, the _WORD_ACCESS must be set to 0.
/ If it is not the case, the value can also be set to 1 to improve the
/ performance and code size. */
#define _FS_REENTRANT 0 /* 0 or 1 */
#define _FS_TIMEOUT 1000 /* Timeout period in unit of time ticks */
#define _SYNC_t HANDLE /* O/S dependent type of sync object. e.g. HANDLE, OS_EVENT*, ID and etc.. */
/* The _FS_REENTRANT option switches the reentrancy of the FatFs module.
/
/ 0: Disable reentrancy. _SYNC_t and _FS_TIMEOUT have no effect.
/ 1: Enable reentrancy. Also user provided synchronization handlers,
/ ff_req_grant, ff_rel_grant, ff_del_syncobj and ff_cre_syncobj
/ function must be added to the project. */
#define _FS_SHARE 0 /* 0 or >=1 */
/* To enable file shareing feature, set _FS_SHARE to >= 1 and also user
provided memory handlers, ff_memalloc and ff_memfree function must be
added to the project. The value defines number of files can be opened
per volume. */
#endif /* _FFCONF */

View File

@@ -0,0 +1,37 @@
/*-------------------------------------------*/
/* Integer type definitions for FatFs module */
/*-------------------------------------------*/
#ifndef _INTEGER
#define _INTEGER
#ifdef _WIN32 /* FatFs development platform */
#include <windows.h>
#include <tchar.h>
#else /* Embedded platform */
/* These types must be 16-bit, 32-bit or larger integer */
typedef int INT;
typedef unsigned int UINT;
/* These types must be 8-bit integer */
typedef char CHAR;
typedef unsigned char UCHAR;
typedef unsigned char BYTE;
/* These types must be 16-bit integer */
typedef short SHORT;
typedef unsigned short USHORT;
typedef unsigned short WORD;
typedef unsigned short WCHAR;
/* These types must be 32-bit integer */
typedef long LONG;
typedef unsigned long ULONG;
typedef unsigned long DWORD;
#endif
#endif

View File

@@ -0,0 +1,296 @@
/**
@file main.c
@brief Lab 3 Starter Code
@version .01
@mainpage Lab 3 Starter Code
@section intro Code Overview
@section hw Hardware Pin Out
Port A:
A0 - A3 : Push Buttons
A4 - A7 : Slide Switches
Port B:
B0 - B3 : SPI (SD Card)
B4 : Nothing
B5 : Audio Out
B6 : Red Enable
B7 : Green Enable
Port C:
C0 - C7 : LED Array (Row)
Port D:
D0 - D1 : Nothing
D2 : Serial RX
D3 : Serial TX
D4 - D7 : Nothing
Port E:
E0 - E2 : LED Array (Column)
E3 : USB (UID)
E4 - E5 : Nothing
E6 : Relay
E7 : Nothing
Port F:
F0 : ADC Channel 0
F1 : ADC Channel 1
F2 : ADC Channel 2
F3 : ADC Channel 3
F4 : ADC Channel 4 (Audio In)
F5 : ADC Channel 5 (Accel X Axis)
F6 : ADC Channel 6 (Accel Y Axis)
F7 : ADC Channel 7 (Accel Z Axis (if installed))
*/
/** Includes */
#include <avr/io.h>
#include <util/delay.h>
/** Constants */
#define F_CPU 1000000UL
#define DEBUG 1
#ifdef DEBUG == 1
#define SENDSPEED 3 //If less than .12, there are problems
#endif
/** Global Variables */
/** Functions */
#ifdef DEBUG == 1
/** This function needs to setup the variables used by the UART to enable the UART and tramsmit at 9600bps. This
function should always return 0. Remember, by defualt the Wunderboard runs at 1mHz for its system clock.*/
unsigned char InitializeUART (){
unsigned char baud = ((F_CPU/(9600*8UL))-1);
/* Set baud rate */
UBRR1H = (baud >> 8);
UBRR1L = baud;
/* Set the U2X1 bit */
UCSR1A = (1 << U2X1);
/* Enable transmitter */
UCSR1B = (1 << TXEN1 | 1 << RXEN1);
/* Set frame format: 8data, 1stop bit */
UCSR1C = (3 << UCSZ10);
return 0;
}
/** This function needs to write a single byte to the UART. It must check that the UART is ready for a new byte
and return a 1 if the byte was not sent.
@param [in] data This is the data byte to be sent.
@return The function returns a 1 or error and 0 on successful completion.*/
unsigned char SendByteUART (unsigned char data){
/*
** Checks the buffer empty bit so that data can either be placed in the buffer
** or else reuturn a 1
*/
if((UCSR1A & (1 << UDRE1)) == (1 << UDRE1)){
UDR1 = data;
_delay_ms(SENDSPEED); //Places data into the UDR1 8-bit data buffer
}else {
return 1;
}
return 0;
}
/** This function needs to writes a string to the UART. It must check that the UART is ready for a new byte and
return a 1 if the string was not sent.
@param [in] data This is a pointer to the data to be sent.
@return The function returns a 1 or error and 0 on successful completion.*/
unsigned char SendStringUART (unsigned char *data){
for (int loop = 0 ; data[loop] != '\0'; loop++){
unsigned char bytereturn; //Storage for return value of SendByteUART
/* Sends the current byte based on the loop umber to SendByte */
bytereturn = SendByteUART(data[loop]);
/* Stops sending if SendByteUART had an error */
if(bytereturn == 1){
return 1;
}
}
return 0;
}
unsigned char GetByteUART(){
if (UCSR1A & (1 << RXC1)){
return(UDR1);
} else{
return(-1);
}
}
#endif
/** The clearArray() function turns off all LEDS on the Wunderboard array. It accepts no inputs and returns nothing*/
void clearArray(void){
PORTC = 0x00;
PORTB |= (1 << PB6) | (1 << PB7); /** Enable latches*/
PORTB &= ~((1 << PB6) | (1 << PB7)); /** Disable latches*/
}
/** The initialize() function initializes all of the Data Direction Registers for the Wunderboard. Before making changes to DDRx registers, ensure that you have read the peripherals section of the Wunderboard user guide.*/
void initialize(void){
/** Port A is the switches and buttons. They should always be inputs. ( 0 = Input and 1 = Output )*/
DDRA=0b00000000;
/** Port B has the LED Array color control, SD card, and audio-out on it. Leave DDRB alone. ( 0 = Input and 1 = Output )*/
DDRB=0b11000111;
/** Port C is for the 'row' of the LED array. They should always be outputs. ( 0 = Input and 1 = Output )*/
DDRC=0b11111111;
/** Port D has the Serial on it. Leave DDRB alone. ( 0 = Input and 1 = Output )*/
DDRD=0b00000000;
/** Port E has the LED Array Column control out on it. Leave DDRE alone. ( 0 = Input and 1 = Output )*/
DDRE=0b00000111;
/** Port F has the accelerometer and audio-in on it. Leave DDRF alone. ( 0 = Input and 1 = Output )*/
DDRF=0b00000000;
}
unsigned char read_adc(uint8_t channel){
unsigned char test;
ADMUX = 0x60 | channel; // Set the channel to the one we want
ADCSRA = 0b11000110; // Start a new sample.
while ((ADCSRA & 0b00010000) == 0 ); // Wait for a Valid Sample
ADCSRA |= 0b00010000; // Tell ADC you have the sample you want.
ADCSRA |= 0b01000000; // Start a new sample.
while ((ADCSRA & 0b00010000) == 0 ); // Wait for a Valid Sample
ADCSRA |= 0b00010000; // Tell ADC you have the sample you want.
test = ADCH;
ADCSRA = 0x00; // Disable the ADC
return (test);
}
/** This function needs to setup the variables used by TIMER0 Compare Match (CTC) mode with
a base clock frequency of clk/1024. This function should return a 1 if it fails and a 0 if it
does not. Remember, by default the Wunderboard runs at 1mHz for its system clock.
@return This function returns a 1 is unsuccessful, else return 0.*/
unsigned char initializeTIMER0(void){
/* Set the CTC mode */
TCCR0A = (1 << WGM01);
/* Set the Clock Frequency */
TCCR0B = ((1 << CS02) | (1 << CS00));
/* Set initial count value */
OCR0A = 0;
}
/** This function checks if TIMER0 has elapsed.
@return This function should return a 1 if the timer has elapsed, else return 0*/
unsigned char checkTIMER0(void){
if((TIFR0 & (1 << OCF0A)) == (1 << OCF0A)){
TIFR0 |= (1 << OCF0A);
return 1;
}else {
return 0;
}
}
/** This function takes two values, clock and count. The value of count should be copied into OCR0A and the value of clock should be used to set CS02:0. The TCNT0 variable should also be reset to 0 so that the new timer rate starts from 0.
@param [in] clock Insert Comment
@param [in] count Insert Comment
@return The function returns a 1 or error and 0 on successful completion.*/
unsigned char setTIMER0(unsigned char clock, unsigned char count){
if(clock > 7){
return 1;
}
TCCR0B &= 0b11111000; //Zeros out last three bits
TCCR0B |= clock;
OCR0A = count;
TCNT0 = 0;
return 0;
}
/** Main Function */
int main (void){
enum states {
setup,
idle,
running
} state = setup;
unsigned char numelapsed = 0;
unsigned char debug;
unsigned char received;
unsigned char send[150];
unsigned char adcreturn1;
unsigned char adcreturn2;
while(1){
switch(state){
case setup:
initialize();
initializeTIMER0();
InitializeUART();
clearArray();
setTIMER0(5, 121);
PORTB = 0b11000000;
state = idle;
sprintf(send, "Initialized...\n");
SendStringUART(send);
break;
case idle:
if(debug != 1){
sprintf(send, "Idling...\n");
SendStringUART(send);
debug = 1;
}
received = GetByteUART();
if (received == 's'){
state = running;
debug = 0;
break;
}
break;
case running:
received = GetByteUART();
adcreturn1 = read_adc(5);
adcreturn2 = read_adc(6);
if (received == 's'){
state = idle;
}
if (checkTIMER0() == 1){
if(numelapsed == 3){
PORTC = ~PORTC;
numelapsed = 0;
sprintf(send, "X value: %d\tY value: %d\n", adcreturn1, adcreturn2);
SendStringUART(send);
}else {
numelapsed++;
}
}
break;
}
}
}

View File

@@ -0,0 +1,337 @@
#----------------------------------------------------------------------------
# Wunderboard Makefile Template written by Dan Albert
#----------------------------------------------------------------------------
#
# make all = Make software.
#
# make clean = Clean out built project files.
#
# make filename.s = Just compile filename.c into the assembler code only.
#
# To rebuild project do "make clean" then "make all".
#----------------------------------------------------------------------------
# Target file name.
TARGET = main
# List C source files here.
SRC = $(TARGET).c \
ff.c \
diskio.c \
# MCU name, you MUST set this to match the board you are using
# type "make clean" after changing this, so all files will be rebuilt
MCU = at90usb646
# Detect platform
UNAME = $(shell uname)
ifeq ($(UNAME),Linux)
ENV=unix
endif
ifeq ($(UNAME),Darwin)
ENV=unix
endif
ifndef ENV
ENV=windows
endif
ifeq ($(ENV),unix)
PROGRAM = dfu-programmer
PROGRAMFLAGS = $(MCU)
ERASE = erase
FLASH = flash "$(TARGET).hex"
START = start
else
PROGRAM = "batchisp.exe"
PROGRAMFLAGS = -device at90usb646 -hardware USB
ERASE = -operation erase F
FLASH = -operation loadbuffer "$(TARGET).hex" program verify
START = -operation start noreset 0
endif
# Processor frequency.
# Normally the first thing your program should do is set the clock prescaler,
# so your program will run at the correct speed. You should also set this
# variable to same clock speed. The _delay_ms() macro uses this, and many
# examples use this variable to calculate timings. Do not add a "UL" here.
F_CPU = 1000000
# Output format. (can be srec, ihex, binary)
FORMAT = ihex
# Object files directory
# To put object files in current directory, use a dot (.), do NOT make
# this an empty or blank macro!
OBJDIR = obj
# 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
# List any extra directories to look for include files here.
# Each directory must be seperated by a space.
# Use forward slashes for directory separators.
# For a directory that has spaces, enclose it in quotes.
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 for C sources
CDEFS = -DF_CPU=$(F_CPU)UL
#---------------- Compiler Options C ----------------
# -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 += $(CDEFS)
CFLAGS += -O$(OPT)
CFLAGS += -funsigned-char
CFLAGS += -funsigned-bitfields
CFLAGS += -ffunction-sections
CFLAGS += -fpack-struct
CFLAGS += -fshort-enums
CFLAGS += -Wall
CFLAGS += -Wstrict-prototypes
#CFLAGS += -mshort-calls
#CFLAGS += -fno-unit-at-a-time
#CFLAGS += -Wundef
#CFLAGS += -Wunreachable-code
#CFLAGS += -Wsign-compare
CFLAGS += -Wa,-adhlns=$(<:%.c=$(OBJDIR)/%.lst)
CFLAGS += $(patsubst %,-I%,$(EXTRAINCDIRS))
CFLAGS += $(CSTANDARD)
#---------------- Library Options ----------------
# 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
# If this is left blank, then it will use the Standard printf version.
PRINTF_LIB =
#PRINTF_LIB = $(PRINTF_LIB_MIN)
#PRINTF_LIB = $(PRINTF_LIB_FLOAT)
# 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
# If this is left blank, then it will use the Standard scanf version.
SCANF_LIB =
#SCANF_LIB = $(SCANF_LIB_MIN)
#SCANF_LIB = $(SCANF_LIB_FLOAT)
MATH_LIB = -lm
# List any extra directories to look for libraries here.
# Each directory must be seperated by a space.
# Use forward slashes for directory separators.
# For a directory that has spaces, enclose it in quotes.
EXTRALIBDIRS =
#---------------- Linker Options ----------------
# -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 += -Wl,--relax
LDFLAGS += -Wl,--gc-sections
LDFLAGS += $(patsubst %,-L%,$(EXTRALIBDIRS))
LDFLAGS += $(PRINTF_LIB) $(SCANF_LIB) $(MATH_LIB)
#LDFLAGS += -T linker_script.x
#============================================================================
# Define programs and commands.
SHELL = sh
CC = avr-gcc
OBJCOPY = avr-objcopy
OBJDUMP = avr-objdump
SIZE = avr-size
AR = avr-ar rcs
NM = avr-nm
REMOVE = rm -f
REMOVEDIR = rm -rf
COPY = cp
WINSHELL = cmd
# 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_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 C:
MSG_ASSEMBLING = Assembling:
MSG_CLEANING = Cleaning project:
MSG_CREATING_LIBRARY = Creating library:
# Define all object files.
OBJ = $(SRC:%.c=$(OBJDIR)/%.o)
# Define all listing files.
LST = $(SRC:%.c=$(OBJDIR)/%.lst)
# Compiler flags to generate dependency files.
GENDEPFLAGS = -MMD -MP -MF .dep/$(@F).d
# Combine all necessary flags and optional flags.
# Add target processor to flags.
ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) $(GENDEPFLAGS)
# Default target.
all: begin gccversion sizebefore build sizeafter end
# Change the build target to build a HEX file or a library.
build: elf hex eep lss sym
#build: lib
elf: $(TARGET).elf
hex: $(TARGET).hex
eep: $(TARGET).eep
lss: $(TARGET).lss
sym: $(TARGET).sym
LIBNAME=lib$(TARGET).a
lib: $(LIBNAME)
# 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)
end:
@echo $(MSG_END)
@echo
# Display size of file.
HEXSIZE = $(SIZE) --target=$(FORMAT) $(TARGET).hex
ELFSIZE = $(SIZE) --mcu=$(MCU) --format=avr $(TARGET).elf
sizebefore:
@if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_BEFORE); $(ELFSIZE); \
2>/dev/null; echo; fi
sizeafter:
@if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_AFTER); $(ELFSIZE); \
2>/dev/null; echo; fi
# Display compiler version information.
gccversion :
@$(CC) --version
# Create final output files (.hex, .eep) from ELF output file.
%.hex: %.elf
@echo
@echo $(MSG_FLASH) $@
$(OBJCOPY) -O $(FORMAT) -R .eeprom -R .fuse -R .lock -R .signature $< $@
%.eep: %.elf
@echo
@echo $(MSG_EEPROM) $@
-$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \
--change-section-lma .eeprom=0 --no-change-warnings -O $(FORMAT) $< $@ || exit 0
# Create extended listing file from ELF output file.
%.lss: %.elf
@echo
@echo $(MSG_EXTENDED_LISTING) $@
$(OBJDUMP) -h -S -z $< > $@
# Create a symbol table from ELF output file.
%.sym: %.elf
@echo
@echo $(MSG_SYMBOL_TABLE) $@
$(NM) -n $< > $@
# Create library from object files.
.SECONDARY : $(TARGET).a
.PRECIOUS : $(OBJ)
%.a: $(OBJ)
@echo
@echo $(MSG_CREATING_LIBRARY) $@
$(AR) $@ $(OBJ)
# Link: create ELF output file from object files.
.SECONDARY : $(TARGET).elf
.PRECIOUS : $(OBJ)
%.elf: $(OBJ)
@echo
@echo $(MSG_LINKING) $@
$(CC) $(ALL_CFLAGS) $^ --output $@ $(LDFLAGS)
# Compile: create object files from C source files.
$(OBJDIR)/%.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 $@
## Program
.PHONY: program
program: all
$(PROGRAM) $(PROGRAMFLAGS) $(ERASE)
$(PROGRAM) $(PROGRAMFLAGS) $(FLASH)
$(PROGRAM) $(PROGRAMFLAGS) $(START)
doxygen:
doxygen
# Target: clean project.
clean: begin clean_list end
clean_list :
@echo
@echo $(MSG_CLEANING)
$(REMOVE) $(TARGET).hex
$(REMOVE) $(TARGET).eep
$(REMOVE) $(TARGET).elf
$(REMOVE) $(TARGET).map
$(REMOVE) $(TARGET).sym
$(REMOVE) $(TARGET).lss
$(REMOVE) $(SRC:%.c=$(OBJDIR)/%.o)
$(REMOVE) $(SRC:%.c=$(OBJDIR)/%.lst)
$(REMOVE) $(SRC:.c=.s)
$(REMOVE) $(SRC:.c=.d)
$(REMOVEDIR) .dep
$(REMOVEDIR) $(OBJDIR)
# Create object files directory
$(shell mkdir $(OBJDIR) 2>/dev/null)
# 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 \
clean clean_list

View File

@@ -0,0 +1,623 @@
/*-----------------------------------------------------------------------*/
/* MMCv3/SDv1/SDv2 (in SPI mode) control module (C)ChaN, 2007 */
/*-----------------------------------------------------------------------*/
/* Only rcvr_spi(), xmit_spi(), disk_timerproc() and some macros */
/* are platform dependent. */
/*-----------------------------------------------------------------------*/
#include <avr/io.h>
#include <avr/interrupt.h>
#include "diskio.h"
/* Definitions for MMC/SDC command */
#define CMD0 (0) /* GO_IDLE_STATE */
#define CMD1 (1) /* SEND_OP_COND (MMC) */
#define ACMD41 (0x80+41) /* SEND_OP_COND (SDC) */
#define CMD8 (8) /* SEND_IF_COND */
#define CMD9 (9) /* SEND_CSD */
#define CMD10 (10) /* SEND_CID */
#define CMD12 (12) /* STOP_TRANSMISSION */
#define ACMD13 (0x80+13) /* SD_STATUS (SDC) */
#define CMD16 (16) /* SET_BLOCKLEN */
#define CMD17 (17) /* READ_SINGLE_BLOCK */
#define CMD18 (18) /* READ_MULTIPLE_BLOCK */
#define CMD23 (23) /* SET_BLOCK_COUNT (MMC) */
#define ACMD23 (0x80+23) /* SET_WR_BLK_ERASE_COUNT (SDC) */
#define CMD24 (24) /* WRITE_BLOCK */
#define CMD25 (25) /* WRITE_MULTIPLE_BLOCK */
#define CMD55 (55) /* APP_CMD */
#define CMD58 (58) /* READ_OCR */
/* Port Controls (Platform dependent) */
#define CS_LOW() PORTB &= ~1 /* MMC CS = L */
#define CS_HIGH() PORTB |= 1 /* MMC CS = H */
#define SOCKPORT PINB /* Socket contact port */
#define SOCKWP 0x20 /* Write protect switch (PB5) */
#define SOCKINS 0x10 /* Card detect switch (PB4) */
#define FCLK_SLOW() SPCR = 0x52 /* Set slow clock (100k-400k) */
#define FCLK_FAST() SPCR = 0x50 /* Set fast clock (depends on the CSD) */
/*--------------------------------------------------------------------------
Module Private Functions
---------------------------------------------------------------------------*/
static volatile
DSTATUS Stat = STA_NOINIT; /* Disk status */
static volatile
BYTE Timer1, Timer2; /* 100Hz decrement timer */
static
BYTE CardType; /* Card type flags */
/*-----------------------------------------------------------------------*/
/* Transmit a byte to MMC via SPI (Platform dependent) */
/*-----------------------------------------------------------------------*/
#define xmit_spi(dat) cli(); SPDR=(dat); loop_until_bit_is_set(SPSR,SPIF); sei()
/*-----------------------------------------------------------------------*/
/* Receive a byte from MMC via SPI (Platform dependent) */
/*-----------------------------------------------------------------------*/
static
BYTE rcvr_spi (void)
{
cli();
SPDR = 0xFF;
loop_until_bit_is_set(SPSR, SPIF);
sei();
return SPDR;
}
/* Alternative macro to receive data fast */
#define rcvr_spi_m(dst) SPDR=0xFF; loop_until_bit_is_set(SPSR,SPIF); *(dst)=SPDR
/*-----------------------------------------------------------------------*/
/* Wait for card ready */
/*-----------------------------------------------------------------------*/
static
int wait_ready (void) /* 1:OK, 0:Timeout */
{
Timer2 = 50; /* Wait for ready in timeout of 500ms */
rcvr_spi();
do
if (rcvr_spi() == 0xFF) return 1;
while (Timer2);
return 0;
}
/*-----------------------------------------------------------------------*/
/* Deselect the card and release SPI bus */
/*-----------------------------------------------------------------------*/
static
void deselect (void)
{
CS_HIGH();
rcvr_spi();
}
/*-----------------------------------------------------------------------*/
/* Select the card and wait for ready */
/*-----------------------------------------------------------------------*/
static
int select (void) /* 1:Successful, 0:Timeout */
{
CS_LOW();
if (!wait_ready()) {
deselect();
return 0;
}
return 1;
}
/*-----------------------------------------------------------------------*/
/* Power Control (Platform dependent) */
/*-----------------------------------------------------------------------*/
/* When the target system does not support socket power control, there */
/* is nothing to do in these functions and chk_power always returns 1. */
/*
static
void power_on (void)
{
PORTE &= ~0x80; // Socket power ON *
for (Timer1 = 3; Timer1; ); // Wait for 30ms *
PORTB = 0b10110101; //Enable drivers *
DDRB = 0b11000111;
SPCR = 0x52; // Enable SPI function in mode 0 *
SPSR = 0x01; // 2x mode *
}
static
void power_off (void)
{
select(); // Wait for card ready *
deselect();
SPCR = 0; // Disable SPI function *
DDRB = 0b11000000; // Disable drivers *
PORTB = 0b10110000;
PORTE |= 0x80; // Socket power OFF *
Stat |= STA_NOINIT; // Set STA_NOINIT *
}
*/
static
int chk_power(void) /* Socket power state: 0=off, 1=on */
{
return 1;
}
/*-----------------------------------------------------------------------*/
/* Receive a data packet from MMC */
/*-----------------------------------------------------------------------*/
static
int rcvr_datablock (
BYTE *buff, /* Data buffer to store received data */
UINT btr /* Byte count (must be multiple of 4) */
)
{
BYTE token;
Timer1 = 20;
do { /* Wait for data packet in timeout of 200ms */
token = rcvr_spi();
} while ((token == 0xFF) && Timer1);
if(token != 0xFE) return 0; /* If not valid data token, retutn with error */
do { /* Receive the data block into buffer */
rcvr_spi_m(buff++);
rcvr_spi_m(buff++);
rcvr_spi_m(buff++);
rcvr_spi_m(buff++);
} while (btr -= 4);
rcvr_spi(); /* Discard CRC */
rcvr_spi();
return 1; /* Return with success */
}
/*-----------------------------------------------------------------------*/
/* Send a data packet to MMC */
/*-----------------------------------------------------------------------*/
#if _READONLY == 0
static
int xmit_datablock (
const BYTE *buff, /* 512 byte data block to be transmitted */
BYTE token /* Data/Stop token */
)
{
BYTE resp, wc;
if (!wait_ready()) return 0;
xmit_spi(token); /* Xmit data token */
if (token != 0xFD) { /* Is data token */
wc = 0;
do { /* Xmit the 512 byte data block to MMC */
xmit_spi(*buff++);
xmit_spi(*buff++);
} while (--wc);
xmit_spi(0xFF); /* CRC (Dummy) */
xmit_spi(0xFF);
resp = rcvr_spi(); /* Reveive data response */
if ((resp & 0x1F) != 0x05) /* If not accepted, return with error */
return 0;
}
return 1;
}
#endif /* _READONLY */
/*-----------------------------------------------------------------------*/
/* Send a command packet to MMC */
/*-----------------------------------------------------------------------*/
static
BYTE send_cmd ( /* Returns R1 resp (bit7==1:Send failed) */
BYTE cmd, /* Command index */
DWORD arg /* Argument */
)
{
BYTE n, res;
if (cmd & 0x80) { /* ACMD<n> is the command sequense of CMD55-CMD<n> */
cmd &= 0x7F;
res = send_cmd(CMD55, 0);
if (res > 1) return res;
}
/* Select the card and wait for ready */
deselect();
if (!select()) return 0xFF;
/* Send command packet */
xmit_spi(0x40 | cmd); /* Start + Command index */
xmit_spi((BYTE)(arg >> 24)); /* Argument[31..24] */
xmit_spi((BYTE)(arg >> 16)); /* Argument[23..16] */
xmit_spi((BYTE)(arg >> 8)); /* Argument[15..8] */
xmit_spi((BYTE)arg); /* Argument[7..0] */
n = 0x01; /* Dummy CRC + Stop */
if (cmd == CMD0) n = 0x95; /* Valid CRC for CMD0(0) */
if (cmd == CMD8) n = 0x87; /* Valid CRC for CMD8(0x1AA) */
xmit_spi(n);
/* Receive command response */
if (cmd == CMD12) rcvr_spi(); /* Skip a stuff byte when stop reading */
n = 10; /* Wait for a valid response in timeout of 10 attempts */
do
res = rcvr_spi();
while ((res & 0x80) && --n);
return res; /* Return with the response value */
}
/*--------------------------------------------------------------------------
Public Functions
---------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------*/
/* Initialize Disk Drive */
/*-----------------------------------------------------------------------*/
DSTATUS disk_initialize (BYTE drv) /* Physical drive nmuber (0) */
{
BYTE n, cmd, ty, ocr[4];
if (drv) return STA_NOINIT; /* Supports only single drive */
if (Stat & STA_NODISK) return Stat; /* No card in the socket */
//power_on(); /* Force socket power on */
PORTB |= 0b11000000;
FCLK_SLOW();
for (n = 10; n; n--) rcvr_spi(); /* 80 dummy clocks */
ty = 0;
if (send_cmd(CMD0, 0) == 1) { /* Enter Idle state */
Timer1 = 200; /* Initialization timeout of 1000 msec */
if (send_cmd(CMD8, 0x1AA) == 1) { /* SDv2? */
for (n = 0; n < 4; n++) ocr[n] = rcvr_spi(); /* Get trailing return value of R7 resp */
if (ocr[2] == 0x01 && ocr[3] == 0xAA) { /* The card can work at vdd range of 2.7-3.6V */
while (Timer1 && send_cmd(ACMD41, 1UL << 30)); /* Wait for leaving idle state (ACMD41 with HCS bit) */
if (Timer1 && send_cmd(CMD58, 0) == 0) { /* Check CCS bit in the OCR */
for (n = 0; n < 4; n++) ocr[n] = rcvr_spi();
ty = (ocr[0] & 0x40) ? CT_SD2 | CT_BLOCK : CT_SD2; /* SDv2 */
}
}
} else { /* SDv1 or MMCv3 */
if (send_cmd(ACMD41, 0) <= 1) {
ty = CT_SD1; cmd = ACMD41; /* SDv1 */
} else {
ty = CT_MMC; cmd = CMD1; /* MMCv3 */
}
while (Timer1 && send_cmd(cmd, 0)); /* Wait for leaving idle state */
if (!Timer1 || send_cmd(CMD16, 512) != 0) /* Set R/W block length to 512 */
ty = 0;
}
}
CardType = ty;
deselect();
if (ty) { /* Initialization succeded */
Stat &= ~STA_NOINIT; /* Clear STA_NOINIT */
FCLK_FAST();
} else { /* Initialization failed */
//power_off();
}
return Stat;
}
/*-----------------------------------------------------------------------*/
/* Get Disk Status */
/*-----------------------------------------------------------------------*/
DSTATUS disk_status (
BYTE drv /* Physical drive nmuber (0) */
)
{
if (drv) return STA_NOINIT; /* Supports only single drive */
return Stat;
}
/*-----------------------------------------------------------------------*/
/* Read Sector(s) */
/*-----------------------------------------------------------------------*/
DRESULT disk_read (
BYTE drv, /* Physical drive nmuber (0) */
BYTE *buff, /* Pointer to the data buffer to store read data */
DWORD sector, /* Start sector number (LBA) */
BYTE count /* Sector count (1..255) */
)
{
if (drv || !count) return RES_PARERR;
if (Stat & STA_NOINIT) return RES_NOTRDY;
if (!(CardType & CT_BLOCK)) sector *= 512; /* Convert to byte address if needed */
if (count == 1) { /* Single block read */
if ((send_cmd(CMD17, sector) == 0) /* READ_SINGLE_BLOCK */
&& rcvr_datablock(buff, 512))
count = 0;
}
else { /* Multiple block read */
if (send_cmd(CMD18, sector) == 0) { /* READ_MULTIPLE_BLOCK */
do {
if (!rcvr_datablock(buff, 512)) break;
buff += 512;
} while (--count);
send_cmd(CMD12, 0); /* STOP_TRANSMISSION */
}
}
deselect();
return count ? RES_ERROR : RES_OK;
}
/*-----------------------------------------------------------------------*/
/* Write Sector(s) */
/*-----------------------------------------------------------------------*/
#if _READONLY == 0
DRESULT disk_write (
BYTE drv, /* Physical drive nmuber (0) */
const BYTE *buff, /* Pointer to the data to be written */
DWORD sector, /* Start sector number (LBA) */
BYTE count /* Sector count (1..255) */
)
{
if (drv || !count) return RES_PARERR;
if (Stat & STA_NOINIT) return RES_NOTRDY;
if (Stat & STA_PROTECT) return RES_WRPRT;
if (!(CardType & CT_BLOCK)) sector *= 512; /* Convert to byte address if needed */
if (count == 1) { /* Single block write */
if ((send_cmd(CMD24, sector) == 0) /* WRITE_BLOCK */
&& xmit_datablock(buff, 0xFE))
count = 0;
}
else { /* Multiple block write */
if (CardType & CT_SDC) send_cmd(ACMD23, count);
if (send_cmd(CMD25, sector) == 0) { /* WRITE_MULTIPLE_BLOCK */
do {
if (!xmit_datablock(buff, 0xFC)) break;
buff += 512;
} while (--count);
if (!xmit_datablock(0, 0xFD)) /* STOP_TRAN token */
count = 1;
}
}
deselect();
return count ? RES_ERROR : RES_OK;
}
#endif /* _READONLY == 0 */
/*-----------------------------------------------------------------------*/
/* Miscellaneous Functions */
/*-----------------------------------------------------------------------*/
#if _USE_IOCTL != 0
DRESULT disk_ioctl (
BYTE drv, /* Physical drive nmuber (0) */
BYTE ctrl, /* Control code */
void *buff /* Buffer to send/receive control data */
)
{
DRESULT res;
BYTE n, csd[16], *ptr = buff;
WORD csize;
if (drv) return RES_PARERR;
res = RES_ERROR;
if (ctrl == CTRL_POWER) {
switch (*ptr) {
case 0: /* Sub control code == 0 (POWER_OFF) */
if (chk_power())
//power_off(); // Power off */
res = RES_OK;
break;
case 1: /* Sub control code == 1 (POWER_ON) */
//power_on(); // Power on */
res = RES_OK;
break;
case 2: /* Sub control code == 2 (POWER_GET) */
*(ptr+1) = (BYTE)chk_power();
res = RES_OK;
break;
default :
res = RES_PARERR;
}
}
else {
if (Stat & STA_NOINIT) return RES_NOTRDY;
switch (ctrl) {
case CTRL_SYNC : /* Make sure that no pending write process. Do not remove this or written sector might not left updated. */
if (select()) {
deselect();
res = RES_OK;
}
break;
case GET_SECTOR_COUNT : /* Get number of sectors on the disk (DWORD) */
if ((send_cmd(CMD9, 0) == 0) && rcvr_datablock(csd, 16)) {
if ((csd[0] >> 6) == 1) { /* SDC ver 2.00 */
csize = csd[9] + ((WORD)csd[8] << 8) + 1;
*(DWORD*)buff = (DWORD)csize << 10;
} else { /* SDC ver 1.XX or MMC*/
n = (csd[5] & 15) + ((csd[10] & 128) >> 7) + ((csd[9] & 3) << 1) + 2;
csize = (csd[8] >> 6) + ((WORD)csd[7] << 2) + ((WORD)(csd[6] & 3) << 10) + 1;
*(DWORD*)buff = (DWORD)csize << (n - 9);
}
res = RES_OK;
}
break;
case GET_SECTOR_SIZE : /* Get R/W sector size (WORD) */
*(WORD*)buff = 512;
res = RES_OK;
break;
case GET_BLOCK_SIZE : /* Get erase block size in unit of sector (DWORD) */
if (CardType & CT_SD2) { /* SDv2? */
if (send_cmd(ACMD13, 0) == 0) { /* Read SD status */
rcvr_spi();
if (rcvr_datablock(csd, 16)) { /* Read partial block */
for (n = 64 - 16; n; n--) rcvr_spi(); /* Purge trailing data */
*(DWORD*)buff = 16UL << (csd[10] >> 4);
res = RES_OK;
}
}
} else { /* SDv1 or MMCv3 */
if ((send_cmd(CMD9, 0) == 0) && rcvr_datablock(csd, 16)) { /* Read CSD */
if (CardType & CT_SD1) { /* SDv1 */
*(DWORD*)buff = (((csd[10] & 63) << 1) + ((WORD)(csd[11] & 128) >> 7) + 1) << ((csd[13] >> 6) - 1);
} else { /* MMCv3 */
*(DWORD*)buff = ((WORD)((csd[10] & 124) >> 2) + 1) * (((csd[11] & 3) << 3) + ((csd[11] & 224) >> 5) + 1);
}
res = RES_OK;
}
}
break;
case MMC_GET_TYPE : /* Get card type flags (1 byte) */
*ptr = CardType;
res = RES_OK;
break;
case MMC_GET_CSD : /* Receive CSD as a data block (16 bytes) */
if (send_cmd(CMD9, 0) == 0 /* READ_CSD */
&& rcvr_datablock(ptr, 16))
res = RES_OK;
break;
case MMC_GET_CID : /* Receive CID as a data block (16 bytes) */
if (send_cmd(CMD10, 0) == 0 /* READ_CID */
&& rcvr_datablock(ptr, 16))
res = RES_OK;
break;
case MMC_GET_OCR : /* Receive OCR as an R3 resp (4 bytes) */
if (send_cmd(CMD58, 0) == 0) { /* READ_OCR */
for (n = 4; n; n--) *ptr++ = rcvr_spi();
res = RES_OK;
}
break;
case MMC_GET_SDSTAT : /* Receive SD statsu as a data block (64 bytes) */
if (send_cmd(ACMD13, 0) == 0) { /* SD_STATUS */
rcvr_spi();
if (rcvr_datablock(ptr, 64))
res = RES_OK;
}
break;
default:
res = RES_PARERR;
}
deselect();
}
return res;
}
#endif /* _USE_IOCTL != 0 */
/*-----------------------------------------------------------------------*/
/* Device Timer Interrupt Procedure (Platform dependent) */
/*-----------------------------------------------------------------------*/
/* This function must be called in period of 10ms */
void disk_timerproc (void)
{
static BYTE pv;
BYTE n, s;
n = Timer1; /* 100Hz decrement timer */
if (n) Timer1 = --n;
n = Timer2;
if (n) Timer2 = --n;
n = pv;
pv = SOCKPORT & (SOCKWP | SOCKINS); /* Sample socket switch */
if (n == pv) { /* Have contacts stabled? */
s = Stat;
if (pv & SOCKWP) /* WP is H (write protected) */
s |= STA_PROTECT;
else /* WP is L (write enabled) */
s &= ~STA_PROTECT;
if (pv & SOCKINS) /* INS = H (Socket empty) */
s |= (STA_NODISK | STA_NOINIT);
else /* INS = L (Card inserted) */
s &= ~STA_NODISK;
Stat = s;
}
}
DWORD get_fattime ()
{
return 0;
}

View File

@@ -0,0 +1,76 @@
/*-----------------------------------------------------------------------
/ Low level disk interface modlue include file R0.07 (C)ChaN, 2009
/-----------------------------------------------------------------------*/
#ifndef _DISKIO
#define _READONLY 0 /* 1: Read-only mode */
#define _USE_IOCTL 1
#include "integer.h"
/* Status of Disk Functions */
typedef BYTE DSTATUS;
/* Results of Disk Functions */
typedef enum {
RES_OK = 0, /* 0: Successful */
RES_ERROR, /* 1: R/W Error */
RES_WRPRT, /* 2: Write Protected */
RES_NOTRDY, /* 3: Not Ready */
RES_PARERR /* 4: Invalid Parameter */
} DRESULT;
/*---------------------------------------*/
/* Prototypes for disk control functions */
DSTATUS disk_initialize (BYTE);
DSTATUS disk_status (BYTE);
DRESULT disk_read (BYTE, BYTE*, DWORD, BYTE);
#if _READONLY == 0
DRESULT disk_write (BYTE, const BYTE*, DWORD, BYTE);
#endif
DRESULT disk_ioctl (BYTE, BYTE, void*);
/* Disk Status Bits (DSTATUS) */
#define STA_NOINIT 0x01 /* Drive not initialized */
#define STA_NODISK 0x02 /* No medium in the drive */
#define STA_PROTECT 0x04 /* Write protected */
/* Card type flags (CardType) */
#define CT_MMC 0x01
#define CT_SD1 0x02
#define CT_SD2 0x04
#define CT_SDC (CT_SD1|CT_SD2)
#define CT_BLOCK 0x08
/* Command code for disk_ioctrl() */
/* Generic command */
#define CTRL_SYNC 0 /* Mandatory for write functions */
#define GET_SECTOR_COUNT 1 /* Mandatory for only f_mkfs() */
#define GET_SECTOR_SIZE 2 /* Mandatory for multiple sector size cfg */
#define GET_BLOCK_SIZE 3 /* Mandatory for only f_mkfs() */
#define CTRL_POWER 4
#define CTRL_LOCK 5
#define CTRL_EJECT 6
/* MMC/SDC command */
#define MMC_GET_TYPE 10
#define MMC_GET_CSD 11
#define MMC_GET_CID 12
#define MMC_GET_OCR 13
#define MMC_GET_SDSTAT 14
/* ATA/CF command */
#define ATA_GET_REV 20
#define ATA_GET_MODEL 21
#define ATA_GET_SN 22
#define _DISKIO
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,613 @@
/*---------------------------------------------------------------------------/
/ FatFs - FAT file system module include file R0.08 (C)ChaN, 2010
/----------------------------------------------------------------------------/
/ FatFs module is a generic FAT file system module for small embedded systems.
/ This is a free software that opened for education, research and commercial
/ developments under license policy of following trems.
/
/ Copyright (C) 2010, ChaN, all right reserved.
/
/ * The FatFs module is a free software and there is NO WARRANTY.
/ * No restriction on use. You can use, modify and redistribute it for
/ personal, non-profit or commercial product UNDER YOUR RESPONSIBILITY.
/ * Redistributions of source code must retain the above copyright notice.
/
/----------------------------------------------------------------------------*/
#ifndef _FATFS
#define _FATFS 8085 /* Revision ID */
#ifdef __cplusplus
extern "C" {
#endif
#include "integer.h" /* Basic integer types */
#include "ffconf.h" /* FatFs configuration options */
#if _FATFS != _FFCONF
#error Wrong configuration file (ffconf.h).
#endif
/* DBCS code ranges and SBCS extend char conversion table */
#if _CODE_PAGE == 932 /* Japanese Shift-JIS */
#define _DF1S 0x81 /* DBC 1st byte range 1 start */
#define _DF1E 0x9F /* DBC 1st byte range 1 end */
#define _DF2S 0xE0 /* DBC 1st byte range 2 start */
#define _DF2E 0xFC /* DBC 1st byte range 2 end */
#define _DS1S 0x40 /* DBC 2nd byte range 1 start */
#define _DS1E 0x7E /* DBC 2nd byte range 1 end */
#define _DS2S 0x80 /* DBC 2nd byte range 2 start */
#define _DS2E 0xFC /* DBC 2nd byte range 2 end */
#elif _CODE_PAGE == 936 /* Simplified Chinese GBK */
#define _DF1S 0x81
#define _DF1E 0xFE
#define _DS1S 0x40
#define _DS1E 0x7E
#define _DS2S 0x80
#define _DS2E 0xFE
#elif _CODE_PAGE == 949 /* Korean */
#define _DF1S 0x81
#define _DF1E 0xFE
#define _DS1S 0x41
#define _DS1E 0x5A
#define _DS2S 0x61
#define _DS2E 0x7A
#define _DS3S 0x81
#define _DS3E 0xFE
#elif _CODE_PAGE == 950 /* Traditional Chinese Big5 */
#define _DF1S 0x81
#define _DF1E 0xFE
#define _DS1S 0x40
#define _DS1E 0x7E
#define _DS2S 0xA1
#define _DS2E 0xFE
#elif _CODE_PAGE == 437 /* U.S. (OEM) */
#define _DF1S 0
#define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0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D2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
#elif _CODE_PAGE == 737 /* Greek (OEM) */
#define _DF1S 0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x92,0x92,0x93,0x94,0x95,0x96,0x97,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87, \
0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0xAA,0x92,0x93,0x94,0x95,0x96,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
0x97,0xEA,0xEB,0xEC,0xE4,0xED,0xEE,0xE7,0xE8,0xF1,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
#elif _CODE_PAGE == 775 /* Baltic (OEM) */
#define _DF1S 0
#define _EXCVT {0x80,0x9A,0x91,0xA0,0x8E,0x95,0x8F,0x80,0xAD,0xED,0x8A,0x8A,0xA1,0x8D,0x8E,0x8F,0x90,0x92,0x92,0xE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,0xDC,0xDD,0xDE,0xDF, \
0x90,0x91,0x92,0x93,0x9d,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F,0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
#elif _CODE_PAGE == 874 /* Thai (OEM, Windows) */
#define _DF1S 0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
#elif _CODE_PAGE == 1250 /* Central Europe (Windows) */
#define _DF1S 0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x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C0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF}
#elif _CODE_PAGE == 1252 /* Latin 1 (Windows) */
#define _DF1S 0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0xAd,0x9B,0x8C,0x9D,0xAE,0x9F, \
0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0x9F}
#elif _CODE_PAGE == 1253 /* Greek (Windows) */
#define _DF1S 0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F,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4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0x9F}
#elif _CODE_PAGE == 1255 /* Hebrew (Windows) */
#define _DF1S 0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
#elif _CODE_PAGE == 1256 /* Arabic (Windows) */
#define _DF1S 0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x8C,0x9D,0x9E,0x9F, \
0xA0,0xA1,0xA2,0xA3,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CB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xFF}
#elif _CODE_PAGE == 1258 /* Vietnam (OEM, Windows) */
#define _DF1S 0
#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0xAC,0x9D,0x9E,0x9F, \
0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xEC,0xCD,0xCE,0xCF,0xD0,0xD1,0xF2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xFE,0x9F}
#elif _CODE_PAGE == 1 /* ASCII (for only non-LFN cfg) */
#define _DF1S 0
#else
#error Unknown code page
#endif
/* Definitions corresponds to volume management */
#if _MULTI_PARTITION /* Multiple partition configuration */
#define LD2PD(drv) (Drives[drv].pd) /* Get physical drive# */
#define LD2PT(drv) (Drives[drv].pt) /* Get partition# */
typedef struct {
BYTE pd; /* Physical drive# */
BYTE pt; /* Partition # (0-3) */
} PARTITION;
extern const PARTITION Drives[]; /* Logical drive# to physical location conversion table */
#else /* Single partition configuration */
#define LD2PD(drv) (drv) /* Physical drive# is equal to the logical drive# */
#define LD2PT(drv) 0 /* Always mounts the 1st partition */
#endif
/* Type of path name strings on FatFs API */
#if _LFN_UNICODE /* Unicode string */
#if !_USE_LFN
#error _LFN_UNICODE must be 0 in non-LFN cfg.
#endif
#ifndef _INC_TCHAR
typedef WCHAR TCHAR;
#define _T(x) L ## x
#define _TEXT(x) L ## x
#endif
#else /* ANSI/OEM string */
#ifndef _INC_TCHAR
typedef char TCHAR;
#define _T(x) x
#define _TEXT(x) x
#endif
#endif
/* Definitions corresponds to file shareing feature */
#if _FS_SHARE
#if _FS_READONLY
#error _FS_SHARE must be 0 on R/O cfg.
#endif
typedef struct {
DWORD clu; /* File ID 1, directory */
WORD idx; /* File ID 2, index in the directory */
WORD ctr; /* File open counter, 0:none, 0x01..0xFF:read open count, 0x100:in write open */
} FILESEM;
#endif
/* File system object structure (FATFS) */
typedef struct {
BYTE fs_type; /* FAT sub-type (0:Not mounted) */
BYTE drv; /* Physical drive number */
BYTE csize; /* Sectors per cluster (1,2,4...128) */
BYTE n_fats; /* Number of FAT copies (1,2) */
BYTE wflag; /* win[] dirty flag (1:must be written back) */
BYTE fsi_flag; /* fsinfo dirty flag (1:must be written back) */
WORD id; /* File system mount ID */
WORD n_rootdir; /* Number of root directory entries (FAT12/16) */
#if _MAX_SS != 512
WORD ssize; /* Bytes per sector (512,1024,2048,4096) */
#endif
#if _FS_REENTRANT
_SYNC_t sobj; /* Identifier of sync object */
#endif
#if !_FS_READONLY
DWORD last_clust; /* Last allocated cluster */
DWORD free_clust; /* Number of free clusters */
DWORD fsi_sector; /* fsinfo sector (FAT32) */
#endif
#if _FS_RPATH
DWORD cdir; /* Current directory start cluster (0:root) */
#endif
DWORD n_fatent; /* Number of FAT entries (= number of clusters + 2) */
DWORD fsize; /* Sectors per FAT */
DWORD fatbase; /* FAT start sector */
DWORD dirbase; /* Root directory start sector (FAT32:Cluster#) */
DWORD database; /* Data start sector */
DWORD winsect; /* Current sector appearing in the win[] */
BYTE win[_MAX_SS]; /* Disk access window for Directory, FAT (and Data on tiny cfg) */
#if _FS_SHARE
FILESEM flsem[_FS_SHARE]; /* File lock semaphores */
#endif
} FATFS;
/* File object structure (FIL) */
typedef struct {
FATFS* fs; /* Pointer to the owner file system object */
WORD id; /* Owner file system mount ID */
BYTE flag; /* File status flags */
BYTE pad1;
DWORD fptr; /* File read/write pointer */
DWORD fsize; /* File size */
DWORD org_clust; /* File start cluster (0 when fsize==0) */
DWORD curr_clust; /* Current cluster */
DWORD dsect; /* Current data sector */
#if !_FS_READONLY
DWORD dir_sect; /* Sector containing the directory entry */
BYTE* dir_ptr; /* Ponter to the directory entry in the window */
#endif
#if _USE_FASTSEEK
DWORD* cltbl; /* Pointer to the cluster link map table */
#endif
#if _FS_SHARE
UINT lockid; /* File lock ID */
#endif
#if !_FS_TINY
BYTE buf[_MAX_SS]; /* File data read/write buffer */
#endif
} FIL;
/* Directory object structure (DIR) */
typedef struct {
FATFS* fs; /* Pointer to the owner file system object */
WORD id; /* Owner file system mount ID */
WORD index; /* Current read/write index number */
DWORD sclust; /* Table start cluster (0:Root dir) */
DWORD clust; /* Current cluster */
DWORD sect; /* Current sector */
BYTE* dir; /* Pointer to the current SFN entry in the win[] */
BYTE* fn; /* Pointer to the SFN (in/out) {file[8],ext[3],status[1]} */
#if _USE_LFN
WCHAR* lfn; /* Pointer to the LFN working buffer */
WORD lfn_idx; /* Last matched LFN index number (0xFFFF:No LFN) */
#endif
} DIR;
/* File status structure (FILINFO) */
typedef struct {
DWORD fsize; /* File size */
WORD fdate; /* Last modified date */
WORD ftime; /* Last modified time */
BYTE fattrib; /* Attribute */
TCHAR fname[13]; /* Short file name (8.3 format) */
#if _USE_LFN
TCHAR* lfname; /* Pointer to the LFN buffer */
int lfsize; /* Size of LFN buffer [chrs] */
#endif
} FILINFO;
/* File function return code (FRESULT) */
typedef enum {
FR_OK = 0, /* (0) Succeeded */
FR_DISK_ERR, /* (1) A hard error occured in the low level disk I/O layer */
FR_INT_ERR, /* (2) Assertion failed */
FR_NOT_READY, /* (3) The physical drive cannot work */
FR_NO_FILE, /* (4) Could not find the file */
FR_NO_PATH, /* (5) Could not find the path */
FR_INVALID_NAME, /* (6) The path name format is invalid */
FR_DENIED, /* (7) Acces denied due to prohibited access or directory full */
FR_EXIST, /* (8) Acces denied due to prohibited access */
FR_INVALID_OBJECT, /* (9) The file/directory object is invalid */
FR_WRITE_PROTECTED, /* (10) The physical drive is write protected */
FR_INVALID_DRIVE, /* (11) The logical drive number is invalid */
FR_NOT_ENABLED, /* (12) The volume has no work area */
FR_NO_FILESYSTEM, /* (13) There is no valid FAT volume on the physical drive */
FR_MKFS_ABORTED, /* (14) The f_mkfs() aborted due to any parameter error */
FR_TIMEOUT, /* (15) Could not get a grant to access the volume within defined period */
FR_LOCKED, /* (16) The operation is rejected according to the file shareing policy */
FR_NOT_ENOUGH_CORE, /* (17) LFN working buffer could not be allocated */
FR_TOO_MANY_OPEN_FILES /* (18) Number of open files > _FS_SHARE */
} FRESULT;
/*--------------------------------------------------------------*/
/* FatFs module application interface */
FRESULT f_mount (BYTE, FATFS*); /* Mount/Unmount a logical drive */
FRESULT f_open (FIL*, const TCHAR*, BYTE); /* Open or create a file */
FRESULT f_read (FIL*, void*, UINT, UINT*); /* Read data from a file */
FRESULT f_lseek (FIL*, DWORD); /* Move file pointer of a file object */
FRESULT f_close (FIL*); /* Close an open file object */
FRESULT f_opendir (DIR*, const TCHAR*); /* Open an existing directory */
FRESULT f_readdir (DIR*, FILINFO*); /* Read a directory item */
FRESULT f_stat (const TCHAR*, FILINFO*); /* Get file status */
#if !_FS_READONLY
FRESULT f_write (FIL*, const void*, UINT, UINT*); /* Write data to a file */
FRESULT f_getfree (const TCHAR*, DWORD*, FATFS**); /* Get number of free clusters on the drive */
FRESULT f_truncate (FIL*); /* Truncate file */
FRESULT f_sync (FIL*); /* Flush cached data of a writing file */
FRESULT f_unlink (const TCHAR*); /* Delete an existing file or directory */
FRESULT f_mkdir (const TCHAR*); /* Create a new directory */
FRESULT f_chmod (const TCHAR*, BYTE, BYTE); /* Change attriburte of the file/dir */
FRESULT f_utime (const TCHAR*, const FILINFO*); /* Change timestamp of the file/dir */
FRESULT f_rename (const TCHAR*, const TCHAR*); /* Rename/Move a file or directory */
#endif
#if _USE_FORWARD
FRESULT f_forward (FIL*, UINT(*)(const BYTE*,UINT), UINT, UINT*); /* Forward data to the stream */
#endif
#if _USE_MKFS
FRESULT f_mkfs (BYTE, BYTE, UINT); /* Create a file system on the drive */
#endif
#if _FS_RPATH
FRESULT f_chdir (const TCHAR*); /* Change current directory */
FRESULT f_chdrive (BYTE); /* Change current drive */
#endif
#if _USE_STRFUNC
int f_putc (TCHAR, FIL*); /* Put a character to the file */
int f_puts (const TCHAR*, FIL*); /* Put a string to the file */
int f_printf (FIL*, const TCHAR*, ...); /* Put a formatted string to the file */
TCHAR* f_gets (TCHAR*, int, FIL*); /* Get a string from the file */
#define f_eof(fp) (((fp)->fptr == (fp)->fsize) ? 1 : 0)
#define f_error(fp) (((fp)->flag & FA__ERROR) ? 1 : 0)
#ifndef EOF
#define EOF (-1)
#endif
#endif
/*--------------------------------------------------------------*/
/* Additional user defined functions */
/* RTC function */
#if !_FS_READONLY
DWORD get_fattime (void);
#endif
/* Unicode support functions */
#if _USE_LFN /* Unicode - OEM code conversion */
WCHAR ff_convert (WCHAR, UINT); /* OEM-Unicode bidirectional conversion */
WCHAR ff_wtoupper (WCHAR); /* Unicode upper-case conversion */
#if _USE_LFN == 3 /* Memory functions */
void* ff_memalloc (UINT); /* Allocate memory block */
void ff_memfree (void*); /* Free memory block */
#endif
#endif
/* Sync functions */
#if _FS_REENTRANT
int ff_cre_syncobj (BYTE, _SYNC_t*);/* Create a sync object */
int ff_del_syncobj (_SYNC_t); /* Delete a sync object */
int ff_req_grant (_SYNC_t); /* Lock sync object */
void ff_rel_grant (_SYNC_t); /* Unlock sync object */
#endif
/*--------------------------------------------------------------*/
/* Flags and offset address */
/* File access control and file status flags (FIL.flag) */
#define FA_READ 0x01
#define FA_OPEN_EXISTING 0x00
#define FA__ERROR 0x80
#if !_FS_READONLY
#define FA_WRITE 0x02
#define FA_CREATE_NEW 0x04
#define FA_CREATE_ALWAYS 0x08
#define FA_OPEN_ALWAYS 0x10
#define FA__WRITTEN 0x20
#define FA__DIRTY 0x40
#endif
/* FAT sub type (FATFS.fs_type) */
#define FS_FAT12 1
#define FS_FAT16 2
#define FS_FAT32 3
/* File attribute bits for directory entry */
#define AM_RDO 0x01 /* Read only */
#define AM_HID 0x02 /* Hidden */
#define AM_SYS 0x04 /* System */
#define AM_VOL 0x08 /* Volume label */
#define AM_LFN 0x0F /* LFN entry */
#define AM_DIR 0x10 /* Directory */
#define AM_ARC 0x20 /* Archive */
#define AM_MASK 0x3F /* Mask of defined bits */
/* Fast seek function */
#define CREATE_LINKMAP 0xFFFFFFFF
/* FatFs refers the members in the FAT structures with byte offset instead of
/ structure member because there are incompatibility of the packing option
/ between various compilers. */
#define BS_jmpBoot 0
#define BS_OEMName 3
#define BPB_BytsPerSec 11
#define BPB_SecPerClus 13
#define BPB_RsvdSecCnt 14
#define BPB_NumFATs 16
#define BPB_RootEntCnt 17
#define BPB_TotSec16 19
#define BPB_Media 21
#define BPB_FATSz16 22
#define BPB_SecPerTrk 24
#define BPB_NumHeads 26
#define BPB_HiddSec 28
#define BPB_TotSec32 32
#define BS_55AA 510
#define BS_DrvNum 36
#define BS_BootSig 38
#define BS_VolID 39
#define BS_VolLab 43
#define BS_FilSysType 54
#define BPB_FATSz32 36
#define BPB_ExtFlags 40
#define BPB_FSVer 42
#define BPB_RootClus 44
#define BPB_FSInfo 48
#define BPB_BkBootSec 50
#define BS_DrvNum32 64
#define BS_BootSig32 66
#define BS_VolID32 67
#define BS_VolLab32 71
#define BS_FilSysType32 82
#define FSI_LeadSig 0
#define FSI_StrucSig 484
#define FSI_Free_Count 488
#define FSI_Nxt_Free 492
#define MBR_Table 446
#define DIR_Name 0
#define DIR_Attr 11
#define DIR_NTres 12
#define DIR_CrtTime 14
#define DIR_CrtDate 16
#define DIR_FstClusHI 20
#define DIR_WrtTime 22
#define DIR_WrtDate 24
#define DIR_FstClusLO 26
#define DIR_FileSize 28
#define LDIR_Ord 0
#define LDIR_Attr 11
#define LDIR_Type 12
#define LDIR_Chksum 13
#define LDIR_FstClusLO 26
/*--------------------------------*/
/* Multi-byte word access macros */
#if _WORD_ACCESS == 1 /* Enable word access to the FAT structure */
#define LD_WORD(ptr) (WORD)(*(WORD*)(BYTE*)(ptr))
#define LD_DWORD(ptr) (DWORD)(*(DWORD*)(BYTE*)(ptr))
#define ST_WORD(ptr,val) *(WORD*)(BYTE*)(ptr)=(WORD)(val)
#define ST_DWORD(ptr,val) *(DWORD*)(BYTE*)(ptr)=(DWORD)(val)
#else /* Use byte-by-byte access to the FAT structure */
#define LD_WORD(ptr) (WORD)(((WORD)*(BYTE*)((ptr)+1)<<8)|(WORD)*(BYTE*)(ptr))
#define LD_DWORD(ptr) (DWORD)(((DWORD)*(BYTE*)((ptr)+3)<<24)|((DWORD)*(BYTE*)((ptr)+2)<<16)|((WORD)*(BYTE*)((ptr)+1)<<8)|*(BYTE*)(ptr))
#define ST_WORD(ptr,val) *(BYTE*)(ptr)=(BYTE)(val); *(BYTE*)((ptr)+1)=(BYTE)((WORD)(val)>>8)
#define ST_DWORD(ptr,val) *(BYTE*)(ptr)=(BYTE)(val); *(BYTE*)((ptr)+1)=(BYTE)((WORD)(val)>>8); *(BYTE*)((ptr)+2)=(BYTE)((DWORD)(val)>>16); *(BYTE*)((ptr)+3)=(BYTE)((DWORD)(val)>>24)
#endif
#ifdef __cplusplus
}
#endif
#endif /* _FATFS */

View File

@@ -0,0 +1,179 @@
/*---------------------------------------------------------------------------/
/ FatFs - FAT file system module configuration file R0.08 (C)ChaN, 2010
/----------------------------------------------------------------------------/
/
/ CAUTION! Do not forget to make clean the project after any changes to
/ the configuration options.
/
/----------------------------------------------------------------------------*/
#ifndef _FFCONF
#define _FFCONF 8085 /* Revision ID */
/*---------------------------------------------------------------------------/
/ Function and Buffer Configurations
/----------------------------------------------------------------------------*/
#define _FS_TINY 1 /* 0 or 1 */
/* When _FS_TINY is set to 1, FatFs uses the sector buffer in the file system
/ object instead of the sector buffer in the individual file object for file
/ data transfer. This reduces memory consumption 512 bytes each file object. */
#define _FS_READONLY 0 /* 0 or 1 */
/* Setting _FS_READONLY to 1 defines read only configuration. This removes
/ writing functions, f_write, f_sync, f_unlink, f_mkdir, f_chmod, f_rename,
/ f_truncate and useless f_getfree. */
#define _FS_MINIMIZE 0 /* 0, 1, 2 or 3 */
/* The _FS_MINIMIZE option defines minimization level to remove some functions.
/
/ 0: Full function.
/ 1: f_stat, f_getfree, f_unlink, f_mkdir, f_chmod, f_truncate and f_rename
/ are removed.
/ 2: f_opendir and f_readdir are removed in addition to level 1.
/ 3: f_lseek is removed in addition to level 2. */
#define _USE_STRFUNC 0 /* 0, 1 or 2 */
/* To enable string functions, set _USE_STRFUNC to 1 or 2. */
#define _USE_MKFS 1 /* 0 or 1 */
/* To enable f_mkfs function, set _USE_MKFS to 1 and set _FS_READONLY to 0 */
#define _USE_FORWARD 0 /* 0 or 1 */
/* To enable f_forward function, set _USE_FORWARD to 1 and set _FS_TINY to 1. */
#define _USE_FASTSEEK 0 /* 0 or 1 */
/* To enable f_fastseek function, set _USE_FASTSEEK to 1. */
/*---------------------------------------------------------------------------/
/ Locale and Namespace Configurations
/----------------------------------------------------------------------------*/
#define _CODE_PAGE 1
/* The _CODE_PAGE specifies the OEM code page to be used on the target system.
/ Incorrect setting of the code page can cause a file open failure.
/
/ 932 - Japanese Shift-JIS (DBCS, OEM, Windows)
/ 936 - Simplified Chinese GBK (DBCS, OEM, Windows)
/ 949 - Korean (DBCS, OEM, Windows)
/ 950 - Traditional Chinese Big5 (DBCS, OEM, Windows)
/ 1250 - Central Europe (Windows)
/ 1251 - Cyrillic (Windows)
/ 1252 - Latin 1 (Windows)
/ 1253 - Greek (Windows)
/ 1254 - Turkish (Windows)
/ 1255 - Hebrew (Windows)
/ 1256 - Arabic (Windows)
/ 1257 - Baltic (Windows)
/ 1258 - Vietnam (OEM, Windows)
/ 437 - U.S. (OEM)
/ 720 - Arabic (OEM)
/ 737 - Greek (OEM)
/ 775 - Baltic (OEM)
/ 850 - Multilingual Latin 1 (OEM)
/ 858 - Multilingual Latin 1 + Euro (OEM)
/ 852 - Latin 2 (OEM)
/ 855 - Cyrillic (OEM)
/ 866 - Russian (OEM)
/ 857 - Turkish (OEM)
/ 862 - Hebrew (OEM)
/ 874 - Thai (OEM, Windows)
/ 1 - ASCII only (Valid for non LFN cfg.)
*/
#define _USE_LFN 0 /* 0 to 3 */
#define _MAX_LFN 128 /* Maximum LFN length to handle (12 to 255) */
/* The _USE_LFN option switches the LFN support.
/
/ 0: Disable LFN. _MAX_LFN and _LFN_UNICODE have no effect.
/ 1: Enable LFN with static working buffer on the bss. NOT REENTRANT.
/ 2: Enable LFN with dynamic working buffer on the STACK.
/ 3: Enable LFN with dynamic working buffer on the HEAP.
/
/ The LFN working buffer occupies (_MAX_LFN + 1) * 2 bytes. When enable LFN,
/ Unicode handling functions ff_convert() and ff_wtoupper() must be added
/ to the project. When enable to use heap, memory control functions
/ ff_memalloc() and ff_memfree() must be added to the project. */
#define _LFN_UNICODE 0 /* 0 or 1 */
/* To switch the character code set on FatFs API to Unicode,
/ enable LFN feature and set _LFN_UNICODE to 1.
*/
#define _FS_RPATH 1 /* 0 or 1 */
/* When _FS_RPATH is set to 1, relative path feature is enabled and f_chdir,
/ f_chdrive function are available.
/ Note that output of the f_readdir fnction is affected by this option. */
/*---------------------------------------------------------------------------/
/ Physical Drive Configurations
/----------------------------------------------------------------------------*/
#define _DRIVES 2
/* Number of volumes (logical drives) to be used. */
#define _MAX_SS 512 /* 512, 1024, 2048 or 4096 */
/* Maximum sector size to be handled.
/ Always set 512 for memory card and hard disk but a larger value may be
/ required for floppy disk (512/1024) and optical disk (512/2048).
/ When _MAX_SS is larger than 512, GET_SECTOR_SIZE command must be implememted
/ to the disk_ioctl function. */
#define _MULTI_PARTITION 0 /* 0 or 1 */
/* When _MULTI_PARTITION is set to 0, each volume is bound to the same physical
/ drive number and can mount only first primaly partition. When it is set to 1,
/ each volume is tied to the partitions listed in Drives[]. */
/*---------------------------------------------------------------------------/
/ System Configurations
/----------------------------------------------------------------------------*/
#define _WORD_ACCESS 1 /* 0 or 1 */
/* Set 0 first and it is always compatible with all platforms. The _WORD_ACCESS
/ option defines which access method is used to the word data on the FAT volume.
/
/ 0: Byte-by-byte access.
/ 1: Word access. Do not choose this unless following condition is met.
/
/ When the byte order on the memory is big-endian or address miss-aligned word
/ access results incorrect behavior, the _WORD_ACCESS must be set to 0.
/ If it is not the case, the value can also be set to 1 to improve the
/ performance and code size. */
#define _FS_REENTRANT 0 /* 0 or 1 */
#define _FS_TIMEOUT 1000 /* Timeout period in unit of time ticks */
#define _SYNC_t HANDLE /* O/S dependent type of sync object. e.g. HANDLE, OS_EVENT*, ID and etc.. */
/* The _FS_REENTRANT option switches the reentrancy of the FatFs module.
/
/ 0: Disable reentrancy. _SYNC_t and _FS_TIMEOUT have no effect.
/ 1: Enable reentrancy. Also user provided synchronization handlers,
/ ff_req_grant, ff_rel_grant, ff_del_syncobj and ff_cre_syncobj
/ function must be added to the project. */
#define _FS_SHARE 0 /* 0 or >=1 */
/* To enable file shareing feature, set _FS_SHARE to >= 1 and also user
provided memory handlers, ff_memalloc and ff_memfree function must be
added to the project. The value defines number of files can be opened
per volume. */
#endif /* _FFCONF */

View File

@@ -0,0 +1,37 @@
/*-------------------------------------------*/
/* Integer type definitions for FatFs module */
/*-------------------------------------------*/
#ifndef _INTEGER
#define _INTEGER
#ifdef _WIN32 /* FatFs development platform */
#include <windows.h>
#include <tchar.h>
#else /* Embedded platform */
/* These types must be 16-bit, 32-bit or larger integer */
typedef int INT;
typedef unsigned int UINT;
/* These types must be 8-bit integer */
typedef char CHAR;
typedef unsigned char UCHAR;
typedef unsigned char BYTE;
/* These types must be 16-bit integer */
typedef short SHORT;
typedef unsigned short USHORT;
typedef unsigned short WORD;
typedef unsigned short WCHAR;
/* These types must be 32-bit integer */
typedef long LONG;
typedef unsigned long ULONG;
typedef unsigned long DWORD;
#endif
#endif

View File

@@ -0,0 +1,300 @@
/**
@file main.c
@brief Lab 3 Starter Code
@version .01
@mainpage Lab 3 Starter Code
@section intro Code Overview
@section hw Hardware Pin Out
Port A:
A0 - A3 : Push Buttons
A4 - A7 : Slide Switches
Port B:
B0 - B3 : SPI (SD Card)
B4 : Nothing
B5 : Audio Out
B6 : Red Enable
B7 : Green Enable
Port C:
C0 - C7 : LED Array (Row)
Port D:
D0 - D1 : Nothing
D2 : Serial RX
D3 : Serial TX
D4 - D7 : Nothing
Port E:
E0 - E2 : LED Array (Column)
E3 : USB (UID)
E4 - E5 : Nothing
E6 : Relay
E7 : Nothing
Port F:
F0 : ADC Channel 0
F1 : ADC Channel 1
F2 : ADC Channel 2
F3 : ADC Channel 3
F4 : ADC Channel 4 (Audio In)
F5 : ADC Channel 5 (Accel X Axis)
F6 : ADC Channel 6 (Accel Y Axis)
F7 : ADC Channel 7 (Accel Z Axis (if installed))
*/
/** Includes */
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
/** Constants */
#define F_CPU 1000000UL
#define DEBUG 1
#ifdef DEBUG == 1
#define SENDSPEED 3 //If less than .12, there are problems
#endif
/** Global Variables */
volatile unsigned char numelapsed = 0;
/** Functions */
#ifdef DEBUG == 1
/** This function needs to setup the variables used by the UART to enable the UART and tramsmit at 9600bps. This
function should always return 0. Remember, by defualt the Wunderboard runs at 1mHz for its system clock.*/
unsigned char InitializeUART (){
unsigned char baud = ((F_CPU/(9600*8UL))-1);
/* Set baud rate */
UBRR1H = (baud >> 8);
UBRR1L = baud;
/* Set the U2X1 bit */
UCSR1A = (1 << U2X1);
/* Enable transmitter */
UCSR1B = (1 << TXEN1 | 1 << RXEN1);
/* Set frame format: 8data, 1stop bit */
UCSR1C = (3 << UCSZ10);
return 0;
}
/** This function needs to write a single byte to the UART. It must check that the UART is ready for a new byte
and return a 1 if the byte was not sent.
@param [in] data This is the data byte to be sent.
@return The function returns a 1 or error and 0 on successful completion.*/
unsigned char SendByteUART (unsigned char data){
/*
** Checks the buffer empty bit so that data can either be placed in the buffer
** or else reuturn a 1
*/
if((UCSR1A & (1 << UDRE1)) == (1 << UDRE1)){
UDR1 = data; //Places data into the UDR1 8-bit data buffer
}else {
return 1;
}
return 0;
}
/** This function needs to writes a string to the UART. It must check that the UART is ready for a new byte and
return a 1 if the string was not sent.
@param [in] data This is a pointer to the data to be sent.
@return The function returns a 1 or error and 0 on successful completion.*/
unsigned char SendStringUART (unsigned char *data){
for (int loop = 0 ; data[loop] != '\0'; loop++){
unsigned char bytereturn; //Storage for return value of SendByteUART
/* Sends the current byte based on the loop umber to SendByte */
while(SendByteUART(data[loop]));
/* Stops sending if SendByteUART had an error */
if(bytereturn == 1){
return 1;
}
}
return 0;
}
unsigned char GetByteUART(){
if (UCSR1A & (1 << RXC1)){
return(UDR1);
} else{
return(-1);
}
}
#endif
/** The clearArray() function turns off all LEDS on the Wunderboard array. It accepts no inputs and returns nothing*/
void clearArray(void){
PORTC = 0x00;
PORTB |= (1 << PB6) | (1 << PB7); /** Enable latches*/
PORTB &= ~((1 << PB6) | (1 << PB7)); /** Disable latches*/
}
/** The initialize() function initializes all of the Data Direction Registers for the Wunderboard. Before making changes to DDRx registers, ensure that you have read the peripherals section of the Wunderboard user guide.*/
void initialize(void){
/** Port A is the switches and buttons. They should always be inputs. ( 0 = Input and 1 = Output )*/
DDRA=0b00000000;
/** Port B has the LED Array color control, SD card, and audio-out on it. Leave DDRB alone. ( 0 = Input and 1 = Output )*/
DDRB=0b11000111;
/** Port C is for the 'row' of the LED array. They should always be outputs. ( 0 = Input and 1 = Output )*/
DDRC=0b11111111;
/** Port D has the Serial on it. Leave DDRB alone. ( 0 = Input and 1 = Output )*/
DDRD=0b00000000;
/** Port E has the LED Array Column control out on it. Leave DDRE alone. ( 0 = Input and 1 = Output )*/
DDRE=0b00000111;
/** Port F has the accelerometer and audio-in on it. Leave DDRF alone. ( 0 = Input and 1 = Output )*/
DDRF=0b00000000;
}
unsigned char read_adc(uint8_t channel){
unsigned char test;
ADMUX = 0x60 | channel; // Set the channel to the one we want
ADCSRA = 0b11000110; // Start a new sample.
while ((ADCSRA & 0b00010000) == 0 ); // Wait for a Valid Sample
ADCSRA |= 0b00010000; // Tell ADC you have the sample you want.
ADCSRA |= 0b01000000; // Start a new sample.
while ((ADCSRA & 0b00010000) == 0 ); // Wait for a Valid Sample
ADCSRA |= 0b00010000; // Tell ADC you have the sample you want.
test = ADCH;
ADCSRA = 0x00; // Disable the ADC
return (test);
}
/** This function needs to setup the variables used by TIMER0 Compare Match (CTC) mode with
a base clock frequency of clk/1024. This function should return a 1 if it fails and a 0 if it
does not. Remember, by default the Wunderboard runs at 1mHz for its system clock.
@return This function returns a 1 is unsuccessful, else return 0.*/
unsigned char initializeTIMER0(void){
/* Set the CTC mode */
TCCR0A = (1 << WGM01);
/* Set the Clock Frequency */
TCCR0B = ((1 << CS02) | (1 << CS00));
/* Set initial count value */
OCR0A = 0;
}
/** This function takes two values, clock and count. The value of count should be copied into OCR0A and the value of clock should be used to set CS02:0. The TCNT0 variable should also be reset to 0 so that the new timer rate starts from 0.
@param [in] clock Insert Comment
@param [in] count Insert Comment
@return The function returns a 1 or error and 0 on successful completion.*/
unsigned char setTIMER0(unsigned char clock, unsigned char count){
if(clock > 7){
return 1;
}
TCCR0B &= 0b11111000; //Zeros out last three bits
TCCR0B |= clock;
OCR0A = count;
TIMSK0 = 2;
TCNT0 = 0;
return 0;
}
ISR(TIMER0_COMPA_vect){
unsigned char adcreturn1;
unsigned char adcreturn2;
unsigned char send[50];
adcreturn1 = read_adc(5);
adcreturn2 = read_adc(6);
if(numelapsed == 3){
PORTC = ~PORTC;
numelapsed = 0;
SendStringUART("X Value: ");
itoa(adcreturn1, send, 2);
SendStringUART(send);
SendStringUART("\tY Value: ");
itoa(adcreturn2, send, 2);
SendStringUART(send);
SendStringUART("\n");
}else {
numelapsed++;
}
}
/** Main Function */
int main (void){
enum states{
setup,
idle,
running
} state = setup;
unsigned char debug;
unsigned char received;
while(1){
switch(state){
case setup:
initialize();
initializeTIMER0();
InitializeUART();
clearArray();
setTIMER0(5,120);
PORTB = 0b11000000;
state = idle;
SendStringUART("Initialized...\n");
break;
case idle:
cli();
if(debug != 1){
SendStringUART("Idling...\n");
debug = 1;
}
received = GetByteUART();
if (received == 's'){
state = running;
debug = 0;
break;
}
break;
case running:
sei();
received = GetByteUART();
if (received == 's'){
state = idle;
}
break;
}
}
}

View File

@@ -0,0 +1,54 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
<storageModule moduleId="org.eclipse.cdt.core.settings">
<cconfiguration id="cdt.managedbuild.toolchain.gnu.cross.base.1400812991">
<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.toolchain.gnu.cross.base.1400812991" moduleId="org.eclipse.cdt.core.settings" name="Default">
<externalSettings/>
<extensions>
<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
<extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
</extensions>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<configuration artifactName="Assignment 2" buildProperties="" description="" id="cdt.managedbuild.toolchain.gnu.cross.base.1400812991" name="Default" parent="org.eclipse.cdt.build.core.emptycfg">
<folderInfo id="cdt.managedbuild.toolchain.gnu.cross.base.1400812991.35170586" name="/" resourcePath="">
<toolChain id="cdt.managedbuild.toolchain.gnu.cross.base.1508668141" name="cdt.managedbuild.toolchain.gnu.cross.base" superClass="cdt.managedbuild.toolchain.gnu.cross.base">
<option id="cdt.managedbuild.option.gnu.cross.prefix.2079751801" name="Prefix" superClass="cdt.managedbuild.option.gnu.cross.prefix"/>
<option id="cdt.managedbuild.option.gnu.cross.path.163334932" name="Path" superClass="cdt.managedbuild.option.gnu.cross.path"/>
<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="cdt.managedbuild.targetPlatform.gnu.cross.107229620" isAbstract="false" osList="all" superClass="cdt.managedbuild.targetPlatform.gnu.cross"/>
<builder id="cdt.managedbuild.builder.gnu.cross.217779992" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Gnu Make Builder" superClass="cdt.managedbuild.builder.gnu.cross"/>
<tool id="cdt.managedbuild.tool.gnu.cross.c.compiler.926370999" name="Cross GCC Compiler" superClass="cdt.managedbuild.tool.gnu.cross.c.compiler">
<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1328834840" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
</tool>
<tool id="cdt.managedbuild.tool.gnu.cross.cpp.compiler.1744738686" name="Cross G++ Compiler" superClass="cdt.managedbuild.tool.gnu.cross.cpp.compiler"/>
<tool id="cdt.managedbuild.tool.gnu.cross.c.linker.243486500" name="Cross GCC Linker" superClass="cdt.managedbuild.tool.gnu.cross.c.linker">
<inputType id="cdt.managedbuild.tool.gnu.c.linker.input.569562329" superClass="cdt.managedbuild.tool.gnu.c.linker.input">
<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
<additionalInput kind="additionalinput" paths="$(LIBS)"/>
</inputType>
</tool>
<tool id="cdt.managedbuild.tool.gnu.cross.cpp.linker.2108641884" name="Cross G++ Linker" superClass="cdt.managedbuild.tool.gnu.cross.cpp.linker"/>
<tool id="cdt.managedbuild.tool.gnu.cross.archiver.1691225243" name="Cross GCC Archiver" superClass="cdt.managedbuild.tool.gnu.cross.archiver"/>
<tool id="cdt.managedbuild.tool.gnu.cross.assembler.858869286" name="Cross GCC Assembler" superClass="cdt.managedbuild.tool.gnu.cross.assembler">
<inputType id="cdt.managedbuild.tool.gnu.assembler.input.2083482904" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
</tool>
</toolChain>
</folderInfo>
</configuration>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
</cconfiguration>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<project id="Assignment 2.null.1988302796" name="Assignment 2"/>
</storageModule>
<storageModule moduleId="scannerConfiguration">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
<storageModule moduleId="org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings"/>
</cproject>

View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Assignment 2</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
<triggers>clean,full,incremental,</triggers>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
<triggers>full,incremental,</triggers>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.cdt.core.cnature</nature>
<nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
<nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,146 @@
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "dynamicArray.h"
/* param: s the string
param: num a pointer to double
returns: true (1) if s is a number else 0 or false.
postcondition: if it is a number, num will hold
the value of the number
*/
int isNumber(char *s, double *num)
{
char *end;
double returnNum;
if(strcmp(s, "0") == 0)
{
*num = 0;
return 1;
}
else
{
returnNum = strtod(s, &end);
/* If there's anythin in end, it's bad */
if((returnNum != 0.0) && (strcmp(end, "") == 0))
{
*num = returnNum;
return 1;
}
}
return 0; //if got here, it was not a number
}
/* param: stack the stack being manipulated
pre: the stack contains at least two elements
post: the top two elements are popped and
their sum is pushed back onto the stack.
*/
void add (struct DynArr *stack)
{
/* FIXME: You will write this function */
}
/* param: stack the stack being manipulated
pre: the stack contains at least two elements
post: the top two elements are popped and
their difference is pushed back onto the stack.
*/
void subtract(struct DynArr *stack)
{
/* FIXME: You will write this function */
}
/* param: stack the stack being manipulated
pre: the stack contains at least two elements
post: the top two elements are popped and
their quotient is pushed back onto the stack.
*/
void divide(struct DynArr *stack)
{
/* FIXME: You will write this function */
}
double calculate(int numInputTokens, char **inputString)
{
int i;
double result = 0.0;
char *s;
struct DynArr *stack;
//set up the stack
stack = createDynArr(20);
// start at 1 to skip the name of the calculator calc
for(i=1;i < numInputTokens;i++)
{
s = inputString[i];
// Hint: General algorithm:
// (1) Check if the string s is in the list of operators.
// (1a) If it is, perform corresponding operations.
// (1b) Otherwise, check if s is a number.
// (1b - I) If s is not a number, produce an error.
// (1b - II) If s is a number, push it onto the stack
if(strcmp(s, "+") == 0)
add(stack);
else if(strcmp(s,"-") == 0)
subtract(stack);
else if(strcmp(s, "/") == 0)
divide(stack);
else if(strcmp(s, "x") == 0)
/* FIXME: replace printf with your own function */
printf("Multiplying\n");
else if(strcmp(s, "^") == 0)
/* FIXME: replace printf with your own function */
printf("Power\n");
else if(strcmp(s, "^2") == 0)
/* FIXME: replace printf with your own function */
printf("Squaring\n");
else if(strcmp(s, "^3") == 0)
/* FIXME: replace printf with your own function */
printf("Cubing\n");
else if(strcmp(s, "abs") == 0)
/* FIXME: replace printf with your own function */
printf("Absolute value\n");
else if(strcmp(s, "sqrt") == 0)
/* FIXME: replace printf with your own function */
printf("Square root\n");
else if(strcmp(s, "exp") == 0)
/* FIXME: replace printf with your own function */
printf("Exponential\n");
else if(strcmp(s, "ln") == 0)
/* FIXME: replace printf with your own function */
printf("Natural Log\n");
else if(strcmp(s, "log") == 0)
/* FIXME: replace printf with your own function */
printf("Log\n");
else
{
// FIXME: You need to develop the code here (when s is not an operator)
// Remember to deal with special values ("pi" and "e")
}
} //end for
/* FIXME: You will write this part of the function (2 steps below)
* (1) Check if everything looks OK and produce an error if needed.
* (2) Store the final value in result and print it out.
*/
return result;
}
int main(int argc , char** argv)
{
// assume each argument is contained in the argv array
// argc-1 determines the number of operands + operators
if (argc == 1)
return 0;
calculate(argc,argv);
return 0;
}

View File

@@ -0,0 +1,291 @@
/* dynamicArray.c: Dynamic Array implementation. */
#include <assert.h>
#include <stdlib.h>
#include "dynamicArray.h"
struct DynArr
{
TYPE *data; /* pointer to the data array */
int size; /* Number of elements in the array */
int capacity; /* capacity ofthe array */
};
/* ************************************************************************
Dynamic Array Functions
************************************************************************ */
/* Initialize (including allocation of data array) dynamic array.
param: v pointer to the dynamic array
param: cap capacity of the dynamic array
pre: v is not null
post: internal data array can hold cap elements
post: v->data is not null
*/
void initDynArr(DynArr *v, int capacity)
{
assert(capacity > 0);
assert(v!= 0);
v->data = (TYPE *) malloc(sizeof(TYPE) * capacity);
assert(v->data != 0);
v->size = 0;
v->capacity = capacity;
}
/* Allocate and initialize dynamic array.
param: cap desired capacity for the dyn array
pre: none
post: none
ret: a non-null pointer to a dynArr of cap capacity
and 0 elements in it.
*/
DynArr* createDynArr(int cap)
{
assert(cap > 0);
DynArr *r = (DynArr *)malloc(sizeof( DynArr));
assert(r != 0);
initDynArr(r,cap);
return r;
}
/* Deallocate data array in dynamic array.
param: v pointer to the dynamic array
pre: none
post: d.data points to null
post: size and capacity are 0
post: the memory used by v->data is freed
*/
void freeDynArr(DynArr *v)
{
if(v->data != 0)
{
free(v->data); /* free the space on the heap */
v->data = 0; /* make it point to null */
}
v->size = 0;
v->capacity = 0;
}
/* Deallocate data array and the dynamic array ure.
param: v pointer to the dynamic array
pre: none
post: the memory used by v->data is freed
post: the memory used by d is freed
*/
void deleteDynArr(DynArr *v)
{
freeDynArr(v);
free(v);
}
/* Resizes the underlying array to be the size cap
param: v pointer to the dynamic array
param: cap the new desired capacity
pre: v is not null
post: v has capacity newCap
*/
void _dynArrSetCapacity(DynArr *v, int newCap)
{
/* FIXME: You will write this function */
}
/* Get the size of the dynamic array
param: v pointer to the dynamic array
pre: v is not null
post: none
ret: the size of the dynamic array
*/
int sizeDynArr(DynArr *v)
{
return v->size;
}
/* Adds an element to the end of the dynamic array
param: v pointer to the dynamic array
param: val the value to add to the end of the dynamic array
pre: the dynArry is not null
post: size increases by 1
post: if reached capacity, capacity is doubled
post: val is in the last utilized position in the array
*/
void addDynArr(DynArr *v, TYPE val)
{
/* FIXME: You will write this function */
}
/* Get an element from the dynamic array from a specified position
param: v pointer to the dynamic array
param: pos integer index to get the element from
pre: v is not null
pre: v is not empty
pre: pos < size of the dyn array and >= 0
post: no changes to the dyn Array
ret: value stored at index pos
*/
TYPE getDynArr(DynArr *v, int pos)
{
/* FIXME: You will write this function */
/* FIXME: you must change this return value */
return 1;
}
/* Put an item into the dynamic array at the specified location,
overwriting the element that was there
param: v pointer to the dynamic array
param: pos the index to put the value into
param: val the value to insert
pre: v is not null
pre: v is not empty
pre: pos >= 0 and pos < size of the array
post: index pos contains new value, val
*/
void putDynArr(DynArr *v, int pos, TYPE val)
{
/* FIXME: You will write this function */
}
/* Swap two specified elements in the dynamic array
param: v pointer to the dynamic array
param: i,j the elements to be swapped
pre: v is not null
pre: v is not empty
pre: i, j >= 0 and i,j < size of the dynamic array
post: index i now holds the value at j and index j now holds the value at i
*/
void swapDynArr(DynArr *v, int i, int j)
{
/* FIXME: You will write this function */
}
/* Remove the element at the specified location from the array,
shifts other elements back one to fill the gap
param: v pointer to the dynamic array
param: idx location of element to remove
pre: v is not null
pre: v is not empty
pre: idx < size and idx >= 0
post: the element at idx is removed
post: the elements past idx are moved back one
*/
void removeAtDynArr(DynArr *v, int idx)
{
/* FIXME: You will write this function */
}
/* ************************************************************************
Stack Interface Functions
************************************************************************ */
/* Returns boolean (encoded in an int) demonstrating whether or not the
dynamic array stack has an item on it.
param: v pointer to the dynamic array
pre: the dynArr is not null
post: none
ret: 1 if empty, otherwise 0
*/
int isEmptyDynArr(DynArr *v)
{
/* FIXME: You will write this function */
/* FIXME: You will change this return value*/
return 1;
}
/* Push an element onto the top of the stack
param: v pointer to the dynamic array
param: val the value to push onto the stack
pre: v is not null
post: size increases by 1
if reached capacity, capacity is doubled
val is on the top of the stack
*/
void pushDynArr(DynArr *v, TYPE val)
{
/* FIXME: You will write this function */
}
/* Returns the element at the top of the stack
param: v pointer to the dynamic array
pre: v is not null
pre: v is not empty
post: no changes to the stack
*/
TYPE topDynArr(DynArr *v)
{
/* FIXME: You will write this function */
/* FIXME: You will change this return value*/
return 1;
}
/* Removes the element on top of the stack
param: v pointer to the dynamic array
pre: v is not null
pre: v is not empty
post: size is decremented by 1
the top has been removed
*/
void popDynArr(DynArr *v)
{
/* FIXME: You will write this function */
}
/* ************************************************************************
Bag Interface Functions
************************************************************************ */
/* Returns boolean (encoded as an int) demonstrating whether or not
the specified value is in the collection
true = 1
false = 0
param: v pointer to the dynamic array
param: val the value to look for in the bag
pre: v is not null
pre: v is not empty
post: no changes to the bag
*/
int containsDynArr(DynArr *v, TYPE val)
{
/* FIXME: You will write this function */
/* FIXME: You will change this return value */
return 1;
}
/* Removes the first occurrence of the specified value from the collection
if it occurs
param: v pointer to the dynamic array
param: val the value to remove from the array
pre: v is not null
pre: v is not empty
post: val has been removed
post: size of the bag is reduced by 1
*/
void removeDynArr(DynArr *v, TYPE val)
{
/* FIXME: You will write this function */
}

View File

@@ -0,0 +1,41 @@
/* dynamicArray.h : Dynamic Array implementation. */
#include<math.h>
#ifndef DYNAMIC_ARRAY_INCLUDED
#define DYNAMIC_ARRAY_INCLUDED 1
# ifndef TYPE
# define TYPE double
# define TYPE_SIZE sizeof(double)
# endif
# ifndef EQ
# define EQ(A, B) (fabs(A - B) < 10e-7)
# endif
typedef struct DynArr DynArr;
/* Dynamic Array Functions */
DynArr *createDynArr(int cap);
void deleteDynArr(DynArr *v);
int sizeDynArr(DynArr *v);
void addDynArr(DynArr *v, TYPE val);
TYPE getDynArr(DynArr *v, int pos);
void putDynArr(DynArr *v, int pos, TYPE val);
void swapDynArr(DynArr *v, int i, int j);
void removeAtDynArr(DynArr *v, int idx);
/* Stack interface. */
int isEmptyDynArr(DynArr *v);
void pushDynArr(DynArr *v, TYPE val);
TYPE topDynArr(DynArr *v);
void popDynArr(DynArr *v);
/* Bag Interface */
int containsDynArr(DynArr *v, TYPE val);
void removeDynArr(DynArr *v, TYPE val);
#endif

View File

@@ -0,0 +1,23 @@
all: calc testda
calc: dynamicArray.o calc.o
gcc -g -Wall -std=c99 -o calc dynamicArray.o calc.o -lm
testda: dynamicArray.o testDynArray.o
gcc -g -Wall -std=c99 -o testda dynamicArray.o testDynArray.o
calc.o: calc.c dynamicArray.h
gcc -g -Wall -std=c99 -c calc.c
testDynArray.o: testDynArray.c dynamicArray.h
gcc -g -Wall -std=c99 -c testDynArray.c
dynamicArray.o: dynamicArray.c dynamicArray.h
gcc -g -Wall -std=c99 -c dynamicArray.c
clean:
rm dynamicArray.o
rm calc.o
rm testDynArray.o
rm calc
rm testda

View File

@@ -0,0 +1,87 @@
/* testDynArray.c
* This file is used for testing the dynamicArray.c file.
* This test suite is by no means complete or thorough.
* More testing is needed on your own.
*/
#include <stdio.h>
#include <stdlib.h>
#include "dynamicArray.h"
void assertTrue(int predicate, char *message)
{
printf("%s: ", message);
if (predicate)
printf("PASSED\n");
else
printf("FAILED\n");
}
// this main function contains some
int main(int argc, char* argv[]){
DynArr *dyn;
dyn = createDynArr(2);
printf("\n\nTesting addDynArr...\n");
addDynArr(dyn, 3);
addDynArr(dyn, 4);
addDynArr(dyn, 10);
addDynArr(dyn, 5);
addDynArr(dyn, 6);
printf("The array's content: [3,4,10,5,6]\n");
assertTrue(EQ(getDynArr(dyn, 0), 3), "Test 1st element == 3");
assertTrue(EQ(getDynArr(dyn, 1), 4), "Test 2nd element == 4");
assertTrue(EQ(getDynArr(dyn, 2), 10), "Test 3rd element == 10");
assertTrue(EQ(getDynArr(dyn, 3), 5), "Test 4th element == 5");
assertTrue(EQ(getDynArr(dyn, 4), 6), "Test 5th element == 6");
assertTrue(sizeDynArr(dyn) == 5, "Test size = 5");
printf("\n\nTesting putDynArr...\nCalling putDynArr(dyn, 2, 7)\n");
putDynArr(dyn, 2, 7);
printf("The array's content: [3,4,7,5,6]\n");
assertTrue(EQ(getDynArr(dyn, 2), 7), "Test 3rd element == 7");
assertTrue(sizeDynArr(dyn) == 5, "Test size = 5");
printf("\n\nTesting swapDynArr...\nCalling swapDynArr(dyn, 2, 4)\n");
swapDynArr(dyn, 2, 4);
printf("The array's content: [3,4,6,5,7]\n");
assertTrue(EQ(getDynArr(dyn, 2), 6), "Test 3rd element == 6");
assertTrue(EQ(getDynArr(dyn, 4), 7), "Test 5th element == 7");
printf("\n\nTesting removeAtDynArr...\nCalling removeAtDynArr(dyn, 1)\n");
removeAtDynArr(dyn, 1);
printf("The array's content: [3,6,5,7]\n");
assertTrue(EQ(getDynArr(dyn, 0), 3), "Test 1st element == 3");
assertTrue(EQ(getDynArr(dyn, 3), 7), "Test 4th element == 7");
assertTrue(sizeDynArr(dyn) == 4, "Test size = 4");
printf("\n\nTesting stack interface...\n");
printf("The stack's content: [3,6,5,7] <- top\n");
assertTrue(!isEmptyDynArr(dyn), "Testing isEmptyDynArr");
assertTrue(EQ(topDynArr(dyn), 7), "Test topDynArr == 7");
popDynArr(dyn);
printf("Poping...\nThe stack's content: [3,6,5] <- top\n");
assertTrue(EQ(topDynArr(dyn), 5), "Test topDynArr == 5");
pushDynArr(dyn, 9);
printf("Pushing 9...\nThe stack's content: [3,6,5,9] <- top\n");
assertTrue(EQ(topDynArr(dyn), 9), "Test topDynArr == 9");
printf("\n\nTesting bag interface...\n");
printf("The bag's content: [3,6,5,9]\n");
assertTrue(containsDynArr(dyn, 3), "Test containing 3");
assertTrue(containsDynArr(dyn, 6), "Test containing 6");
assertTrue(containsDynArr(dyn, 5), "Test containing 5");
assertTrue(containsDynArr(dyn, 9), "Test containing 9");
assertTrue(!containsDynArr(dyn, 7), "Test not containing 7");
removeDynArr(dyn, 3);
printf("Removing 3...\nThe stack's content: [6,5,9]\n");
assertTrue(!containsDynArr(dyn, 3), "Test not containing 3");
return 0;
}

View File

@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
<storageModule moduleId="org.eclipse.cdt.core.settings">
<cconfiguration id="cdt.managedbuild.toolchain.gnu.base.698156890">
<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.toolchain.gnu.base.698156890" moduleId="org.eclipse.cdt.core.settings" name="Default">
<externalSettings/>
<extensions>
<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
<extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
</extensions>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<configuration buildProperties="" id="cdt.managedbuild.toolchain.gnu.base.698156890" name="Default" parent="org.eclipse.cdt.build.core.emptycfg">
<folderInfo id="cdt.managedbuild.toolchain.gnu.base.698156890.240830756" name="/" resourcePath="">
<toolChain id="cdt.managedbuild.toolchain.gnu.base.884460920" name="cdt.managedbuild.toolchain.gnu.base" superClass="cdt.managedbuild.toolchain.gnu.base">
<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="cdt.managedbuild.target.gnu.platform.base.1378688406" name="Debug Platform" osList="linux,hpux,aix,qnx" superClass="cdt.managedbuild.target.gnu.platform.base"/>
<builder id="cdt.managedbuild.target.gnu.builder.base.148477352" managedBuildOn="false" name="Gnu Make Builder.Default" superClass="cdt.managedbuild.target.gnu.builder.base"/>
<tool id="cdt.managedbuild.tool.gnu.archiver.base.888444366" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.base"/>
<tool id="cdt.managedbuild.tool.gnu.cpp.compiler.base.495720762" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.base"/>
<tool id="cdt.managedbuild.tool.gnu.c.compiler.base.479463272" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.base"/>
<tool id="cdt.managedbuild.tool.gnu.c.linker.base.1889370225" name="GCC C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.base"/>
<tool id="cdt.managedbuild.tool.gnu.cpp.linker.base.475736613" name="GCC C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.base"/>
<tool id="cdt.managedbuild.tool.gnu.assembler.base.516392826" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.base"/>
</toolChain>
</folderInfo>
</configuration>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
</cconfiguration>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<project id="assign5.null.1525443262" name="assign5"/>
</storageModule>
<storageModule moduleId="scannerConfiguration">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
</cproject>

View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>assign5</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
<triggers>clean,full,incremental,</triggers>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
<triggers>full,incremental,</triggers>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.cdt.core.cnature</nature>
<nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
<nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,27 @@
all: prog1 prog2
prog1: dynamicArray.o main.o toDoList.o
gcc -g -Wall -std=c99 -o prog1 dynamicArray.o toDoList.o main.o
prog2: dynamicArray.o main2.o toDoList.o
gcc -g -Wall -std=c99 -o prog2 dynamicArray.o toDoList.o main2.o
main.o: main.c dynamicArray.h type.h toDoList.h
gcc -g -Wall -std=c99 -c main.c
main2.o: main2.c dynamicArray.h type.h toDoList.h
gcc -g -Wall -std=c99 -c main2.c
dynamicArray.o: dynamicArray.c dynamicArray.h
gcc -g -Wall -std=c99 -c dynamicArray.c
toDoList.o: toDoList.c toDoList.h
gcc -g -Wall -std=c99 -c toDoList.c
clean:
rm dynamicArray.o
rm toDoList.o
rm main.o
rm main2.o
rm prog1
rm prog2

View File

@@ -0,0 +1,572 @@
/* dynArr.c: Dynamic Array implementation. */
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include "dynamicArray.h"
struct DynArr
{
TYPE *data; /* pointer to the data array */
int size; /* Number of elements in the array */
int capacity; /* capacity ofthe array */
};
struct bag
{
struct DynArr *dynArr;
};
/* ************************************************************************
Dynamic Array Functions
************************************************************************ */
/* Initialize (including allocation of data array) dynamic array.
param: v pointer to the dynamic array
param: cap capacity of the dynamic array
pre: v is not null
post: internal data array can hold capacity elements
post: v->data is not null
*/
void _initDynArr(DynArr *v, int capacity)
{
assert(capacity > 0);
assert(v!= 0);
v->data = malloc(sizeof(TYPE) * capacity);
assert(v->data != 0);
v->size = 0;
v->capacity = capacity;
}
/* Allocate and initialize dynamic array.
param: cap desired capacity for the dyn array
pre: none
post: none
ret: a non-null pointer to a dynArr of cap capacity
and 0 elements in it.
*/
DynArr* createDynArr(int cap)
{
DynArr *r;
assert(cap > 0);
r = malloc(sizeof( DynArr));
assert(r != 0);
_initDynArr(r,cap);
return r;
}
/* Deallocate data array in dynamic array.
param: v pointer to the dynamic array
pre: v is not null
post: d.data points to null
post: size and capacity are 0
post: the memory used by v->data is freed
*/
void freeDynArr(DynArr *v)
{
assert(v!=0);
if(v->data != 0)
{
free(v->data); /* free the space on the heap */
v->data = 0; /* make it point to null */
}
v->size = 0;
v->capacity = 0;
}
/* Deallocate data array and the dynamic array ure.
param: v pointer to the dynamic array
pre: v is not null
post: the memory used by v->data is freed
post: the memory used by d is freed
*/
void deleteDynArr(DynArr *v)
{
assert (v!= 0);
freeDynArr(v);
free(v);
}
/* Resizes the underlying array to be the size cap
param: v pointer to the dynamic array
param: cap the new desired capacity
pre: v is not null
post: v has capacity newCap
*/
void _dynArrSetCapacity(DynArr *v, int newCap)
{
int i;
TYPE *oldData;
int oldSize = v->size;
oldData = v->data;
printf("========Resizing========\n");
/* Create a new dyn array with larger underlying array */
_initDynArr(v, newCap);
for(i = 0; i < oldSize; i++){
v->data[i] = oldData[i];
}
v->size = oldSize;
/* Remember, init did not free the original data */
free(oldData);
#ifdef ALTERNATIVE
int i;
/* Create a new underlying array*/
TYPE *newData = (TYPE*)malloc(sizeof(TYPE)*newCap);
assert(newData != 0);
/* copy elements to it */
for(i = 0; i < v->size; i++)
{
newData[i] = v->data[i];
}
/* Delete the oldunderlying array*/
free(v->data);
/* update capacity and size and data*/
v->data = newData;
v->capacity = newCap;struct Task {
char description[TASK_DESC_SIZE]; /* description of the task */
int priority; /* task priority */
};
#endif
}
/* Get the size of the dynamic array
param: v pointer to the dynamic array
pre: v is not null
post: none
ret: the size of the dynamic array
*/
int sizeDynArr(DynArr *v)
{
assert(v!=0);
return v->size;
}
/* Adds an element to the end of the dynamic array
param: v pointer to the dynamic array
param: val the value to add to the end of the dynamic array
pre: the dynArry is not null
post: size increases by 1
post: if reached capacity, capacity is doubled
post: val is in the last utilized position in the array
*/
void addDynArr(DynArr *v, TYPE val)
{
assert(v!=0);
/* Check to see if a resize is necessary */
if(v->size >= v->capacity)
_dynArrSetCapacity(v, 2 * v->capacity);
v->data[v->size] = val;
v->size++;
}
/* Get an element from the dynamic array from a specified position
param: v pointer to the dynamic array
param: pos integer index to get the element from
pre: v is not null
pre: v is not empty
pre: pos < size of the dyn array and >= 0
post: no changes to the dyn Array
ret: value stored at index pos
*/
TYPE getDynArr(DynArr *v, int pos)
{
assert(v!=0);
assert(pos < v->size);
assert(pos >= 0);
return v->data[pos];
}
/* Put an item into the dynamic array at the specified location,
overwriting the element that was there
param: v pointer to the dynamic array
param: pos the index to put the value into
param: val the value to insert
pre: v is not null
pre: v is not empty
pre: pos >= 0 and pos < size of the array
post: index pos contains new value, val
*/
void putDynArr(DynArr *v, int pos, TYPE val)
{
assert(v!=0);
assert(pos < v->size);
assert(pos >= 0);
v->data[pos] = val;
}
/* Swap two specified elements in the dynamic array
param: v pointer to the dynamic array
param: i,j the elements to be swapped
pre: v is not null
pre: v is not empty
pre: i, j >= 0 and i,j < size of the dynamic array
post: index i now holds the value at j and index j now holds the value at i
*/
void swapDynArr(DynArr *v, int i, int j)
{
TYPE temp;
assert(v!=0);
assert(i < v->size);
assert(j < v->size);
assert(i >= 0);
assert(j >= 0);
temp = v->data[i];
v->data[i] = v->data[j];
v->data[j] = temp;
}
/* Remove the element at the specified location from the array,
shifts other elements back one to fill the gap
param: v pointer to the dynamic array
param: idx location of element to remove
pre: v is not null
pre: v is not empty
pre: idx < size and idx >= 0
post: the element at idx is removed
post: the elements past idx are moved back one
*/
void removeAtDynArr(DynArr *v, int idx){
int i;
assert(v!= 0);
assert(idx < v->size);
assert(idx >= 0);
//Move all elements up
for(i = idx; i < v->size-1; i++){
v->data[i] = v->data[i+1];
}
v->size--;
}
/* ************************************************************************
Stack Interface Functions
************************************************************************ */
/* Returns boolean (encoded in an int) demonstrating whether or not the
dynamic array stack has an item on it.
param: v pointer to the dynamic array
pre: v is not null
post: none
ret: >0 if empty, otherwise 0
*/
int isEmptyDynArr(DynArr *v)
{
assert(v!= 0);
return !(v->size);
/* alternatively:
if(v->size == 0)
return 1;
else return 0;
*/
}
/* Push an element onto the top of the stack
param: v pointer to the dynamic array
param: val the value to push onto the stack
pre: v is not null
post: size increases by 1
if reached capacity, capacity is doubled
val is on the top of the stack
*/
void pushDynArr(DynArr *v, TYPE val)
{
assert(v!=0);
addDynArr(v, val);
}
/* Returns the element at the top of the stack
param: v pointer to the dynamic array
pre: v is not null
pre: v is not empty
post: no changes to the stack
*/
TYPE topDynArr(DynArr *v)
{
assert(v!=0);
assert(!isEmptyDynArr(v));
return v->data[v->size-1];
}
/* Removes the element on top of the stack
param: v pointer to the dynamic array
pre: v is not null
pre: v is not empty
post: size is decremented by 1
the top has been removed
*/
void popDynArr(DynArr *v)
{
assert(v!=0);
assert(! isEmptyDynArr(v));
v->size--;
}
/* ************************************************************************
Bag Interface Functions
************************************************************************ */
/* Returns boolean (encoded as an int) demonstrating whether or not
the specified value is in the collection
true = 1
false = 0
param: v pointer to the dynamic array
param: val the value to look for in the bag
pre: v is not null
pre: v is not empty
post: no changes to the bag
*/
int containsDynArr(DynArr *v, TYPE val)
{
int i = 0;
assert(v!=0);
assert(!isEmptyDynArr(v));
for(i = 0; i < sizeDynArr(v); i++)
if(compare(v->data[i], val) == 0)
return 1;
return 0;
}
/* Removes the first occurrence of the specified value from the collection
if it occurs
param: v pointer to the dynamic array
param: val the value to remove from the array
pre: v is not null
pre: v is not empty
post: val has been removed
post: size of the bag is reduced by 1
*/
void removeDynArr(DynArr *v, TYPE val)
{
int i = 0;
assert(v!=0);
assert(!isEmptyDynArr(v));
assert(containsDynArr(v,val)); /* Design decision: Error if they try to remove something not in there! */
for(i = 0; i < sizeDynArr(v); i++)
if(compare(v->data[i], val) == 0)
{
removeAtDynArr(v,i);
break;
}
}
/* Copy elements from a dynamic array to another dynamic array
param: source pointer to the source dynamic array
param: destination pointer to the destination dynamic array
pre: s is not null and s is not empty
post: destination is initialized
post: the elements from source are copied to destination
*/
void copyDynArr(DynArr *source, DynArr *destination)
{
int i;
assert(source->size > 0);
_initDynArr(destination, source->capacity);
/* copy elements to destination array */
for(i = 0; i < source->size; i++)
destination->data[i] = source->data[i];
destination->size = source->size;
}
/* ************************************************************************
Heap-based Priority Queue Implementation
************************************************************************ */
/* internal function prototypes */
int _smallerIndexHeap(DynArr *heap, int i, int j);
void _adjustHeap(DynArr *heap, int max, int pos);
/* Get the index of the smaller node between two nodes in a heap
param: heap pointer to the heap
param: i index of one node
param: j index of other node
pre: i < size and j < size
ret: the index of the smaller node
*/
int _smallerIndexHeap(DynArr *heap, int i, int j)
{
/* FIXME */
/* DONE */
assert(i < heap->size);
assert(j < heap->size);
if(((struct Task*)heap->data[i])->priority > ((struct Task*)heap->data[j])->priority){
return j;
}else{
return i;
}
}
/* Get the first node, which has the min priority, from the heap
param: heap pointer to the heap
pre: heap is not empty
ret: value of first node
*/
TYPE getMinHeap(DynArr *heap)
{
/* FIXME */
/* DONE */
assert(heap != 0);
return heap->data[0];
}
/* Add a node to the heap
param: heap pointer to the heap
param: node node to be added to the heap
pre: heap is not null
post: node is added to the heap
*/
void addHeap(DynArr *heap, TYPE val)
{
/* FIXME */
/* DONE */
int pos;
int parent;
assert(heap != 0);
addDynArr(heap, val);
pos = sizeDynArr(heap)-1;
while(pos != 0){
parent = (pos -1)/2;
if(((struct Task*)heap->data[pos])->priority < ((struct Task*)heap->data[parent])->priority){
swapDynArr(heap, pos, parent);
pos = parent;
}else{
return;
}
}
}
/* Adjust heap to maintain heap property
param: heap pointer to the heap
param: max index to adjust up to (but not included)
param: pos position index where the adjustment starts
pre: max <= size
post: heap property is maintained for nodes from index pos to index max-1 (ie. up to, but not including max)
*/
void _adjustHeap(DynArr *heap, int max, int pos)
{
/* FIXME */
/* DONE */
int leftChild = 2*pos + 1;
int rightChild = 2*pos + 2;
if(rightChild < max){
int smallestindex = _smallerIndexHeap(heap, leftChild, rightChild);
if(((struct Task*)heap->data[pos])->priority > ((struct Task*)heap->data[smallestindex])->priority){
swapDynArr(heap, pos, smallestindex);
_adjustHeap(heap, max, smallestindex);
}
}else if(leftChild < max){
if(((struct Task*)heap->data[pos])->priority > ((struct Task*)heap->data[leftChild])->priority){
swapDynArr(heap, pos, leftChild);
_adjustHeap(heap, max, leftChild);
}
}
}
/* Remove the first node, which has the min priority, from the heap
param: heap pointer to the heap
pre: heap is not empty
post: the first node is removed from the heap
*/
void removeMinHeap(DynArr *heap)
{
/* FIXME */
/* DONE */
int last = sizeDynArr(heap)-1;
//assert(last !=0);
putDynArr(heap, 0, getDynArr(heap, last));
removeAtDynArr(heap, last);
_adjustHeap(heap, last, 0);
}
/* builds a heap from an arbitrary dynArray
param: v dynamicArray
pre: v is not empty
post: v is a proper heap
*/
void _buildHeap(DynArr *heap)
{
/* FIXME */
/* DONE */
int max = sizeDynArr(heap);
for(int i = max/2 -1 ; i >=0 ; i--){
_adjustHeap(heap, max, i);
}
}
/*
In-place sort of the heap
param: heap pointer to the heap
pre: heap is not empty
post: the dynArr is in reverse sorted order
*/
void sortHeap(DynArr *heap)
{
/* FIXME */
/* DONE */
_buildHeap(heap);
for(int i = sizeDynArr(heap)-1 ; i > 0 ; i--){
swapDynArr(heap, 0, i);
_adjustHeap(heap, i, 0);
}
}

View File

@@ -0,0 +1,52 @@
/* dynArr.h : Dynamic Array implementation. */
#ifndef DYNAMIC_ARRAY_INCLUDED
#define DYNAMIC_ARRAY_INCLUDED 1
#include "type.h"
# ifndef TYPE
# define TYPE void*
# endif
/* function used to compare two TYPE values to each other, define this in your compare.c file */
int compare(TYPE left, TYPE right);
/* function used to print TYPE values, define this in your compare.c file */
void print_type(TYPE curval);
typedef struct DynArr DynArr;
struct bag;
/* Dynamic Array Functions */
DynArr *createDynArr(int cap);
void deleteDynArr(DynArr *v);
int sizeDynArr(DynArr *v);
void addDynArr(DynArr *v, TYPE val);
TYPE getDynArr(DynArr *v, int pos);
void putDynArr(DynArr *v, int pos, TYPE val);
void swapDynArr(DynArr *v, int i, int j);
void removeAtDynArr(DynArr *v, int idx);
/* Stack interface. */
int isEmptyDynArr(DynArr *v);
void pushDynArr(DynArr *v, TYPE val);
TYPE topDynArr(DynArr *v);
void popDynArr(DynArr *v);
/* Bag Interface */
int containsDynArr(DynArr *v, TYPE val);
void removeDynArr(DynArr *v, TYPE val);
/* Heap-based Priority Queue Interface */
TYPE getMinHeap(DynArr *heap);
void addHeap(DynArr *heap, TYPE node);
void removeMinHeap(DynArr *heap);
void sortHeap(DynArr *heap);
/* Utility function*/
void copyDynArr(DynArr *source, DynArr *destination);
#endif

View File

@@ -0,0 +1,164 @@
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "toDoList.h"
int main (int argc, const char * argv[])
{
Task* newTask;
Task* firstTask;
char desc[TASK_DESC_SIZE], filename[50], *nlptr;
int priority;
char cmd = ' ';
FILE *filePointer;
DynArr* mainList = createDynArr(10);
printf("\n\n** TO-DO LIST APPLICATION **\n\n");
do
{
printf("Press:\n"
"'l' to load to-do list from a file\n"
"'s' to save to-do list to a file\n"
"'a' to add a new task\n"
"'g' to get the first task\n"
"'r' to remove the first task\n"
"'p' to print the list\n"
"'e' to exit the program\n"
);
/* get input command (from the keyboard) */
cmd = getchar();
/* clear the trailing newline character */
while (getchar() != '\n');
switch (cmd)
{
case 'a': /* add new task */
printf("Please enter the task description: ");
/* get task description from user input (from keyboard) */
if (fgets(desc, sizeof(desc), stdin) != NULL)
{
/* remove trailing newline character */
nlptr = strchr(desc, '\n');
if (nlptr)
*nlptr = '\0';
}
/* get task priority from user input (from keyboard) */
do {
printf("Please enter the task priority (0-999): ");
scanf("%d", &priority);
} while(!(priority >= 0 && priority <= 999));
/* clear the trailing newline character */
while (getchar() != '\n');
/* create task and add the task to the heap */
newTask = createTask(priority, desc);
addHeap(mainList, newTask);
printf("The task '%s' has been added to your to-do list.\n\n", desc);
break;
case 'g': /* get the first task */
if (sizeDynArr(mainList) > 0)
{
firstTask = (Task*)getMinHeap(mainList);
printf("Your first task is: %s\n\n", firstTask->description);
}
else
printf("Your to-do list is empty!\n\n");
break;
case 'r': /* remove the first task */
if (sizeDynArr(mainList) > 0)
{
firstTask = (Task*)getMinHeap(mainList);
removeMinHeap(mainList);
printf("Your first task '%s' has been removed from the list.\n\n", firstTask->description);
/* need to free up memory occupied by this task */
free(firstTask);
}
else
printf("Your to-do list is empty!\n\n");
break;
case 'p': /* print the list */
if (sizeDynArr(mainList) > 0)
{
printList(mainList);
}
else
printf("Your to-do list is empty!\n\n");
break;
case 's': /* save the list to file */
if (sizeDynArr(mainList) > 0)
{
/* get filename from user input (from keyboard) */
printf("Please enter the filename: ");
if (fgets(filename, sizeof(filename), stdin) != NULL)
{
/* remove trailing newline character */
nlptr = strchr(filename, '\n');
if (nlptr)
*nlptr = '\0';
}
/* open the file */
filePointer = fopen(filename, "w");
if (filePointer == NULL) {
fprintf(stderr, "Cannot open %s\n", filename);
break;
}
/* save the list to the file */
saveList(mainList, filePointer);
/* close the file */
fclose(filePointer);
printf("The list has been saved into the file successfully.\n\n");
}
else
printf("Your to-do list is empty!\n\n");
break;
case 'l': /* load the list from the file */
printf("Please enter the filename: ");
/* get filename from user input (from keyboard) */
if (fgets(filename, sizeof(filename), stdin) != NULL)
{
/* remove trailing newline character */
nlptr = strchr(filename, '\n');
if (nlptr)
*nlptr = '\0';
}
/* open the file */
filePointer = fopen(filename, "r");
if (filePointer == NULL) {
fprintf(stderr, "Cannot open %s\n", filename);
break;
}
/* load the list from the file */
loadList(mainList, filePointer);
/* close the file */
fclose(filePointer);
printf("The list has been loaded from file successfully.\n\n");
break;
case 'e': /* exit the program */
printf("Bye!\n\n");
break;
default:
printf("What is your command anyway?\n\n" );
break;
}
}
while(cmd != 'e');
/* delete the list */
deleteList(mainList);
return 0;
}

View File

@@ -0,0 +1,74 @@
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "dynamicArray.h"
#include "toDoList.h"
/* NOTE: Switch between TESTSORT and TESTHEAP to test either the heap sort algoritm or the heap operations*/
#define TESTHEAP
int main(int argc, const char * argv[])
{
Task *task1, *task2, *task3, *task4, *task5, *task6, *task7, *task8, *task9, *task10;
DynArr *mainList;
int i;
mainList = createDynArr(10);
/* create tasks */
task1 = createTask(9, "task 1");
task2 = createTask(3, "task 2");
task3 = createTask(2, "task 3");
task4 = createTask(4, "task 4");
task5 = createTask(5, "task 5");
task6 = createTask(7, "task 6");
task7 = createTask(8, "task 7");
task8 = createTask(6, "task 8");
task9 = createTask(1, "task 9");
task10 = createTask(0, "task 10");
/* add tasks to the dynamic array */
addHeap(mainList, task1);
addHeap(mainList, task2);
addHeap(mainList, task3);
addHeap(mainList, task4);
addHeap(mainList, task5);
addHeap(mainList, task6);
addHeap(mainList, task7);
addHeap(mainList, task8);
addHeap(mainList, task9);
addHeap(mainList, task10);
#ifdef TESTHEAP
for(i = 0; i < sizeDynArr(mainList);i++)
printf("DynArr[%d] = %d\n", i, ((Task*)getDynArr(mainList,i))->priority);
while(!isEmptyDynArr(mainList))
{
Task* v;
v = getMinHeap(mainList);
printf("Val = %s___%d\n", v->description, v->priority);
removeMinHeap(mainList);
}
#endif
#ifdef TESTSORT
printf("Before Sort Called \n");
for(i = 0; i < sizeDynArr(mainList);i++)
printf("DynArr[%d] = %d\n", i, ((Task*)getDynArr(mainList,i))->priority);
/* sort tasks */
sortHeap(mainList);
printf("After Sort Called \n");
/* print sorted tasks from the dynamic array */
for(i = 0; i < sizeDynArr(mainList);i++)
printf("DynArr[%d] = %d\n", i, ((Task*)getDynArr(mainList,i))->priority);
return 0;
#endif
}

View File

@@ -0,0 +1,223 @@
flip ~/cs261/as5/todo_list 605% ./prog
** TO-DO LIST APPLICATION **
Press:
'l' to load to-do list from a file
's' to save to-do list to a file
'a' to add a new task
'g' to get the first task
'r' to remove the first task
'p' to print the list
'e' to exit the program
g
Your to-do list is empty!
Press:
'l' to load to-do list from a file
's' to save to-do list to a file
'a' to add a new task
'g' to get the first task
'r' to remove the first task
'p' to print the list
'e' to exit the program
a
Please enter the task description: do assignment 5
Please enter the task priority (0-999): 3
The task 'do assignment 5' has been added to your to-do list.
Press:
'l' to load to-do list from a file
's' to save to-do list to a file
'a' to add a new task
'g' to get the first task
'r' to remove the first task
'p' to print the list
'e' to exit the program
a
Please enter the task description: study heap-based priority queue
Please enter the task priority (0-999): 1
The task 'study heap-based priority queue' has been added to your to-do list.
Press:
'l' to load to-do list from a file
's' to save to-do list to a file
'a' to add a new task
'g' to get the first task
'r' to remove the first task
'p' to print the list
'e' to exit the program
a
Please enter the task description: review trees for Final exam
Please enter the task priority (0-999): 101
The task 'review trees for Final exam' has been added to your to-do list.
Press:
'l' to load to-do list from a file
's' to save to-do list to a file
'a' to add a new task
'g' to get the first task
'r' to remove the first task
'p' to print the list
'e' to exit the program
g
Your first task is: study heap-based priority queue
Press:
'l' to load to-do list from a file
's' to save to-do list to a file
'a' to add a new task
'g' to get the first task
'r' to remove the first task
'p' to print the list
'e' to exit the program
a
Please enter the task description: take a nap
Please enter the task priority (0-999): 0
The task 'take a nap' has been added to your to-do list.
Press:
'l' to load to-do list from a file
's' to save to-do list to a file
'a' to add a new task
'g' to get the first task
'r' to remove the first task
'p' to print the list
'e' to exit the program
s
Please enter the filename: todo.txt
The list has been saved into the file successfully.
Press:
'l' to load to-do list from a file
's' to save to-do list to a file
'a' to add a new task
'g' to get the first task
'r' to remove the first task
'p' to print the list
'e' to exit the program
e
Bye!
============
flip ~/cs261/as5/todo_list 613% ./prog
** TO-DO LIST APPLICATION **
Press:
'l' to load to-do list from a file
's' to save to-do list to a file
'a' to add a new task
'g' to get the first task
'r' to remove the first task
'p' to print the list
'e' to exit the program
g
Your to-do list is empty!
Press:
'l' to load to-do list from a file
's' to save to-do list to a file
'a' to add a new task
'g' to get the first task
'r' to remove the first task
'p' to print the list
'e' to exit the program
l
Please enter the filename: todo.txt
The list has been loaded from file successfully.
Press:
'l' to load to-do list from a file
's' to save to-do list to a file
'a' to add a new task
'g' to get the first task
'r' to remove the first task
'p' to print the list
'e' to exit the program
g
Your first task is: take a nap
Press:
'l' to load to-do list from a file
's' to save to-do list to a file
'a' to add a new task
'g' to get the first task
'r' to remove the first task
'p' to print the list
'e' to exit the program
r
Your first task 'take a nap' has been removed from the list.
Press:
'l' to load to-do list from a file
's' to save to-do list to a file
'a' to add a new task
'g' to get the first task
'r' to remove the first task
'p' to print the list
'e' to exit the program
p
study heap-based priority queue
do assignment 5
review trees for Final exam
Press:
'l' to load to-do list from a file
's' to save to-do list to a file
'a' to add a new task
'g' to get the first task
'r' to remove the first task
'p' to print the list
'e' to exit the program
r
Your first task 'study heap-based priority queue' has been removed from the list.
Press:
'l' to load to-do list from a file
's' to save to-do list to a file
'a' to add a new task
'g' to get the first task
'r' to remove the first task
'p' to print the list
'e' to exit the program
r
Your first task 'do assignment 5' has been removed from the list.
Press:
'l' to load to-do list from a file
's' to save to-do list to a file
'a' to add a new task
'g' to get the first task
'r' to remove the first task
'p' to print the list
'e' to exit the program
r
Your first task 'review trees for Final exam' has been removed from the list.
Press:
'l' to load to-do list from a file
's' to save to-do list to a file
'a' to add a new task
'g' to get the first task
'r' to remove the first task
'p' to print the list
'e' to exit the program
r
Your to-do list is empty!
Press:
'l' to load to-do list from a file
's' to save to-do list to a file
'a' to add a new task
'g' to get the first task
'r' to remove the first task
'p' to print the list
'e' to exit the program
e
Bye!

View File

@@ -0,0 +1,180 @@
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "toDoList.h"
/* Create a task from the description and the priority
param: priority priority of the task
param: desc pointer to the description string
pre: none
post: none
ret: a task with description and priority
*/
Task* createTask (int priority, char *desc)
{
/* FIXME */
/* DONE */
struct Task *temp = malloc(sizeof(struct Task));
strcpy(temp->description, desc);
temp->priority = priority;
return temp;
}
/* Save the list to a file
param: heap pointer to the list
param: filePtr pointer to the file to which the list is saved
pre: The list is not empty
post: The list is saved to the file in tab-delimited format.
Each line in the file stores a task, starting with the
task priority, followed by a tab character (\t), and
the task description.
The tasks are not necessarily stored in the file in
priority order.
*/
void saveList(DynArr *heap, FILE *filePtr)
{
int i;
Task* task;
assert(sizeDynArr(heap) > 0);
for(i = 0; i < sizeDynArr(heap); i++)
{
task = getDynArr(heap, i);
fprintf(filePtr, "%d\t%s\n", task->priority, task->description);
}
}
/* Load the list from a file
param: heap pointer to the list
param: filePtr pointer to the file
pre: none
post: The tasks are retrieved from the file and are added to the list.
Refer to the saveList() function for the format of tasks in the file
*/
void loadList(DynArr *heap, FILE *filePtr)
{
Task* task;
char line[100]; /* Assume lines < 100 */
char desc[TASK_DESC_SIZE], *nlptr;
int priority;
/* Read the priority first, then the description.
* fgets() is used to read string with spaces
*/
#ifdef NOTDEF
while (fscanf(filePtr, "%d\t", &priority) != EOF)
{
/* fgets() stops reading at \n character */
fgets(desc, sizeof(desc), filePtr);
/* remove trailing newline character */
nlptr = strchr(desc, '\n');
if (nlptr)
*nlptr = '\0';
task = createTask(priority, desc);
addHeap(heap, task);
}
#endif
while(fgets(line, sizeof(line), filePtr) != 0)
{
sscanf(line, "%d\t%[^\n]", &priority, desc);
task = createTask(priority, desc);
addHeap(heap, task);
} /* should use feof to make sure it found eof and not error*/
}
/* Print the list
param: heap pointer to the list
pre: the list is not empty
post: The tasks from the list are printed out in priority order.
The tasks are not removed from the list.
*/
void printList(DynArr *heap)
{
/* FIXME: Write this */
/* DONE: May need adjustment */
Task *temp;
for(int i = 0 ; i < sizeDynArr(heap) ; i++){
temp = (Task*)getDynArr(heap, i);
printf("Priority: %d\tDescription: %s\n", temp->priority, temp->description);
}
}
/* Delete the list
param: heap pointer to the list
post: The tasks from the list are removed and their occupied memories are freed
*/
void deleteList(DynArr *heap)
{
Task* task;
while(sizeDynArr(heap) > 0)
{
/* get the task */
task = getMinHeap(heap);
/* remove the task */
removeMinHeap(heap);
/* free the task */
free(task);
}
/* free the heap */
deleteDynArr(heap);
}
/* Compare two tasks by priority
param: left first task
param: right second task
pre: none
post: none
ret: -1 if priority of left < priority of right
1 if priority of left > priority of right
0 if priority of left = priority of right
*/
/*Define this function, type casting the value of void * to the desired type.
The current definition of TYPE in dynamicArray.h is void*, which means that left and
right are void pointers. To compare left and right, you should first cast
left and right to the corresponding pointer type (struct Task*), and then
compare the values pointed by the casted pointers.
DO NOT compare the addresses pointed by left and right, i.e. "if (left < right)",
which is really wrong.
*/
int compare(TYPE left, TYPE right)
{
/*FIXME: write this*/
/* DONE */
struct Task *temp1 = (struct Task*)left;
struct Task *temp2 = (struct Task*)right;
if(temp1->priority < temp2->priority){
return -1;
}else if(temp1->priority > temp2->priority){
return 1;
}else{
return 0;
}
}
/*Define this function, type casting the value of void * to the desired type*/
void print_type(TYPE curval)
{
/*FIXME: write this*/
/* DONE */
Task* data1;
data1 = (Task*)curval;
printf("Priority: %d\tDescription: %s\n", data1->priority, data1->description);
}

View File

@@ -0,0 +1,17 @@
#ifndef __TODOLIST_H
#define __TODOLIST_H
#include "dynamicArray.h"
#include "type.h"
Task* createTask (int priority, char *desc);
void saveList(DynArr *heap, FILE *filePtr);
void loadList(DynArr *heap, FILE *filePtr);
void printList(DynArr *heap);
void deleteList(DynArr *heap);
#endif

View File

@@ -0,0 +1,3 @@
1 pet kitty
101 review trees for Midterm 2
3 do assignment 5

View File

@@ -0,0 +1,16 @@
/* You can modify the structure to store whatever you'd like in your dynamic array.
We define struct Task for the to-do list application in this example */
#ifndef __TYPE_H
#define __TYPE_H
#define TASK_DESC_SIZE 128
struct Task {
char description[TASK_DESC_SIZE]; /* description of the task */
int priority; /* task priority */
};
typedef struct Task Task;
#endif

View File

@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.21005.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ASM_Project", "Assignment1.vcxproj", "{4164AA65-1EF9-4E69-899B-D1BED776070B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4164AA65-1EF9-4E69-899B-D1BED776070B}.Debug|Win32.ActiveCfg = Debug|Win32
{4164AA65-1EF9-4E69-899B-D1BED776070B}.Debug|Win32.Build.0 = Debug|Win32
{4164AA65-1EF9-4E69-899B-D1BED776070B}.Release|Win32.ActiveCfg = Release|Win32
{4164AA65-1EF9-4E69-899B-D1BED776070B}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,79 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<MASM Include="main.asm" />
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{4164AA65-1EF9-4E69-899B-D1BED776070B}</ProjectGuid>
<ProjectName>ASM_Project</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
<Import Project="$(VCTargetsPath)\BuildCustomizations\masm.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<MASM>
<IncludePaths>c:\Irvine</IncludePaths>
</MASM>
<Link>
<AdditionalDependencies>user32.lib;irvine32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>c:\Irvine;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Link>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<AdditionalLibraryDirectories>c:\Irvine;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SubSystem>Console</SubSystem>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
<AdditionalDependencies>user32.lib;irvine32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
<MASM>
<IncludePaths>c:\Irvine</IncludePaths>
</MASM>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
<Import Project="$(VCTargetsPath)\BuildCustomizations\masm.targets" />
</ImportGroup>
</Project>

View File

@@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
</Project>

View File

@@ -0,0 +1,59 @@
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
TITLE Assignment 1 (main.asm)
;Author: Corwin Perren
;Date: 1/19/2014
;Description:
; This program will request two numbers from the user, perform common
; mathematical calculations on them, and print the results
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
INCLUDE Irvine32.inc
.data
ProgramTitle BYTE "CS 271 - Assignment 1",0dh,0ah,0
CreatorName BYTE "Creator: Corwin Peren",0dh,0ah,0
Prompt1 BYTE "Please enter the first number: ",0
Prompt2 BYTE "Please enter the second number: ",0
SumMessage BYTE "Sum: ",0
DifMessage BYTE "Difference: ",0
ProdMessage BYTE "Product: ",0
QuotMessage BYTE "Quotient: ",0
RemainMessage BYTE "Remainder: ",0
TermMessage BYTE "Computations Complete...",0dh,0ah,0
FirstNumber DWORD ?
SecondNumber DWORD ?
FinalSum DWORD ?
FinalDif DWORD ?
FinalProd DWORD ?
FinalQuot DWORD ?
FinalRemain DWORD ?
.code
NineToFive PROC uses EAX
mov eax, 9
call WriteInt
mov eax, 8
call WriteInt
mov eax, 7
call WriteInt
mov eax, 6
call WriteInt
mov eax, 5
call WriteInt
ret
NineToFive ENDP
main PROC
call NineToFive
exit
main ENDP
END main

View File

@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.21005.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ASM_Project", "Assignement 2.vcxproj", "{4164AA65-1EF9-4E69-899B-D1BED776070B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4164AA65-1EF9-4E69-899B-D1BED776070B}.Debug|Win32.ActiveCfg = Debug|Win32
{4164AA65-1EF9-4E69-899B-D1BED776070B}.Debug|Win32.Build.0 = Debug|Win32
{4164AA65-1EF9-4E69-899B-D1BED776070B}.Release|Win32.ActiveCfg = Release|Win32
{4164AA65-1EF9-4E69-899B-D1BED776070B}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,79 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<MASM Include="main.asm" />
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{4164AA65-1EF9-4E69-899B-D1BED776070B}</ProjectGuid>
<ProjectName>ASM_Project</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
<Import Project="$(VCTargetsPath)\BuildCustomizations\masm.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<MASM>
<IncludePaths>c:\Irvine</IncludePaths>
</MASM>
<Link>
<AdditionalDependencies>user32.lib;irvine32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>c:\Irvine;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Link>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<AdditionalLibraryDirectories>c:\Irvine;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SubSystem>Console</SubSystem>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
<AdditionalDependencies>user32.lib;irvine32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
<MASM>
<IncludePaths>c:\Irvine</IncludePaths>
</MASM>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
<Import Project="$(VCTargetsPath)\BuildCustomizations\masm.targets" />
</ImportGroup>
</Project>

View File

@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.21005.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ASM_Project", "Project 2.vcxproj", "{4164AA65-1EF9-4E69-899B-D1BED776070B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4164AA65-1EF9-4E69-899B-D1BED776070B}.Debug|Win32.ActiveCfg = Debug|Win32
{4164AA65-1EF9-4E69-899B-D1BED776070B}.Debug|Win32.Build.0 = Debug|Win32
{4164AA65-1EF9-4E69-899B-D1BED776070B}.Release|Win32.ActiveCfg = Release|Win32
{4164AA65-1EF9-4E69-899B-D1BED776070B}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,268 @@
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
TITLE Assignment 2 (main.asm)
;Author: Corwin Perren
;Date: 1/28/2014
;Description:
; This program will calculate and display the nth iteration of the fibonacci
; sequence for n values between 1 and 46
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
INCLUDE Irvine32.inc
.data
ProgramTitle BYTE "CS 271 - Assignment 2",0
ProgrammersName BYTE "Programmed By: Corwin Perren",0
NamePrompt BYTE "By what name may I call you?",0
NamePrompt2 BYTE "Your name: ", 0
NameResponse BYTE "Welcome, ", 0
NameResponse2 BYTE ".", 0
FibPrompt BYTE "How many values of the fibonacci sequence would you like to calculate?", 0
FibPrompt2 BYTE "Enter a value from 1 to 46: ", 0
FibPromptIncorrect BYTE "Value was not between 1 and 46. Please try again.", 0
TabString BYTE 9, 0
ExtraTab DWORD 1346269
TryAgainMessage BYTE "Would you like to run the program again?", 0
TryAgainMessage2 BYTE "Answer (y/n): ", 0
IncorrectTryMessage BYTE "Please enter y or n....", 0
TermMessage BYTE "Goodbye, ", 0
TermMessage2 BYTE ".", 0
FibMax DWORD 46
FibMin DWORD 1
UserName BYTE 25 dup(0)
KeyAnswer BYTE 2 dup(0)
NumFib DWORD ?
FibVal DWORD 1
FibVal2 DWORD 1
CurCol DWORD 0
ColMax DWORD 5
Yep BYTE "y", 0
Nope BYTE "n", 0
.code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Simple procedure for printing a tab to the screen
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
InsertTab PROC
mov edx,OFFSET TabString ;Moves the tab character into the buffer
call WriteString ;Writes the tab to the screen
ret ;Returns out of the procedure
InsertTab ENDP
main PROC
call Clrscr ;Clears the screen
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Write title and programmers name to screen
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov edx,OFFSET ProgramTitle ;Gets title ready to print
call WriteString ;Prints title
call Crlf ;Prints a new line
mov edx,OFFSET ProgrammersName ;Gets programmers name ready to print
call WriteString ;Prints programmers name
call Crlf ;Prints newline
call Crlf ;Prints newline
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Prompt user for their name
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov edx,OFFSET NamePrompt ;Gets username prompt ready
call WriteString ;Prints username prompt
call Crlf ;Prints newline
mov edx,OFFSET NamePrompt2 ;Gets second half of username prompt ready
call WriteString ;Prints username prompt part 2
mov edx,OFFSET UserName ;Moves offset for username storage var into edx
mov ecx,SIZEOF UserName ;Sets max number of characters to read in
call ReadString ;Reads in username string from user
call Crlf ;Prints newline
call Crlf ;Prints newline
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Write user welcome message, with their name
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
DoAgain:
call Clrscr ;Clears the screen to clean up output
mov edx,OFFSET NameResponse ;Gets the welcome message part 1 ready to print
call WriteString ;Prints welcome message part 1
mov edx,OFFSET UserName ;Gets username ready to print
call WriteString ;Prints username
mov edx,OFFSET NameResponse2 ;Gets welcome message part 2 redy to print
call WriteString ;Prints welcome message part 2
call Crlf ;Prints a new line
call Crlf ;Prints a new line
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Prompt user for number of fibonacci to calculate
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov edx,OFFSET FibPrompt ;Gets prompt for fibonacci number ready
call WriteString ;Prints fib prompt
call Crlf ;Prints a new line
jmp EnterNumber ;Jumps to enter number label to begin input
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;This prompt shows when the number enterred is not within 1 to 46
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
IncorrectInput:
call Crlf ;Prints a new line
mov edx,OFFSET FibPromptIncorrect ;Gets incorrect range prompt ready to print
call WriteString ;Prints incorrect range prompt
call Crlf ;Prints a new line
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Main prompt and read-in of fibonacci value from user
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
EnterNumber:
mov edx,OFFSET FibPrompt2 ;Get main number entry prompt ready to print
call WriteString ;Prints main input prompt
call ReadInt ;Reads in int from user
cmp eax, FibMin ;Checks if input is less than 1
jl IncorrectInput ;Jumps to incorrect input if true
cmp eax, FibMax ;Checks if input is greater than 46
jg IncorrectInput ;Jumps to incorrect input if true
mov NumFib, eax ;Copies number to variable if in correct range
call Crlf ;Prints a new line
mov FibVal, 1 ;Reset fib start vals
mov FibVal2, 1 ;Reset fib start vals
mov CurCol, 0 ;Reset current column position
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;This section prints the first fibonacci sequence value
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov eax, FibVal ;Gets first value of fibonacci sequence ready to print (1)
call WriteInt ;Writes value to screen
cmp NumFib, 1 ;Checks if only this one value should be displayed
je FibDone ;If true, jump to end of program
inc CurCol ;Increment column index
call InsertTab ;Prints tab for column alignment
call InsertTab ;Prints tab for column alignment
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;This section prints the second fibonacci sequence value
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Call WriteInt ;Prints the second value of the fibonacci sequence (also 1)
cmp NumFib, 2 ;Checks if only these two should be displayed
je FibDone ;If true, jump to end of program
inc CurCol ;Otherwise, increment column index
call InsertTab ;Prints tab for column alignment
call InsertTab ;Prints tab for column alignment
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Setup of registers for the impending loop
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov ecx, NumFib ;Sets loop ecx value
sub ecx, 2 ;Subtracts two because of the first two have already been printed
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Main fibonacci calculation and print loop
;PSEUDO
;newval = FibVal2 + Fibval
;print newval
;FibVal = FibVal2
;FibVal2 = newval;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
CalcFib:
mov eax, FibVal2 ;Moves most recent fibonacci value into one reg
add eax, FibVal ;Adds second to last to most recent
call WriteInt ;Prints this fibonacci value to screen
push FibVal2 ;Moves old most recent to temp spot for move
pop FibVal ;Replaces second to last old val
mov FibVal2, eax ;Moves new most recent val to FibVal2
call InsertTab ;Prints tab for column alignment
cmp eax, ExtraTab ;Check if output val requires extra tab on output
jl OneExtra ;Jump to extra tab output label if necessary
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Return jump point for extra tab printing to make output alignment nice
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
MidCalcFib:
inc CurCol ;Increment column index
mov edx, CurCol ;Place index in reg for compare
cmp edx, ColMax ;Compare current col index with max
jne CalcFibLoop ;Jump to rest of loop if newline not needed
call Crlf ;Prints newline when needed
mov CurCol, 0 ;Resets current column index
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Jump location used for avoiding printing a newline from above
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
CalcFibLoop:
loop CalcFib ;Loops fib calc sequence until ecx counter 0
jmp TryAgain ;Jumps to program end if loop done
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Jump location used for printing on screen tabs
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
OneExtra:
call InsertTab ;Calls procedure to input tab when necessary
jmp MidCalcFib ;Jumps back to where it was called
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;This section deals with jumping if the user wants to calculate more values
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
IncorrectTry:
call Crlf ;Prints a new line
mov edx,OFFSET IncorrectTryMessage ;Gets ready to print the incorrect try message
call Writestring ;Prints the incorrect try message
TryAgain:
call Crlf ;Prints a new line
call Crlf ;Prints a new line
mov edx,OFFSET TryAgainMessage ;Gets ready to print the try again message
call WriteString ;Prints the try again message
call Crlf ;Prints a new line
mov edx,OFFSET TryAgainMessage2 ;Gets ready to print the try again message part 2
call WriteString ;Prints the try again message 2
mov edx,OFFSET KeyAnswer ;Assigns edx to offset of keyanswer for keyboard input
mov ecx,SIZEOF KeyAnswer ;Sets number of characters to read in
call ReadString ;Reads in keyboard input
INVOKE Str_compare,OFFSET KeyAnswer,OFFSET Yep ;Uses a multi-input irvine procedure to do a string comparison
je DoAgain ;Jump to DoAgain if the user answered 'y'
INVOKE Str_compare,OFFSET KeyAnswer,OFFSET Nope ;Uses a multi-input irvine procedure to do a string comparison
je FibDone ;Jumps to end if user answered 'n'
jmp IncorrectTry ;Jumps to an incorrect input section if user enterred wrong values
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Section to show the termination message
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
FibDone:
call Crlf ;Prints a new line
call Crlf ;Prints a new line
mov edx,OFFSET TermMessage ;Gets termination message part 1 ready to print
call WriteString ;Prints termination message
mov edx,OFFSET UserName ;Gets username ready to print
call WriteString ;Prints username
mov edx,OFFSET TermMessage2 ;Gets termination message part 2 ready to print
call WriteString ;Prints termination messag part 2
call Crlf ;Prints a new line
exit ;Ends main program
main ENDP
END main

View File

@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.21005.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ASM_Project", "Assignment3.vcxproj", "{4164AA65-1EF9-4E69-899B-D1BED776070B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4164AA65-1EF9-4E69-899B-D1BED776070B}.Debug|Win32.ActiveCfg = Debug|Win32
{4164AA65-1EF9-4E69-899B-D1BED776070B}.Debug|Win32.Build.0 = Debug|Win32
{4164AA65-1EF9-4E69-899B-D1BED776070B}.Release|Win32.ActiveCfg = Release|Win32
{4164AA65-1EF9-4E69-899B-D1BED776070B}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,79 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<MASM Include="main.asm" />
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{4164AA65-1EF9-4E69-899B-D1BED776070B}</ProjectGuid>
<ProjectName>ASM_Project</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
<Import Project="$(VCTargetsPath)\BuildCustomizations\masm.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<MASM>
<IncludePaths>c:\Irvine</IncludePaths>
</MASM>
<Link>
<AdditionalDependencies>user32.lib;irvine32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>c:\Irvine;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Link>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<AdditionalLibraryDirectories>c:\Irvine;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SubSystem>Console</SubSystem>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
<AdditionalDependencies>user32.lib;irvine32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
<MASM>
<IncludePaths>c:\Irvine</IncludePaths>
</MASM>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
<Import Project="$(VCTargetsPath)\BuildCustomizations\masm.targets" />
</ImportGroup>
</Project>

View File

@@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
</Project>

View File

@@ -0,0 +1,441 @@
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
TITLE Assignment 5 (main.asm)
;Author: Corwin Perren
;Date: 3/3/2014
;Description:
; This program runs all three programs from assignment 5 from a menu screen
; These programs include an array reverser, frequency table generator, and
; prime number generator
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
INCLUDE Irvine32.inc
.data
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Variables to change for testing program capabilities
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
SieveArray BYTE 1000000 dup(?)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Globally relevant vars
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ProgramTitle BYTE "CS 271 - Assignment 5",0
ProgrammerName BYTE "Written by: Corwin Perren",0
SelectInstructions BYTE "Please enter 1-4 to run desired program.", 0
MenuItem1 BYTE "1: Reverse Array In Place (Chapter 4, Exercise 5)",0
MenuItem2 BYTE "2: Frequency Table (Chapter 9, Exercise 6)",0
MenuItem3 BYTE "3: Sieve of Eratosthenes (Chapter 9, Exercise 7)",0
MenuItem4 BYTE "4: Exit",0
Selection BYTE "Selection: ",0
IncorrectNumberEntry BYTE "You did not enter 1-4. Press enter to try again.", 0
ReturnToSelect BYTE "Program Complete. Press enter to return to selection screen.", 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Vars for Prog 1
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ArrayToReverse BYTE 1,2,3,4,5,6,7,8,9,10, 11, 12, 13, 14
PressEnter BYTE "Press enter to reverse the currently reversed array. Enter 1 to quit.", 0
OriginalArray BYTE "Original Array:", 0
ReversedArray BYTE "Reversed Array:", 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Vars for Prog 2
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
StringEntry BYTE "Please enter a string to create a frequency table for.", 0
StringThing BYTE "Your string: ", 0
StringArray BYTE 256 dup(?)
FrequencyTable DWORD 256 dup(?)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Vars for Prog 3
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
EnterPrimes1 BYTE "Press enter to calculate primes up to ", 0
EnterPrimes2 BYTE ".", 0
.code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Procedure for writing string with newline
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Write_String_NL PROC uses EDX,
StringPtr:Ptr BYTE ;Varible to store string offset pointer
mov edx, StringPtr ;Moves the string to the proper register
call WriteString ;Prints the string
call Crlf ;Prints a new line
ret ;Return from procedure
Write_String_NL ENDP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Procedure for writing string without newline
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Write_String PROC uses EDX,
StringPtr:Ptr BYTE ;Variable to store string offset pointer
mov edx, StringPtr ;Moves the string to the proper registers
call WriteString ;Prints the string
ret
Write_String ENDP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Procedure for printing program title and programmer name
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PrintTitle PROC
INVOKE Write_String_NL, OFFSET ProgramTitle ;Prints the program title
INVOKE Write_String_NL, OFFSET ProgrammerName ;prints the programmer's name
call Crlf ;Prints a new line
INVOKE Write_String_NL, OFFSET SelectInstructions ;Prints the selection screen instructions
call Crlf ;Prints a new line
INVOKE Write_String_NL, OFFSET MenuItem1 ;Prints menu item 1
INVOKE Write_String_NL, OFFSET MenuItem2 ;Prints menu item 2
INVOKE Write_String_NL, OFFSET MenuItem3 ;Prints menu item 3
INVOKE Write_String_NL, OFFSET MenuItem4 ;Prints menu item 4
INVOKE Write_String, OFFSET Selection ;Print selction prompt
ret
PrintTitle ENDP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Procedure to fill array with zeros using stosb
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
FillWithZeros PROC
mov al, 0 ;Set al with value we want to fill array with
cld ;Clear Direction Flag
mov edi, OFFSET SieveArray ;Point edi to array
mov ecx, LENGTHOF SieveArray ;Set counter so instruction knows when to end
dec ecx ;Subtract one because it's starting at zero instead of one
rep stosb ;Repeats the fill operation until the array is full
ret ;Returns from function
FillWithZeros ENDP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Procedure to mark multiples of primes with ones
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
MarkMultiples PROC
mov esi, OFFSET SieveArray ;Move into esi to get easy access
mov BYTE PTR [esi], 1 ;Mark zero as non-prime
mov BYTE PTR [esi+1], 1 ;Mark one as non-prime
mov eax, 2 ;Set cursor position
mov ebx, 2 ;Multiplication value
jmp Inner
Outer:
pop eax ;Pop eax if we got here so the stack gets aligned and we know where we are
LookForOne:
inc eax ;Go up by one
cmp BYTE PTR [esi+eax], 1 ;Check to see if the new value at that position of the array has been marked
je LookForOne ;If so, increment again to find an unmarked one
cmp eax, LENGTHOF SieveArray ;Once an unmarked is found, make sure it's not outside our array size
jg MultEnd ;If it's out of array bounds, we're done so exit
mov ebx, 2 ;Otherwise, get ready to mark multiples of current prime starting with two times the prime
Inner:
push eax ;Save our original prime we're using
mul ebx ;Multiply prime by scaler
cmp eax, LENGTHOF SieveArray ;Make sure new value is not out of array size
jg Outer ;If it is, we're done with this prime
mov BYTE PTR [esi+eax], 1 ;Otherwise, mark the multiple with a one
inc ebx ;Increase our scaler
pop eax ;Restore the prime we're on
jmp Inner ;Re-do for next scaler
MultEnd:
ret ;Return from procedure
MarkMultiples ENDP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Procedure to print out unmarked values in array, which are primes
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PrintPrimes PROC
mov esi, OFFSET SieveArray ;Load array into esi to get ready to print
mov eax, 0 ;Set our cursor to zero
LookForZeros:
inc eax ;Move cursor forward one
cmp eax, LENGTHOF SieveArray ;Check if cursor is out of array bounds
jg PrintExit ;If so, exit because we are done
cmp BYTE PTR [esi+eax], 1 ;If we're in bounds, check if the position is marked
je LookForZeros ;If so, don't print and look at the next position
call WriteDec ;If unmarked, print the prime number sotred here
call Crlf ;Print a new line to make things look nice
jmp LookForZeros ;Continue for the next array position
PrintExit:
ret ;Return from procedure
PrintPrimes ENDP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Procedure to run program 3
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Program3 PROC
call ClrScr ;Clears the screen
INVOKE Write_String, OFFSET EnterPrimes1 ;Prints prompt part one
mov eax, LENGTHOF SieveArray ;Moves number of primes to calculate to print
call WriteDec ;Prints number of primes to calculate
INVOKE Write_String_NL, OFFSET EnterPrimes2 ;Prints end of prompt line
call ReadInt ;Waits for any key
call FillWithZeros ;Fills the sieve array with zeros using stosb method
call MarkMultiples ;Marks positions that are multiples of primes
call PrintPrimes ;Prints remaining prime numbers
ret ;Returns from procedure
Program3 ENDP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Procedure to determine the character frequency of a string
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Get_Frequencies PROC InputString:PTR BYTE, OutputTable:PTR DWORD
mov esi, InputString ;Moves string to parse into esi
mov edi, OutputTable ;Moves output table into edi
FreqLoop:
mov eax, 0 ;Zeros eax to make things work right
mov al, BYTE PTR [esi] ;Moves ascii decimal value into eax
mov ecx, eax ;Saves current decimal value
mov ebx, 4 ;Multiply eax by four because it's stored in DWORD and not BYTE array
mul ebx ;Actual multiplication
add DWORD PTR [edi+eax], 1 ;Increments frequency table position by one for this character
cmp ecx, 0 ;Checks if we've hit the NUL character
je FreqDone ;Exit if it's found because we're done
inc esi ;Otherwise, move to the next string array position
jmp FreqLoop ;Do above again for next character
FreqDone:
ret ;Return from procedure
Get_Frequencies ENDP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Procedure to read in string from user
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
GetNewString PROC StringPtr:PTR BYTE
mov edx, StringPtr ;Move string array into edx for read in
mov ecx, 256 ;Read in a max of 256 characters
call ReadString ;Read in string from user
ret ;Exit from procedure
GetNewString ENDP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Procedure to print out the frequency table
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PrintFreqTable PROC TablePtr:PTR DWORD
mov esi, TablePtr ;Move frequency table into esi
mov ecx, 256 ;Set number of elements
mov ebx, 4 ;Set size of storage elements
call DumpMem ;Dump memory for the array
ret
PrintFreqTable ENDP
ZeroProg2 PROC
mov eax, 0 ;Set al with value we want to fill array with
cld ;Clear Direction Flag
mov edi, OFFSET StringArray ;Point edi to array
mov ecx, 256 ;Set counter so instruction knows when to end
dec ecx ;Subtract one because it's starting at zero instead of one
rep stosb ;Repeats the fill operation until the array is full
mov eax, 0 ;Set al with value we want to fill array with
cld ;Clear Direction Flag
mov edi, OFFSET FrequencyTable ;Point edi to array
mov ecx, 1024 ;Set counter so instruction knows when to end
dec ecx ;Subtract one because it's starting at zero instead of one
rep stosb ;Repeats the fill operation until the array is full
ret ;Returns from function
ZeroProg2 ENDP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Procedure to run program 2
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Program2 PROC
call ClrScr ;Clear the screen
call ZeroProg2 ;Zeros string and freq table array
INVOKE Write_String_NL, OFFSET StringEntry ;Prompts the user to enter a string
INVOKE Write_String, OFFSET StringThing ;Line prompt for above
INVOKE GetNewString, OFFSET StringArray ;Reads in user string
INVOKE Get_Frequencies, OFFSET StringArray, OFFSET FrequencyTable ;Runs frequency procedure on input string
INVOKE PrintFreqTable, OFFSET FrequencyTable ;Prints out the new frequency table
ret ;Returns from procedure
Program2 ENDP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Procedure to run program 1
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Program1 PROC
call ClrScr ;Clears the screen
INVOKE Write_String_NL, OFFSET OriginalArray ;Prints header for original array
mov eax, TYPE ArrayToReverse ;Moves the array type into eax
cmp eax, 1 ;Checks if it's a BYTE array
je ITSBYTE ;Jumps to BYTE section if so
cmp eax, 2 ;Checks if WORD array
je ITSWORD ;Jumps to WORD section if so
cmp eax, 4 ;Check if DWORD array
je ITSDWORD ;Jumps to DWORD section if so
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Run for BYTE Array
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ITSBYTE:
mov esi, OFFSET ArrayToReverse ;Moves array into esi
mov ecx, LENGTHOF ArrayToReverse ;Moves number of elements in array into ecx
mov ebx, TYPE ArrayToReverse ;Moves type of array into ebx
call DumpMem ;Shows original array
mov esi, OFFSET ArrayToReverse ;Re-moves array into esi
mov edi, OFFSET ArrayToReverse + SIZEOF ArrayToReverse - TYPE ArrayToReverse ;Moves the pointer to the last value of the array into edi
mov eax, LENGTHOF ArrayToReverse ;Moves number of elements in array into eax
mov edx, 0 ;Sets remainder to zero by default
mov ebx, 2 ;Moves two into ebx
div ebx ;Divides number of elements by two
mov ecx, eax ;Puts that number into our loop counter
ReverseBYTE:
mov bl, [esi] ;Move data at beginning cursor to tmp storage
mov dl, [edi] ;Move data at end cursor to tmp storage
mov [esi], dl ;Move end data to beginning
mov [edi], bl ;Move beginning data to end
add esi, TYPE ArrayToReverse ;Move beginning cursor forward
sub edi, TYPE ArrayToReverse ;Move ending cursor back
loop ReverseBYTE ;Loop until count expired
jmp Prog1Ret ;Jump to procedure end when done
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Run for WORD Array
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ITSWORD:
mov esi, OFFSET ArrayToReverse ;Moves array into esi
mov ecx, LENGTHOF ArrayToReverse ;Moves number of elements in array into ecx
mov ebx, TYPE ArrayToReverse ;Moves type of array into ebx
call DumpMem ;Shows original array
mov esi, OFFSET ArrayToReverse ;Re-moves array into esi
mov edi, OFFSET ArrayToReverse + SIZEOF ArrayToReverse - TYPE ArrayToReverse ;Moves the pointer to the last value of the array into edi
mov eax, LENGTHOF ArrayToReverse ;Moves number of elements in array into eax
mov edx, 0 ;Sets remainder to zero by default
mov ebx, 2 ;Moves two into ebx
div ebx ;Divides number of elements by two
mov ecx, eax ;Puts that number into our loop counter
ReverseWORD:
mov bx, [esi] ;Move data at beginning cursor to tmp storage
mov dx, [edi] ;Move data at end cursor to tmp storage
mov [esi], dx ;Move end data to beginning
mov [edi], bx ;Move beginning data to end
add esi, TYPE ArrayToReverse ;Move beginning cursor forward
sub edi, TYPE ArrayToReverse ;Move ending cursor back
loop ReverseWORD ;Loop until count expired
jmp Prog1Ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Run for DWORD Array
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ITSDWORD:
mov esi, OFFSET ArrayToReverse ;Moves array into esi
mov ecx, LENGTHOF ArrayToReverse ;Moves number of elements in array into ecx
mov ebx, TYPE ArrayToReverse ;Moves type of array into ebx
call DumpMem ;Shows original array
mov esi, OFFSET ArrayToReverse ;Re-moves array into esi
mov edi, OFFSET ArrayToReverse + SIZEOF ArrayToReverse - TYPE ArrayToReverse ;Moves the pointer to the last value of the array into edi
mov eax, LENGTHOF ArrayToReverse ;Moves number of elements in array into eax
mov edx, 0 ;Sets remainder to zero by default
mov ebx, 2 ;Moves two into ebx
div ebx ;Divides number of elements by two
mov ecx, eax ;Puts that number into our loop counter
ReverseDWORD:
mov ebx, [esi] ;Move data at beginning cursor to tmp storage
mov edx, [edi] ;Move data at end cursor to tmp storage
mov [esi], edx ;Move end data to beginning
mov [edi], ebx ;Move beginning data to end
add esi, TYPE ArrayToReverse ;Move beginning cursor forward
sub edi, TYPE ArrayToReverse ;Move ending cursor back
loop ReverseWORD ;Loop until count expired
Prog1Ret:
call Crlf ;Print a new line
call Crlf ;Print a second new line
INVOKE Write_String_NL, OFFSET ReversedArray ;Print header to say this is the reversed array
mov esi, OFFSET ArrayToReverse ;Move array into esi
mov ecx, LENGTHOF ArrayToReverse ;Set number of elements
mov ebx, TYPE ArrayToReverse ;Set size of elements
call DumpMem ;Display array
ret ;Return from procedure
Program1 ENDP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Main Procedure
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
main PROC
MainTitle:
call ClrScr ;Clear screen
call PrintTitle ;Print the title screen
call ReadInt ;Read in user selection
cmp eax, 1 ;Check if user selected entry item 1
je Prog1Jmp ;If so, jump to that program
cmp eax, 2 ;Check if user selected entry item 2
je Prog2Jmp ;If so, jump to that program
cmp eax, 3 ;Check if user selected entry item 3
je Prog3Jmp ;If so, jump to that program
cmp eax, 4 ;Check if user selected exit
je MainExit ;If so, jump to end of program
call ClrScr ;Clear screeen
INVOKE Write_String_NL, OFFSET IncorrectNumberEntry ;Scold user for not entering one to four
call ReadInt ;Wait for enter key
jmp MainTitle ;Jump back to main screen
Prog1Jmp:
call Program1 ;Call array reverse program
call Crlf ;Print new line
INVOKE Write_String_NL, OFFSET ReturnToSelect ;Print hit enter to return to screen
call ReadInt ;Wait for enter
jmp MainTitle ;Jump to main screen
Prog2Jmp:
call Program2 ;Call String frequency program
call Crlf ;Print new line
INVOKE Write_String_NL, OFFSET ReturnToSelect ;Print hit enter to return to screen
call ReadInt ;Wait for enter
jmp MainTitle ;Jump to main screen
Prog3Jmp:
call Program3 ;Call prime generator program
call Crlf ;Print new line
INVOKE Write_String_NL, OFFSET ReturnToSelect ;Print hit enter to return to screen
call ReadInt ;Wait for enter
jmp MainTitle ;Jump to main screen
MainExit:
exit
main ENDP
END main

View File

@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.21005.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ASM_Project", "Assignment3.vcxproj", "{4164AA65-1EF9-4E69-899B-D1BED776070B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4164AA65-1EF9-4E69-899B-D1BED776070B}.Debug|Win32.ActiveCfg = Debug|Win32
{4164AA65-1EF9-4E69-899B-D1BED776070B}.Debug|Win32.Build.0 = Debug|Win32
{4164AA65-1EF9-4E69-899B-D1BED776070B}.Release|Win32.ActiveCfg = Release|Win32
{4164AA65-1EF9-4E69-899B-D1BED776070B}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,79 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<MASM Include="Assignment4_perrenc.asm" />
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{4164AA65-1EF9-4E69-899B-D1BED776070B}</ProjectGuid>
<ProjectName>ASM_Project</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
<Import Project="$(VCTargetsPath)\BuildCustomizations\masm.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<MASM>
<IncludePaths>c:\Irvine</IncludePaths>
</MASM>
<Link>
<AdditionalDependencies>user32.lib;irvine32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>c:\Irvine;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Link>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<AdditionalLibraryDirectories>c:\Irvine;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SubSystem>Console</SubSystem>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
<AdditionalDependencies>user32.lib;irvine32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
<MASM>
<IncludePaths>c:\Irvine</IncludePaths>
</MASM>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
<Import Project="$(VCTargetsPath)\BuildCustomizations\masm.targets" />
</ImportGroup>
</Project>

Some files were not shown because too many files have changed in this diff Show More