Subversion Repositories svnkaklik

Compare Revisions

No changes between revisions

Ignore whitespace Rev 506 → Rev 507

/programy/C/avr/LCD/Makefile
0,0 → 1,55
# makefile, written by kaklik
MCU=atmega128
CC=avr-gcc
OBJCOPY=avr-objcopy
# optimize for size:
CFLAGS=-g -mmcu=$(MCU) -Wall -Wstrict-prototypes -Os -mcall-prologues
#-------------------
all: lcd_hd44780_test.hex
#-------------------
lcd_hd44780_test.hex : lcd_hd44780_test.out
$(OBJCOPY) -R .eeprom -O ihex lcd_hd44780_test.out lcd_hd44780_test.hex
lcd_hd44780_test.out : lcd_hd44780_test.o
$(CC) $(CFLAGS) -o lcd_hd44780_test.out -Wl,-Map,lcd_hd44780_test.map lcd_hd44780_test.o
lcd_hd44780_test.o : lcd_hd44780_test.c
$(CC) $(CFLAGS) -Os -c lcd_hd44780_test.c
#------------------
load: $(FILE).hex
./prg_load_uc $(FILE).hex
# here is a pre-compiled version in case you have trouble with
# your development environment
load_pre: $(FILE).hex
./prg_load_uc $(FILE)_pre.hex
#
loaduisp: $(FILE).hex
./prg_load_uc -u $(FILE).hex
# here is a pre-compiled version in case you have trouble with
# your development environment
load_preuisp: $(FILE)_pre.hex
./prg_load_uc -u avrm8ledtest.hex
#-------------------
# fuse byte settings:
# Atmel AVR ATmega8
# Fuse Low Byte = 0xe1 (1MHz internal), 0xe3 (4MHz internal), 0xe4 (8MHz internal)
# Fuse High Byte = 0xd9
# Factory default is 0xe1 for low byte and 0xd9 for high byte
# Check this with make rdfuses
rdfuses:
./prg_fusebit_uc -r
# use internal RC oscillator 1 Mhz
wrfuse1mhz:
./prg_fusebit_uc -w 1
# use internal RC oscillator 4 Mhz
wrfuse4mhz:
./prg_fusebit_uc -w 4
# use external 3-8 Mhz crystal
# Warning: you can not reset this to intenal unless you connect a crystal!!
wrfusecrystal:
@echo "Warning: The external crystal setting can not be changed back without a working crystal"
@echo " You have 3 seconds to abort this with crtl-c"
@sleep 3
./prg_fusebit_uc -w 0
#-------------------
clean:
rm -f *.o *.map *.out *.hex
#-------------------
/programy/C/avr/LCD/lcd_hd44780.h
0,0 → 1,602
/* ---------------------------------------------------------------------------
* AVR_MLIB - HD 44780 LCD Display Driver
* www.mlab.cz miho 2008
* ---------------------------------------------------------------------------
* LCD display driver for standard Hitachi 1/2/4 line character LCD modules
* for AVR processors. It uses 4 or 8 bit interface without readback.
* In the Examples section there is a demo application for this library.
* ---------------------------------------------------------------------------
* 00.00 2008/03/28 First Version
* ---------------------------------------------------------------------------
*/
 
 
// What should be set and done before here
// ---------------------------------------
//
// #include <stdio.h> // If you want to use printf, ...
//
// #define LCD_DATA B // 4 or 8 bits field (lsb bit of the port)
// #define LCD_DATA_BIT 4
//
// #define LCD_RS D // Register Select (port and bit)
// #define LCD_RS_BIT 4
//
// #define LCD_E D // Enable (port and bit)
// #define LCD_E_BIT 3
//
//
// // LCD Display Parameters
// #define LCD_INTERFACE_BITS 4 // 4 or 8 bit interface
// #define LCD_LINES 1 // 1 or 2 or 4 lines
// #define LCD_CHARS 20 // usualy 16 or 20, important for 4 line display only
//
// #include "lcd_hd44780.h" // Use LCD Library
//
//
// How to use the library
// ----------------------
//
// void lcd_init(void) // Init LCD Display
//
// void lcd_home() // Goto Home
//
// void lcd_clear() // Clear Display
//
// void lcd_clear_home() // Clear Display and Goto Home with no Cursor
//
// void lcd_cursor_on() // Switch Cursor On
//
// void lcd_cursor_off() // Switch Cursor Off
//
// void lcd_cursor_left() // Move Cursor Left
//
// void lcd_cursor_right() // Move Cursor Right
//
// void lcd_gotoxy(uint8_t x, uint8_t y) // Move to Position (1,1 is the first position)
//
// int lcd_putc(char c) // LCD Char Output
//
// int lcd_putc_stream(char c, FILE *unused) // LCD Char Output (for Stream Library)
//
//
// How to use printf
// -----------------
//
// 1) Define FILE structure
//
// static FILE lcd_stream = FDEV_SETUP_STREAM(lcd_putc_stream, NULL, _FDEV_SETUP_WRITE);
//
// 2) Connect it with standard output
//
// stdout = &lcd_stream; // Connect stdout to LCD Stream
//
// 3) Use printf
//
// printf("\fHello World!\n------------");
//
// 4) Use special chars
//
// \f - clear display and goto home
// \n - goto the beginning of the next line
// \r - goto to the beginning of curent line
// \b - backspace
// \v - start and end definition of user defined char
//
//
// How to use User Defined symbols
// -------------------------------
//
// That is easy. Just print the definition to lcd. Look at the example
//
// printf("\v" "\x10" LCD_CHAR_BAT50 "\v"); // definition (redefines CGRAM content of the LCD)
// printf("Battery Status \x10"); // usage
//
// \v starts the definition
// \x10 first (of eight) user defined char
// LCD_CHAR_BAT50 half battery symbol, you can define more symbols here (up to 8)
// \v end of definition
//
 
 
// Check Defined Values and use Default Values if possible
// -------------------------------------------------------
 
// 1 / 2 / 4 Line
#ifndef LCD_CHARS
#if LCD_LINES > 2
#error "LCD: Undefined LCD_CHARS"
#else
// Dafault Value
#define LCD_CHARS 20
#endif
#endif
 
#ifndef LCD_LINE_1
// Address of the 1st char on the 1st line
#define LCD_LINE_1 0
#endif
 
#ifndef LCD_LINE_2
// Address of the 1st char on the 2nd line
#define LCD_LINE_2 64
#endif
 
#ifndef LCD_LINE_3
// Address of the 1st char on the 3rd line
#define LCD_LINE_3 LCD_CHARS
#endif
 
#ifndef LCD_LINE_4
// Address of the 1st char on the 4th line
#define LCD_LINE_4 (LCD_LINE_2 + LCD_CHARS)
#endif
 
// Data Interface
#if LCD_INTERFACE_BITS == 4
#define LCD_DATA_MASK (0x0F << LCD_DATA_BIT)
#elif LCD_INTERFACE_BITS==8
#define LCD_DATA_MASK (0xFF << LCD_DATA_BIT)
#else
#error "LCD: Wrong Value: LCD_INTERFACE_BITS"
#endif
 
#if LCD_DATA_MASK > 0xFF
#error "LCD: Value too Big: LCD_DATA_BIT"
#endif
 
 
// Need Delay Library
// ------------------
 
#ifndef F_CPU
#error "LCD: Undefined F_CPU"
#endif
#include <util/delay.h> // Delay Routines
 
 
// Need IO Pins
// ------------
 
#include <avr/io.h> // Device Specific Defines
 
#define GLUE(a,b) a##b
#define PORT(a) GLUE(PORT,a)
#define PIN(a) GLUE(PIN,a)
#define DDR(a) GLUE(DDR,a)
 
 
#define LCD_E_PORT PORT(LCD_E)
#define LCD_E_DDR DDR(LCD_E)
 
#define LCD_RS_PORT PORT(LCD_RS)
#define LCD_RS_DDR DDR(LCD_RS)
 
#define LCD_DATA_PORT PORT(LCD_DATA)
#define LCD_DATA_DDR DDR(LCD_DATA)
 
#ifdef LCD_RW
#define LCD_RW_PORT PORT(LCD_RW)
#define LCD_RW_DDR DDR(LCD_RW)
#endif
 
 
// LCD Chip Commands
// -----------------
 
// Comand Clear LCD Display
#define LCD_HD44780_CLR 0x01
 
// Command Home Cursor
#define LCD_HD44780_HOME 0x02
 
// Command Entry Mode (increment/decrement, shift/no shift)
#define LCD_HD44780_ENTMODE(inc, shift) \
(0x04 | ((inc)? 0x02: 0) | ((shift)? 1: 0))
 
#define LCD_HD44780_ENTMODE_DEF LCD_HD44780_ENTMODE(1,0) // Increment Position, No Shift
 
// Command Display Controll (display on/off, cursor on/off, cursor blinking on/off)
#define LCD_HD44780_DISPCTL(disp, cursor, blink) \
(0x08 | ((disp)? 0x04: 0) | ((cursor)? 0x02: 0) | ((blink)? 1: 0))
 
#define LCD_HD44780_CURSORON LCD_HD44780_DISPCTL(1,1,0) // on, cursor on,
#define LCD_HD44780_CURSOROFF LCD_HD44780_DISPCTL(1,0,0) // on, cursor off
 
// Command Cursor or Display Shift (shift display/cursor, left/right)
#define LCD_HD44780_SHIFT(shift, right) \
(0x10 | ((shift)? 0x08: 0) | ((right)? 0x04: 0))
 
#define LCD_HD44780_CURSORLEFT LCD_HD44780_SHIFT(0,0)
#define LCD_HD44780_CURSORRIGHT LCD_HD44780_SHIFT(0,1)
 
// Command Function Set ( 4/8-bit interface / 1 or 2 lines )
#define LCD_HD44780_4BIT1LINE 0x20 // 4-bit 1-line font 5x7
#define LCD_HD44780_4BIT2LINES 0x28 // 4-bit 2-lines font 5x7
#define LCD_HD44780_8BIT1LINE 0x30 // 8-bit 1-line font 5x7
#define LCD_HD44780_8BIT2LINES 0x38 // 8-bit 2-lines font 5x7
 
// Select Apropriate Mode
#if LCD_INTERFACE_BITS==4
#if LCD_LINES == 1
#define LCD_HD44780_FNSET LCD_HD44780_4BIT1LINE // 4-bit 1-line
#else
#define LCD_HD44780_FNSET LCD_HD44780_4BIT2LINES // 4-bit 2-lines
#endif
#elif LCD_INTERFACE_BITS==8
#if LCD_LINES == 1
#define LCD_HD44780_FNSET LCD_HD44780_8BIT1LINE // 8-bit 1-line
#else
#define LCD_HD44780_FNSET LCD_HD44780_8BIT2LINES // 8-bit 2-lines
#endif
#endif
 
 
// User Defined Chars
// ------------------
 
// Definitions only.
// Because these definitions may be sent to lcd via printf,
// it is impossible to contain 0 bytes (end of string in C)
// so we ored 0x80 to each byte
 
#define LCD_CHAR_SPACE "\x80\x80\x80\x80\x80\x80\x80\x80" /* space (blank char) */
#define LCD_CHAR_BAT100 "\x8E\x9F\x9F\x9F\x9F\x9F\x9F\x1F" /* symbol battery full */
#define LCD_CHAR_BAT50 "\x8E\x9F\x91\x91\x93\x97\x9F\x1F" /* symbol baterry half */
#define LCD_CHAR_BAT0 "\x8E\x9F\x91\x91\x91\x91\x91\x1F" /* symbol baterry empty */
#define LCD_CHAR_UP "\x80\x84\x8E\x95\x84\x84\x84\x80" /* symbol arrow up */
#define LCD_CHAR_DOWN "\x80\x84\x84\x84\x95\x8E\x84\x80" /* symbol arrow down */
#define LCD_CHAR_LUA "\x84\x8E\x91\x91\x9F\x91\x91\x80" /* A s carkou */
#define LCD_CHAR_LLA "\x81\x82\x8E\x81\x9F\x91\x8F\x80" /* a s carkou */
#define LCD_CHAR_HUC "\x8A\x8E\x91\x90\x90\x91\x8E\x80" /* C s hackem */
#define LCD_CHAR_HLC "\x8A\x84\x8E\x90\x90\x91\x8E\x80" /* c s hackem */
#define LCD_CHAR_HUD "\x8A\x9C\x92\x91\x91\x92\x9C\x80" /* D s hackem */
#define LCD_CHAR_HLD "\x85\x83\x8D\x93\x91\x91\x8F\x80" /* d s hackem */
#define LCD_CHAR_LUE "\x84\x9F\x90\x90\x9E\x90\x9F\x80" /* E s carkou */
#define LCD_CHAR_LLE "\x81\x82\x8E\x91\x9F\x90\x8E\x80" /* e s carkou */
#define LCD_CHAR_HUE "\x8A\x9F\x90\x9E\x90\x90\x9F\x80" /* E s hackem */
#define LCD_CHAR_HLE "\x8A\x84\x8E\x91\x9F\x90\x8E\x80" /* e s hackem */
#define LCD_CHAR_LUI "\x84\x8E\x84\x84\x84\x84\x8E\x80" /* I s carkou */
#define LCD_CHAR_LLI "\x82\x84\x80\x8C\x84\x84\x8E\x80" /* i s carkou */
#define LCD_CHAR_HUN "\x8A\x95\x91\x99\x95\x93\x91\x80" /* N s hackem */
#define LCD_CHAR_HLN "\x8A\x84\x96\x99\x91\x91\x91\x80" /* n s hackem */
#define LCD_CHAR_LUO "\x84\x8E\x91\x91\x91\x91\x8E\x80" /* O s carkou */
#define LCD_CHAR_LLO "\x82\x84\x8E\x91\x91\x91\x8E\x80" /* o s carkou */
#define LCD_CHAR_HUR "\x8A\x9E\x91\x9E\x94\x92\x91\x80" /* R s hackem */
#define LCD_CHAR_HLR "\x8A\x84\x96\x99\x90\x90\x90\x80" /* r s hackem */
#define LCD_CHAR_HUS "\x8A\x8F\x90\x8E\x81\x81\x9E\x80" /* S s hackem */
#define LCD_CHAR_HLS "\x8A\x84\x8E\x90\x8E\x81\x9E\x80" /* s s hackem */
#define LCD_CHAR_HUT "\x8A\x9F\x84\x84\x84\x84\x84\x80" /* T s hackem */
#define LCD_CHAR_HLT "\x8A\x8C\x9C\x88\x88\x89\x86\x80" /* t s hackem */
#define LCD_CHAR_LUU "\x82\x95\x91\x91\x91\x91\x8E\x80" /* U s carkou */
#define LCD_CHAR_LLU "\x82\x84\x91\x91\x91\x93\x8D\x80" /* u s carkou */
#define LCD_CHAR_CUU "\x86\x97\x91\x91\x91\x91\x8E\x80" /* U s krouzkem */
#define LCD_CHAR_CLU "\x86\x86\x91\x91\x91\x91\x8E\x80" /* u s krouzkem */
#define LCD_CHAR_LUY "\x82\x95\x91\x8A\x84\x84\x84\x80" /* Y s carkou */
#define LCD_CHAR_LLY "\x82\x84\x91\x91\x8F\x81\x8E\x80" /* y s carkou */
#define LCD_CHAR_HUZ "\x8A\x9F\x81\x82\x84\x88\x9F\x80" /* Z s hackem */
#define LCD_CHAR_HLZ "\x8A\x84\x9F\x82\x84\x88\x9F\x80" /* z s hackem */
 
 
// Program
// -------
 
 
static int8_t lcd_posx; // Mirror Register with Position X (1..LCD_CHARS)
#if LCD_LINES > 1
static int8_t lcd_posy; // Mirror Register with Position Y (1..LCD_LINES)
#endif
 
 
// Send a Nibble or Byte to the LCD COntroller
static void
lcd_send_nibble(uint8_t rs, uint8_t data)
{
// Select Register or Data
if (rs)
LCD_RS_PORT |= (1<<LCD_RS_BIT);
else
LCD_RS_PORT &= ~(1<<LCD_RS_BIT);
 
// Put 4bit/8bit data
LCD_DATA_PORT = (LCD_DATA_PORT & ~LCD_DATA_MASK) | ((data<<LCD_DATA_BIT)&LCD_DATA_MASK);
_delay_us(1); // Data Setup Time
 
// Click Enable on and off
LCD_E_PORT |= 1<<LCD_E_BIT;
_delay_us(1);
LCD_E_PORT &= ~(1<<LCD_E_BIT);
_delay_us(40);
}
 
 
// Send a Byte to the LCD Controller
#if LCD_INTERFACE_BITS == 4
static void
lcd_send_byte(uint8_t rs, uint8_t data)
{
lcd_send_nibble(rs, data >> 4); // High Order Data
lcd_send_nibble(rs, data); // Low Order Data
}
#else
#define lcd_send_byte lcd_send_nibble
#endif
 
 
// Send a Command to the LCD Controller (RS=0)
#define lcd_send_cmd(n) lcd_send_byte(0, (n))
 
 
// Send a Data Byte to the LCD Controller (RS=1)
#define lcd_send_data(n) lcd_send_byte(1, (n))
 
 
// Goto Home
void
lcd_home()
{
lcd_send_cmd(LCD_HD44780_HOME); // Zero Cursor Position and Offset
#if LCD_LINES > 1
lcd_posx=lcd_posy=1;
#else
lcd_posx=1;
#endif
_delay_ms(2);
}
 
 
// Clear Display
void
lcd_clear()
{
lcd_send_cmd(LCD_HD44780_CLR); // Clear Memory
_delay_ms(2);
}
 
 
// Switch Cursor On
void
lcd_cursor_on()
{
lcd_send_cmd(LCD_HD44780_CURSORON);
}
 
 
// Switch Cursor Off
void
lcd_cursor_off()
{
lcd_send_cmd(LCD_HD44780_CURSOROFF);
}
 
 
// Clear Display and Goto Home with no Cursor
void
lcd_clear_home()
{
lcd_clear(); // Clear Memory
lcd_home(); // Zero Cursor Position and Offset
lcd_cursor_off(); // No Cursor
}
 
 
// Move to Position (1,1 is the first position)
void lcd_gotoxy(uint8_t x, uint8_t y)
{
uint8_t Adr;
 
Adr=x-1;
#if LCD_LINES > 1
switch (y)
{
case 2:
Adr+=LCD_LINE_2;
break;
#if LCD_LINES > 2
case 3:
Adr+=LCD_LINE_3;
break;
case 4:
Adr+=LCD_LINE_4;
break;
#endif
}
#endif
 
lcd_send_cmd(0x80 | (Adr & 0x7F) );
lcd_posx=x;
#if LCD_LINES > 1
lcd_posy=y;
#endif
}
 
 
// Increment Position
void
lcd_inc_pos()
{
// Next Position
lcd_posx++;
 
// Correct End of Line
#if LCD_LINES == 1
if (lcd_posx > 40)
lcd_posx = 1;
#elif LCD_LINES == 2
if (lcd_posx > 40)
{
lcd_posx = 1;
lcd_posy++; // on the Next Line
}
#elif LCD_LINES > 2
if ( ((lcd_posy & 1) && (lcd_posx > LCD_CHARS)) // Odd Lines are Short
|| (lcd_posx > 40-LCD_CHARS) ) // Memory is up to 40 Bytes
{
lcd_posx = 1; // Position 1
lcd_posy++; // on the Next Line
}
#endif
 
// Correct End of Last Line
#if LCD_LINES > 1
if (lcd_posy > LCD_LINES)
{
lcd_posy = 1;
}
#endif
}
 
// Decrement Position
void
lcd_dec_pos()
{
// Correct Beginning of Line
if (--lcd_posx==0) // Step Left
{ // If Beginning of the Line
#if LCD_LINES > 1
if(--lcd_posy==0); // Step Up
lcd_posy = LCD_LINES; // If we are on Top Go to the Bottom
#endif
#if LCD_LINES <= 2
lcd_posx = 40;
#else
if(lcd_posy & 1) // If Odd Line (the Short One)
lcd_posx = LCD_CHARS; // Set End of the Short Line
else // Else
lcd_posx = 40-LCD_CHARS; // Set End of Long Line
#endif
}
}
 
// Move Cursor Left
void
lcd_cursor_left()
{
lcd_send_cmd(LCD_HD44780_CURSORLEFT);
lcd_dec_pos();
}
 
 
// Move Cursor Right
void
lcd_cursor_right()
{
lcd_send_cmd(LCD_HD44780_CURSORRIGHT);
lcd_inc_pos();
}
 
 
// Init LCD Display
void
lcd_init(void)
{
// Port Init Direction
LCD_E_PORT &= ~_BV(LCD_E_BIT); // Enable off
LCD_E_DDR |= _BV(LCD_E_BIT); // Enable as Output
LCD_RS_DDR |= _BV(LCD_RS_BIT); // Register Select as Output
#ifdef LCD_RW
LCD_RW_DDR |= _BV(LCD_RW_BIT); // Read Write as Output
#endif
LCD_DATA_DDR |= LCD_DATA_MASK; // Data as Output
 
// Initial Delay
_delay_ms(40); // Delay for Vcc
 
// Sync 8/4 bit Interface
#if LCD_INTERFACE_BITS == 4
lcd_send_nibble(0, LCD_HD44780_8BIT1LINE >> 4); // 8 bit mode - sync nibble/byte
_delay_ms(4.1);
lcd_send_nibble(0, LCD_HD44780_8BIT1LINE >> 4);
_delay_us(100);
lcd_send_nibble(0, LCD_HD44780_8BIT1LINE >> 4);
// Set 4 bit mode
lcd_send_nibble(0, LCD_HD44780_FNSET >> 4);
#elif LCD_INTERFACE_BITS == 8
lcd_send_nibble(0, LCD_HD44780_8BIT1LINE); // 8 bit mode - sync nibble/byte
_delay_ms(4.1);
lcd_send_nibble(0, LCD_HD44780_8BIT1LINE);
_delay_us(100);
lcd_send_nibble(0, LCD_HD44780_8BIT1LINE);
#endif
 
// Set and Init
lcd_send_cmd(LCD_HD44780_FNSET); // 4/8 bits 1/2 lines
lcd_send_cmd(LCD_HD44780_ENTMODE_DEF); // increment/decrement, shift/no shift
lcd_clear_home(); // display on, no cursor, clear and home
}
 
 
// LCD Char Output
int
lcd_putc(char c)
{
static uint8_t mode=0;
 
switch (c)
{
case '\f':
lcd_clear_home(); // Clear Display
break;
 
case '\n':
#if LCD_LINES > 1
if (lcd_posy <= LCD_LINES) // Go to the Next Line
lcd_posy++;
#endif
 
case '\r':
#if LCD_LINES > 1
lcd_gotoxy(1,lcd_posy); // Go to the Beginning of the Line
#else
lcd_home();
#endif
break;
 
case '\b':
lcd_cursor_left(); // Cursor (Position) Move Back
break;
 
default:
if (mode==0 && c=='\v') // Startr of Definition String
{
mode=1; // Mode Next Char will be Defined Char
break;
}
if (mode==1) // First Char is Position Number
{
lcd_send_cmd(0x40 | ((c & 0x07)<<3) ); // Set CGRAM Address
mode++; // Mode Define Char Patern
break;
}
if (mode==2 && c=='\v') // End of Definition String
{
mode=0;
#if LCD_LINES > 1
lcd_gotoxy(lcd_posx,lcd_posy);
#else
lcd_gotoxy(lcd_posx,1);
#endif
break;
}
if (mode != 2) // Ordinary Chars
{
if (c<0x20) // Remap User Defind Char
c &= 0x07; // from rage 0x10-0x1F to 0x00-0x0f
lcd_inc_pos(); // Next Position
}
lcd_send_data(c); // Send Byte to LCD
break;
}
return 0; // Success
}
 
 
// LCD Char Output (for Stream Library)
#ifdef _STDIO_H_
static int
lcd_putc_stream(char c, FILE *unused)
{
return lcd_putc(c);
}
#endif
/programy/C/avr/LCD/lcd_hd44780_test.c
0,0 → 1,95
/* ---------------------------------------------------------------------------
* AVR_MLIB - HD 44780 LCD Display Driver Test Application
* www.mlab.cz miho 2008
* ---------------------------------------------------------------------------
* Simple test application for lcd_hd44780.h LCD library. This code ilustates
* how to use and configure the library functions.
* ---------------------------------------------------------------------------
* 00.00 2008/03/28 First Version
* 00.01 2008/04/19 Improved
* ---------------------------------------------------------------------------
*/
 
 
// Required Libraries
// ------------------
 
// Delay
 
#define F_CPU 1000000UL // CPU Frequency
#include <util/delay.h> // Delay Routines
 
// Standard Output Library
 
#include <stdio.h> // For printf
 
 
// LCD Display Interface
// ---------------------
 
// LCD Port Settings
 
#define LCD_DATA B // 4 or 8 bits field (lsb port)
#define LCD_DATA_BIT 0
 
#define LCD_RS D // Register Select
#define LCD_RS_BIT 4
 
#define LCD_E D // Enable
#define LCD_E_BIT 3
 
// LCD Display Parameters
 
#define LCD_INTERFACE_BITS 4 // 4 or 8 bit interface
#define LCD_LINES 2 // 1 or 2 or 4 lines
#define LCD_CHARS 16 // usualy 16 or 20, important for 4 line display only
 
// LCD Library
 
#include "lcd_hd44780.h"
 
 
// Test Application
// ----------------
 
 
// Define Output Stream to LCD
static FILE lcd_stream = FDEV_SETUP_STREAM(lcd_putc_stream, NULL, _FDEV_SETUP_WRITE);
 
 
// Main Program
int main ()
{
int i;
 
DDRB|= (1<<DDB6);
DDRB|= (1<<DDB7);
PORTB &= ~(1<<PB6);
 
stdout = &lcd_stream; // Connect stdout to LCD Stream
 
lcd_init(); // Init LCD (interface and display module)
lcd_gotoxy(1,1);
printf("stavebnice MLAB");
_delay_ms(1000);
 
while(1)
{
lcd_gotoxy(2,2);
printf("demo aplikace");
_delay_ms(1000);
lcd_gotoxy(2,2);
printf(" ");
 
PORTB|= (1<<PB6);
_delay_ms(500);
PORTB &= ~(1<<PB6);
_delay_ms(5000);
 
PORTB|= (1<<PB7);
_delay_ms(500);
PORTB &= ~(1<<PB7);
_delay_ms(5000);
 
}
}
/programy/C/avr/LCD/lcd_hd44780_test.hex
0,0 → 1,174
:100000000C9446000C9465000C9465000C946500FB
:100010000C9465000C9465000C9465000C946500CC
:100020000C9465000C9465000C9465000C946500BC
:100030000C9465000C9465000C9465000C946500AC
:100040000C9465000C9465000C9465000C9465009C
:100050000C9465000C9465000C9465000C9465008C
:100060000C9465000C9465000C9465000C9465007C
:100070000C9465000C9465000C9465000C9465006C
:100080000C9465000C9465000C94650011241FBE4F
:10009000CFEFD0E1DEBFCDBF11E0A0E0B1E0E6E8F8
:1000A000FAE000E00BBF02C007900D92AC33B1073D
:1000B000D9F711E0ACE3B1E001C01D92A534B1075E
:1000C000E1F70E9480010C9442050C940000882303
:1000D00011F0949A01C0949888B36F70807F862B3A
:1000E00088BB81E0982F9A95F1F7939A8A95F1F75A
:1000F00093988DE08A95F1F708950F931F93082F39
:10010000162F62956F700E946700612F802F0E94EA
:1001100067001F910F91089562E080E00E947D00CA
:1001200081E080933E0180933D0184EF91E001974F
:10013000F1F7089561E080E00E947D0084EF91E096
:100140000197F1F708956EE080E00E947D00089528
:100150006CE080E00E947D0008950E949A000E9459
:100160008C000E94A80008950F931F93182F062F4C
:10017000682F6150023009F4605C606880E00E9482
:100180007D0010933D0100933E011F910F91089552
:1001900080913D018F5F80933D01893244F081E081
:1001A00080933D0180913E018F5F80933E0180915D
:1001B0003E0183301CF081E080933E0108958091E0
:1001C0003D01815080933D01882331F482E080938A
:1001D0003E0188E280933D01089560E180E00E9445
:1001E0007D000E94DF00089564E180E00E947D00B0
:1001F0000E94C800089593988B9A8C9A87B38F6059
:1002000087BB80E197E20197F1F763E080E00E940D
:10021000670081E094E00197F1F763E080E00E94DD
:10022000670081E28A95F1F763E080E00E94670051
:1002300062E080E00E94670068E280E00E947D004A
:1002400066E080E00E947D000E94AD0008951F934B
:10025000182F8A3069F08B301CF48830B9F413C041
:100260008C3019F08D3091F40AC00E94AD0041C06D
:1002700080913E0183301CF48F5F80933E0160913A
:100280003E0181E02AC00E94ED0033C080913C0114
:10029000882321F41B3021F581E012C0813099F4CC
:1002A000612F772767FD70956770707083E0660F28
:1002B000771F8A95E1F7606480E00E947D0082E00C
:1002C00080933C0116C0823059F41B3071F41092B7
:1002D0003C0160913E0180913D010E94B40009C043
:1002E00010320CF417700E94C800612F81E00E9448
:1002F0007D0080E090E01F9108950E9427010895FD
:10030000CFEFD0E1DEBFCDBFBE9ABF9AC6988DE2D7
:1003100091E090934201809341010E94FB0061E0D3
:1003200081E00E94B40080E091E09F938F930E944F
:10033000EE0120E137E20F900F9089E190E0019704
:10034000F1F721503040C9F700E111E0CEE1D1E0F2
:1003500062E082E00E94B4001F930F930E94EE01BE
:1003600020E137E20F900F9089E190E00197F1F7DB
:1003700021503040C9F762E082E00E94B400DF9370
:10038000CF930E94EE01C69A28E833E10F900F90B8
:1003900089E190E00197F1F721503040C9F7C69804
:1003A00020E533EC89E190E00197F1F721503040EE
:1003B000C9F7C79A28E833E189E190E00197F1F79E
:1003C00021503040C9F7C79820E533EC89E190E02F
:1003D0000197F1F721503040C9F7BACFA2E0B0E061
:1003E000E4EFF1E00C941B05FE01379661917191E9
:1003F000FA83E983AF0180914101909142010E940B
:100400000502E2E022960C943705A7E1B0E0EBE0AC
:10041000F2E00C940B058824992454012C017C8B68
:100420006B8B3A01FC0117821682838181FD03C028
:100430008FEF9FEF7EC2CC24DD249E012F5F3F4FC4
:100440003F8B2E8B65C2C0FE48C2832D80538A30FD
:10045000D8F430E3331641F48D85882329F4C3FCA6
:1004600003C0E0E0F1E073C08AE0FD85F802C0015E
:1004700011248053830D8D8787FF02C02FE72D87BE
:10048000C3FC40C22D843EC2960128703070C3FE6A
:1004900005C08D85882311F491E09D87E7E6E3157B
:1004A0006CF1F5E63F160CF068C083E5381609F4E8
:1004B00089C08315BCF09BE2391609F442C093153C
:1004C0004CF0E0E23E1609F440C0F3E23F1609F0BA
:1004D000FCC143C02DE23216E9F13EE2331609F0C9
:1004E000F4C140C083E6381609F44DC083150CF4FE
:1004F00081C098E5391609F0E8C120C0E0E73E1652
:1005000009F4A2C0E3155CF0FCE63F1689F12FE682
:10051000321689F039E6331609F0D7C16BC085E78A
:10052000381609F499C098E7391641F0E3E73E160A
:1005300009F0CBC130C0F8E0F88B8EC020E1288BE9
:100540008BC080E190E0C82AD92AE0E2F0E0CE2A10
:10055000DF2AD8C120E830E00DC080E490E0C82A4E
:10056000D92AD0C1E8E0F0E0CE2ADF2A1D86CAC130
:1005700024E030E0C22AD32AC5C13FE3832E2A9467
:1005800023E6322E30C1F30180802A9422E030E04D
:10059000620E731E28C1F301A081B1814D01232B8E
:1005A00049F0FD856F2F772767FD7095CD010E947B
:1005B000B10418C0FD0101900020E9F73197EA1B52
:1005C000E88B11C0F301808191814C01232B41F014
:1005D000FD856F2F772767FD70950E94A60402C0E6
:1005E0000E949D04888B22E030E0620E731E3889E1
:1005F000231AF9C0C2FE08C0F30180819181A28153
:10060000B38124E030E009C0F30180819181AA2701
:1006100097FDA095BA2F22E030E0620E731E4C01C8
:100620005D01B7FF0CC082E090E0C82AD92AB094DF
:10063000A09490948094811C911CA11CB11CEFEBA0
:10064000FFEFCE22DF2221C020E430E0C22AD32AED
:1006500098E7392E30E1388BC2FE08C0F301808163
:100660009181A281B38124E030E007C0F301808151
:100670009181AA27BB2722E030E0620E731E4C0155
:100680005D018FEC9FEFC822D92285017401FE0124
:100690003196FF87EE87F8898F2E9924AA24BB24F0
:1006A000232D21522D8BC801B701A50194010E9471
:1006B000E9046A301CF03D89630F01C0605DEE857E
:1006C000FF856193FF87EE87C801B701A5019401FB
:1006D0000E94E90479018A0121153105410551057E
:1006E00011F78824992454014E85FE894F1B842ECE
:1006F000C60182739070892B09F02A94C6FE07C048
:100700002889203111F482E001C081E0281AC3FE5B
:1007100012C08D85282F332727FD3095842F9927E8
:10072000821793072CF0E7EFFFEFCE22DF2203C002
:10073000FD85F41BFD87860108701070C3FE03C0A1
:100740002D85221A01C0241AC60180789170892B48
:1007500031F00AC0B20180E290E00E94BC042A9409
:10076000822D8F5F1816B4F3C1FE04C0B2018DE272
:1007700090E00BC0C4FE04C0B2018BE290E005C063
:10078000C5FE05C0B20180E290E00E94BC04C6FE36
:100790000FC0B20180E390E00E94BC043889303180
:1007A00039F4B201832D992787FD90950E94BC04EE
:1007B000D0FC06C00AC0B20180E390E00E94BC04F5
:1007C0002A94822D8F5F1816B4F3012B31F40BC0DD
:1007D000B20180E390E00E94BC048D8581508D873A
:1007E0008F5F1816ACF3F601E078F070FA8BE98BA6
:1007F000C7FE06C00AC0B20180E290E00E94BC04BD
:100800002A94822D8F5F1816B4F3F3E63F1641F455
:10081000B201882D992787FD90950E94BC0445C0A0
:1008200023E73216B1F464017401188909C0F70195
:1008300081917F01B201992787FD90950E94BC04A8
:100840001150A8F74601F8898F0E911C2FEF288BC5
:100850002CC033E5331619F00E851F851FC06401C7
:100860008401F88808C0F8018491B20199270E9498
:10087000BC040F5F1F4FFA94FFEFFF16A1F746016C
:100880002889820E911CF88B10C0F80182918F018B
:10089000B201992787FD90950E94BC042E893F895B
:1008A0000217130791F71F870E8789899A89892B69
:1008B00031F426C0B20180E290E00E94BC042A9488
:1008C000822D8F5F1816B4F31BC0B201832D9927B8
:1008D00087FD90950E94BC0413C095E2391641F43F
:1008E000EAE0E88B22241D8681E0C82ED12C0AC0C4
:1008F000B201832D992787FD90950E94BC0402C008
:10090000CC24DD242B893C892F5F3F4F3C8B2B8BE4
:10091000F201838183FF04C0EB89FC89349003C01A
:10092000EB89FC893080332009F08DCDF20186817E
:100930009781E2E167960C942705FC010590002061
:10094000E9F7809590958E0F9F1F0895FC01059003
:10095000615070400110D8F7809590958E0F9F1FC1
:100960000895FC016150704001900110D8F7809506
:1009700090958E0F9F1F08950F931F93CF93DF9332
:100980008C01EB018B81992781FF1BC082FF0DC079
:100990002E813F818C819D812817390764F4E8817D
:1009A000F9810193F983E88306C0E885F985802FF2
:1009B0000995892B31F48E819F8101969F838E83C7
:1009C00002C00FEF1FEFC801DF91CF911F910F9170
:1009D0000895A1E21A2EAA1BBB1BFD010DC0AA1F80
:1009E000BB1FEE1FFF1FA217B307E407F50720F098
:1009F000A21BB30BE40BF50B661F771F881F991F13
:100A00001A9469F760957095809590959B01AC015B
:100A1000BD01CF0108952F923F924F925F926F9246
:100A20007F928F929F92AF92BF92CF92DF92EF927E
:100A3000FF920F931F93CF93DF93CDB7DEB7CA1BFF
:100A4000DB0B0FB6F894DEBF0FBECDBF09942A882A
:100A5000398848885F846E847D848C849B84AA84D2
:100A6000B984C884DF80EE80FD800C811B81AA815F
:100A7000B981CE0FD11D0FB6F894DEBF0FBECDBF2A
:060A8000ED010895FFCF17
:100A86007374617665626E696365204D4C41420000
:100A960064656D6F2061706C696B61636500202011
:100AA60020202020202020202020202000000000C0
:0C0AB60002000000007D010000000000B4
:00000001FF
/programy/C/avr/LCD/lcd_hd44780_test.map
0,0 → 1,456
Archive member included because of file (symbol)
 
/usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_exit.o)
/usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/crtm128.o (exit)
/usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_clear_bss.o)
lcd_hd44780_test.o (__do_clear_bss)
/usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(iob.o)
lcd_hd44780_test.o (__iob)
/usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(printf.o)
lcd_hd44780_test.o (printf)
/usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(vfprintf_std.o)
/usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(printf.o) (vfprintf)
/usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(strlen_P.o)
/usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(vfprintf_std.o) (strlen_P)
/usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(strnlen_P.o)
/usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(vfprintf_std.o) (strnlen_P)
/usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(strnlen.o)
/usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(vfprintf_std.o) (strnlen)
/usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(fputc.o)
/usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(vfprintf_std.o) (fputc)
/usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_udivmodsi4.o)
/usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(vfprintf_std.o) (__udivmodsi4)
/usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_prologue.o)
/usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(printf.o) (__prologue_saves__)
/usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_epilogue.o)
/usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(printf.o) (__epilogue_restores__)
 
Allocating common symbols
Common symbol size file
 
__iob 0x6 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(iob.o)
 
Memory Configuration
 
Name Origin Length Attributes
text 0x00000000 0x00020000 xr
data 0x00800060 0x0000ffa0 rw !x
eeprom 0x00810000 0x00010000 rw !x
fuse 0x00820000 0x00000400 rw !x
lock 0x00830000 0x00000400 rw !x
signature 0x00840000 0x00000400 rw !x
*default* 0x00000000 0xffffffff
 
Linker script and memory map
 
Address of section .data set to 0x800100
LOAD /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/crtm128.o
LOAD lcd_hd44780_test.o
LOAD /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a
LOAD /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a
LOAD /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a
 
.hash
*(.hash)
 
.dynsym
*(.dynsym)
 
.dynstr
*(.dynstr)
 
.gnu.version
*(.gnu.version)
 
.gnu.version_d
*(.gnu.version_d)
 
.gnu.version_r
*(.gnu.version_r)
 
.rel.init
*(.rel.init)
 
.rela.init
*(.rela.init)
 
.rel.text
*(.rel.text)
*(.rel.text.*)
*(.rel.gnu.linkonce.t*)
 
.rela.text
*(.rela.text)
*(.rela.text.*)
*(.rela.gnu.linkonce.t*)
 
.rel.fini
*(.rel.fini)
 
.rela.fini
*(.rela.fini)
 
.rel.rodata
*(.rel.rodata)
*(.rel.rodata.*)
*(.rel.gnu.linkonce.r*)
 
.rela.rodata
*(.rela.rodata)
*(.rela.rodata.*)
*(.rela.gnu.linkonce.r*)
 
.rel.data
*(.rel.data)
*(.rel.data.*)
*(.rel.gnu.linkonce.d*)
 
.rela.data
*(.rela.data)
*(.rela.data.*)
*(.rela.gnu.linkonce.d*)
 
.rel.ctors
*(.rel.ctors)
 
.rela.ctors
*(.rela.ctors)
 
.rel.dtors
*(.rel.dtors)
 
.rela.dtors
*(.rela.dtors)
 
.rel.got
*(.rel.got)
 
.rela.got
*(.rela.got)
 
.rel.bss
*(.rel.bss)
 
.rela.bss
*(.rela.bss)
 
.rel.plt
*(.rel.plt)
 
.rela.plt
*(.rela.plt)
 
.text 0x00000000 0xa86
*(.vectors)
.vectors 0x00000000 0x8c /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/crtm128.o
0x00000000 __vectors
0x00000000 __vector_default
*(.vectors)
*(.progmem.gcc*)
*(.progmem*)
0x0000008c . = ALIGN (0x2)
0x0000008c __trampolines_start = .
*(.trampolines)
.trampolines 0x0000008c 0x0 linker stubs
*(.trampolines*)
0x0000008c __trampolines_end = .
*(.jumptables)
*(.jumptables*)
*(.lowtext)
*(.lowtext*)
0x0000008c __ctors_start = .
*(.ctors)
0x0000008c __ctors_end = .
0x0000008c __dtors_start = .
*(.dtors)
0x0000008c __dtors_end = .
SORT(*)(.ctors)
SORT(*)(.dtors)
*(.init0)
.init0 0x0000008c 0x0 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/crtm128.o
0x0000008c __init
*(.init0)
*(.init1)
*(.init1)
*(.init2)
.init2 0x0000008c 0xc /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/crtm128.o
*(.init2)
*(.init3)
*(.init3)
*(.init4)
.init4 0x00000098 0x1a /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/crtm128.o
0x00000098 __do_copy_data
.init4 0x000000b2 0x10 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_clear_bss.o)
0x000000b2 __do_clear_bss
*(.init4)
*(.init5)
*(.init5)
*(.init6)
*(.init6)
*(.init7)
*(.init7)
*(.init8)
*(.init8)
*(.init9)
.init9 0x000000c2 0x8 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/crtm128.o
*(.init9)
*(.text)
.text 0x000000ca 0x4 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/crtm128.o
0x000000ca __vector_22
0x000000ca __vector_28
0x000000ca __vector_1
0x000000ca __vector_32
0x000000ca __vector_34
0x000000ca __vector_24
0x000000ca __vector_12
0x000000ca __bad_interrupt
0x000000ca __vector_6
0x000000ca __vector_31
0x000000ca __vector_3
0x000000ca __vector_23
0x000000ca __vector_30
0x000000ca __vector_25
0x000000ca __vector_11
0x000000ca __vector_13
0x000000ca __vector_17
0x000000ca __vector_19
0x000000ca __vector_7
0x000000ca __vector_27
0x000000ca __vector_5
0x000000ca __vector_33
0x000000ca __vector_4
0x000000ca __vector_9
0x000000ca __vector_2
0x000000ca __vector_21
0x000000ca __vector_15
0x000000ca __vector_29
0x000000ca __vector_8
0x000000ca __vector_26
0x000000ca __vector_14
0x000000ca __vector_10
0x000000ca __vector_16
0x000000ca __vector_18
0x000000ca __vector_20
.text 0x000000ce 0x30e lcd_hd44780_test.o
0x0000015a lcd_clear_home
0x00000168 lcd_gotoxy
0x0000024e lcd_putc
0x000001be lcd_dec_pos
0x00000146 lcd_cursor_on
0x00000134 lcd_clear
0x00000118 lcd_home
0x000001f6 lcd_init
0x00000300 main
0x00000190 lcd_inc_pos
0x000001da lcd_cursor_left
0x000001e8 lcd_cursor_right
0x00000150 lcd_cursor_off
.text 0x000003dc 0x0 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_exit.o)
.text 0x000003dc 0x0 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_clear_bss.o)
.text 0x000003dc 0x0 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(iob.o)
.text 0x000003dc 0x2e /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(printf.o)
0x000003dc printf
.text 0x0000040a 0x530 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(vfprintf_std.o)
0x0000040a vfprintf
.text 0x0000093a 0x12 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(strlen_P.o)
0x0000093a strlen_P
.text 0x0000094c 0x16 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(strnlen_P.o)
0x0000094c strnlen_P
.text 0x00000962 0x16 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(strnlen.o)
0x00000962 strnlen
.text 0x00000978 0x5a /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(fputc.o)
0x00000978 fputc
.text 0x000009d2 0x0 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_udivmodsi4.o)
.text 0x000009d2 0x0 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_prologue.o)
.text 0x000009d2 0x0 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_epilogue.o)
0x000009d2 . = ALIGN (0x2)
*(.text.*)
.text.libgcc 0x000009d2 0x0 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_exit.o)
.text.libgcc 0x000009d2 0x0 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_clear_bss.o)
.text.libgcc 0x000009d2 0x44 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_udivmodsi4.o)
0x000009d2 __udivmodsi4
.text.libgcc 0x00000a16 0x38 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_prologue.o)
0x00000a16 __prologue_saves__
.text.libgcc 0x00000a4e 0x36 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_epilogue.o)
0x00000a4e __epilogue_restores__
0x00000a84 . = ALIGN (0x2)
*(.fini9)
.fini9 0x00000a84 0x0 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_exit.o)
0x00000a84 exit
0x00000a84 _exit
*(.fini9)
*(.fini8)
*(.fini8)
*(.fini7)
*(.fini7)
*(.fini6)
*(.fini6)
*(.fini5)
*(.fini5)
*(.fini4)
*(.fini4)
*(.fini3)
*(.fini3)
*(.fini2)
*(.fini2)
*(.fini1)
*(.fini1)
*(.fini0)
.fini0 0x00000a84 0x2 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_exit.o)
*(.fini0)
0x00000a86 _etext = .
 
.data 0x00800100 0x3c load address 0x00000a86
0x00800100 PROVIDE (__data_start, .)
*(.data)
.data 0x00800100 0x0 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/crtm128.o
.data 0x00800100 0x3b lcd_hd44780_test.o
.data 0x0080013b 0x0 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_exit.o)
.data 0x0080013b 0x0 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_clear_bss.o)
.data 0x0080013b 0x0 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(iob.o)
.data 0x0080013b 0x0 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(printf.o)
.data 0x0080013b 0x0 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(vfprintf_std.o)
.data 0x0080013b 0x0 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(strlen_P.o)
.data 0x0080013b 0x0 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(strnlen_P.o)
.data 0x0080013b 0x0 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(strnlen.o)
.data 0x0080013b 0x0 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(fputc.o)
.data 0x0080013b 0x0 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_udivmodsi4.o)
.data 0x0080013b 0x0 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_prologue.o)
.data 0x0080013b 0x0 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_epilogue.o)
*(.data*)
*(.rodata)
*(.rodata*)
*(.gnu.linkonce.d*)
0x0080013c . = ALIGN (0x2)
*fill* 0x0080013b 0x1 00
0x0080013c _edata = .
0x0080013c PROVIDE (__data_end, .)
 
.bss 0x0080013c 0x9 load address 0x00000ac2
0x0080013c PROVIDE (__bss_start, .)
*(.bss)
.bss 0x0080013c 0x0 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/crtm128.o
.bss 0x0080013c 0x3 lcd_hd44780_test.o
.bss 0x0080013f 0x0 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_exit.o)
.bss 0x0080013f 0x0 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_clear_bss.o)
.bss 0x0080013f 0x0 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(iob.o)
.bss 0x0080013f 0x0 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(printf.o)
.bss 0x0080013f 0x0 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(vfprintf_std.o)
.bss 0x0080013f 0x0 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(strlen_P.o)
.bss 0x0080013f 0x0 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(strnlen_P.o)
.bss 0x0080013f 0x0 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(strnlen.o)
.bss 0x0080013f 0x0 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(fputc.o)
.bss 0x0080013f 0x0 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_udivmodsi4.o)
.bss 0x0080013f 0x0 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_prologue.o)
.bss 0x0080013f 0x0 /usr/lib/gcc/avr/4.2.2/avr5/libgcc.a(_epilogue.o)
*(.bss*)
*(COMMON)
COMMON 0x0080013f 0x6 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(iob.o)
0x0080013f __iob
0x00800145 PROVIDE (__bss_end, .)
0x00000a86 __data_load_start = LOADADDR (.data)
0x00000ac2 __data_load_end = (__data_load_start + SIZEOF (.data))
 
.noinit 0x00800145 0x0
0x00800145 PROVIDE (__noinit_start, .)
*(.noinit*)
0x00800145 PROVIDE (__noinit_end, .)
0x00800145 _end = .
0x00800145 PROVIDE (__heap_start, .)
 
.eeprom 0x00810000 0x0
*(.eeprom*)
0x00810000 __eeprom_end = .
 
.fuse
*(.fuse)
*(.lfuse)
*(.hfuse)
*(.efuse)
 
.lock
*(.lock*)
 
.signature
*(.signature*)
 
.stab 0x00000000 0x2598
*(.stab)
.stab 0x00000000 0x414 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/crtm128.o
.stab 0x00000414 0x11a0 lcd_hd44780_test.o
0x11ac (size before relaxing)
.stab 0x000015b4 0x2c4 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(iob.o)
0x30c (size before relaxing)
.stab 0x00001878 0x1b0 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(printf.o)
0x390 (size before relaxing)
.stab 0x00001a28 0x7e0 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(vfprintf_std.o)
0x9c0 (size before relaxing)
.stab 0x00002208 0x84 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(strlen_P.o)
0x90 (size before relaxing)
.stab 0x0000228c 0x9c /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(strnlen_P.o)
0xa8 (size before relaxing)
.stab 0x00002328 0x9c /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(strnlen.o)
0xa8 (size before relaxing)
.stab 0x000023c4 0x1d4 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/libc.a(fputc.o)
0x3b4 (size before relaxing)
 
.stabstr 0x00000000 0x14c9
*(.stabstr)
.stabstr 0x00000000 0x14c9 /usr/lib/gcc/avr/4.2.2/../../../../avr/lib/avr5/crtm128.o
 
.stab.excl
*(.stab.excl)
 
.stab.exclstr
*(.stab.exclstr)
 
.stab.index
*(.stab.index)
 
.stab.indexstr
*(.stab.indexstr)
 
.comment
*(.comment)
 
.debug
*(.debug)
 
.line
*(.line)
 
.debug_srcinfo
*(.debug_srcinfo)
 
.debug_sfnames
*(.debug_sfnames)
 
.debug_aranges
*(.debug_aranges)
 
.debug_pubnames
*(.debug_pubnames)
 
.debug_info
*(.debug_info)
*(.gnu.linkonce.wi.*)
 
.debug_abbrev
*(.debug_abbrev)
 
.debug_line
*(.debug_line)
 
.debug_frame
*(.debug_frame)
 
.debug_str
*(.debug_str)
 
.debug_loc
*(.debug_loc)
 
.debug_macinfo
*(.debug_macinfo)
OUTPUT(lcd_hd44780_test.out elf32-avr)
LOAD linker stubs
/programy/C/avr/LCD/lcd_hd44780_test.out
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:executable
+*
\ No newline at end of property
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/programy/C/avr/SDcard/Makefile
0,0 → 1,61
# makefile, written by guido socher
MCU=atmega64
CC=avr-gcc
OBJCOPY=avr-objcopy
# optimize for size:
CFLAGS=-g -mmcu=$(MCU) -Wall -Wstrict-prototypes -Os -mcall-prologues
#-------------------
all: main.hex
#-------------------
help:
@echo "Usage: make all|load|load_pre|rdfuses|wrfuse1mhz|wrfuse4mhz|wrfusecrystal"
@echo "Warning: you will not be able to undo wrfusecrystal unless you connect an"
@echo " external crystal! uC is dead after wrfusecrystal if you do not"
@echo " have an external crystal."
#-------------------
main.hex : main.out
$(OBJCOPY) -R .eeprom -O ihex main.out main.hex
main.out : main.o
$(CC) $(CFLAGS) -o main.out -Wl,-Map,main.map main.o
main.o : main.c
$(CC) $(CFLAGS) -Os -c main.c
#------------------
load: $(FILE).hex
./prg_load_uc $(FILE).hex
# here is a pre-compiled version in case you have trouble with
# your development environment
load_pre: $(FILE).hex
./prg_load_uc $(FILE)_pre.hex
#
loaduisp: $(FILE).hex
./prg_load_uc -u $(FILE).hex
# here is a pre-compiled version in case you have trouble with
# your development environment
load_preuisp: $(FILE)_pre.hex
./prg_load_uc -u avrm8ledtest.hex
#-------------------
# fuse byte settings:
# Atmel AVR ATmega8
# Fuse Low Byte = 0xe1 (1MHz internal), 0xe3 (4MHz internal), 0xe4 (8MHz internal)
# Fuse High Byte = 0xd9
# Factory default is 0xe1 for low byte and 0xd9 for high byte
# Check this with make rdfuses
rdfuses:
./prg_fusebit_uc -r
# use internal RC oscillator 1 Mhz
wrfuse1mhz:
./prg_fusebit_uc -w 1
# use internal RC oscillator 4 Mhz
wrfuse4mhz:
./prg_fusebit_uc -w 4
# use external 3-8 Mhz crystal
# Warning: you can not reset this to intenal unless you connect a crystal!!
wrfusecrystal:
@echo "Warning: The external crystal setting can not be changed back without a working crystal"
@echo " You have 3 seconds to abort this with crtl-c"
@sleep 3
./prg_fusebit_uc -w 0
#-------------------
clean:
rm -f *.o *.map *.out *.hex
#-------------------
/programy/C/avr/SDcard/diskio.h
0,0 → 1,71
/*-----------------------------------------------------------------------
/ Low level disk interface modlue include file R0.05 (C)ChaN, 2007
/-----------------------------------------------------------------------*/
 
#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*);
void disk_timerproc (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 */
 
 
/* 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
#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
/programy/C/avr/SDcard/ff.c
0,0 → 1,2036
/*----------------------------------------------------------------------------/
/ FatFs - FAT file system module R0.06 (C)ChaN, 2008
/-----------------------------------------------------------------------------/
/ The FatFs module is an experimenal project to implement FAT file system to
/ cheap microcontrollers. This is a free software and is opened for education,
/ research and development under license policy of following trems.
/
/ Copyright (C) 2008, ChaN, all right reserved.
/
/ * The FatFs module is a free software and there is no warranty.
/ * You can use, modify and/or redistribute it for personal, non-profit or
/ commercial use without restriction under your responsibility.
/ * Redistributions of source code must retain the above copyright notice.
/
/-----------------------------------------------------------------------------/
/ Feb 26,'06 R0.00 Prototype.
/
/ Apr 29,'06 R0.01 First stable version.
/
/ Jun 01,'06 R0.02 Added FAT12 support.
/ Removed unbuffered mode.
/ Fixed a problem on small (<32M) patition.
/ Jun 10,'06 R0.02a Added a configuration option (_FS_MINIMUM).
/
/ Sep 22,'06 R0.03 Added f_rename().
/ Changed option _FS_MINIMUM to _FS_MINIMIZE.
/ Dec 11,'06 R0.03a Improved cluster scan algolithm to write files fast.
/ Fixed f_mkdir() creates incorrect directory on FAT32.
/
/ Feb 04,'07 R0.04 Supported multiple drive system.
/ Changed some interfaces for multiple drive system.
/ Changed f_mountdrv() to f_mount().
/ Added f_mkfs().
/ Apr 01,'07 R0.04a Supported multiple partitions on a plysical drive.
/ Added a capability of extending file size to f_lseek().
/ Added minimization level 3.
/ Fixed an endian sensitive code in f_mkfs().
/ May 05,'07 R0.04b Added a configuration option _USE_NTFLAG.
/ Added FSInfo support.
/ Fixed DBCS name can result FR_INVALID_NAME.
/ Fixed short seek (<= csize) collapses the file object.
/
/ Aug 25,'07 R0.05 Changed arguments of f_read(), f_write() and f_mkfs().
/ Fixed f_mkfs() on FAT32 creates incorrect FSInfo.
/ Fixed f_mkdir() on FAT32 creates incorrect directory.
/ Feb 03,'08 R0.05a Added f_truncate() and f_utime().
/ Fixed off by one error at FAT sub-type determination.
/ Fixed btr in f_read() can be mistruncated.
/ Fixed cached sector is not flushed when create and close
/ without write.
/
/ Apr 01,'08 R0.06 Added fputc(), fputs(), fprintf() and fgets().
/ Improved performance of f_lseek() on moving to the same
/ or following cluster.
/---------------------------------------------------------------------------*/
 
#include <string.h>
#include "ff.h" /* FatFs declarations */
#include "diskio.h" /* Include file for user provided disk functions */
 
 
/*--------------------------------------------------------------------------
 
Module Private Functions
 
---------------------------------------------------------------------------*/
 
static
FATFS *FatFs[_DRIVES]; /* Pointer to the file system objects (logical drives) */
static
WORD fsid; /* File system mount ID */
 
 
 
/*-----------------------------------------------------------------------*/
/* Change window offset */
/*-----------------------------------------------------------------------*/
 
static
BOOL move_window ( /* TRUE: successful, FALSE: failed */
FATFS *fs, /* File system object */
DWORD sector /* Sector number to make apperance in the fs->win[] */
) /* Move to zero only writes back dirty window */
{
DWORD wsect;
 
 
wsect = fs->winsect;
if (wsect != sector) { /* Changed current window */
#if !_FS_READONLY
BYTE n;
if (fs->winflag) { /* Write back dirty window if needed */
if (disk_write(fs->drive, fs->win, wsect, 1) != RES_OK)
return FALSE;
fs->winflag = 0;
if (wsect < (fs->fatbase + fs->sects_fat)) { /* In FAT area */
for (n = fs->n_fats; n >= 2; n--) { /* Refrect the change to FAT copy */
wsect += fs->sects_fat;
disk_write(fs->drive, fs->win, wsect, 1);
}
}
}
#endif
if (sector) {
if (disk_read(fs->drive, fs->win, sector, 1) != RES_OK)
return FALSE;
fs->winsect = sector;
}
}
return TRUE;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Clean-up cached data */
/*-----------------------------------------------------------------------*/
 
#if !_FS_READONLY
static
FRESULT sync ( /* FR_OK: successful, FR_RW_ERROR: failed */
FATFS *fs /* File system object */
)
{
fs->winflag = 1;
if (!move_window(fs, 0)) return FR_RW_ERROR;
#if _USE_FSINFO
/* Update FSInfo sector if needed */
if (fs->fs_type == FS_FAT32 && fs->fsi_flag) {
fs->winsect = 0;
memset(fs->win, 0, 512);
ST_WORD(&fs->win[BS_55AA], 0xAA55);
ST_DWORD(&fs->win[FSI_LeadSig], 0x41615252);
ST_DWORD(&fs->win[FSI_StrucSig], 0x61417272);
ST_DWORD(&fs->win[FSI_Free_Count], fs->free_clust);
ST_DWORD(&fs->win[FSI_Nxt_Free], fs->last_clust);
disk_write(fs->drive, fs->win, fs->fsi_sector, 1);
fs->fsi_flag = 0;
}
#endif
/* Make sure that no pending write process in the physical drive */
if (disk_ioctl(fs->drive, CTRL_SYNC, NULL) != RES_OK)
return FR_RW_ERROR;
return FR_OK;
}
#endif
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Get a cluster status */
/*-----------------------------------------------------------------------*/
 
static
DWORD get_cluster ( /* 0,>=2: successful, 1: failed */
FATFS *fs, /* File system object */
DWORD clust /* Cluster# to get the link information */
)
{
WORD wc, bc;
DWORD fatsect;
 
 
if (clust >= 2 && clust < fs->max_clust) { /* Is it a valid cluster#? */
fatsect = fs->fatbase;
switch (fs->fs_type) {
case FS_FAT12 :
bc = (WORD)clust * 3 / 2;
if (!move_window(fs, fatsect + (bc / SS(fs)))) break;
wc = fs->win[bc & (SS(fs) - 1)]; bc++;
if (!move_window(fs, fatsect + (bc / SS(fs)))) break;
wc |= (WORD)fs->win[bc & (SS(fs) - 1)] << 8;
return (clust & 1) ? (wc >> 4) : (wc & 0xFFF);
 
case FS_FAT16 :
if (!move_window(fs, fatsect + (clust / (SS(fs) / 2)))) break;
return LD_WORD(&fs->win[((WORD)clust * 2) & (SS(fs) - 1)]);
 
case FS_FAT32 :
if (!move_window(fs, fatsect + (clust / (SS(fs) / 4)))) break;
return LD_DWORD(&fs->win[((WORD)clust * 4) & (SS(fs) - 1)]) & 0x0FFFFFFF;
}
}
 
return 1; /* Out of cluster range, or an error occured */
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Change a cluster status */
/*-----------------------------------------------------------------------*/
 
#if !_FS_READONLY
static
BOOL put_cluster ( /* TRUE: successful, FALSE: failed */
FATFS *fs, /* File system object */
DWORD clust, /* Cluster# to change (must be 2 to fs->max_clust-1) */
DWORD val /* New value to mark the cluster */
)
{
WORD bc;
BYTE *p;
DWORD fatsect;
 
 
fatsect = fs->fatbase;
switch (fs->fs_type) {
case FS_FAT12 :
bc = (WORD)clust * 3 / 2;
if (!move_window(fs, fatsect + (bc / SS(fs)))) return FALSE;
p = &fs->win[bc & (SS(fs) - 1)];
*p = (clust & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val;
bc++;
fs->winflag = 1;
if (!move_window(fs, fatsect + (bc / SS(fs)))) return FALSE;
p = &fs->win[bc & (SS(fs) - 1)];
*p = (clust & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F));
break;
 
case FS_FAT16 :
if (!move_window(fs, fatsect + (clust / (SS(fs) / 2)))) return FALSE;
ST_WORD(&fs->win[((WORD)clust * 2) & (SS(fs) - 1)], (WORD)val);
break;
 
case FS_FAT32 :
if (!move_window(fs, fatsect + (clust / (SS(fs) / 4)))) return FALSE;
ST_DWORD(&fs->win[((WORD)clust * 4) & (SS(fs) - 1)], val);
break;
 
default :
return FALSE;
}
fs->winflag = 1;
return TRUE;
}
#endif /* !_FS_READONLY */
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Remove a cluster chain */
/*-----------------------------------------------------------------------*/
 
#if !_FS_READONLY
static
BOOL remove_chain ( /* TRUE: successful, FALSE: failed */
FATFS *fs, /* File system object */
DWORD clust /* Cluster# to remove chain from */
)
{
DWORD nxt;
 
 
while (clust >= 2 && clust < fs->max_clust) {
nxt = get_cluster(fs, clust);
if (nxt == 1) return FALSE;
if (!put_cluster(fs, clust, 0)) return FALSE;
if (fs->free_clust != 0xFFFFFFFF) {
fs->free_clust++;
#if _USE_FSINFO
fs->fsi_flag = 1;
#endif
}
clust = nxt;
}
return TRUE;
}
#endif
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Stretch or create a cluster chain */
/*-----------------------------------------------------------------------*/
 
#if !_FS_READONLY
static
DWORD create_chain ( /* 0: No free cluster, 1: Error, >=2: New cluster number */
FATFS *fs, /* File system object */
DWORD clust /* Cluster# to stretch, 0 means create new */
)
{
DWORD cstat, ncl, scl, mcl = fs->max_clust;
 
 
if (clust == 0) { /* Create new chain */
scl = fs->last_clust; /* Get suggested start point */
if (scl == 0 || scl >= mcl) scl = 1;
}
else { /* Stretch existing chain */
cstat = get_cluster(fs, clust); /* Check the cluster status */
if (cstat < 2) return 1; /* It is an invalid cluster */
if (cstat < mcl) return cstat; /* It is already followed by next cluster */
scl = clust;
}
 
ncl = scl; /* Start cluster */
for (;;) {
ncl++; /* Next cluster */
if (ncl >= mcl) { /* Wrap around */
ncl = 2;
if (ncl > scl) return 0; /* No free custer */
}
cstat = get_cluster(fs, ncl); /* Get the cluster status */
if (cstat == 0) break; /* Found a free cluster */
if (cstat == 1) return 1; /* Any error occured */
if (ncl == scl) return 0; /* No free custer */
}
 
if (!put_cluster(fs, ncl, 0x0FFFFFFF)) return 1; /* Mark the new cluster "in use" */
if (clust != 0 && !put_cluster(fs, clust, ncl)) return 1; /* Link it to previous one if needed */
 
fs->last_clust = ncl; /* Update fsinfo */
if (fs->free_clust != 0xFFFFFFFF) {
fs->free_clust--;
#if _USE_FSINFO
fs->fsi_flag = 1;
#endif
}
 
return ncl; /* Return new cluster number */
}
#endif /* !_FS_READONLY */
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Get sector# from cluster# */
/*-----------------------------------------------------------------------*/
 
static
DWORD clust2sect ( /* !=0: sector number, 0: failed - invalid cluster# */
FATFS *fs, /* File system object */
DWORD clust /* Cluster# to be converted */
)
{
clust -= 2;
if (clust >= (fs->max_clust - 2)) return 0; /* Invalid cluster# */
return clust * fs->csize + fs->database;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Move directory pointer to next */
/*-----------------------------------------------------------------------*/
 
static
BOOL next_dir_entry ( /* TRUE: successful, FALSE: could not move next */
DIR *dj /* Pointer to directory object */
)
{
DWORD clust;
WORD idx;
 
 
idx = dj->index + 1;
if ((idx & ((SS(dj->fs) - 1) / 32)) == 0) { /* Table sector changed? */
dj->sect++; /* Next sector */
if (dj->clust == 0) { /* In static table */
if (idx >= dj->fs->n_rootdir) return FALSE; /* Reached to end of table */
} else { /* In dynamic table */
if (((idx / (SS(dj->fs) / 32)) & (dj->fs->csize - 1)) == 0) { /* Cluster changed? */
clust = get_cluster(dj->fs, dj->clust); /* Get next cluster */
if (clust < 2 || clust >= dj->fs->max_clust) /* Reached to end of table */
return FALSE;
dj->clust = clust; /* Initialize for new cluster */
dj->sect = clust2sect(dj->fs, clust);
}
}
}
dj->index = idx; /* Lower several bits of dj->index indicates offset in dj->sect */
return TRUE;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Get file status from directory entry */
/*-----------------------------------------------------------------------*/
 
#if _FS_MINIMIZE <= 1
static
void get_fileinfo ( /* No return code */
FILINFO *finfo, /* Ptr to store the file information */
const BYTE *dir /* Ptr to the directory entry */
)
{
BYTE n, c, a;
char *p;
 
 
p = &finfo->fname[0];
a = _USE_NTFLAG ? dir[DIR_NTres] : 0; /* NT flag */
for (n = 0; n < 8; n++) { /* Convert file name (body) */
c = dir[n];
if (c == ' ') break;
if (c == 0x05) c = 0xE5;
if (a & 0x08 && c >= 'A' && c <= 'Z') c += 0x20;
*p++ = c;
}
if (dir[8] != ' ') { /* Convert file name (extension) */
*p++ = '.';
for (n = 8; n < 11; n++) {
c = dir[n];
if (c == ' ') break;
if (a & 0x10 && c >= 'A' && c <= 'Z') c += 0x20;
*p++ = c;
}
}
*p = '\0';
 
finfo->fattrib = dir[DIR_Attr]; /* Attribute */
finfo->fsize = LD_DWORD(&dir[DIR_FileSize]); /* Size */
finfo->fdate = LD_WORD(&dir[DIR_WrtDate]); /* Date */
finfo->ftime = LD_WORD(&dir[DIR_WrtTime]); /* Time */
}
#endif /* _FS_MINIMIZE <= 1 */
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Pick a paragraph and create the name in format of directory entry */
/*-----------------------------------------------------------------------*/
 
static
char make_dirfile ( /* 1: error - detected an invalid format, '\0'or'/': next character */
const char **path, /* Pointer to the file path pointer */
char *dirname /* Pointer to directory name buffer {Name(8), Ext(3), NT flag(1)} */
)
{
BYTE n, t, c, a, b;
 
 
memset(dirname, ' ', 8+3); /* Fill buffer with spaces */
a = 0; b = 0x18; /* NT flag */
n = 0; t = 8;
for (;;) {
c = *(*path)++;
if (c == '\0' || c == '/') { /* Reached to end of str or directory separator */
if (n == 0) break;
dirname[11] = _USE_NTFLAG ? (a & b) : 0;
return c;
}
if (c <= ' ' || c == 0x7F) break; /* Reject invisible chars */
if (c == '.') {
if (!(a & 1) && n >= 1 && n <= 8) { /* Enter extension part */
n = 8; t = 11; continue;
}
break;
}
if (_USE_SJIS &&
((c >= 0x81 && c <= 0x9F) || /* Accept S-JIS code */
(c >= 0xE0 && c <= 0xFC))) {
if (n == 0 && c == 0xE5) /* Change heading \xE5 to \x05 */
c = 0x05;
a ^= 0x01; goto md_l2;
}
if (c == '"') break; /* Reject " */
if (c <= ')') goto md_l1; /* Accept ! # $ % & ' ( ) */
if (c <= ',') break; /* Reject * + , */
if (c <= '9') goto md_l1; /* Accept - 0-9 */
if (c <= '?') break; /* Reject : ; < = > ? */
if (!(a & 1)) { /* These checks are not applied to S-JIS 2nd byte */
if (c == '|') break; /* Reject | */
if (c >= '[' && c <= ']') break;/* Reject [ \ ] */
if (_USE_NTFLAG && c >= 'A' && c <= 'Z')
(t == 8) ? (b &= 0xF7) : (b &= 0xEF);
if (c >= 'a' && c <= 'z') { /* Convert to upper case */
c -= 0x20;
if (_USE_NTFLAG) (t == 8) ? (a |= 0x08) : (a |= 0x10);
}
}
md_l1:
a &= 0xFE;
md_l2:
if (n >= t) break;
dirname[n++] = c;
}
return 1;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Trace a file path */
/*-----------------------------------------------------------------------*/
 
static
FRESULT trace_path ( /* FR_OK(0): successful, !=0: error code */
DIR *dj, /* Pointer to directory object to return last directory */
char *fn, /* Pointer to last segment name to return {file(8),ext(3),attr(1)} */
const char *path, /* Full-path string to trace a file or directory */
BYTE **dir /* Pointer to pointer to found entry to retutn */
)
{
DWORD clust;
char ds;
BYTE *dptr = NULL;
FATFS *fs = dj->fs;
 
 
/* Initialize directory object */
clust = fs->dirbase;
if (fs->fs_type == FS_FAT32) {
dj->clust = dj->sclust = clust;
dj->sect = clust2sect(fs, clust);
} else {
dj->clust = dj->sclust = 0;
dj->sect = clust;
}
dj->index = 0;
 
if (*path == '\0') { /* Null path means the root directory */
*dir = NULL; return FR_OK;
}
 
for (;;) {
ds = make_dirfile(&path, fn); /* Get a paragraph into fn[] */
if (ds == 1) return FR_INVALID_NAME;
for (;;) {
if (!move_window(fs, dj->sect)) return FR_RW_ERROR;
dptr = &fs->win[(dj->index & ((SS(fs) - 1) / 32)) * 32]; /* Pointer to the directory entry */
if (dptr[DIR_Name] == 0) /* Has it reached to end of dir? */
return !ds ? FR_NO_FILE : FR_NO_PATH;
if (dptr[DIR_Name] != 0xE5 /* Matched? */
&& !(dptr[DIR_Attr] & AM_VOL)
&& !memcmp(&dptr[DIR_Name], fn, 8+3) ) break;
if (!next_dir_entry(dj)) /* Next directory pointer */
return !ds ? FR_NO_FILE : FR_NO_PATH;
}
if (!ds) { *dir = dptr; return FR_OK; } /* Matched with end of path */
if (!(dptr[DIR_Attr] & AM_DIR)) return FR_NO_PATH; /* Cannot trace because it is a file */
clust = ((DWORD)LD_WORD(&dptr[DIR_FstClusHI]) << 16) | LD_WORD(&dptr[DIR_FstClusLO]); /* Get cluster# of the directory */
dj->clust = dj->sclust = clust; /* Restart scanning at the new directory */
dj->sect = clust2sect(fs, clust);
dj->index = 2;
}
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Reserve a directory entry */
/*-----------------------------------------------------------------------*/
 
#if !_FS_READONLY
static
FRESULT reserve_direntry ( /* FR_OK: successful, FR_DENIED: no free entry, FR_RW_ERROR: a disk error occured */
DIR *dj, /* Target directory to create new entry */
BYTE **dir /* Pointer to pointer to created entry to retutn */
)
{
DWORD clust, sector;
BYTE c, n, *dptr;
FATFS *fs = dj->fs;
 
 
/* Re-initialize directory object */
clust = dj->sclust;
if (clust != 0) { /* Dyanmic directory table */
dj->clust = clust;
dj->sect = clust2sect(fs, clust);
} else { /* Static directory table */
dj->sect = fs->dirbase;
}
dj->index = 0;
 
do {
if (!move_window(fs, dj->sect)) return FR_RW_ERROR;
dptr = &fs->win[(dj->index & ((SS(dj->fs) - 1) / 32)) * 32]; /* Pointer to the directory entry */
c = dptr[DIR_Name];
if (c == 0 || c == 0xE5) { /* Found an empty entry */
*dir = dptr; return FR_OK;
}
} while (next_dir_entry(dj)); /* Next directory pointer */
/* Reached to end of the directory table */
 
/* Abort when it is a static table or could not stretch dynamic table */
if (clust == 0 || !(clust = create_chain(fs, dj->clust))) return FR_DENIED;
if (clust == 1 || !move_window(fs, 0)) return FR_RW_ERROR;
 
/* Cleanup the expanded table */
fs->winsect = sector = clust2sect(fs, clust);
memset(fs->win, 0, SS(fs));
for (n = fs->csize; n; n--) {
if (disk_write(fs->drive, fs->win, sector, 1) != RES_OK)
return FR_RW_ERROR;
sector++;
}
fs->winflag = 1;
*dir = fs->win;
 
return FR_OK;
}
#endif /* !_FS_READONLY */
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Load boot record and check if it is an FAT boot record */
/*-----------------------------------------------------------------------*/
 
static
BYTE check_fs ( /* 0:The FAT boot record, 1:Valid boot record but not an FAT, 2:Not a boot record or error */
FATFS *fs, /* File system object */
DWORD sect /* Sector# (lba) to check if it is an FAT boot record or not */
)
{
if (disk_read(fs->drive, fs->win, sect, 1) != RES_OK) /* Load boot record */
return 2;
if (LD_WORD(&fs->win[BS_55AA]) != 0xAA55) /* Check record signature (always placed at offset 510 even if the sector size is >512) */
return 2;
 
if (!memcmp(&fs->win[BS_FilSysType], "FAT", 3)) /* Check FAT signature */
return 0;
if (!memcmp(&fs->win[BS_FilSysType32], "FAT32", 5) && !(fs->win[BPB_ExtFlags] & 0x80))
return 0;
 
return 1;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Make sure that the file system is valid */
/*-----------------------------------------------------------------------*/
 
static
FRESULT auto_mount ( /* FR_OK(0): successful, !=0: any error occured */
const char **path, /* Pointer to pointer to the path name (drive number) */
FATFS **rfs, /* Pointer to pointer to the found file system object */
BYTE chk_wp /* !=0: Check media write protection for write access */
)
{
BYTE drv, fmt, *tbl;
DSTATUS stat;
DWORD bootsect, fatsize, totalsect, maxclust;
const char *p = *path;
FATFS *fs;
 
 
/* Get drive number from the path name */
while (*p == ' ') p++; /* Strip leading spaces */
drv = p[0] - '0'; /* Is there a drive number? */
if (drv <= 9 && p[1] == ':')
p += 2; /* Found a drive number, get and strip it */
else
drv = 0; /* No drive number is given, use drive number 0 as default */
if (*p == '/') p++; /* Strip heading slash */
*path = p; /* Return pointer to the path name */
 
/* Check if the drive number is valid or not */
if (drv >= _DRIVES) return FR_INVALID_DRIVE; /* Is the drive number valid? */
*rfs = fs = FatFs[drv]; /* Returen pointer to the corresponding file system object */
if (!fs) return FR_NOT_ENABLED; /* Is the file system object registered? */
 
if (fs->fs_type) { /* If the logical drive has been mounted */
stat = disk_status(fs->drive);
if (!(stat & STA_NOINIT)) { /* and physical drive is kept initialized (has not been changed), */
#if !_FS_READONLY
if (chk_wp && (stat & STA_PROTECT)) /* Check write protection if needed */
return FR_WRITE_PROTECTED;
#endif
return FR_OK; /* The file system object is valid */
}
}
 
/* The logical drive must be re-mounted. Following code attempts to mount the logical drive */
 
memset(fs, 0, sizeof(FATFS)); /* Clean-up the file system object */
fs->drive = LD2PD(drv); /* Bind the logical drive and a physical drive */
stat = disk_initialize(fs->drive); /* Initialize low level disk I/O layer */
if (stat & STA_NOINIT) /* Check if the drive is ready */
return FR_NOT_READY;
#if S_MAX_SIZ > 512 /* Get disk sector size if needed */
if (disk_ioctl(drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK || SS(fs) > S_MAX_SIZ)
return FR_NO_FILESYSTEM;
#endif
#if !_FS_READONLY
if (chk_wp && (stat & STA_PROTECT)) /* Check write protection if needed */
return FR_WRITE_PROTECTED;
#endif
/* Search FAT partition on the drive */
fmt = check_fs(fs, bootsect = 0); /* Check sector 0 as an SFD format */
if (fmt == 1) { /* Not an FAT boot record, it may be patitioned */
/* Check a partition listed in top of the partition table */
tbl = &fs->win[MBR_Table + LD2PT(drv) * 16]; /* Partition table */
if (tbl[4]) { /* Is the partition existing? */
bootsect = LD_DWORD(&tbl[8]); /* Partition offset in LBA */
fmt = check_fs(fs, bootsect); /* Check the partition */
}
}
if (fmt || LD_WORD(&fs->win[BPB_BytsPerSec]) != SS(fs)) /* No valid FAT patition is found */
return FR_NO_FILESYSTEM;
 
/* Initialize the file system object */
fatsize = LD_WORD(&fs->win[BPB_FATSz16]); /* Number of sectors per FAT */
if (!fatsize) fatsize = LD_DWORD(&fs->win[BPB_FATSz32]);
fs->sects_fat = fatsize;
fs->n_fats = fs->win[BPB_NumFATs]; /* Number of FAT copies */
fatsize *= fs->n_fats; /* (Number of sectors in FAT area) */
fs->fatbase = bootsect + LD_WORD(&fs->win[BPB_RsvdSecCnt]); /* FAT start sector (lba) */
fs->csize = fs->win[BPB_SecPerClus]; /* Number of sectors per cluster */
fs->n_rootdir = LD_WORD(&fs->win[BPB_RootEntCnt]); /* Nmuber of root directory entries */
totalsect = LD_WORD(&fs->win[BPB_TotSec16]); /* Number of sectors on the file system */
if (!totalsect) totalsect = LD_DWORD(&fs->win[BPB_TotSec32]);
fs->max_clust = maxclust = (totalsect /* max_clust = Last cluster# + 1 */
- LD_WORD(&fs->win[BPB_RsvdSecCnt]) - fatsize - fs->n_rootdir / (SS(fs)/32)
) / fs->csize + 2;
 
fmt = FS_FAT12; /* Determine the FAT sub type */
if (maxclust >= 0xFF7) fmt = FS_FAT16;
if (maxclust >= 0xFFF7) fmt = FS_FAT32;
 
if (fmt == FS_FAT32)
fs->dirbase = LD_DWORD(&fs->win[BPB_RootClus]); /* Root directory start cluster */
else
fs->dirbase = fs->fatbase + fatsize; /* Root directory start sector (lba) */
fs->database = fs->fatbase + fatsize + fs->n_rootdir / (SS(fs)/32); /* Data start sector (lba) */
 
#if !_FS_READONLY
/* Initialize allocation information */
fs->free_clust = 0xFFFFFFFF;
#if _USE_FSINFO
/* Get fsinfo if needed */
if (fmt == FS_FAT32) {
fs->fsi_sector = bootsect + LD_WORD(&fs->win[BPB_FSInfo]);
if (disk_read(fs->drive, fs->win, fs->fsi_sector, 1) == RES_OK &&
LD_WORD(&fs->win[BS_55AA]) == 0xAA55 &&
LD_DWORD(&fs->win[FSI_LeadSig]) == 0x41615252 &&
LD_DWORD(&fs->win[FSI_StrucSig]) == 0x61417272) {
fs->last_clust = LD_DWORD(&fs->win[FSI_Nxt_Free]);
fs->free_clust = LD_DWORD(&fs->win[FSI_Free_Count]);
}
}
#endif
#endif
 
fs->fs_type = fmt; /* FAT syb-type */
fs->id = ++fsid; /* File system mount ID */
return FR_OK;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Check if the file/dir object is valid or not */
/*-----------------------------------------------------------------------*/
 
static
FRESULT validate ( /* FR_OK(0): The object is valid, !=0: Invalid */
const FATFS *fs, /* Pointer to the file system object */
WORD id /* Member id of the target object to be checked */
)
{
if (!fs || !fs->fs_type || fs->id != id)
return FR_INVALID_OBJECT;
if (disk_status(fs->drive) & STA_NOINIT)
return FR_NOT_READY;
 
return FR_OK;
}
 
 
 
 
/*--------------------------------------------------------------------------
 
Public Functions
 
--------------------------------------------------------------------------*/
 
 
 
/*-----------------------------------------------------------------------*/
/* Mount/Unmount a Locical Drive */
/*-----------------------------------------------------------------------*/
 
FRESULT f_mount (
BYTE drv, /* Logical drive number to be mounted/unmounted */
FATFS *fs /* Pointer to new file system object (NULL for unmount)*/
)
{
if (drv >= _DRIVES) return FR_INVALID_DRIVE;
 
if (FatFs[drv]) FatFs[drv]->fs_type = 0; /* Clear old object */
 
FatFs[drv] = fs; /* Register and clear new object */
if (fs) fs->fs_type = 0;
 
return FR_OK;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Open or Create a File */
/*-----------------------------------------------------------------------*/
 
FRESULT f_open (
FIL *fp, /* Pointer to the blank file object */
const char *path, /* Pointer to the file name */
BYTE mode /* Access mode and file open mode flags */
)
{
FRESULT res;
DIR dj;
BYTE *dir;
char fn[8+3+1];
 
 
fp->fs = NULL; /* Clear file object */
#if !_FS_READONLY
mode &= (FA_READ|FA_WRITE|FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW);
res = auto_mount(&path, &dj.fs, (BYTE)(mode & (FA_WRITE|FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW)));
#else
mode &= FA_READ;
res = auto_mount(&path, &dj.fs, 0);
#endif
if (res != FR_OK) return res;
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */
 
#if !_FS_READONLY
/* Create or Open a file */
if (mode & (FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW)) {
DWORD ps, rs;
if (res != FR_OK) { /* No file, create new */
if (res != FR_NO_FILE) return res;
res = reserve_direntry(&dj, &dir);
if (res != FR_OK) return res;
memset(dir, 0, 32); /* Initialize the new entry with open name */
memcpy(&dir[DIR_Name], fn, 8+3);
dir[DIR_NTres] = fn[11];
mode |= FA_CREATE_ALWAYS;
}
else { /* Any object is already existing */
if (mode & FA_CREATE_NEW) /* Cannot create new */
return FR_EXIST;
if (!dir || (dir[DIR_Attr] & (AM_RDO|AM_DIR))) /* Cannot overwrite it (R/O or DIR) */
return FR_DENIED;
if (mode & FA_CREATE_ALWAYS) { /* Resize it to zero if needed */
rs = ((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | LD_WORD(&dir[DIR_FstClusLO]); /* Get start cluster */
ST_WORD(&dir[DIR_FstClusHI], 0); /* cluster = 0 */
ST_WORD(&dir[DIR_FstClusLO], 0);
ST_DWORD(&dir[DIR_FileSize], 0); /* size = 0 */
dj.fs->winflag = 1;
ps = dj.fs->winsect; /* Remove the cluster chain */
if (!remove_chain(dj.fs, rs) || !move_window(dj.fs, ps))
return FR_RW_ERROR;
dj.fs->last_clust = rs - 1; /* Reuse the cluster hole */
}
}
if (mode & FA_CREATE_ALWAYS) {
dir[DIR_Attr] = 0; /* Reset attribute */
ps = get_fattime();
ST_DWORD(&dir[DIR_CrtTime], ps); /* Created time */
dj.fs->winflag = 1;
mode |= FA__WRITTEN; /* Set file changed flag */
}
}
/* Open an existing file */
else {
#endif /* !_FS_READONLY */
if (res != FR_OK) return res; /* Trace failed */
if (!dir || (dir[DIR_Attr] & AM_DIR)) /* It is a directory */
return FR_NO_FILE;
#if !_FS_READONLY
if ((mode & FA_WRITE) && (dir[DIR_Attr] & AM_RDO)) /* R/O violation */
return FR_DENIED;
}
fp->dir_sect = dj.fs->winsect; /* Pointer to the directory entry */
fp->dir_ptr = dir;
#endif
fp->flag = mode; /* File access mode */
fp->org_clust = /* File start cluster */
((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | LD_WORD(&dir[DIR_FstClusLO]);
fp->fsize = LD_DWORD(&dir[DIR_FileSize]); /* File size */
fp->fptr = 0; fp->csect = 255; /* File pointer */
fp->curr_sect = 0;
fp->fs = dj.fs; fp->id = dj.fs->id; /* Owner file system object of the file */
 
return FR_OK;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Read File */
/*-----------------------------------------------------------------------*/
 
FRESULT f_read (
FIL *fp, /* Pointer to the file object */
void *buff, /* Pointer to data buffer */
UINT btr, /* Number of bytes to read */
UINT *br /* Pointer to number of bytes read */
)
{
FRESULT res;
DWORD clust, sect, remain;
UINT rcnt, cc;
BYTE *rbuff = buff;
 
 
*br = 0;
res = validate(fp->fs, fp->id); /* Check validity of the object */
if (res != FR_OK) return res;
if (fp->flag & FA__ERROR) return FR_RW_ERROR; /* Check error flag */
if (!(fp->flag & FA_READ)) return FR_DENIED; /* Check access mode */
remain = fp->fsize - fp->fptr;
if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */
 
for ( ; btr; /* Repeat until all data transferred */
rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) {
if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */
if (fp->csect >= fp->fs->csize) { /* On the cluster boundary? */
clust = (fp->fptr == 0) ? /* On the top of the file? */
fp->org_clust : get_cluster(fp->fs, fp->curr_clust);
if (clust < 2 || clust >= fp->fs->max_clust) goto fr_error;
fp->curr_clust = clust; /* Update current cluster */
fp->csect = 0; /* Reset sector address in the cluster */
}
sect = clust2sect(fp->fs, fp->curr_clust) + fp->csect; /* Get current sector */
cc = btr / SS(fp->fs); /* When remaining bytes >= sector size, */
if (cc) { /* Read maximum contiguous sectors directly */
if (fp->csect + cc > fp->fs->csize) /* Clip at cluster boundary */
cc = fp->fs->csize - fp->csect;
if (disk_read(fp->fs->drive, rbuff, sect, (BYTE)cc) != RES_OK)
goto fr_error;
fp->csect += (BYTE)cc; /* Next sector address in the cluster */
rcnt = SS(fp->fs) * cc; /* Number of bytes transferred */
continue;
}
if (sect != fp->curr_sect) { /* Is window offset changed? */
#if !_FS_READONLY
if (fp->flag & FA__DIRTY) { /* Write back file I/O buffer if needed */
if (disk_write(fp->fs->drive, fp->buffer, fp->curr_sect, 1) != RES_OK)
goto fr_error;
fp->flag &= (BYTE)~FA__DIRTY;
}
#endif
if (disk_read(fp->fs->drive, fp->buffer, sect, 1) != RES_OK) /* Fill file I/O buffer with file data */
goto fr_error;
fp->curr_sect = sect;
}
fp->csect++; /* Next sector address in the cluster */
}
rcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs)); /* Get partial sector from file I/O buffer */
if (rcnt > btr) rcnt = btr;
memcpy(rbuff, &fp->buffer[fp->fptr % SS(fp->fs)], rcnt);
}
 
return FR_OK;
 
fr_error: /* Abort this file due to an unrecoverable error */
fp->flag |= FA__ERROR;
return FR_RW_ERROR;
}
 
 
 
 
#if !_FS_READONLY
/*-----------------------------------------------------------------------*/
/* Write File */
/*-----------------------------------------------------------------------*/
 
FRESULT f_write (
FIL *fp, /* Pointer to the file object */
const void *buff, /* Pointer to the data to be written */
UINT btw, /* Number of bytes to write */
UINT *bw /* Pointer to number of bytes written */
)
{
FRESULT res;
DWORD clust, sect;
UINT wcnt, cc;
const BYTE *wbuff = buff;
 
 
*bw = 0;
res = validate(fp->fs, fp->id); /* Check validity of the object */
if (res != FR_OK) return res;
if (fp->flag & FA__ERROR) return FR_RW_ERROR; /* Check error flag */
if (!(fp->flag & FA_WRITE)) return FR_DENIED; /* Check access mode */
if (fp->fsize + btw < fp->fsize) return FR_OK; /* File size cannot reach 4GB */
 
for ( ; btw; /* Repeat until all data transferred */
wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt) {
if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */
if (fp->csect >= fp->fs->csize) { /* On the cluster boundary? */
if (fp->fptr == 0) { /* On the top of the file? */
clust = fp->org_clust; /* Follow from the origin */
if (clust == 0) /* When there is no cluster chain, */
fp->org_clust = clust = create_chain(fp->fs, 0); /* Create a new cluster chain */
} else { /* Middle or end of the file */
clust = create_chain(fp->fs, fp->curr_clust); /* Trace or streach cluster chain */
}
if (clust == 0) break; /* Could not allocate a new cluster (disk full) */
if (clust == 1 || clust >= fp->fs->max_clust) goto fw_error;
fp->curr_clust = clust; /* Update current cluster */
fp->csect = 0; /* Reset sector address in the cluster */
}
sect = clust2sect(fp->fs, fp->curr_clust) + fp->csect; /* Get current sector */
cc = btw / SS(fp->fs); /* When remaining bytes >= sector size, */
if (cc) { /* Write maximum contiguous sectors directly */
if (fp->csect + cc > fp->fs->csize) /* Clip at cluster boundary */
cc = fp->fs->csize - fp->csect;
if (disk_write(fp->fs->drive, wbuff, sect, (BYTE)cc) != RES_OK)
goto fw_error;
fp->csect += (BYTE)cc; /* Next sector address in the cluster */
wcnt = SS(fp->fs) * cc; /* Number of bytes transferred */
continue;
}
if (sect != fp->curr_sect) { /* Is window offset changed? */
if (fp->flag & FA__DIRTY) { /* Write back file I/O buffer if needed */
if (disk_write(fp->fs->drive, fp->buffer, fp->curr_sect, 1) != RES_OK)
goto fw_error;
fp->flag &= (BYTE)~FA__DIRTY;
}
if (fp->fptr < fp->fsize && /* Fill file I/O buffer with file data */
disk_read(fp->fs->drive, fp->buffer, sect, 1) != RES_OK)
goto fw_error;
fp->curr_sect = sect;
}
fp->csect++; /* Next sector address in the cluster */
}
wcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs)); /* Put partial sector into file I/O buffer */
if (wcnt > btw) wcnt = btw;
memcpy(&fp->buffer[fp->fptr % SS(fp->fs)], wbuff, wcnt);
fp->flag |= FA__DIRTY;
}
 
if (fp->fptr > fp->fsize) fp->fsize = fp->fptr; /* Update file size if needed */
fp->flag |= FA__WRITTEN; /* Set file changed flag */
return FR_OK;
 
fw_error: /* Abort this file due to an unrecoverable error */
fp->flag |= FA__ERROR;
return FR_RW_ERROR;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Synchronize the file object */
/*-----------------------------------------------------------------------*/
 
FRESULT f_sync (
FIL *fp /* Pointer to the file object */
)
{
FRESULT res;
DWORD tim;
BYTE *dir;
 
 
res = validate(fp->fs, fp->id); /* Check validity of the object */
if (res == FR_OK) {
if (fp->flag & FA__WRITTEN) { /* Has the file been written? */
/* Write back data buffer if needed */
if (fp->flag & FA__DIRTY) {
if (disk_write(fp->fs->drive, fp->buffer, fp->curr_sect, 1) != RES_OK)
return FR_RW_ERROR;
fp->flag &= (BYTE)~FA__DIRTY;
}
/* Update the directory entry */
if (!move_window(fp->fs, fp->dir_sect))
return FR_RW_ERROR;
dir = fp->dir_ptr;
dir[DIR_Attr] |= AM_ARC; /* Set archive bit */
ST_DWORD(&dir[DIR_FileSize], fp->fsize); /* Update file size */
ST_WORD(&dir[DIR_FstClusLO], fp->org_clust); /* Update start cluster */
ST_WORD(&dir[DIR_FstClusHI], fp->org_clust >> 16);
tim = get_fattime(); /* Updated time */
ST_DWORD(&dir[DIR_WrtTime], tim);
fp->flag &= (BYTE)~FA__WRITTEN;
res = sync(fp->fs);
}
}
return res;
}
 
#endif /* !_FS_READONLY */
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Close File */
/*-----------------------------------------------------------------------*/
 
FRESULT f_close (
FIL *fp /* Pointer to the file object to be closed */
)
{
FRESULT res;
 
 
#if !_FS_READONLY
res = f_sync(fp);
#else
res = validate(fp->fs, fp->id);
#endif
if (res == FR_OK) fp->fs = NULL;
return res;
}
 
 
 
 
#if _FS_MINIMIZE <= 2
/*-----------------------------------------------------------------------*/
/* Seek File R/W Pointer */
/*-----------------------------------------------------------------------*/
 
FRESULT f_lseek (
FIL *fp, /* Pointer to the file object */
DWORD ofs /* File pointer from top of file */
)
{
FRESULT res;
DWORD clust, csize, nsect, ifptr;
 
 
res = validate(fp->fs, fp->id); /* Check validity of the object */
if (res != FR_OK) return res;
if (fp->flag & FA__ERROR) return FR_RW_ERROR;
if (ofs > fp->fsize /* In read-only mode, clip offset with the file size */
#if !_FS_READONLY
&& !(fp->flag & FA_WRITE)
#endif
) ofs = fp->fsize;
 
ifptr = fp->fptr;
fp->fptr = 0; fp->csect = 255;
nsect = 0;
if (ofs > 0) {
csize = (DWORD)fp->fs->csize * SS(fp->fs); /* Cluster size (byte) */
if (ifptr > 0 &&
(ofs - 1) / csize >= (ifptr - 1) / csize) {/* When seek to same or following cluster, */
fp->fptr = (ifptr - 1) & ~(csize - 1); /* start from the current cluster */
ofs -= fp->fptr;
clust = fp->curr_clust;
} else { /* When seek to back cluster, */
clust = fp->org_clust; /* start from the first cluster */
#if !_FS_READONLY
if (clust == 0) { /* If no cluster chain, create a new chain */
clust = create_chain(fp->fs, 0);
if (clust == 1) goto fk_error;
fp->org_clust = clust;
}
#endif
fp->curr_clust = clust;
}
if (clust != 0) {
while (ofs > csize) { /* Cluster following loop */
#if !_FS_READONLY
if (fp->flag & FA_WRITE) { /* Check if in write mode or not */
clust = create_chain(fp->fs, clust); /* Force streached if in write mode */
if (clust == 0) { /* When disk gets full, clip file size */
ofs = csize; break;
}
} else
#endif
clust = get_cluster(fp->fs, clust); /* Follow cluster chain if not in write mode */
if (clust < 2 || clust >= fp->fs->max_clust) goto fk_error;
fp->curr_clust = clust;
fp->fptr += csize;
ofs -= csize;
}
fp->fptr += ofs;
fp->csect = (BYTE)(ofs / SS(fp->fs)); /* Sector offset in the cluster */
if (ofs & (SS(fp->fs) - 1)) {
nsect = clust2sect(fp->fs, clust) + fp->csect; /* Current sector */
fp->csect++;
}
}
}
if (nsect && nsect != fp->curr_sect) {
#if !_FS_READONLY
if (fp->flag & FA__DIRTY) { /* Write-back dirty buffer if needed */
if (disk_write(fp->fs->drive, fp->buffer, fp->curr_sect, 1) != RES_OK)
goto fk_error;
fp->flag &= (BYTE)~FA__DIRTY;
}
#endif
if (disk_read(fp->fs->drive, fp->buffer, nsect, 1) != RES_OK)
goto fk_error;
fp->curr_sect = nsect;
}
 
#if !_FS_READONLY
if (fp->fptr > fp->fsize) { /* Set changed flag if the file was extended */
fp->fsize = fp->fptr;
fp->flag |= FA__WRITTEN;
}
#endif
 
return FR_OK;
 
fk_error: /* Abort this file due to an unrecoverable error */
fp->flag |= FA__ERROR;
return FR_RW_ERROR;
}
 
 
 
 
#if _FS_MINIMIZE <= 1
/*-----------------------------------------------------------------------*/
/* Create a directroy object */
/*-----------------------------------------------------------------------*/
 
FRESULT f_opendir (
DIR *dj, /* Pointer to directory object to create */
const char *path /* Pointer to the directory path */
)
{
FRESULT res;
BYTE *dir;
char fn[8+3+1];
 
 
res = auto_mount(&path, &dj->fs, 0);
if (res == FR_OK) {
res = trace_path(dj, fn, path, &dir); /* Trace the directory path */
if (res == FR_OK) { /* Trace completed */
if (dir) { /* It is not the root dir */
if (dir[DIR_Attr] & AM_DIR) { /* The entry is a directory */
dj->clust = ((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | LD_WORD(&dir[DIR_FstClusLO]);
dj->sect = clust2sect(dj->fs, dj->clust);
dj->index = 2;
} else { /* The entry is not a directory */
res = FR_NO_FILE;
}
}
dj->id = dj->fs->id;
}
}
 
return res;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Read Directory Entry in Sequense */
/*-----------------------------------------------------------------------*/
 
FRESULT f_readdir (
DIR *dj, /* Pointer to the directory object */
FILINFO *finfo /* Pointer to file information to return */
)
{
BYTE *dir, c, res;
 
 
res = validate(dj->fs, dj->id); /* Check validity of the object */
if (res != FR_OK) return res;
 
finfo->fname[0] = 0;
while (dj->sect) {
if (!move_window(dj->fs, dj->sect))
return FR_RW_ERROR;
dir = &dj->fs->win[(dj->index & ((SS(dj->fs) - 1) >> 5)) * 32]; /* pointer to the directory entry */
c = dir[DIR_Name];
if (c == 0) break; /* Has it reached to end of dir? */
if (c != 0xE5 && !(dir[DIR_Attr] & AM_VOL)) /* Is it a valid entry? */
get_fileinfo(finfo, dir);
if (!next_dir_entry(dj)) dj->sect = 0; /* Next entry */
if (finfo->fname[0]) break; /* Found valid entry */
}
 
return FR_OK;
}
 
 
 
 
#if _FS_MINIMIZE == 0
/*-----------------------------------------------------------------------*/
/* Get File Status */
/*-----------------------------------------------------------------------*/
 
FRESULT f_stat (
const char *path, /* Pointer to the file path */
FILINFO *finfo /* Pointer to file information to return */
)
{
FRESULT res;
DIR dj;
BYTE *dir;
char fn[8+3+1];
 
 
res = auto_mount(&path, &dj.fs, 0);
if (res == FR_OK) {
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */
if (res == FR_OK) { /* Trace completed */
if (dir) /* Found an object */
get_fileinfo(finfo, dir);
else /* It is root dir */
res = FR_INVALID_NAME;
}
}
 
return res;
}
 
 
 
#if !_FS_READONLY
/*-----------------------------------------------------------------------*/
/* Truncate File */
/*-----------------------------------------------------------------------*/
 
FRESULT f_truncate (
FIL *fp /* Pointer to the file object */
)
{
FRESULT res;
DWORD ncl;
 
 
res = validate(fp->fs, fp->id); /* Check validity of the object */
if (res != FR_OK) return res;
if (fp->flag & FA__ERROR) return FR_RW_ERROR; /* Check error flag */
if (!(fp->flag & FA_WRITE)) return FR_DENIED; /* Check access mode */
 
if (fp->fsize > fp->fptr) {
fp->fsize = fp->fptr; /* Set file size to current R/W point */
fp->flag |= FA__WRITTEN;
if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */
if (!remove_chain(fp->fs, fp->org_clust)) goto ft_error;
fp->org_clust = 0;
} else { /* When truncate a part of the file, remove remaining clusters */
ncl = get_cluster(fp->fs, fp->curr_clust);
if (ncl < 2) goto ft_error;
if (ncl < fp->fs->max_clust) {
if (!put_cluster(fp->fs, fp->curr_clust, 0x0FFFFFFF)) goto ft_error;
if (!remove_chain(fp->fs, ncl)) goto ft_error;
}
}
}
 
return FR_OK;
 
ft_error: /* Abort this file due to an unrecoverable error */
fp->flag |= FA__ERROR;
return FR_RW_ERROR;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Get Number of Free Clusters */
/*-----------------------------------------------------------------------*/
 
FRESULT f_getfree (
const char *drv, /* Pointer to the logical drive number (root dir) */
DWORD *nclust, /* Pointer to the variable to return number of free clusters */
FATFS **fatfs /* Pointer to pointer to corresponding file system object to return */
)
{
FRESULT res;
DWORD n, clust, sect;
BYTE fat, f, *p;
 
 
/* Get drive number */
res = auto_mount(&drv, fatfs, 0);
if (res != FR_OK) return res;
 
/* If number of free cluster is valid, return it without cluster scan. */
if ((*fatfs)->free_clust <= (*fatfs)->max_clust - 2) {
*nclust = (*fatfs)->free_clust;
return FR_OK;
}
 
/* Get number of free clusters */
fat = (*fatfs)->fs_type;
n = 0;
if (fat == FS_FAT12) {
clust = 2;
do {
if ((WORD)get_cluster(*fatfs, clust) == 0) n++;
} while (++clust < (*fatfs)->max_clust);
} else {
clust = (*fatfs)->max_clust;
sect = (*fatfs)->fatbase;
f = 0; p = 0;
do {
if (!f) {
if (!move_window(*fatfs, sect++)) return FR_RW_ERROR;
p = (*fatfs)->win;
}
if (fat == FS_FAT16) {
if (LD_WORD(p) == 0) n++;
p += 2; f += 1;
} else {
if (LD_DWORD(p) == 0) n++;
p += 4; f += 2;
}
} while (--clust);
}
(*fatfs)->free_clust = n;
#if _USE_FSINFO
if (fat == FS_FAT32) (*fatfs)->fsi_flag = 1;
#endif
 
*nclust = n;
return FR_OK;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Delete a File or Directory */
/*-----------------------------------------------------------------------*/
 
FRESULT f_unlink (
const char *path /* Pointer to the file or directory path */
)
{
FRESULT res;
DIR dj;
BYTE *dir, *sdir;
DWORD dclust, dsect;
char fn[8+3+1];
 
 
res = auto_mount(&path, &dj.fs, 1);
if (res != FR_OK) return res;
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */
if (res != FR_OK) return res; /* Trace failed */
if (!dir) return FR_INVALID_NAME; /* It is the root directory */
if (dir[DIR_Attr] & AM_RDO) return FR_DENIED; /* It is a R/O object */
dsect = dj.fs->winsect;
dclust = ((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | LD_WORD(&dir[DIR_FstClusLO]);
 
if (dir[DIR_Attr] & AM_DIR) { /* It is a sub-directory */
dj.clust = dclust; /* Check if the sub-dir is empty or not */
dj.sect = clust2sect(dj.fs, dclust);
dj.index = 2;
do {
if (!move_window(dj.fs, dj.sect)) return FR_RW_ERROR;
sdir = &dj.fs->win[(dj.index & ((SS(dj.fs) - 1) >> 5)) * 32];
if (sdir[DIR_Name] == 0) break;
if (sdir[DIR_Name] != 0xE5 && !(sdir[DIR_Attr] & AM_VOL))
return FR_DENIED; /* The directory is not empty */
} while (next_dir_entry(&dj));
}
 
if (!move_window(dj.fs, dsect)) return FR_RW_ERROR; /* Mark the directory entry 'deleted' */
dir[DIR_Name] = 0xE5;
dj.fs->winflag = 1;
if (!remove_chain(dj.fs, dclust)) return FR_RW_ERROR; /* Remove the cluster chain */
 
return sync(dj.fs);
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Create a Directory */
/*-----------------------------------------------------------------------*/
 
FRESULT f_mkdir (
const char *path /* Pointer to the directory path */
)
{
FRESULT res;
DIR dj;
BYTE *dir, *fw, n;
char fn[8+3+1];
DWORD sect, dsect, dclust, pclust, tim;
 
 
res = auto_mount(&path, &dj.fs, 1);
if (res != FR_OK) return res;
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */
if (res == FR_OK) return FR_EXIST; /* Any file or directory is already existing */
if (res != FR_NO_FILE) return res;
 
res = reserve_direntry(&dj, &dir); /* Reserve a directory entry */
if (res != FR_OK) return res;
sect = dj.fs->winsect;
dclust = create_chain(dj.fs, 0); /* Allocate a cluster for new directory table */
if (dclust == 1) return FR_RW_ERROR;
dsect = clust2sect(dj.fs, dclust);
if (!dsect) return FR_DENIED;
if (!move_window(dj.fs, dsect)) return FR_RW_ERROR;
 
fw = dj.fs->win;
memset(fw, 0, SS(dj.fs)); /* Clear the new directory table */
for (n = 1; n < dj.fs->csize; n++) {
if (disk_write(dj.fs->drive, fw, ++dsect, 1) != RES_OK)
return FR_RW_ERROR;
}
memset(&fw[DIR_Name], ' ', 8+3); /* Create "." entry */
fw[DIR_Name] = '.';
fw[DIR_Attr] = AM_DIR;
tim = get_fattime();
ST_DWORD(&fw[DIR_WrtTime], tim);
memcpy(&fw[32], &fw[0], 32); fw[33] = '.'; /* Create ".." entry */
ST_WORD(&fw[ DIR_FstClusLO], dclust);
ST_WORD(&fw[ DIR_FstClusHI], dclust >> 16);
pclust = dj.sclust;
if (dj.fs->fs_type == FS_FAT32 && pclust == dj.fs->dirbase) pclust = 0;
ST_WORD(&fw[32+DIR_FstClusLO], pclust);
ST_WORD(&fw[32+DIR_FstClusHI], pclust >> 16);
dj.fs->winflag = 1;
 
if (!move_window(dj.fs, sect)) return FR_RW_ERROR;
memset(&dir[0], 0, 32); /* Initialize the new entry */
memcpy(&dir[DIR_Name], fn, 8+3); /* Name */
dir[DIR_NTres] = fn[11];
dir[DIR_Attr] = AM_DIR; /* Attribute */
ST_DWORD(&dir[DIR_WrtTime], tim); /* Crated time */
ST_WORD(&dir[DIR_FstClusLO], dclust); /* Table start cluster */
ST_WORD(&dir[DIR_FstClusHI], dclust >> 16);
 
return sync(dj.fs);
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Change File Attribute */
/*-----------------------------------------------------------------------*/
 
FRESULT f_chmod (
const char *path, /* Pointer to the file path */
BYTE value, /* Attribute bits */
BYTE mask /* Attribute mask to change */
)
{
FRESULT res;
DIR dj;
BYTE *dir;
char fn[8+3+1];
 
 
res = auto_mount(&path, &dj.fs, 1);
if (res == FR_OK) {
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */
if (res == FR_OK) { /* Trace completed */
if (!dir) {
res = FR_INVALID_NAME; /* Root directory */
} else {
mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */
dir[DIR_Attr] = (value & mask) | (dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */
res = sync(dj.fs);
}
}
}
return res;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Change Timestamp */
/*-----------------------------------------------------------------------*/
 
FRESULT f_utime (
const char *path, /* Pointer to the file/directory name */
const FILINFO *finfo /* Pointer to the timestamp to be set */
)
{
FRESULT res;
DIR dj;
BYTE *dir;
char fn[8+3+1];
 
 
res = auto_mount(&path, &dj.fs, 1);
if (res == FR_OK) {
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */
if (res == FR_OK) { /* Trace completed */
if (!dir) {
res = FR_INVALID_NAME; /* Root directory */
} else {
ST_WORD(&dir[DIR_WrtTime], finfo->ftime);
ST_WORD(&dir[DIR_WrtDate], finfo->fdate);
res = sync(dj.fs);
}
}
}
return res;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Rename File/Directory */
/*-----------------------------------------------------------------------*/
 
FRESULT f_rename (
const char *path_old, /* Pointer to the old name */
const char *path_new /* Pointer to the new name */
)
{
FRESULT res;
DIR dj;
DWORD sect_old;
BYTE *dir_old, *dir_new, direntry[32-11];
char fn[8+3+1];
 
 
res = auto_mount(&path_old, &dj.fs, 1);
if (res != FR_OK) return res;
 
res = trace_path(&dj, fn, path_old, &dir_old); /* Check old object */
if (res != FR_OK) return res; /* The old object is not found */
if (!dir_old) return FR_NO_FILE;
sect_old = dj.fs->winsect; /* Save the object information */
memcpy(direntry, &dir_old[DIR_Attr], 32-11);
 
res = trace_path(&dj, fn, path_new, &dir_new); /* Check new object */
if (res == FR_OK) return FR_EXIST; /* The new object name is already existing */
if (res != FR_NO_FILE) return res; /* Is there no old name? */
res = reserve_direntry(&dj, &dir_new); /* Reserve a directory entry */
if (res != FR_OK) return res;
 
memcpy(&dir_new[DIR_Attr], direntry, 32-11); /* Create new entry */
memcpy(&dir_new[DIR_Name], fn, 8+3);
dir_new[DIR_NTres] = fn[11];
dj.fs->winflag = 1;
 
if (!move_window(dj.fs, sect_old)) return FR_RW_ERROR; /* Delete old entry */
dir_old[DIR_Name] = 0xE5;
 
return sync(dj.fs);
}
 
#endif /* !_FS_READONLY */
#endif /* _FS_MINIMIZE == 0 */
#endif /* _FS_MINIMIZE <= 1 */
#endif /* _FS_MINIMIZE <= 2 */
 
 
 
#if _USE_MKFS && !_FS_READONLY
/*-----------------------------------------------------------------------*/
/* Create File System on the Drive */
/*-----------------------------------------------------------------------*/
#define N_ROOTDIR 512 /* Multiple of 32 and <= 2048 */
#define N_FATS 1 /* 1 or 2 */
#define MAX_SECTOR 64000000UL /* Maximum partition size */
#define MIN_SECTOR 2000UL /* Minimum partition size */
 
 
 
FRESULT f_mkfs (
BYTE drv, /* Logical drive number */
BYTE partition, /* Partitioning rule 0:FDISK, 1:SFD */
WORD allocsize /* Allocation unit size [bytes] */
)
{
BYTE fmt, m, *tbl;
DWORD b_part, b_fat, b_dir, b_data; /* Area offset (LBA) */
DWORD n_part, n_rsv, n_fat, n_dir; /* Area size */
DWORD n_clust, n;
FATFS *fs;
DSTATUS stat;
 
 
/* Check validity of the parameters */
if (drv >= _DRIVES) return FR_INVALID_DRIVE;
if (partition >= 2) return FR_MKFS_ABORTED;
for (n = 512; n <= 32768U && n != allocsize; n <<= 1);
if (n != allocsize) return FR_MKFS_ABORTED;
 
/* Check mounted drive and clear work area */
fs = FatFs[drv];
if (!fs) return FR_NOT_ENABLED;
fs->fs_type = 0;
drv = LD2PD(drv);
 
/* Get disk statics */
stat = disk_initialize(drv);
if (stat & STA_NOINIT) return FR_NOT_READY;
if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
if (disk_ioctl(drv, GET_SECTOR_COUNT, &n_part) != RES_OK || n_part < MIN_SECTOR)
return FR_MKFS_ABORTED;
if (n_part > MAX_SECTOR) n_part = MAX_SECTOR;
b_part = (!partition) ? 63 : 0; /* Boot sector */
n_part -= b_part;
#if S_MAX_SIZ > 512 /* Check disk sector size */
if (disk_ioctl(drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK
|| SS(fs) > S_MAX_SIZ
|| SS(fs) > allocsize)
return FR_MKFS_ABORTED;
#endif
allocsize /= SS(fs); /* Number of sectors per cluster */
 
/* Pre-compute number of clusters and FAT type */
n_clust = n_part / allocsize;
fmt = FS_FAT12;
if (n_clust >= 0xFF5) fmt = FS_FAT16;
if (n_clust >= 0xFFF5) fmt = FS_FAT32;
 
/* Determine offset and size of FAT structure */
switch (fmt) {
case FS_FAT12:
n_fat = ((n_clust * 3 + 1) / 2 + 3 + SS(fs) - 1) / SS(fs);
n_rsv = 1 + partition;
n_dir = N_ROOTDIR * 32 / SS(fs);
break;
case FS_FAT16:
n_fat = ((n_clust * 2) + 4 + SS(fs) - 1) / SS(fs);
n_rsv = 1 + partition;
n_dir = N_ROOTDIR * 32 / SS(fs);
break;
default:
n_fat = ((n_clust * 4) + 8 + SS(fs) - 1) / SS(fs);
n_rsv = 33 - partition;
n_dir = 0;
}
b_fat = b_part + n_rsv; /* FATs start sector */
b_dir = b_fat + n_fat * N_FATS; /* Directory start sector */
b_data = b_dir + n_dir; /* Data start sector */
 
/* Align data start sector to erase block boundary (for flash memory media) */
if (disk_ioctl(drv, GET_BLOCK_SIZE, &n) != RES_OK) return FR_MKFS_ABORTED;
n = (b_data + n - 1) & ~(n - 1);
n_fat += (n - b_data) / N_FATS;
/* b_dir and b_data are no longer used below */
 
/* Determine number of cluster and final check of validity of the FAT type */
n_clust = (n_part - n_rsv - n_fat * N_FATS - n_dir) / allocsize;
if ( (fmt == FS_FAT16 && n_clust < 0xFF5)
|| (fmt == FS_FAT32 && n_clust < 0xFFF5))
return FR_MKFS_ABORTED;
 
/* Create partition table if needed */
if (!partition) {
DWORD n_disk = b_part + n_part;
 
tbl = &fs->win[MBR_Table];
ST_DWORD(&tbl[0], 0x00010180); /* Partition start in CHS */
if (n_disk < 63UL * 255 * 1024) { /* Partition end in CHS */
n_disk = n_disk / 63 / 255;
tbl[7] = (BYTE)n_disk;
tbl[6] = (BYTE)((n_disk >> 2) | 63);
} else {
ST_WORD(&tbl[6], 0xFFFF);
}
tbl[5] = 254;
if (fmt != FS_FAT32) /* System ID */
tbl[4] = (n_part < 0x10000) ? 0x04 : 0x06;
else
tbl[4] = 0x0c;
ST_DWORD(&tbl[8], 63); /* Partition start in LBA */
ST_DWORD(&tbl[12], n_part); /* Partition size in LBA */
ST_WORD(&tbl[64], 0xAA55); /* Signature */
if (disk_write(drv, fs->win, 0, 1) != RES_OK)
return FR_RW_ERROR;
}
 
/* Create boot record */
tbl = fs->win; /* Clear buffer */
memset(tbl, 0, SS(fs));
ST_DWORD(&tbl[BS_jmpBoot], 0x90FEEB); /* Boot code (jmp $, nop) */
ST_WORD(&tbl[BPB_BytsPerSec], SS(fs)); /* Sector size */
tbl[BPB_SecPerClus] = (BYTE)allocsize; /* Sectors per cluster */
ST_WORD(&tbl[BPB_RsvdSecCnt], n_rsv); /* Reserved sectors */
tbl[BPB_NumFATs] = N_FATS; /* Number of FATs */
ST_WORD(&tbl[BPB_RootEntCnt], SS(fs) / 32 * n_dir); /* Number of rootdir entries */
if (n_part < 0x10000) { /* Number of total sectors */
ST_WORD(&tbl[BPB_TotSec16], n_part);
} else {
ST_DWORD(&tbl[BPB_TotSec32], n_part);
}
tbl[BPB_Media] = 0xF8; /* Media descripter */
ST_WORD(&tbl[BPB_SecPerTrk], 63); /* Number of sectors per track */
ST_WORD(&tbl[BPB_NumHeads], 255); /* Number of heads */
ST_DWORD(&tbl[BPB_HiddSec], b_part); /* Hidden sectors */
n = get_fattime(); /* Use current time as a VSN */
if (fmt != FS_FAT32) {
ST_DWORD(&tbl[BS_VolID], n); /* Volume serial number */
ST_WORD(&tbl[BPB_FATSz16], n_fat); /* Number of secters per FAT */
tbl[BS_DrvNum] = 0x80; /* Drive number */
tbl[BS_BootSig] = 0x29; /* Extended boot signature */
memcpy(&tbl[BS_VolLab], "NO NAME FAT ", 19); /* Volume lavel, FAT signature */
} else {
ST_DWORD(&tbl[BS_VolID32], n); /* Volume serial number */
ST_DWORD(&tbl[BPB_FATSz32], n_fat); /* Number of secters per FAT */
ST_DWORD(&tbl[BPB_RootClus], 2); /* Root directory cluster (2) */
ST_WORD(&tbl[BPB_FSInfo], 1); /* FSInfo record (bs+1) */
ST_WORD(&tbl[BPB_BkBootSec], 6); /* Backup boot record (bs+6) */
tbl[BS_DrvNum32] = 0x80; /* Drive number */
tbl[BS_BootSig32] = 0x29; /* Extended boot signature */
memcpy(&tbl[BS_VolLab32], "NO NAME FAT32 ", 19); /* Volume lavel, FAT signature */
}
ST_WORD(&tbl[BS_55AA], 0xAA55); /* Signature */
if (disk_write(drv, tbl, b_part+0, 1) != RES_OK)
return FR_RW_ERROR;
if (fmt == FS_FAT32)
disk_write(drv, tbl, b_part+6, 1);
 
/* Initialize FAT area */
for (m = 0; m < N_FATS; m++) {
memset(tbl, 0, SS(fs)); /* 1st sector of the FAT */
if (fmt != FS_FAT32) {
n = (fmt == FS_FAT12) ? 0x00FFFFF8 : 0xFFFFFFF8;
ST_DWORD(&tbl[0], n); /* Reserve cluster #0-1 (FAT12/16) */
} else {
ST_DWORD(&tbl[0], 0xFFFFFFF8); /* Reserve cluster #0-1 (FAT32) */
ST_DWORD(&tbl[4], 0xFFFFFFFF);
ST_DWORD(&tbl[8], 0x0FFFFFFF); /* Reserve cluster #2 for root dir */
}
if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)
return FR_RW_ERROR;
memset(tbl, 0, SS(fs)); /* Following FAT entries are filled by zero */
for (n = 1; n < n_fat; n++) {
if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)
return FR_RW_ERROR;
}
}
 
/* Initialize Root directory */
m = (BYTE)((fmt == FS_FAT32) ? allocsize : n_dir);
do {
if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)
return FR_RW_ERROR;
} while (--m);
 
/* Create FSInfo record if needed */
if (fmt == FS_FAT32) {
ST_WORD(&tbl[BS_55AA], 0xAA55);
ST_DWORD(&tbl[FSI_LeadSig], 0x41615252);
ST_DWORD(&tbl[FSI_StrucSig], 0x61417272);
ST_DWORD(&tbl[FSI_Free_Count], n_clust - 1);
ST_DWORD(&tbl[FSI_Nxt_Free], 0xFFFFFFFF);
disk_write(drv, tbl, b_part+1, 1);
disk_write(drv, tbl, b_part+7, 1);
}
 
return (disk_ioctl(drv, CTRL_SYNC, NULL) == RES_OK) ? FR_OK : FR_RW_ERROR;
}
 
#endif /* _USE_MKFS && !_FS_READONLY */
 
 
 
 
#if _USE_STRFUNC >= 1
/*-----------------------------------------------------------------------*/
/* Get a string from the file */
/*-----------------------------------------------------------------------*/
char* fgets (
char* buff, /* Pointer to the string buffer to read */
int len, /* Size of string buffer */
FIL* fil /* Pointer to the file object */
)
{
int i = 0;
char *p = buff;
UINT rc;
 
 
while (i < len - 1) { /* Read bytes until buffer gets filled */
f_read(fil, p, 1, &rc);
if (rc != 1) break; /* Break when no data to read */
#if _USE_STRFUNC >= 2
if (*p == '\r') continue; /* Strip '\r' */
#endif
i++;
if (*p++ == '\n') break; /* Break when reached end of line */
}
*p = 0;
return i ? buff : 0; /* When no data read (eof or error), return with error. */
}
 
 
 
#if !_FS_READONLY
#include <stdarg.h>
/*-----------------------------------------------------------------------*/
/* Put a character to the file */
/*-----------------------------------------------------------------------*/
int fputc (
int chr, /* A character to be output */
FIL* fil /* Ponter to the file object */
)
{
UINT bw;
char c;
 
 
#if _USE_STRFUNC >= 2
if (chr == '\n') fputc ('\r', fil); /* LF -> CRLF conversion */
#endif
if (!fil) { /* Special value may be used to switch the destination to any other device */
/* put_console(chr); */
return chr;
}
c = (char)chr;
f_write(fil, &c, 1, &bw); /* Write a byte to the file */
return bw ? chr : EOF; /* Return the resulut */
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Put a string to the file */
/*-----------------------------------------------------------------------*/
int fputs (
const char* str, /* Pointer to the string to be output */
FIL* fil /* Pointer to the file object */
)
{
int n;
 
 
for (n = 0; *str; str++, n++) {
if (fputc(*str, fil) == EOF) return EOF;
}
return n;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Put a formatted string to the file */
/*-----------------------------------------------------------------------*/
int fprintf (
FIL* fil, /* Pointer to the file object */
const char* str, /* Pointer to the format string */
... /* Optional arguments... */
)
{
va_list arp;
UCHAR c, f, r;
ULONG val;
char s[16];
int i, w, res, cc;
 
 
va_start(arp, str);
 
for (cc = res = 0; cc != EOF; res += cc) {
c = *str++;
if (c == 0) break; /* End of string */
if (c != '%') { /* Non escape cahracter */
cc = fputc(c, fil);
if (cc != EOF) cc = 1;
continue;
}
w = f = 0;
c = *str++;
if (c == '0') { /* Flag: '0' padding */
f = 1; c = *str++;
}
while (c >= '0' && c <= '9') { /* Precision */
w = w * 10 + (c - '0');
c = *str++;
}
if (c == 'l') { /* Prefix: Size is long int */
f |= 2; c = *str++;
}
if (c == 's') { /* Type is string */
cc = fputs(va_arg(arp, char*), fil);
continue;
}
if (c == 'c') { /* Type is character */
cc = fputc(va_arg(arp, char), fil);
if (cc != EOF) cc = 1;
continue;
}
r = 0;
if (c == 'd') r = 10; /* Type is signed decimal */
if (c == 'u') r = 10; /* Type is unsigned decimal */
if (c == 'X') r = 16; /* Type is unsigned hexdecimal */
if (r == 0) break; /* Unknown type */
if (f & 2) { /* Get the value */
val = (ULONG)va_arg(arp, long);
} else {
val = (c == 'd') ? (ULONG)(long)va_arg(arp, int) : (ULONG)va_arg(arp, unsigned int);
}
/* Put numeral string */
if (c == 'd') {
if (val >= 0x80000000) {
val = 0 - val;
f |= 4;
}
}
i = sizeof(s) - 1; s[i] = 0;
do {
c = (UCHAR)(val % r + '0');
if (c > '9') c += 7;
s[--i] = c;
val /= r;
} while (i && val);
if (i && (f & 4)) s[--i] = '-';
w = sizeof(s) - 1 - w;
while (i && i > w) s[--i] = (f & 1) ? '0' : ' ';
cc = fputs(&s[i], fil);
}
 
va_end(arp);
return (cc == EOF) ? cc : res;
}
 
#endif /* !_FS_READONLY */
#endif /* _USE_STRFUNC >= 1*/
/programy/C/avr/SDcard/ff.h
0,0 → 1,339
/*--------------------------------------------------------------------------/
/ FatFs - FAT file system module include file R0.06 (C)ChaN, 2008
/---------------------------------------------------------------------------/
/ FatFs module is an experimenal project to implement FAT file system to
/ cheap microcontrollers. This is a free software and is opened for education,
/ research and development under license policy of following trems.
/
/ Copyright (C) 2008, ChaN, all right reserved.
/
/ * The FatFs module is a free software and there is no warranty.
/ * You can use, modify and/or redistribute it for personal, non-profit or
/ commercial use without any restriction under your responsibility.
/ * Redistributions of source code must retain the above copyright notice.
/
/---------------------------------------------------------------------------*/
 
#ifndef _FATFS
 
#define _MCU_ENDIAN 1
/* The _MCU_ENDIAN defines which access method is used to the FAT structure.
/ 1: Enable word access.
/ 2: Disable word access and use byte-by-byte access instead.
/ When the architectural byte order of the MCU is big-endian and/or address
/ miss-aligned access results incorrect behavior, the _MCU_ENDIAN must be set to 2.
/ If it is not the case, it can also be set to 1 for good code efficiency. */
 
#define _FS_READONLY 0
/* 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
/* 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
/* To enable string functions, set _USE_STRFUNC to 1 or 2. */
 
#define _USE_MKFS 1
/* When _USE_MKFS is set to 1 and _FS_READONLY is set to 0, f_mkfs function is
/ enabled. */
 
#define _DRIVES 2
/* Number of logical drives to be used. This affects the size of internal table. */
 
#define _MULTI_PARTITION 0
/* When _MULTI_PARTITION is set to 0, each logical drive is bound to same
/ physical drive number and can mount only 1st primaly partition. When it is
/ set to 1, each logical drive can mount a partition listed in Drives[]. */
 
#define _USE_FSINFO 1
/* To enable FSInfo support on FAT32 volume, set _USE_FSINFO to 1. */
 
#define _USE_SJIS 1
/* When _USE_SJIS is set to 1, Shift-JIS code transparency is enabled, otherwise
/ only US-ASCII(7bit) code can be accepted as file/directory name. */
 
#define _USE_NTFLAG 1
/* When _USE_NTFLAG is set to 1, upper/lower case of the file name is preserved.
/ Note that the files are always accessed in case insensitive. */
 
 
#include "integer.h"
 
 
 
/* Definitions corresponds to multiple sector size (not tested) */
#define S_MAX_SIZ 512U /* Do not change */
#if S_MAX_SIZ > 512U
#define SS(fs) ((fs)->s_size)
#else
#define SS(fs) 512U
#endif
 
 
/* File system object structure */
typedef struct _FATFS {
WORD id; /* File system mount ID */
WORD n_rootdir; /* Number of root directory entries */
DWORD winsect; /* Current sector appearing in the win[] */
DWORD sects_fat; /* Sectors per fat */
DWORD max_clust; /* Maximum cluster# + 1 */
DWORD fatbase; /* FAT start sector */
DWORD dirbase; /* Root directory start sector (cluster# for FAT32) */
DWORD database; /* Data start sector */
#if !_FS_READONLY
DWORD last_clust; /* Last allocated cluster */
DWORD free_clust; /* Number of free clusters */
#if _USE_FSINFO
DWORD fsi_sector; /* fsinfo sector */
BYTE fsi_flag; /* fsinfo dirty flag (1:must be written back) */
BYTE pad2;
#endif
#endif
BYTE fs_type; /* FAT sub type */
BYTE csize; /* Number of sectors per cluster */
#if S_MAX_SIZ > 512U
WORD s_size; /* Sector size */
#endif
BYTE n_fats; /* Number of FAT copies */
BYTE drive; /* Physical drive number */
BYTE winflag; /* win[] dirty flag (1:must be written back) */
BYTE pad1;
BYTE win[S_MAX_SIZ]; /* Disk access window for Directory/FAT */
} FATFS;
 
 
/* Directory object structure */
typedef struct _DIR {
WORD id; /* Owner file system mount ID */
WORD index; /* Current index */
FATFS* fs; /* Pointer to the owner file system object */
DWORD sclust; /* Start cluster */
DWORD clust; /* Current cluster */
DWORD sect; /* Current sector */
} DIR;
 
 
/* File object structure */
typedef struct _FIL {
WORD id; /* Owner file system mount ID */
BYTE flag; /* File status flags */
BYTE csect; /* Sector address in the cluster */
FATFS* fs; /* Pointer to the owner file system object */
DWORD fptr; /* File R/W pointer */
DWORD fsize; /* File size */
DWORD org_clust; /* File start cluster */
DWORD curr_clust; /* Current cluster */
DWORD curr_sect; /* Current sector */
#if _FS_READONLY == 0
DWORD dir_sect; /* Sector containing the directory entry */
BYTE* dir_ptr; /* Ponter to the directory entry in the window */
#endif
BYTE buffer[S_MAX_SIZ]; /* File R/W buffer */
} FIL;
 
 
/* File status structure */
typedef struct _FILINFO {
DWORD fsize; /* Size */
WORD fdate; /* Date */
WORD ftime; /* Time */
BYTE fattrib; /* Attribute */
char fname[8+1+3+1]; /* Name (8.3 format) */
} FILINFO;
 
 
 
/* Definitions corresponds to multi partition */
 
#if _MULTI_PARTITION != 0 /* Multiple partition cfg */
 
typedef struct _PARTITION {
BYTE pd; /* Physical drive # (0-255) */
BYTE pt; /* Partition # (0-3) */
} PARTITION;
extern
const PARTITION Drives[]; /* Logical drive# to physical location conversion table */
#define LD2PD(drv) (Drives[drv].pd) /* Get physical drive# */
#define LD2PT(drv) (Drives[drv].pt) /* Get partition# */
 
#else /* Single partition cfg */
 
#define LD2PD(drv) (drv) /* Physical drive# is equal to logical drive# */
#define LD2PT(drv) 0 /* Always mounts the 1st partition */
 
#endif
 
 
/* File function return code (FRESULT) */
 
typedef enum {
FR_OK = 0, /* 0 */
FR_NOT_READY, /* 1 */
FR_NO_FILE, /* 2 */
FR_NO_PATH, /* 3 */
FR_INVALID_NAME, /* 4 */
FR_INVALID_DRIVE, /* 5 */
FR_DENIED, /* 6 */
FR_EXIST, /* 7 */
FR_RW_ERROR, /* 8 */
FR_WRITE_PROTECTED, /* 9 */
FR_NOT_ENABLED, /* 10 */
FR_NO_FILESYSTEM, /* 11 */
FR_INVALID_OBJECT, /* 12 */
FR_MKFS_ABORTED /* 13 */
} FRESULT;
 
 
 
/*-----------------------------------------------------*/
/* FatFs module application interface */
 
FRESULT f_mount (BYTE, FATFS*); /* Mount/Unmount a logical drive */
FRESULT f_open (FIL*, const char*, BYTE); /* Open or create a file */
FRESULT f_read (FIL*, void*, UINT, UINT*); /* Read data from a file */
FRESULT f_write (FIL*, const void*, UINT, UINT*); /* Write data to 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 char*); /* Open an existing directory */
FRESULT f_readdir (DIR*, FILINFO*); /* Read a directory item */
FRESULT f_stat (const char*, FILINFO*); /* Get file status */
FRESULT f_getfree (const char*, 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 char*); /* Delete an existing file or directory */
FRESULT f_mkdir (const char*); /* Create a new directory */
FRESULT f_chmod (const char*, BYTE, BYTE); /* Change file/dir attriburte */
FRESULT f_utime (const char*, const FILINFO*); /* Change file/dir timestamp */
FRESULT f_rename (const char*, const char*); /* Rename/Move a file or directory */
FRESULT f_mkfs (BYTE, BYTE, WORD); /* Create a file system on the drive */
#if _USE_STRFUNC
#define feof(fp) ((fp)->fptr == (fp)->fsize)
#define EOF -1
int fputc (int, FIL*); /* Put a character to the file */
int fputs (const char*, FIL*); /* Put a string to the file */
int fprintf (FIL*, const char*, ...); /* Put a formatted string to the file */
char* fgets (char*, int, FIL*); /* Get a string from the file */
#endif
 
/* User defined function to give a current time to fatfs module */
 
DWORD get_fattime (void); /* 31-25: Year(0-127 org.1980), 24-21: Month(1-12), 20-16: Day(1-31) */
/* 15-11: Hour(0-23), 10-5: Minute(0-59), 4-0: Second(0-29 *2) */
 
 
 
/* File access control and file status flags (FIL.flag) */
 
#define FA_READ 0x01
#define FA_OPEN_EXISTING 0x00
#if _FS_READONLY == 0
#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
#define FA__ERROR 0x80
 
 
/* 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 */
 
 
 
/* Offset of FAT structure members */
 
#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
 
 
 
/* Multi-byte word access macros */
 
#if _MCU_ENDIAN == 1 /* Use word access */
#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)
#elif _MCU_ENDIAN == 2 /* Use byte-by-byte access */
#define LD_WORD(ptr) (WORD)(((WORD)*(volatile BYTE*)((ptr)+1)<<8)|(WORD)*(volatile BYTE*)(ptr))
#define LD_DWORD(ptr) (DWORD)(((DWORD)*(volatile BYTE*)((ptr)+3)<<24)|((DWORD)*(volatile BYTE*)((ptr)+2)<<16)|((WORD)*(volatile BYTE*)((ptr)+1)<<8)|*(volatile BYTE*)(ptr))
#define ST_WORD(ptr,val) *(volatile BYTE*)(ptr)=(BYTE)(val); *(volatile BYTE*)((ptr)+1)=(BYTE)((WORD)(val)>>8)
#define ST_DWORD(ptr,val) *(volatile BYTE*)(ptr)=(BYTE)(val); *(volatile BYTE*)((ptr)+1)=(BYTE)((WORD)(val)>>8); *(volatile BYTE*)((ptr)+2)=(BYTE)((DWORD)(val)>>16); *(volatile BYTE*)((ptr)+3)=(BYTE)((DWORD)(val)>>24)
#else
#error Do not forget to set _MCU_ENDIAN properly!
#endif
 
 
#define _FATFS
#endif /* _FATFS */
/programy/C/avr/SDcard/integer.h
0,0 → 1,30
/*-------------------------------------------*/
/* Integer type definitions for FatFs module */
/*-------------------------------------------*/
 
#ifndef _INTEGER
 
/* 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 signed 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;
 
/* These types must be 32-bit integer */
typedef long LONG;
typedef unsigned long ULONG;
typedef unsigned long DWORD;
 
/* Boolean type */
typedef enum { FALSE = 0, TRUE } BOOL;
 
#define _INTEGER
#endif
/programy/C/avr/SDcard/main.c
0,0 → 1,554
/*----------------------------------------------------------------------*/
/* FAT file system sample project for FatFs R0.06 (C)ChaN, 2008 */
/*----------------------------------------------------------------------*/
 
 
#include <avr/io.h>
#include <avr/pgmspace.h>
#include <avr/interrupt.h>
#include <string.h>
#include "uart.h"
#include "xitoa.h"
#include "ff.h"
#include "diskio.h"
#include "rtc.h"
 
#include "mmc.c"
 
 
 
DWORD acc_size; /* Work register for fs command */
WORD acc_files, acc_dirs;
FILINFO finfo;
 
BYTE line[120]; /* Console input buffer */
 
FATFS fatfs[2]; /* File system object for each logical drive */
BYTE Buff[1024]; /* Working buffer */
 
 
volatile WORD Timer; /* 100Hz increment timer */
 
 
 
#if _MULTI_PARTITION != 0
const PARTITION Drives[] = { {0,0}, {0,1} };
#endif
 
/*---------------------------------------------------------*/
/* 100Hz timer interrupt generated by OC2 */
/*---------------------------------------------------------*/
 
 
ISR(TIMER2_COMP_vect)
{
Timer++; /* Performance counter for this module */
disk_timerproc(); /* Drive timer procedure of low level disk I/O module */
}
 
 
 
/*---------------------------------------------------------*/
/* User Provided Timer Function for FatFs module */
/*---------------------------------------------------------*/
/* This is a real time clock service to be called from */
/* FatFs module. Any valid time must be returned even if */
/* the system does not support a real time clock. */
/* This is not required in read-only configuration. */
 
 
DWORD get_fattime ()
{
RTC rtc;
 
 
rtc_gettime(&rtc);
 
return ((DWORD)(rtc.year - 1980) << 25)
| ((DWORD)rtc.month << 21)
| ((DWORD)rtc.mday << 16)
| ((DWORD)rtc.hour << 11)
| ((DWORD)rtc.min << 5)
| ((DWORD)rtc.sec >> 1);
}
 
 
/*--------------------------------------------------------------------------*/
/* Monitor */
 
 
static
void put_dump (const BYTE *buff, uint32_t ofs, BYTE cnt)
{
BYTE n;
 
 
xprintf(PSTR("%08lX "), ofs);
for(n = 0; n < cnt; n++)
xprintf(PSTR(" %02X"), buff[n]);
xputc(' ');
for(n = 0; n < cnt; n++) {
if ((buff[n] < 0x20)||(buff[n] >= 0x7F))
xputc('.');
else
xputc(buff[n]);
}
xputc('\n');
}
 
 
static
void get_line (char *buff, int len)
{
char c;
int idx = 0;
 
 
for (;;) {
c = uart_get();
if (c == '\r') break;
if ((c == '\b') && idx) {
idx--; uart_put(c);
}
if (((BYTE)c >= ' ') && (idx < len - 1)) {
buff[idx++] = c; uart_put(c);
}
}
buff[idx] = 0;
uart_put(c);
uart_put('\n');
}
 
 
static
FRESULT scan_files (char* path)
{
DIR dirs;
FRESULT res;
int i;
 
 
if ((res = f_opendir(&dirs, path)) == FR_OK) {
i = strlen(path);
while (((res = f_readdir(&dirs, &finfo)) == FR_OK) && finfo.fname[0]) {
if (finfo.fattrib & AM_DIR) {
acc_dirs++;
*(path+i) = '/'; strcpy(path+i+1, &finfo.fname[0]);
res = scan_files(path);
*(path+i) = '\0';
if (res != FR_OK) break;
} else {
acc_files++;
acc_size += finfo.fsize;
}
}
}
 
return res;
}
 
 
 
static
void put_rc (FRESULT rc)
{
const prog_char *p;
static const prog_char str[] =
"OK\0" "NOT_READY\0" "NO_FILE\0" "NO_PATH\0" "INVALID_NAME\0" "INVALID_DRIVE\0"
"DENIED\0" "EXIST\0" "RW_ERROR\0" "WRITE_PROTECTED\0" "NOT_ENABLED\0"
"NO_FILESYSTEM\0" "INVALID_OBJECT\0" "MKFS_ABORTED\0";
FRESULT i;
 
for (p = str, i = 0; i != rc && pgm_read_byte_near(p); i++) {
while(pgm_read_byte_near(p++));
}
xprintf(PSTR("rc=%u FR_%S\n"), (WORD)rc, p);
}
 
 
 
 
static
void IoInit ()
{
PORTA = 0b11111111; // Port A
 
PORTB = 0b10110000; // Port B
DDRB = 0b11000000;
 
PORTC = 0b11111111; // Port C
 
PORTD = 0b11111111; // Port D
 
PORTE = 0b11110010; // Port E
DDRE = 0b10000010;
 
PORTF = 0b11111111; // Port F
 
PORTG = 0b11111; // Port G
 
uart_init(); // Initialize UART driver
 
/*
OCR1A = 51; // Timer1: LCD bias generator (OC1B)
OCR1B = 51;
TCCR1A = 0b00010000;
TCCR1B = 0b00001010;
*/
OCR2 = 90-1; // Timer2: 100Hz interval (OC2)
TCCR2 = 0b00001101;
 
TIMSK = 0b10000000; // Enable TC2.oc, interrupt
 
rtc_init(); // Initialize RTC
 
sei();
}
 
 
 
/*-----------------------------------------------------------------------*/
/* Main */
 
 
int main ()
{
char *ptr, *ptr2;
DWORD p1, p2, p3;
BYTE res, b1;
WORD w1;
UINT s1, s2, cnt;
DWORD ofs, sect = 0;
RTC rtc;
FATFS *fs;
DIR dir; /* Directory object */
FIL file1, file2; /* File object */
 
 
IoInit();
 
/* Join xitoa module to uart module */
xfunc_out = (void (*)(char))uart_put;
 
xputs(PSTR("FatFs module test monitor\n"));
 
for (;;) {
xputc('>');
get_line(line, sizeof(line));
ptr = line;
 
switch (*ptr++) {
 
case 'd' :
switch (*ptr++) {
case 'd' : /* dd <phy_drv#> [<sector>] - Dump secrtor */
if (!xatoi(&ptr, &p1)) break;
if (!xatoi(&ptr, &p2)) p2 = sect;
res = disk_read((BYTE)p1, Buff, p2, 1);
if (res) { xprintf(PSTR("rc=%d\n"), (WORD)res); break; }
sect = p2 + 1;
xprintf(PSTR("Sector:%lu\n"), p2);
for (ptr=Buff, ofs = 0; ofs < 0x200; ptr+=16, ofs+=16)
put_dump(ptr, ofs, 16);
break;
 
case 'i' : /* di <phy_drv#> - Initialize disk */
if (!xatoi(&ptr, &p1)) break;
xprintf(PSTR("rc=%d\n"), (WORD)disk_initialize((BYTE)p1));
break;
 
case 's' : /* ds <phy_drv#> - Show disk status */
if (!xatoi(&ptr, &p1)) break;
if (disk_ioctl((BYTE)p1, GET_SECTOR_COUNT, &p2) == RES_OK)
{ xprintf(PSTR("Drive size: %lu sectors\n"), p2); }
if (disk_ioctl((BYTE)p1, GET_SECTOR_SIZE, &w1) == RES_OK)
{ xprintf(PSTR("Sector size: %u\n"), w1); }
if (disk_ioctl((BYTE)p1, GET_BLOCK_SIZE, &p2) == RES_OK)
{ xprintf(PSTR("Erase block size: %lu sectors\n"), p2); }
if (disk_ioctl((BYTE)p1, MMC_GET_TYPE, &b1) == RES_OK)
{ xprintf(PSTR("MMC/SDC type: %u\n"), b1); }
if (disk_ioctl((BYTE)p1, MMC_GET_CSD, Buff) == RES_OK)
{ xputs(PSTR("CSD:\n")); put_dump(Buff, 0, 16); }
if (disk_ioctl((BYTE)p1, MMC_GET_CID, Buff) == RES_OK)
{ xputs(PSTR("CID:\n")); put_dump(Buff, 0, 16); }
if (disk_ioctl((BYTE)p1, MMC_GET_OCR, Buff) == RES_OK)
{ xputs(PSTR("OCR:\n")); put_dump(Buff, 0, 4); }
if (disk_ioctl((BYTE)p1, MMC_GET_SDSTAT, Buff) == RES_OK) {
xputs(PSTR("SD Status:\n"));
for (s1 = 0; s1 < 64; s1 += 16) put_dump(Buff+s1, s1, 16);
}
if (disk_ioctl((BYTE)p1, ATA_GET_MODEL, line) == RES_OK)
{ line[40] = '\0'; xprintf(PSTR("Model: %s\n"), line); }
if (disk_ioctl((BYTE)p1, ATA_GET_SN, line) == RES_OK)
{ line[20] = '\0'; xprintf(PSTR("S/N: %s\n"), line); }
break;
}
break;
 
case 'b' :
switch (*ptr++) {
case 'd' : /* bd <addr> - Dump R/W buffer */
if (!xatoi(&ptr, &p1)) break;
for (ptr=&Buff[p1], ofs = p1, cnt = 32; cnt; cnt--, ptr+=16, ofs+=16)
put_dump(ptr, ofs, 16);
break;
 
case 'e' : /* be <addr> [<data>] ... - Edit R/W buffer */
if (!xatoi(&ptr, &p1)) break;
if (xatoi(&ptr, &p2)) {
do {
Buff[p1++] = (BYTE)p2;
} while (xatoi(&ptr, &p2));
break;
}
for (;;) {
xprintf(PSTR("%04X %02X-"), (WORD)(p1), (WORD)Buff[p1]);
get_line(line, sizeof(line));
ptr = line;
if (*ptr == '.') break;
if (*ptr < ' ') { p1++; continue; }
if (xatoi(&ptr, &p2))
Buff[p1++] = (BYTE)p2;
else
xputs(PSTR("???\n"));
}
break;
 
case 'r' : /* br <phy_drv#> <sector> [<n>] - Read disk into R/W buffer */
if (!xatoi(&ptr, &p1)) break;
if (!xatoi(&ptr, &p2)) break;
if (!xatoi(&ptr, &p3)) p3 = 1;
xprintf(PSTR("rc=%u\n"), (WORD)disk_read((BYTE)p1, Buff, p2, p3));
break;
 
case 'w' : /* bw <phy_drv#> <sector> [<n>] - Write R/W buffer into disk */
if (!xatoi(&ptr, &p1)) break;
if (!xatoi(&ptr, &p2)) break;
if (!xatoi(&ptr, &p3)) p3 = 1;
xprintf(PSTR("rc=%u\n"), (WORD)disk_write((BYTE)p1, Buff, p2, p3));
break;
 
case 'f' : /* bf <n> - Fill working buffer */
if (!xatoi(&ptr, &p1)) break;
memset(Buff, (BYTE)p1, sizeof(Buff));
break;
 
}
break;
 
case 'f' :
switch (*ptr++) {
 
case 'i' : /* fi <log drv#> - Initialize logical drive */
if (!xatoi(&ptr, &p1)) break;
put_rc(f_mount((BYTE)p1, &fatfs[p1]));
break;
 
case 's' : /* fs [<path>] - Show logical drive status */
res = f_getfree(ptr, &p2, &fs);
if (res) { put_rc(res); break; }
xprintf(PSTR("FAT type = %u\nBytes/Cluster = %lu\nNumber of FATs = %u\n"
"Root DIR entries = %u\nSectors/FAT = %lu\nNumber of clusters = %lu\n"
"FAT start (lba) = %lu\nDIR start (lba,clustor) = %lu\nData start (lba) = %lu\n"),
(WORD)fs->fs_type, (DWORD)fs->csize * 512, (WORD)fs->n_fats,
fs->n_rootdir, (DWORD)fs->sects_fat, (DWORD)fs->max_clust - 2,
fs->fatbase, fs->dirbase, fs->database
);
acc_size = acc_files = acc_dirs = 0;
res = scan_files(ptr);
if (res) { put_rc(res); break; }
xprintf(PSTR("%u files, %lu bytes.\n%u folders.\n"
"%lu KB total disk space.\n%lu KB available.\n"),
acc_files, acc_size, acc_dirs,
(fs->max_clust - 2) * (fs->csize / 2), p2 * (fs->csize / 2)
);
break;
 
case 'l' : /* fl [<path>] - Directory listing */
res = f_opendir(&dir, ptr);
if (res) { put_rc(res); break; }
p1 = s1 = s2 = 0;
for(;;) {
res = f_readdir(&dir, &finfo);
if ((res != FR_OK) || !finfo.fname[0]) break;
if (finfo.fattrib & AM_DIR) {
s2++;
} else {
s1++; p1 += finfo.fsize;
}
xprintf(PSTR("%c%c%c%c%c %u/%02u/%02u %02u:%02u %9lu %s\n"),
(finfo.fattrib & AM_DIR) ? 'D' : '-',
(finfo.fattrib & AM_RDO) ? 'R' : '-',
(finfo.fattrib & AM_HID) ? 'H' : '-',
(finfo.fattrib & AM_SYS) ? 'S' : '-',
(finfo.fattrib & AM_ARC) ? 'A' : '-',
(finfo.fdate >> 9) + 1980, (finfo.fdate >> 5) & 15, finfo.fdate & 31,
(finfo.ftime >> 11), (finfo.ftime >> 5) & 63,
finfo.fsize, &(finfo.fname[0]));
}
xprintf(PSTR("%4u File(s),%10lu bytes total\n%4u Dir(s)"), s1, p1, s2);
if (f_getfree(ptr, &p1, &fs) == FR_OK)
xprintf(PSTR(", %10luK bytes free\n"), p1 * fs->csize / 2);
break;
 
case 'o' : /* fo <mode> <name> - Open a file */
if (!xatoi(&ptr, &p1)) break;
put_rc(f_open(&file1, ptr, (BYTE)p1));
break;
 
case 'c' : /* fc - Close a file */
put_rc(f_close(&file1));
break;
 
case 'e' : /* fe - Seek file pointer */
if (!xatoi(&ptr, &p1)) break;
res = f_lseek(&file1, p1);
put_rc(res);
if (res == FR_OK)
xprintf(PSTR("fptr = %lu(0x%lX)\n"), file1.fptr, file1.fptr);
break;
 
case 'r' : /* fr <len> - read file */
if (!xatoi(&ptr, &p1)) break;
p2 = 0;
Timer = 0;
while (p1) {
if (p1 >= sizeof(Buff)) { cnt = sizeof(Buff); p1 -= sizeof(Buff); }
else { cnt = (WORD)p1; p1 = 0; }
res = f_read(&file1, Buff, cnt, &s2);
if (res != FR_OK) { put_rc(res); break; }
p2 += s2;
if (cnt != s2) break;
}
s2 = Timer;
xprintf(PSTR("%lu bytes read with %lu bytes/sec.\n"), p2, p2 * 100 / s2);
break;
 
case 'd' : /* fd <len> - read and dump file from current fp */
if (!xatoi(&ptr, &p1)) break;
ofs = file1.fptr;
while (p1) {
if (p1 >= 16) { cnt = 16; p1 -= 16; }
else { cnt = (WORD)p1; p1 = 0; }
res = f_read(&file1, Buff, cnt, &cnt);
if (res != FR_OK) { put_rc(res); break; }
if (!cnt) break;
put_dump(Buff, ofs, cnt);
ofs += 16;
}
break;
 
case 'w' : /* fw <len> <val> - write file */
if (!xatoi(&ptr, &p1) || !xatoi(&ptr, &p2)) break;
memset(Buff, (BYTE)p2, sizeof(Buff));
p2 = 0;
Timer = 0;
while (p1) {
if (p1 >= sizeof(Buff)) { cnt = sizeof(Buff); p1 -= sizeof(Buff); }
else { cnt = (WORD)p1; p1 = 0; }
res = f_write(&file1, Buff, cnt, &s2);
if (res != FR_OK) { put_rc(res); break; }
p2 += s2;
if (cnt != s2) break;
}
s2 = Timer;
xprintf(PSTR("%lu bytes written with %lu bytes/sec.\n"), p2, p2 * 100 / s2);
break;
 
case 'v' : /* fv - Truncate file */
put_rc(f_truncate(&file1));
break;
 
case 'n' : /* fn <old_name> <new_name> - Change file/dir name */
while (*ptr == ' ') ptr++;
ptr2 = strchr(ptr, ' ');
if (!ptr2) break;
*ptr2++ = 0;
while (*ptr2 == ' ') ptr2++;
put_rc(f_rename(ptr, ptr2));
break;
 
case 'u' : /* fu <name> - Unlink a file or dir */
put_rc(f_unlink(ptr));
break;
 
case 'k' : /* fk <name> - Create a directory */
put_rc(f_mkdir(ptr));
break;
 
case 'a' : /* fa <atrr> <mask> <name> - Change file/dir attribute */
if (!xatoi(&ptr, &p1) || !xatoi(&ptr, &p2)) break;
put_rc(f_chmod(ptr, p1, p2));
break;
 
case 't' : /* ft <year> <month> <day> <hour> <min> <sec> <name> */
if (!xatoi(&ptr, &p1) || !xatoi(&ptr, &p2) || !xatoi(&ptr, &p3)) break;
finfo.fdate = ((p1 - 1980) << 9) | ((p2 & 15) << 5) | (p3 & 31);
if (!xatoi(&ptr, &p1) || !xatoi(&ptr, &p2) || !xatoi(&ptr, &p3)) break;
finfo.ftime = ((p1 & 31) << 11) | ((p1 & 63) << 5) | ((p1 >> 1) & 31);
put_rc(f_utime(ptr, &finfo));
break;
 
case 'x' : /* fx <src_name> <dst_name> - Copy file */
while (*ptr == ' ') ptr++;
ptr2 = strchr(ptr, ' ');
if (!ptr2) break;
*ptr2++ = 0;
xprintf(PSTR("Opening \"%s\""), ptr);
res = f_open(&file1, ptr, FA_OPEN_EXISTING | FA_READ);
if (res) {
put_rc(res);
break;
}
xprintf(PSTR("\nCreating \"%s\""), ptr2);
res = f_open(&file2, ptr2, FA_CREATE_ALWAYS | FA_WRITE);
if (res) {
put_rc(res);
f_close(&file1);
break;
}
xprintf(PSTR("\nCopying..."));
p1 = 0;
for (;;) {
res = f_read(&file1, Buff, sizeof(Buff), &s1);
if (res || s1 == 0) break; /* error or eof */
res = f_write(&file2, Buff, s1, &s2);
p1 += s2;
if (res || s2 < s1) break; /* error or disk full */
}
if (res) put_rc(res);
xprintf(PSTR("\n%lu bytes copied.\n"), p1);
f_close(&file1);
f_close(&file2);
break;
#if _USE_MKFS
case 'm' : /* fm <logi drv#> <part type> <bytes/clust> - Create file system */
if (!xatoi(&ptr, &p1) || !xatoi(&ptr, &p2) || !xatoi(&ptr, &p3)) break;
xprintf(PSTR("The drive %u will be formatted. Are you sure? (Y/n)="), (WORD)p1);
get_line(ptr, sizeof(line));
if (*ptr == 'Y') put_rc(f_mkfs((BYTE)p1, (BYTE)p2, (WORD)p3));
break;
#endif
}
break;
 
case 't' : /* t [<year> <mon> <mday> <hour> <min> <sec>] */
if (xatoi(&ptr, &p1)) {
rtc.year = (WORD)p1;
xatoi(&ptr, &p1); rtc.month = (BYTE)p1;
xatoi(&ptr, &p1); rtc.mday = (BYTE)p1;
xatoi(&ptr, &p1); rtc.hour = (BYTE)p1;
xatoi(&ptr, &p1); rtc.min = (BYTE)p1;
if (!xatoi(&ptr, &p1)) break;
rtc.sec = (BYTE)p1;
rtc_settime(&rtc);
}
rtc_gettime(&rtc);
xprintf(PSTR("%u/%u/%u %02u:%02u:%02u\n"), rtc.year, rtc.month, rtc.mday, rtc.hour, rtc.min, rtc.sec);
break;
}
}
 
}
 
 
/programy/C/avr/SDcard/mmc.c
0,0 → 1,597
/*-----------------------------------------------------------------------*/
/* MMC/SDSC/SDHC (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 "diskio.h"
 
 
/* Definitions for MMC/SDC command */
#define CMD0 (0x40+0) /* GO_IDLE_STATE */
#define CMD1 (0x40+1) /* SEND_OP_COND (MMC) */
#define ACMD41 (0xC0+41) /* SEND_OP_COND (SDC) */
#define CMD8 (0x40+8) /* SEND_IF_COND */
#define CMD9 (0x40+9) /* SEND_CSD */
#define CMD10 (0x40+10) /* SEND_CID */
#define CMD12 (0x40+12) /* STOP_TRANSMISSION */
#define ACMD13 (0xC0+13) /* SD_STATUS (SDC) */
#define CMD16 (0x40+16) /* SET_BLOCKLEN */
#define CMD17 (0x40+17) /* READ_SINGLE_BLOCK */
#define CMD18 (0x40+18) /* READ_MULTIPLE_BLOCK */
#define CMD23 (0x40+23) /* SET_BLOCK_COUNT (MMC) */
#define ACMD23 (0xC0+23) /* SET_WR_BLK_ERASE_COUNT (SDC) */
#define CMD24 (0x40+24) /* WRITE_BLOCK */
#define CMD25 (0x40+25) /* WRITE_MULTIPLE_BLOCK */
#define CMD55 (0x40+55) /* APP_CMD */
#define CMD58 (0x40+58) /* READ_OCR */
 
 
/* Port Controls (Platform dependent) */
#define SELECT() PORTB &= ~1 /* MMC CS = L */
#define DESELECT() 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) */
 
 
 
/*--------------------------------------------------------------------------
 
Module Private Functions
 
---------------------------------------------------------------------------*/
 
static volatile
DSTATUS Stat = STA_NOINIT; /* Disk status */
 
static volatile
BYTE Timer1, Timer2; /* 100Hz decrement timer */
 
static
BYTE CardType; /* b0:MMC, b1:SDv1, b2:SDv2, b3:Block addressing */
 
 
 
/*-----------------------------------------------------------------------*/
/* Transmit a byte to MMC via SPI (Platform dependent) */
/*-----------------------------------------------------------------------*/
 
#define xmit_spi(dat) SPDR=(dat); loop_until_bit_is_set(SPSR,SPIF)
 
 
 
/*-----------------------------------------------------------------------*/
/* Receive a byte from MMC via SPI (Platform dependent) */
/*-----------------------------------------------------------------------*/
 
static
BYTE rcvr_spi (void)
{
SPDR = 0xFF;
loop_until_bit_is_set(SPSR, SPIF);
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
BYTE wait_ready (void)
{
BYTE res;
 
 
Timer2 = 50; /* Wait for ready in timeout of 500ms */
rcvr_spi();
do
res = rcvr_spi();
while ((res != 0xFF) && Timer2);
 
return res;
}
 
 
 
/*-----------------------------------------------------------------------*/
/* Deselect the card and release SPI bus */
/*-----------------------------------------------------------------------*/
 
static
void release_spi (void)
{
DESELECT();
rcvr_spi();
}
 
 
 
/*-----------------------------------------------------------------------*/
/* 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 = 0b01010000; /* Initialize SPI port (Mode 0) */
SPSR = 0b00000001;
}
 
static
void power_off (void)
{
SELECT(); /* Wait for card ready */
wait_ready();
release_spi();
 
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 (PORTE & 0x80) ? 0 : 1;
}
 
 
 
/*-----------------------------------------------------------------------*/
/* Receive a data packet from MMC */
/*-----------------------------------------------------------------------*/
 
static
BOOL rcvr_datablock (
BYTE *buff, /* Data buffer to store received data */
UINT btr /* Byte count (must be multiple of 4) */
)
{
BYTE token;
 
 
Timer1 = 10;
do { /* Wait for data packet in timeout of 100ms */
token = rcvr_spi();
} while ((token == 0xFF) && Timer1);
if(token != 0xFE) return FALSE; /* 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 TRUE; /* Return with success */
}
 
 
 
/*-----------------------------------------------------------------------*/
/* Send a data packet to MMC */
/*-----------------------------------------------------------------------*/
 
#if _READONLY == 0
static
BOOL xmit_datablock (
const BYTE *buff, /* 512 byte data block to be transmitted */
BYTE token /* Data/Stop token */
)
{
BYTE resp, wc;
 
 
if (wait_ready() != 0xFF) return FALSE;
 
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 FALSE;
}
 
return TRUE;
}
#endif /* _READONLY */
 
 
 
/*-----------------------------------------------------------------------*/
/* Send a command packet to MMC */
/*-----------------------------------------------------------------------*/
 
static
BYTE send_cmd (
BYTE cmd, /* Command byte */
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();
SELECT();
if (wait_ready() != 0xFF) return 0xFF;
 
/* Send command packet */
xmit_spi(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 */
for (n = 10; n; n--) rcvr_spi(); /* 80 dummy clocks */
 
ty = 0;
if (send_cmd(CMD0, 0) == 1) { /* Enter Idle state */
Timer1 = 100; /* Initialization timeout of 1000 msec */
if (send_cmd(CMD8, 0x1AA) == 1) { /* SDHC */
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) ? 12 : 4;
}
}
} else { /* SDSC or MMC */
if (send_cmd(ACMD41, 0) <= 1) {
ty = 2; cmd = ACMD41; /* SDSC */
} else {
ty = 1; cmd = CMD1; /* MMC */
}
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;
release_spi();
 
if (ty) { /* Initialization succeded */
Stat &= ~STA_NOINIT; /* Clear STA_NOINIT */
} 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 & 8)) 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 */
}
}
release_spi();
 
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 & 8)) 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 & 6) 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;
}
}
release_spi();
 
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 */
SELECT();
if (wait_ready() == 0xFF)
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 & 4) { /* SDC ver 2.00 */
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 { /* SDC ver 1.XX or MMC */
if ((send_cmd(CMD9, 0) == 0) && rcvr_datablock(csd, 16)) { /* Read CSD */
if (CardType & 2) { /* SDC ver 1.XX */
*(DWORD*)buff = (((csd[10] & 63) << 1) + ((WORD)(csd[11] & 128) >> 7) + 1) << ((csd[13] >> 6) - 1);
} else { /* MMC */
*(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;
}
 
release_spi();
}
 
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;
}
}
 
/programy/C/avr/SDcard/rtc.c
0,0 → 1,252
/*--------------------------------------------------------------------------*/
/* RTC controls */
 
#include <avr/io.h>
#include <string.h>
#include "rtc.h"
 
 
 
#define SCL_LOW() DDRE |= 0x04 /* SCL = LOW */
#define SCL_HIGH() DDRE &= 0xFB /* SCL = High-Z */
#define SCL_VAL ((PINE & 0x04) ? 1 : 0) /* SCL input level */
#define SDA_LOW() DDRE |= 0x08 /* SDA = LOW */
#define SDA_HIGH() DDRE &= 0xF7 /* SDA = High-Z */
#define SDA_VAL ((PINE & 0x08) ? 1 : 0) /* SDA input level */
 
 
 
static
void iic_delay (void)
{
int n;
BYTE d;
 
for (n = 4; n; n--) d = PINE;
}
 
 
/* Generate start condition on the IIC bus */
static
void iic_start (void)
{
SDA_HIGH();
iic_delay();
SCL_HIGH();
iic_delay();
SDA_LOW();
iic_delay();
SCL_LOW();
iic_delay();
}
 
 
/* Generate stop condition on the IIC bus */
static
void iic_stop (void)
{
SDA_LOW();
iic_delay();
SCL_HIGH();
iic_delay();
SDA_HIGH();
iic_delay();
}
 
 
/* Send a byte to the IIC bus */
static
BOOL iic_send (BYTE dat)
{
BYTE b = 0x80;
BOOL ack;
 
 
do {
if (dat & b) { /* SDA = Z/L */
SDA_HIGH();
} else {
SDA_LOW();
}
iic_delay();
SCL_HIGH();
iic_delay();
SCL_LOW();
iic_delay();
} while (b >>= 1);
SDA_HIGH();
iic_delay();
SCL_HIGH();
ack = SDA_VAL ? FALSE : TRUE; /* Sample ACK */
iic_delay();
SCL_LOW();
iic_delay();
return ack;
}
 
 
/* Receive a byte from the IIC bus */
static
BYTE iic_rcvr (BOOL ack)
{
UINT d = 1;
 
 
do {
d <<= 1;
SCL_HIGH();
if (SDA_VAL) d++;
iic_delay();
SCL_LOW();
iic_delay();
} while (d < 0x100);
if (ack) { /* SDA = ACK */
SDA_LOW();
} else {
SDA_HIGH();
}
iic_delay();
SCL_HIGH();
iic_delay();
SCL_LOW();
SDA_HIGH();
iic_delay();
 
return (BYTE)d;
}
 
 
 
 
BOOL rtc_read (
UINT adr, /* Read start address */
UINT cnt, /* Read byte count */
void* buff /* Read data buffer */
)
{
BYTE *rbuff = buff;
int n;
 
 
if (!cnt) return FALSE;
 
n = 10;
do { /* Select DS1338 (0xD0) */
iic_start();
} while (!iic_send(0xD0) && --n);
if (!n) return FALSE;
 
if (iic_send((BYTE)adr)) { /* Set start address */
iic_start(); /* Reselect DS1338 in read mode (0xD1) */
if (iic_send(0xD1)) {
do { /* Receive data */
cnt--;
*rbuff++ = iic_rcvr(cnt ? TRUE : FALSE);
} while (cnt);
}
}
 
iic_stop(); /* Deselect device */
 
return cnt ? FALSE : TRUE;
}
 
 
 
 
BOOL rtc_write (
UINT adr, /* Write start address */
UINT cnt, /* Write byte count */
const void* buff /* Data to be written */
)
{
const BYTE *wbuff = buff;
int n;
 
 
if (!cnt) return FALSE;
 
n = 10;
do { /* Select DS1338 (0xD0) */
iic_start();
} while (!iic_send(0xD0) && --n);
if (!n) return FALSE;
 
if (iic_send((BYTE)adr)) { /* Set start address */
do { /* Send data */
if (!iic_send(*wbuff++)) break;
} while (--cnt);
}
 
iic_stop(); /* Deselect device */
 
return cnt ? FALSE : TRUE;
}
 
 
 
 
BOOL rtc_gettime (RTC *rtc)
{
BYTE buf[8];
 
 
if (!rtc_read(0, 7, buf)) return FALSE;
 
rtc->sec = (buf[0] & 0x0F) + ((buf[0] >> 4) & 7) * 10;
rtc->min = (buf[1] & 0x0F) + (buf[1] >> 4) * 10;
rtc->hour = (buf[2] & 0x0F) + ((buf[2] >> 4) & 3) * 10;
rtc->mday = (buf[4] & 0x0F) + ((buf[4] >> 4) & 3) * 10;
rtc->month = (buf[5] & 0x0F) + ((buf[5] >> 4) & 1) * 10;
rtc->year = 2000 + (buf[6] & 0x0F) + (buf[6] >> 4) * 10;
 
return TRUE;
}
 
 
 
 
BOOL rtc_settime (const RTC *rtc)
{
 
BYTE buf[8];
 
 
buf[0] = rtc->sec / 10 * 16 + rtc->sec % 10;
buf[1] = rtc->min / 10 * 16 + rtc->min % 10;
buf[2] = rtc->hour / 10 * 16 + rtc->hour % 10;
buf[3] = 0;
buf[4] = rtc->mday / 10 * 16 + rtc->mday % 10;
buf[5] = rtc->month / 10 * 16 + rtc->month % 10;
buf[6] = (rtc->year - 2000) / 10 * 16 + (rtc->year - 2000) % 10;
rtc_write(0, 7, buf);
 
return TRUE;
}
 
 
 
 
BOOL rtc_init (void)
{
BYTE buf[8]; /* RTC R/W buffer */
UINT n;
 
 
/* Read RTC registers */
if (!rtc_read(0, 8, buf)) return FALSE; /* IIC error */
 
if (buf[7] & 0x20) { /* When RTC data has been broken, set default time */
/* Reset time to Jan 1, '08 */
memset(buf, 0, 8);
buf[4] = 1; buf[5] = 1; buf[6] = 8;
rtc_write(0, 8, buf);
/* Clear data memory */
memset(buf, 0, 8);
for (n = 8; n < 64; n += 8)
rtc_write(n, 8, buf);
return FALSE;
}
return TRUE;
}
 
/programy/C/avr/SDcard/rtc.h
0,0 → 1,18
#include "integer.h"
#include "rtc.c"
 
typedef struct {
WORD year;
BYTE month;
BYTE mday;
BYTE hour;
BYTE min;
BYTE sec;
} RTC;
 
BOOL rtc_init (void); /* Initialize RTC */
BOOL rtc_gettime (RTC*); /* Get time */
BOOL rtc_settime (const RTC*); /* Set time */
BOOL rtc_write (UINT, UINT, const void*); /* Write RTC regs */
BOOL rtc_read (UINT, UINT, void*); /* Read RTC regs */
 
/programy/C/avr/SDcard/tff.c
0,0 → 1,1876
/*----------------------------------------------------------------------------/
/ FatFs - Tiny FAT file system module R0.06 (C)ChaN, 2008
/-----------------------------------------------------------------------------/
/ The FatFs module is an experimenal project to implement FAT file system to
/ cheap microcontrollers. This is a free software and is opened for education,
/ research and development under license policy of following trems.
/
/ Copyright (C) 2008, ChaN, all right reserved.
/
/ * The FatFs module is a free software and there is no warranty.
/ * You can use, modify and/or redistribute it for personal, non-profit or
/ commercial use without any restriction under your responsibility.
/ * Redistributions of source code must retain the above copyright notice.
/
/-----------------------------------------------------------------------------/
/ Feb 26,'06 R0.00 Prototype.
/
/ Apr 29,'06 R0.01 First stable version.
/
/ Jun 01,'06 R0.02 Added FAT12 support.
/ Removed unbuffered mode.
/ Fixed a problem on small (<32M) patition.
/ Jun 10,'06 R0.02a Added a configuration option (_FS_MINIMUM).
/
/ Sep 22,'06 R0.03 Added f_rename().
/ Changed option _FS_MINIMUM to _FS_MINIMIZE.
/ Dec 09,'06 R0.03a Improved cluster scan algolithm to write files fast.
/
/ Feb 04,'07 R0.04 Added FAT32 supprt.
/ Changed some interfaces incidental to FatFs.
/ Changed f_mountdrv() to f_mount().
/ Apr 01,'07 R0.04a Added a capability of extending file size to f_lseek().
/ Added minimization level 3.
/ Fixed a problem in FAT32 support.
/ May 05,'07 R0.04b Added a configuration option _USE_NTFLAG.
/ Added FSInfo support.
/ Fixed some problems corresponds to FAT32 support.
/ Fixed DBCS name can result FR_INVALID_NAME.
/ Fixed short seek (<= csize) collapses the file object.
/
/ Aug 25,'07 R0.05 Changed arguments of f_read() and f_write().
/ Feb 03,'08 R0.05a Added f_truncate() and f_utime().
/ Fixed off by one error at FAT sub-type determination.
/ Fixed btr in f_read() can be mistruncated.
/ Fixed cached sector is not flushed when create and close
/ without write.
/
/ Apr 01,'08 R0.06 Added f_forward(), fputc(), fputs(), fprintf() and fgets().
/ Improved performance of f_lseek() on moving to the same
/ or following cluster.
/----------------------------------------------------------------------------*/
 
#include <string.h>
#include "tff.h" /* Tiny-FatFs declarations */
#include "diskio.h" /* Include file for user provided disk functions */
 
 
static
FATFS *FatFs; /* Pointer to the file system objects (logical drive) */
static
WORD fsid; /* File system mount ID */
 
 
/*-------------------------------------------------------------------------
 
Module Private Functions
 
-------------------------------------------------------------------------*/
 
 
/*-----------------------------------------------------------------------*/
/* Change window offset */
/*-----------------------------------------------------------------------*/
 
static
BOOL move_window ( /* TRUE: successful, FALSE: failed */
DWORD sector /* Sector number to make apperance in the FatFs->win */
) /* Move to zero only writes back dirty window */
{
DWORD wsect;
FATFS *fs = FatFs;
 
 
wsect = fs->winsect;
if (wsect != sector) { /* Changed current window */
#if !_FS_READONLY
BYTE n;
if (fs->winflag) { /* Write back dirty window if needed */
if (disk_write(0, fs->win, wsect, 1) != RES_OK)
return FALSE;
fs->winflag = 0;
if (wsect < (fs->fatbase + fs->sects_fat)) { /* In FAT area */
for (n = fs->n_fats; n >= 2; n--) { /* Refrect the change to all FAT copies */
wsect += fs->sects_fat;
disk_write(0, fs->win, wsect, 1);
}
}
}
#endif
if (sector) {
if (disk_read(0, fs->win, sector, 1) != RES_OK)
return FALSE;
fs->winsect = sector;
}
}
return TRUE;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Clean-up cached data */
/*-----------------------------------------------------------------------*/
 
#if !_FS_READONLY
static
FRESULT sync (void) /* FR_OK: successful, FR_RW_ERROR: failed */
{
FATFS *fs = FatFs;
 
 
fs->winflag = 1;
if (!move_window(0)) return FR_RW_ERROR;
#if _USE_FSINFO
/* Update FSInfo sector if needed */
if (fs->fs_type == FS_FAT32 && fs->fsi_flag) {
fs->winsect = 0;
memset(fs->win, 0, 512U);
ST_WORD(&fs->win[BS_55AA], 0xAA55);
ST_DWORD(&fs->win[FSI_LeadSig], 0x41615252);
ST_DWORD(&fs->win[FSI_StrucSig], 0x61417272);
ST_DWORD(&fs->win[FSI_Free_Count], fs->free_clust);
ST_DWORD(&fs->win[FSI_Nxt_Free], fs->last_clust);
disk_write(0, fs->win, fs->fsi_sector, 1);
fs->fsi_flag = 0;
}
#endif
/* Make sure that no pending write process in the physical drive */
if (disk_ioctl(0, CTRL_SYNC, NULL) != RES_OK)
return FR_RW_ERROR;
return FR_OK;
}
#endif
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Get a cluster status */
/*-----------------------------------------------------------------------*/
 
static
CLUST get_cluster ( /* 0,>=2: successful, 1: failed */
CLUST clust /* Cluster# to get the link information */
)
{
WORD wc, bc;
DWORD fatsect;
FATFS *fs = FatFs;
 
 
if (clust >= 2 && clust < fs->max_clust) { /* Valid cluster# */
fatsect = fs->fatbase;
switch (fs->fs_type) {
case FS_FAT12 :
bc = (WORD)clust * 3 / 2;
if (!move_window(fatsect + bc / 512U)) break;
wc = fs->win[bc % 512U]; bc++;
if (!move_window(fatsect + bc / 512U)) break;
wc |= (WORD)fs->win[bc % 512U] << 8;
return (clust & 1) ? (wc >> 4) : (wc & 0xFFF);
 
case FS_FAT16 :
if (!move_window(fatsect + clust / 256)) break;
return LD_WORD(&fs->win[((WORD)clust * 2) % 512U]);
#if _FAT32
case FS_FAT32 :
if (!move_window(fatsect + clust / 128)) break;
return LD_DWORD(&fs->win[((WORD)clust * 4) % 512U]) & 0x0FFFFFFF;
#endif
}
}
 
return 1; /* Out of cluster range, or an error occured */
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Change a cluster status */
/*-----------------------------------------------------------------------*/
 
#if !_FS_READONLY
static
BOOL put_cluster ( /* TRUE: successful, FALSE: failed */
CLUST clust, /* Cluster# to change (must be 2 to fs->max_clust-1) */
CLUST val /* New value to mark the cluster */
)
{
WORD bc;
BYTE *p;
DWORD fatsect;
FATFS *fs = FatFs;
 
 
fatsect = fs->fatbase;
switch (fs->fs_type) {
case FS_FAT12 :
bc = (WORD)clust * 3 / 2;
if (!move_window(fatsect + bc / 512U)) return FALSE;
p = &fs->win[bc % 512U];
*p = (clust & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val;
bc++;
fs->winflag = 1;
if (!move_window(fatsect + bc / 512U)) return FALSE;
p = &fs->win[bc % 512U];
*p = (clust & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F));
break;
 
case FS_FAT16 :
if (!move_window(fatsect + clust / 256)) return FALSE;
ST_WORD(&fs->win[((WORD)clust * 2) % 512U], (WORD)val);
break;
#if _FAT32
case FS_FAT32 :
if (!move_window(fatsect + clust / 128)) return FALSE;
ST_DWORD(&fs->win[((WORD)clust * 4) % 512U], val);
break;
#endif
default :
return FALSE;
}
fs->winflag = 1;
return TRUE;
}
#endif /* !_FS_READONLY */
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Remove a cluster chain */
/*-----------------------------------------------------------------------*/
 
#if !_FS_READONLY
static
BOOL remove_chain ( /* TRUE: successful, FALSE: failed */
CLUST clust /* Cluster# to remove chain from */
)
{
CLUST nxt;
FATFS *fs = FatFs;
 
 
while (clust >= 2 && clust < fs->max_clust) {
nxt = get_cluster(clust);
if (nxt == 1) return FALSE;
if (!put_cluster(clust, 0)) return FALSE;
if (fs->free_clust != (CLUST)0xFFFFFFFF) {
fs->free_clust++;
#if _USE_FSINFO
fs->fsi_flag = 1;
#endif
}
clust = nxt;
}
return TRUE;
}
#endif
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Stretch or create a cluster chain */
/*-----------------------------------------------------------------------*/
 
#if !_FS_READONLY
static
CLUST create_chain ( /* 0: No free cluster, 1: Error, >=2: New cluster number */
CLUST clust /* Cluster# to stretch, 0 means create new */
)
{
CLUST cstat, ncl, scl, mcl;
FATFS *fs = FatFs;
 
 
mcl = fs->max_clust;
if (clust == 0) { /* Create new chain */
scl = fs->last_clust; /* Get last allocated cluster */
if (scl < 2 || scl >= mcl) scl = 1;
}
else { /* Stretch existing chain */
cstat = get_cluster(clust); /* Check the cluster status */
if (cstat < 2) return 1; /* It is an invalid cluster */
if (cstat < mcl) return cstat; /* It is already followed by next cluster */
scl = clust;
}
 
ncl = scl; /* Start cluster */
for (;;) {
ncl++; /* Next cluster */
if (ncl >= mcl) { /* Wrap around */
ncl = 2;
if (ncl > scl) return 0; /* No free custer */
}
cstat = get_cluster(ncl); /* Get the cluster status */
if (cstat == 0) break; /* Found a free cluster */
if (cstat == 1) return 1; /* Any error occured */
if (ncl == scl) return 0; /* No free custer */
}
 
if (!put_cluster(ncl, (CLUST)0x0FFFFFFF)) return 1; /* Mark the new cluster "in use" */
if (clust != 0 && !put_cluster(clust, ncl)) return 1; /* Link it to previous one if needed */
 
fs->last_clust = ncl; /* Update fsinfo */
if (fs->free_clust != (CLUST)0xFFFFFFFF) {
fs->free_clust--;
#if _USE_FSINFO
fs->fsi_flag = 1;
#endif
}
 
return ncl; /* Return new cluster number */
}
#endif /* !_FS_READONLY */
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Get sector# from cluster# */
/*-----------------------------------------------------------------------*/
 
static
DWORD clust2sect ( /* !=0: sector number, 0: failed - invalid cluster# */
CLUST clust /* Cluster# to be converted */
)
{
FATFS *fs = FatFs;
 
 
clust -= 2;
if (clust >= (fs->max_clust - 2)) return 0; /* Invalid cluster# */
return (DWORD)clust * fs->csize + fs->database;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Move directory pointer to next */
/*-----------------------------------------------------------------------*/
 
static
BOOL next_dir_entry ( /* TRUE: successful, FALSE: could not move next */
DIR *dj /* Pointer to directory object */
)
{
CLUST clust;
WORD idx;
 
 
idx = dj->index + 1;
if ((idx & 15) == 0) { /* Table sector changed? */
dj->sect++; /* Next sector */
if (dj->clust == 0) { /* In static table */
if (idx >= dj->fs->n_rootdir) return FALSE; /* Reached to end of table */
} else { /* In dynamic table */
if (((idx / 16) & (dj->fs->csize - 1)) == 0) { /* Cluster changed? */
clust = get_cluster(dj->clust); /* Get next cluster */
if (clust < 2 || clust >= dj->fs->max_clust) /* Reached to end of table */
return FALSE;
dj->clust = clust; /* Initialize for new cluster */
dj->sect = clust2sect(clust);
}
}
}
dj->index = idx; /* Lower 4 bit of dj->index indicates offset in dj->sect */
return TRUE;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Get file status from directory entry */
/*-----------------------------------------------------------------------*/
 
#if _FS_MINIMIZE <= 1
static
void get_fileinfo ( /* No return code */
FILINFO *finfo, /* Ptr to store the File Information */
const BYTE *dir /* Ptr to the directory entry */
)
{
BYTE n, c, a;
char *p;
 
 
p = &finfo->fname[0];
a = _USE_NTFLAG ? dir[DIR_NTres] : 0; /* NT flag */
for (n = 0; n < 8; n++) { /* Convert file name (body) */
c = dir[n];
if (c == ' ') break;
if (c == 0x05) c = 0xE5;
if (a & 0x08 && c >= 'A' && c <= 'Z') c += 0x20;
*p++ = c;
}
if (dir[8] != ' ') { /* Convert file name (extension) */
*p++ = '.';
for (n = 8; n < 11; n++) {
c = dir[n];
if (c == ' ') break;
if (a & 0x10 && c >= 'A' && c <= 'Z') c += 0x20;
*p++ = c;
}
}
*p = '\0';
 
finfo->fattrib = dir[DIR_Attr]; /* Attribute */
finfo->fsize = LD_DWORD(&dir[DIR_FileSize]); /* Size */
finfo->fdate = LD_WORD(&dir[DIR_WrtDate]); /* Date */
finfo->ftime = LD_WORD(&dir[DIR_WrtTime]); /* Time */
}
#endif /* _FS_MINIMIZE <= 1 */
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Pick a paragraph and create the name in format of directory entry */
/*-----------------------------------------------------------------------*/
 
static
char make_dirfile ( /* 1: error - detected an invalid format, '\0'or'/': next character */
const char **path, /* Pointer to the file path pointer */
char *dirname /* Pointer to directory name buffer {Name(8), Ext(3), NT flag(1)} */
)
{
BYTE n, t, c, a, b;
 
 
memset(dirname, ' ', 8+3); /* Fill buffer with spaces */
a = 0; b = 0x18; /* NT flag */
n = 0; t = 8;
for (;;) {
c = *(*path)++;
if (c == '\0' || c == '/') { /* Reached to end of str or directory separator */
if (n == 0) break;
dirname[11] = _USE_NTFLAG ? (a & b) : 0;
return c;
}
if (c <= ' ' || c == 0x7F) break; /* Reject invisible chars */
if (c == '.') {
if (!(a & 1) && n >= 1 && n <= 8) { /* Enter extension part */
n = 8; t = 11; continue;
}
break;
}
if (_USE_SJIS &&
((c >= 0x81 && c <= 0x9F) || /* Accept S-JIS code */
(c >= 0xE0 && c <= 0xFC))) {
if (n == 0 && c == 0xE5) /* Change heading \xE5 to \x05 */
c = 0x05;
a ^= 1; goto md_l2;
}
if (c == '"') break; /* Reject " */
if (c <= ')') goto md_l1; /* Accept ! # $ % & ' ( ) */
if (c <= ',') break; /* Reject * + , */
if (c <= '9') goto md_l1; /* Accept - 0-9 */
if (c <= '?') break; /* Reject : ; < = > ? */
if (!(a & 1)) { /* These checks are not applied to S-JIS 2nd byte */
if (c == '|') break; /* Reject | */
if (c >= '[' && c <= ']') break;/* Reject [ \ ] */
if (_USE_NTFLAG && c >= 'A' && c <= 'Z')
(t == 8) ? (b &= 0xF7) : (b &= 0xEF);
if (c >= 'a' && c <= 'z') { /* Convert to upper case */
c -= 0x20;
if (_USE_NTFLAG) (t == 8) ? (a |= 0x08) : (a |= 0x10);
}
}
md_l1:
a &= 0xFE;
md_l2:
if (n >= t) break;
dirname[n++] = c;
}
return 1;
}
 
 
 
/*-----------------------------------------------------------------------*/
/* Trace a file path */
/*-----------------------------------------------------------------------*/
 
static
FRESULT trace_path ( /* FR_OK(0): successful, !=0: error code */
DIR *dj, /* Pointer to directory object to return last directory */
char *fn, /* Pointer to last segment name to return */
const char *path, /* Full-path string to trace a file or directory */
BYTE **dir /* Pointer to pointer to found entry to retutn */
)
{
CLUST clust;
char ds;
BYTE *dptr = NULL;
FATFS *fs = FatFs;
 
/* Initialize directory object */
dj->fs = fs;
clust = fs->dirbase;
#if _FAT32
if (fs->fs_type == FS_FAT32) {
dj->clust = dj->sclust = clust;
dj->sect = clust2sect(clust);
} else
#endif
{
dj->clust = dj->sclust = 0;
dj->sect = clust;
}
dj->index = 0;
 
if (*path == '\0') { /* Null path means the root directory */
*dir = NULL; return FR_OK;
}
 
for (;;) {
ds = make_dirfile(&path, fn); /* Get a paragraph into fn[] */
if (ds == 1) return FR_INVALID_NAME;
for (;;) {
if (!move_window(dj->sect)) return FR_RW_ERROR;
dptr = &fs->win[(dj->index & 15) * 32]; /* Pointer to the directory entry */
if (dptr[DIR_Name] == 0) /* Has it reached to end of dir? */
return !ds ? FR_NO_FILE : FR_NO_PATH;
if (dptr[DIR_Name] != 0xE5 /* Matched? */
&& !(dptr[DIR_Attr] & AM_VOL)
&& !memcmp(&dptr[DIR_Name], fn, 8+3) ) break;
if (!next_dir_entry(dj)) /* Next directory pointer */
return !ds ? FR_NO_FILE : FR_NO_PATH;
}
if (!ds) { *dir = dptr; return FR_OK; } /* Matched with end of path */
if (!(dptr[DIR_Attr] & AM_DIR)) return FR_NO_PATH; /* Cannot trace because it is a file */
clust = /* Get cluster# of the directory */
#if _FAT32
((DWORD)LD_WORD(&dptr[DIR_FstClusHI]) << 16) |
#endif
LD_WORD(&dptr[DIR_FstClusLO]);
dj->clust = dj->sclust = clust; /* Restart scannig with the new directory */
dj->sect = clust2sect(clust);
dj->index = 2;
}
}
 
 
 
/*-----------------------------------------------------------------------*/
/* Reserve a directory entry */
/*-----------------------------------------------------------------------*/
 
#if !_FS_READONLY
static
FRESULT reserve_direntry ( /* FR_OK: successful, FR_DENIED: no free entry, FR_RW_ERROR: a disk error occured */
DIR *dj, /* Target directory to create new entry */
BYTE **dir /* Pointer to pointer to created entry to retutn */
)
{
CLUST clust;
DWORD sector;
BYTE c, n, *dptr;
FATFS *fs = dj->fs;
 
 
/* Re-initialize directory object */
clust = dj->sclust;
if (clust != 0) { /* Dyanmic directory table */
dj->clust = clust;
dj->sect = clust2sect(clust);
} else { /* Static directory table */
dj->sect = fs->dirbase;
}
dj->index = 0;
 
do {
if (!move_window(dj->sect)) return FR_RW_ERROR;
dptr = &fs->win[(dj->index & 15) * 32]; /* Pointer to the directory entry */
c = dptr[DIR_Name];
if (c == 0 || c == 0xE5) { /* Found an empty entry! */
*dir = dptr; return FR_OK;
}
} while (next_dir_entry(dj)); /* Next directory pointer */
/* Reached to end of the directory table */
 
/* Abort when static table or could not stretch dynamic table */
if (clust == 0 || !(clust = create_chain(dj->clust))) return FR_DENIED;
if (clust == 1 || !move_window(0)) return FR_RW_ERROR;
 
fs->winsect = sector = clust2sect(clust); /* Cleanup the expanded table */
memset(fs->win, 0, 512U);
for (n = fs->csize; n; n--) {
if (disk_write(0, fs->win, sector, 1) != RES_OK)
return FR_RW_ERROR;
sector++;
}
fs->winflag = 1;
*dir = fs->win;
return FR_OK;
}
#endif /* !_FS_READONLY */
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Load boot record and check if it is an FAT boot record */
/*-----------------------------------------------------------------------*/
 
static
BYTE check_fs ( /* 0:The FAT boot record, 1:Valid boot record but not an FAT, 2:Not a boot record or error */
DWORD sect /* Sector# to check if it is an FAT boot record or not */
)
{
FATFS *fs = FatFs;
 
if (disk_read(0, fs->win, sect, 1) != RES_OK) /* Load boot record */
return 2;
if (LD_WORD(&fs->win[BS_55AA]) != 0xAA55) /* Check record signature */
return 2;
 
if (!memcmp(&fs->win[BS_FilSysType], "FAT", 3)) /* Check FAT signature */
return 0;
#if _FAT32
if (!memcmp(&fs->win[BS_FilSysType32], "FAT32", 5) && !(fs->win[BPB_ExtFlags] & 0x80))
return 0;
#endif
return 1;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Make sure that the file system is valid */
/*-----------------------------------------------------------------------*/
 
static
FRESULT auto_mount ( /* FR_OK(0): successful, !=0: any error occured */
const char **path, /* Pointer to pointer to the path name (drive number) */
BYTE chk_wp /* !=0: Check media write protection for write access */
)
{
BYTE fmt;
DSTATUS stat;
DWORD bootsect, fatsize, totalsect, maxclust;
const char *p = *path;
FATFS *fs;
 
 
while (*p == ' ') p++; /* Strip leading spaces */
if (*p == '/') p++; /* Strip heading slash */
*path = p; /* Return pointer to the path name */
 
/* Is the file system object registered? */
fs = FatFs;
if (!fs) return FR_NOT_ENABLED;
 
if (fs->fs_type) { /* If the logical drive has been mounted */
stat = disk_status(0);
if (!(stat & STA_NOINIT)) { /* and physical drive is kept initialized (has not been changed), */
#if !_FS_READONLY
if (chk_wp && (stat & STA_PROTECT)) /* Check write protection if needed */
return FR_WRITE_PROTECTED;
#endif
return FR_OK; /* The file system object is valid */
}
}
 
/* The logical drive must be re-mounted. Following code attempts to mount the logical drive */
 
memset(fs, 0, sizeof(FATFS)); /* Clean-up the file system object */
stat = disk_initialize(0); /* Initialize low level disk I/O layer */
if (stat & STA_NOINIT) /* Check if the drive is ready */
return FR_NOT_READY;
#if !_FS_READONLY
if (chk_wp && (stat & STA_PROTECT)) /* Check write protection if needed */
return FR_WRITE_PROTECTED;
#endif
 
/* Search FAT partition on the drive */
fmt = check_fs(bootsect = 0); /* Check sector 0 as an SFD format */
if (fmt == 1) { /* Not an FAT boot record, it may be patitioned */
/* Check a partition listed in top of the partition table */
if (fs->win[MBR_Table+4]) { /* Is the 1st partition existing? */
bootsect = LD_DWORD(&fs->win[MBR_Table+8]); /* Partition offset in LBA */
fmt = check_fs(bootsect); /* Check the partition */
}
}
if (fmt || LD_WORD(&fs->win[BPB_BytsPerSec]) != 512U) /* No valid FAT patition is found */
return FR_NO_FILESYSTEM;
 
/* Initialize the file system object */
fatsize = LD_WORD(&fs->win[BPB_FATSz16]); /* Number of sectors per FAT */
if (!fatsize) fatsize = LD_DWORD(&fs->win[BPB_FATSz32]);
fs->sects_fat = (CLUST)fatsize;
fs->n_fats = fs->win[BPB_NumFATs]; /* Number of FAT copies */
fatsize *= fs->n_fats; /* (Number of sectors in FAT area) */
fs->fatbase = bootsect + LD_WORD(&fs->win[BPB_RsvdSecCnt]); /* FAT start sector (lba) */
fs->csize = fs->win[BPB_SecPerClus]; /* Number of sectors per cluster */
fs->n_rootdir = LD_WORD(&fs->win[BPB_RootEntCnt]); /* Nmuber of root directory entries */
totalsect = LD_WORD(&fs->win[BPB_TotSec16]); /* Number of sectors on the file system */
if (!totalsect) totalsect = LD_DWORD(&fs->win[BPB_TotSec32]);
fs->max_clust = maxclust = (totalsect /* max_clust = Last cluster# + 1 */
- LD_WORD(&fs->win[BPB_RsvdSecCnt]) - fatsize - fs->n_rootdir / 16
) / fs->csize + 2;
 
fmt = FS_FAT12; /* Determine the FAT sub type */
if (maxclust >= 0xFF7) fmt = FS_FAT16;
if (maxclust >= 0xFFF7)
#if !_FAT32
return FR_NO_FILESYSTEM;
#else
fmt = FS_FAT32;
if (fmt == FS_FAT32)
fs->dirbase = LD_DWORD(&fs->win[BPB_RootClus]); /* Root directory start cluster */
else
#endif
fs->dirbase = fs->fatbase + fatsize; /* Root directory start sector (lba) */
fs->database = fs->fatbase + fatsize + fs->n_rootdir / 16; /* Data start sector (lba) */
 
#if !_FS_READONLY
/* Initialize allocation information */
fs->free_clust = (CLUST)0xFFFFFFFF;
#if _USE_FSINFO
/* Get fsinfo if needed */
if (fmt == FS_FAT32) {
fs->fsi_sector = bootsect + LD_WORD(&fs->win[BPB_FSInfo]);
if (disk_read(0, fs->win, fs->fsi_sector, 1) == RES_OK &&
LD_WORD(&fs->win[BS_55AA]) == 0xAA55 &&
LD_DWORD(&fs->win[FSI_LeadSig]) == 0x41615252 &&
LD_DWORD(&fs->win[FSI_StrucSig]) == 0x61417272) {
fs->last_clust = LD_DWORD(&fs->win[FSI_Nxt_Free]);
fs->free_clust = LD_DWORD(&fs->win[FSI_Free_Count]);
}
}
#endif
#endif
 
fs->fs_type = fmt; /* FAT syb-type */
fs->id = ++fsid; /* File system mount ID */
return FR_OK;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Check if the file/dir object is valid or not */
/*-----------------------------------------------------------------------*/
 
static
FRESULT validate ( /* FR_OK(0): The object is valid, !=0: Invalid */
const FATFS *fs, /* Pointer to the file system object */
WORD id /* Member id of the target object to be checked */
)
{
if (!fs || !fs->fs_type || fs->id != id)
return FR_INVALID_OBJECT;
if (disk_status(0) & STA_NOINIT)
return FR_NOT_READY;
 
return FR_OK;
}
 
 
 
 
/*--------------------------------------------------------------------------
 
Public Functions
 
--------------------------------------------------------------------------*/
 
 
/*-----------------------------------------------------------------------*/
/* Mount/Unmount a Locical Drive */
/*-----------------------------------------------------------------------*/
 
FRESULT f_mount (
BYTE drv, /* Logical drive number to be mounted/unmounted */
FATFS *fs /* Pointer to new file system object (NULL for unmount)*/
)
{
if (drv) return FR_INVALID_DRIVE;
 
if (FatFs) FatFs->fs_type = 0; /* Clear old object */
 
FatFs = fs; /* Register and clear new object */
if (fs) fs->fs_type = 0;
 
return FR_OK;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Open or Create a File */
/*-----------------------------------------------------------------------*/
 
FRESULT f_open (
FIL *fp, /* Pointer to the blank file object */
const char *path, /* Pointer to the file name */
BYTE mode /* Access mode and file open mode flags */
)
{
FRESULT res;
DIR dj;
BYTE *dir;
char fn[8+3+1];
 
 
fp->fs = NULL; /* Clear file object */
#if !_FS_READONLY
mode &= (FA_READ|FA_WRITE|FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW);
res = auto_mount(&path, (BYTE)(mode & (FA_WRITE|FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW)));
#else
mode &= FA_READ;
res = auto_mount(&path, 0);
#endif
if (res != FR_OK) return res;
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */
 
#if !_FS_READONLY
/* Create or Open a File */
if (mode & (FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW)) {
CLUST rs;
DWORD dw;
if (res != FR_OK) { /* No file, create new */
if (res != FR_NO_FILE) return res;
res = reserve_direntry(&dj, &dir);
if (res != FR_OK) return res;
memset(dir, 0, 32); /* Initialize the new entry with open name */
memcpy(&dir[DIR_Name], fn, 8+3);
dir[DIR_NTres] = fn[11];
mode |= FA_CREATE_ALWAYS;
}
else { /* Any object is already existing */
if (mode & FA_CREATE_NEW) /* Cannot create new */
return FR_EXIST;
if (!dir || (dir[DIR_Attr] & (AM_RDO|AM_DIR))) /* Cannot overwrite (R/O or DIR) */
return FR_DENIED;
if (mode & FA_CREATE_ALWAYS) { /* Resize it to zero */
#if _FAT32
rs = ((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | LD_WORD(&dir[DIR_FstClusLO]);
ST_WORD(&dir[DIR_FstClusHI], 0);
#else
rs = LD_WORD(&dir[DIR_FstClusLO]);
#endif
ST_WORD(&dir[DIR_FstClusLO], 0); /* cluster = 0 */
ST_DWORD(&dir[DIR_FileSize], 0); /* size = 0 */
dj.fs->winflag = 1;
dw = dj.fs->winsect; /* Remove the cluster chain */
if (!remove_chain(rs) || !move_window(dw))
return FR_RW_ERROR;
dj.fs->last_clust = rs - 1; /* Reuse the cluster hole */
}
}
if (mode & FA_CREATE_ALWAYS) {
dir[DIR_Attr] = 0; /* Reset attribute */
dw = get_fattime();
ST_DWORD(&dir[DIR_CrtTime], dw); /* Created time */
dj.fs->winflag = 1;
mode |= FA__WRITTEN; /* Set file changed flag */
}
}
/* Open an existing file */
else {
#endif /* !_FS_READONLY */
if (res != FR_OK) return res; /* Trace failed */
if (!dir || (dir[DIR_Attr] & AM_DIR)) /* It is a directory */
return FR_NO_FILE;
#if !_FS_READONLY
if ((mode & FA_WRITE) && (dir[DIR_Attr] & AM_RDO)) /* R/O violation */
return FR_DENIED;
}
fp->dir_sect = dj.fs->winsect; /* Pointer to the directory entry */
fp->dir_ptr = dir;
#endif
fp->flag = mode; /* File access mode */
fp->org_clust = /* File start cluster */
#if _FAT32
((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) |
#endif
LD_WORD(&dir[DIR_FstClusLO]);
fp->fsize = LD_DWORD(&dir[DIR_FileSize]); /* File size */
fp->fptr = 0; fp->csect = 255; /* File pointer */
fp->fs = dj.fs; fp->id = dj.fs->id; /* Owner file system object of the file */
 
return FR_OK;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Read File */
/*-----------------------------------------------------------------------*/
 
FRESULT f_read (
FIL *fp, /* Pointer to the file object */
void *buff, /* Pointer to data buffer */
UINT btr, /* Number of bytes to read */
UINT *br /* Pointer to number of bytes read */
)
{
FRESULT res;
DWORD sect, remain;
UINT rcnt, cc;
CLUST clust;
BYTE *rbuff = buff;
 
 
*br = 0;
res = validate(fp->fs, fp->id); /* Check validity of the object */
if (res != FR_OK) return res;
if (fp->flag & FA__ERROR) return FR_RW_ERROR; /* Check error flag */
if (!(fp->flag & FA_READ)) return FR_DENIED; /* Check access mode */
remain = fp->fsize - fp->fptr;
if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */
 
for ( ; btr; /* Repeat until all data transferred */
rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) {
if ((fp->fptr % 512U) == 0) { /* On the sector boundary? */
if (fp->csect >= fp->fs->csize) { /* On the cluster boundary? */
clust = (fp->fptr == 0) ? /* On the top of the file? */
fp->org_clust : get_cluster(fp->curr_clust);
if (clust < 2 || clust >= fp->fs->max_clust) goto fr_error;
fp->curr_clust = clust; /* Update current cluster */
fp->csect = 0; /* Reset sector address in the cluster */
}
sect = clust2sect(fp->curr_clust) + fp->csect; /* Get current sector */
cc = btr / 512U; /* When remaining bytes >= sector size, */
if (cc) { /* Read maximum contiguous sectors directly */
if (fp->csect + cc > fp->fs->csize) /* Clip at cluster boundary */
cc = fp->fs->csize - fp->csect;
if (disk_read(0, rbuff, sect, (BYTE)cc) != RES_OK)
goto fr_error;
fp->csect += (BYTE)cc; /* Next sector address in the cluster */
rcnt = 512U * cc; /* Number of bytes transferred */
continue;
}
fp->csect++; /* Next sector address in the cluster */
}
sect = clust2sect(fp->curr_clust) + fp->csect - 1; /* Get current sector */
if (!move_window(sect)) goto fr_error; /* Move sector window */
rcnt = 512U - (fp->fptr % 512U); /* Get partial sector from sector window */
if (rcnt > btr) rcnt = btr;
memcpy(rbuff, &fp->fs->win[fp->fptr % 512U], rcnt);
}
 
return FR_OK;
 
fr_error: /* Abort this file due to an unrecoverable error */
fp->flag |= FA__ERROR;
return FR_RW_ERROR;
}
 
 
 
 
#if !_FS_READONLY
/*-----------------------------------------------------------------------*/
/* Write File */
/*-----------------------------------------------------------------------*/
 
FRESULT f_write (
FIL *fp, /* Pointer to the file object */
const void *buff, /* Pointer to the data to be written */
UINT btw, /* Number of bytes to write */
UINT *bw /* Pointer to number of bytes written */
)
{
FRESULT res;
DWORD sect;
UINT wcnt, cc;
CLUST clust;
const BYTE *wbuff = buff;
 
 
*bw = 0;
res = validate(fp->fs, fp->id); /* Check validity of the object */
if (res != FR_OK) return res;
if (fp->flag & FA__ERROR) return FR_RW_ERROR; /* Check error flag */
if (!(fp->flag & FA_WRITE)) return FR_DENIED; /* Check access mode */
if (fp->fsize + btw < fp->fsize) return FR_OK; /* File size cannot reach 4GB */
 
for ( ; btw; /* Repeat until all data transferred */
wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt) {
if ((fp->fptr % 512U) == 0) { /* On the sector boundary? */
if (fp->csect >= fp->fs->csize) { /* On the cluster boundary? */
if (fp->fptr == 0) { /* On the top of the file? */
clust = fp->org_clust; /* Follow from the origin */
if (clust == 0) /* When there is no cluster chain, */
fp->org_clust = clust = create_chain(0); /* Create a new cluster chain */
} else { /* Middle or end of the file */
clust = create_chain(fp->curr_clust); /* Trace or streach cluster chain */
}
if (clust == 0) break; /* Could not allocate a new cluster (disk full) */
if (clust == 1 || clust >= fp->fs->max_clust) goto fw_error;
fp->curr_clust = clust; /* Update current cluster */
fp->csect = 0; /* Reset sector address in the cluster */
}
sect = clust2sect(fp->curr_clust) + fp->csect; /* Get current sector */
cc = btw / 512U; /* When remaining bytes >= sector size, */
if (cc) { /* Write maximum contiguous sectors directly */
if (fp->csect + cc > fp->fs->csize) /* Clip at cluster boundary */
cc = fp->fs->csize - fp->csect;
if (disk_write(0, wbuff, sect, (BYTE)cc) != RES_OK)
goto fw_error;
fp->csect += (BYTE)cc; /* Next sector address in the cluster */
wcnt = 512U * cc; /* Number of bytes transferred */
continue;
}
if (fp->fptr >= fp->fsize) { /* Flush R/W window without reading if needed */
if (!move_window(0)) goto fw_error;
fp->fs->winsect = sect;
}
fp->csect++; /* Next sector address in the cluster */
}
sect = clust2sect(fp->curr_clust) + fp->csect - 1; /* Get current sector */
if (!move_window(sect)) goto fw_error; /* Move sector window */
wcnt = 512U - (fp->fptr % 512U); /* Put partial sector into sector window */
if (wcnt > btw) wcnt = btw;
memcpy(&fp->fs->win[fp->fptr % 512U], wbuff, wcnt);
fp->fs->winflag = 1;
}
 
if (fp->fptr > fp->fsize) fp->fsize = fp->fptr; /* Update file size if needed */
fp->flag |= FA__WRITTEN; /* Set file changed flag */
return res;
 
fw_error: /* Abort this file due to an unrecoverable error */
fp->flag |= FA__ERROR;
return FR_RW_ERROR;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Synchronize the file object */
/*-----------------------------------------------------------------------*/
 
FRESULT f_sync (
FIL *fp /* Pointer to the file object */
)
{
FRESULT res;
DWORD tim;
BYTE *dir;
 
 
res = validate(fp->fs, fp->id); /* Check validity of the object */
if (res == FR_OK) {
if (fp->flag & FA__WRITTEN) { /* Has the file been written? */
/* Update the directory entry */
if (!move_window(fp->dir_sect))
return FR_RW_ERROR;
dir = fp->dir_ptr;
dir[DIR_Attr] |= AM_ARC; /* Set archive bit */
ST_DWORD(&dir[DIR_FileSize], fp->fsize); /* Update file size */
ST_WORD(&dir[DIR_FstClusLO], fp->org_clust); /* Update start cluster */
#if _FAT32
ST_WORD(&dir[DIR_FstClusHI], fp->org_clust >> 16);
#endif
tim = get_fattime(); /* Updated time */
ST_DWORD(&dir[DIR_WrtTime], tim);
fp->flag &= (BYTE)~FA__WRITTEN;
res = sync();
}
}
return res;
}
 
#endif /* !_FS_READONLY */
 
 
 
/*-----------------------------------------------------------------------*/
/* Close File */
/*-----------------------------------------------------------------------*/
 
FRESULT f_close (
FIL *fp /* Pointer to the file object to be closed */
)
{
FRESULT res;
 
 
#if !_FS_READONLY
res = f_sync(fp);
#else
res = validate(fp->fs, fp->id);
#endif
if (res == FR_OK) fp->fs = NULL;
return res;
}
 
 
 
 
#if _FS_MINIMIZE <= 2
/*-----------------------------------------------------------------------*/
/* Seek File R/W Pointer */
/*-----------------------------------------------------------------------*/
 
FRESULT f_lseek (
FIL *fp, /* Pointer to the file object */
DWORD ofs /* File pointer from top of file */
)
{
FRESULT res;
CLUST clust;
DWORD csize, ifptr;
 
 
res = validate(fp->fs, fp->id); /* Check validity of the object */
if (res != FR_OK) return res;
if (fp->flag & FA__ERROR) return FR_RW_ERROR;
if (ofs > fp->fsize /* In read-only mode, clip offset with the file size */
#if !_FS_READONLY
&& !(fp->flag & FA_WRITE)
#endif
) ofs = fp->fsize;
 
ifptr = fp->fptr;
fp->fptr = 0; fp->csect = 255;
if (ofs > 0) {
csize = (DWORD)fp->fs->csize * 512U; /* Cluster size (byte) */
if (ifptr > 0 &&
(ofs - 1) / csize >= (ifptr - 1) / csize) {/* When seek to same or following cluster, */
fp->fptr = (ifptr - 1) & ~(csize - 1); /* start from the current cluster */
ofs -= fp->fptr;
clust = fp->curr_clust;
} else { /* When seek to back cluster, */
clust = fp->org_clust; /* start from the first cluster */
#if !_FS_READONLY
if (clust == 0) { /* If no cluster chain, create a new chain */
clust = create_chain(0);
if (clust == 1) goto fk_error;
fp->org_clust = clust;
}
#endif
fp->curr_clust = clust;
}
if (clust != 0) {
while (ofs > csize) { /* Cluster following loop */
#if !_FS_READONLY
if (fp->flag & FA_WRITE) { /* Check if in write mode or not */
clust = create_chain(clust); /* Force streached if in write mode */
if (clust == 0) { /* When disk gets full, clip file size */
ofs = csize; break;
}
} else
#endif
clust = get_cluster(clust); /* Follow cluster chain if not in write mode */
if (clust < 2 || clust >= fp->fs->max_clust) goto fk_error;
fp->curr_clust = clust;
fp->fptr += csize;
ofs -= csize;
}
fp->fptr += ofs;
fp->csect = (BYTE)(ofs / 512U); /* Sector offset in the cluster */
if (ofs % 512U) fp->csect++;
}
}
 
#if !_FS_READONLY
if (fp->fptr > fp->fsize) { /* Set changed flag if the file was extended */
fp->fsize = fp->fptr;
fp->flag |= FA__WRITTEN;
}
#endif
 
return FR_OK;
 
fk_error: /* Abort this file due to an unrecoverable error */
fp->flag |= FA__ERROR;
return FR_RW_ERROR;
}
 
 
 
 
#if _FS_MINIMIZE <= 1
/*-----------------------------------------------------------------------*/
/* Create a directroy object */
/*-----------------------------------------------------------------------*/
 
FRESULT f_opendir (
DIR *dj, /* Pointer to directory object to create */
const char *path /* Pointer to the directory path */
)
{
FRESULT res;
BYTE *dir;
char fn[8+3+1];
 
 
res = auto_mount(&path, 0);
if (res == FR_OK) {
res = trace_path(dj, fn, path, &dir); /* Trace the directory path */
if (res == FR_OK) { /* Trace completed */
if (dir) { /* It is not the root dir */
if (dir[DIR_Attr] & AM_DIR) { /* The entry is a directory */
dj->clust =
#if _FAT32
((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) |
#endif
LD_WORD(&dir[DIR_FstClusLO]);
dj->sect = clust2sect(dj->clust);
dj->index = 2;
} else { /* The entry is not a directory */
res = FR_NO_FILE;
}
}
dj->id = dj->fs->id;
}
}
 
return res;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Read Directory Entry in Sequense */
/*-----------------------------------------------------------------------*/
 
FRESULT f_readdir (
DIR *dj, /* Pointer to the directory object */
FILINFO *finfo /* Pointer to file information to return */
)
{
FRESULT res;
BYTE *dir, c;
 
 
res = validate(dj->fs, dj->id); /* Check validity of the object */
if (res != FR_OK) return res;
 
finfo->fname[0] = 0;
while (dj->sect) {
if (!move_window(dj->sect))
return FR_RW_ERROR;
dir = &dj->fs->win[(dj->index & 15) * 32]; /* pointer to the directory entry */
c = dir[DIR_Name];
if (c == 0) break; /* Has it reached to end of dir? */
if (c != 0xE5 && !(dir[DIR_Attr] & AM_VOL)) /* Is it a valid entry? */
get_fileinfo(finfo, dir);
if (!next_dir_entry(dj)) dj->sect = 0; /* Next entry */
if (finfo->fname[0]) break; /* Found valid entry */
}
 
return FR_OK;
}
 
 
 
 
#if _FS_MINIMIZE == 0
/*-----------------------------------------------------------------------*/
/* Get File Status */
/*-----------------------------------------------------------------------*/
 
FRESULT f_stat (
const char *path, /* Pointer to the file path */
FILINFO *finfo /* Pointer to file information to return */
)
{
FRESULT res;
DIR dj;
BYTE *dir;
char fn[8+3+1];
 
 
res = auto_mount(&path, 0);
if (res == FR_OK) {
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */
if (res == FR_OK) { /* Trace completed */
if (dir) /* Found an object */
get_fileinfo(finfo, dir);
else /* It is root dir */
res = FR_INVALID_NAME;
}
}
 
return res;
}
 
 
 
 
#if !_FS_READONLY
/*-----------------------------------------------------------------------*/
/* Truncate File */
/*-----------------------------------------------------------------------*/
 
FRESULT f_truncate (
FIL *fp /* Pointer to the file object */
)
{
FRESULT res;
CLUST ncl;
 
 
res = validate(fp->fs, fp->id); /* Check validity of the object */
if (res != FR_OK) return res;
if (fp->flag & FA__ERROR) return FR_RW_ERROR; /* Check error flag */
if (!(fp->flag & FA_WRITE)) return FR_DENIED; /* Check access mode */
 
if (fp->fsize > fp->fptr) {
fp->fsize = fp->fptr; /* Set file size to current R/W point */
fp->flag |= FA__WRITTEN;
if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */
if (!remove_chain(fp->org_clust)) goto ft_error;
fp->org_clust = 0;
} else { /* When truncate a part of the file, remove remaining clusters */
ncl = get_cluster(fp->curr_clust);
if (ncl < 2) goto ft_error;
if (ncl < fp->fs->max_clust) {
if (!put_cluster(fp->curr_clust, (CLUST)0x0FFFFFFF)) goto ft_error;
if (!remove_chain(ncl)) goto ft_error;
}
}
}
 
return FR_OK;
 
ft_error: /* Abort this file due to an unrecoverable error */
fp->flag |= FA__ERROR;
return FR_RW_ERROR;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Get Number of Free Clusters */
/*-----------------------------------------------------------------------*/
 
FRESULT f_getfree (
const char *drv, /* Pointer to the logical drive number (root dir) */
DWORD *nclust, /* Pointer to the variable to return number of free clusters */
FATFS **fatfs /* Pointer to pointer to corresponding file system object to return */
)
{
FRESULT res;
FATFS *fs;
DWORD n, sect;
CLUST clust;
BYTE fat, f, *p;
 
 
/* Get drive number */
res = auto_mount(&drv, 0);
if (res != FR_OK) return res;
*fatfs = fs = FatFs;
 
/* If number of free cluster is valid, return it without cluster scan. */
if (fs->free_clust <= fs->max_clust - 2) {
*nclust = fs->free_clust;
return FR_OK;
}
 
/* Get number of free clusters */
fat = fs->fs_type;
n = 0;
if (fat == FS_FAT12) {
clust = 2;
do {
if ((WORD)get_cluster(clust) == 0) n++;
} while (++clust < fs->max_clust);
} else {
clust = fs->max_clust;
sect = fs->fatbase;
f = 0; p = 0;
do {
if (!f) {
if (!move_window(sect++)) return FR_RW_ERROR;
p = fs->win;
}
if (!_FAT32 || fat == FS_FAT16) {
if (LD_WORD(p) == 0) n++;
p += 2; f += 1;
} else {
if (LD_DWORD(p) == 0) n++;
p += 4; f += 2;
}
} while (--clust);
}
fs->free_clust = n;
#if _USE_FSINFO
if (fat == FS_FAT32) fs->fsi_flag = 1;
#endif
 
*nclust = n;
return FR_OK;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Delete a File or Directory */
/*-----------------------------------------------------------------------*/
 
FRESULT f_unlink (
const char *path /* Pointer to the file or directory path */
)
{
FRESULT res;
DIR dj;
BYTE *dir, *sdir;
DWORD dsect;
char fn[8+3+1];
CLUST dclust;
 
 
res = auto_mount(&path, 1);
if (res != FR_OK) return res;
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */
if (res != FR_OK) return res; /* Trace failed */
if (!dir) return FR_INVALID_NAME; /* It is the root directory */
if (dir[DIR_Attr] & AM_RDO) return FR_DENIED; /* It is a R/O object */
dsect = dj.fs->winsect;
dclust =
#if _FAT32
((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) |
#endif
LD_WORD(&dir[DIR_FstClusLO]);
if (dir[DIR_Attr] & AM_DIR) { /* It is a sub-directory */
dj.clust = dclust; /* Check if the sub-dir is empty or not */
dj.sect = clust2sect(dclust);
dj.index = 2;
do {
if (!move_window(dj.sect)) return FR_RW_ERROR;
sdir = &dj.fs->win[(dj.index & 15) * 32];
if (sdir[DIR_Name] == 0) break;
if (sdir[DIR_Name] != 0xE5 && !(sdir[DIR_Attr] & AM_VOL))
return FR_DENIED; /* The directory is not empty */
} while (next_dir_entry(&dj));
}
 
if (!move_window(dsect)) return FR_RW_ERROR; /* Mark the directory entry 'deleted' */
dir[DIR_Name] = 0xE5;
dj.fs->winflag = 1;
if (!remove_chain(dclust)) return FR_RW_ERROR; /* Remove the cluster chain */
 
return sync();
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Create a Directory */
/*-----------------------------------------------------------------------*/
 
FRESULT f_mkdir (
const char *path /* Pointer to the directory path */
)
{
FRESULT res;
DIR dj;
BYTE *dir, *fw, n;
char fn[8+3+1];
DWORD sect, dsect, tim;
CLUST dclust, pclust;
 
 
res = auto_mount(&path, 1);
if (res != FR_OK) return res;
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */
if (res == FR_OK) return FR_EXIST; /* Any file or directory is already existing */
if (res != FR_NO_FILE) return res;
 
res = reserve_direntry(&dj, &dir); /* Reserve a directory entry */
if (res != FR_OK) return res;
sect = dj.fs->winsect;
dclust = create_chain(0); /* Allocate a cluster for new directory table */
if (dclust == 1) return FR_RW_ERROR;
dsect = clust2sect(dclust);
if (!dsect) return FR_DENIED;
if (!move_window(dsect)) return FR_RW_ERROR;
 
fw = dj.fs->win;
memset(fw, 0, 512U); /* Clear the directory table */
for (n = 1; n < dj.fs->csize; n++) {
if (disk_write(0, fw, ++dsect, 1) != RES_OK)
return FR_RW_ERROR;
}
 
memset(&fw[DIR_Name], ' ', 8+3); /* Create "." entry */
fw[DIR_Name] = '.';
fw[DIR_Attr] = AM_DIR;
tim = get_fattime();
ST_DWORD(&fw[DIR_WrtTime], tim);
memcpy(&fw[32], &fw[0], 32); fw[33] = '.'; /* Create ".." entry */
pclust = dj.sclust;
#if _FAT32
ST_WORD(&fw[ DIR_FstClusHI], dclust >> 16);
if (dj.fs->fs_type == FS_FAT32 && pclust == dj.fs->dirbase) pclust = 0;
ST_WORD(&fw[32+DIR_FstClusHI], pclust >> 16);
#endif
ST_WORD(&fw[ DIR_FstClusLO], dclust);
ST_WORD(&fw[32+DIR_FstClusLO], pclust);
dj.fs->winflag = 1;
 
if (!move_window(sect)) return FR_RW_ERROR;
memset(&dir[0], 0, 32); /* Clean-up the new entry */
memcpy(&dir[DIR_Name], fn, 8+3); /* Name */
dir[DIR_NTres] = fn[11];
dir[DIR_Attr] = AM_DIR; /* Attribute */
ST_DWORD(&dir[DIR_WrtTime], tim); /* Crated time */
ST_WORD(&dir[DIR_FstClusLO], dclust); /* Table start cluster */
#if _FAT32
ST_WORD(&dir[DIR_FstClusHI], dclust >> 16);
#endif
 
return sync();
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Change File Attribute */
/*-----------------------------------------------------------------------*/
 
FRESULT f_chmod (
const char *path, /* Pointer to the file path */
BYTE value, /* Attribute bits */
BYTE mask /* Attribute mask to change */
)
{
FRESULT res;
DIR dj;
BYTE *dir;
char fn[8+3+1];
 
 
res = auto_mount(&path, 1);
if (res == FR_OK) {
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */
if (res == FR_OK) { /* Trace completed */
if (!dir) {
res = FR_INVALID_NAME; /* Root directory */
} else {
mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */
dir[DIR_Attr] = (value & mask) | (dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */
res = sync();
}
}
}
return res;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Change Timestamp */
/*-----------------------------------------------------------------------*/
 
FRESULT f_utime (
const char *path, /* Pointer to the file/directory name */
const FILINFO *finfo /* Pointer to the timestamp to be set */
)
{
FRESULT res;
DIR dj;
BYTE *dir;
char fn[8+3+1];
 
 
res = auto_mount(&path, 1);
if (res == FR_OK) {
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */
if (res == FR_OK) { /* Trace completed */
if (!dir) {
res = FR_INVALID_NAME; /* Root directory */
} else {
ST_WORD(&dir[DIR_WrtTime], finfo->ftime);
ST_WORD(&dir[DIR_WrtDate], finfo->fdate);
res = sync();
}
}
}
return res;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Rename File/Directory */
/*-----------------------------------------------------------------------*/
 
FRESULT f_rename (
const char *path_old, /* Pointer to the old name */
const char *path_new /* Pointer to the new name */
)
{
FRESULT res;
DWORD sect_old;
BYTE *dir_old, *dir_new, direntry[32-11];
DIR dj;
char fn[8+3+1];
 
 
res = auto_mount(&path_old, 1);
if (res != FR_OK) return res;
 
res = trace_path(&dj, fn, path_old, &dir_old); /* Check old object */
if (res != FR_OK) return res; /* The old object is not found */
if (!dir_old) return FR_NO_FILE;
sect_old = dj.fs->winsect; /* Save the object information */
memcpy(direntry, &dir_old[DIR_Attr], 32-11);
 
res = trace_path(&dj, fn, path_new, &dir_new); /* Check new object */
if (res == FR_OK) return FR_EXIST; /* The new object name is already existing */
if (res != FR_NO_FILE) return res; /* Is there no old name? */
res = reserve_direntry(&dj, &dir_new); /* Reserve a directory entry */
if (res != FR_OK) return res;
 
memcpy(&dir_new[DIR_Attr], direntry, 32-11); /* Create new entry */
memcpy(&dir_new[DIR_Name], fn, 8+3);
dir_new[DIR_NTres] = fn[11];
dj.fs->winflag = 1;
 
if (!move_window(sect_old)) return FR_RW_ERROR; /* Delete old entry */
dir_old[DIR_Name] = 0xE5;
 
return sync();
}
 
#endif /* !_FS_READONLY */
#endif /* _FS_MINIMIZE == 0 */
#endif /* _FS_MINIMIZE <= 1 */
#endif /* _FS_MINIMIZE <= 2 */
 
 
#if _USE_FORWARD
/*-----------------------------------------------------------------------*/
/* Forward data to the stream directly */
/*-----------------------------------------------------------------------*/
 
FRESULT f_forward (
FIL *fp, /* Pointer to the file object */
UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */
UINT btr, /* Number of bytes to forward */
UINT *br /* Pointer to number of bytes forwarded */
)
{
FRESULT res;
DWORD remain;
UINT rcnt;
CLUST clust;
 
 
*br = 0;
res = validate(fp->fs, fp->id); /* Check validity of the object */
if (res != FR_OK) return res;
if (fp->flag & FA__ERROR) return FR_RW_ERROR; /* Check error flag */
if (!(fp->flag & FA_READ)) return FR_DENIED; /* Check access mode */
remain = fp->fsize - fp->fptr;
if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */
 
for ( ; btr && (*func)(NULL, 0); /* Repeat until all data transferred */
fp->fptr += rcnt, *br += rcnt, btr -= rcnt) {
if ((fp->fptr % 512U) == 0) { /* On the sector boundary? */
if (fp->csect >= fp->fs->csize) { /* On the cluster boundary? */
clust = (fp->fptr == 0) ? /* On the top of the file? */
fp->org_clust : get_cluster(fp->curr_clust);
if (clust < 2 || clust >= fp->fs->max_clust) goto ff_error;
fp->curr_clust = clust; /* Update current cluster */
fp->csect = 0; /* Reset sector address in the cluster */
}
fp->csect++; /* Next sector address in the cluster */
}
if (!move_window(clust2sect(fp->curr_clust) + fp->csect - 1)) /* Move sector window */
goto ff_error;
rcnt = 512U - (WORD)(fp->fptr % 512U); /* Forward data from sector window */
if (rcnt > btr) rcnt = btr;
rcnt = (*func)(&fp->fs->win[(WORD)fp->fptr % 512U], rcnt);
if (rcnt == 0) goto ff_error;
}
 
return FR_OK;
 
ff_error: /* Abort this function due to an unrecoverable error */
fp->flag |= FA__ERROR;
return FR_RW_ERROR;
}
#endif /* _USE_FORWARD */
 
 
 
#if _USE_STRFUNC >= 1
/*-----------------------------------------------------------------------*/
/* Get a string from the file */
/*-----------------------------------------------------------------------*/
char* fgets (
char* buff, /* Pointer to the string buffer to read */
int len, /* Size of string buffer */
FIL* fil /* Pointer to the file object */
)
{
int i = 0;
char *p = buff;
UINT rc;
 
 
while (i < len - 1) { /* Read bytes until buffer gets filled */
f_read(fil, p, 1, &rc);
if (rc != 1) break; /* Break when no data to read */
#if _USE_STRFUNC >= 2
if (*p == '\r') continue; /* Strip '\r' */
#endif
i++;
if (*p++ == '\n') break; /* Break when reached end of line */
}
*p = 0;
return i ? buff : 0; /* When no data read (eof or error), return with error. */
}
 
 
 
#if !_FS_READONLY
#include <stdarg.h>
/*-----------------------------------------------------------------------*/
/* Put a character to the file */
/*-----------------------------------------------------------------------*/
int fputc (
int chr, /* A character to be output */
FIL* fil /* Ponter to the file object */
)
{
UINT bw;
char c;
 
 
#if _USE_STRFUNC >= 2
if (chr == '\n') fputc ('\r', fil); /* LF -> CRLF conversion */
#endif
if (!fil) { /* Special value may be used to switch the destination to any other device */
/* put_console(chr); */
return chr;
}
c = (char)chr;
f_write(fil, &c, 1, &bw); /* Write a byte to the file */
return bw ? chr : EOF; /* Return the resulut */
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Put a string to the file */
/*-----------------------------------------------------------------------*/
int fputs (
const char* str, /* Pointer to the string to be output */
FIL* fil /* Pointer to the file object */
)
{
int n;
 
 
for (n = 0; *str; str++, n++) {
if (fputc(*str, fil) == EOF) return EOF;
}
return n;
}
 
 
 
 
/*-----------------------------------------------------------------------*/
/* Put a formatted string to the file */
/*-----------------------------------------------------------------------*/
int fprintf (
FIL* fil, /* Pointer to the file object */
const char* str, /* Pointer to the format string */
... /* Optional arguments... */
)
{
va_list arp;
UCHAR c, f, r;
ULONG val;
char s[16];
int i, w, res, cc;
 
 
va_start(arp, str);
 
for (cc = res = 0; cc != EOF; res += cc) {
c = *str++;
if (c == 0) break; /* End of string */
if (c != '%') { /* Non escape cahracter */
cc = fputc(c, fil);
if (cc != EOF) cc = 1;
continue;
}
w = f = 0;
c = *str++;
if (c == '0') { /* Flag: '0' padding */
f = 1; c = *str++;
}
while (c >= '0' && c <= '9') { /* Precision */
w = w * 10 + (c - '0');
c = *str++;
}
if (c == 'l') { /* Prefix: Size is long int */
f |= 2; c = *str++;
}
if (c == 's') { /* Type is string */
cc = fputs(va_arg(arp, char*), fil);
continue;
}
if (c == 'c') { /* Type is character */
cc = fputc(va_arg(arp, char), fil);
if (cc != EOF) cc = 1;
continue;
}
r = 0;
if (c == 'd') r = 10; /* Type is signed decimal */
if (c == 'u') r = 10; /* Type is unsigned decimal */
if (c == 'X') r = 16; /* Type is unsigned hexdecimal */
if (r == 0) break; /* Unknown type */
if (f & 2) { /* Get the value */
val = (ULONG)va_arg(arp, long);
} else {
val = (c == 'd') ? (ULONG)(long)va_arg(arp, int) : (ULONG)va_arg(arp, unsigned int);
}
/* Put numeral string */
if (c == 'd') {
if (val >= 0x80000000) {
val = 0 - val;
f |= 4;
}
}
i = sizeof(s) - 1; s[i] = 0;
do {
c = (UCHAR)(val % r + '0');
if (c > '9') c += 7;
s[--i] = c;
val /= r;
} while (i && val);
if (i && (f & 4)) s[--i] = '-';
w = sizeof(s) - 1 - w;
while (i && i > w) s[--i] = (f & 1) ? '0' : ' ';
cc = fputs(&s[i], fil);
}
 
va_end(arp);
return (cc == EOF) ? cc : res;
}
 
#endif /* !_FS_READONLY */
#endif /* _USE_STRFUNC >= 1*/
/programy/C/avr/SDcard/tff.h
0,0 → 1,306
/*--------------------------------------------------------------------------/
/ Tiny-FatFs - FAT file system module include file R0.06 (C)ChaN, 2008
/---------------------------------------------------------------------------/
/ FatFs module is an experimenal project to implement FAT file system to
/ cheap microcontrollers. This is a free software and is opened for education,
/ research and development under license policy of following trems.
/
/ Copyright (C) 2008, ChaN, all right reserved.
/
/ * The FatFs module is a free software and there is no warranty.
/ * You can use, modify and/or redistribute it for personal, non-profit or
/ commercial use without any restriction under your responsibility.
/ * Redistributions of source code must retain the above copyright notice.
/
/---------------------------------------------------------------------------*/
 
#ifndef _FATFS
 
#define _MCU_ENDIAN 1
/* The _MCU_ENDIAN defines which access method is used to the FAT structure.
/ 1: Enable word access.
/ 2: Disable word access and use byte-by-byte access instead.
/ When the architectural byte order of the MCU is big-endian and/or address
/ miss-aligned access results incorrect behavior, the _MCU_ENDIAN must be set to 2.
/ If it is not the case, it can also be set to 1 for good code efficiency. */
 
#define _FS_READONLY 0
/* 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, f_getfree and internal writing codes. */
 
#define _FS_MINIMIZE 0
/* 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
/* To enable string functions, set _USE_STRFUNC to 1 or 2. */
 
#define _USE_FORWARD 0
/* To enable f_forward function, set _USE_FORWARD to 1. */
 
#define _FAT32 1
/* To enable FAT32 support in addition of FAT12/16, set _FAT32 to 1. */
 
#define _USE_FSINFO 1
/* To enable FSInfo support on FAT32 volume, set _USE_FSINFO to 1. */
 
#define _USE_SJIS 1
/* When _USE_SJIS is set to 1, Shift-JIS code transparency is enabled, otherwise
/ only US-ASCII(7bit) code can be accepted as file/directory name. */
 
#define _USE_NTFLAG 1
/* When _USE_NTFLAG is set to 1, upper/lower case of the file name is preserved.
/ Note that the files are always accessed in case insensitive. */
 
 
#include "integer.h"
 
 
/* Type definition for cluster number */
#if _FAT32
typedef DWORD CLUST;
#else
typedef WORD CLUST;
#undef _USE_FSINFO
#define _USE_FSINFO 0
#endif
 
 
/* File system object structure */
typedef struct _FATFS {
WORD id; /* File system mount ID */
WORD n_rootdir; /* Number of root directory entries */
DWORD winsect; /* Current sector appearing in the win[] */
DWORD fatbase; /* FAT start sector */
DWORD dirbase; /* Root directory start sector */
DWORD database; /* Data start sector */
CLUST sects_fat; /* Sectors per fat */
CLUST max_clust; /* Maximum cluster# + 1 */
#if !_FS_READONLY
CLUST last_clust; /* Last allocated cluster */
CLUST free_clust; /* Number of free clusters */
#if _USE_FSINFO
DWORD fsi_sector; /* fsinfo sector */
BYTE fsi_flag; /* fsinfo dirty flag (1:must be written back) */
BYTE pad1;
#endif
#endif
BYTE fs_type; /* FAT sub type */
BYTE csize; /* Number of sectors per cluster */
BYTE n_fats; /* Number of FAT copies */
BYTE winflag; /* win[] dirty flag (1:must be written back) */
BYTE win[512]; /* Disk access window for Directory/FAT/File */
} FATFS;
 
 
/* Directory object structure */
typedef struct _DIR {
WORD id; /* Owner file system mount ID */
WORD index; /* Current index */
FATFS* fs; /* Pointer to the owner file system object */
CLUST sclust; /* Start cluster */
CLUST clust; /* Current cluster */
DWORD sect; /* Current sector */
} DIR;
 
 
/* File object structure */
typedef struct _FIL {
WORD id; /* Owner file system mount ID */
BYTE flag; /* File status flags */
BYTE csect; /* Sector address in the cluster */
FATFS* fs; /* Pointer to owner file system */
DWORD fptr; /* File R/W pointer */
DWORD fsize; /* File size */
CLUST org_clust; /* File start cluster */
CLUST curr_clust; /* Current cluster */
DWORD curr_sect; /* Current sector */
#if !_FS_READONLY
DWORD dir_sect; /* Sector containing the directory entry */
BYTE* dir_ptr; /* Ponter to the directory entry in the window */
#endif
} FIL;
 
 
/* File status structure */
typedef struct _FILINFO {
DWORD fsize; /* Size */
WORD fdate; /* Date */
WORD ftime; /* Time */
BYTE fattrib; /* Attribute */
char fname[8+1+3+1]; /* Name (8.3 format) */
} FILINFO;
 
 
/* File function return code (FRESULT) */
 
typedef enum {
FR_OK = 0, /* 0 */
FR_NOT_READY, /* 1 */
FR_NO_FILE, /* 2 */
FR_NO_PATH, /* 3 */
FR_INVALID_NAME, /* 4 */
FR_INVALID_DRIVE, /* 5 */
FR_DENIED, /* 6 */
FR_EXIST, /* 7 */
FR_RW_ERROR, /* 8 */
FR_WRITE_PROTECTED, /* 9 */
FR_NOT_ENABLED, /* 10 */
FR_NO_FILESYSTEM, /* 11 */
FR_INVALID_OBJECT, /* 12 */
FR_MKFS_ABORTED /* 13 (not used) */
} FRESULT;
 
 
 
/*-----------------------------------------------------*/
/* Tiny-FatFs module application interface */
 
FRESULT f_mount (BYTE, FATFS*); /* Mount/Unmount a logical drive */
FRESULT f_open (FIL*, const char*, BYTE); /* Open or create a file */
FRESULT f_read (FIL*, void*, UINT, UINT*); /* Read data from a file */
FRESULT f_write (FIL*, const void*, UINT, UINT*); /* Write data to 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 char*); /* Open an existing directory */
FRESULT f_readdir (DIR*, FILINFO*); /* Read a directory item */
FRESULT f_stat (const char*, FILINFO*); /* Get file status */
FRESULT f_getfree (const char*, 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 char*); /* Delete an existing file or directory */
FRESULT f_mkdir (const char*); /* Create a new directory */
FRESULT f_chmod (const char*, BYTE, BYTE); /* Change file/dir attriburte */
FRESULT f_utime (const char*, const FILINFO*); /* Change file/dir timestamp */
FRESULT f_rename (const char*, const char*); /* Rename/Move a file or directory */
FRESULT f_forward (FIL*, UINT(*)(const BYTE*,UINT), UINT, UINT*); /* Forward data to the stream */
#if _USE_STRFUNC
#define feof(fp) ((fp)->fptr == (fp)->fsize)
#define EOF -1
int fputc (int, FIL*); /* Put a character to the file */
int fputs (const char*, FIL*); /* Put a string to the file */
int fprintf (FIL*, const char*, ...); /* Put a formatted string to the file */
char* fgets (char*, int, FIL*); /* Get a string from the file */
#endif
 
 
/* User defined function to give a current time to fatfs module */
 
DWORD get_fattime (void); /* 31-25: Year(0-127 +1980), 24-21: Month(1-12), 20-16: Day(1-31) */
/* 15-11: Hour(0-23), 10-5: Minute(0-59), 4-0: Second(0-29 *2) */
 
 
 
/* File access control and file status flags (FIL.flag) */
 
#define FA_READ 0x01
#define FA_OPEN_EXISTING 0x00
#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
#endif
#define FA__ERROR 0x80
 
 
/* 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 */
 
 
 
/* Offset of FAT structure members */
 
#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
 
 
 
/* Multi-byte word access macros */
 
#if _MCU_ENDIAN == 1 /* Use word access */
#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)
#elif _MCU_ENDIAN == 2 /* Use byte-by-byte access */
#define LD_WORD(ptr) (WORD)(((WORD)*(volatile BYTE*)((ptr)+1)<<8)|(WORD)*(volatile BYTE*)(ptr))
#define LD_DWORD(ptr) (DWORD)(((DWORD)*(volatile BYTE*)((ptr)+3)<<24)|((DWORD)*(volatile BYTE*)((ptr)+2)<<16)|((WORD)*(volatile BYTE*)((ptr)+1)<<8)|*(volatile BYTE*)(ptr))
#define ST_WORD(ptr,val) *(volatile BYTE*)(ptr)=(BYTE)(val); *(volatile BYTE*)((ptr)+1)=(BYTE)((WORD)(val)>>8)
#define ST_DWORD(ptr,val) *(volatile BYTE*)(ptr)=(BYTE)(val); *(volatile BYTE*)((ptr)+1)=(BYTE)((WORD)(val)>>8); *(volatile BYTE*)((ptr)+2)=(BYTE)((DWORD)(val)>>16); *(volatile BYTE*)((ptr)+3)=(BYTE)((DWORD)(val)>>24)
#else
#error Do not forget to set _MCU_ENDIAN properly!
#endif
 
 
 
#define _FATFS
#endif /* _FATFS */
/programy/C/avr/SDcard/tt.ini
0,0 → 1,0
bps=115200
/programy/C/avr/SDcard/uart.c
0,0 → 1,128
/*------------------------------------------------*/
/* UART functions */
 
 
#include <avr/io.h>
#include <avr/interrupt.h>
#include "uart.h"
 
#define SYSCLK 9216000
#define BAUD 115200
 
 
typedef struct _fifo {
uint8_t idx_w;
uint8_t idx_r;
uint8_t count;
uint8_t buff[64];
} FIFO;
 
 
static volatile
FIFO txfifo, rxfifo;
 
 
 
/* Initialize UART */
 
void uart_init()
{
rxfifo.idx_r = 0;
rxfifo.idx_w = 0;
rxfifo.count = 0;
txfifo.idx_r = 0;
txfifo.idx_w = 0;
txfifo.count = 0;
 
UBRR0L = SYSCLK/BAUD/16-1;
UCSR0B = _BV(RXEN0)|_BV(RXCIE0)|_BV(TXEN0);
}
 
 
/* Get a received character */
 
uint8_t uart_test ()
{
return rxfifo.count;
}
 
 
uint8_t uart_get ()
{
uint8_t d, i;
 
 
i = rxfifo.idx_r;
while(rxfifo.count == 0);
d = rxfifo.buff[i++];
cli();
rxfifo.count--;
sei();
if(i >= sizeof(rxfifo.buff))
i = 0;
rxfifo.idx_r = i;
 
return d;
}
 
 
/* Put a character to transmit */
 
void uart_put (uint8_t d)
{
uint8_t i;
 
 
i = txfifo.idx_w;
while(txfifo.count >= sizeof(txfifo.buff));
txfifo.buff[i++] = d;
cli();
txfifo.count++;
UCSR0B = _BV(RXEN0)|_BV(RXCIE0)|_BV(TXEN0)|_BV(UDRIE0);
sei();
if(i >= sizeof(txfifo.buff))
i = 0;
txfifo.idx_w = i;
}
 
 
/* UART RXC interrupt */
 
SIGNAL(SIG_UART0_RECV)
{
uint8_t d, n, i;
 
 
d = UDR0;
n = rxfifo.count;
if(n < sizeof(rxfifo.buff)) {
rxfifo.count = ++n;
i = rxfifo.idx_w;
rxfifo.buff[i++] = d;
if(i >= sizeof(rxfifo.buff))
i = 0;
rxfifo.idx_w = i;
}
}
 
 
/* UART UDRE interrupt */
 
SIGNAL(SIG_UART0_DATA)
{
uint8_t n, i;
 
 
n = txfifo.count;
if(n) {
txfifo.count = --n;
i = txfifo.idx_r;
UDR0 = txfifo.buff[i++];
if(i >= sizeof(txfifo.buff))
i = 0;
txfifo.idx_r = i;
}
if(n == 0)
UCSR0B = _BV(RXEN0)|_BV(RXCIE0)|_BV(TXEN0);
}
 
/programy/C/avr/SDcard/uart.h
0,0 → 1,6
#include "uart.c"
 
void uart_init(void); /* Initialize UART and Flush FIFOs */
uint8_t uart_get (void); /* Get a byte from UART Rx FIFO */
uint8_t uart_test(void); /* Check number of data in UART Rx FIFO */
void uart_put (uint8_t); /* Put a byte into UART Tx FIFO */
/programy/C/avr/SDcard/xitoa.S
0,0 → 1,415
;---------------------------------------------------------------------------;
; Extended itoa, puts, printf and atoi (C)ChaN, 2006
;
; Module size: 277/261 words (max)
;
 
#define USE_XPUTS
#define USE_XITOA
#define USE_XPRINTF
#define USE_XATOI
 
 
 
.nolist
#include <avr/io.h> // Include device specific definitions.
.list
 
#ifdef SPM_PAGESIZE // Recent devices have "lpm Rd,Z+" and "movw".
.macro _LPMI reg
lpm \reg, Z+
.endm
.macro _MOVW dh,dl, sh,sl
movw \dl, \sl
.endm
#else // Earlier devices do not have "lpm Rd,Z+" nor "movw".
.macro _LPMI reg
lpm
mov \reg, r0
adiw ZL, 1
.endm
.macro _MOVW dh,dl, sh,sl
mov \dl, \sl
mov \dh, \sh
.endm
#endif
 
 
 
;---------------------------------------------------------------------------
; Stub function to forward to user output function
;
;Prototype: void xputc (char chr // a character to be output
; );
;Size: 15/15 words
 
.section .bss
 
.global xfunc_out ; xfunc_out must be initialized before using this module.
xfunc_out: .ds.w 1
 
.section .text
 
 
.global xputc
.func xputc
xputc:
cpi r24, 10 ;LF --> CRLF
brne 1f ;
ldi r24, 13 ;
rcall 1f ;
ldi r24, 10 ;/
1: push ZH
push ZL
lds ZL, xfunc_out+0 ;Pointer to the registered output function.
lds ZH, xfunc_out+1 ;/
icall
pop ZL
pop ZH
ret
.endfunc
 
 
 
;---------------------------------------------------------------------------
; Direct ROM string output
;
;Prototype: void xputs (const prog_char *str // rom string to be output
; );
;Size: 10/7 words
 
#ifdef USE_XPUTS
.global xputs
.func xputs
xputs:
_MOVW ZH,ZL, r25,r24 ; Z = pointer to rom string
1: _LPMI r24
cpi r24, 0
breq 2f
rcall xputc
rjmp 1b
2: ret
.endfunc
#endif
 
 
;---------------------------------------------------------------------------
; Extended direct numeral string output (32bit version)
;
;Prototype: void xitoa (long value, // value to be output
; char radix, // radix
; char width); // minimum width
;Size: 59/59 words
;
 
#ifdef USE_XITOA
.global xitoa
.func xitoa
xitoa:
;r25:r22 = value, r20 = base, r18 = digits
clr r31 ;r31 = stack level
ldi r30, ' ' ;r30 = sign
ldi r19, ' ' ;r19 = filler
sbrs r20, 7 ;When base indicates signd format and the value
rjmp 0f ;is minus, add a '-'.
neg r20 ;
sbrs r25, 7 ;
rjmp 0f ;
ldi r30, '-' ;
com r22 ;
com r23 ;
com r24 ;
com r25 ;
adc r22, r1 ;
adc r23, r1 ;
adc r24, r1 ;
adc r25, r1 ;/
0: sbrs r18, 7 ;When digits indicates zero filled,
rjmp 1f ;filler is '0'.
neg r18 ;
ldi r19, '0' ;/
;----- string conversion loop
1: ldi r21, 32 ;r26 = r25:r22 % r20
clr r26 ;r25:r22 /= r20
2: lsl r22 ;
rol r23 ;
rol r24 ;
rol r25 ;
rol r26 ;
cp r26, r20 ;
brcs 3f ;
sub r26, r20 ;
inc r22 ;
3: dec r21 ;
brne 2b ;/
cpi r26, 10 ;r26 is a numeral digit '0'-'F'
brcs 4f ;
subi r26, -7 ;
4: subi r26, -'0' ;/
push r26 ;Stack it
inc r31 ;/
cp r22, r1 ;Repeat until r25:r22 gets zero
cpc r23, r1 ;
cpc r24, r1 ;
cpc r25, r1 ;
brne 1b ;/
 
cpi r30, '-' ;Minus sign if needed
brne 5f ;
push r30 ;
inc r31 ;/
5: cp r31, r18 ;Filler
brcc 6f ;
push r19 ;
inc r31 ;
rjmp 5b ;/
 
6: pop r24 ;Flush stacked digits and exit
rcall xputc ;
dec r31 ;
brne 6b ;/
 
ret
.endfunc
#endif
 
 
 
;---------------------------------------------------------------------------;
; Formatted string output (16/32bit version)
;
;Prototype:
; void xprintf (const prog_char *format, ...);
;Size: 104/94 words
;
 
#ifdef USE_XPRINTF
.global xprintf
.func xprintf
xprintf:
push YH
push YL
in YL, _SFR_IO_ADDR(SPL)
#ifdef SPH
in YH, _SFR_IO_ADDR(SPH)
#else
clr YH
#endif
#if FLASHEND > 0x1FFFF
adiw YL, 6 ;Y = pointer to arguments
#else
adiw YL, 5 ;Y = pointer to arguments
#endif
ld ZL, Y+ ;Z = pointer to format string
ld ZH, Y+ ;/
 
0: _LPMI r24 ;Get a format char
cpi r24, 0 ;End of format string?
breq 90f ;/
cpi r24, '%' ;Is format?
breq 20f ;/
1: rcall xputc ;Put a normal character
rjmp 0b ;/
90: pop YL
pop YH
ret
 
20: ldi r18, 0 ;r18: digits
clt ;T: filler
_LPMI r21 ;Get flags
cpi r21, '%' ;Is a %?
breq 1b ;/
cpi r21, '0' ;Zero filled?
brne 23f ;
set ;/
22: _LPMI r21 ;Get width
23: cpi r21, '9'+1 ;
brcc 24f ;
subi r21, '0' ;
brcs 90b ;
lsl r18 ;
mov r0, r18 ;
lsl r18 ;
lsl r18 ;
add r18, r0 ;
add r18, r21 ;
rjmp 22b ;/
 
24: brtc 25f ;get value (low word)
neg r18 ;
25: ld r24, Y+ ;
ld r25, Y+ ;/
cpi r21, 'c' ;Is type character?
breq 1b ;/
cpi r21, 's' ;Is type RAM string?
breq 50f ;/
cpi r21, 'S' ;Is type ROM string?
breq 60f ;/
_MOVW r23,r22,r25,r24 ;r25:r22 = value
clr r24 ;
clr r25 ;
clt ;/
cpi r21, 'l' ;Is long int?
brne 26f ;
ld r24, Y+ ;get value (high word)
ld r25, Y+ ;
set ;
_LPMI r21 ;/
26: cpi r21, 'd' ;Is type signed decimal?
brne 27f ;/
ldi r20, -10 ;
brts 40f ;
sbrs r23, 7 ;
rjmp 40f ;
ldi r24, -1 ;
ldi r25, -1 ;
rjmp 40f ;/
27: cpi r21, 'u' ;Is type unsigned decimal?
ldi r20, 10 ;
breq 40f ;/
cpi r21, 'X' ;Is type hexdecimal?
ldi r20, 16 ;
breq 40f ;/
cpi r21, 'b' ;Is type binary?
ldi r20, 2 ;
breq 40f ;/
rjmp 90b ;abort
40: push ZH ;Output the value
push ZL ;
rcall xitoa ;
42: pop ZL ;
pop ZH ;
rjmp 0b ;/
 
50: push ZH ;Put a string on the RAM
push ZL
_MOVW ZH,ZL, r25,r24
51: ld r24, Z+
cpi r24, 0
breq 42b
rcall xputc
rjmp 51b
 
60: push ZH ;Put a string on the ROM
push ZL
rcall xputs
rjmp 42b
 
.endfunc
#endif
 
 
 
;---------------------------------------------------------------------------
; Extended numeral string input
;
;Prototype:
; char xatoi ( /* 1: Successful, 0: Failed */
; const char **str, /* pointer to pointer to source string */
; long *res /* result */
; );
;Size: 94/91 words
;
 
#ifdef USE_XATOI
.global xatoi
.func xatoi
xatoi:
_MOVW r1, r0, r23, r22
_MOVW XH, XL, r25, r24
ld ZL, X+
ld ZH, X+
clr r18 ;r21:r18 = 0;
clr r19 ;
clr r20 ;
clr r21 ;/
clt ;T = 0;
 
ldi r25, 10 ;r25 = 10;
rjmp 41f ;/
40: adiw ZL, 1 ;Z++;
41: ld r22, Z ;r22 = *Z;
cpi r22, ' ' ;if(r22 == ' ') continue
breq 40b ;/
brcs 70f ;if(r22 < ' ') error;
cpi r22, '-' ;if(r22 == '-') {
brne 42f ; T = 1;
set ; continue;
rjmp 40b ;}
42: cpi r22, '9'+1 ;if(r22 > '9') error;
brcc 70f ;/
cpi r22, '0' ;if(r22 < '0') error;
brcs 70f ;/
brne 51f ;if(r22 > '0') cv_start;
ldi r25, 8 ;r25 = 8;
adiw ZL, 1 ;r22 = *(++Z);
ld r22, Z ;/
cpi r22, ' '+1 ;if(r22 <= ' ') exit;
brcs 80f ;/
cpi r22, 'b' ;if(r22 == 'b') {
brne 43f ; r25 = 2;
ldi r25, 2 ; cv_start;
rjmp 50f ;}
43: cpi r22, 'x' ;if(r22 != 'x') error;
brne 51f ;/
ldi r25, 16 ;r25 = 16;
 
50: adiw ZL, 1 ;Z++;
ld r22, Z ;r22 = *Z;
51: cpi r22, ' '+1 ;if(r22 <= ' ') break;
brcs 80f ;/
cpi r22, 'a' ;if(r22 >= 'a') r22 =- 0x20;
brcs 52f ;
subi r22, 0x20 ;/
52: subi r22, '0' ;if((r22 -= '0') < 0) error;
brcs 70f ;/
cpi r22, 10 ;if(r22 >= 10) {
brcs 53f ; r22 -= 7;
subi r22, 7 ; if(r22 < 10)
cpi r22, 10 ;
brcs 70f ;}
53: cp r22, r25 ;if(r22 >= r25) error;
brcc 70f ;/
60: ldi r24, 33 ;r21:r18 *= r25;
sub r23, r23 ;
61: brcc 62f ;
add r23, r25 ;
62: lsr r23 ;
ror r21 ;
ror r20 ;
ror r19 ;
ror r18 ;
dec r24 ;
brne 61b ;/
add r18, r22 ;r21:r18 += r22;
adc r19, r24 ;
adc r20, r24 ;
adc r21, r24 ;/
rjmp 50b ;repeat
 
70: ldi r24, 0
rjmp 81f
80: ldi r24, 1
81: brtc 82f
clr r22
com r18
com r19
com r20
com r21
adc r18, r22
adc r19, r22
adc r20, r22
adc r21, r22
82: st -X, ZH
st -X, ZL
_MOVW XH, XL, r1, r0
st X+, r18
st X+, r19
st X+, r20
st X+, r21
clr r1
ret
.endfunc
#endif
 
 
/programy/C/avr/SDcard/xitoa.h
0,0 → 1,97
/*---------------------------------------------------------------------------
Extended itoa, puts and printf (C)ChaN, 2006
 
-----------------------------------------------------------------------------*/
 
#ifndef XITOA
#define XITOA
 
#include <avr/pgmspace.h>
#include "xitoa.S"
 
extern void (*xfunc_out)(char);
 
/* This is a pointer to user defined output function. It must be initialized
before using this modle.
*/
 
void xputc(char chr);
 
/* This is a stub function to forward outputs to user defined output function.
All outputs from this module are output via this function.
*/
 
 
/*-----------------------------------------------------------------------------*/
void xputs(const prog_char *string);
 
/* The string placed in the ROM is forwarded to xputc() directly.
*/
 
 
/*-----------------------------------------------------------------------------*/
void xitoa(long value, char radix, char width);
 
/* Extended itoa().
 
value radix width output
100 10 6 " 100"
100 10 -6 "000100"
100 10 0 "100"
4294967295 10 0 "4294967295"
4294967295 -10 0 "-1"
655360 16 -8 "000A0000"
1024 16 0 "400"
0x55 2 -8 "01010101"
*/
 
 
/*-----------------------------------------------------------------------------*/
void xprintf(const prog_char *format, ...);
 
/* Format string is placed in the ROM. The format flags is similar to printf().
 
%[flag][width][size]type
 
flag
A '0' means filled with '0' when output is shorter than width.
' ' is used in default. This is effective only numeral type.
width
Minimum width in decimal number. This is effective only numeral type.
Default width is zero.
size
A 'l' means the argument is long(32bit). Default is short(16bit).
This is effective only numeral type.
type
'c' : Character, argument is the value
's' : String placed on the RAM, argument is the pointer
'S' : String placed on the ROM, argument is the pointer
'd' : Signed decimal, argument is the value
'u' : Unsigned decimal, argument is the value
'X' : Hex decimal, argument is the value
'b' : Binary, argument is the value
'%' : '%'
 
*/
 
 
/*-----------------------------------------------------------------------------*/
char xatoi(char **str, long *ret);
 
/* Get value of the numeral string.
 
str
Pointer to pointer to source string
 
"0b11001010" binary
"0377" octal
"0xff800" hexdecimal
"1250000" decimal
"-25000" decimal
 
ret
Pointer to return value
*/
 
#endif /* XITOA */
 
/programy/C/avr/akcelerometr/.hfuse
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/programy/C/avr/akcelerometr/.lfuse
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/programy/C/avr/akcelerometr/.lock
0,0 → 1,0
?
/programy/C/avr/akcelerometr/Makefile
0,0 → 1,51
 
NAME := gpsrl
HEX := $(NAME).hex
OUT := $(NAME).out
MAP := $(NAME).map
SOURCES := $(wildcard *.c)
HEADERS := $(wildcard *.h)
OBJECTS := $(patsubst %.c,%.o,$(SOURCES))
 
MCU := atmega8
MCU_AVRDUDE := m8
 
CC := avr-gcc
OBJCOPY := avr-objcopy
SIZE := avr-size -A
DOXYGEN := doxygen
 
CFLAGS := -Wall -pedantic -mmcu=$(MCU) -std=c99 -g -Os
 
all: $(HEX)
 
clean:
rm -f $(HEX) $(OUT) $(MAP) $(OBJECTS)
rm -rf doc/html
 
flash: $(HEX)
avrdude -y -p $(MCU_AVRDUDE) -P /dev/ttyUSB0 -c stk500v2 -U flash:w:$(HEX)
 
$(HEX): $(OUT)
$(OBJCOPY) -R .eeprom -O ihex $< $@
 
$(OUT): $(OBJECTS)
$(CC) $(CFLAGS) -o $@ -Wl,-Map,$(MAP) $^
@echo
@$(SIZE) $@
@echo
 
%.o: %.c $(HEADERS)
$(CC) $(CFLAGS) -c -o $@ $<
 
%.pp: %.c
$(CC) $(CFLAGS) -E -o $@ $<
 
%.ppo: %.c
$(CC) $(CFLAGS) -E $<
 
doc: $(HEADERS) $(SOURCES) Doxyfile
$(DOXYGEN) Doxyfile
 
.PHONY: all clean flash doc
 
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/akcelerometr/a2d.c
0,0 → 1,115
/*! \file a2d.c \brief Analog-to-Digital converter function library. */
//*****************************************************************************
//
// File Name : 'a2d.c'
// Title : Analog-to-digital converter functions
// Author : Pascal Stang - Copyright (C) 2002
// Created : 2002-04-08
// Revised : 2002-09-30
// Version : 1.1
// Target MCU : Atmel AVR series
// Editor Tabs : 4
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
#include <avr/io.h>
#include <avr/interrupt.h>
 
#include "global.h"
#include "a2d.h"
 
// global variables
 
//! Software flag used to indicate when
/// the a2d conversion is complete.
volatile unsigned char a2dCompleteFlag;
 
// functions
 
// initialize a2d converter
void a2dInit(void)
{
sbi(ADCSR, ADEN); // enable ADC (turn on ADC power)
cbi(ADCSR, ADFR); // default to single sample convert mode
a2dSetPrescaler(ADC_PRESCALE); // set default prescaler
a2dSetReference(ADC_REFERENCE); // set default reference
cbi(ADMUX, ADLAR); // set to right-adjusted result
 
sbi(ADCSR, ADIE); // enable ADC interrupts
 
a2dCompleteFlag = FALSE; // clear conversion complete flag
sei(); // turn on interrupts (if not already on)
}
 
// turn off a2d converter
void a2dOff(void)
{
cbi(ADCSR, ADIE); // disable ADC interrupts
cbi(ADCSR, ADEN); // disable ADC (turn off ADC power)
}
 
// configure A2D converter clock division (prescaling)
void a2dSetPrescaler(unsigned char prescale)
{
outb(ADCSR, ((inb(ADCSR) & ~ADC_PRESCALE_MASK) | prescale));
}
 
// configure A2D converter voltage reference
void a2dSetReference(unsigned char ref)
{
outb(ADMUX, ((inb(ADMUX) & ~ADC_REFERENCE_MASK) | (ref<<6)));
}
 
// sets the a2d input channel
void a2dSetChannel(unsigned char ch)
{
outb(ADMUX, (inb(ADMUX) & ~ADC_MUX_MASK) | (ch & ADC_MUX_MASK)); // set channel
}
 
// start a conversion on the current a2d input channel
void a2dStartConvert(void)
{
sbi(ADCSR, ADIF); // clear hardware "conversion complete" flag
sbi(ADCSR, ADSC); // start conversion
}
 
// return TRUE if conversion is complete
u08 a2dIsComplete(void)
{
return bit_is_set(ADCSR, ADSC);
}
 
// Perform a 10-bit conversion
// starts conversion, waits until conversion is done, and returns result
unsigned short a2dConvert10bit(unsigned char ch)
{
a2dCompleteFlag = FALSE; // clear conversion complete flag
outb(ADMUX, (inb(ADMUX) & ~ADC_MUX_MASK) | (ch & ADC_MUX_MASK)); // set channel
sbi(ADCSR, ADIF); // clear hardware "conversion complete" flag
sbi(ADCSR, ADSC); // start conversion
//while(!a2dCompleteFlag); // wait until conversion complete
//while( bit_is_clear(ADCSR, ADIF) ); // wait until conversion complete
while( bit_is_set(ADCSR, ADSC) ); // wait until conversion complete
 
// CAUTION: MUST READ ADCL BEFORE ADCH!!!
return (inb(ADCL) | (inb(ADCH)<<8)); // read ADC (full 10 bits);
}
 
// Perform a 8-bit conversion.
// starts conversion, waits until conversion is done, and returns result
unsigned char a2dConvert8bit(unsigned char ch)
{
// do 10-bit conversion and return highest 8 bits
return a2dConvert10bit(ch)>>2; // return ADC MSB byte
}
 
//! Interrupt handler for ADC complete interrupt.
SIGNAL(SIG_ADC)
{
// set the a2d conversion flag to indicate "complete"
a2dCompleteFlag = TRUE;
}
 
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/akcelerometr/a2d.h
0,0 → 1,151
/*! \file a2d.h \brief Analog-to-Digital converter function library. */
//*****************************************************************************
//
// File Name : 'a2d.h'
// Title : Analog-to-digital converter functions
// Author : Pascal Stang - Copyright (C) 2002
// Created : 4/08/2002
// Revised : 4/30/2002
// Version : 1.1
// Target MCU : Atmel AVR series
// Editor Tabs : 4
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
/// \ingroup driver_avr
/// \defgroup a2d A/D Converter Function Library (a2d.c)
/// \code #include "a2d.h" \endcode
/// \par Overview
/// This library provides an easy interface to the analog-to-digital
/// converter available on many AVR processors. Updated to support
/// the ATmega128.
//
//****************************************************************************
//@{
 
#ifndef A2D_H
#define A2D_H
 
// defines
 
// A2D clock prescaler select
// *selects how much the CPU clock frequency is divided
// to create the A2D clock frequency
// *lower division ratios make conversion go faster
// *higher division ratios make conversions more accurate
#define ADC_PRESCALE_DIV2 0x00 ///< 0x01,0x00 -> CPU clk/2
#define ADC_PRESCALE_DIV4 0x02 ///< 0x02 -> CPU clk/4
#define ADC_PRESCALE_DIV8 0x03 ///< 0x03 -> CPU clk/8
#define ADC_PRESCALE_DIV16 0x04 ///< 0x04 -> CPU clk/16
#define ADC_PRESCALE_DIV32 0x05 ///< 0x05 -> CPU clk/32
#define ADC_PRESCALE_DIV64 0x06 ///< 0x06 -> CPU clk/64
#define ADC_PRESCALE_DIV128 0x07 ///< 0x07 -> CPU clk/128
// default value
#define ADC_PRESCALE ADC_PRESCALE_DIV64
// do not change the mask value
#define ADC_PRESCALE_MASK 0x07
 
// A2D voltage reference select
// *this determines what is used as the
// full-scale voltage point for A2D conversions
#define ADC_REFERENCE_AREF 0x00 ///< 0x00 -> AREF pin, internal VREF turned off
#define ADC_REFERENCE_AVCC 0x01 ///< 0x01 -> AVCC pin, internal VREF turned off
#define ADC_REFERENCE_RSVD 0x02 ///< 0x02 -> Reserved
#define ADC_REFERENCE_256V 0x03 ///< 0x03 -> Internal 2.56V VREF
// default value
#define ADC_REFERENCE ADC_REFERENCE_AVCC
// do not change the mask value
#define ADC_REFERENCE_MASK 0xC0
 
// bit mask for A2D channel multiplexer
#define ADC_MUX_MASK 0x1F
 
// channel defines (for reference and use in code)
// these channels supported by all AVRs with A2D
#define ADC_CH_ADC0 0x00
#define ADC_CH_ADC1 0x01
#define ADC_CH_ADC2 0x02
#define ADC_CH_ADC3 0x03
#define ADC_CH_ADC4 0x04
#define ADC_CH_ADC5 0x05
#define ADC_CH_ADC6 0x06
#define ADC_CH_ADC7 0x07
#define ADC_CH_122V 0x1E ///< 1.22V voltage reference
#define ADC_CH_AGND 0x1F ///< AGND
// these channels supported only in ATmega128
// differential with gain
#define ADC_CH_0_0_DIFF10X 0x08
#define ADC_CH_1_0_DIFF10X 0x09
#define ADC_CH_0_0_DIFF200X 0x0A
#define ADC_CH_1_0_DIFF200X 0x0B
#define ADC_CH_2_2_DIFF10X 0x0C
#define ADC_CH_3_2_DIFF10X 0x0D
#define ADC_CH_2_2_DIFF200X 0x0E
#define ADC_CH_3_2_DIFF200X 0x0F
// differential
#define ADC_CH_0_1_DIFF1X 0x10
#define ADC_CH_1_1_DIFF1X 0x11
#define ADC_CH_2_1_DIFF1X 0x12
#define ADC_CH_3_1_DIFF1X 0x13
#define ADC_CH_4_1_DIFF1X 0x14
#define ADC_CH_5_1_DIFF1X 0x15
#define ADC_CH_6_1_DIFF1X 0x16
#define ADC_CH_7_1_DIFF1X 0x17
 
#define ADC_CH_0_2_DIFF1X 0x18
#define ADC_CH_1_2_DIFF1X 0x19
#define ADC_CH_2_2_DIFF1X 0x1A
#define ADC_CH_3_2_DIFF1X 0x1B
#define ADC_CH_4_2_DIFF1X 0x1C
#define ADC_CH_5_2_DIFF1X 0x1D
 
// compatibility for new Mega processors
// ADCSR hack apparently no longer necessary in new AVR-GCC
#ifdef ADCSRA
#ifndef ADCSR
#define ADCSR ADCSRA
#endif
#endif
#ifdef ADATE
#define ADFR ADATE
#endif
 
// function prototypes
 
//! Initializes the A/D converter.
/// Turns ADC on and prepares it for use.
void a2dInit(void);
 
//! Turn off A/D converter
void a2dOff(void);
 
//! Sets the division ratio of the A/D converter clock.
/// This function is automatically called from a2dInit()
/// with a default value.
void a2dSetPrescaler(unsigned char prescale);
 
//! Configures which voltage reference the A/D converter uses.
/// This function is automatically called from a2dInit()
/// with a default value.
void a2dSetReference(unsigned char ref);
 
//! sets the a2d input channel
void a2dSetChannel(unsigned char ch);
 
//! start a conversion on the current a2d input channel
void a2dStartConvert(void);
 
//! return TRUE if conversion is complete
u08 a2dIsComplete(void);
 
//! Starts a conversion on A/D channel# ch,
/// returns the 10-bit value of the conversion when it is finished.
unsigned short a2dConvert10bit(unsigned char ch);
 
//! Starts a conversion on A/D channel# ch,
/// returns the 8-bit value of the conversion when it is finished.
unsigned char a2dConvert8bit(unsigned char ch);
 
#endif
//@}
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/akcelerometr/a2dtest.c
0,0 → 1,86
//*****************************************************************************
// File Name : a2dtest.c
//
// Title : example usage of some avr library functions
// Revision : 1.0
// Notes :
// Target MCU : Atmel AVR series
// Editor Tabs : 4
//
// Revision History:
// When Who Description of change
// ----------- ----------- -----------------------
// 20-Oct-2002 pstang Created the program
//*****************************************************************************
//----- Include Files ---------------------------------------------------------
#include <avr/io.h> // include I/O definitions (port names, pin names, etc)
#include <avr/interrupt.h> // include interrupt support
#include <math.h>
 
#include "global.h" // include our global settings
#include "uart.h" // include uart function library
#include "rprintf.h" // include printf function library
#include "timer.h" // include timer function library (timing, PWM, etc)
#include "a2d.h" // include A/D converter function library
 
//----- Begin Code ------------------------------------------------------------
#define BUFLEN 32
 
int main(void)
{
u08 i=0;
s16 x=0,y=0;
double fi;
s16 fia;
u16 fib;
 
// initialize our libraries
// initialize the UART (serial port)
uartInit();
uartSetBaudRate(9600);
// make all rprintf statements use uart for output
rprintfInit(uartSendByte);
// initialize the timer system
timerInit();
// turn on and initialize A/D converter
a2dInit();
// configure a2d port (PORTA) as input
// so we can receive analog signals
DDRC = 0x00;
// make sure pull-up resistors are turned off
PORTC = 0x00;
 
// set the a2d prescaler (clock division ratio)
// - a lower prescale setting will make the a2d converter go faster
// - a higher setting will make it go slower but the measurements
// will be more accurate
// - other allowed prescale values can be found in a2d.h
a2dSetPrescaler(ADC_PRESCALE_DIV128);
 
// set the a2d reference
// - the reference is the voltage against which a2d measurements are made
// - other allowed reference values can be found in a2d.h
a2dSetReference(ADC_REFERENCE_AREF);
 
// use a2dConvert8bit(channel#) to get an 8bit a2d reading
// use a2dConvert10bit(channel#) to get a 10bit a2d reading
 
while(1)
{
for(i=0; i<BUFLEN; i++)
{
x += a2dConvert10bit(0);
y += a2dConvert10bit(1);
}
x = x/BUFLEN - 512;
y = y/BUFLEN - 512;
 
fi = atan2(y,x) * 180.0 / PI;
fia = floor(fi);
fib = floor((fi - fia));
rprintf("X:%d Y:%d fi:%d.%d \r\n", x, y, fia, fib);
}
return 0;
}
/programy/C/avr/akcelerometr/avrlibdefs.h
0,0 → 1,83
/*! \file avrlibdefs.h \brief AVRlib global defines and macros. */
//*****************************************************************************
//
// File Name : 'avrlibdefs.h'
// Title : AVRlib global defines and macros include file
// Author : Pascal Stang
// Created : 7/12/2001
// Revised : 9/30/2002
// Version : 1.1
// Target MCU : Atmel AVR series
// Editor Tabs : 4
//
// Description : This include file is designed to contain items useful to all
// code files and projects, regardless of specific implementation.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
 
#ifndef AVRLIBDEFS_H
#define AVRLIBDEFS_H
 
// Code compatibility to new AVR-libc
// outb(), inb(), inw(), outw(), BV(), sbi(), cbi(), sei(), cli()
#ifndef outb
#define outb(addr, data) addr = (data)
#endif
#ifndef inb
#define inb(addr) (addr)
#endif
#ifndef outw
#define outw(addr, data) addr = (data)
#endif
#ifndef inw
#define inw(addr) (addr)
#endif
#ifndef BV
#define BV(bit) (1<<(bit))
#endif
#ifndef cbi
#define cbi(reg,bit) reg &= ~(BV(bit))
#endif
#ifndef sbi
#define sbi(reg,bit) reg |= (BV(bit))
#endif
#ifndef cli
#define cli() __asm__ __volatile__ ("cli" ::)
#endif
#ifndef sei
#define sei() __asm__ __volatile__ ("sei" ::)
#endif
 
// support for individual port pin naming in the mega128
// see port128.h for details
#ifdef __AVR_ATmega128__
// not currently necessary due to inclusion
// of these defines in newest AVR-GCC
// do a quick test to see if include is needed
#ifndef PD0
#include "port128.h"
#endif
#endif
 
// use this for packed structures
// (this is seldom necessary on an 8-bit architecture like AVR,
// but can assist in code portability to AVR)
#define GNUC_PACKED __attribute__((packed))
 
// port address helpers
#define DDR(x) ((x)-1) // address of data direction register of port x
#define PIN(x) ((x)-2) // address of input register of port x
 
// MIN/MAX/ABS macros
#define MIN(a,b) ((a<b)?(a):(b))
#define MAX(a,b) ((a>b)?(a):(b))
#define ABS(x) ((x>0)?(x):(-x))
 
// constants
#define PI 3.14159265359
 
#endif
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/akcelerometr/avrlibtypes.h
0,0 → 1,84
/*! \file avrlibtypes.h \brief AVRlib global types and typedefines. */
//*****************************************************************************
//
// File Name : 'avrlibtypes.h'
// Title : AVRlib global types and typedefines include file
// Author : Pascal Stang
// Created : 7/12/2001
// Revised : 9/30/2002
// Version : 1.0
// Target MCU : Atmel AVR series
// Editor Tabs : 4
//
// Description : Type-defines required and used by AVRlib. Most types are also
// generally useful.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
 
#ifndef AVRLIBTYPES_H
#define AVRLIBTYPES_H
 
#ifndef WIN32
// true/false defines
#define FALSE 0
#define TRUE -1
#endif
 
// datatype definitions macros
typedef unsigned char u08;
typedef signed char s08;
typedef unsigned short u16;
typedef signed short s16;
typedef unsigned long u32;
typedef signed long s32;
typedef unsigned long long u64;
typedef signed long long s64;
 
/* use inttypes.h instead
// C99 standard integer type definitions
typedef unsigned char uint8_t;
typedef signed char int8_t;
typedef unsigned short uint16_t;
typedef signed short int16_t;
typedef unsigned long uint32_t;
typedef signed long int32_t;
typedef unsigned long uint64_t;
typedef signed long int64_t;
*/
// maximum value that can be held
// by unsigned data types (8,16,32bits)
#define MAX_U08 255
#define MAX_U16 65535
#define MAX_U32 4294967295
 
// maximum values that can be held
// by signed data types (8,16,32bits)
#define MIN_S08 -128
#define MAX_S08 127
#define MIN_S16 -32768
#define MAX_S16 32767
#define MIN_S32 -2147483648
#define MAX_S32 2147483647
 
#ifndef WIN32
// more type redefinitions
typedef unsigned char BOOL;
typedef unsigned char BYTE;
typedef unsigned int WORD;
typedef unsigned long DWORD;
 
typedef unsigned char UCHAR;
typedef unsigned int UINT;
typedef unsigned short USHORT;
typedef unsigned long ULONG;
 
typedef char CHAR;
typedef int INT;
typedef long LONG;
#endif
 
#endif
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/akcelerometr/buffer.c
0,0 → 1,149
/*! \file buffer.c \brief Multipurpose byte buffer structure and methods. */
//*****************************************************************************
//
// File Name : 'buffer.c'
// Title : Multipurpose byte buffer structure and methods
// Author : Pascal Stang - Copyright (C) 2001-2002
// Created : 9/23/2001
// Revised : 9/23/2001
// Version : 1.0
// Target MCU : any
// Editor Tabs : 4
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
#include "buffer.h"
#include "global.h"
#include "avr/io.h"
 
#ifndef CRITICAL_SECTION_START
#define CRITICAL_SECTION_START unsigned char _sreg = SREG; cli()
#define CRITICAL_SECTION_END SREG = _sreg
#endif
 
// global variables
 
// initialization
 
void bufferInit(cBuffer* buffer, unsigned char *start, unsigned short size)
{
// begin critical section
CRITICAL_SECTION_START;
// set start pointer of the buffer
buffer->dataptr = start;
buffer->size = size;
// initialize index and length
buffer->dataindex = 0;
buffer->datalength = 0;
// end critical section
CRITICAL_SECTION_END;
}
 
// access routines
unsigned char bufferGetFromFront(cBuffer* buffer)
{
unsigned char data = 0;
// begin critical section
CRITICAL_SECTION_START;
// check to see if there's data in the buffer
if(buffer->datalength)
{
// get the first character from buffer
data = buffer->dataptr[buffer->dataindex];
// move index down and decrement length
buffer->dataindex++;
if(buffer->dataindex >= buffer->size)
{
buffer->dataindex -= buffer->size;
}
buffer->datalength--;
}
// end critical section
CRITICAL_SECTION_END;
// return
return data;
}
 
void bufferDumpFromFront(cBuffer* buffer, unsigned short numbytes)
{
// begin critical section
CRITICAL_SECTION_START;
// dump numbytes from the front of the buffer
// are we dumping less than the entire buffer?
if(numbytes < buffer->datalength)
{
// move index down by numbytes and decrement length by numbytes
buffer->dataindex += numbytes;
if(buffer->dataindex >= buffer->size)
{
buffer->dataindex -= buffer->size;
}
buffer->datalength -= numbytes;
}
else
{
// flush the whole buffer
buffer->datalength = 0;
}
// end critical section
CRITICAL_SECTION_END;
}
 
unsigned char bufferGetAtIndex(cBuffer* buffer, unsigned short index)
{
// begin critical section
CRITICAL_SECTION_START;
// return character at index in buffer
unsigned char data = buffer->dataptr[(buffer->dataindex+index)%(buffer->size)];
// end critical section
CRITICAL_SECTION_END;
return data;
}
 
unsigned char bufferAddToEnd(cBuffer* buffer, unsigned char data)
{
// begin critical section
CRITICAL_SECTION_START;
// make sure the buffer has room
if(buffer->datalength < buffer->size)
{
// save data byte at end of buffer
buffer->dataptr[(buffer->dataindex + buffer->datalength) % buffer->size] = data;
// increment the length
buffer->datalength++;
// end critical section
CRITICAL_SECTION_END;
// return success
return -1;
}
// end critical section
CRITICAL_SECTION_END;
// return failure
return 0;
}
 
unsigned short bufferIsNotFull(cBuffer* buffer)
{
// begin critical section
CRITICAL_SECTION_START;
// check to see if the buffer has room
// return true if there is room
unsigned short bytesleft = (buffer->size - buffer->datalength);
// end critical section
CRITICAL_SECTION_END;
return bytesleft;
}
 
void bufferFlush(cBuffer* buffer)
{
// begin critical section
CRITICAL_SECTION_START;
// flush contents of the buffer
buffer->datalength = 0;
// end critical section
CRITICAL_SECTION_END;
}
 
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/akcelerometr/buffer.h
0,0 → 1,74
/*! \file buffer.h \brief Multipurpose byte buffer structure and methods. */
//*****************************************************************************
//
// File Name : 'buffer.h'
// Title : Multipurpose byte buffer structure and methods
// Author : Pascal Stang - Copyright (C) 2001-2002
// Created : 9/23/2001
// Revised : 11/16/2002
// Version : 1.1
// Target MCU : any
// Editor Tabs : 4
//
/// \ingroup general
/// \defgroup buffer Circular Byte-Buffer Structure and Function Library (buffer.c)
/// \code #include "buffer.h" \endcode
/// \par Overview
/// This byte-buffer structure provides an easy and efficient way to store
/// and process a stream of bytes.� You can create as many buffers as you
/// like (within memory limits), and then use this common set of functions to
/// access each buffer.� The buffers are designed for FIFO�operation (first
/// in, first out).� This means that the first byte you put in the buffer
/// will be the first one you get when you read out the buffer.� Supported
/// functions include buffer initialize, get byte from front of buffer, add
/// byte to end of buffer, check if buffer is full, and flush buffer.� The
/// buffer uses a circular design so no copying of data is ever necessary.
/// This buffer is not dynamically allocated, it has a user-defined fixed
/// maximum size.� This buffer is used in many places in the avrlib code.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
//@{
 
#ifndef BUFFER_H
#define BUFFER_H
 
// structure/typdefs
 
//! cBuffer structure
typedef struct struct_cBuffer
{
unsigned char *dataptr; ///< the physical memory address where the buffer is stored
unsigned short size; ///< the allocated size of the buffer
unsigned short datalength; ///< the length of the data currently in the buffer
unsigned short dataindex; ///< the index into the buffer where the data starts
} cBuffer;
 
// function prototypes
 
//! initialize a buffer to start at a given address and have given size
void bufferInit(cBuffer* buffer, unsigned char *start, unsigned short size);
 
//! get the first byte from the front of the buffer
unsigned char bufferGetFromFront(cBuffer* buffer);
 
//! dump (discard) the first numbytes from the front of the buffer
void bufferDumpFromFront(cBuffer* buffer, unsigned short numbytes);
 
//! get a byte at the specified index in the buffer (kind of like array access)
// ** note: this does not remove the byte that was read from the buffer
unsigned char bufferGetAtIndex(cBuffer* buffer, unsigned short index);
 
//! add a byte to the end of the buffer
unsigned char bufferAddToEnd(cBuffer* buffer, unsigned char data);
 
//! check if the buffer is full/not full (returns zero value if full)
unsigned short bufferIsNotFull(cBuffer* buffer);
 
//! flush (clear) the contents of the buffer
void bufferFlush(cBuffer* buffer);
 
#endif
//@}
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/akcelerometr/global.h
0,0 → 1,42
 
//*****************************************************************************
//
// File Name : 'global.h'
// Title : AVR project global include
// Author : Pascal Stang
// Created : 7/12/2001
// Revised : 9/30/2002
// Version : 1.1
// Target MCU : Atmel AVR series
// Editor Tabs : 4
//
// Description : This include file is designed to contain items useful to all
// code files and projects.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
#ifndef GLOBAL_H
#define GLOBAL_H
 
// global AVRLIB defines
#include "avrlibdefs.h"
// global AVRLIB types definitions
#include "avrlibtypes.h"
 
// project/system dependent defines
 
#define UART_RX_BUFFER_SIZE 0x00FF
 
// CPU clock speed
//#define F_CPU 16000000 // 16MHz processor
//#define F_CPU 14745000 // 14.745MHz processor
#define F_CPU 8000000 // 8MHz processor
//#define F_CPU 7372800 // 7.37MHz processor
//#define F_CPU 4000000 // 4MHz processor
//#define F_CPU 3686400 // 3.69MHz processor
#define CYCLES_PER_US ((F_CPU+500000)/1000000) // cpu cycles per microsecond
 
#endif
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/akcelerometr/gmetr.kontrollerlab
0,0 → 1,70
<!DOCTYPE KontrollerLab>
<PROJECT VERSION="0.8.0-beta1" >
<FILES>
<FILE VIEWS="0,0,1024,482,5," SHOWN="TRUE" NAME="a2dtest.c" />
<FILE SHOWN="FALSE" NAME="avrlibdefs.h" />
<FILE SHOWN="FALSE" NAME="avrlibtypes.h" />
<FILE SHOWN="FALSE" NAME="a2d.c" />
<FILE SHOWN="FALSE" NAME="a2d.h" />
<FILE SHOWN="FALSE" NAME="buffer.c" />
<FILE SHOWN="FALSE" NAME="buffer.h" />
<FILE SHOWN="FALSE" NAME="global.h" />
<FILE SHOWN="FALSE" NAME="rprintf.c" />
<FILE SHOWN="FALSE" NAME="rprintf.h" />
<FILE SHOWN="FALSE" NAME="timer.c" />
<FILE SHOWN="FALSE" NAME="timer.h" />
<FILE VIEWS="4,480,1,1,6," SHOWN="TRUE" NAME="uart.c" />
<FILE SHOWN="FALSE" NAME="uart.h" />
<FILE SHOWN="FALSE" NAME="vt100.c" />
<FILE SHOWN="FALSE" NAME="vt100.h" />
</FILES>
<SETTINGS>
<ASSEMBLER_COMMAND VALUE="avr-gcc" />
<BUILD_SYSTEM VALUE="BUILT_IN_BUILD" />
<CLOCK VALUE="8e+06" />
<COMPILER_CALL_PROLOGUES VALUE="FALSE" />
<COMPILER_COMMAND VALUE="avr-gcc" />
<COMPILER_F_CPU VALUE="FALSE" />
<COMPILER_GDEBUG VALUE="FALSE" />
<COMPILER_OPT_LEVEL VALUE="s" />
<COMPILER_STRICT_PROTOTYPES VALUE="TRUE" />
<COMPILER_WALL VALUE="TRUE" />
<CPU VALUE="ATMega8" />
<HEX_FILE VALUE="project.hex" />
<LINKER_COMMAND VALUE="avr-gcc" />
<LINKER_FLAGS VALUE="" />
<MAKE_CLEAN_TARGET VALUE="clean" />
<MAKE_COMMAND VALUE="make" />
<MAKE_DEFAULT_TARGET VALUE="all" />
<MAP_FILE VALUE="project.map" />
<OBJCOPY_COMMAND VALUE="avr-objcopy" />
</SETTINGS>
<DEBUGGER_SETTINGS/>
<PROGRAMMERCONFIG>
<AVRDUDE_CONNECTION_PORT VALUE="/dev/parport0" />
<AVRDUDE_COUNT_ERASE VALUE="FALSE" />
<AVRDUDE_DISABLE_AUTO_ERASE VALUE="FALSE" />
<AVRDUDE_OVERRIDE_INVALID_SIGNATURE VALUE="FALSE" />
<AVRDUDE_PROGRAMMER_TYPE VALUE="dapa" />
<AVRDUDE_TEST_MODE VALUE="FALSE" />
<PROGRAMMER_COMMAND VALUE="avrdude" />
<PROGRAMMER_NAME VALUE="AVRDUDE" />
<UISP_PARALLEL_AT89S VALUE="FALSE" />
<UISP_PARALLEL_DISABLE_RETRIES VALUE="FALSE" />
<UISP_PARALLEL_EEPROM_MAX_WRITE_DELAY VALUE="2777" />
<UISP_PARALLEL_FLASH_MAX_WRITE_DELAY VALUE="2777" />
<UISP_PARALLEL_NO_DATA_POLLING VALUE="FALSE" />
<UISP_PARALLEL_PORT VALUE="" />
<UISP_PARALLEL_RESET_HIGH_TIME VALUE="0" />
<UISP_PARALLEL_SCK_HIGH_LOW_TIME VALUE="0" />
<UISP_PARALLEL_VOLTAGE VALUE="0" />
<UISP_PROGRAMMER_TYPE VALUE="" />
<UISP_SERIAL_PORT VALUE="" />
<UISP_SERIAL_SPEED VALUE="9600" />
<UISP_SPECIFY_PART VALUE="FALSE" />
<UISP_STK500_AREF_VOLTAGE VALUE="0" />
<UISP_STK500_OSCILLATOR_FREQUENCY VALUE="14.1" />
<UISP_STK500_USE_HIGH_VOLTAGE VALUE="FALSE" />
<UISP_STK500_VTARGET_VOLTAGE VALUE="0" />
</PROGRAMMERCONFIG>
</PROJECT>
/programy/C/avr/akcelerometr/project.hex
0,0 → 1,480
:100000004AC064C063C05DC6D1C53EC603C61FC634
:10001000B0C568C55BC0AFC659C0E2C615C156C001
:1000200055C054C053C0084AD73B3BCE016E84BC78
:10003000BFFDC12F3D6C74319ABD56833DDA3D0042
:10004000C77F11BED9E4BB4C3E916BAAAABE00008B
:1000500000803F583A256420593A25642066693A61
:1000600025642E2564200D0A0030313233343536B4
:10007000373839414243444546000000010008003A
:1000800040000001000400000100080020004000C2
:1000900080000001000411241FBECFE5D4E0DEBFC4
:1000A000CDBF11E0A0E6B0E0EAEDFCE102C00590B2
:1000B0000D92A836B107D9F712E0A8E6B1E001C069
:1000C0001D92AA3DB107E1F702D005CE99CF9F92CC
:1000D000AF92BF92CF92DF92EF92FF920F931F9356
:1000E000CF93DF93EBD660E875E280E090E00BD62B
:1000F00083EA96E060D139D360D014BA15BA87E0AC
:100100006FD080E072D0CC24DD2410E0C0E0D0E0DD
:1001100033E5A32E30E0B32E9924939409C080E0F8
:1001200079D0C80FD91F81E075D0C80ED91E1F5FC6
:100130001032A8F3CE0160E270E0E3DAEB01C050C8
:10014000D240C60160E270E0DCDAC12C2EEFD22E84
:10015000C60ED71EBE01882777FD8095982F5FD8E1
:100160007B018C01B601882777FD8095982F57D8A1
:10017000A80197015CDB20E030E044E353E4B5D60E
:100180002BED3FE049E450E4A5D70ADC1F921F9213
:10019000A0D87F936F93DF92CF92DF93CF93BF92DC
:1001A000AF929F9254D210E08DB79EB70B960FB6C8
:1001B000F8949EBF0FBE8DBFB2CF379A359886B1E7
:1001C000887F866086B987B18F73806487B93D98D0
:1001D000339A1092B9027894089533983798089515
:1001E00096B1987F982B96B9089597B18295880F0C
:1001F000880F807C9F73982B97B9089597B18F7162
:10020000907E892B87B90895349A369A089586B1DD
:10021000807408951092B90297B18F71907E892BE6
:1002200087B9349A369A3699FECF24B145B1942FC6
:1002300080E030E0282B392BC9010895EBDF96953B
:1002400087959695879508951F920F920FB60F92F6
:1002500011248F938FEF8093B9028F910F900FBE6F
:100260000F901F901895FC018FB7F89471836083ED
:100270005383428317821682158214828FBF08959A
:10028000CF93DF93DC014FB7F894EC018C819D8113
:10029000892B11F4E0E01CC0FD0186819781ED916E
:1002A000FC911197E80FF91FE0810196ED019F8302
:1002B0008E832A813B818217930720F0821B930B48
:1002C0009F838E83ED018C819D8101979D838C831B
:1002D0004FBF8E2FDF91CF910895FC014FB7F89457
:1002E0008481958168177907B0F486819781860F9C
:1002F000971F97838683228133818217930720F08B
:10030000821B930B9783868384819581861B970B31
:100310009583848302C0158214824FBF0895FC0127
:10032000CB012FB7F8942FBF26813781628173816B
:10033000820F931FD2D90190F081E02DE80FF91FB1
:10034000808108951F93CF93DF93EC01162F4FB751
:10035000F8942C813D816A817B812617370790F4C0
:100360008E819F81820F931FB8D9E881F981E80FB0
:10037000F91F10838C819D8101969D838C834FBFD3
:100380008FEF02C04FBF80E0DF91CF911F910895A2
:10039000FC018FB7F8948FBF2281338184819581CE
:1003A000281B390BC9010895FC018FB7F8941582F9
:1003B00014828FBF08959093690180936801089516
:1003C0001F93182F8A3031F4E0916801F091690190
:1003D0008DE00995E0916801F0916901812F0995FF
:1003E0001F910895CF93DF93EC01009719F405C096
:1003F0002196E6DF88818823D9F7DF91CF91089590
:10040000EF92FF920F931F93CF93DF938C017A01AA
:100410000097E1F020E030E02617370738F4F801C4
:1004200081918F012F5F3F4F8823B1F7C0E0D0E06B
:100430000AC0F8018081882319F00F5F1F4F01C0A7
:1004400080E2BEDF2196CE15DF0598F3DF91CF91D4
:100450001F910F91FF90EF900895CF93DF93EC01E0
:10046000009711F406C0ACDFFE0121968491882329
:10047000D1F7DF91CF9108958AE0A2DF0895E82FA8
:10048000F0E0EF70F070E759FF4FE4918E2F98DFA6
:1004900008951F93182F82958F70F1DF812FEFDF62
:1004A0001F9108951F93182F892FF3DF812FF1DFFC
:1004B0001F910895EF92FF920F931F937B018C0180
:1004C000C801AA27BB27EEDFC701ECDF1F910F9100
:1004D000FF90EF9008952F923F924F925F926F920C
:1004E0007F928F929F92AF92BF92CF92DF92EF92C4
:1004F000FF920F931F93DF93CF93CDB7DEB7A397F0
:100500000FB6F894DEBF0FBECDBF4AA32BA33701B1
:100510004801442351F017FF08C0EE24FF2487014F
:10052000E618F7080809190902C084017301262E8C
:10053000262F215090E03AA1311191E0291B29A3E7
:1005400018A2A82EBB24A7FCB094CB2CDB2CC8018E
:10055000B701A6019501E8D8FB01EF70F070E759EB
:10056000FF4F64916F8FC801B701A6019501DCD8D8
:10057000C901DA017C018D019EE1492E512C4C0EFE
:100580005D1E39A023C0E114F10401051105B9F085
:10059000C801B701A6019501C7D8FB01EF70F07043
:1005A000E759FF4F6491F2016083C801B701A601CA
:1005B0009501BAD8C901DA017C018D0103C02BA1D4
:1005C000F20120833A940894410851083320D9F667
:1005D000CE014F968C0139A1031B11098AA18823F2
:1005E000D9F097FE05C08DE2F80182938F0114C007
:1005F000C8010197611471048104910419F08C0100
:100600008BE202C08C0180E2F801808305C0F80112
:1006100081918F01D5DE2A942220C9F7A3960FB6C7
:10062000F894DEBF0FBECDBFCF91DF911F910F9128
:10063000FF90EF90DF90CF90BF90AF909F908F9002
:100640007F906F905F904F903F902F9008957F9292
:100650008F929F92AF92BF92CF92DF92EF92FF92D2
:100660000F931F93DF93CF93CDB7DEB77888C988F8
:10067000DA8853E1E52EF12CEC0EFD1E13C0882321
:1006800081F480E090E0CF91DF911F910F91FF9076
:10069000EF90DF90CF90BF90AF909F908F907F9022
:1006A00008958EDE96012F5F3F4F772021F0F601EF
:1006B0006901849103C0F601808169018532F9F6F0
:1006C0002F5F3F4F772021F0F6016901849103C02D
:1006D000F60180816901843629F0883781F08336FC
:1006E00001F706C000E117E24AE0A42EB12C0CC0CD
:1006F000F701808122E030E0E20EF31ED2CF00E06D
:1007000010E130E1A32EB12C22E0822E912C8E0C30
:100710009F1CF701E080F1808436A1F4F7FE0FC042
:10072000F094E194F108F3948DE24ADE08C0C80128
:100730006AE070E0D2D78B016230710518F0E016E4
:10074000F106A8F3C701B801C8D7862F98DEC70104
:10075000B801C3D77C01C801B501BFD78B016115B2
:10076000710581F774019ECF089580E090E0FC014F
:10077000EE0FFF1FE659FE4F11821082019687305F
:100780009105A9F783B7887F826083BF12BE89B7BE
:10079000816089BF1092BA021092BB021092BC0213
:1007A0001092BD028EB5887F83608EBD1DBC1CBCBF
:1007B00089B7846089BF85B5887F846085BD14BC96
:1007C00089B7806489BF1092C2021092C30210924E
:1007D000C4021092C5027894089583B7887F82601E
:1007E00083BF12BE89B7816089BF1092BA0210928E
:1007F000BB021092BC021092BD0208958EB5887F94
:1008000083608EBD1DBC1CBC89B7846089BF089500
:1008100085B5887F846085BD14BC89B7806489BF35
:100820001092C2021092C3021092C4021092C5022A
:10083000089593B7987F982B93BF08959EB5987F9E
:10084000982B9EBD089595B5987F982B95BD0895DA
:1008500083B7E82FF0E0E770F070EE0FFF1FE65867
:10086000FF4F25913491C90108958EB5E82FF0E02E
:10087000E770F070EE0FFF1FE658FF4F259134919F
:10088000C901089585B5E82FF0E0E770F070EE0F2C
:10089000FF1FEA57FF4F25913491C9010895873012
:1008A00040F4E82FF0E0EE0FFF1FE659FE4F718392
:1008B00060830895873040F4E82FF0E0EE0FFF1FCB
:1008C000E659FE4F118210820895EF92FF920F9326
:1008D0001F93CF93DF93EC0112B71092BE021092D8
:1008E000BF021092C0021092C10283B7E82FF0E05D
:1008F000E770F070EE0FFF1FE658FF4F259134911F
:1009000040E050E060E072E18AE790E02FD7B90163
:10091000CA01693B2DE8720726E0820720E09207B2
:1009200090F437E2C131D30770F49E0140E050E00B
:10093000B5D628EE33E040E050E0F6D6C901DA0142
:10094000BC01CD011FC028EE33E040E050E0ECD602
:10095000CA01B9019E0140E050E0A0D613C08091C9
:10096000BE029091BF02A091C002B091C10285B7B2
:100970008F7885BF85B7806885BF889585B78F7765
:1009800085BF08C09B01AC01210F311D411D511DC8
:1009900079018A012091BE023091BF024091C002CC
:1009A0005091C10282B790E0A0E0B0E0542F432FF5
:1009B000322F2227822B932BA42BB52B8E159F052C
:1009C000A007B10760F2DF91CF911F910F91FF90C7
:1009D000EF9008951092BA021092BB021092BC02DE
:1009E0001092BD0208952091BA023091BB0240914D
:1009F000BC025091BD02B901CA0108951092C20211
:100A00001092C3021092C4021092C5020895209160
:100A1000C2023091C3024091C4025091C502B90193
:100A2000CA010895893031F48FB582608FBD8FB5CA
:100A30008E7F0AC08A3019F48FB5826002C08FB5EC
:100A40008D7F8FBD8FB581608FBD1BBC1ABC19BC5B
:100A500018BC08952FB52E7F2FBD2FB522602FBD56
:100A60002EB528602EBD2EB520612EBD97BD86BD4A
:100A70001BBC1ABC19BC18BC08958FB58D7F8FBDE7
:100A80008FB58E7F8FBD8FB58F778FBD8FB58F7BE5
:100A90008FBD8FB58F7D8FBD8FB58F7E8FBD089534
:100AA0008FB580688FBD8FB58F7B8FBD08958FB553
:100AB00080628FBD8FB58F7E8FBD08958FB58F7784
:100AC0008FBD8FB58F7B8FBD08958FB58F7D8FBD07
:100AD0008FB58F7E8FBD08959BBD8ABD089599BD4A
:100AE00088BD08951F920F920FB60F9211248F9315
:100AF0009F93AF93BF93EF93FF938091BA0290912E
:100B0000BB02A091BC02B091BD020196A11DB11D16
:100B10008093BA029093BB02A093BC02B093BD0233
:100B20008091BE029091BF02A091C002B091C1021B
:100B30000196A11DB11D8093BE029093BF02A093A8
:100B4000C002B093C10280916A0190916B01892B20
:100B500029F0E0916A01F0916B010995FF91EF9105
:100B6000BF91AF919F918F910F900FBE0F901F90EB
:100B700018951F920F920FB60F9211248F939F9387
:100B8000EF93FF9380916C0190916D01892B29F077
:100B9000E0916C01F0916D010995FF91EF919F91AA
:100BA0008F910F900FBE0F901F9018951F920F926C
:100BB0000FB60F9211248F939F93AF93BF93EF9330
:100BC000FF938091C2029091C302A091C402B091A0
:100BD000C5020196A11DB11D8093C2029093C3026C
:100BE000A093C402B093C5028091740190917501E5
:100BF000892B29F0E0917401F09175010995FF911D
:100C0000EF91BF91AF919F918F910F900FBE0F9079
:100C10001F9018951F920F920FB60F9211248F9369
:100C20009F93EF93FF9380916E0190916F01892BB9
:100C300029F0E0916E01F0916F010995FF91EF911C
:100C40009F918F910F900FBE0F901F9018951F923C
:100C50000F920FB60F9211248F939F93EF93FF93F0
:100C60008091700190917101892B29F0E0917001C0
:100C7000F09171010995FF91EF919F918F910F90E4
:100C80000FBE0F901F9018951F920F920FB60F92E4
:100C900011248F939F93EF93FF9380917201909112
:100CA0007301892B29F0E0917201F091730109958C
:100CB000FF91EF919F918F910F900FBE0F901F901A
:100CC00018951F920F920FB60F9211248F939F9336
:100CD000EF93FF938091760190917701892B29F012
:100CE000E0917601F09177010995FF91EF919F9145
:100CF0008F910F900FBE0F901F9018959093B80290
:100D00008093B70208959B01AC01605C7D4B804FDE
:100D10009F4FF3E0660F771F881F991FFA95D1F751
:100D2000E4E0220F331F441F551FEA95D1F7FCD48E
:100D30002150304029B930BD089587EC92E00895E4
:100D400080ED92E00895982F8091C6028823E1F308
:100D50009CB91092C60208951092CC021092CB0258
:100D600008958091CB029091CC02892B11F080E004
:100D700008958FEF08951F920F920FB60F921124CE
:100D80006F938F939F93EF93FF936CB18091B70212
:100D90009091B802892B39F0E091B702F091B80236
:100DA000862F09950EC087EC92E0CCDA882349F4AF
:100DB0008091D8029091D90201969093D9028093A4
:100DC000D802FF91EF919F918F916F910F900FBE7D
:100DD0000F901F901895682F80ED92E0B3DA089578
:100DE0001F920F920FB60F9211248F939F938091B1
:100DF000CF02882369F08091D4029091D502892B8B
:100E000029F080ED92E03CDA8CB905C01092CF0257
:100E10008FEF8093C6029F918F910F900FBE0F901E
:100E20001F9018958FEF8093CF0280ED92E028DA23
:100E3000982F8091C6028823E1F39CB91092C602D4
:100E40000895CF93DF93EC018091C9029091CA027B
:100E5000892B61F08091CB029091CC02892B31F0EB
:100E600087EC92E00DDA88838FEF01C080E0DF919C
:100E7000CF910895DF93CF930F92CDB7DEB7CE0118
:100E80000196DFDF882319F42FEF3FEF03C089813C
:100E9000282F30E0C9010F90CF91DF9108954FEFD7
:100EA00050E068E771E087EC92E0DDD940E450E083
:100EB00067E772E080ED92E0D6D90895F0DF1092F6
:100EC000B8021092B70288ED8AB960E875E280E056
:100ED00090E019DF8FEF8093C6021092CF0210923C
:100EE000D9021092D80278940895A0E2B0E0EAE71F
:100EF000F7E057C469837A838B839C832D833E8379
:100F00004F835887BE01675F7F4FCE01019656D34E
:100F1000BE016F5E7F4FCE01059650D3998592300A
:100F200088F089898230C8F0943019F4823051F405
:100F300004C0843029F4923081F480E690E0C6C089
:100F4000923049F420E09A858A89981321E02A8713
:100F5000CE010996BBC0823049F420E09A858A8987
:100F6000981321E02A8BCE014196B0C02D843E8497
:100F70004F8458886D887E888F88988CEE24FF2453
:100F80008701AA24BB24650140E050E060E070E0E6
:100F9000E0E0F0E0C10181709070892BE9F0E60C8F
:100FA000F71C081D191D9A01AB012A0D3B1D4C1D94
:100FB0005D1D80E090E0A0E0B0E0E614F7040805D5
:100FC000190520F481E090E0A0E0B0E0BA01A901A9
:100FD000480F591F6A1F7B1FAA0CBB1CCC1CDD1CB1
:100FE00097FE08C081E090E0A0E0B0E0A82AB92A0E
:100FF000CA2ADB2A3196E032F10549F0660C771CEB
:10100000881C991C5694479437942794C3CFFA852B
:10101000EA892B893C898B859C85280F391F2E5F97
:101020003F4F17C0CA0181709070892B61F01695EF
:101030000795F794E79480E090E0A0E0B0E8E82A14
:10104000F92A0A2B1B2B76956795579547952F5FA5
:101050003F4F77FDE7CF0CC0440F551F661F771F2A
:1010600017FD4160EE0CFF1C001F111F2150304086
:10107000403090E0590790E0690790E4790760F309
:101080002B8F3C8FDB01CA018F779070A070B070FE
:1010900080349105A105B10561F447FD0AC0E11452
:1010A000F1040105110529F0405C5F4F6F4F7F4F40
:1010B00040781A8EFE1711F081E08A8F4D8F5E8F77
:1010C0006F8F78A383E0898FCE014996A2D1A09635
:1010D000E2E183C3A8E1B0E0EFE6F8E06AC3698328
:1010E0007A838B839C832D833E834F835887B9E01B
:1010F000EB2EF12CEC0EFD1EB701CE0101965ED257
:101100008E010F5E1F4FB801CE01059657D229857B
:10111000223008F47CC03989323010F4B8017AC02A
:101120008A859A8989278A87243011F0223031F400
:10113000231709F06CC060E670E06CC0343039F4FD
:101140001D861E861F86188A1C861B8604C03230A8
:1011500021F484E08987B7015DC02B853C858B89AC
:101160009C89281B390B3C872B87ED84FE840F85D7
:101170001889AD88BE88CF88D88CEA14FB040C058A
:101180001D0540F4EE0CFF1C001F111F21503040C4
:101190003C872B8720E030E040E050E080E090E0AA
:1011A000A0E0B0E46FE170E0EA14FB040C051D055B
:1011B00040F0282B392B4A2B5B2BEA18FB080C0933
:1011C0001D09B695A79597958795EE0CFF1C001FF6
:1011D000111F6150704041F7DA01C9018F7790709B
:1011E000A070B07080349105A105B10561F427FDB0
:1011F0000AC0E114F1040105110529F0205C3F4FFC
:101200004F4F5F4F20782D873E874F87588BBE0109
:10121000675F7F4FCB01FDD06896EAE0E6C2A8E0A9
:10122000B0E0E4E1F9E0C6C29B01AC0183E0898350
:10123000DA01C9018827B7FD83959927AA27BB271B
:10124000B82E211531054105510519F482E0898335
:1012500039C08823A9F0203080E0380780E04807B3
:1012600080E8580729F460E070E080E09FEC2EC031
:10127000EE24FF248701E21AF30A040B150B02C0C7
:1012800079018A018EE1C82ED12CDC82CB82ED82DD
:10129000FE820F831887C801B7016CD0019718161A
:1012A000190684F4082E04C0EE0CFF1C001F111F49
:1012B0000A94D2F7ED82FE820F831887C81AD90AE2
:1012C000DC82CB82BA82CE010196A3D02896E9E0D7
:1012D0008DC2ACE0B0E0EEE6F9E073C269837A83D8
:1012E0008B839C83BE016B5F7F4FCE01019666D1DD
:1012F0008D81823061F1823050F1843021F48E8111
:10130000882351F12EC02F81388537FD20C06E8192
:101310002F3131051CF06623F9F023C08EE190E0F7
:10132000821B930B29853A854B855C8504C05695B5
:101330004795379527958A95D2F76623B1F0509552
:101340004095309521953F4F4F4F5F4F0EC020E0A5
:1013500030E040E050E009C02FEF3FEF4FEF5FE794
:1013600004C020E030E040E050E8B901CA012C960A
:10137000E2E043C2EF92FF920F931F937B018C0137
:1013800080E0E81680E0F80681E0080780E01807B2
:1013900088F48FEFE816F1040105110531F028F00B
:1013A00088E090E0A0E0B0E017C080E090E0A0E02E
:1013B000B0E012C080E0E81680E0F80680E00807A0
:1013C00081E0180728F088E190E0A0E0B0E004C0D8
:1013D00080E190E0A0E0B0E020E230E040E050E0CA
:1013E000281B390B4A0B5B0B04C016950795F79425
:1013F000E7948A95D2F7F701E859FF4F8081281BBF
:10140000310941095109C9011F910F91FF90EF90D6
:101410000895DF92EF92FF920F931F93FC01E480F7
:10142000F58006811781D1808081823048F480E088
:1014300090E0A0E1B0E0E82AF92A0A2B1B2BA5C016
:10144000843009F49FC0823021F4EE24FF24870108
:1014500005C0E114F1040105110519F4E0E0F0E024
:1014600096C0628173819FEF623879070CF05BC090
:1014700022E83FEF261B370B2A3131052CF020E004
:1014800030E040E050E02AC0B801A701022E04C0BD
:1014900076956795579547950A94D2F781E090E045
:1014A000A0E0B0E004C0880F991FAA1FBB1F2A95B7
:1014B000D2F70197A109B1098E219F21A023B12361
:1014C0000097A105B10521F081E090E0A0E0B0E037
:1014D0009A01AB01282B392B4A2B5B2BDA01C9016E
:1014E0008F779070A070B07080349105A105B10520
:1014F00039F427FF09C0205C3F4F4F4F5F4F04C0B6
:10150000215C3F4F4F4F5F4FE0E0F0E02030A0E024
:101510003A07A0E04A07A0E45A0710F0E1E0F0E043
:1015200079018A0127C06038710564F5FB01E15833
:10153000FF4FD801C7018F779070A070B0708034D2
:101540009105A105B10539F4E7FE0DC080E490E0F6
:10155000A0E0B0E004C08FE390E0A0E0B0E0E80ECF
:10156000F91E0A1F1B1F17FF05C016950795F79454
:10157000E794319687E016950795F794E7948A9556
:10158000D1F705C0EE24FF248701EFEFF0E06E2FC6
:10159000679566276795902F9F77D794DD24D7941A
:1015A0008E2F8695492F462B582F5D29B701CA01EA
:1015B0001F910F91FF90EF90DF900895FC01DB01E8
:1015C000408151812281622F6F7770E0221F222794
:1015D000221F9381892F880F822B282F30E0991F9B
:1015E0009927991FFD0191832115310581F5411539
:1015F00051056105710511F482E032C082E89FEF68
:10160000FD01938382839A01AB0167E0220F331FB0
:10161000441F551F6A95D1F783E08C930AC0220FAF
:10162000331F441F551FFD018281938101979383CE
:1016300082832030F0E03F07F0E04F07F0E45F07DF
:1016400070F3FD01248335834683578308952F3F2C
:10165000310581F4411551056105710519F484E0E6
:101660008C93089564FF03C081E08C9301C01C92A9
:10167000FD010FC02F573040FD013383228383E0EB
:101680008C9387E0440F551F661F771F8A95D1F70B
:10169000706444835583668377830895629FD00185
:1016A000739FF001829FE00DF11D649FE00DF11D1D
:1016B000929FF00D839FF00D749FF00D659FF00DCC
:1016C0009927729FB00DE11DF91F639FB00DE11DB9
:1016D000F91FBD01CF0111240895AA1BBB1B51E1C5
:1016E00007C0AA1FBB1FA617B70710F0A61BB70B92
:1016F000881F991F5A95A9F780959095BC01CD0137
:10170000089597FB092E07260AD077FD04D0E5DF60
:1017100006D000201AF4709561957F4F0895F6F772
:10172000909581959F4F0895A1E21A2EAA1BBB1B8D
:10173000FD010DC0AA1FBB1FEE1FFF1FA217B3079D
:10174000E407F50720F0A21BB30BE40BF50B661FB3
:10175000771F881F991F1A9469F760957095809577
:1017600090959B01AC01BD01CF01089597FB092E17
:1017700005260ED057FD04D0D7DF0AD0001C38F460
:1017800050954095309521953F4F4F4F5F4F0895AD
:10179000F6F790958095709561957F4F8F4F9F4F8D
:1017A00008952F923F924F925F926F927F928F9205
:1017B0009F92AF92BF92CF92DF92EF92FF920F93E0
:1017C0001F93CF93DF93CDB7DEB7CA1BDB0B0FB6EA
:1017D000F894DEBF0FBECDBF09942A8839884888A7
:1017E0005F846E847D848C849B84AA84B984C8843D
:1017F000DF80EE80FD800C811B81AA81B981CE0F34
:10180000D11D0FB6F894DEBF0FBECDBFED01089518
:1018100033D158F080E891E009F49EEF34D128F0FC
:1018200040E851E059F45EEF09C0FEC07DC1E92FE8
:10183000E07841D168F3092E052AC1F3261737074E
:101840004807590738F00E2E07F8E02569F0E02523
:10185000E0640AC0EF6307F8009407FADB01B901FE
:101860009D01DC01CA01AD01EF9341D013D10AD033
:101870005F91552331F02BED3FE049E450FD49ECF9
:10188000C6C10895DF93DD27B92FBF7740E85FE336
:101890001616170648075B0710F4D92F4CD19F93F3
:1018A0008F937F936F93AFD1E6E2F0E0C0D0F2D098
:1018B0002F913F914F915F914FD1DD2349F0905887
:1018C000A2EA2AED3FE049EC5FE3D0785D27B0D192
:1018D000DF91E0C0D8D040F0CFD030F021F45F3FAE
:1018E00019F071C0511121C19FC0E5D098F399231F
:1018F000C9F35523B1F3951B550BBB27AA276217D4
:101900007307840738F09F5F5F4F220F331F441F18
:10191000AA1FA9F333D00E2E3AF0E0E830D0915050
:101920005040E695001CCAF729D0FE2F27D0660F3D
:10193000771F881FBB1F261737074807AB07B0E87C
:1019400009F0BB0B802DBF01FF2793585F4F2AF092
:101950009E3F510568F037C0E8C05F3FECF3983E0A
:10196000DCF3869577956795B795F7959F5FC9F7EF
:10197000880F911D9695879597F90895E1E0660F78
:10198000771F881FBB1F621773078407BA0720F0F1
:10199000621B730B840BBA0BEE1F88F7E09508955A
:1019A000ACD080F09F3740F491110EF0BEC060E0E3
:1019B00070E080E89FEB089526F41B16611D711DF1
:1019C000811D07C021C097F99F6780E870E060E043
:1019D0000895882371F4772321F09850872B762F70
:1019E00007C0662311F499270DC09051862B70E033
:1019F00060E02AF09A95660F771F881FDAF7880F44
:101A00009695879597F908959F3F49F0915028F44E
:101A1000869577956795B7959F5F80389F4F880F1C
:101A20009695879597F908959FEF80EC0895DF9339
:101A3000CF931F930F93FF92EF92DF927B018C0164
:101A4000689405C0DA2EEF0187D0FE01E894A591D5
:101A50002591359145915591AEF3EF01E9D0FE0105
:101A60009701A801DA9479F7DF90EF90FF900F913A
:101A70001F91CF91DF91089500240A94161617063E
:101A800018060906089500240A941216130614066F
:101A900005060895092E0394000C11F4882352F0D2
:101AA000BB0F40F4BF2B11F460FF04C06F5F7F4F8A
:101AB0008F4F9F4F089557FD9058440F551F59F071
:101AC0005F3F71F04795880F97FB991F61F09F3F2B
:101AD00079F087950895121613061406551FF2CF54
:101AE0004695F1DF08C0161617061806991FF1CFA4
:101AF00086957105610508940895E5DFA0F0BEE7BD
:101B0000B91788F4BB279F3860F41616B11D672FEC
:101B1000782F8827985FF7CF869577956795B11DC1
:101B200093959639C8F30895E894BB2766277727DD
:101B3000CB0197F908959B01AC0160E070E080E86B
:101B40009FE3C8CA99DF28F09EDF18F0952309F0BB
:101B50003ACF6ACF1124E9CFAEDFA0F3959FD1F33E
:101B6000950F50E0551F629FF001729FBB27F00D4B
:101B7000B11D639FAA27F00DB11DAA1F649F6627A0
:101B8000B00DA11D661F829F2227B00DA11D621FEF
:101B9000739FB00DA11D621F839FA00D611D221FA9
:101BA000749F3327A00D611D231F849F600D211D8D
:101BB000822F762F6A2F11249F5750408AF0E1F030
:101BC00088234AF0EE0FFF1FBB1F661F771F881F79
:101BD00091505040A9F79E3F510570F0F4CEA5CF2B
:101BE0005F3FECF3983EDCF3869577956795B79564
:101BF000F795E7959F5FC1F7FE2B880F911D96958E
:101C0000879597F908959B01AC016FC95058BB2780
:101C1000AA270ED03FCF30DF30F035DF20F031F48F
:101C20009F3F11F41EF400CF0EF4E095E7FBCBCEFE
:101C3000E92F41DF80F3BA1762077307840795071E
:101C400018F071F49EF570CF0EF4E0950B2EBA2FBC
:101C5000A02D0B01B90190010C01CA01A0011124B2
:101C6000FF27591B99F0593F50F4503E68F11A165E
:101C7000F040A22F232F342F4427585FF3CF4695EF
:101C800037952795A795F0405395C9F77EF41F1611
:101C9000BA0B620B730B840BBAF09150A1F0FF0FDB
:101CA000BB1F661F771F881FC2F70EC0BA0F621FC7
:101CB000731F841F48F4879577956795B795F795B7
:101CC0009E3F08F0B3CF9395880F08F09927EE0F49
:0A1CD000979587950895F894FFCFCB
:101CDA0000000000000000000001020203030303E9
:101CEA0004040404040404040505050505050505A2
:101CFA000505050505050505060606060606060682
:101D0A000606060606060606060606060606060669
:101D1A000606060606060606070707070707070751
:101D2A000707070707070707070707070707070739
:101D3A000707070707070707070707070707070729
:101D4A000707070707070707070707070707070719
:101D5A000707070707070707080808080808080801
:101D6A0008080808080808080808080808080808E9
:101D7A0008080808080808080808080808080808D9
:101D8A0008080808080808080808080808080808C9
:101D9A0008080808080808080808080808080808B9
:101DAA0008080808080808080808080808080808A9
:101DBA000808080808080808080808080808080899
:101DCA000808080808080808080808080808080889
:081DDA000808080808080808C1
:00000001FF
/programy/C/avr/akcelerometr/project.map
0,0 → 1,771
Archive member included because of file (symbol)
 
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_mulsi3.o)
timer.o (__mulsi3)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_udivmodhi4.o)
buffer.o (__udivmodhi4)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_divmodhi4.o)
a2dtest.o (__divmodhi4)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_udivmodsi4.o)
rprintf.o (__udivmodsi4)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_divmodsi4.o)
timer.o (__divmodsi4)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_exit.o)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/crtm8.o (exit)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_copy_data.o)
a2dtest.o (__do_copy_data)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_clear_bss.o)
a2dtest.o (__do_clear_bss)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_fixunssfsi.o)
a2dtest.o (__fixunssfsi)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_addsub_sf.o)
a2dtest.o (__subsf3)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_mul_sf.o)
a2dtest.o (__mulsf3)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_div_sf.o)
a2dtest.o (__divsf3)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_ge_sf.o)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_fixunssfsi.o) (__gesf2)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_si_to_sf.o)
a2dtest.o (__floatsisf)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_sf_to_si.o)
a2dtest.o (__fixsfsi)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_thenan_sf.o)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_addsub_sf.o) (__thenan_sf)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_prologue.o)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_addsub_sf.o) (__prologue_saves__)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_epilogue.o)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_addsub_sf.o) (__epilogue_restores__)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_clzsi2.o)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_si_to_sf.o) (__clzsi2)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_pack_sf.o)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_addsub_sf.o) (__pack_f)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_unpack_sf.o)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_addsub_sf.o) (__unpack_f)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_fpcmp_parts_sf.o)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_ge_sf.o) (__fpcmp_parts_f)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_clz.o)
/usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_clzsi2.o) (__clz_tab)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan2.o)
a2dtest.o (atan2)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan.o)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan2.o) (atan)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(divsf3x.o)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan2.o) (__divsf3_pse)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(floor.o)
a2dtest.o (floor)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_inf.o)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(divsf3x.o) (__fp_inf)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_mintl.o)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(floor.o) (__fp_mintl)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_mpack.o)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(floor.o) (__fp_mpack)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_nan.o)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan2.o) (__fp_nan)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_powser.o)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan.o) (__fp_powser)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_pscA.o)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan2.o) (__fp_pscA)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_pscB.o)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan2.o) (__fp_pscB)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_round.o)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan2.o) (__fp_round)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_split3.o)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan2.o) (__fp_split3)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_trunc.o)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(floor.o) (__fp_trunc)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_zero.o)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan2.o) (__fp_zero)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(inverse.o)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan.o) (inverse)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(mulsf3x.o)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan.o) (__mulsf3x)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(square.o)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan.o) (square)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(addsf3x.o)
/usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan.o) (__addsf3x)
 
Allocating common symbols
Common symbol size file
 
uartReadyTx 0x1 uart.o
Timer0Reg0 0x4 timer.o
uartRxBuffer 0x8 uart.o
TimerPauseReg 0x4 timer.o
Timer2Reg0 0x4 timer.o
uartBufferedTx 0x1 uart.o
a2dCompleteFlag 0x1 a2d.o
uartTxBuffer 0x8 uart.o
uartRxOverflow 0x2 uart.o
 
Memory Configuration
 
Name Origin Length Attributes
text 0x00000000 0x00002000 xr
data 0x00800060 0x0000ffa0 rw !x
eeprom 0x00810000 0x00010000 rw !x
fuse 0x00820000 0x00000400 rw !x
lock 0x00830000 0x00000400 rw !x
signature 0x00840000 0x00000400 rw !x
*default* 0x00000000 0xffffffff
 
Linker script and memory map
 
LOAD /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/crtm8.o
LOAD a2dtest.o
LOAD a2d.o
LOAD buffer.o
LOAD rprintf.o
LOAD timer.o
LOAD uart.o
LOAD /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a
LOAD /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a
LOAD /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a
 
.hash
*(.hash)
 
.dynsym
*(.dynsym)
 
.dynstr
*(.dynstr)
 
.gnu.version
*(.gnu.version)
 
.gnu.version_d
*(.gnu.version_d)
 
.gnu.version_r
*(.gnu.version_r)
 
.rel.init
*(.rel.init)
 
.rela.init
*(.rela.init)
 
.rel.text
*(.rel.text)
*(.rel.text.*)
*(.rel.gnu.linkonce.t*)
 
.rela.text
*(.rela.text)
*(.rela.text.*)
*(.rela.gnu.linkonce.t*)
 
.rel.fini
*(.rel.fini)
 
.rela.fini
*(.rela.fini)
 
.rel.rodata
*(.rel.rodata)
*(.rel.rodata.*)
*(.rel.gnu.linkonce.r*)
 
.rela.rodata
*(.rela.rodata)
*(.rela.rodata.*)
*(.rela.gnu.linkonce.r*)
 
.rel.data
*(.rel.data)
*(.rel.data.*)
*(.rel.gnu.linkonce.d*)
 
.rela.data
*(.rela.data)
*(.rela.data.*)
*(.rela.gnu.linkonce.d*)
 
.rel.ctors
*(.rel.ctors)
 
.rela.ctors
*(.rela.ctors)
 
.rel.dtors
*(.rel.dtors)
 
.rela.dtors
*(.rela.dtors)
 
.rel.got
*(.rel.got)
 
.rela.got
*(.rela.got)
 
.rel.bss
*(.rel.bss)
 
.rela.bss
*(.rela.bss)
 
.rel.plt
*(.rel.plt)
 
.rela.plt
*(.rela.plt)
 
.text 0x00000000 0x2186
*(.vectors)
.vectors 0x00000000 0x26 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/crtm8.o
0x00000000 __vectors
0x00000000 __vector_default
*(.vectors)
*(.progmem.gcc*)
.progmem.gcc_fplib
0x00000026 0x2d /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan.o)
*(.progmem*)
.progmem.data 0x00000053 0x16 a2dtest.o
.progmem.data 0x00000069 0x11 rprintf.o
.progmem.data 0x0000007a 0x1c timer.o
0x00000086 TimerRTCPrescaleFactor
0x0000007a TimerPrescaleFactor
0x00000096 . = ALIGN (0x2)
0x00000096 __trampolines_start = .
*(.trampolines)
.trampolines 0x00000096 0x0 linker stubs
*(.trampolines*)
0x00000096 __trampolines_end = .
*(.jumptables)
*(.jumptables*)
*(.lowtext)
*(.lowtext*)
0x00000096 __ctors_start = .
*(.ctors)
0x00000096 __ctors_end = .
0x00000096 __dtors_start = .
*(.dtors)
0x00000096 __dtors_end = .
SORT(*)(.ctors)
SORT(*)(.dtors)
*(.init0)
.init0 0x00000096 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/crtm8.o
0x00000096 __init
*(.init0)
*(.init1)
*(.init1)
*(.init2)
.init2 0x00000096 0xc /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/crtm8.o
*(.init2)
*(.init3)
*(.init3)
*(.init4)
.init4 0x000000a2 0x16 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_copy_data.o)
0x000000a2 __do_copy_data
.init4 0x000000b8 0x10 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_clear_bss.o)
0x000000b8 __do_clear_bss
*(.init4)
*(.init5)
*(.init5)
*(.init6)
*(.init6)
*(.init7)
*(.init7)
*(.init8)
*(.init8)
*(.init9)
.init9 0x000000c8 0x4 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/crtm8.o
*(.init9)
*(.text)
.text 0x000000cc 0x2 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/crtm8.o
0x000000cc __vector_1
0x000000cc __vector_12
0x000000cc __bad_interrupt
0x000000cc __vector_17
0x000000cc __vector_2
0x000000cc __vector_15
0x000000cc __vector_10
0x000000cc __vector_16
0x000000cc __vector_18
.text 0x000000ce 0x116 a2dtest.o
0x000000ce main
.text 0x000001e4 0xac a2d.o
0x00000238 a2dIsComplete
0x00000266 a2dConvert8bit
0x00000204 a2dOff
0x0000020a a2dSetPrescaler
0x0000023e a2dConvert10bit
0x000001e4 a2dInit
0x00000214 a2dSetReference
0x00000272 __vector_14
0x00000226 a2dSetChannel
0x00000232 a2dStartConvert
.text 0x00000290 0x150 buffer.o
0x000003ba bufferIsNotFull
0x000002aa bufferGetFromFront
0x00000348 bufferGetAtIndex
0x00000304 bufferDumpFromFront
0x00000290 bufferInit
0x0000036e bufferAddToEnd
0x000003d2 bufferFlush
.text 0x000003e0 0x3b2 rprintf.o
0x00000678 rprintf1RamRom
0x000004bc rprintfu08
0x000004de rprintfu32
0x0000040e rprintfStr
0x0000042a rprintfStrLen
0x00000484 rprintfProgStr
0x000004ce rprintfu16
0x000003e0 rprintfInit
0x000003ea rprintfChar
0x000004a2 rprintfCRLF
0x000004a8 rprintfu04
0x00000500 rprintfNum
.text 0x00000792 0x594 timer.o
0x00000a38 timer2GetOverflowCount
0x000008de timerDetach
0x00000866 timer1SetPrescaler
0x00000af4 timer1PWMBOff
0x000008ae timer2GetPrescaler
0x00000c3e __vector_6
0x00000804 timer0Init
0x00000ae6 timer1PWMAOff
0x00000b08 timer1PWMBSet
0x00000cec __vector_3
0x00000a7e timer1PWMInitICR
0x0000087a timer0GetPrescaler
0x00000c78 __vector_7
0x00000a10 timer0GetOverflowCount
0x00000cb2 __vector_5
0x00000794 timerInit
0x00000870 timer2SetPrescaler
0x00000aca timer1PWMAOn
0x0000085c timer0SetPrescaler
0x00000792 delay_us
0x00000bd6 __vector_4
0x000009fe timer0ClearOverflowCount
0x00000b0e __vector_9
0x00000826 timer1Init
0x00000a4e timer1PWMInit
0x00000ad8 timer1PWMBOn
0x0000083a timer2Init
0x00000b9c __vector_8
0x00000b02 timer1PWMASet
0x000008c8 timerAttach
0x00000aa4 timer1PWMOff
0x00000894 timer1GetPrescaler
0x00000a26 timer2ClearOverflowCount
0x000008f4 timerPause
.text 0x00000d26 0x1ee uart.o
0x00000e4e uartSendTxBuffer
0x00000d70 uartSendByte
0x00000ec8 uartInitBuffers
0x00000e6c uartReceiveByte
0x00000e00 uartAddToTxBuffer
0x00000da0 __vector_11
0x00000d26 uartSetRxHandler
0x00000e0a __vector_13
0x00000d82 uartFlushReceiveBuffer
0x00000ee6 uartInit
0x00000d8c uartReceiveBufferIsEmpty
0x00000d30 uartSetBaudRate
0x00000d6a uartGetTxBuffer
0x00000e9e uartGetByte
0x00000d64 uartGetRxBuffer
.text 0x00000f14 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_mulsi3.o)
.text 0x00000f14 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_udivmodhi4.o)
.text 0x00000f14 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_divmodhi4.o)
.text 0x00000f14 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_udivmodsi4.o)
.text 0x00000f14 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_divmodsi4.o)
.text 0x00000f14 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_exit.o)
.text 0x00000f14 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_copy_data.o)
.text 0x00000f14 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_clear_bss.o)
.text 0x00000f14 0x50 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_fixunssfsi.o)
0x00000f14 __fixunssfsi
.text 0x00000f64 0x332 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_addsub_sf.o)
0x000011f2 __subsf3
0x00001248 __addsf3
.text 0x00001296 0x1ea /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_mul_sf.o)
0x00001296 __mulsf3
.text 0x00001480 0x14a /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_div_sf.o)
0x00001480 __divsf3
.text 0x000015ca 0x56 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_ge_sf.o)
0x000015ca __gesf2
.text 0x00001620 0xb4 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_si_to_sf.o)
0x00001620 __floatsisf
.text 0x000016d4 0xa2 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_sf_to_si.o)
0x000016d4 __fixsfsi
.text 0x00001776 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_thenan_sf.o)
.text 0x00001776 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_prologue.o)
.text 0x00001776 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_epilogue.o)
.text 0x00001776 0x9e /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_clzsi2.o)
0x00001776 __clzsi2
.text 0x00001814 0x1aa /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_pack_sf.o)
0x00001814 __pack_f
.text 0x000019be 0xe0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_unpack_sf.o)
0x000019be __unpack_f
.text 0x00001a9e 0xb4 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_fpcmp_parts_sf.o)
0x00001a9e __fpcmp_parts_f
.text 0x00001b52 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_clz.o)
.text 0x00001b52 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan2.o)
.text 0x00001b52 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan.o)
.text 0x00001b52 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(divsf3x.o)
.text 0x00001b52 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(floor.o)
.text 0x00001b52 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_inf.o)
.text 0x00001b52 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_mintl.o)
.text 0x00001b52 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_mpack.o)
.text 0x00001b52 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_nan.o)
.text 0x00001b52 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_powser.o)
.text 0x00001b52 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_pscA.o)
.text 0x00001b52 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_pscB.o)
.text 0x00001b52 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_round.o)
.text 0x00001b52 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_split3.o)
.text 0x00001b52 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_trunc.o)
.text 0x00001b52 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_zero.o)
.text 0x00001b52 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(inverse.o)
.text 0x00001b52 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(mulsf3x.o)
.text 0x00001b52 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(square.o)
.text 0x00001b52 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(addsf3x.o)
0x00001b52 . = ALIGN (0x2)
*(.text.*)
.text.libgcc 0x00001b52 0x3e /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_mulsi3.o)
0x00001b52 __mulsi3
.text.libgcc 0x00001b90 0x28 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_udivmodhi4.o)
0x00001b90 __udivmodhi4
.text.libgcc 0x00001bb8 0x26 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_divmodhi4.o)
0x00001bb8 __divmodhi4
0x00001bb8 _div
.text.libgcc 0x00001bde 0x44 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_udivmodsi4.o)
0x00001bde __udivmodsi4
.text.libgcc 0x00001c22 0x36 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_divmodsi4.o)
0x00001c22 __divmodsi4
.text.libgcc 0x00001c58 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_exit.o)
.text.libgcc 0x00001c58 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_copy_data.o)
.text.libgcc 0x00001c58 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_clear_bss.o)
.text.libgcc 0x00001c58 0x38 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_prologue.o)
0x00001c58 __prologue_saves__
.text.libgcc 0x00001c90 0x36 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_epilogue.o)
0x00001c90 __epilogue_restores__
.text.fplib 0x00001cc6 0x74 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan2.o)
0x00001ce4 atan2
.text.fplib 0x00001d3a 0x50 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan.o)
0x00001d3a atan
.text.fplib 0x00001d8a 0xcc /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(divsf3x.o)
0x00001da0 __divsf3x
0x00001da4 __divsf3_pse
.text.fplib 0x00001e56 0x26 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(floor.o)
0x00001e56 floor
.text.fplib 0x00001e7c 0xc /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_inf.o)
0x00001e7c __fp_inf
.text.fplib 0x00001e88 0x36 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_mintl.o)
0x00001e88 __fp_mintl
.text.fplib 0x00001ebe 0x20 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_mpack.o)
0x00001ebe __fp_mpack
.text.fplib 0x00001ede 0x6 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_nan.o)
0x00001ede __fp_nan
.text.fplib 0x00001ee4 0x4a /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_powser.o)
0x00001ee4 __fp_powser
.text.fplib 0x00001f2e 0xe /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_pscA.o)
0x00001f2e __fp_pscA
.text.fplib 0x00001f3c 0xe /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_pscB.o)
0x00001f3c __fp_pscB
.text.fplib 0x00001f4a 0x22 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_round.o)
0x00001f4a __fp_round
.text.fplib 0x00001f6c 0x44 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_split3.o)
0x00001f6c __fp_split3
0x00001f7c __fp_splitA
.text.fplib 0x00001fb0 0x2e /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_trunc.o)
0x00001fb0 __fp_trunc
.text.fplib 0x00001fde 0xe /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_zero.o)
0x00001fde __fp_zero
0x00001fe0 __fp_szero
.text.fplib 0x00001fec 0xe /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(inverse.o)
0x00001fec inverse
.text.fplib 0x00001ffa 0xc2 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(mulsf3x.o)
0x00002012 __mulsf3_pse
0x0000200e __mulsf3x
.text.fplib 0x000020bc 0x6 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(square.o)
0x000020bc square
.text.fplib 0x000020c2 0xc0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(addsf3x.o)
0x000020dc __addsf3x
0x00002182 . = ALIGN (0x2)
*(.fini9)
.fini9 0x00002182 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_exit.o)
0x00002182 exit
0x00002182 _exit
*(.fini9)
*(.fini8)
*(.fini8)
*(.fini7)
*(.fini7)
*(.fini6)
*(.fini6)
*(.fini5)
*(.fini5)
*(.fini4)
*(.fini4)
*(.fini3)
*(.fini3)
*(.fini2)
*(.fini2)
*(.fini1)
*(.fini1)
*(.fini0)
.fini0 0x00002182 0x4 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_exit.o)
*(.fini0)
0x00002186 _etext = .
 
.data 0x00800060 0x108 load address 0x00002186
0x00800060 PROVIDE (__data_start, .)
*(.data)
.data 0x00800060 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/crtm8.o
.data 0x00800060 0x0 a2dtest.o
.data 0x00800060 0x0 a2d.o
.data 0x00800060 0x0 buffer.o
.data 0x00800060 0x0 rprintf.o
.data 0x00800060 0x0 timer.o
.data 0x00800060 0x0 uart.o
.data 0x00800060 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_mulsi3.o)
.data 0x00800060 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_udivmodhi4.o)
.data 0x00800060 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_divmodhi4.o)
.data 0x00800060 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_udivmodsi4.o)
.data 0x00800060 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_divmodsi4.o)
.data 0x00800060 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_exit.o)
.data 0x00800060 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_copy_data.o)
.data 0x00800060 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_clear_bss.o)
.data 0x00800060 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_fixunssfsi.o)
.data 0x00800060 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_addsub_sf.o)
.data 0x00800060 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_mul_sf.o)
.data 0x00800060 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_div_sf.o)
.data 0x00800060 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_ge_sf.o)
.data 0x00800060 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_si_to_sf.o)
.data 0x00800060 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_sf_to_si.o)
.data 0x00800060 0x8 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_thenan_sf.o)
0x00800060 __thenan_sf
.data 0x00800068 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_prologue.o)
.data 0x00800068 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_epilogue.o)
.data 0x00800068 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_clzsi2.o)
.data 0x00800068 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_pack_sf.o)
.data 0x00800068 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_unpack_sf.o)
.data 0x00800068 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_fpcmp_parts_sf.o)
.data 0x00800068 0x100 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_clz.o)
0x00800068 __clz_tab
.data 0x00800168 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan2.o)
.data 0x00800168 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan.o)
.data 0x00800168 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(divsf3x.o)
.data 0x00800168 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(floor.o)
.data 0x00800168 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_inf.o)
.data 0x00800168 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_mintl.o)
.data 0x00800168 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_mpack.o)
.data 0x00800168 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_nan.o)
.data 0x00800168 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_powser.o)
.data 0x00800168 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_pscA.o)
.data 0x00800168 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_pscB.o)
.data 0x00800168 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_round.o)
.data 0x00800168 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_split3.o)
.data 0x00800168 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_trunc.o)
.data 0x00800168 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_zero.o)
.data 0x00800168 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(inverse.o)
.data 0x00800168 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(mulsf3x.o)
.data 0x00800168 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(square.o)
.data 0x00800168 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(addsf3x.o)
*(.data*)
*(.rodata)
*(.rodata*)
*(.gnu.linkonce.d*)
0x00800168 . = ALIGN (0x2)
0x00800168 _edata = .
0x00800168 PROVIDE (__data_end, .)
 
.bss 0x00800168 0x172 load address 0x0000228e
0x00800168 PROVIDE (__bss_start, .)
*(.bss)
.bss 0x00800168 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/crtm8.o
.bss 0x00800168 0x0 a2dtest.o
.bss 0x00800168 0x0 a2d.o
.bss 0x00800168 0x0 buffer.o
.bss 0x00800168 0x2 rprintf.o
.bss 0x0080016a 0xe timer.o
.bss 0x00800178 0x141 uart.o
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_mulsi3.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_udivmodhi4.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_divmodhi4.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_udivmodsi4.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_divmodsi4.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_exit.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_copy_data.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_clear_bss.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_fixunssfsi.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_addsub_sf.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_mul_sf.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_div_sf.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_ge_sf.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_si_to_sf.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_sf_to_si.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_thenan_sf.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_prologue.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_epilogue.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_clzsi2.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_pack_sf.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_unpack_sf.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_fpcmp_parts_sf.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/avr4/libgcc.a(_clz.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan2.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(divsf3x.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(floor.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_inf.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_mintl.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_mpack.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_nan.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_powser.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_pscA.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_pscB.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_round.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_split3.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_trunc.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_zero.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(inverse.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(mulsf3x.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(square.o)
.bss 0x008002b9 0x0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(addsf3x.o)
*(.bss*)
*(COMMON)
COMMON 0x008002b9 0x1 a2d.o
0x008002b9 a2dCompleteFlag
COMMON 0x008002ba 0xc timer.o
0x008002ba Timer0Reg0
0x008002be TimerPauseReg
0x008002c2 Timer2Reg0
COMMON 0x008002c6 0x14 uart.o
0x008002c6 uartReadyTx
0x008002c7 uartRxBuffer
0x008002cf uartBufferedTx
0x008002d0 uartTxBuffer
0x008002d8 uartRxOverflow
0x008002da PROVIDE (__bss_end, .)
0x00002186 __data_load_start = LOADADDR (.data)
0x0000228e __data_load_end = (__data_load_start + SIZEOF (.data))
 
.noinit 0x008002da 0x0
0x008002da PROVIDE (__noinit_start, .)
*(.noinit*)
0x008002da PROVIDE (__noinit_end, .)
0x008002da _end = .
0x008002da PROVIDE (__heap_start, .)
 
.eeprom 0x00810000 0x0
*(.eeprom*)
0x00810000 __eeprom_end = .
 
.fuse
*(.fuse)
*(.lfuse)
*(.hfuse)
*(.efuse)
 
.lock
*(.lock*)
 
.signature
*(.signature*)
 
.stab 0x00000000 0x270c
*(.stab)
.stab 0x00000000 0x6b4 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/crtm8.o
.stab 0x000006b4 0x2f4 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan2.o)
0x300 (size before relaxing)
.stab 0x000009a8 0x210 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(atan.o)
0x21c (size before relaxing)
.stab 0x00000bb8 0x510 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(divsf3x.o)
0x51c (size before relaxing)
.stab 0x000010c8 0x114 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(floor.o)
0x120 (size before relaxing)
.stab 0x000011dc 0x78 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_inf.o)
0x84 (size before relaxing)
.stab 0x00001254 0x174 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_mintl.o)
0x180 (size before relaxing)
.stab 0x000013c8 0xf0 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_mpack.o)
0xfc (size before relaxing)
.stab 0x000014b8 0x54 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_nan.o)
0x60 (size before relaxing)
.stab 0x0000150c 0x1ec /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_powser.o)
0x1f8 (size before relaxing)
.stab 0x000016f8 0x84 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_pscA.o)
0x90 (size before relaxing)
.stab 0x0000177c 0x84 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_pscB.o)
0x90 (size before relaxing)
.stab 0x00001800 0xfc /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_round.o)
0x108 (size before relaxing)
.stab 0x000018fc 0x1d4 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_split3.o)
0x1e0 (size before relaxing)
.stab 0x00001ad0 0x144 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_trunc.o)
0x150 (size before relaxing)
.stab 0x00001c14 0x90 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(fp_zero.o)
0x9c (size before relaxing)
.stab 0x00001ca4 0x84 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(inverse.o)
0x90 (size before relaxing)
.stab 0x00001d28 0x4d4 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(mulsf3x.o)
0x4e0 (size before relaxing)
.stab 0x000021fc 0x54 /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(square.o)
0x60 (size before relaxing)
.stab 0x00002250 0x4bc /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/libc.a(addsf3x.o)
0x4c8 (size before relaxing)
 
.stabstr 0x00000000 0x3bc
*(.stabstr)
.stabstr 0x00000000 0x3bc /usr/lib/gcc/avr/4.3.0/../../../../avr/lib/avr4/crtm8.o
 
.stab.excl
*(.stab.excl)
 
.stab.exclstr
*(.stab.exclstr)
 
.stab.index
*(.stab.index)
 
.stab.indexstr
*(.stab.indexstr)
 
.comment
*(.comment)
 
.debug
*(.debug)
 
.line
*(.line)
 
.debug_srcinfo
*(.debug_srcinfo)
 
.debug_sfnames
*(.debug_sfnames)
 
.debug_aranges
*(.debug_aranges)
 
.debug_pubnames
*(.debug_pubnames)
 
.debug_info
*(.debug_info)
*(.gnu.linkonce.wi.*)
 
.debug_abbrev
*(.debug_abbrev)
 
.debug_line
*(.debug_line)
 
.debug_frame
*(.debug_frame)
 
.debug_str
*(.debug_str)
 
.debug_loc
*(.debug_loc)
 
.debug_macinfo
*(.debug_macinfo)
OUTPUT(project.out elf32-avr)
LOAD linker stubs
/programy/C/avr/akcelerometr/rprintf.c
0,0 → 1,782
/*! \file rprintf.c \brief printf routine and associated routines. */
//*****************************************************************************
//
// File Name : 'rprintf.c'
// Title : printf routine and associated routines
// Author : Pascal Stang - Copyright (C) 2000-2002
// Created : 2000.12.26
// Revised : 2003.5.1
// Version : 1.0
// Target MCU : Atmel AVR series and other targets
// Editor Tabs : 4
//
// NOTE: This code is currently below version 1.0, and therefore is considered
// to be lacking in some functionality or documentation, or may not be fully
// tested. Nonetheless, you can expect most functions to work.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
#include <avr/pgmspace.h>
//#include <string-avr.h>
//#include <stdlib.h>
#include <stdarg.h>
#include "global.h"
#include "rprintf.h"
 
#ifndef TRUE
#define TRUE -1
#define FALSE 0
#endif
 
#define INF 32766 // maximum field size to print
#define READMEMBYTE(a,char_ptr) ((a)?(pgm_read_byte(char_ptr)):(*char_ptr))
 
#ifdef RPRINTF_COMPLEX
static unsigned char buf[128];
#endif
 
// use this to store hex conversion in RAM
//static char HexChars[] = "0123456789ABCDEF";
// use this to store hex conversion in program memory
//static prog_char HexChars[] = "0123456789ABCDEF";
static char __attribute__ ((progmem)) HexChars[] = "0123456789ABCDEF";
 
#define hexchar(x) pgm_read_byte( HexChars+((x)&0x0f) )
//#define hexchar(x) ((((x)&0x0F)>9)?((x)+'A'-10):((x)+'0'))
 
// function pointer to single character output routine
static void (*rputchar)(unsigned char c);
 
// *** rprintf initialization ***
// you must call this function once and supply the character output
// routine before using other functions in this library
void rprintfInit(void (*putchar_func)(unsigned char c))
{
rputchar = putchar_func;
}
 
// *** rprintfChar ***
// send a character/byte to the current output device
void rprintfChar(unsigned char c)
{
// do LF -> CR/LF translation
if(c == '\n')
rputchar('\r');
// send character
rputchar(c);
}
 
// *** rprintfStr ***
// prints a null-terminated string stored in RAM
void rprintfStr(char str[])
{
// send a string stored in RAM
// check to make sure we have a good pointer
if (!str) return;
 
// print the string until a null-terminator
while (*str)
rprintfChar(*str++);
}
 
// *** rprintfStrLen ***
// prints a section of a string stored in RAM
// begins printing at position indicated by <start>
// prints number of characters indicated by <len>
void rprintfStrLen(char str[], unsigned int start, unsigned int len)
{
register int i=0;
 
// check to make sure we have a good pointer
if (!str) return;
// spin through characters up to requested start
// keep going as long as there's no null
while((i++<start) && (*str++));
// for(i=0; i<start; i++)
// {
// // keep steping through string as long as there's no null
// if(*str) str++;
// }
 
// then print exactly len characters
for(i=0; i<len; i++)
{
// print data out of the string as long as we haven't reached a null yet
// at the null, start printing spaces
if(*str)
rprintfChar(*str++);
else
rprintfChar(' ');
}
 
}
 
// *** rprintfProgStr ***
// prints a null-terminated string stored in program ROM
void rprintfProgStr(const prog_char str[])
{
// print a string stored in program memory
register char c;
 
// check to make sure we have a good pointer
if (!str) return;
// print the string until the null-terminator
while((c = pgm_read_byte(str++)))
rprintfChar(c);
}
 
// *** rprintfCRLF ***
// prints carriage return and line feed
void rprintfCRLF(void)
{
// print CR/LF
//rprintfChar('\r');
// LF -> CR/LF translation built-in to rprintfChar()
rprintfChar('\n');
}
 
// *** rprintfu04 ***
// prints an unsigned 4-bit number in hex (1 digit)
void rprintfu04(unsigned char data)
{
// print 4-bit hex value
// char Character = data&0x0f;
// if (Character>9)
// Character+='A'-10;
// else
// Character+='0';
rprintfChar(hexchar(data));
}
 
// *** rprintfu08 ***
// prints an unsigned 8-bit number in hex (2 digits)
void rprintfu08(unsigned char data)
{
// print 8-bit hex value
rprintfu04(data>>4);
rprintfu04(data);
}
 
// *** rprintfu16 ***
// prints an unsigned 16-bit number in hex (4 digits)
void rprintfu16(unsigned short data)
{
// print 16-bit hex value
rprintfu08(data>>8);
rprintfu08(data);
}
 
// *** rprintfu32 ***
// prints an unsigned 32-bit number in hex (8 digits)
void rprintfu32(unsigned long data)
{
// print 32-bit hex value
rprintfu16(data>>16);
rprintfu16(data);
}
 
// *** rprintfNum ***
// special printf for numbers only
// see formatting information below
// Print the number "n" in the given "base"
// using exactly "numDigits"
// print +/- if signed flag "isSigned" is TRUE
// use the character specified in "padchar" to pad extra characters
//
// Examples:
// uartPrintfNum(10, 6, TRUE, ' ', 1234); --> " +1234"
// uartPrintfNum(10, 6, FALSE, '0', 1234); --> "001234"
// uartPrintfNum(16, 6, FALSE, '.', 0x5AA5); --> "..5AA5"
void rprintfNum(char base, char numDigits, char isSigned, char padchar, long n)
{
// define a global HexChars or use line below
//static char HexChars[16] = "0123456789ABCDEF";
char *p, buf[32];
unsigned long x;
unsigned char count;
 
// prepare negative number
if( isSigned && (n < 0) )
{
x = -n;
}
else
{
x = n;
}
 
// setup little string buffer
count = (numDigits-1)-(isSigned?1:0);
p = buf + sizeof (buf);
*--p = '\0';
// force calculation of first digit
// (to prevent zero from not printing at all!!!)
*--p = hexchar(x%base); x /= base;
// calculate remaining digits
while(count--)
{
if(x != 0)
{
// calculate next digit
*--p = hexchar(x%base); x /= base;
}
else
{
// no more digits left, pad out to desired length
*--p = padchar;
}
}
 
// apply signed notation if requested
if( isSigned )
{
if(n < 0)
{
*--p = '-';
}
else if(n > 0)
{
*--p = '+';
}
else
{
*--p = ' ';
}
}
 
// print the string right-justified
count = numDigits;
while(count--)
{
rprintfChar(*p++);
}
}
 
#ifdef RPRINTF_FLOAT
// *** rprintfFloat ***
// floating-point print
void rprintfFloat(char numDigits, double x)
{
unsigned char firstplace = FALSE;
unsigned char negative;
unsigned char i, digit;
double place = 1.0;
// save sign
negative = (x<0);
// convert to absolute value
x = (x>0)?(x):(-x);
// find starting digit place
for(i=0; i<15; i++)
{
if((x/place) < 10.0)
break;
else
place *= 10.0;
}
// print polarity character
if(negative)
rprintfChar('-');
else
rprintfChar('+');
 
// print digits
for(i=0; i<numDigits; i++)
{
digit = (x/place);
 
if(digit | firstplace | (place == 1.0))
{
firstplace = TRUE;
rprintfChar(digit+0x30);
}
else
rprintfChar(' ');
if(place == 1.0)
{
rprintfChar('.');
}
x -= (digit*place);
place /= 10.0;
}
}
#endif
 
#ifdef RPRINTF_SIMPLE
// *** rprintf1RamRom ***
// called by rprintf() - does a simple printf (supports %d, %x, %c)
// Supports:
// %d - decimal
// %x - hex
// %c - character
int rprintf1RamRom(unsigned char stringInRom, const char *format, ...)
{
// simple printf routine
// define a global HexChars or use line below
//static char HexChars[16] = "0123456789ABCDEF";
char format_flag;
unsigned int u_val, div_val, base;
va_list ap;
 
va_start(ap, format);
for (;;)
{
while ((format_flag = READMEMBYTE(stringInRom,format++) ) != '%')
{ // Until '%' or '\0'
if (!format_flag)
{
va_end(ap);
return(0);
}
rprintfChar(format_flag);
}
 
switch (format_flag = READMEMBYTE(stringInRom,format++) )
{
case 'c': format_flag = va_arg(ap,int);
default: rprintfChar(format_flag); continue;
case 'd': base = 10; div_val = 10000; goto CONVERSION_LOOP;
// case 'x': base = 16; div_val = 0x10;
case 'x': base = 16; div_val = 0x1000;
 
CONVERSION_LOOP:
u_val = va_arg(ap,int);
if (format_flag == 'd')
{
if (((int)u_val) < 0)
{
u_val = - u_val;
rprintfChar('-');
}
while (div_val > 1 && div_val > u_val) div_val /= 10;
}
do
{
//rprintfChar(pgm_read_byte(HexChars+(u_val/div_val)));
rprintfu04(u_val/div_val);
u_val %= div_val;
div_val /= base;
} while (div_val);
}
}
va_end(ap);
}
#endif
 
 
#ifdef RPRINTF_COMPLEX
// *** rprintf2RamRom ***
// called by rprintf() - does a more powerful printf (supports %d, %u, %o, %x, %c, %s)
// Supports:
// %d - decimal
// %u - unsigned decimal
// %o - octal
// %x - hex
// %c - character
// %s - strings
// and the width,precision,padding modifiers
// **this printf does not support floating point numbers
int rprintf2RamRom(unsigned char stringInRom, const char *sfmt, ...)
{
register unsigned char *f, *bp;
register long l;
register unsigned long u;
register int i;
register int fmt;
register unsigned char pad = ' ';
int flush_left = 0, f_width = 0, prec = INF, hash = 0, do_long = 0;
int sign = 0;
 
va_list ap;
va_start(ap, sfmt);
 
f = (unsigned char *) sfmt;
 
for (; READMEMBYTE(stringInRom,f); f++)
{
if (READMEMBYTE(stringInRom,f) != '%')
{ // not a format character
// then just output the char
rprintfChar(READMEMBYTE(stringInRom,f));
}
else
{
f++; // if we have a "%" then skip it
if (READMEMBYTE(stringInRom,f) == '-')
{
flush_left = 1; // minus: flush left
f++;
}
if (READMEMBYTE(stringInRom,f) == '0'
|| READMEMBYTE(stringInRom,f) == '.')
{
// padding with 0 rather than blank
pad = '0';
f++;
}
if (READMEMBYTE(stringInRom,f) == '*')
{ // field width
f_width = va_arg(ap, int);
f++;
}
else if (Isdigit(READMEMBYTE(stringInRom,f)))
{
f_width = atoiRamRom(stringInRom, (char *) f);
while (Isdigit(READMEMBYTE(stringInRom,f)))
f++; // skip the digits
}
if (READMEMBYTE(stringInRom,f) == '.')
{ // precision
f++;
if (READMEMBYTE(stringInRom,f) == '*')
{
prec = va_arg(ap, int);
f++;
}
else if (Isdigit(READMEMBYTE(stringInRom,f)))
{
prec = atoiRamRom(stringInRom, (char *) f);
while (Isdigit(READMEMBYTE(stringInRom,f)))
f++; // skip the digits
}
}
if (READMEMBYTE(stringInRom,f) == '#')
{ // alternate form
hash = 1;
f++;
}
if (READMEMBYTE(stringInRom,f) == 'l')
{ // long format
do_long = 1;
f++;
}
 
fmt = READMEMBYTE(stringInRom,f);
bp = buf;
switch (fmt) { // do the formatting
case 'd': // 'd' signed decimal
if (do_long)
l = va_arg(ap, long);
else
l = (long) (va_arg(ap, int));
if (l < 0)
{
sign = 1;
l = -l;
}
do {
*bp++ = l % 10 + '0';
} while ((l /= 10) > 0);
if (sign)
*bp++ = '-';
f_width = f_width - (bp - buf);
if (!flush_left)
while (f_width-- > 0)
rprintfChar(pad);
for (bp--; bp >= buf; bp--)
rprintfChar(*bp);
if (flush_left)
while (f_width-- > 0)
rprintfChar(' ');
break;
case 'o': // 'o' octal number
case 'x': // 'x' hex number
case 'u': // 'u' unsigned decimal
if (do_long)
u = va_arg(ap, unsigned long);
else
u = (unsigned long) (va_arg(ap, unsigned));
if (fmt == 'u')
{ // unsigned decimal
do {
*bp++ = u % 10 + '0';
} while ((u /= 10) > 0);
}
else if (fmt == 'o')
{ // octal
do {
*bp++ = u % 8 + '0';
} while ((u /= 8) > 0);
if (hash)
*bp++ = '0';
}
else if (fmt == 'x')
{ // hex
do {
i = u % 16;
if (i < 10)
*bp++ = i + '0';
else
*bp++ = i - 10 + 'a';
} while ((u /= 16) > 0);
if (hash)
{
*bp++ = 'x';
*bp++ = '0';
}
}
i = f_width - (bp - buf);
if (!flush_left)
while (i-- > 0)
rprintfChar(pad);
for (bp--; bp >= buf; bp--)
rprintfChar((int) (*bp));
if (flush_left)
while (i-- > 0)
rprintfChar(' ');
break;
case 'c': // 'c' character
i = va_arg(ap, int);
rprintfChar((int) (i));
break;
case 's': // 's' string
bp = va_arg(ap, unsigned char *);
if (!bp)
bp = (unsigned char *) "(nil)";
f_width = f_width - strlen((char *) bp);
if (!flush_left)
while (f_width-- > 0)
rprintfChar(pad);
for (i = 0; *bp && i < prec; i++)
{
rprintfChar(*bp);
bp++;
}
if (flush_left)
while (f_width-- > 0)
rprintfChar(' ');
break;
case '%': // '%' character
rprintfChar('%');
break;
}
flush_left = 0, f_width = 0, prec = INF, hash = 0, do_long = 0;
sign = 0;
pad = ' ';
}
}
 
va_end(ap);
return 0;
}
 
unsigned char Isdigit(char c)
{
if((c >= 0x30) && (c <= 0x39))
return TRUE;
else
return FALSE;
}
 
int atoiRamRom(unsigned char stringInRom, char *str)
{
int num = 0;;
 
while(Isdigit(READMEMBYTE(stringInRom,str)))
{
num *= 10;
num += ((READMEMBYTE(stringInRom,str++)) - 0x30);
}
return num;
}
 
#endif
 
//******************************************************************************
// code below this line is commented out and can be ignored
//******************************************************************************
/*
char* sprintf(const char *sfmt, ...)
{
register unsigned char *f, *bp, *str;
register long l;
register unsigned long u;
register int i;
register int fmt;
register unsigned char pad = ' ';
int flush_left = 0, f_width = 0, prec = INF, hash = 0, do_long = 0;
int sign = 0;
 
va_list ap;
va_start(ap, sfmt);
 
str = bufstring;
f = (unsigned char *) sfmt;
 
for (; *f; f++)
{
if (*f != '%')
{ // not a format character
*str++ = (*f); // then just output the char
}
else
{
f++; // if we have a "%" then skip it
if (*f == '-')
{
flush_left = 1; // minus: flush left
f++;
}
if (*f == '0' || *f == '.')
{
// padding with 0 rather than blank
pad = '0';
f++;
}
if (*f == '*')
{ // field width
f_width = va_arg(ap, int);
f++;
}
else if (Isdigit(*f))
{
f_width = atoi((char *) f);
while (Isdigit(*f))
f++; // skip the digits
}
if (*f == '.')
{ // precision
f++;
if (*f == '*')
{
prec = va_arg(ap, int);
f++;
}
else if (Isdigit(*f))
{
prec = atoi((char *) f);
while (Isdigit(*f))
f++; // skip the digits
}
}
if (*f == '#')
{ // alternate form
hash = 1;
f++;
}
if (*f == 'l')
{ // long format
do_long = 1;
f++;
}
 
fmt = *f;
bp = buf;
switch (fmt) { // do the formatting
case 'd': // 'd' signed decimal
if (do_long)
l = va_arg(ap, long);
else
l = (long) (va_arg(ap, int));
if (l < 0)
{
sign = 1;
l = -l;
}
do {
*bp++ = l % 10 + '0';
} while ((l /= 10) > 0);
if (sign)
*bp++ = '-';
f_width = f_width - (bp - buf);
if (!flush_left)
while (f_width-- > 0)
*str++ = (pad);
for (bp--; bp >= buf; bp--)
*str++ = (*bp);
if (flush_left)
while (f_width-- > 0)
*str++ = (' ');
break;
case 'o': // 'o' octal number
case 'x': // 'x' hex number
case 'u': // 'u' unsigned decimal
if (do_long)
u = va_arg(ap, unsigned long);
else
u = (unsigned long) (va_arg(ap, unsigned));
if (fmt == 'u')
{ // unsigned decimal
do {
*bp++ = u % 10 + '0';
} while ((u /= 10) > 0);
}
else if (fmt == 'o')
{ // octal
do {
*bp++ = u % 8 + '0';
} while ((u /= 8) > 0);
if (hash)
*bp++ = '0';
}
else if (fmt == 'x')
{ // hex
do {
i = u % 16;
if (i < 10)
*bp++ = i + '0';
else
*bp++ = i - 10 + 'a';
} while ((u /= 16) > 0);
if (hash)
{
*bp++ = 'x';
*bp++ = '0';
}
}
i = f_width - (bp - buf);
if (!flush_left)
while (i-- > 0)
*str++ = (pad);
for (bp--; bp >= buf; bp--)
*str++ = ((int) (*bp));
if (flush_left)
while (i-- > 0)
*str++ = (' ');
break;
case 'c': // 'c' character
i = va_arg(ap, int);
*str++ = ((int) (i));
break;
case 's': // 's' string
bp = va_arg(ap, unsigned char *);
if (!bp)
bp = (unsigned char *) "(nil)";
f_width = f_width - strlen((char *) bp);
if (!flush_left)
while (f_width-- > 0)
*str++ = (pad);
for (i = 0; *bp && i < prec; i++)
{
*str++ = (*bp);
bp++;
}
if (flush_left)
while (f_width-- > 0)
*str++ = (' ');
break;
case '%': // '%' character
*str++ = ('%');
break;
}
flush_left = 0, f_width = 0, prec = INF, hash = 0, do_long = 0;
sign = 0;
pad = ' ';
}
}
 
va_end(ap);
// terminate string with null
*str++ = '\0';
return bufstring;
}
 
*/
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/akcelerometr/rprintf.h
0,0 → 1,191
/*! \file rprintf.h \brief printf routine and associated routines. */
//****************************************************************************
//
// File Name : 'rprintf.h'
// Title : printf routine and associated routines
// Author : Pascal Stang - Copyright (C) 2000-2002
// Created : 2000.12.26
// Revised : 2003.5.1
// Version : 1.0
// Target MCU : Atmel AVR series and other targets
// Editor Tabs : 4
//
// NOTE: This code is currently below version 1.0, and therefore is considered
// to be lacking in some functionality or documentation, or may not be fully
// tested. Nonetheless, you can expect most functions to work.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
/// \ingroup general
/// \defgroup rprintf printf() Function Library (rprintf.c)
/// \code #include "rprintf.h" \endcode
/// \par Overview
/// The rprintf function library provides a simplified (reduced) version of
/// the common C printf() function.� See the code files for details about
/// which printf features are supported.� Also in this library are a
/// variety of functions for fast printing of certain common data types
/// (variable types).� Functions include print string from RAM, print
/// string from ROM, print string snippet, print hex byte/short/long, and
/// a custom-formatted number print, as well as an optional floating-point
/// print routine.
///
/// \note All output from the rprintf library can be directed to any device
/// or software which accepts characters.� This means that rprintf output
/// can be sent to the UART (serial port) or can be used with the LCD
/// display libraries to print formatted text on the screen.
//
//****************************************************************************
//@{
 
#ifndef RPRINTF_H
#define RPRINTF_H
 
// needed for use of PSTR below
#include <avr/pgmspace.h>
 
// configuration
// defining RPRINTF_SIMPLE will compile a smaller, simpler, and faster printf() function
// defining RPRINTF_COMPLEX will compile a larger, more capable, and slower printf() function
#ifndef RPRINTF_COMPLEX
#define RPRINTF_SIMPLE
#endif
 
// Define RPRINTF_FLOAT to enable the floating-point printf function: rprintfFloat()
// (adds +4600bytes or 2.2Kwords of code)
 
// defines/constants
#define STRING_IN_RAM 0
#define STRING_IN_ROM 1
 
// make a putchar for those that are used to using it
//#define putchar(c) rprintfChar(c);
 
// functions
 
//! Initializes the rprintf library for an output stream.
/// You must call this initializer once before using any other rprintf function.
/// The argument must be a character stream output function.
void rprintfInit(void (*putchar_func)(unsigned char c));
 
//! prints a single character to the current output device
void rprintfChar(unsigned char c);
 
//! prints a null-terminated string stored in RAM
void rprintfStr(char str[]);
 
//! Prints a section of a string stored in RAM.
/// Begins printing at position indicated by <start>,
/// and prints number of characters indicated by <len>.
void rprintfStrLen(char str[], unsigned int start, unsigned int len);
 
//! prints a string stored in program rom
/// \note This function does not actually store your string in
/// program rom, but merely reads it assuming you stored it properly.
void rprintfProgStr(const prog_char str[]);
 
//! Using the function rprintfProgStrM(...) automatically causes
/// your string to be stored in ROM, thereby not wasting precious RAM.
/// Example usage:
/// \code
/// rprintfProgStrM("Hello, this string is stored in program rom");
/// \endcode
#define rprintfProgStrM(string) (rprintfProgStr(PSTR(string)))
 
//! Prints a carriage-return and line-feed.
/// Useful when printing to serial ports/terminals.
void rprintfCRLF(void);
 
// Prints the number contained in "data" in hex format
// u04,u08,u16,and u32 functions handle 4,8,16,or 32 bits respectively
void rprintfu04(unsigned char data); ///< Print 4-bit hex number. Outputs a single hex character.
void rprintfu08(unsigned char data); ///< Print 8-bit hex number. Outputs two hex characters.
void rprintfu16(unsigned short data); ///< Print 16-bit hex number. Outputs four hex characters.
void rprintfu32(unsigned long data); ///< Print 32-bit hex number. Outputs eight hex characters.
 
//! A flexible integer-number printing routine.
/// Print the number "n" in the given "base", using exactly "numDigits".
/// Print +/- if signed flag "isSigned" is TRUE.
/// The character specified in "padchar" will be used to pad extra characters.
///
/// Examples:
/// \code
/// uartPrintfNum(10, 6, TRUE, ' ', 1234); --> " +1234"
/// uartPrintfNum(10, 6, FALSE, '0', 1234); --> "001234"
/// uartPrintfNum(16, 6, FALSE, '.', 0x5AA5); --> "..5AA5"
/// \endcode
void rprintfNum(char base, char numDigits, char isSigned, char padchar, long n);
 
#ifdef RPRINTF_FLOAT
//! floating-point print routine
void rprintfFloat(char numDigits, double x);
#endif
 
// NOTE: Below you'll see the function prototypes of rprintf1RamRom and
// rprintf2RamRom. rprintf1RamRom and rprintf2RamRom are both reduced versions
// of the regular C printf() command. However, they are modified to be able
// to read their text/format strings from RAM or ROM in the Atmel microprocessors.
// Unless you really intend to, do not use the "RamRom" versions of the functions
// directly. Instead use the #defined function versions:
//
// printfx("text/format",args) ...to keep your text/format string stored in RAM
// - or -
// printfxROM("text/format",args) ...to keep your text/format string stored in ROM
//
// where x is either 1 or 2 for the simple or more powerful version of printf()
//
// Since there is much more ROM than RAM available in the Atmel microprocessors,
// and nearly all text/format strings are constant (never change in the course
// of the program), you should try to use the ROM printf version exclusively.
// This will ensure you leave as much RAM as possible for program variables and
// data.
 
//! \fn int rprintf(const char *format, ...);
/// A reduced substitute for the usual C printf() function.
/// This function actually points to either rprintf1RamRom or rprintf2RamRom
/// depending on the user's selection. Rprintf1 is a simple small fast print
/// routine while rprintf2 is larger and slower but more capable. To choose
/// the routine you would like to use, define either RPRINTF_SIMPLE or
/// RPRINTF_COMPLEX in global.h.
 
#ifdef RPRINTF_SIMPLE
//! A simple printf routine.
/// Called by rprintf() - does a simple printf (supports %d, %x, %c).
/// Supports:
/// - %d - decimal
/// - %x - hex
/// - %c - character
int rprintf1RamRom(unsigned char stringInRom, const char *format, ...);
// #defines for RAM or ROM operation
#define rprintf1(format, args...) rprintf1RamRom(STRING_IN_ROM, PSTR(format), ## args)
#define rprintf1RAM(format, args...) rprintf1RamRom(STRING_IN_RAM, format, ## args)
 
// *** Default rprintf(...) ***
// this next line determines what the the basic rprintf() defaults to:
#define rprintf(format, args...) rprintf1RamRom(STRING_IN_ROM, PSTR(format), ## args)
#endif
 
#ifdef RPRINTF_COMPLEX
//! A more powerful printf routine.
/// Called by rprintf() - does a more powerful printf (supports %d, %u, %o, %x, %c, %s).
/// Supports:
/// - %d - decimal
/// - %u - unsigned decimal
/// - %o - octal
/// - %x - hex
/// - %c - character
/// - %s - strings
/// - and the width,precision,padding modifiers
/// \note This printf does not support floating point numbers.
int rprintf2RamRom(unsigned char stringInRom, const char *sfmt, ...);
// #defines for RAM or ROM operation
#define rprintf2(format, args...) rprintf2RamRom(STRING_IN_ROM, format, ## args)
#define rprintf2RAM(format, args...) rprintf2RamRom(STRING_IN_RAM, format, ## args)
 
// *** Default rprintf(...) ***
// this next line determines what the the basic rprintf() defaults to:
#define rprintf(format, args...) rprintf2RamRom(STRING_IN_ROM, PSTR(format), ## args)
#endif
 
#endif
//@}
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/akcelerometr/timer.c
0,0 → 1,469
/*! \file timer.c \brief System Timer function library. */
//*****************************************************************************
//
// File Name : 'timer.c'
// Title : System Timer function library
// Author : Pascal Stang - Copyright (C) 2000-2002
// Created : 11/22/2000
// Revised : 07/09/2003
// Version : 1.1
// Target MCU : Atmel AVR Series
// Editor Tabs : 4
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <avr/sleep.h>
 
#include "global.h"
#include "timer.h"
 
#include "rprintf.h"
 
// Program ROM constants
// the prescale division values stored in order of timer control register index
// STOP, CLK, CLK/8, CLK/64, CLK/256, CLK/1024
unsigned short __attribute__ ((progmem)) TimerPrescaleFactor[] = {0,1,8,64,256,1024};
// the prescale division values stored in order of timer control register index
// STOP, CLK, CLK/8, CLK/32, CLK/64, CLK/128, CLK/256, CLK/1024
unsigned short __attribute__ ((progmem)) TimerRTCPrescaleFactor[] = {0,1,8,32,64,128,256,1024};
 
// Global variables
// time registers
volatile unsigned long TimerPauseReg;
volatile unsigned long Timer0Reg0;
volatile unsigned long Timer2Reg0;
 
typedef void (*voidFuncPtr)(void);
volatile static voidFuncPtr TimerIntFunc[TIMER_NUM_INTERRUPTS];
 
// delay for a minimum of <us> microseconds
// the time resolution is dependent on the time the loop takes
// e.g. with 4Mhz and 5 cycles per loop, the resolution is 1.25 us
void delay_us(unsigned short time_us)
{
unsigned short delay_loops;
register unsigned short i;
 
delay_loops = (time_us+3)/5*CYCLES_PER_US; // +3 for rounding up (dirty)
 
// one loop takes 5 cpu cycles
for (i=0; i < delay_loops; i++) {};
}
/*
void delay_ms(unsigned char time_ms)
{
unsigned short delay_count = F_CPU / 4000;
 
unsigned short cnt;
asm volatile ("\n"
"L_dl1%=:\n\t"
"mov %A0, %A2\n\t"
"mov %B0, %B2\n"
"L_dl2%=:\n\t"
"sbiw %A0, 1\n\t"
"brne L_dl2%=\n\t"
"dec %1\n\t" "brne L_dl1%=\n\t":"=&w" (cnt)
:"r"(time_ms), "r"((unsigned short) (delay_count))
);
}
*/
void timerInit(void)
{
u08 intNum;
// detach all user functions from interrupts
for(intNum=0; intNum<TIMER_NUM_INTERRUPTS; intNum++)
timerDetach(intNum);
 
// initialize all timers
timer0Init();
timer1Init();
#ifdef TCNT2 // support timer2 only if it exists
timer2Init();
#endif
// enable interrupts
sei();
}
 
void timer0Init()
{
// initialize timer 0
timer0SetPrescaler( TIMER0PRESCALE ); // set prescaler
outb(TCNT0, 0); // reset TCNT0
sbi(TIMSK, TOIE0); // enable TCNT0 overflow interrupt
 
timer0ClearOverflowCount(); // initialize time registers
}
 
void timer1Init(void)
{
// initialize timer 1
timer1SetPrescaler( TIMER1PRESCALE ); // set prescaler
outb(TCNT1H, 0); // reset TCNT1
outb(TCNT1L, 0);
sbi(TIMSK, TOIE1); // enable TCNT1 overflow
}
 
#ifdef TCNT2 // support timer2 only if it exists
void timer2Init(void)
{
// initialize timer 2
timer2SetPrescaler( TIMER2PRESCALE ); // set prescaler
outb(TCNT2, 0); // reset TCNT2
sbi(TIMSK, TOIE2); // enable TCNT2 overflow
 
timer2ClearOverflowCount(); // initialize time registers
}
#endif
 
void timer0SetPrescaler(u08 prescale)
{
// set prescaler on timer 0
outb(TCCR0, (inb(TCCR0) & ~TIMER_PRESCALE_MASK) | prescale);
}
 
void timer1SetPrescaler(u08 prescale)
{
// set prescaler on timer 1
outb(TCCR1B, (inb(TCCR1B) & ~TIMER_PRESCALE_MASK) | prescale);
}
 
#ifdef TCNT2 // support timer2 only if it exists
void timer2SetPrescaler(u08 prescale)
{
// set prescaler on timer 2
outb(TCCR2, (inb(TCCR2) & ~TIMER_PRESCALE_MASK) | prescale);
}
#endif
 
u16 timer0GetPrescaler(void)
{
// get the current prescaler setting
return (pgm_read_word(TimerPrescaleFactor+(inb(TCCR0) & TIMER_PRESCALE_MASK)));
}
 
u16 timer1GetPrescaler(void)
{
// get the current prescaler setting
return (pgm_read_word(TimerPrescaleFactor+(inb(TCCR1B) & TIMER_PRESCALE_MASK)));
}
 
#ifdef TCNT2 // support timer2 only if it exists
u16 timer2GetPrescaler(void)
{
//TODO: can we assume for all 3-timer AVR processors,
// that timer2 is the RTC timer?
 
// get the current prescaler setting
return (pgm_read_word(TimerRTCPrescaleFactor+(inb(TCCR2) & TIMER_PRESCALE_MASK)));
}
#endif
 
void timerAttach(u08 interruptNum, void (*userFunc)(void) )
{
// make sure the interrupt number is within bounds
if(interruptNum < TIMER_NUM_INTERRUPTS)
{
// set the interrupt function to run
// the supplied user's function
TimerIntFunc[interruptNum] = userFunc;
}
}
 
void timerDetach(u08 interruptNum)
{
// make sure the interrupt number is within bounds
if(interruptNum < TIMER_NUM_INTERRUPTS)
{
// set the interrupt function to run nothing
TimerIntFunc[interruptNum] = 0;
}
}
/*
u32 timerMsToTics(u16 ms)
{
// calculate the prescaler division rate
u16 prescaleDiv = 1<<(pgm_read_byte(TimerPrescaleFactor+inb(TCCR0)));
// calculate the number of timer tics in x milliseconds
return (ms*(F_CPU/(prescaleDiv*256)))/1000;
}
 
u16 timerTicsToMs(u32 tics)
{
// calculate the prescaler division rate
u16 prescaleDiv = 1<<(pgm_read_byte(TimerPrescaleFactor+inb(TCCR0)));
// calculate the number of milliseconds in x timer tics
return (tics*1000*(prescaleDiv*256))/F_CPU;
}
*/
void timerPause(unsigned short pause_ms)
{
// pauses for exactly <pause_ms> number of milliseconds
u08 timerThres;
u32 ticRateHz;
u32 pause;
 
// capture current pause timer value
timerThres = inb(TCNT0);
// reset pause timer overflow count
TimerPauseReg = 0;
// calculate delay for [pause_ms] milliseconds
// prescaler division = 1<<(pgm_read_byte(TimerPrescaleFactor+inb(TCCR0)))
ticRateHz = F_CPU/timer0GetPrescaler();
// precision management
// prevent overflow and precision underflow
// -could add more conditions to improve accuracy
if( ((ticRateHz < 429497) && (pause_ms <= 10000)) )
pause = (pause_ms*ticRateHz)/1000;
else
pause = pause_ms*(ticRateHz/1000);
 
// loop until time expires
while( ((TimerPauseReg<<8) | inb(TCNT0)) < (pause+timerThres) )
{
if( TimerPauseReg < (pause>>8));
{
// save power by idling the processor
set_sleep_mode(SLEEP_MODE_IDLE);
sleep_mode();
}
}
 
/* old inaccurate code, for reference
// calculate delay for [pause_ms] milliseconds
u16 prescaleDiv = 1<<(pgm_read_byte(TimerPrescaleFactor+inb(TCCR0)));
u32 pause = (pause_ms*(F_CPU/(prescaleDiv*256)))/1000;
TimerPauseReg = 0;
while(TimerPauseReg < pause);
 
*/
}
 
void timer0ClearOverflowCount(void)
{
// clear the timer overflow counter registers
Timer0Reg0 = 0; // initialize time registers
}
 
long timer0GetOverflowCount(void)
{
// return the current timer overflow count
// (this is since the last timer0ClearOverflowCount() command was called)
return Timer0Reg0;
}
 
#ifdef TCNT2 // support timer2 only if it exists
void timer2ClearOverflowCount(void)
{
// clear the timer overflow counter registers
Timer2Reg0 = 0; // initialize time registers
}
 
long timer2GetOverflowCount(void)
{
// return the current timer overflow count
// (this is since the last timer2ClearOverflowCount() command was called)
return Timer2Reg0;
}
#endif
 
void timer1PWMInit(u08 bitRes)
{
// configures timer1 for use with PWM output
// on OC1A and OC1B pins
 
// enable timer1 as 8,9,10bit PWM
if(bitRes == 9)
{ // 9bit mode
sbi(TCCR1A,PWM11);
cbi(TCCR1A,PWM10);
}
else if( bitRes == 10 )
{ // 10bit mode
sbi(TCCR1A,PWM11);
sbi(TCCR1A,PWM10);
}
else
{ // default 8bit mode
cbi(TCCR1A,PWM11);
sbi(TCCR1A,PWM10);
}
 
// clear output compare value A
outb(OCR1AH, 0);
outb(OCR1AL, 0);
// clear output compare value B
outb(OCR1BH, 0);
outb(OCR1BL, 0);
}
 
#ifdef WGM10
// include support for arbitrary top-count PWM
// on new AVR processors that support it
void timer1PWMInitICR(u16 topcount)
{
// set PWM mode with ICR top-count
cbi(TCCR1A,WGM10);
sbi(TCCR1A,WGM11);
sbi(TCCR1B,WGM12);
sbi(TCCR1B,WGM13);
// set top count value
ICR1 = topcount;
// clear output compare value A
OCR1A = 0;
// clear output compare value B
OCR1B = 0;
 
}
#endif
 
void timer1PWMOff(void)
{
// turn off timer1 PWM mode
cbi(TCCR1A,PWM11);
cbi(TCCR1A,PWM10);
// set PWM1A/B (OutputCompare action) to none
timer1PWMAOff();
timer1PWMBOff();
}
 
void timer1PWMAOn(void)
{
// turn on channel A (OC1A) PWM output
// set OC1A as non-inverted PWM
sbi(TCCR1A,COM1A1);
cbi(TCCR1A,COM1A0);
}
 
void timer1PWMBOn(void)
{
// turn on channel B (OC1B) PWM output
// set OC1B as non-inverted PWM
sbi(TCCR1A,COM1B1);
cbi(TCCR1A,COM1B0);
}
 
void timer1PWMAOff(void)
{
// turn off channel A (OC1A) PWM output
// set OC1A (OutputCompare action) to none
cbi(TCCR1A,COM1A1);
cbi(TCCR1A,COM1A0);
}
 
void timer1PWMBOff(void)
{
// turn off channel B (OC1B) PWM output
// set OC1B (OutputCompare action) to none
cbi(TCCR1A,COM1B1);
cbi(TCCR1A,COM1B0);
}
 
void timer1PWMASet(u16 pwmDuty)
{
// set PWM (output compare) duty for channel A
// this PWM output is generated on OC1A pin
// NOTE: pwmDuty should be in the range 0-255 for 8bit PWM
// pwmDuty should be in the range 0-511 for 9bit PWM
// pwmDuty should be in the range 0-1023 for 10bit PWM
//outp( (pwmDuty>>8), OCR1AH); // set the high 8bits of OCR1A
//outp( (pwmDuty&0x00FF), OCR1AL); // set the low 8bits of OCR1A
OCR1A = pwmDuty;
}
 
void timer1PWMBSet(u16 pwmDuty)
{
// set PWM (output compare) duty for channel B
// this PWM output is generated on OC1B pin
// NOTE: pwmDuty should be in the range 0-255 for 8bit PWM
// pwmDuty should be in the range 0-511 for 9bit PWM
// pwmDuty should be in the range 0-1023 for 10bit PWM
//outp( (pwmDuty>>8), OCR1BH); // set the high 8bits of OCR1B
//outp( (pwmDuty&0x00FF), OCR1BL); // set the low 8bits of OCR1B
OCR1B = pwmDuty;
}
 
//! Interrupt handler for tcnt0 overflow interrupt
TIMER_INTERRUPT_HANDLER(SIG_OVERFLOW0)
{
Timer0Reg0++; // increment low-order counter
 
// increment pause counter
TimerPauseReg++;
 
// if a user function is defined, execute it too
if(TimerIntFunc[TIMER0OVERFLOW_INT])
TimerIntFunc[TIMER0OVERFLOW_INT]();
}
 
//! Interrupt handler for tcnt1 overflow interrupt
TIMER_INTERRUPT_HANDLER(SIG_OVERFLOW1)
{
// if a user function is defined, execute it
if(TimerIntFunc[TIMER1OVERFLOW_INT])
TimerIntFunc[TIMER1OVERFLOW_INT]();
}
 
#ifdef TCNT2 // support timer2 only if it exists
//! Interrupt handler for tcnt2 overflow interrupt
TIMER_INTERRUPT_HANDLER(SIG_OVERFLOW2)
{
Timer2Reg0++; // increment low-order counter
 
// if a user function is defined, execute it
if(TimerIntFunc[TIMER2OVERFLOW_INT])
TimerIntFunc[TIMER2OVERFLOW_INT]();
}
#endif
 
#ifdef OCR0
// include support for Output Compare 0 for new AVR processors that support it
//! Interrupt handler for OutputCompare0 match (OC0) interrupt
TIMER_INTERRUPT_HANDLER(SIG_OUTPUT_COMPARE0)
{
// if a user function is defined, execute it
if(TimerIntFunc[TIMER0OUTCOMPARE_INT])
TimerIntFunc[TIMER0OUTCOMPARE_INT]();
}
#endif
 
//! Interrupt handler for CutputCompare1A match (OC1A) interrupt
TIMER_INTERRUPT_HANDLER(SIG_OUTPUT_COMPARE1A)
{
// if a user function is defined, execute it
if(TimerIntFunc[TIMER1OUTCOMPAREA_INT])
TimerIntFunc[TIMER1OUTCOMPAREA_INT]();
}
 
//! Interrupt handler for OutputCompare1B match (OC1B) interrupt
TIMER_INTERRUPT_HANDLER(SIG_OUTPUT_COMPARE1B)
{
// if a user function is defined, execute it
if(TimerIntFunc[TIMER1OUTCOMPAREB_INT])
TimerIntFunc[TIMER1OUTCOMPAREB_INT]();
}
 
//! Interrupt handler for InputCapture1 (IC1) interrupt
TIMER_INTERRUPT_HANDLER(SIG_INPUT_CAPTURE1)
{
// if a user function is defined, execute it
if(TimerIntFunc[TIMER1INPUTCAPTURE_INT])
TimerIntFunc[TIMER1INPUTCAPTURE_INT]();
}
 
//! Interrupt handler for OutputCompare2 match (OC2) interrupt
TIMER_INTERRUPT_HANDLER(SIG_OUTPUT_COMPARE2)
{
// if a user function is defined, execute it
if(TimerIntFunc[TIMER2OUTCOMPARE_INT])
TimerIntFunc[TIMER2OUTCOMPARE_INT]();
}
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/akcelerometr/timer.h
0,0 → 1,314
/*! \file timer.h \brief System Timer function library. */
//*****************************************************************************
//
// File Name : 'timer.h'
// Title : System Timer function library
// Author : Pascal Stang - Copyright (C) 2000-2002
// Created : 11/22/2000
// Revised : 02/10/2003
// Version : 1.1
// Target MCU : Atmel AVR Series
// Editor Tabs : 4
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
/// \ingroup driver_avr
/// \defgroup timer Timer Function Library (timer.c)
/// \code #include "timer.h" \endcode
/// \par Overview
/// This library provides functions for use with the timers internal
/// to the AVR processors. Functions include initialization, set prescaler,
/// calibrated pause function (in milliseconds), attaching and detaching of
/// user functions to interrupts, overflow counters, PWM. Arbitrary
/// frequency generation has been moved to the Pulse Library.
///
/// \par About Timers
/// The Atmel AVR-series processors each contain at least one
/// hardware timer/counter. Many of the processors contain 2 or 3
/// timers. Generally speaking, a timer is a hardware counter inside
/// the processor which counts at a rate related to the main CPU clock
/// frequency. Because the counter value increasing (counting up) at
/// a precise rate, we can use it as a timer to create or measure
/// precise delays, schedule events, or generate signals of a certain
/// frequency or pulse-width.
/// \par
/// As an example, the ATmega163 processor has 3 timer/counters.
/// Timer0, Timer1, and Timer2 are 8, 16, and 8 bits wide respectively.
/// This means that they overflow, or roll over back to zero, at a
/// count value of 256 for 8bits or 65536 for 16bits. A prescaler is
/// avaiable for each timer, and the prescaler allows you to pre-divide
/// the main CPU clock rate down to a slower speed before feeding it to
/// the counting input of a timer. For example, if the CPU clock
/// frequency is 3.69MHz, and Timer0's prescaler is set to divide-by-8,
/// then Timer0 will "tic" at 3690000/8 = 461250Hz. Because Timer0 is
/// an 8bit timer, it will count to 256 in just 256/461250Hz = 0.555ms.
/// In fact, when it hits 255, it will overflow and start again at
/// zero. In this case, Timer0 will overflow 461250/256 = 1801.76
/// times per second.
/// \par
/// Timer0 can be used a number of ways simultaneously. First, the
/// value of the timer can be read by accessing the CPU register \c TCNT0.
/// We could, for example, figure out how long it takes to execute a
/// C command by recording the value of \c TCNT0 before and after
/// execution, then subtract (after-before) = time elapsed. Or we can
/// enable the overflow interrupt which goes off every time T0
/// overflows and count out longer delays (multiple overflows), or
/// execute a special periodic function at every overflow.
/// \par
/// The other timers (Timer1 and Timer2) offer all the abilities of
/// Timer0 and many more features. Both T1 and T2 can operate as
/// general-purpose timers, but T1 has special hardware allowing it to
/// generate PWM signals, while T2 is specially designed to help count
/// out real time (like hours, minutes, seconds). See the
/// Timer/Counter section of the processor datasheet for more info.
///
//*****************************************************************************
//@{
 
#ifndef TIMER_H
#define TIMER_H
 
#include "global.h"
 
// constants/macros/typdefs
 
// processor compatibility fixes
#ifdef __AVR_ATmega323__
// redefinition for the Mega323
#define CTC1 CTC10
#endif
#ifndef PWM10
// mega128 PWM bits
#define PWM10 WGM10
#define PWM11 WGM11
#endif
 
 
// Timer/clock prescaler values and timer overflow rates
// tics = rate at which the timer counts up
// 8bitoverflow = rate at which the timer overflows 8bits (or reaches 256)
// 16bit [overflow] = rate at which the timer overflows 16bits (65536)
//
// overflows can be used to generate periodic interrupts
//
// for 8MHz crystal
// 0 = STOP (Timer not counting)
// 1 = CLOCK tics= 8MHz 8bitoverflow= 31250Hz 16bit= 122.070Hz
// 2 = CLOCK/8 tics= 1MHz 8bitoverflow= 3906.25Hz 16bit= 15.259Hz
// 3 = CLOCK/64 tics= 125kHz 8bitoverflow= 488.28Hz 16bit= 1.907Hz
// 4 = CLOCK/256 tics= 31250Hz 8bitoverflow= 122.07Hz 16bit= 0.477Hz
// 5 = CLOCK/1024 tics= 7812.5Hz 8bitoverflow= 30.52Hz 16bit= 0.119Hz
// 6 = External Clock on T(x) pin (falling edge)
// 7 = External Clock on T(x) pin (rising edge)
 
// for 4MHz crystal
// 0 = STOP (Timer not counting)
// 1 = CLOCK tics= 4MHz 8bitoverflow= 15625Hz 16bit= 61.035Hz
// 2 = CLOCK/8 tics= 500kHz 8bitoverflow= 1953.125Hz 16bit= 7.629Hz
// 3 = CLOCK/64 tics= 62500Hz 8bitoverflow= 244.141Hz 16bit= 0.954Hz
// 4 = CLOCK/256 tics= 15625Hz 8bitoverflow= 61.035Hz 16bit= 0.238Hz
// 5 = CLOCK/1024 tics= 3906.25Hz 8bitoverflow= 15.259Hz 16bit= 0.060Hz
// 6 = External Clock on T(x) pin (falling edge)
// 7 = External Clock on T(x) pin (rising edge)
 
// for 3.69MHz crystal
// 0 = STOP (Timer not counting)
// 1 = CLOCK tics= 3.69MHz 8bitoverflow= 14414Hz 16bit= 56.304Hz
// 2 = CLOCK/8 tics= 461250Hz 8bitoverflow= 1801.758Hz 16bit= 7.038Hz
// 3 = CLOCK/64 tics= 57625.25Hz 8bitoverflow= 225.220Hz 16bit= 0.880Hz
// 4 = CLOCK/256 tics= 14414.063Hz 8bitoverflow= 56.305Hz 16bit= 0.220Hz
// 5 = CLOCK/1024 tics= 3603.516Hz 8bitoverflow= 14.076Hz 16bit= 0.055Hz
// 6 = External Clock on T(x) pin (falling edge)
// 7 = External Clock on T(x) pin (rising edge)
 
// for 32.768KHz crystal on timer 2 (use for real-time clock)
// 0 = STOP
// 1 = CLOCK tics= 32.768kHz 8bitoverflow= 128Hz
// 2 = CLOCK/8 tics= 4096kHz 8bitoverflow= 16Hz
// 3 = CLOCK/32 tics= 1024kHz 8bitoverflow= 4Hz
// 4 = CLOCK/64 tics= 512Hz 8bitoverflow= 2Hz
// 5 = CLOCK/128 tics= 256Hz 8bitoverflow= 1Hz
// 6 = CLOCK/256 tics= 128Hz 8bitoverflow= 0.5Hz
// 7 = CLOCK/1024 tics= 32Hz 8bitoverflow= 0.125Hz
 
#define TIMER_CLK_STOP 0x00 ///< Timer Stopped
#define TIMER_CLK_DIV1 0x01 ///< Timer clocked at F_CPU
#define TIMER_CLK_DIV8 0x02 ///< Timer clocked at F_CPU/8
#define TIMER_CLK_DIV64 0x03 ///< Timer clocked at F_CPU/64
#define TIMER_CLK_DIV256 0x04 ///< Timer clocked at F_CPU/256
#define TIMER_CLK_DIV1024 0x05 ///< Timer clocked at F_CPU/1024
#define TIMER_CLK_T_FALL 0x06 ///< Timer clocked at T falling edge
#define TIMER_CLK_T_RISE 0x07 ///< Timer clocked at T rising edge
#define TIMER_PRESCALE_MASK 0x07 ///< Timer Prescaler Bit-Mask
 
#define TIMERRTC_CLK_STOP 0x00 ///< RTC Timer Stopped
#define TIMERRTC_CLK_DIV1 0x01 ///< RTC Timer clocked at F_CPU
#define TIMERRTC_CLK_DIV8 0x02 ///< RTC Timer clocked at F_CPU/8
#define TIMERRTC_CLK_DIV32 0x03 ///< RTC Timer clocked at F_CPU/32
#define TIMERRTC_CLK_DIV64 0x04 ///< RTC Timer clocked at F_CPU/64
#define TIMERRTC_CLK_DIV128 0x05 ///< RTC Timer clocked at F_CPU/128
#define TIMERRTC_CLK_DIV256 0x06 ///< RTC Timer clocked at F_CPU/256
#define TIMERRTC_CLK_DIV1024 0x07 ///< RTC Timer clocked at F_CPU/1024
#define TIMERRTC_PRESCALE_MASK 0x07 ///< RTC Timer Prescaler Bit-Mask
 
// default prescale settings for the timers
// these settings are applied when you call
// timerInit or any of the timer<x>Init
#define TIMER0PRESCALE TIMER_CLK_DIV8 ///< timer 0 prescaler default
#define TIMER1PRESCALE TIMER_CLK_DIV64 ///< timer 1 prescaler default
#define TIMER2PRESCALE TIMERRTC_CLK_DIV64 ///< timer 2 prescaler default
 
// interrupt macros for attaching user functions to timer interrupts
// use these with timerAttach( intNum, function )
#define TIMER0OVERFLOW_INT 0
#define TIMER1OVERFLOW_INT 1
#define TIMER1OUTCOMPAREA_INT 2
#define TIMER1OUTCOMPAREB_INT 3
#define TIMER1INPUTCAPTURE_INT 4
#define TIMER2OVERFLOW_INT 5
#define TIMER2OUTCOMPARE_INT 6
#ifdef OCR0 // for processors that support output compare on Timer0
#define TIMER0OUTCOMPARE_INT 7
#define TIMER_NUM_INTERRUPTS 8
#else
#define TIMER_NUM_INTERRUPTS 7
#endif
 
// default type of interrupt handler to use for timers
// *do not change unless you know what you're doing
// Value may be SIGNAL or INTERRUPT
#ifndef TIMER_INTERRUPT_HANDLER
#define TIMER_INTERRUPT_HANDLER SIGNAL
#endif
 
// functions
#define delay delay_us
#define delay_ms timerPause
void delay_us(unsigned short time_us);
 
//! initializes timing system (all timers)
// runs all timer init functions
// sets all timers to default prescale values #defined in systimer.c
void timerInit(void);
 
// default initialization routines for each timer
void timer0Init(void); ///< initialize timer0
void timer1Init(void); ///< initialize timer1
#ifdef TCNT2 // support timer2 only if it exists
void timer2Init(void); ///< initialize timer2
#endif
 
// Clock prescaler set/get commands for each timer/counter
// For setting the prescaler, you should use one of the #defines
// above like TIMER_CLK_DIVx, where [x] is the division rate
// you want.
// When getting the current prescaler setting, the return value
// will be the [x] division value currently set.
void timer0SetPrescaler(u08 prescale); ///< set timer0 prescaler
u16 timer0GetPrescaler(void); ///< get timer0 prescaler
void timer1SetPrescaler(u08 prescale); ///< set timer1 prescaler
u16 timer1GetPrescaler(void); ///< get timer0 prescaler
#ifdef TCNT2 // support timer2 only if it exists
void timer2SetPrescaler(u08 prescale); ///< set timer2 prescaler
u16 timer2GetPrescaler(void); ///< get timer2 prescaler
#endif
 
 
// TimerAttach and Detach commands
// These functions allow the attachment (or detachment) of any user function
// to a timer interrupt. "Attaching" one of your own functions to a timer
// interrupt means that it will be called whenever that interrupt happens.
// Using attach is better than rewriting the actual INTERRUPT() function
// because your code will still work and be compatible if the timer library
// is updated. Also, using Attach allows your code and any predefined timer
// code to work together and at the same time. (ie. "attaching" your own
// function to the timer0 overflow doesn't prevent timerPause from working,
// but rather allows you to share the interrupt.)
//
// timerAttach(TIMER1OVERFLOW_INT, myOverflowFunction);
// timerDetach(TIMER1OVERFLOW_INT)
//
// timerAttach causes the myOverflowFunction() to be attached, and therefore
// execute, whenever an overflow on timer1 occurs. timerDetach removes the
// association and executes no user function when the interrupt occurs.
// myOverflowFunction must be defined with no return value and no arguments:
//
// void myOverflowFunction(void) { ... }
 
//! Attach a user function to a timer interrupt
void timerAttach(u08 interruptNum, void (*userFunc)(void) );
//! Detach a user function from a timer interrupt
void timerDetach(u08 interruptNum);
 
 
// timing commands
/// A timer-based delay/pause function
/// @param pause_ms Number of integer milliseconds to wait.
void timerPause(unsigned short pause_ms);
 
// overflow counters
void timer0ClearOverflowCount(void); ///< Clear timer0's overflow counter.
long timer0GetOverflowCount(void); ///< read timer0's overflow counter
#ifdef TCNT2 // support timer2 only if it exists
void timer2ClearOverflowCount(void); ///< clear timer2's overflow counter
long timer2GetOverflowCount(void); ///< read timer0's overflow counter
#endif
 
/// @defgroup timerpwm Timer PWM Commands
/// @ingroup timer
/// These commands control PWM functionality on timer1
// PWM initialization and set commands for timer1
// timer1PWMInit()
// configures the timer1 hardware for PWM mode on pins OC1A and OC1B.
// bitRes should be 8,9,or 10 for 8,9,or 10bit PWM resolution
//
// timer1PWMOff()
// turns off all timer1 PWM output and set timer mode to normal state
//
// timer1PWMAOn() and timer1PWMBOn()
// turn on output of PWM signals to OC1A or OC1B pins
// NOTE: Until you define the OC1A and OC1B pins as outputs, and run
// this "on" command, no PWM output will be output
//
// timer1PWMAOff() and timer1PWMBOff()
// turn off output of PWM signals to OC1A or OC1B pins
//
// timer1PWMASet() and timer1PWMBSet()
// sets the PWM duty cycle for each channel
// NOTE: <pwmDuty> should be in the range 0-255 for 8bit PWM
// <pwmDuty> should be in the range 0-511 for 9bit PWM
// <pwmDuty> should be in the range 0-1023 for 10bit PWM
// NOTE: the PWM frequency can be controlled in increments by setting the
// prescaler for timer1
//@{
 
 
/// Enter standard PWM Mode on timer1.
/// \param bitRes indicates the period/resolution to use for PWM output in timer bits.
/// Must be either 8, 9, or 10 bits corresponding to PWM periods of 256, 512, or 1024 timer tics.
void timer1PWMInit(u08 bitRes);
 
/// Enter PWM Mode on timer1 with a specific top-count value.
/// \param topcount indicates the desired PWM period in timer tics.
/// Can be a number between 1 and 65535 (16-bit).
void timer1PWMInitICR(u16 topcount);
 
/// Turn off all timer1 PWM output and set timer mode to normal.
void timer1PWMOff(void);
 
/// Turn on/off Timer1 PWM outputs.
void timer1PWMAOn(void); ///< Turn on timer1 Channel A (OC1A) PWM output.
void timer1PWMBOn(void); ///< Turn on timer1 Channel B (OC1B) PWM output.
void timer1PWMAOff(void); ///< turn off timer1 Channel A (OC1A) PWM output
void timer1PWMBOff(void); ///< turn off timer1 Channel B (OC1B) PWM output
 
void timer1PWMASet(u16 pwmDuty); ///< set duty of timer1 Channel A (OC1A) PWM output
void timer1PWMBSet(u16 pwmDuty); ///< set duty of timer1 Channel B (OC1B) PWM output
 
//@}
//@}
 
// Pulse generation commands have been moved to the pulse.c library
 
#endif
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/akcelerometr/uart.c
0,0 → 1,283
/*! \file uart.c \brief UART driver with buffer support. */
// *****************************************************************************
//
// File Name : 'uart.c'
// Title : UART driver with buffer support
// Author : Pascal Stang - Copyright (C) 2000-2002
// Created : 11/22/2000
// Revised : 06/09/2003
// Version : 1.3
// Target MCU : ATMEL AVR Series
// Editor Tabs : 4
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
// *****************************************************************************
 
#include <avr/io.h>
#include <avr/interrupt.h>
 
#include "buffer.h"
#include "uart.h"
 
// UART global variables
// flag variables
volatile u08 uartReadyTx; ///< uartReadyTx flag
volatile u08 uartBufferedTx; ///< uartBufferedTx flag
// receive and transmit buffers
cBuffer uartRxBuffer; ///< uart receive buffer
cBuffer uartTxBuffer; ///< uart transmit buffer
unsigned short uartRxOverflow; ///< receive overflow counter
 
#ifndef UART_BUFFERS_EXTERNAL_RAM
// using internal ram,
// automatically allocate space in ram for each buffer
static char uartRxData[UART_RX_BUFFER_SIZE];
static char uartTxData[UART_TX_BUFFER_SIZE];
#endif
 
typedef void (*voidFuncPtru08)(unsigned char);
volatile static voidFuncPtru08 UartRxFunc;
 
// enable and initialize the uart
void uartInit(void)
{
// initialize the buffers
uartInitBuffers();
// initialize user receive handler
UartRxFunc = 0;
 
// enable RxD/TxD and interrupts
outb(UCR, BV(RXCIE)|BV(TXCIE)|BV(RXEN)|BV(TXEN));
 
// set default baud rate
uartSetBaudRate(UART_DEFAULT_BAUD_RATE);
// initialize states
uartReadyTx = TRUE;
uartBufferedTx = FALSE;
// clear overflow count
uartRxOverflow = 0;
// enable interrupts
sei();
}
 
// create and initialize the uart transmit and receive buffers
void uartInitBuffers(void)
{
#ifndef UART_BUFFERS_EXTERNAL_RAM
// initialize the UART receive buffer
bufferInit(&uartRxBuffer, uartRxData, UART_RX_BUFFER_SIZE);
// initialize the UART transmit buffer
bufferInit(&uartTxBuffer, uartTxData, UART_TX_BUFFER_SIZE);
#else
// initialize the UART receive buffer
bufferInit(&uartRxBuffer, (u08*) UART_RX_BUFFER_ADDR, UART_RX_BUFFER_SIZE);
// initialize the UART transmit buffer
bufferInit(&uartTxBuffer, (u08*) UART_TX_BUFFER_ADDR, UART_TX_BUFFER_SIZE);
#endif
}
 
// redirects received data to a user function
void uartSetRxHandler(void (*rx_func)(unsigned char c))
{
// set the receive interrupt to run the supplied user function
UartRxFunc = rx_func;
}
 
// set the uart baud rate
void uartSetBaudRate(u32 baudrate)
{
// calculate division factor for requested baud rate, and set it
u16 bauddiv = ((F_CPU+(baudrate*8L))/(baudrate*16L)-1);
outb(UBRRL, bauddiv);
#ifdef UBRRH
outb(UBRRH, bauddiv>>8);
#endif
}
 
// returns the receive buffer structure
cBuffer* uartGetRxBuffer(void)
{
// return rx buffer pointer
return &uartRxBuffer;
}
 
// returns the transmit buffer structure
cBuffer* uartGetTxBuffer(void)
{
// return tx buffer pointer
return &uartTxBuffer;
}
 
// transmits a byte over the uart
void uartSendByte(u08 txData)
{
// wait for the transmitter to be ready
while(!uartReadyTx);
// send byte
outb(UDR, txData);
// set ready state to FALSE
uartReadyTx = FALSE;
}
 
// gets a single byte from the uart receive buffer (getchar-style)
int uartGetByte(void)
{
u08 c;
if(uartReceiveByte(&c))
return c;
else
return -1;
}
 
// gets a byte (if available) from the uart receive buffer
u08 uartReceiveByte(u08* rxData)
{
// make sure we have a receive buffer
if(uartRxBuffer.size)
{
// make sure we have data
if(uartRxBuffer.datalength)
{
// get byte from beginning of buffer
*rxData = bufferGetFromFront(&uartRxBuffer);
return TRUE;
}
else
{
// no data
return FALSE;
}
}
else
{
// no buffer
return FALSE;
}
}
 
// flush all data out of the receive buffer
void uartFlushReceiveBuffer(void)
{
// flush all data from receive buffer
//bufferFlush(&uartRxBuffer);
// same effect as above
uartRxBuffer.datalength = 0;
}
 
// return true if uart receive buffer is empty
u08 uartReceiveBufferIsEmpty(void)
{
if(uartRxBuffer.datalength == 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
 
// add byte to end of uart Tx buffer
u08 uartAddToTxBuffer(u08 data)
{
// add data byte to the end of the tx buffer
return bufferAddToEnd(&uartTxBuffer, data);
}
 
// start transmission of the current uart Tx buffer contents
void uartSendTxBuffer(void)
{
// turn on buffered transmit
uartBufferedTx = TRUE;
// send the first byte to get things going by interrupts
uartSendByte(bufferGetFromFront(&uartTxBuffer));
}
/*
// transmit nBytes from buffer out the uart
u08 uartSendBuffer(char *buffer, u16 nBytes)
{
register u08 first;
register u16 i;
 
// check if there's space (and that we have any bytes to send at all)
if((uartTxBuffer.datalength + nBytes < uartTxBuffer.size) && nBytes)
{
// grab first character
first = *buffer++;
// copy user buffer to uart transmit buffer
for(i = 0; i < nBytes-1; i++)
{
// put data bytes at end of buffer
bufferAddToEnd(&uartTxBuffer, *buffer++);
}
 
// send the first byte to get things going by interrupts
uartBufferedTx = TRUE;
uartSendByte(first);
// return success
return TRUE;
}
else
{
// return failure
return FALSE;
}
}
*/
// UART Transmit Complete Interrupt Handler
UART_INTERRUPT_HANDLER(SIG_UART_TRANS)
{
// check if buffered tx is enabled
if(uartBufferedTx)
{
// check if there's data left in the buffer
if(uartTxBuffer.datalength)
{
// send byte from top of buffer
outb(UDR, bufferGetFromFront(&uartTxBuffer));
}
else
{
// no data left
uartBufferedTx = FALSE;
// return to ready state
uartReadyTx = TRUE;
}
}
else
{
// we're using single-byte tx mode
// indicate transmit complete, back to ready
uartReadyTx = TRUE;
}
}
 
// UART Receive Complete Interrupt Handler
UART_INTERRUPT_HANDLER(SIG_UART_RECV)
{
u08 c;
// get received char
c = inb(UDR);
 
// if there's a user function to handle this receive event
if(UartRxFunc)
{
// call it and pass the received data
UartRxFunc(c);
}
else
{
// otherwise do default processing
// put received char in buffer
// check if there's space
if( !bufferAddToEnd(&uartRxBuffer, c) )
{
// no space in buffer
// count overflow
uartRxOverflow++;
}
}
}
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/akcelerometr/uart.h
0,0 → 1,232
/*! \file uart.h \brief UART driver with buffer support. */
//*****************************************************************************
//
// File Name : 'uart.h'
// Title : UART driver with buffer support
// Author : Pascal Stang - Copyright (C) 2000-2002
// Created : 11/22/2000
// Revised : 02/01/2004
// Version : 1.3
// Target MCU : ATMEL AVR Series
// Editor Tabs : 4
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
/// \ingroup driver_avr
/// \defgroup uart UART Driver/Function Library (uart.c)
/// \code #include "uart.h" \endcode
/// \par Overview
/// This library provides both buffered and unbuffered transmit and receive
/// functions for the AVR processor UART.� Buffered access means that the
/// UART can transmit and receive data in the "background", while your code
/// continues executing.� Also included are functions to initialize the
/// UART, set the baud rate, flush the buffers, and check buffer status.
///
/// \note For full text output functionality, you may wish to use the rprintf
/// functions along with this driver.
///
/// \par About UART operations
/// Most Atmel AVR-series processors contain one or more hardware UARTs
/// (aka, serial ports). UART serial ports can communicate with other
/// serial ports of the same type, like those used on PCs. In general,
/// UARTs are used to communicate with devices that are RS-232 compatible
/// (RS-232 is a certain kind of serial port).
/// \par
/// By far, the most common use for serial communications on AVR processors
/// is for sending information and data to a PC running a terminal program.
/// Here is an exmaple:
/// \code
/// uartInit(); // initialize UART (serial port)
/// uartSetBaudRate(9600); // set UART speed to 9600 baud
/// rprintfInit(uartSendByte); // configure rprintf to use UART for output
/// rprintf("Hello World\r\n"); // send "hello world" message via serial port
/// \endcode
///
/// \warning The CPU frequency (F_CPU) must be set correctly in \c global.h
/// for the UART library to calculate correct baud rates. Furthermore,
/// certain CPU frequencies will not produce exact baud rates due to
/// integer frequency division round-off. See your AVR processor's
/// datasheet for full details.
//
//*****************************************************************************
//@{
 
#ifndef UART_H
#define UART_H
 
#include "global.h"
#include "buffer.h"
 
//! Default uart baud rate.
/// This is the default speed after a uartInit() command,
/// and can be changed by using uartSetBaudRate().
#define UART_DEFAULT_BAUD_RATE 9600
 
// buffer memory allocation defines
// buffer sizes
#ifndef UART_TX_BUFFER_SIZE
//! Number of bytes for uart transmit buffer.
/// Do not change this value in uart.h, but rather override
/// it with the desired value defined in your project's global.h
#define UART_TX_BUFFER_SIZE 0x0040
#endif
#ifndef UART_RX_BUFFER_SIZE
//! Number of bytes for uart receive buffer.
/// Do not change this value in uart.h, but rather override
/// it with the desired value defined in your project's global.h
#define UART_RX_BUFFER_SIZE 0x0040
#endif
 
// define this key if you wish to use
// external RAM for the UART buffers
//#define UART_BUFFER_EXTERNAL_RAM
#ifdef UART_BUFFER_EXTERNAL_RAM
// absolute address of uart buffers
#define UART_TX_BUFFER_ADDR 0x1000
#define UART_RX_BUFFER_ADDR 0x1100
#endif
 
//! Type of interrupt handler to use for uart interrupts.
/// Value may be SIGNAL or INTERRUPT.
/// \warning Do not change unless you know what you're doing.
#ifndef UART_INTERRUPT_HANDLER
#define UART_INTERRUPT_HANDLER SIGNAL
#endif
 
// compatibility with most newer processors
#ifdef UCSRB
#define UCR UCSRB
#endif
// compatibility with old Mega processors
#if defined(UBRR) && !defined(UBRRL)
#define UBRRL UBRR
#endif
// compatibility with megaXX8 processors
#if defined(__AVR_ATmega88__) || \
defined(__AVR_ATmega168__) || \
defined(__AVR_ATmega644__)
#define UDR UDR0
#define UCR UCSR0B
#define RXCIE RXCIE0
#define TXCIE TXCIE0
#define RXC RXC0
#define TXC TXC0
#define RXEN RXEN0
#define TXEN TXEN0
#define UBRRL UBRR0L
#define UBRRH UBRR0H
#define SIG_UART_TRANS SIG_USART_TRANS
#define SIG_UART_RECV SIG_USART_RECV
#define SIG_UART_DATA SIG_USART_DATA
#endif
// compatibility with mega169 processors
#if defined(__AVR_ATmega169__)
#define SIG_UART_TRANS SIG_USART_TRANS
#define SIG_UART_RECV SIG_USART_RECV
#define SIG_UART_DATA SIG_USART_DATA
#endif
// compatibility with dual-uart processors
// (if you need to use both uarts, please use the uart2 library)
#if defined(__AVR_ATmega161__)
#define UDR UDR0
#define UCR UCSR0B
#define UBRRL UBRR0
#define SIG_UART_TRANS SIG_UART0_TRANS
#define SIG_UART_RECV SIG_UART0_RECV
#define SIG_UART_DATA SIG_UART0_DATA
#endif
#if defined(__AVR_ATmega128__)
#ifdef UART_USE_UART1
#define UDR UDR1
#define UCR UCSR1B
#define UBRRL UBRR1L
#define UBRRH UBRR1H
#define SIG_UART_TRANS SIG_UART1_TRANS
#define SIG_UART_RECV SIG_UART1_RECV
#define SIG_UART_DATA SIG_UART1_DATA
#else
#define UDR UDR0
#define UCR UCSR0B
#define UBRRL UBRR0L
#define UBRRH UBRR0H
#define SIG_UART_TRANS SIG_UART0_TRANS
#define SIG_UART_RECV SIG_UART0_RECV
#define SIG_UART_DATA SIG_UART0_DATA
#endif
#endif
 
// functions
 
//! Initializes uart.
/// \note After running this init function, the processor
/// I/O pins that used for uart communications (RXD, TXD)
/// are no long available for general purpose I/O.
void uartInit(void);
 
//! Initializes transmit and receive buffers.
/// Automatically called from uartInit()
void uartInitBuffers(void);
 
//! Redirects received data to a user function.
///
void uartSetRxHandler(void (*rx_func)(unsigned char c));
 
//! Sets the uart baud rate.
/// Argument should be in bits-per-second, like \c uartSetBaudRate(9600);
void uartSetBaudRate(u32 baudrate);
 
//! Returns pointer to the receive buffer structure.
///
cBuffer* uartGetRxBuffer(void);
 
//! Returns pointer to the transmit buffer structure.
///
cBuffer* uartGetTxBuffer(void);
 
//! Sends a single byte over the uart.
/// \note This function waits for the uart to be ready,
/// therefore, consecutive calls to uartSendByte() will
/// go only as fast as the data can be sent over the
/// serial port.
void uartSendByte(u08 data);
 
//! Gets a single byte from the uart receive buffer.
/// Returns the byte, or -1 if no byte is available (getchar-style).
int uartGetByte(void);
 
//! Gets a single byte from the uart receive buffer.
/// Function returns TRUE if data was available, FALSE if not.
/// Actual data is returned in variable pointed to by "data".
/// Example usage:
/// \code
/// char myReceivedByte;
/// uartReceiveByte( &myReceivedByte );
/// \endcode
u08 uartReceiveByte(u08* data);
 
//! Returns TRUE/FALSE if receive buffer is empty/not-empty.
///
u08 uartReceiveBufferIsEmpty(void);
 
//! Flushes (deletes) all data from receive buffer.
///
void uartFlushReceiveBuffer(void);
 
//! Add byte to end of uart Tx buffer.
/// Returns TRUE if successful, FALSE if failed (no room left in buffer).
u08 uartAddToTxBuffer(u08 data);
 
//! Begins transmission of the transmit buffer under interrupt control.
///
void uartSendTxBuffer(void);
 
//! Sends a block of data via the uart using interrupt control.
/// \param buffer pointer to data to be sent
/// \param nBytes length of data (number of bytes to sent)
u08 uartSendBuffer(char *buffer, u16 nBytes);
 
#endif
//@}
 
 
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/gps/Makefile
0,0 → 1,51
 
NAME := gpstest
HEX := $(NAME).hex
OUT := $(NAME).out
MAP := $(NAME).map
SOURCES := $(wildcard *.c)
HEADERS := $(wildcard *.h)
OBJECTS := $(patsubst %.c,%.o,$(SOURCES))
 
MCU := atmega8
MCU_AVRDUDE := m128
 
CC := avr-gcc
OBJCOPY := avr-objcopy
SIZE := avr-size -A
DOXYGEN := doxygen
 
CFLAGS := -Wall -pedantic -mmcu=$(MCU) -std=c99 -g -Os
 
all: $(HEX)
 
clean:
rm -f $(HEX) $(OUT) $(MAP) $(OBJECTS)
rm -rf doc/html
 
flash: $(HEX)
avrdude -y -p $(MCU_AVRDUDE) -P /dev/ttyUSB0 -c stk500v2 -U flash:w:$(HEX)
 
$(HEX): $(OUT)
$(OBJCOPY) -R .eeprom -O ihex $< $@
 
$(OUT): $(OBJECTS)
$(CC) $(CFLAGS) -o $@ -Wl,-Map,$(MAP) $^
@echo
@$(SIZE) $@
@echo
 
%.o: %.c $(HEADERS)
$(CC) $(CFLAGS) -c -o $@ $<
 
%.pp: %.c
$(CC) $(CFLAGS) -E -o $@ $<
 
%.ppo: %.c
$(CC) $(CFLAGS) -E $<
 
doc: $(HEADERS) $(SOURCES) Doxyfile
$(DOXYGEN) Doxyfile
 
.PHONY: all clean flash doc
 
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/gps/avrlibdefs.h
0,0 → 1,83
/*! \file avrlibdefs.h \brief AVRlib global defines and macros. */
//*****************************************************************************
//
// File Name : 'avrlibdefs.h'
// Title : AVRlib global defines and macros include file
// Author : Pascal Stang
// Created : 7/12/2001
// Revised : 9/30/2002
// Version : 1.1
// Target MCU : Atmel AVR series
// Editor Tabs : 4
//
// Description : This include file is designed to contain items useful to all
// code files and projects, regardless of specific implementation.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
 
#ifndef AVRLIBDEFS_H
#define AVRLIBDEFS_H
 
// Code compatibility to new AVR-libc
// outb(), inb(), inw(), outw(), BV(), sbi(), cbi(), sei(), cli()
#ifndef outb
#define outb(addr, data) addr = (data)
#endif
#ifndef inb
#define inb(addr) (addr)
#endif
#ifndef outw
#define outw(addr, data) addr = (data)
#endif
#ifndef inw
#define inw(addr) (addr)
#endif
#ifndef BV
#define BV(bit) (1<<(bit))
#endif
#ifndef cbi
#define cbi(reg,bit) reg &= ~(BV(bit))
#endif
#ifndef sbi
#define sbi(reg,bit) reg |= (BV(bit))
#endif
#ifndef cli
#define cli() __asm__ __volatile__ ("cli" ::)
#endif
#ifndef sei
#define sei() __asm__ __volatile__ ("sei" ::)
#endif
 
// support for individual port pin naming in the mega128
// see port128.h for details
#ifdef __AVR_ATmega128__
// not currently necessary due to inclusion
// of these defines in newest AVR-GCC
// do a quick test to see if include is needed
#ifndef PD0
#include "port128.h"
#endif
#endif
 
// use this for packed structures
// (this is seldom necessary on an 8-bit architecture like AVR,
// but can assist in code portability to AVR)
#define GNUC_PACKED __attribute__((packed))
 
// port address helpers
#define DDR(x) ((x)-1) // address of data direction register of port x
#define PIN(x) ((x)-2) // address of input register of port x
 
// MIN/MAX/ABS macros
#define MIN(a,b) ((a<b)?(a):(b))
#define MAX(a,b) ((a>b)?(a):(b))
#define ABS(x) ((x>0)?(x):(-x))
 
// constants
#define PI 3.14159265359
 
#endif
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/gps/avrlibtypes.h
0,0 → 1,84
/*! \file avrlibtypes.h \brief AVRlib global types and typedefines. */
//*****************************************************************************
//
// File Name : 'avrlibtypes.h'
// Title : AVRlib global types and typedefines include file
// Author : Pascal Stang
// Created : 7/12/2001
// Revised : 9/30/2002
// Version : 1.0
// Target MCU : Atmel AVR series
// Editor Tabs : 4
//
// Description : Type-defines required and used by AVRlib. Most types are also
// generally useful.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
 
#ifndef AVRLIBTYPES_H
#define AVRLIBTYPES_H
 
#ifndef WIN32
// true/false defines
#define FALSE 0
#define TRUE -1
#endif
 
// datatype definitions macros
typedef unsigned char u08;
typedef signed char s08;
typedef unsigned short u16;
typedef signed short s16;
typedef unsigned long u32;
typedef signed long s32;
typedef unsigned long long u64;
typedef signed long long s64;
 
/* use inttypes.h instead
// C99 standard integer type definitions
typedef unsigned char uint8_t;
typedef signed char int8_t;
typedef unsigned short uint16_t;
typedef signed short int16_t;
typedef unsigned long uint32_t;
typedef signed long int32_t;
typedef unsigned long uint64_t;
typedef signed long int64_t;
*/
// maximum value that can be held
// by unsigned data types (8,16,32bits)
#define MAX_U08 255
#define MAX_U16 65535
#define MAX_U32 4294967295
 
// maximum values that can be held
// by signed data types (8,16,32bits)
#define MIN_S08 -128
#define MAX_S08 127
#define MIN_S16 -32768
#define MAX_S16 32767
#define MIN_S32 -2147483648
#define MAX_S32 2147483647
 
#ifndef WIN32
// more type redefinitions
typedef unsigned char BOOL;
typedef unsigned char BYTE;
typedef unsigned int WORD;
typedef unsigned long DWORD;
 
typedef unsigned char UCHAR;
typedef unsigned int UINT;
typedef unsigned short USHORT;
typedef unsigned long ULONG;
 
typedef char CHAR;
typedef int INT;
typedef long LONG;
#endif
 
#endif
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/gps/buffer.c
0,0 → 1,149
/*! \file buffer.c \brief Multipurpose byte buffer structure and methods. */
//*****************************************************************************
//
// File Name : 'buffer.c'
// Title : Multipurpose byte buffer structure and methods
// Author : Pascal Stang - Copyright (C) 2001-2002
// Created : 9/23/2001
// Revised : 9/23/2001
// Version : 1.0
// Target MCU : any
// Editor Tabs : 4
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
#include "buffer.h"
#include "global.h"
#include "avr/io.h"
 
#ifndef CRITICAL_SECTION_START
#define CRITICAL_SECTION_START unsigned char _sreg = SREG; cli()
#define CRITICAL_SECTION_END SREG = _sreg
#endif
 
// global variables
 
// initialization
 
void bufferInit(cBuffer* buffer, unsigned char *start, unsigned short size)
{
// begin critical section
CRITICAL_SECTION_START;
// set start pointer of the buffer
buffer->dataptr = start;
buffer->size = size;
// initialize index and length
buffer->dataindex = 0;
buffer->datalength = 0;
// end critical section
CRITICAL_SECTION_END;
}
 
// access routines
unsigned char bufferGetFromFront(cBuffer* buffer)
{
unsigned char data = 0;
// begin critical section
CRITICAL_SECTION_START;
// check to see if there's data in the buffer
if(buffer->datalength)
{
// get the first character from buffer
data = buffer->dataptr[buffer->dataindex];
// move index down and decrement length
buffer->dataindex++;
if(buffer->dataindex >= buffer->size)
{
buffer->dataindex -= buffer->size;
}
buffer->datalength--;
}
// end critical section
CRITICAL_SECTION_END;
// return
return data;
}
 
void bufferDumpFromFront(cBuffer* buffer, unsigned short numbytes)
{
// begin critical section
CRITICAL_SECTION_START;
// dump numbytes from the front of the buffer
// are we dumping less than the entire buffer?
if(numbytes < buffer->datalength)
{
// move index down by numbytes and decrement length by numbytes
buffer->dataindex += numbytes;
if(buffer->dataindex >= buffer->size)
{
buffer->dataindex -= buffer->size;
}
buffer->datalength -= numbytes;
}
else
{
// flush the whole buffer
buffer->datalength = 0;
}
// end critical section
CRITICAL_SECTION_END;
}
 
unsigned char bufferGetAtIndex(cBuffer* buffer, unsigned short index)
{
// begin critical section
CRITICAL_SECTION_START;
// return character at index in buffer
unsigned char data = buffer->dataptr[(buffer->dataindex+index)%(buffer->size)];
// end critical section
CRITICAL_SECTION_END;
return data;
}
 
unsigned char bufferAddToEnd(cBuffer* buffer, unsigned char data)
{
// begin critical section
CRITICAL_SECTION_START;
// make sure the buffer has room
if(buffer->datalength < buffer->size)
{
// save data byte at end of buffer
buffer->dataptr[(buffer->dataindex + buffer->datalength) % buffer->size] = data;
// increment the length
buffer->datalength++;
// end critical section
CRITICAL_SECTION_END;
// return success
return -1;
}
// end critical section
CRITICAL_SECTION_END;
// return failure
return 0;
}
 
unsigned short bufferIsNotFull(cBuffer* buffer)
{
// begin critical section
CRITICAL_SECTION_START;
// check to see if the buffer has room
// return true if there is room
unsigned short bytesleft = (buffer->size - buffer->datalength);
// end critical section
CRITICAL_SECTION_END;
return bytesleft;
}
 
void bufferFlush(cBuffer* buffer)
{
// begin critical section
CRITICAL_SECTION_START;
// flush contents of the buffer
buffer->datalength = 0;
// end critical section
CRITICAL_SECTION_END;
}
 
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/gps/buffer.h
0,0 → 1,74
/*! \file buffer.h \brief Multipurpose byte buffer structure and methods. */
//*****************************************************************************
//
// File Name : 'buffer.h'
// Title : Multipurpose byte buffer structure and methods
// Author : Pascal Stang - Copyright (C) 2001-2002
// Created : 9/23/2001
// Revised : 11/16/2002
// Version : 1.1
// Target MCU : any
// Editor Tabs : 4
//
/// \ingroup general
/// \defgroup buffer Circular Byte-Buffer Structure and Function Library (buffer.c)
/// \code #include "buffer.h" \endcode
/// \par Overview
/// This byte-buffer structure provides an easy and efficient way to store
/// and process a stream of bytes.  You can create as many buffers as you
/// like (within memory limits), and then use this common set of functions to
/// access each buffer.  The buffers are designed for FIFO operation (first
/// in, first out).  This means that the first byte you put in the buffer
/// will be the first one you get when you read out the buffer.  Supported
/// functions include buffer initialize, get byte from front of buffer, add
/// byte to end of buffer, check if buffer is full, and flush buffer.  The
/// buffer uses a circular design so no copying of data is ever necessary.
/// This buffer is not dynamically allocated, it has a user-defined fixed
/// maximum size.  This buffer is used in many places in the avrlib code.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
//@{
 
#ifndef BUFFER_H
#define BUFFER_H
 
// structure/typdefs
 
//! cBuffer structure
typedef struct struct_cBuffer
{
unsigned char *dataptr; ///< the physical memory address where the buffer is stored
unsigned short size; ///< the allocated size of the buffer
unsigned short datalength; ///< the length of the data currently in the buffer
unsigned short dataindex; ///< the index into the buffer where the data starts
} cBuffer;
 
// function prototypes
 
//! initialize a buffer to start at a given address and have given size
void bufferInit(cBuffer* buffer, unsigned char *start, unsigned short size);
 
//! get the first byte from the front of the buffer
unsigned char bufferGetFromFront(cBuffer* buffer);
 
//! dump (discard) the first numbytes from the front of the buffer
void bufferDumpFromFront(cBuffer* buffer, unsigned short numbytes);
 
//! get a byte at the specified index in the buffer (kind of like array access)
// ** note: this does not remove the byte that was read from the buffer
unsigned char bufferGetAtIndex(cBuffer* buffer, unsigned short index);
 
//! add a byte to the end of the buffer
unsigned char bufferAddToEnd(cBuffer* buffer, unsigned char data);
 
//! check if the buffer is full/not full (returns zero value if full)
unsigned short bufferIsNotFull(cBuffer* buffer);
 
//! flush (clear) the contents of the buffer
void bufferFlush(cBuffer* buffer);
 
#endif
//@}
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/gps/global.h
0,0 → 1,43
 
//*****************************************************************************
//
// File Name : 'global.h'
// Title : AVR project global include
// Author : Pascal Stang
// Created : 7/12/2001
// Revised : 9/30/2002
// Version : 1.1
// Target MCU : Atmel AVR series
// Editor Tabs : 4
//
// Description : This include file is designed to contain items useful to all
// code files and projects.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
#ifndef GLOBAL_H
#define GLOBAL_H
 
// global AVRLIB defines
#include "avrlibdefs.h"
// global AVRLIB types definitions
#include "avrlibtypes.h"
 
// project/system dependent defines
 
// back-door way to enable floating-point print support
#define RPRINTF_FLOAT
 
// CPU clock speed
//#define F_CPU 16000000 // 16MHz processor
//#define F_CPU 14745000 // 14.745MHz processor
//#define F_CPU 8000000 // 8MHz processor
#define F_CPU 7372800 // 7.37MHz processor
//#define F_CPU 4000000 // 4MHz processor
//#define F_CPU 3686400 // 3.69MHz processor
#define CYCLES_PER_US ((F_CPU+500000)/1000000) // cpu cycles per microsecond
 
#endif
/programy/C/avr/gps/gps.c
0,0 → 1,83
/*! \file gps.c \brief GPS position storage and processing library. */
//*****************************************************************************
//
// File Name : 'gps.c'
// Title : GPS position storage and processing function library
// Author : Pascal Stang - Copyright (C) 2002-2005
// Created : 2005.01.14
// Revised : 2002.07.17
// Version : 0.1
// Target MCU : Atmel AVR Series
// Editor Tabs : 4
//
// NOTE: This code is currently below version 1.0, and therefore is considered
// to be lacking in some functionality or documentation, or may not be fully
// tested. Nonetheless, you can expect most functions to work.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
#ifndef WIN32
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <math.h>
#include <stdlib.h>
#endif
 
#include "global.h"
#include "rprintf.h"
#include "gps.h"
 
// Global variables
GpsInfoType GpsInfo;
 
// Functions
void gpsInit(void)
{
}
 
GpsInfoType* gpsGetInfo(void)
{
return &GpsInfo;
}
 
void gpsInfoPrint(void)
{
 
rprintfProgStrM("TOW: "); rprintfFloat(8, GpsInfo.TimeOfWeek.f); rprintfCRLF();
rprintfProgStrM("WkNum: "); rprintfNum(10,4,0,' ',GpsInfo.WeekNum); rprintfCRLF();
rprintfProgStrM("UTCoffset:"); rprintfFloat(8, GpsInfo.UtcOffset.f); rprintfCRLF();
rprintfProgStrM("Num SVs: "); rprintfNum(10,4,0,' ',GpsInfo.numSVs); rprintfCRLF();
 
rprintfProgStrM("X_ECEF: "); rprintfFloat(8, GpsInfo.PosECEF.x.f); rprintfCRLF();
rprintfProgStrM("Y_ECEF: "); rprintfFloat(8, GpsInfo.PosECEF.y.f); rprintfCRLF();
rprintfProgStrM("Z_ECEF: "); rprintfFloat(8, GpsInfo.PosECEF.z.f); rprintfCRLF();
rprintfProgStrM("TOF: "); rprintfFloat(8, GpsInfo.PosECEF.TimeOfFix.f); rprintfCRLF();
rprintfProgStrM("Updates: "); rprintfNum(10,6,0,' ',GpsInfo.PosECEF.updates); rprintfCRLF();
 
//u08 str[20];
//rprintfProgStrM(" PosLat: "); rprintfStr(dtostrf(GpsInfo.PosLat.f, 10, 5, str));
rprintfProgStrM("PosLat: "); rprintfFloat(8, 180*(GpsInfo.PosLLA.lat.f/PI)); rprintfCRLF();
rprintfProgStrM("PosLon: "); rprintfFloat(8, 180*(GpsInfo.PosLLA.lon.f/PI)); rprintfCRLF();
rprintfProgStrM("PosAlt: "); rprintfFloat(8, GpsInfo.PosLLA.alt.f); rprintfCRLF();
rprintfProgStrM("TOF: "); rprintfFloat(8, GpsInfo.PosLLA.TimeOfFix.f); rprintfCRLF();
rprintfProgStrM("Updates: "); rprintfNum(10,6,0,' ',GpsInfo.PosLLA.updates); rprintfCRLF();
 
rprintfProgStrM("Vel East: "); rprintfFloat(8, GpsInfo.VelENU.east.f); rprintfCRLF();
rprintfProgStrM("Vel North:"); rprintfFloat(8, GpsInfo.VelENU.north.f); rprintfCRLF();
rprintfProgStrM("Vel Up: "); rprintfFloat(8, GpsInfo.VelENU.up.f); rprintfCRLF();
// rprintfProgStrM("TOF: "); rprintfFloat(8, GpsInfo.VelENU.TimeOfFix.f); rprintfCRLF();
rprintfProgStrM("Updates: "); rprintfNum(10,6,0,' ',GpsInfo.VelENU.updates); rprintfCRLF();
 
rprintfProgStrM("Vel Head: "); rprintfFloat(8, GpsInfo.VelHS.heading.f); rprintfCRLF();
rprintfProgStrM("Vel Speed:"); rprintfFloat(8, GpsInfo.VelHS.speed.f); rprintfCRLF();
// rprintfProgStrM("TOF: "); rprintfFloat(8, GpsInfo.VelHS.TimeOfFix.f); rprintfCRLF();
rprintfProgStrM("Updates: "); rprintfNum(10,6,0,' ',GpsInfo.VelHS.updates); rprintfCRLF();
 
}
 
 
/programy/C/avr/gps/gps.h
0,0 → 1,119
/*! \file gps.h \brief GPS position storage and processing library. */
//*****************************************************************************
//
// File Name : 'gps.h'
// Title : GPS position storage and processing function library
// Author : Pascal Stang - Copyright (C) 2002
// Created : 2002.08.29
// Revised : 2002.08.29
// Version : 0.1
// Target MCU : Atmel AVR Series
// Editor Tabs : 4
//
// NOTE: This code is currently below version 1.0, and therefore is considered
// to be lacking in some functionality or documentation, or may not be fully
// tested. Nonetheless, you can expect most functions to work.
//
/// \ingroup driver_hw
/// \defgroup gps GPS Positioning and Navigation Function Library (gps.c)
/// \code #include "gps.h" \endcode
/// \par Overview
/// This library provides a generic way to store and process information
/// received from a GPS receiver.  Currently the library only stores the most
/// recent set of GPS data (position, velocity, time) from a GPS receiver.
/// Future revisions will include navigation functions like calculate
/// heading/distance to a waypoint.  The processing of incoming serial data
/// packets from GPS hardware is not done in this library.  The libraries
/// tsip.c and nmea.c do the packet processing for Trimble Standard Interface
/// Protocol and NMEA-0813 repectively, and store the results in this library.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
#ifndef GPS_H
#define GPS_H
 
#include "global.h"
 
// constants/macros/typdefs
typedef union union_float_u32
{
float f;
unsigned long i;
unsigned char b[4];
} float_u32;
 
typedef union union_double_u64
{
double f;
unsigned long long i;
unsigned char b[8];
} double_u64;
 
struct PositionLLA
{
float_u32 lat;
float_u32 lon;
float_u32 alt;
float_u32 TimeOfFix;
u16 updates;
};
 
struct VelocityENU
{
float_u32 east;
float_u32 north;
float_u32 up;
float_u32 TimeOfFix;
u16 updates;
};
 
struct VelocityHS
{
float_u32 heading;
float_u32 speed;
float_u32 TimeOfFix;
u16 updates;
};
 
struct PositionECEF
{
float_u32 x;
float_u32 y;
float_u32 z;
float_u32 TimeOfFix;
u16 updates;
};
 
struct VelocityECEF
{
float_u32 x;
float_u32 y;
float_u32 z;
float_u32 TimeOfFix;
u16 updates;
};
 
typedef struct struct_GpsInfo
{
float_u32 TimeOfWeek;
u16 WeekNum;
float_u32 UtcOffset;
u08 numSVs;
struct PositionLLA PosLLA;
struct PositionECEF PosECEF;
struct VelocityECEF VelECEF;
struct VelocityENU VelENU;
struct VelocityHS VelHS;
 
} GpsInfoType;
 
// functions
void gpsInit(void);
GpsInfoType* gpsGetInfo(void);
void gpsInfoPrint(void);
 
#endif
/programy/C/avr/gps/gpstest.c
0,0 → 1,126
//*****************************************************************************
// File Name : gpstest.c
//
// Title : example usage of gps processing library functions
// Revision : 1.0
// Notes :
// Target MCU : Atmel AVR series
// Editor Tabs : 4
//
// Revision History:
// When Who Description of change
// ----------- ----------- -----------------------
// 10-Sep-2002 pstang Created the program
//*****************************************************************************
 
//----- Include Files ---------------------------------------------------------
#include <avr/io.h> // include I/O definitions (port names, pin names, etc)
#include <avr/interrupt.h> // include interrupt support
//#include <math.h>
#include <stdlib.h>
 
#include "global.h" // include our global settings
#include "uart2.h" // include dual-uart function library
#include "rprintf.h" // include printf function library
#include "timer.h" // include timer function library (timing, PWM, etc)
#include "gps.h" // include gps data support
#include "tsip.h" // include TSIP gps packet handling
#include "nmea.h" // include NMEA gps packet handling
#include "vt100.h" // include VT100 terminal commands
 
// uartRxOverflow is a global variable defined in uart.c/uart2.c
// we define it here as <extern> here so that we can use its value
// in code contained in this file
extern unsigned short uartRxOverflow[2];
 
void gpsTsipTest(void);
void gpsNmeaTest(void);
 
//----- Begin Code ------------------------------------------------------------
int main(void)
{
// initialize our libraries
// initialize the UART (serial port)
uartInit();
// set the baud rate of UART 0 for our debug/reporting output
uartSetBaudRate(0,9600);
// set uart0SendByte as the output for all rprintf statements
rprintfInit(uart0SendByte);
// initialize the timer system
timerInit();
// initialize vt100 library
vt100Init();
// print a little intro message so we know things are working
vt100ClearScreen();
rprintf("\r\nWelcome to GPS Test!\r\n");
// run example gps processing loop
// (pick the one appropriate for your GPS packet format)
// gpsTsipTest();
gpsNmeaTest();
return 0;
}
 
void gpsTsipTest(void)
{
// set the baud rate of UART 1 for TSIP
uartSetBaudRate(1,9600);
 
// clear screen
vt100ClearScreen();
// initialize gps library
gpsInit();
// initialize gps packet decoder
tsipInit(uart1SendByte); // use uart1 for tsip packet output
 
// begin gps packet processing loop
while(1)
{
// process received gps packets until receive buffer is exhausted
while( tsipProcess(uartGetRxBuffer(1)) );
 
// set cursor position to top left of screen
vt100SetCursorPos(0,0);
// print/dump current formatted GPS data
gpsInfoPrint();
// print UART 1 overflow status to verify that we're processing packets
// fast enough and that our receive buffer is large enough
rprintf("Uart1RxOvfl: %d\r\n",uartRxOverflow[1]);
// pause for 100ms
timerPause(100);
}
}
 
void gpsNmeaTest(void)
{
// set the baud rate of UART 1 for NMEA
uartSetBaudRate(1,4800);
 
// clear screen
vt100ClearScreen();
// initialize gps library
gpsInit();
// initialize gps packet decoder
nmeaInit();
 
// begin gps packet processing loop
while(1)
{
// process received gps packets until receive buffer is exhausted
while( nmeaProcess(uartGetRxBuffer(1)) );
 
// set cursor position to top left of screen
vt100SetCursorPos(0,0);
// print/dump current formatted GPS data
gpsInfoPrint();
// print UART 1 overflow status to verify that we're processing packets
// fast enough and that our receive buffer is large enough
rprintf("Uart1RxOvfl: %d\r\n",uartRxOverflow[1]);
// pause for 100ms
timerPause(100);
}
}
 
/programy/C/avr/gps/nmea.c
0,0 → 1,259
/*! \file nmea.c \brief NMEA protocol function library. */
//*****************************************************************************
//
// File Name : 'nmea.c'
// Title : NMEA protocol function library
// Author : Pascal Stang - Copyright (C) 2002
// Created : 2002.08.27
// Revised : 2002.08.27
// Version : 0.1
// Target MCU : Atmel AVR Series
// Editor Tabs : 4
//
// NOTE: This code is currently below version 1.0, and therefore is considered
// to be lacking in some functionality or documentation, or may not be fully
// tested. Nonetheless, you can expect most functions to work.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
#ifndef WIN32
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#endif
#include <string.h>
#include <stdlib.h>
#include <math.h>
 
#include "global.h"
#include "buffer.h"
#include "rprintf.h"
#include "gps.h"
 
#include "nmea.h"
 
// Program ROM constants
 
// Global variables
extern GpsInfoType GpsInfo;
u08 NmeaPacket[NMEA_BUFFERSIZE];
 
void nmeaInit(void)
{
}
 
u08* nmeaGetPacketBuffer(void)
{
return NmeaPacket;
}
 
u08 nmeaProcess(cBuffer* rxBuffer)
{
u08 foundpacket = NMEA_NODATA;
u08 startFlag = FALSE;
//u08 data;
u16 i,j;
 
// process the receive buffer
// go through buffer looking for packets
while(rxBuffer->datalength)
{
// look for a start of NMEA packet
if(bufferGetAtIndex(rxBuffer,0) == '$')
{
// found start
startFlag = TRUE;
// when start is found, we leave it intact in the receive buffer
// in case the full NMEA string is not completely received. The
// start will be detected in the next nmeaProcess iteration.
 
// done looking for start
break;
}
else
bufferGetFromFront(rxBuffer);
}
// if we detected a start, look for end of packet
if(startFlag)
{
for(i=1; i<(rxBuffer->datalength)-1; i++)
{
// check for end of NMEA packet <CR><LF>
if((bufferGetAtIndex(rxBuffer,i) == '\r') && (bufferGetAtIndex(rxBuffer,i+1) == '\n'))
{
// have a packet end
// dump initial '$'
bufferGetFromFront(rxBuffer);
// copy packet to NmeaPacket
for(j=0; j<(i-1); j++)
{
// although NMEA strings should be 80 characters or less,
// receive buffer errors can generate erroneous packets.
// Protect against packet buffer overflow
if(j<(NMEA_BUFFERSIZE-1))
NmeaPacket[j] = bufferGetFromFront(rxBuffer);
else
bufferGetFromFront(rxBuffer);
}
// null terminate it
NmeaPacket[j] = 0;
// dump <CR><LF> from rxBuffer
bufferGetFromFront(rxBuffer);
bufferGetFromFront(rxBuffer);
 
#ifdef NMEA_DEBUG_PKT
rprintf("Rx NMEA packet type: ");
rprintfStrLen(NmeaPacket, 0, 5);
rprintfStrLen(NmeaPacket, 5, (i-1)-5);
rprintfCRLF();
#endif
// found a packet
// done with this processing session
foundpacket = NMEA_UNKNOWN;
break;
}
}
}
 
if(foundpacket)
{
// check message type and process appropriately
if(!strncmp(NmeaPacket, "GPGGA", 5))
{
// process packet of this type
nmeaProcessGPGGA(NmeaPacket);
// report packet type
foundpacket = NMEA_GPGGA;
}
else if(!strncmp(NmeaPacket, "GPVTG", 5))
{
// process packet of this type
nmeaProcessGPVTG(NmeaPacket);
// report packet type
foundpacket = NMEA_GPVTG;
}
}
else if(rxBuffer->datalength >= rxBuffer->size)
{
// if we found no packet, and the buffer is full
// we're logjammed, flush entire buffer
bufferFlush(rxBuffer);
}
return foundpacket;
}
 
void nmeaProcessGPGGA(u08* packet)
{
u08 i;
char* endptr;
double degrees, minutesfrac;
 
#ifdef NMEA_DEBUG_GGA
rprintf("NMEA: ");
rprintfStr(packet);
rprintfCRLF();
#endif
 
// start parsing just after "GPGGA,"
i = 6;
// attempt to reject empty packets right away
if(packet[i]==',' && packet[i+1]==',')
return;
 
// get UTC time [hhmmss.sss]
GpsInfo.PosLLA.TimeOfFix.f = strtod(&packet[i], &endptr);
while(packet[i++] != ','); // next field: latitude
// get latitude [ddmm.mmmmm]
GpsInfo.PosLLA.lat.f = strtod(&packet[i], &endptr);
// convert to pure degrees [dd.dddd] format
minutesfrac = modf(GpsInfo.PosLLA.lat.f/100, &degrees);
GpsInfo.PosLLA.lat.f = degrees + (minutesfrac*100)/60;
// convert to radians
GpsInfo.PosLLA.lat.f *= (M_PI/180);
while(packet[i++] != ','); // next field: N/S indicator
// correct latitute for N/S
if(packet[i] == 'S') GpsInfo.PosLLA.lat.f = -GpsInfo.PosLLA.lat.f;
while(packet[i++] != ','); // next field: longitude
// get longitude [ddmm.mmmmm]
GpsInfo.PosLLA.lon.f = strtod(&packet[i], &endptr);
// convert to pure degrees [dd.dddd] format
minutesfrac = modf(GpsInfo.PosLLA.lon.f/100, &degrees);
GpsInfo.PosLLA.lon.f = degrees + (minutesfrac*100)/60;
// convert to radians
GpsInfo.PosLLA.lon.f *= (M_PI/180);
while(packet[i++] != ','); // next field: E/W indicator
 
// correct latitute for E/W
if(packet[i] == 'W') GpsInfo.PosLLA.lon.f = -GpsInfo.PosLLA.lon.f;
while(packet[i++] != ','); // next field: position fix status
 
// position fix status
// 0 = Invalid, 1 = Valid SPS, 2 = Valid DGPS, 3 = Valid PPS
// check for good position fix
if( (packet[i] != '0') && (packet[i] != ',') )
GpsInfo.PosLLA.updates++;
while(packet[i++] != ','); // next field: satellites used
// get number of satellites used in GPS solution
GpsInfo.numSVs = atoi(&packet[i]);
while(packet[i++] != ','); // next field: HDOP (horizontal dilution of precision)
while(packet[i++] != ','); // next field: altitude
// get altitude (in meters)
GpsInfo.PosLLA.alt.f = strtod(&packet[i], &endptr);
 
while(packet[i++] != ','); // next field: altitude units, always 'M'
while(packet[i++] != ','); // next field: geoid seperation
while(packet[i++] != ','); // next field: seperation units
while(packet[i++] != ','); // next field: DGPS age
while(packet[i++] != ','); // next field: DGPS station ID
while(packet[i++] != '*'); // next field: checksum
}
 
void nmeaProcessGPVTG(u08* packet)
{
u08 i;
char* endptr;
 
#ifdef NMEA_DEBUG_VTG
rprintf("NMEA: ");
rprintfStr(packet);
rprintfCRLF();
#endif
 
// start parsing just after "GPVTG,"
i = 6;
// attempt to reject empty packets right away
if(packet[i]==',' && packet[i+1]==',')
return;
 
// get course (true north ref) in degrees [ddd.dd]
GpsInfo.VelHS.heading.f = strtod(&packet[i], &endptr);
while(packet[i++] != ','); // next field: 'T'
while(packet[i++] != ','); // next field: course (magnetic north)
 
// get course (magnetic north ref) in degrees [ddd.dd]
//GpsInfo.VelHS.heading.f = strtod(&packet[i], &endptr);
while(packet[i++] != ','); // next field: 'M'
while(packet[i++] != ','); // next field: speed (knots)
 
// get speed in knots
//GpsInfo.VelHS.speed.f = strtod(&packet[i], &endptr);
while(packet[i++] != ','); // next field: 'N'
while(packet[i++] != ','); // next field: speed (km/h)
 
// get speed in km/h
GpsInfo.VelHS.speed.f = strtod(&packet[i], &endptr);
while(packet[i++] != ','); // next field: 'K'
while(packet[i++] != '*'); // next field: checksum
 
GpsInfo.VelHS.updates++;
}
 
/programy/C/avr/gps/nmea.h
0,0 → 1,61
/*! \file nmea.h \brief NMEA protocol function library. */
//*****************************************************************************
//
// File Name : 'nmea.h'
// Title : NMEA protocol function library
// Author : Pascal Stang - Copyright (C) 2002
// Created : 2002.08.27
// Revised : 2002.08.27
// Version : 0.1
// Target MCU : Atmel AVR Series
// Editor Tabs : 4
//
// NOTE: This code is currently below version 1.0, and therefore is considered
// to be lacking in some functionality or documentation, or may not be fully
// tested. Nonetheless, you can expect most functions to work.
//
/// \ingroup driver_hw
/// \defgroup nmea NMEA Packet Interface for GPS Receivers (nmea.c)
/// \code #include "nmea.h" \endcode
/// \par Overview
/// This library parses and decodes the standard NMEA data stream from a
/// GPS and stores the position, velocity, and time solutions in the gps.c
/// library.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
#ifndef NMEA_H
#define NMEA_H
 
#include "global.h"
#include "buffer.h"
 
// constants/macros/typdefs
#define NMEA_BUFFERSIZE 80
 
// Message Codes
#define NMEA_NODATA 0 // No data. Packet not available, bad, or not decoded
#define NMEA_GPGGA 1 // Global Positioning System Fix Data
#define NMEA_GPVTG 2 // Course over ground and ground speed
#define NMEA_GPGLL 3 // Geographic position - latitude/longitude
#define NMEA_GPGSV 4 // GPS satellites in view
#define NMEA_GPGSA 5 // GPS DOP and active satellites
#define NMEA_GPRMC 6 // Recommended minimum specific GPS data
#define NMEA_UNKNOWN 0xFF// Packet received but not known
 
// Debugging
//#define NMEA_DEBUG_PKT ///< define to enable debug of all NMEA messages
//#define NMEA_DEBUG_GGA ///< define to enable debug of GGA messages
//#define NMEA_DEBUG_VTG ///< define to enable debug of VTG messages
 
// functions
void nmeaInit(void);
u08* nmeaGetPacketBuffer(void);
u08 nmeaProcess(cBuffer* rxBuffer);
void nmeaProcessGPGGA(u08* packet);
void nmeaProcessGPVTG(u08* packet);
 
#endif
/programy/C/avr/gps/port128.h
0,0 → 1,98
/*! \file port128.h \brief Additional include for Mega128 to define individual port pins. */
//*****************************************************************************
//
// File Name : 'port128.h'
// Title : Additional include for Mega128 to define individual port pins
// Author : Pascal Stang
// Created : 11/18/2002
// Revised : 11/18/2002
// Version : 1.1
// Target MCU : Atmel AVR series
// Editor Tabs : 4
//
// Description : This include file contains additional port and pin defines
// to help make code transparently compatible with the mega128. As in
// the other AVR processors, using defines like PD2 to denote PORTD, pin2
// is not absolutely necessary but enhances readability. The mega128 io.h
// no longer defines individual pins of ports (like PD2 or PA5, for
// example). Instead, port pins are defines universally for all ports as
// PORT0 through PORT7. However, this renaming causes a code-portability
// issue from non-mega128 AVRs to the mega128. Including this file will
// replace the missing defines.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
#ifndef PORT128_H
#define PORT128_H
 
// Mega128 individual port defines
// (using these is technically unnecessary but improves code compatibility to
// the mega128 from other AVR processors where these values were still defined
// in the io.h for that processor)
 
// PORTA
#define PA0 PORT0
#define PA1 PORT1
#define PA2 PORT2
#define PA3 PORT3
#define PA4 PORT4
#define PA5 PORT5
#define PA6 PORT6
#define PA7 PORT7
// PORTB
#define PB0 PORT0
#define PB1 PORT1
#define PB2 PORT2
#define PB3 PORT3
#define PB4 PORT4
#define PB5 PORT5
#define PB6 PORT6
#define PB7 PORT7
// PORTC
#define PC0 PORT0
#define PC1 PORT1
#define PC2 PORT2
#define PC3 PORT3
#define PC4 PORT4
#define PC5 PORT5
#define PC6 PORT6
#define PC7 PORT7
// PORTD
#define PD0 PORT0
#define PD1 PORT1
#define PD2 PORT2
#define PD3 PORT3
#define PD4 PORT4
#define PD5 PORT5
#define PD6 PORT6
#define PD7 PORT7
// PORTE
#define PE0 PORT0
#define PE1 PORT1
#define PE2 PORT2
#define PE3 PORT3
#define PE4 PORT4
#define PE5 PORT5
#define PE6 PORT6
#define PE7 PORT7
// PORTF
#define PF0 PORT0
#define PF1 PORT1
#define PF2 PORT2
#define PF3 PORT3
#define PF4 PORT4
#define PF5 PORT5
#define PF6 PORT6
#define PF7 PORT7
// PORTG
#define PG0 PORT0
#define PG1 PORT1
#define PG2 PORT2
#define PG3 PORT3
#define PG4 PORT4
#define PG5 PORT5
 
#endif
/programy/C/avr/gps/rprintf.c
0,0 → 1,782
/*! \file rprintf.c \brief printf routine and associated routines. */
//*****************************************************************************
//
// File Name : 'rprintf.c'
// Title : printf routine and associated routines
// Author : Pascal Stang - Copyright (C) 2000-2002
// Created : 2000.12.26
// Revised : 2003.5.1
// Version : 1.0
// Target MCU : Atmel AVR series and other targets
// Editor Tabs : 4
//
// NOTE: This code is currently below version 1.0, and therefore is considered
// to be lacking in some functionality or documentation, or may not be fully
// tested. Nonetheless, you can expect most functions to work.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
#include <avr/pgmspace.h>
//#include <string-avr.h>
//#include <stdlib.h>
#include <stdarg.h>
#include "global.h"
#include "rprintf.h"
 
#ifndef TRUE
#define TRUE -1
#define FALSE 0
#endif
 
#define INF 32766 // maximum field size to print
#define READMEMBYTE(a,char_ptr) ((a)?(pgm_read_byte(char_ptr)):(*char_ptr))
 
#ifdef RPRINTF_COMPLEX
static unsigned char buf[128];
#endif
 
// use this to store hex conversion in RAM
//static char HexChars[] = "0123456789ABCDEF";
// use this to store hex conversion in program memory
//static prog_char HexChars[] = "0123456789ABCDEF";
static char __attribute__ ((progmem)) HexChars[] = "0123456789ABCDEF";
 
#define hexchar(x) pgm_read_byte( HexChars+((x)&0x0f) )
//#define hexchar(x) ((((x)&0x0F)>9)?((x)+'A'-10):((x)+'0'))
 
// function pointer to single character output routine
static void (*rputchar)(unsigned char c);
 
// *** rprintf initialization ***
// you must call this function once and supply the character output
// routine before using other functions in this library
void rprintfInit(void (*putchar_func)(unsigned char c))
{
rputchar = putchar_func;
}
 
// *** rprintfChar ***
// send a character/byte to the current output device
void rprintfChar(unsigned char c)
{
// do LF -> CR/LF translation
if(c == '\n')
rputchar('\r');
// send character
rputchar(c);
}
 
// *** rprintfStr ***
// prints a null-terminated string stored in RAM
void rprintfStr(char str[])
{
// send a string stored in RAM
// check to make sure we have a good pointer
if (!str) return;
 
// print the string until a null-terminator
while (*str)
rprintfChar(*str++);
}
 
// *** rprintfStrLen ***
// prints a section of a string stored in RAM
// begins printing at position indicated by <start>
// prints number of characters indicated by <len>
void rprintfStrLen(char str[], unsigned int start, unsigned int len)
{
register int i=0;
 
// check to make sure we have a good pointer
if (!str) return;
// spin through characters up to requested start
// keep going as long as there's no null
while((i++<start) && (*str++));
// for(i=0; i<start; i++)
// {
// // keep steping through string as long as there's no null
// if(*str) str++;
// }
 
// then print exactly len characters
for(i=0; i<len; i++)
{
// print data out of the string as long as we haven't reached a null yet
// at the null, start printing spaces
if(*str)
rprintfChar(*str++);
else
rprintfChar(' ');
}
 
}
 
// *** rprintfProgStr ***
// prints a null-terminated string stored in program ROM
void rprintfProgStr(const prog_char str[])
{
// print a string stored in program memory
register char c;
 
// check to make sure we have a good pointer
if (!str) return;
// print the string until the null-terminator
while((c = pgm_read_byte(str++)))
rprintfChar(c);
}
 
// *** rprintfCRLF ***
// prints carriage return and line feed
void rprintfCRLF(void)
{
// print CR/LF
//rprintfChar('\r');
// LF -> CR/LF translation built-in to rprintfChar()
rprintfChar('\n');
}
 
// *** rprintfu04 ***
// prints an unsigned 4-bit number in hex (1 digit)
void rprintfu04(unsigned char data)
{
// print 4-bit hex value
// char Character = data&0x0f;
// if (Character>9)
// Character+='A'-10;
// else
// Character+='0';
rprintfChar(hexchar(data));
}
 
// *** rprintfu08 ***
// prints an unsigned 8-bit number in hex (2 digits)
void rprintfu08(unsigned char data)
{
// print 8-bit hex value
rprintfu04(data>>4);
rprintfu04(data);
}
 
// *** rprintfu16 ***
// prints an unsigned 16-bit number in hex (4 digits)
void rprintfu16(unsigned short data)
{
// print 16-bit hex value
rprintfu08(data>>8);
rprintfu08(data);
}
 
// *** rprintfu32 ***
// prints an unsigned 32-bit number in hex (8 digits)
void rprintfu32(unsigned long data)
{
// print 32-bit hex value
rprintfu16(data>>16);
rprintfu16(data);
}
 
// *** rprintfNum ***
// special printf for numbers only
// see formatting information below
// Print the number "n" in the given "base"
// using exactly "numDigits"
// print +/- if signed flag "isSigned" is TRUE
// use the character specified in "padchar" to pad extra characters
//
// Examples:
// uartPrintfNum(10, 6, TRUE, ' ', 1234); --> " +1234"
// uartPrintfNum(10, 6, FALSE, '0', 1234); --> "001234"
// uartPrintfNum(16, 6, FALSE, '.', 0x5AA5); --> "..5AA5"
void rprintfNum(char base, char numDigits, char isSigned, char padchar, long n)
{
// define a global HexChars or use line below
//static char HexChars[16] = "0123456789ABCDEF";
char *p, buf[32];
unsigned long x;
unsigned char count;
 
// prepare negative number
if( isSigned && (n < 0) )
{
x = -n;
}
else
{
x = n;
}
 
// setup little string buffer
count = (numDigits-1)-(isSigned?1:0);
p = buf + sizeof (buf);
*--p = '\0';
// force calculation of first digit
// (to prevent zero from not printing at all!!!)
*--p = hexchar(x%base); x /= base;
// calculate remaining digits
while(count--)
{
if(x != 0)
{
// calculate next digit
*--p = hexchar(x%base); x /= base;
}
else
{
// no more digits left, pad out to desired length
*--p = padchar;
}
}
 
// apply signed notation if requested
if( isSigned )
{
if(n < 0)
{
*--p = '-';
}
else if(n > 0)
{
*--p = '+';
}
else
{
*--p = ' ';
}
}
 
// print the string right-justified
count = numDigits;
while(count--)
{
rprintfChar(*p++);
}
}
 
#ifdef RPRINTF_FLOAT
// *** rprintfFloat ***
// floating-point print
void rprintfFloat(char numDigits, double x)
{
unsigned char firstplace = FALSE;
unsigned char negative;
unsigned char i, digit;
double place = 1.0;
// save sign
negative = (x<0);
// convert to absolute value
x = (x>0)?(x):(-x);
// find starting digit place
for(i=0; i<15; i++)
{
if((x/place) < 10.0)
break;
else
place *= 10.0;
}
// print polarity character
if(negative)
rprintfChar('-');
else
rprintfChar('+');
 
// print digits
for(i=0; i<numDigits; i++)
{
digit = (x/place);
 
if(digit | firstplace | (place == 1.0))
{
firstplace = TRUE;
rprintfChar(digit+0x30);
}
else
rprintfChar(' ');
if(place == 1.0)
{
rprintfChar('.');
}
x -= (digit*place);
place /= 10.0;
}
}
#endif
 
#ifdef RPRINTF_SIMPLE
// *** rprintf1RamRom ***
// called by rprintf() - does a simple printf (supports %d, %x, %c)
// Supports:
// %d - decimal
// %x - hex
// %c - character
int rprintf1RamRom(unsigned char stringInRom, const char *format, ...)
{
// simple printf routine
// define a global HexChars or use line below
//static char HexChars[16] = "0123456789ABCDEF";
char format_flag;
unsigned int u_val, div_val, base;
va_list ap;
 
va_start(ap, format);
for (;;)
{
while ((format_flag = READMEMBYTE(stringInRom,format++) ) != '%')
{ // Until '%' or '\0'
if (!format_flag)
{
va_end(ap);
return(0);
}
rprintfChar(format_flag);
}
 
switch (format_flag = READMEMBYTE(stringInRom,format++) )
{
case 'c': format_flag = va_arg(ap,int);
default: rprintfChar(format_flag); continue;
case 'd': base = 10; div_val = 10000; goto CONVERSION_LOOP;
// case 'x': base = 16; div_val = 0x10;
case 'x': base = 16; div_val = 0x1000;
 
CONVERSION_LOOP:
u_val = va_arg(ap,int);
if (format_flag == 'd')
{
if (((int)u_val) < 0)
{
u_val = - u_val;
rprintfChar('-');
}
while (div_val > 1 && div_val > u_val) div_val /= 10;
}
do
{
//rprintfChar(pgm_read_byte(HexChars+(u_val/div_val)));
rprintfu04(u_val/div_val);
u_val %= div_val;
div_val /= base;
} while (div_val);
}
}
va_end(ap);
}
#endif
 
 
#ifdef RPRINTF_COMPLEX
// *** rprintf2RamRom ***
// called by rprintf() - does a more powerful printf (supports %d, %u, %o, %x, %c, %s)
// Supports:
// %d - decimal
// %u - unsigned decimal
// %o - octal
// %x - hex
// %c - character
// %s - strings
// and the width,precision,padding modifiers
// **this printf does not support floating point numbers
int rprintf2RamRom(unsigned char stringInRom, const char *sfmt, ...)
{
register unsigned char *f, *bp;
register long l;
register unsigned long u;
register int i;
register int fmt;
register unsigned char pad = ' ';
int flush_left = 0, f_width = 0, prec = INF, hash = 0, do_long = 0;
int sign = 0;
 
va_list ap;
va_start(ap, sfmt);
 
f = (unsigned char *) sfmt;
 
for (; READMEMBYTE(stringInRom,f); f++)
{
if (READMEMBYTE(stringInRom,f) != '%')
{ // not a format character
// then just output the char
rprintfChar(READMEMBYTE(stringInRom,f));
}
else
{
f++; // if we have a "%" then skip it
if (READMEMBYTE(stringInRom,f) == '-')
{
flush_left = 1; // minus: flush left
f++;
}
if (READMEMBYTE(stringInRom,f) == '0'
|| READMEMBYTE(stringInRom,f) == '.')
{
// padding with 0 rather than blank
pad = '0';
f++;
}
if (READMEMBYTE(stringInRom,f) == '*')
{ // field width
f_width = va_arg(ap, int);
f++;
}
else if (Isdigit(READMEMBYTE(stringInRom,f)))
{
f_width = atoiRamRom(stringInRom, (char *) f);
while (Isdigit(READMEMBYTE(stringInRom,f)))
f++; // skip the digits
}
if (READMEMBYTE(stringInRom,f) == '.')
{ // precision
f++;
if (READMEMBYTE(stringInRom,f) == '*')
{
prec = va_arg(ap, int);
f++;
}
else if (Isdigit(READMEMBYTE(stringInRom,f)))
{
prec = atoiRamRom(stringInRom, (char *) f);
while (Isdigit(READMEMBYTE(stringInRom,f)))
f++; // skip the digits
}
}
if (READMEMBYTE(stringInRom,f) == '#')
{ // alternate form
hash = 1;
f++;
}
if (READMEMBYTE(stringInRom,f) == 'l')
{ // long format
do_long = 1;
f++;
}
 
fmt = READMEMBYTE(stringInRom,f);
bp = buf;
switch (fmt) { // do the formatting
case 'd': // 'd' signed decimal
if (do_long)
l = va_arg(ap, long);
else
l = (long) (va_arg(ap, int));
if (l < 0)
{
sign = 1;
l = -l;
}
do {
*bp++ = l % 10 + '0';
} while ((l /= 10) > 0);
if (sign)
*bp++ = '-';
f_width = f_width - (bp - buf);
if (!flush_left)
while (f_width-- > 0)
rprintfChar(pad);
for (bp--; bp >= buf; bp--)
rprintfChar(*bp);
if (flush_left)
while (f_width-- > 0)
rprintfChar(' ');
break;
case 'o': // 'o' octal number
case 'x': // 'x' hex number
case 'u': // 'u' unsigned decimal
if (do_long)
u = va_arg(ap, unsigned long);
else
u = (unsigned long) (va_arg(ap, unsigned));
if (fmt == 'u')
{ // unsigned decimal
do {
*bp++ = u % 10 + '0';
} while ((u /= 10) > 0);
}
else if (fmt == 'o')
{ // octal
do {
*bp++ = u % 8 + '0';
} while ((u /= 8) > 0);
if (hash)
*bp++ = '0';
}
else if (fmt == 'x')
{ // hex
do {
i = u % 16;
if (i < 10)
*bp++ = i + '0';
else
*bp++ = i - 10 + 'a';
} while ((u /= 16) > 0);
if (hash)
{
*bp++ = 'x';
*bp++ = '0';
}
}
i = f_width - (bp - buf);
if (!flush_left)
while (i-- > 0)
rprintfChar(pad);
for (bp--; bp >= buf; bp--)
rprintfChar((int) (*bp));
if (flush_left)
while (i-- > 0)
rprintfChar(' ');
break;
case 'c': // 'c' character
i = va_arg(ap, int);
rprintfChar((int) (i));
break;
case 's': // 's' string
bp = va_arg(ap, unsigned char *);
if (!bp)
bp = (unsigned char *) "(nil)";
f_width = f_width - strlen((char *) bp);
if (!flush_left)
while (f_width-- > 0)
rprintfChar(pad);
for (i = 0; *bp && i < prec; i++)
{
rprintfChar(*bp);
bp++;
}
if (flush_left)
while (f_width-- > 0)
rprintfChar(' ');
break;
case '%': // '%' character
rprintfChar('%');
break;
}
flush_left = 0, f_width = 0, prec = INF, hash = 0, do_long = 0;
sign = 0;
pad = ' ';
}
}
 
va_end(ap);
return 0;
}
 
unsigned char Isdigit(char c)
{
if((c >= 0x30) && (c <= 0x39))
return TRUE;
else
return FALSE;
}
 
int atoiRamRom(unsigned char stringInRom, char *str)
{
int num = 0;;
 
while(Isdigit(READMEMBYTE(stringInRom,str)))
{
num *= 10;
num += ((READMEMBYTE(stringInRom,str++)) - 0x30);
}
return num;
}
 
#endif
 
//******************************************************************************
// code below this line is commented out and can be ignored
//******************************************************************************
/*
char* sprintf(const char *sfmt, ...)
{
register unsigned char *f, *bp, *str;
register long l;
register unsigned long u;
register int i;
register int fmt;
register unsigned char pad = ' ';
int flush_left = 0, f_width = 0, prec = INF, hash = 0, do_long = 0;
int sign = 0;
 
va_list ap;
va_start(ap, sfmt);
 
str = bufstring;
f = (unsigned char *) sfmt;
 
for (; *f; f++)
{
if (*f != '%')
{ // not a format character
*str++ = (*f); // then just output the char
}
else
{
f++; // if we have a "%" then skip it
if (*f == '-')
{
flush_left = 1; // minus: flush left
f++;
}
if (*f == '0' || *f == '.')
{
// padding with 0 rather than blank
pad = '0';
f++;
}
if (*f == '*')
{ // field width
f_width = va_arg(ap, int);
f++;
}
else if (Isdigit(*f))
{
f_width = atoi((char *) f);
while (Isdigit(*f))
f++; // skip the digits
}
if (*f == '.')
{ // precision
f++;
if (*f == '*')
{
prec = va_arg(ap, int);
f++;
}
else if (Isdigit(*f))
{
prec = atoi((char *) f);
while (Isdigit(*f))
f++; // skip the digits
}
}
if (*f == '#')
{ // alternate form
hash = 1;
f++;
}
if (*f == 'l')
{ // long format
do_long = 1;
f++;
}
 
fmt = *f;
bp = buf;
switch (fmt) { // do the formatting
case 'd': // 'd' signed decimal
if (do_long)
l = va_arg(ap, long);
else
l = (long) (va_arg(ap, int));
if (l < 0)
{
sign = 1;
l = -l;
}
do {
*bp++ = l % 10 + '0';
} while ((l /= 10) > 0);
if (sign)
*bp++ = '-';
f_width = f_width - (bp - buf);
if (!flush_left)
while (f_width-- > 0)
*str++ = (pad);
for (bp--; bp >= buf; bp--)
*str++ = (*bp);
if (flush_left)
while (f_width-- > 0)
*str++ = (' ');
break;
case 'o': // 'o' octal number
case 'x': // 'x' hex number
case 'u': // 'u' unsigned decimal
if (do_long)
u = va_arg(ap, unsigned long);
else
u = (unsigned long) (va_arg(ap, unsigned));
if (fmt == 'u')
{ // unsigned decimal
do {
*bp++ = u % 10 + '0';
} while ((u /= 10) > 0);
}
else if (fmt == 'o')
{ // octal
do {
*bp++ = u % 8 + '0';
} while ((u /= 8) > 0);
if (hash)
*bp++ = '0';
}
else if (fmt == 'x')
{ // hex
do {
i = u % 16;
if (i < 10)
*bp++ = i + '0';
else
*bp++ = i - 10 + 'a';
} while ((u /= 16) > 0);
if (hash)
{
*bp++ = 'x';
*bp++ = '0';
}
}
i = f_width - (bp - buf);
if (!flush_left)
while (i-- > 0)
*str++ = (pad);
for (bp--; bp >= buf; bp--)
*str++ = ((int) (*bp));
if (flush_left)
while (i-- > 0)
*str++ = (' ');
break;
case 'c': // 'c' character
i = va_arg(ap, int);
*str++ = ((int) (i));
break;
case 's': // 's' string
bp = va_arg(ap, unsigned char *);
if (!bp)
bp = (unsigned char *) "(nil)";
f_width = f_width - strlen((char *) bp);
if (!flush_left)
while (f_width-- > 0)
*str++ = (pad);
for (i = 0; *bp && i < prec; i++)
{
*str++ = (*bp);
bp++;
}
if (flush_left)
while (f_width-- > 0)
*str++ = (' ');
break;
case '%': // '%' character
*str++ = ('%');
break;
}
flush_left = 0, f_width = 0, prec = INF, hash = 0, do_long = 0;
sign = 0;
pad = ' ';
}
}
 
va_end(ap);
// terminate string with null
*str++ = '\0';
return bufstring;
}
 
*/
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/gps/rprintf.h
0,0 → 1,191
/*! \file rprintf.h \brief printf routine and associated routines. */
//****************************************************************************
//
// File Name : 'rprintf.h'
// Title : printf routine and associated routines
// Author : Pascal Stang - Copyright (C) 2000-2002
// Created : 2000.12.26
// Revised : 2003.5.1
// Version : 1.0
// Target MCU : Atmel AVR series and other targets
// Editor Tabs : 4
//
// NOTE: This code is currently below version 1.0, and therefore is considered
// to be lacking in some functionality or documentation, or may not be fully
// tested. Nonetheless, you can expect most functions to work.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
/// \ingroup general
/// \defgroup rprintf printf() Function Library (rprintf.c)
/// \code #include "rprintf.h" \endcode
/// \par Overview
/// The rprintf function library provides a simplified (reduced) version of
/// the common C printf() function.  See the code files for details about
/// which printf features are supported.  Also in this library are a
/// variety of functions for fast printing of certain common data types
/// (variable types).  Functions include print string from RAM, print
/// string from ROM, print string snippet, print hex byte/short/long, and
/// a custom-formatted number print, as well as an optional floating-point
/// print routine.
///
/// \note All output from the rprintf library can be directed to any device
/// or software which accepts characters.  This means that rprintf output
/// can be sent to the UART (serial port) or can be used with the LCD
/// display libraries to print formatted text on the screen.
//
//****************************************************************************
//@{
 
#ifndef RPRINTF_H
#define RPRINTF_H
 
// needed for use of PSTR below
#include <avr/pgmspace.h>
 
// configuration
// defining RPRINTF_SIMPLE will compile a smaller, simpler, and faster printf() function
// defining RPRINTF_COMPLEX will compile a larger, more capable, and slower printf() function
#ifndef RPRINTF_COMPLEX
#define RPRINTF_SIMPLE
#endif
 
// Define RPRINTF_FLOAT to enable the floating-point printf function: rprintfFloat()
// (adds +4600bytes or 2.2Kwords of code)
 
// defines/constants
#define STRING_IN_RAM 0
#define STRING_IN_ROM 1
 
// make a putchar for those that are used to using it
//#define putchar(c) rprintfChar(c);
 
// functions
 
//! Initializes the rprintf library for an output stream.
/// You must call this initializer once before using any other rprintf function.
/// The argument must be a character stream output function.
void rprintfInit(void (*putchar_func)(unsigned char c));
 
//! prints a single character to the current output device
void rprintfChar(unsigned char c);
 
//! prints a null-terminated string stored in RAM
void rprintfStr(char str[]);
 
//! Prints a section of a string stored in RAM.
/// Begins printing at position indicated by <start>,
/// and prints number of characters indicated by <len>.
void rprintfStrLen(char str[], unsigned int start, unsigned int len);
 
//! prints a string stored in program rom
/// \note This function does not actually store your string in
/// program rom, but merely reads it assuming you stored it properly.
void rprintfProgStr(const prog_char str[]);
 
//! Using the function rprintfProgStrM(...) automatically causes
/// your string to be stored in ROM, thereby not wasting precious RAM.
/// Example usage:
/// \code
/// rprintfProgStrM("Hello, this string is stored in program rom");
/// \endcode
#define rprintfProgStrM(string) (rprintfProgStr(PSTR(string)))
 
//! Prints a carriage-return and line-feed.
/// Useful when printing to serial ports/terminals.
void rprintfCRLF(void);
 
// Prints the number contained in "data" in hex format
// u04,u08,u16,and u32 functions handle 4,8,16,or 32 bits respectively
void rprintfu04(unsigned char data); ///< Print 4-bit hex number. Outputs a single hex character.
void rprintfu08(unsigned char data); ///< Print 8-bit hex number. Outputs two hex characters.
void rprintfu16(unsigned short data); ///< Print 16-bit hex number. Outputs four hex characters.
void rprintfu32(unsigned long data); ///< Print 32-bit hex number. Outputs eight hex characters.
 
//! A flexible integer-number printing routine.
/// Print the number "n" in the given "base", using exactly "numDigits".
/// Print +/- if signed flag "isSigned" is TRUE.
/// The character specified in "padchar" will be used to pad extra characters.
///
/// Examples:
/// \code
/// uartPrintfNum(10, 6, TRUE, ' ', 1234); --> " +1234"
/// uartPrintfNum(10, 6, FALSE, '0', 1234); --> "001234"
/// uartPrintfNum(16, 6, FALSE, '.', 0x5AA5); --> "..5AA5"
/// \endcode
void rprintfNum(char base, char numDigits, char isSigned, char padchar, long n);
 
#ifdef RPRINTF_FLOAT
//! floating-point print routine
void rprintfFloat(char numDigits, double x);
#endif
 
// NOTE: Below you'll see the function prototypes of rprintf1RamRom and
// rprintf2RamRom. rprintf1RamRom and rprintf2RamRom are both reduced versions
// of the regular C printf() command. However, they are modified to be able
// to read their text/format strings from RAM or ROM in the Atmel microprocessors.
// Unless you really intend to, do not use the "RamRom" versions of the functions
// directly. Instead use the #defined function versions:
//
// printfx("text/format",args) ...to keep your text/format string stored in RAM
// - or -
// printfxROM("text/format",args) ...to keep your text/format string stored in ROM
//
// where x is either 1 or 2 for the simple or more powerful version of printf()
//
// Since there is much more ROM than RAM available in the Atmel microprocessors,
// and nearly all text/format strings are constant (never change in the course
// of the program), you should try to use the ROM printf version exclusively.
// This will ensure you leave as much RAM as possible for program variables and
// data.
 
//! \fn int rprintf(const char *format, ...);
/// A reduced substitute for the usual C printf() function.
/// This function actually points to either rprintf1RamRom or rprintf2RamRom
/// depending on the user's selection. Rprintf1 is a simple small fast print
/// routine while rprintf2 is larger and slower but more capable. To choose
/// the routine you would like to use, define either RPRINTF_SIMPLE or
/// RPRINTF_COMPLEX in global.h.
 
#ifdef RPRINTF_SIMPLE
//! A simple printf routine.
/// Called by rprintf() - does a simple printf (supports %d, %x, %c).
/// Supports:
/// - %d - decimal
/// - %x - hex
/// - %c - character
int rprintf1RamRom(unsigned char stringInRom, const char *format, ...);
// #defines for RAM or ROM operation
#define rprintf1(format, args...) rprintf1RamRom(STRING_IN_ROM, PSTR(format), ## args)
#define rprintf1RAM(format, args...) rprintf1RamRom(STRING_IN_RAM, format, ## args)
 
// *** Default rprintf(...) ***
// this next line determines what the the basic rprintf() defaults to:
#define rprintf(format, args...) rprintf1RamRom(STRING_IN_ROM, PSTR(format), ## args)
#endif
 
#ifdef RPRINTF_COMPLEX
//! A more powerful printf routine.
/// Called by rprintf() - does a more powerful printf (supports %d, %u, %o, %x, %c, %s).
/// Supports:
/// - %d - decimal
/// - %u - unsigned decimal
/// - %o - octal
/// - %x - hex
/// - %c - character
/// - %s - strings
/// - and the width,precision,padding modifiers
/// \note This printf does not support floating point numbers.
int rprintf2RamRom(unsigned char stringInRom, const char *sfmt, ...);
// #defines for RAM or ROM operation
#define rprintf2(format, args...) rprintf2RamRom(STRING_IN_ROM, format, ## args)
#define rprintf2RAM(format, args...) rprintf2RamRom(STRING_IN_RAM, format, ## args)
 
// *** Default rprintf(...) ***
// this next line determines what the the basic rprintf() defaults to:
#define rprintf(format, args...) rprintf2RamRom(STRING_IN_ROM, PSTR(format), ## args)
#endif
 
#endif
//@}
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/gps/timer.c
0,0 → 1,469
/*! \file timer.c \brief System Timer function library. */
//*****************************************************************************
//
// File Name : 'timer.c'
// Title : System Timer function library
// Author : Pascal Stang - Copyright (C) 2000-2002
// Created : 11/22/2000
// Revised : 07/09/2003
// Version : 1.1
// Target MCU : Atmel AVR Series
// Editor Tabs : 4
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <avr/sleep.h>
 
#include "global.h"
#include "timer.h"
 
#include "rprintf.h"
 
// Program ROM constants
// the prescale division values stored in order of timer control register index
// STOP, CLK, CLK/8, CLK/64, CLK/256, CLK/1024
unsigned short __attribute__ ((progmem)) TimerPrescaleFactor[] = {0,1,8,64,256,1024};
// the prescale division values stored in order of timer control register index
// STOP, CLK, CLK/8, CLK/32, CLK/64, CLK/128, CLK/256, CLK/1024
unsigned short __attribute__ ((progmem)) TimerRTCPrescaleFactor[] = {0,1,8,32,64,128,256,1024};
 
// Global variables
// time registers
volatile unsigned long TimerPauseReg;
volatile unsigned long Timer0Reg0;
volatile unsigned long Timer2Reg0;
 
typedef void (*voidFuncPtr)(void);
volatile static voidFuncPtr TimerIntFunc[TIMER_NUM_INTERRUPTS];
 
// delay for a minimum of <us> microseconds
// the time resolution is dependent on the time the loop takes
// e.g. with 4Mhz and 5 cycles per loop, the resolution is 1.25 us
void delay_us(unsigned short time_us)
{
unsigned short delay_loops;
register unsigned short i;
 
delay_loops = (time_us+3)/5*CYCLES_PER_US; // +3 for rounding up (dirty)
 
// one loop takes 5 cpu cycles
for (i=0; i < delay_loops; i++) {};
}
/*
void delay_ms(unsigned char time_ms)
{
unsigned short delay_count = F_CPU / 4000;
 
unsigned short cnt;
asm volatile ("\n"
"L_dl1%=:\n\t"
"mov %A0, %A2\n\t"
"mov %B0, %B2\n"
"L_dl2%=:\n\t"
"sbiw %A0, 1\n\t"
"brne L_dl2%=\n\t"
"dec %1\n\t" "brne L_dl1%=\n\t":"=&w" (cnt)
:"r"(time_ms), "r"((unsigned short) (delay_count))
);
}
*/
void timerInit(void)
{
u08 intNum;
// detach all user functions from interrupts
for(intNum=0; intNum<TIMER_NUM_INTERRUPTS; intNum++)
timerDetach(intNum);
 
// initialize all timers
timer0Init();
timer1Init();
#ifdef TCNT2 // support timer2 only if it exists
timer2Init();
#endif
// enable interrupts
sei();
}
 
void timer0Init()
{
// initialize timer 0
timer0SetPrescaler( TIMER0PRESCALE ); // set prescaler
outb(TCNT0, 0); // reset TCNT0
sbi(TIMSK, TOIE0); // enable TCNT0 overflow interrupt
 
timer0ClearOverflowCount(); // initialize time registers
}
 
void timer1Init(void)
{
// initialize timer 1
timer1SetPrescaler( TIMER1PRESCALE ); // set prescaler
outb(TCNT1H, 0); // reset TCNT1
outb(TCNT1L, 0);
sbi(TIMSK, TOIE1); // enable TCNT1 overflow
}
 
#ifdef TCNT2 // support timer2 only if it exists
void timer2Init(void)
{
// initialize timer 2
timer2SetPrescaler( TIMER2PRESCALE ); // set prescaler
outb(TCNT2, 0); // reset TCNT2
sbi(TIMSK, TOIE2); // enable TCNT2 overflow
 
timer2ClearOverflowCount(); // initialize time registers
}
#endif
 
void timer0SetPrescaler(u08 prescale)
{
// set prescaler on timer 0
outb(TCCR0, (inb(TCCR0) & ~TIMER_PRESCALE_MASK) | prescale);
}
 
void timer1SetPrescaler(u08 prescale)
{
// set prescaler on timer 1
outb(TCCR1B, (inb(TCCR1B) & ~TIMER_PRESCALE_MASK) | prescale);
}
 
#ifdef TCNT2 // support timer2 only if it exists
void timer2SetPrescaler(u08 prescale)
{
// set prescaler on timer 2
outb(TCCR2, (inb(TCCR2) & ~TIMER_PRESCALE_MASK) | prescale);
}
#endif
 
u16 timer0GetPrescaler(void)
{
// get the current prescaler setting
return (pgm_read_word(TimerPrescaleFactor+(inb(TCCR0) & TIMER_PRESCALE_MASK)));
}
 
u16 timer1GetPrescaler(void)
{
// get the current prescaler setting
return (pgm_read_word(TimerPrescaleFactor+(inb(TCCR1B) & TIMER_PRESCALE_MASK)));
}
 
#ifdef TCNT2 // support timer2 only if it exists
u16 timer2GetPrescaler(void)
{
//TODO: can we assume for all 3-timer AVR processors,
// that timer2 is the RTC timer?
 
// get the current prescaler setting
return (pgm_read_word(TimerRTCPrescaleFactor+(inb(TCCR2) & TIMER_PRESCALE_MASK)));
}
#endif
 
void timerAttach(u08 interruptNum, void (*userFunc)(void) )
{
// make sure the interrupt number is within bounds
if(interruptNum < TIMER_NUM_INTERRUPTS)
{
// set the interrupt function to run
// the supplied user's function
TimerIntFunc[interruptNum] = userFunc;
}
}
 
void timerDetach(u08 interruptNum)
{
// make sure the interrupt number is within bounds
if(interruptNum < TIMER_NUM_INTERRUPTS)
{
// set the interrupt function to run nothing
TimerIntFunc[interruptNum] = 0;
}
}
/*
u32 timerMsToTics(u16 ms)
{
// calculate the prescaler division rate
u16 prescaleDiv = 1<<(pgm_read_byte(TimerPrescaleFactor+inb(TCCR0)));
// calculate the number of timer tics in x milliseconds
return (ms*(F_CPU/(prescaleDiv*256)))/1000;
}
 
u16 timerTicsToMs(u32 tics)
{
// calculate the prescaler division rate
u16 prescaleDiv = 1<<(pgm_read_byte(TimerPrescaleFactor+inb(TCCR0)));
// calculate the number of milliseconds in x timer tics
return (tics*1000*(prescaleDiv*256))/F_CPU;
}
*/
void timerPause(unsigned short pause_ms)
{
// pauses for exactly <pause_ms> number of milliseconds
u08 timerThres;
u32 ticRateHz;
u32 pause;
 
// capture current pause timer value
timerThres = inb(TCNT0);
// reset pause timer overflow count
TimerPauseReg = 0;
// calculate delay for [pause_ms] milliseconds
// prescaler division = 1<<(pgm_read_byte(TimerPrescaleFactor+inb(TCCR0)))
ticRateHz = F_CPU/timer0GetPrescaler();
// precision management
// prevent overflow and precision underflow
// -could add more conditions to improve accuracy
if( ((ticRateHz < 429497) && (pause_ms <= 10000)) )
pause = (pause_ms*ticRateHz)/1000;
else
pause = pause_ms*(ticRateHz/1000);
 
// loop until time expires
while( ((TimerPauseReg<<8) | inb(TCNT0)) < (pause+timerThres) )
{
if( TimerPauseReg < (pause>>8));
{
// save power by idling the processor
set_sleep_mode(SLEEP_MODE_IDLE);
sleep_mode();
}
}
 
/* old inaccurate code, for reference
// calculate delay for [pause_ms] milliseconds
u16 prescaleDiv = 1<<(pgm_read_byte(TimerPrescaleFactor+inb(TCCR0)));
u32 pause = (pause_ms*(F_CPU/(prescaleDiv*256)))/1000;
TimerPauseReg = 0;
while(TimerPauseReg < pause);
 
*/
}
 
void timer0ClearOverflowCount(void)
{
// clear the timer overflow counter registers
Timer0Reg0 = 0; // initialize time registers
}
 
long timer0GetOverflowCount(void)
{
// return the current timer overflow count
// (this is since the last timer0ClearOverflowCount() command was called)
return Timer0Reg0;
}
 
#ifdef TCNT2 // support timer2 only if it exists
void timer2ClearOverflowCount(void)
{
// clear the timer overflow counter registers
Timer2Reg0 = 0; // initialize time registers
}
 
long timer2GetOverflowCount(void)
{
// return the current timer overflow count
// (this is since the last timer2ClearOverflowCount() command was called)
return Timer2Reg0;
}
#endif
 
void timer1PWMInit(u08 bitRes)
{
// configures timer1 for use with PWM output
// on OC1A and OC1B pins
 
// enable timer1 as 8,9,10bit PWM
if(bitRes == 9)
{ // 9bit mode
sbi(TCCR1A,PWM11);
cbi(TCCR1A,PWM10);
}
else if( bitRes == 10 )
{ // 10bit mode
sbi(TCCR1A,PWM11);
sbi(TCCR1A,PWM10);
}
else
{ // default 8bit mode
cbi(TCCR1A,PWM11);
sbi(TCCR1A,PWM10);
}
 
// clear output compare value A
outb(OCR1AH, 0);
outb(OCR1AL, 0);
// clear output compare value B
outb(OCR1BH, 0);
outb(OCR1BL, 0);
}
 
#ifdef WGM10
// include support for arbitrary top-count PWM
// on new AVR processors that support it
void timer1PWMInitICR(u16 topcount)
{
// set PWM mode with ICR top-count
cbi(TCCR1A,WGM10);
sbi(TCCR1A,WGM11);
sbi(TCCR1B,WGM12);
sbi(TCCR1B,WGM13);
// set top count value
ICR1 = topcount;
// clear output compare value A
OCR1A = 0;
// clear output compare value B
OCR1B = 0;
 
}
#endif
 
void timer1PWMOff(void)
{
// turn off timer1 PWM mode
cbi(TCCR1A,PWM11);
cbi(TCCR1A,PWM10);
// set PWM1A/B (OutputCompare action) to none
timer1PWMAOff();
timer1PWMBOff();
}
 
void timer1PWMAOn(void)
{
// turn on channel A (OC1A) PWM output
// set OC1A as non-inverted PWM
sbi(TCCR1A,COM1A1);
cbi(TCCR1A,COM1A0);
}
 
void timer1PWMBOn(void)
{
// turn on channel B (OC1B) PWM output
// set OC1B as non-inverted PWM
sbi(TCCR1A,COM1B1);
cbi(TCCR1A,COM1B0);
}
 
void timer1PWMAOff(void)
{
// turn off channel A (OC1A) PWM output
// set OC1A (OutputCompare action) to none
cbi(TCCR1A,COM1A1);
cbi(TCCR1A,COM1A0);
}
 
void timer1PWMBOff(void)
{
// turn off channel B (OC1B) PWM output
// set OC1B (OutputCompare action) to none
cbi(TCCR1A,COM1B1);
cbi(TCCR1A,COM1B0);
}
 
void timer1PWMASet(u16 pwmDuty)
{
// set PWM (output compare) duty for channel A
// this PWM output is generated on OC1A pin
// NOTE: pwmDuty should be in the range 0-255 for 8bit PWM
// pwmDuty should be in the range 0-511 for 9bit PWM
// pwmDuty should be in the range 0-1023 for 10bit PWM
//outp( (pwmDuty>>8), OCR1AH); // set the high 8bits of OCR1A
//outp( (pwmDuty&0x00FF), OCR1AL); // set the low 8bits of OCR1A
OCR1A = pwmDuty;
}
 
void timer1PWMBSet(u16 pwmDuty)
{
// set PWM (output compare) duty for channel B
// this PWM output is generated on OC1B pin
// NOTE: pwmDuty should be in the range 0-255 for 8bit PWM
// pwmDuty should be in the range 0-511 for 9bit PWM
// pwmDuty should be in the range 0-1023 for 10bit PWM
//outp( (pwmDuty>>8), OCR1BH); // set the high 8bits of OCR1B
//outp( (pwmDuty&0x00FF), OCR1BL); // set the low 8bits of OCR1B
OCR1B = pwmDuty;
}
 
//! Interrupt handler for tcnt0 overflow interrupt
TIMER_INTERRUPT_HANDLER(SIG_OVERFLOW0)
{
Timer0Reg0++; // increment low-order counter
 
// increment pause counter
TimerPauseReg++;
 
// if a user function is defined, execute it too
if(TimerIntFunc[TIMER0OVERFLOW_INT])
TimerIntFunc[TIMER0OVERFLOW_INT]();
}
 
//! Interrupt handler for tcnt1 overflow interrupt
TIMER_INTERRUPT_HANDLER(SIG_OVERFLOW1)
{
// if a user function is defined, execute it
if(TimerIntFunc[TIMER1OVERFLOW_INT])
TimerIntFunc[TIMER1OVERFLOW_INT]();
}
 
#ifdef TCNT2 // support timer2 only if it exists
//! Interrupt handler for tcnt2 overflow interrupt
TIMER_INTERRUPT_HANDLER(SIG_OVERFLOW2)
{
Timer2Reg0++; // increment low-order counter
 
// if a user function is defined, execute it
if(TimerIntFunc[TIMER2OVERFLOW_INT])
TimerIntFunc[TIMER2OVERFLOW_INT]();
}
#endif
 
#ifdef OCR0
// include support for Output Compare 0 for new AVR processors that support it
//! Interrupt handler for OutputCompare0 match (OC0) interrupt
TIMER_INTERRUPT_HANDLER(SIG_OUTPUT_COMPARE0)
{
// if a user function is defined, execute it
if(TimerIntFunc[TIMER0OUTCOMPARE_INT])
TimerIntFunc[TIMER0OUTCOMPARE_INT]();
}
#endif
 
//! Interrupt handler for CutputCompare1A match (OC1A) interrupt
TIMER_INTERRUPT_HANDLER(SIG_OUTPUT_COMPARE1A)
{
// if a user function is defined, execute it
if(TimerIntFunc[TIMER1OUTCOMPAREA_INT])
TimerIntFunc[TIMER1OUTCOMPAREA_INT]();
}
 
//! Interrupt handler for OutputCompare1B match (OC1B) interrupt
TIMER_INTERRUPT_HANDLER(SIG_OUTPUT_COMPARE1B)
{
// if a user function is defined, execute it
if(TimerIntFunc[TIMER1OUTCOMPAREB_INT])
TimerIntFunc[TIMER1OUTCOMPAREB_INT]();
}
 
//! Interrupt handler for InputCapture1 (IC1) interrupt
TIMER_INTERRUPT_HANDLER(SIG_INPUT_CAPTURE1)
{
// if a user function is defined, execute it
if(TimerIntFunc[TIMER1INPUTCAPTURE_INT])
TimerIntFunc[TIMER1INPUTCAPTURE_INT]();
}
 
//! Interrupt handler for OutputCompare2 match (OC2) interrupt
TIMER_INTERRUPT_HANDLER(SIG_OUTPUT_COMPARE2)
{
// if a user function is defined, execute it
if(TimerIntFunc[TIMER2OUTCOMPARE_INT])
TimerIntFunc[TIMER2OUTCOMPARE_INT]();
}
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/gps/timer.h
0,0 → 1,314
/*! \file timer.h \brief System Timer function library. */
//*****************************************************************************
//
// File Name : 'timer.h'
// Title : System Timer function library
// Author : Pascal Stang - Copyright (C) 2000-2002
// Created : 11/22/2000
// Revised : 02/10/2003
// Version : 1.1
// Target MCU : Atmel AVR Series
// Editor Tabs : 4
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
/// \ingroup driver_avr
/// \defgroup timer Timer Function Library (timer.c)
/// \code #include "timer.h" \endcode
/// \par Overview
/// This library provides functions for use with the timers internal
/// to the AVR processors. Functions include initialization, set prescaler,
/// calibrated pause function (in milliseconds), attaching and detaching of
/// user functions to interrupts, overflow counters, PWM. Arbitrary
/// frequency generation has been moved to the Pulse Library.
///
/// \par About Timers
/// The Atmel AVR-series processors each contain at least one
/// hardware timer/counter. Many of the processors contain 2 or 3
/// timers. Generally speaking, a timer is a hardware counter inside
/// the processor which counts at a rate related to the main CPU clock
/// frequency. Because the counter value increasing (counting up) at
/// a precise rate, we can use it as a timer to create or measure
/// precise delays, schedule events, or generate signals of a certain
/// frequency or pulse-width.
/// \par
/// As an example, the ATmega163 processor has 3 timer/counters.
/// Timer0, Timer1, and Timer2 are 8, 16, and 8 bits wide respectively.
/// This means that they overflow, or roll over back to zero, at a
/// count value of 256 for 8bits or 65536 for 16bits. A prescaler is
/// avaiable for each timer, and the prescaler allows you to pre-divide
/// the main CPU clock rate down to a slower speed before feeding it to
/// the counting input of a timer. For example, if the CPU clock
/// frequency is 3.69MHz, and Timer0's prescaler is set to divide-by-8,
/// then Timer0 will "tic" at 3690000/8 = 461250Hz. Because Timer0 is
/// an 8bit timer, it will count to 256 in just 256/461250Hz = 0.555ms.
/// In fact, when it hits 255, it will overflow and start again at
/// zero. In this case, Timer0 will overflow 461250/256 = 1801.76
/// times per second.
/// \par
/// Timer0 can be used a number of ways simultaneously. First, the
/// value of the timer can be read by accessing the CPU register \c TCNT0.
/// We could, for example, figure out how long it takes to execute a
/// C command by recording the value of \c TCNT0 before and after
/// execution, then subtract (after-before) = time elapsed. Or we can
/// enable the overflow interrupt which goes off every time T0
/// overflows and count out longer delays (multiple overflows), or
/// execute a special periodic function at every overflow.
/// \par
/// The other timers (Timer1 and Timer2) offer all the abilities of
/// Timer0 and many more features. Both T1 and T2 can operate as
/// general-purpose timers, but T1 has special hardware allowing it to
/// generate PWM signals, while T2 is specially designed to help count
/// out real time (like hours, minutes, seconds). See the
/// Timer/Counter section of the processor datasheet for more info.
///
//*****************************************************************************
//@{
 
#ifndef TIMER_H
#define TIMER_H
 
#include "global.h"
 
// constants/macros/typdefs
 
// processor compatibility fixes
#ifdef __AVR_ATmega323__
// redefinition for the Mega323
#define CTC1 CTC10
#endif
#ifndef PWM10
// mega128 PWM bits
#define PWM10 WGM10
#define PWM11 WGM11
#endif
 
 
// Timer/clock prescaler values and timer overflow rates
// tics = rate at which the timer counts up
// 8bitoverflow = rate at which the timer overflows 8bits (or reaches 256)
// 16bit [overflow] = rate at which the timer overflows 16bits (65536)
//
// overflows can be used to generate periodic interrupts
//
// for 8MHz crystal
// 0 = STOP (Timer not counting)
// 1 = CLOCK tics= 8MHz 8bitoverflow= 31250Hz 16bit= 122.070Hz
// 2 = CLOCK/8 tics= 1MHz 8bitoverflow= 3906.25Hz 16bit= 15.259Hz
// 3 = CLOCK/64 tics= 125kHz 8bitoverflow= 488.28Hz 16bit= 1.907Hz
// 4 = CLOCK/256 tics= 31250Hz 8bitoverflow= 122.07Hz 16bit= 0.477Hz
// 5 = CLOCK/1024 tics= 7812.5Hz 8bitoverflow= 30.52Hz 16bit= 0.119Hz
// 6 = External Clock on T(x) pin (falling edge)
// 7 = External Clock on T(x) pin (rising edge)
 
// for 4MHz crystal
// 0 = STOP (Timer not counting)
// 1 = CLOCK tics= 4MHz 8bitoverflow= 15625Hz 16bit= 61.035Hz
// 2 = CLOCK/8 tics= 500kHz 8bitoverflow= 1953.125Hz 16bit= 7.629Hz
// 3 = CLOCK/64 tics= 62500Hz 8bitoverflow= 244.141Hz 16bit= 0.954Hz
// 4 = CLOCK/256 tics= 15625Hz 8bitoverflow= 61.035Hz 16bit= 0.238Hz
// 5 = CLOCK/1024 tics= 3906.25Hz 8bitoverflow= 15.259Hz 16bit= 0.060Hz
// 6 = External Clock on T(x) pin (falling edge)
// 7 = External Clock on T(x) pin (rising edge)
 
// for 3.69MHz crystal
// 0 = STOP (Timer not counting)
// 1 = CLOCK tics= 3.69MHz 8bitoverflow= 14414Hz 16bit= 56.304Hz
// 2 = CLOCK/8 tics= 461250Hz 8bitoverflow= 1801.758Hz 16bit= 7.038Hz
// 3 = CLOCK/64 tics= 57625.25Hz 8bitoverflow= 225.220Hz 16bit= 0.880Hz
// 4 = CLOCK/256 tics= 14414.063Hz 8bitoverflow= 56.305Hz 16bit= 0.220Hz
// 5 = CLOCK/1024 tics= 3603.516Hz 8bitoverflow= 14.076Hz 16bit= 0.055Hz
// 6 = External Clock on T(x) pin (falling edge)
// 7 = External Clock on T(x) pin (rising edge)
 
// for 32.768KHz crystal on timer 2 (use for real-time clock)
// 0 = STOP
// 1 = CLOCK tics= 32.768kHz 8bitoverflow= 128Hz
// 2 = CLOCK/8 tics= 4096kHz 8bitoverflow= 16Hz
// 3 = CLOCK/32 tics= 1024kHz 8bitoverflow= 4Hz
// 4 = CLOCK/64 tics= 512Hz 8bitoverflow= 2Hz
// 5 = CLOCK/128 tics= 256Hz 8bitoverflow= 1Hz
// 6 = CLOCK/256 tics= 128Hz 8bitoverflow= 0.5Hz
// 7 = CLOCK/1024 tics= 32Hz 8bitoverflow= 0.125Hz
 
#define TIMER_CLK_STOP 0x00 ///< Timer Stopped
#define TIMER_CLK_DIV1 0x01 ///< Timer clocked at F_CPU
#define TIMER_CLK_DIV8 0x02 ///< Timer clocked at F_CPU/8
#define TIMER_CLK_DIV64 0x03 ///< Timer clocked at F_CPU/64
#define TIMER_CLK_DIV256 0x04 ///< Timer clocked at F_CPU/256
#define TIMER_CLK_DIV1024 0x05 ///< Timer clocked at F_CPU/1024
#define TIMER_CLK_T_FALL 0x06 ///< Timer clocked at T falling edge
#define TIMER_CLK_T_RISE 0x07 ///< Timer clocked at T rising edge
#define TIMER_PRESCALE_MASK 0x07 ///< Timer Prescaler Bit-Mask
 
#define TIMERRTC_CLK_STOP 0x00 ///< RTC Timer Stopped
#define TIMERRTC_CLK_DIV1 0x01 ///< RTC Timer clocked at F_CPU
#define TIMERRTC_CLK_DIV8 0x02 ///< RTC Timer clocked at F_CPU/8
#define TIMERRTC_CLK_DIV32 0x03 ///< RTC Timer clocked at F_CPU/32
#define TIMERRTC_CLK_DIV64 0x04 ///< RTC Timer clocked at F_CPU/64
#define TIMERRTC_CLK_DIV128 0x05 ///< RTC Timer clocked at F_CPU/128
#define TIMERRTC_CLK_DIV256 0x06 ///< RTC Timer clocked at F_CPU/256
#define TIMERRTC_CLK_DIV1024 0x07 ///< RTC Timer clocked at F_CPU/1024
#define TIMERRTC_PRESCALE_MASK 0x07 ///< RTC Timer Prescaler Bit-Mask
 
// default prescale settings for the timers
// these settings are applied when you call
// timerInit or any of the timer<x>Init
#define TIMER0PRESCALE TIMER_CLK_DIV8 ///< timer 0 prescaler default
#define TIMER1PRESCALE TIMER_CLK_DIV64 ///< timer 1 prescaler default
#define TIMER2PRESCALE TIMERRTC_CLK_DIV64 ///< timer 2 prescaler default
 
// interrupt macros for attaching user functions to timer interrupts
// use these with timerAttach( intNum, function )
#define TIMER0OVERFLOW_INT 0
#define TIMER1OVERFLOW_INT 1
#define TIMER1OUTCOMPAREA_INT 2
#define TIMER1OUTCOMPAREB_INT 3
#define TIMER1INPUTCAPTURE_INT 4
#define TIMER2OVERFLOW_INT 5
#define TIMER2OUTCOMPARE_INT 6
#ifdef OCR0 // for processors that support output compare on Timer0
#define TIMER0OUTCOMPARE_INT 7
#define TIMER_NUM_INTERRUPTS 8
#else
#define TIMER_NUM_INTERRUPTS 7
#endif
 
// default type of interrupt handler to use for timers
// *do not change unless you know what you're doing
// Value may be SIGNAL or INTERRUPT
#ifndef TIMER_INTERRUPT_HANDLER
#define TIMER_INTERRUPT_HANDLER SIGNAL
#endif
 
// functions
#define delay delay_us
#define delay_ms timerPause
void delay_us(unsigned short time_us);
 
//! initializes timing system (all timers)
// runs all timer init functions
// sets all timers to default prescale values #defined in systimer.c
void timerInit(void);
 
// default initialization routines for each timer
void timer0Init(void); ///< initialize timer0
void timer1Init(void); ///< initialize timer1
#ifdef TCNT2 // support timer2 only if it exists
void timer2Init(void); ///< initialize timer2
#endif
 
// Clock prescaler set/get commands for each timer/counter
// For setting the prescaler, you should use one of the #defines
// above like TIMER_CLK_DIVx, where [x] is the division rate
// you want.
// When getting the current prescaler setting, the return value
// will be the [x] division value currently set.
void timer0SetPrescaler(u08 prescale); ///< set timer0 prescaler
u16 timer0GetPrescaler(void); ///< get timer0 prescaler
void timer1SetPrescaler(u08 prescale); ///< set timer1 prescaler
u16 timer1GetPrescaler(void); ///< get timer0 prescaler
#ifdef TCNT2 // support timer2 only if it exists
void timer2SetPrescaler(u08 prescale); ///< set timer2 prescaler
u16 timer2GetPrescaler(void); ///< get timer2 prescaler
#endif
 
 
// TimerAttach and Detach commands
// These functions allow the attachment (or detachment) of any user function
// to a timer interrupt. "Attaching" one of your own functions to a timer
// interrupt means that it will be called whenever that interrupt happens.
// Using attach is better than rewriting the actual INTERRUPT() function
// because your code will still work and be compatible if the timer library
// is updated. Also, using Attach allows your code and any predefined timer
// code to work together and at the same time. (ie. "attaching" your own
// function to the timer0 overflow doesn't prevent timerPause from working,
// but rather allows you to share the interrupt.)
//
// timerAttach(TIMER1OVERFLOW_INT, myOverflowFunction);
// timerDetach(TIMER1OVERFLOW_INT)
//
// timerAttach causes the myOverflowFunction() to be attached, and therefore
// execute, whenever an overflow on timer1 occurs. timerDetach removes the
// association and executes no user function when the interrupt occurs.
// myOverflowFunction must be defined with no return value and no arguments:
//
// void myOverflowFunction(void) { ... }
 
//! Attach a user function to a timer interrupt
void timerAttach(u08 interruptNum, void (*userFunc)(void) );
//! Detach a user function from a timer interrupt
void timerDetach(u08 interruptNum);
 
 
// timing commands
/// A timer-based delay/pause function
/// @param pause_ms Number of integer milliseconds to wait.
void timerPause(unsigned short pause_ms);
 
// overflow counters
void timer0ClearOverflowCount(void); ///< Clear timer0's overflow counter.
long timer0GetOverflowCount(void); ///< read timer0's overflow counter
#ifdef TCNT2 // support timer2 only if it exists
void timer2ClearOverflowCount(void); ///< clear timer2's overflow counter
long timer2GetOverflowCount(void); ///< read timer0's overflow counter
#endif
 
/// @defgroup timerpwm Timer PWM Commands
/// @ingroup timer
/// These commands control PWM functionality on timer1
// PWM initialization and set commands for timer1
// timer1PWMInit()
// configures the timer1 hardware for PWM mode on pins OC1A and OC1B.
// bitRes should be 8,9,or 10 for 8,9,or 10bit PWM resolution
//
// timer1PWMOff()
// turns off all timer1 PWM output and set timer mode to normal state
//
// timer1PWMAOn() and timer1PWMBOn()
// turn on output of PWM signals to OC1A or OC1B pins
// NOTE: Until you define the OC1A and OC1B pins as outputs, and run
// this "on" command, no PWM output will be output
//
// timer1PWMAOff() and timer1PWMBOff()
// turn off output of PWM signals to OC1A or OC1B pins
//
// timer1PWMASet() and timer1PWMBSet()
// sets the PWM duty cycle for each channel
// NOTE: <pwmDuty> should be in the range 0-255 for 8bit PWM
// <pwmDuty> should be in the range 0-511 for 9bit PWM
// <pwmDuty> should be in the range 0-1023 for 10bit PWM
// NOTE: the PWM frequency can be controlled in increments by setting the
// prescaler for timer1
//@{
 
 
/// Enter standard PWM Mode on timer1.
/// \param bitRes indicates the period/resolution to use for PWM output in timer bits.
/// Must be either 8, 9, or 10 bits corresponding to PWM periods of 256, 512, or 1024 timer tics.
void timer1PWMInit(u08 bitRes);
 
/// Enter PWM Mode on timer1 with a specific top-count value.
/// \param topcount indicates the desired PWM period in timer tics.
/// Can be a number between 1 and 65535 (16-bit).
void timer1PWMInitICR(u16 topcount);
 
/// Turn off all timer1 PWM output and set timer mode to normal.
void timer1PWMOff(void);
 
/// Turn on/off Timer1 PWM outputs.
void timer1PWMAOn(void); ///< Turn on timer1 Channel A (OC1A) PWM output.
void timer1PWMBOn(void); ///< Turn on timer1 Channel B (OC1B) PWM output.
void timer1PWMAOff(void); ///< turn off timer1 Channel A (OC1A) PWM output
void timer1PWMBOff(void); ///< turn off timer1 Channel B (OC1B) PWM output
 
void timer1PWMASet(u16 pwmDuty); ///< set duty of timer1 Channel A (OC1A) PWM output
void timer1PWMBSet(u16 pwmDuty); ///< set duty of timer1 Channel B (OC1B) PWM output
 
//@}
//@}
 
// Pulse generation commands have been moved to the pulse.c library
 
#endif
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/gps/tsip.c
0,0 → 1,331
/*! \file tsip.c \brief TSIP (Trimble Standard Interface Protocol) function library. */
//*****************************************************************************
//
// File Name : 'tsip.c'
// Title : TSIP (Trimble Standard Interface Protocol) function library
// Author : Pascal Stang - Copyright (C) 2002-2003
// Created : 2002.08.27
// Revised : 2003.07.17
// Version : 0.1
// Target MCU : Atmel AVR Series
// Editor Tabs : 4
//
// NOTE: This code is currently below version 1.0, and therefore is considered
// to be lacking in some functionality or documentation, or may not be fully
// tested. Nonetheless, you can expect most functions to work.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
#ifndef WIN32
#include <avr/io.h>
#include <avr/pgmspace.h>
#include <math.h>
#include <stdlib.h>
#endif
 
#include "global.h"
#include "buffer.h"
#include "rprintf.h"
#include "uart2.h"
#include "gps.h"
 
#include "tsip.h"
 
// Program ROM constants
 
// Global variables
extern GpsInfoType GpsInfo;
#define BUFFERSIZE 0x40
u08 TsipPacket[BUFFERSIZE];
u08 debug;
 
// function pointer to single byte output routine
static void (*TsipTxByteFunc)(unsigned char c);
 
void tsipInit(void (*txbytefunc)(unsigned char c))
{
// set transmit function
// (this function will be used for all SendPacket commands)
TsipTxByteFunc = txbytefunc;
 
// set debug status
debug = 0;
 
// compose GPS receiver configuration packet
u08 packet[4];
packet[0] = BV(POS_LLA);
packet[1] = BV(VEL_ENU);
packet[2] = 0;
packet[3] = 0;
// send configuration
tsipSendPacket(TSIPTYPE_SET_IO_OPTIONS, 4, packet);
}
 
void tsipSendPacket(u08 tsipType, u08 dataLength, u08* data)
{
u08 i;
u08 dataIdx = 0;
 
// start of packet
TsipPacket[dataIdx++] = DLE;
// packet type
TsipPacket[dataIdx++] = tsipType;
// add packet data
for(i=0; i<dataLength; i++)
{
if(*data == DLE)
{
// do double-DLE escape sequence
TsipPacket[dataIdx++] = *data;
TsipPacket[dataIdx++] = *data++;
}
else
TsipPacket[dataIdx++] = *data++;
}
// end of packet
TsipPacket[dataIdx++] = DLE;
TsipPacket[dataIdx++] = ETX;
 
for(i=0; i<dataIdx; i++)
TsipTxByteFunc(TsipPacket[i]);
}
 
u08 tsipProcess(cBuffer* rxBuffer)
{
u08 foundpacket = FALSE;
u08 startFlag = FALSE;
u08 data;
u08 i,j,k;
 
u08 TsipPacketIdx;
// process the receive buffer
// go through buffer looking for packets
while(rxBuffer->datalength > 1)
{
// look for a potential start of TSIP packet
if(bufferGetAtIndex(rxBuffer,0) == DLE)
{
// make sure the next byte is not DLE or ETX
data = bufferGetAtIndex(rxBuffer,1);
if((data != DLE) && (data != ETX))
{
// found potential start
startFlag = TRUE;
// done looking for start
break;
}
}
else
// not DLE, dump character from buffer
bufferGetFromFront(rxBuffer);
}
// if we detected a start, look for end of packet
if(startFlag)
{
for(i=1; i<(rxBuffer->datalength)-1; i++)
{
// check for potential end of TSIP packet
if((bufferGetAtIndex(rxBuffer,i) == DLE) && (bufferGetAtIndex(rxBuffer,i+1) == ETX))
{
// have a packet end
// dump initial DLE
bufferGetFromFront(rxBuffer);
// copy data to TsipPacket
TsipPacketIdx = 0;
for(j=0; j<(i-1); j++)
{
data = bufferGetFromFront(rxBuffer);
if(data == DLE)
{
if(bufferGetAtIndex(rxBuffer,0) == DLE)
{
// found double-DLE escape sequence, skip one of them
bufferGetFromFront(rxBuffer);
j++;
}
}
TsipPacket[TsipPacketIdx++] = data;
}
// dump ending DLE+ETX
bufferGetFromFront(rxBuffer);
bufferGetFromFront(rxBuffer);
 
// found a packet
if(debug)
{
rprintf("Rx TSIP packet type: 0x%x len: %d rawlen: %d\r\n",
TsipPacket[0],
TsipPacketIdx,
i);
for(k=0; k<TsipPacketIdx; k++)
{
rprintfu08(TsipPacket[k]);
rprintfChar(' ');
}
//rprintfu08(bufferGetFromFront(rxBuffer)); rprintfChar(' ');
//rprintfu08(bufferGetFromFront(rxBuffer)); rprintfChar(' ');
 
rprintfCRLF();
}
// done with this processing session
foundpacket = TRUE;
break;
}
}
}
 
if(foundpacket)
{
// switch on the packet type
switch(TsipPacket[0])
{
case TSIPTYPE_GPSTIME: tsipProcessGPSTIME(TsipPacket); break;
case TSIPTYPE_POSFIX_XYZ_SP: tsipProcessPOSFIX_XYZ_SP(TsipPacket); break;
case TSIPTYPE_VELFIX_XYZ: tsipProcessVELFIX_XYZ(TsipPacket); break;
 
case TSIPTYPE_POSFIX_LLA_SP: tsipProcessPOSFIX_LLA_SP(TsipPacket); break;
case TSIPTYPE_VELFIX_ENU: tsipProcessVELFIX_ENU(TsipPacket); break;
 
case TSIPTYPE_RAWDATA: break;
default:
//if(debug) rprintf("Unhandled TSIP packet type: 0x%x\r\n",TsipPacket[0]);
break;
}
}
 
return foundpacket;
}
 
void tsipProcessGPSTIME(u08* packet)
{
// NOTE: check endian-ness if porting to processors other than the AVR
GpsInfo.TimeOfWeek.b[3] = packet[1];
GpsInfo.TimeOfWeek.b[2] = packet[2];
GpsInfo.TimeOfWeek.b[1] = packet[3];
GpsInfo.TimeOfWeek.b[0] = packet[4];
 
GpsInfo.WeekNum = ((u16)packet[5]<<8)|((u16)packet[6]);
 
GpsInfo.UtcOffset.b[3] = packet[7];
GpsInfo.UtcOffset.b[2] = packet[8];
GpsInfo.UtcOffset.b[1] = packet[9];
GpsInfo.UtcOffset.b[0] = packet[10];
}
 
void tsipProcessPOSFIX_XYZ_SP(u08* packet)
{
// NOTE: check endian-ness if porting to processors other than the AVR
GpsInfo.PosECEF.x.b[3] = packet[1];
GpsInfo.PosECEF.x.b[2] = packet[2];
GpsInfo.PosECEF.x.b[1] = packet[3];
GpsInfo.PosECEF.x.b[0] = packet[4];
 
GpsInfo.PosECEF.y.b[3] = packet[5];
GpsInfo.PosECEF.y.b[2] = packet[6];
GpsInfo.PosECEF.y.b[1] = packet[7];
GpsInfo.PosECEF.y.b[0] = packet[8];
 
GpsInfo.PosECEF.z.b[3] = packet[9];
GpsInfo.PosECEF.z.b[2] = packet[10];
GpsInfo.PosECEF.z.b[1] = packet[11];
GpsInfo.PosECEF.z.b[0] = packet[12];
 
GpsInfo.PosECEF.TimeOfFix.b[3] = packet[13];
GpsInfo.PosECEF.TimeOfFix.b[2] = packet[14];
GpsInfo.PosECEF.TimeOfFix.b[1] = packet[15];
GpsInfo.PosECEF.TimeOfFix.b[0] = packet[16];
 
GpsInfo.PosECEF.updates++;
 
// GpsInfo.TimeOfFix_ECEF.f = *((float*)&packet[13]);
}
 
void tsipProcessVELFIX_XYZ(u08* packet)
{
}
 
void tsipProcessPOSFIX_LLA_SP(u08* packet)
{
// NOTE: check endian-ness if porting to processors other than the AVR
GpsInfo.PosLLA.lat.b[3] = packet[1];
GpsInfo.PosLLA.lat.b[2] = packet[2];
GpsInfo.PosLLA.lat.b[1] = packet[3];
GpsInfo.PosLLA.lat.b[0] = packet[4];
 
GpsInfo.PosLLA.lon.b[3] = packet[5];
GpsInfo.PosLLA.lon.b[2] = packet[6];
GpsInfo.PosLLA.lon.b[1] = packet[7];
GpsInfo.PosLLA.lon.b[0] = packet[8];
 
GpsInfo.PosLLA.alt.b[3] = packet[9];
GpsInfo.PosLLA.alt.b[2] = packet[10];
GpsInfo.PosLLA.alt.b[1] = packet[11];
GpsInfo.PosLLA.alt.b[0] = packet[12];
 
GpsInfo.PosLLA.TimeOfFix.b[3] = packet[17];
GpsInfo.PosLLA.TimeOfFix.b[2] = packet[18];
GpsInfo.PosLLA.TimeOfFix.b[1] = packet[18];
GpsInfo.PosLLA.TimeOfFix.b[0] = packet[20];
 
GpsInfo.PosLLA.updates++;
}
 
void tsipProcessVELFIX_ENU(u08* packet)
{
// NOTE: check endian-ness if porting to processors other than the AVR
GpsInfo.VelENU.east.b[3] = packet[1];
GpsInfo.VelENU.east.b[2] = packet[2];
GpsInfo.VelENU.east.b[1] = packet[3];
GpsInfo.VelENU.east.b[0] = packet[4];
 
GpsInfo.VelENU.north.b[3] = packet[5];
GpsInfo.VelENU.north.b[2] = packet[6];
GpsInfo.VelENU.north.b[1] = packet[7];
GpsInfo.VelENU.north.b[0] = packet[8];
 
GpsInfo.VelENU.up.b[3] = packet[9];
GpsInfo.VelENU.up.b[2] = packet[10];
GpsInfo.VelENU.up.b[1] = packet[11];
GpsInfo.VelENU.up.b[0] = packet[12];
 
GpsInfo.VelENU.TimeOfFix.b[3] = packet[17];
GpsInfo.VelENU.TimeOfFix.b[2] = packet[18];
GpsInfo.VelENU.TimeOfFix.b[1] = packet[19];
GpsInfo.VelENU.TimeOfFix.b[0] = packet[20];
 
GpsInfo.VelENU.updates++;
}
 
void tsipProcessRAWDATA(cBuffer* packet)
{
/*
char oft = 1;
// process the data in TSIPdata
unsigned char SVnum = TSIPdata[oft];
unsigned __int32 SNR32 = (TSIPdata[oft+5] << 24) + (TSIPdata[oft+6] << 16) + (TSIPdata[oft+7] << 8) + (TSIPdata[oft+8]);
unsigned __int32 codephase32 = (TSIPdata[oft+9] << 24) + (TSIPdata[oft+10] << 16) + (TSIPdata[oft+11] << 8) + (TSIPdata[oft+12]);
unsigned __int32 doppler32 = (TSIPdata[oft+13] << 24) + (TSIPdata[oft+14] << 16) + (TSIPdata[oft+15] << 8) + (TSIPdata[oft+16]);
unsigned __int64 meastimeH32 = (TSIPdata[oft+17] << 24) | (TSIPdata[oft+18] << 16) | (TSIPdata[oft+19] << 8) | (TSIPdata[oft+20]);
unsigned __int64 meastimeL32 = (TSIPdata[oft+21] << 24) | (TSIPdata[oft+22] << 16) | (TSIPdata[oft+23] << 8) | (TSIPdata[oft+24]);
unsigned __int64 meastime64 = (meastimeH32 << 32) | (meastimeL32);
float SNR = *((float*) &SNR32);
float codephase = *((float*) &codephase32);
float doppler = *((float*) &doppler32);
double meastime = *((double*) &meastime64);
// output to screen
printf("SV%2d SNR: %5.2f PH: %11.4f DOP: %11.4f TIME: %5.0I64f EPOCH: %7.2I64f\n",SVnum,SNR,codephase,doppler,meastime,meastime/1.5);
//printf("SV%2d SNR: %5.2f PH: %10.4f DOP: %10.4f TIME: %I64x\n",SVnum,SNR,codephase,doppler,meastime64);
 
// output to file
fprintf( logfile, "%2d %5.2f %11.4f %11.4f %5.0I64f %7.2I64f\n",SVnum,SNR,codephase,doppler,meastime,meastime/1.5);
*/
}
 
/programy/C/avr/gps/tsip.h
0,0 → 1,88
/*! \file tsip.h \brief TSIP (Trimble Standard Interface Protocol) function library. */
//*****************************************************************************
//
// File Name : 'tsip.h'
// Title : TSIP (Trimble Standard Interface Protocol) function library
// Author : Pascal Stang - Copyright (C) 2002
// Created : 2002.08.27
// Revised : 2002.08.27
// Version : 0.1
// Target MCU : Atmel AVR Series
// Editor Tabs : 4
//
// NOTE: This code is currently below version 1.0, and therefore is considered
// to be lacking in some functionality or documentation, or may not be fully
// tested. Nonetheless, you can expect most functions to work.
//
/// \ingroup driver_hw
/// \defgroup tsip TSIP Packet Interface for Trimble GPS Receivers (tsip.c)
/// \code #include "tsip.h" \endcode
/// \par Overview
/// This library parses and decodes the TSIP data stream from a Trimble GPS
/// and stores the position, velocity, and time solutions in the gps.c library.
/// The library also includes functions to transmit TSIP packets to the GPS for
/// configuration and data request.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
#ifndef TSIP_H
#define TSIP_H
 
#include "global.h"
 
// constants/macros/typdefs
// packet delimiters
#define DLE 0x10
#define ETX 0x03
// packet types
// command packets
#define TSIPTYPE_SET_IO_OPTIONS 0x35
// byte 0
#define POS_XYZ_ECEF 0 // outputs 0x42 and 0x83 packets
#define POS_LLA 1 // outputs 0x4A and 0x84 packets
#define POS_ALT 2 // outputs 0x4A/0x84 and 0x8F-17/0x8F-18
#define ALT_REF_MSL 3 // bit cleared = HAE Reference datum
#define POS_DBL_PRECISION 4 // bit cleared = single precision
#define SUPER_PACKETS 5 // 0x8F-17,0x8F-18,0x8F-20
// byte 1
#define VEL_ECEF 0 // outputs 0x43
#define VEL_ENU 1 // outputs 0x56
// byte 2
#define TIME_UTC 0 // 0/1 time format GPS/UTC
// byte 3
#define RAWDATA 0 // outputs 0x5A packets
#define RAWDATA_FILTER 1 // 0/1 raw data unfiltered/filtered
#define SIGNAL_DBHZ 3 // 0/1 signal strength in AMU/dBHz
 
// report packets
#define TSIPTYPE_GPSTIME 0x41
#define TSIPTYPE_POSFIX_XYZ_SP 0x42
#define TSIPTYPE_VELFIX_XYZ 0x43
#define TSIPTYPE_SATSIGLEVEL 0x47
#define TSIPTYPE_GPSSYSMESSAGE 0x48
#define TSIPTYPE_POSFIX_LLA_SP 0x4A
#define TSIPTYPE_VELFIX_ENU 0x56
#define TSIPTYPE_SATTRACKSTAT 0x5C
#define TSIPTYPE_RAWDATA 0x5A
#define TSIPTYPE_GPSSUBCODE 0x6F
#define TSIPTYPE_POSFIX_XYZ_DP 0x83
#define TSIPTYPE_POSFIX_LLA_DP 0x84
 
 
// functions
void tsipInit(void (*txbytefunc)(unsigned char c));
void tsipSendPacket(u08 tsipType, u08 dataLength, u08* data);
u08 tsipProcess(cBuffer* rxBuffer);
void tsipGpsDataPrint(void);
 
// packet processing functions
void tsipProcessGPSTIME(u08* packet);
void tsipProcessPOSFIX_XYZ_SP(u08* packet);
void tsipProcessVELFIX_XYZ(u08* packet);
void tsipProcessPOSFIX_LLA_SP(u08* packet);
void tsipProcessVELFIX_ENU(u08* packet);
 
#endif
/programy/C/avr/gps/uart2.c
0,0 → 1,379
/*! \file uart2.c \brief Dual UART driver with buffer support. */
//*****************************************************************************
//
// File Name : 'uart2.c'
// Title : Dual UART driver with buffer support
// Author : Pascal Stang - Copyright (C) 2000-2004
// Created : 11/20/2000
// Revised : 07/04/2004
// Version : 1.0
// Target MCU : ATMEL AVR Series
// Editor Tabs : 4
//
// Description : This is a UART driver for AVR-series processors with two
// hardware UARTs such as the mega161 and mega128
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
#include <avr/io.h>
#include <avr/interrupt.h>
 
#include "buffer.h"
#include "uart2.h"
 
// UART global variables
// flag variables
volatile u08 uartReadyTx[2];
volatile u08 uartBufferedTx[2];
// receive and transmit buffers
cBuffer uartRxBuffer[2];
cBuffer uartTxBuffer[2];
unsigned short uartRxOverflow[2];
#ifndef UART_BUFFER_EXTERNAL_RAM
// using internal ram,
// automatically allocate space in ram for each buffer
static char uart0RxData[UART0_RX_BUFFER_SIZE];
static char uart0TxData[UART0_TX_BUFFER_SIZE];
static char uart1RxData[UART1_RX_BUFFER_SIZE];
static char uart1TxData[UART1_TX_BUFFER_SIZE];
#endif
 
typedef void (*voidFuncPtru08)(unsigned char);
volatile static voidFuncPtru08 UartRxFunc[2];
 
void uartInit(void)
{
// initialize both uarts
uart0Init();
uart1Init();
}
 
void uart0Init(void)
{
// initialize the buffers
uart0InitBuffers();
// initialize user receive handlers
UartRxFunc[0] = 0;
// enable RxD/TxD and interrupts
outb(UCSR0B, BV(RXCIE)|BV(TXCIE)|BV(RXEN)|BV(TXEN));
// set default baud rate
uartSetBaudRate(0, UART0_DEFAULT_BAUD_RATE);
// initialize states
uartReadyTx[0] = TRUE;
uartBufferedTx[0] = FALSE;
// clear overflow count
uartRxOverflow[0] = 0;
// enable interrupts
sei();
}
 
void uart1Init(void)
{
// initialize the buffers
uart1InitBuffers();
// initialize user receive handlers
UartRxFunc[1] = 0;
// enable RxD/TxD and interrupts
outb(UCSR1B, BV(RXCIE)|BV(TXCIE)|BV(RXEN)|BV(TXEN));
// set default baud rate
uartSetBaudRate(1, UART1_DEFAULT_BAUD_RATE);
// initialize states
uartReadyTx[1] = TRUE;
uartBufferedTx[1] = FALSE;
// clear overflow count
uartRxOverflow[1] = 0;
// enable interrupts
sei();
}
 
void uart0InitBuffers(void)
{
#ifndef UART_BUFFER_EXTERNAL_RAM
// initialize the UART0 buffers
bufferInit(&uartRxBuffer[0], uart0RxData, UART0_RX_BUFFER_SIZE);
bufferInit(&uartTxBuffer[0], uart0TxData, UART0_TX_BUFFER_SIZE);
#else
// initialize the UART0 buffers
bufferInit(&uartRxBuffer[0], (u08*) UART0_RX_BUFFER_ADDR, UART0_RX_BUFFER_SIZE);
bufferInit(&uartTxBuffer[0], (u08*) UART0_TX_BUFFER_ADDR, UART0_TX_BUFFER_SIZE);
#endif
}
 
void uart1InitBuffers(void)
{
#ifndef UART_BUFFER_EXTERNAL_RAM
// initialize the UART1 buffers
bufferInit(&uartRxBuffer[1], uart1RxData, UART1_RX_BUFFER_SIZE);
bufferInit(&uartTxBuffer[1], uart1TxData, UART1_TX_BUFFER_SIZE);
#else
// initialize the UART1 buffers
bufferInit(&uartRxBuffer[1], (u08*) UART1_RX_BUFFER_ADDR, UART1_RX_BUFFER_SIZE);
bufferInit(&uartTxBuffer[1], (u08*) UART1_TX_BUFFER_ADDR, UART1_TX_BUFFER_SIZE);
#endif
}
 
void uartSetRxHandler(u08 nUart, void (*rx_func)(unsigned char c))
{
// make sure the uart number is within bounds
if(nUart < 2)
{
// set the receive interrupt to run the supplied user function
UartRxFunc[nUart] = rx_func;
}
}
 
void uartSetBaudRate(u08 nUart, u32 baudrate)
{
// calculate division factor for requested baud rate, and set it
u16 bauddiv = ((F_CPU+(baudrate*8L))/(baudrate*16L)-1);
if(nUart)
{
outb(UBRR1L, bauddiv);
#ifdef UBRR1H
outb(UBRR1H, bauddiv>>8);
#endif
}
else
{
outb(UBRR0L, bauddiv);
#ifdef UBRR0H
outb(UBRR0H, bauddiv>>8);
#endif
}
}
 
cBuffer* uartGetRxBuffer(u08 nUart)
{
// return rx buffer pointer
return &uartRxBuffer[nUart];
}
 
cBuffer* uartGetTxBuffer(u08 nUart)
{
// return tx buffer pointer
return &uartTxBuffer[nUart];
}
 
void uartSendByte(u08 nUart, u08 txData)
{
// wait for the transmitter to be ready
// while(!uartReadyTx[nUart]);
// send byte
if(nUart)
{
while(!(UCSR1A & (1<<UDRE)));
outb(UDR1, txData);
}
else
{
while(!(UCSR0A & (1<<UDRE)));
outb(UDR0, txData);
}
// set ready state to FALSE
uartReadyTx[nUart] = FALSE;
}
 
void uart0SendByte(u08 data)
{
// send byte on UART0
uartSendByte(0, data);
}
 
void uart1SendByte(u08 data)
{
// send byte on UART1
uartSendByte(1, data);
}
 
int uart0GetByte(void)
{
// get single byte from receive buffer (if available)
u08 c;
if(uartReceiveByte(0,&c))
return c;
else
return -1;
}
 
int uart1GetByte(void)
{
// get single byte from receive buffer (if available)
u08 c;
if(uartReceiveByte(1,&c))
return c;
else
return -1;
}
 
 
u08 uartReceiveByte(u08 nUart, u08* rxData)
{
// make sure we have a receive buffer
if(uartRxBuffer[nUart].size)
{
// make sure we have data
if(uartRxBuffer[nUart].datalength)
{
// get byte from beginning of buffer
*rxData = bufferGetFromFront(&uartRxBuffer[nUart]);
return TRUE;
}
else
return FALSE; // no data
}
else
return FALSE; // no buffer
}
 
void uartFlushReceiveBuffer(u08 nUart)
{
// flush all data from receive buffer
bufferFlush(&uartRxBuffer[nUart]);
}
 
u08 uartReceiveBufferIsEmpty(u08 nUart)
{
return (uartRxBuffer[nUart].datalength == 0);
}
 
void uartAddToTxBuffer(u08 nUart, u08 data)
{
// add data byte to the end of the tx buffer
bufferAddToEnd(&uartTxBuffer[nUart], data);
}
 
void uart0AddToTxBuffer(u08 data)
{
uartAddToTxBuffer(0,data);
}
 
void uart1AddToTxBuffer(u08 data)
{
uartAddToTxBuffer(1,data);
}
 
void uartSendTxBuffer(u08 nUart)
{
// turn on buffered transmit
uartBufferedTx[nUart] = TRUE;
// send the first byte to get things going by interrupts
uartSendByte(nUart, bufferGetFromFront(&uartTxBuffer[nUart]));
}
 
u08 uartSendBuffer(u08 nUart, char *buffer, u16 nBytes)
{
register u08 first;
register u16 i;
 
// check if there's space (and that we have any bytes to send at all)
if((uartTxBuffer[nUart].datalength + nBytes < uartTxBuffer[nUart].size) && nBytes)
{
// grab first character
first = *buffer++;
// copy user buffer to uart transmit buffer
for(i = 0; i < nBytes-1; i++)
{
// put data bytes at end of buffer
bufferAddToEnd(&uartTxBuffer[nUart], *buffer++);
}
 
// send the first byte to get things going by interrupts
uartBufferedTx[nUart] = TRUE;
uartSendByte(nUart, first);
// return success
return TRUE;
}
else
{
// return failure
return FALSE;
}
}
 
// UART Transmit Complete Interrupt Function
void uartTransmitService(u08 nUart)
{
// check if buffered tx is enabled
if(uartBufferedTx[nUart])
{
// check if there's data left in the buffer
if(uartTxBuffer[nUart].datalength)
{
// send byte from top of buffer
if(nUart)
outb(UDR1, bufferGetFromFront(&uartTxBuffer[1]) );
else
outb(UDR0, bufferGetFromFront(&uartTxBuffer[0]) );
}
else
{
// no data left
uartBufferedTx[nUart] = FALSE;
// return to ready state
uartReadyTx[nUart] = TRUE;
}
}
else
{
// we're using single-byte tx mode
// indicate transmit complete, back to ready
uartReadyTx[nUart] = TRUE;
}
}
 
// UART Receive Complete Interrupt Function
void uartReceiveService(u08 nUart)
{
u08 c;
// get received char
if(nUart)
c = inb(UDR1);
else
c = inb(UDR0);
 
// if there's a user function to handle this receive event
if(UartRxFunc[nUart])
{
// call it and pass the received data
UartRxFunc[nUart](c);
}
else
{
// otherwise do default processing
// put received char in buffer
// check if there's space
if( !bufferAddToEnd(&uartRxBuffer[nUart], c) )
{
// no space in buffer
// count overflow
uartRxOverflow[nUart]++;
}
}
}
 
UART_INTERRUPT_HANDLER(SIG_UART0_TRANS)
{
// service UART0 transmit interrupt
uartTransmitService(0);
}
 
UART_INTERRUPT_HANDLER(SIG_UART1_TRANS)
{
// service UART1 transmit interrupt
uartTransmitService(1);
}
 
UART_INTERRUPT_HANDLER(SIG_UART0_RECV)
{
// service UART0 receive interrupt
uartReceiveService(0);
}
 
UART_INTERRUPT_HANDLER(SIG_UART1_RECV)
{
// service UART1 receive interrupt
uartReceiveService(1);
}
/programy/C/avr/gps/uart2.h
0,0 → 1,213
/*! \file uart2.h \brief Dual UART driver with buffer support. */
//*****************************************************************************
//
// File Name : 'uart2.h'
// Title : Dual UART driver with buffer support
// Author : Pascal Stang - Copyright (C) 2000-2002
// Created : 11/20/2000
// Revised : 07/04/2004
// Version : 1.0
// Target MCU : ATMEL AVR Series
// Editor Tabs : 4
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
/// \ingroup driver_avr
/// \defgroup uart2 UART Driver/Function Library for dual-UART processors (uart2.c)
/// \code #include "uart2.h" \endcode
/// \par Overview
/// This is a UART driver for AVR-series processors with two hardware
/// UARTs such as the mega161 and mega128. This library provides both
/// buffered and unbuffered transmit and receive functions for the AVR
/// processor UART. Buffered access means that the UART can transmit
/// and receive data in the "background", while your code continues
/// executing.  Also included are functions to initialize the UARTs,
/// set the baud rate, flush the buffers, and check buffer status.
///
/// \note For full text output functionality, you may wish to use the rprintf
/// functions along with this driver.
///
/// \par About UART operations
/// Most Atmel AVR-series processors contain one or more hardware UARTs
/// (aka, serial ports). UART serial ports can communicate with other
/// serial ports of the same type, like those used on PCs. In general,
/// UARTs are used to communicate with devices that are RS-232 compatible
/// (RS-232 is a certain kind of serial port).
/// \par
/// By far, the most common use for serial communications on AVR processors
/// is for sending information and data to a PC running a terminal program.
/// Here is an exmaple:
/// \code
/// uartInit(); // initialize UARTs (serial ports)
/// uartSetBaudRate(0, 9600); // set UART0 speed to 9600 baud
/// uartSetBaudRate(1, 115200); // set UART1 speed to 115200 baud
///
/// rprintfInit(uart0SendByte); // configure rprintf to use UART0 for output
/// rprintf("Hello UART0\r\n"); // send "hello world" message via UART0
///
/// rprintfInit(uart1SendByte); // configure rprintf to use UART1 for output
/// rprintf("Hello UART1\r\n"); // send "hello world" message via UART1
/// \endcode
///
/// \warning The CPU frequency (F_CPU) must be set correctly in \c global.h
/// for the UART library to calculate correct baud rates. Furthermore,
/// certain CPU frequencies will not produce exact baud rates due to
/// integer frequency division round-off. See your AVR processor's
/// datasheet for full details.
//
//*****************************************************************************
//@{
 
#ifndef UART2_H
#define UART2_H
 
#include "global.h"
#include "buffer.h"
 
//! Default uart baud rate.
/// This is the default speed after a uartInit() command,
/// and can be changed by using uartSetBaudRate().
#define UART0_DEFAULT_BAUD_RATE 9600 ///< default baud rate for UART0
#define UART1_DEFAULT_BAUD_RATE 9600 ///< default baud rate for UART1
 
// buffer memory allocation defines
// buffer sizes
#ifndef UART0_TX_BUFFER_SIZE
#define UART0_TX_BUFFER_SIZE 0x0010 ///< number of bytes for uart0 transmit buffer
#endif
#ifndef UART0_RX_BUFFER_SIZE
#define UART0_RX_BUFFER_SIZE 0x0080 ///< number of bytes for uart0 receive buffer
#endif
#ifndef UART1_TX_BUFFER_SIZE
#define UART1_TX_BUFFER_SIZE 0x0010 ///< number of bytes for uart1 transmit buffer
#endif
#ifndef UART1_RX_BUFFER_SIZE
#define UART1_RX_BUFFER_SIZE 0x0080 ///< number of bytes for uart1 receive buffer
#endif
 
// define this key if you wish to use
// external RAM for the UART buffers
//#define UART_BUFFER_EXTERNAL_RAM
#ifdef UART_BUFFER_EXTERNAL_RAM
// absolute address of uart0 buffers
#define UART0_TX_BUFFER_ADDR 0x1000
#define UART0_RX_BUFFER_ADDR 0x1100
// absolute address of uart1 buffers
#define UART1_TX_BUFFER_ADDR 0x1200
#define UART1_RX_BUFFER_ADDR 0x1300
#endif
 
//! Type of interrupt handler to use for uart interrupts.
/// Value may be SIGNAL or INTERRUPT.
/// \warning Do not change unless you know what you're doing.
#ifndef UART_INTERRUPT_HANDLER
#define UART_INTERRUPT_HANDLER SIGNAL
#endif
 
// compatibility for the mega161
#ifndef RXCIE
#define RXCIE RXCIE0
#define TXCIE TXCIE0
#define UDRIE UDRIE0
#define RXEN RXEN0
#define TXEN TXEN0
#define CHR9 CHR90
#define RXB8 RXB80
#define TXB8 TXB80
#endif
#ifndef UBRR0L
#define UBRR0L UBRR0
#define UBRR1L UBRR1
#endif
 
// functions
 
//! Initializes UARTs.
/// \note After running this init function, the processor
/// I/O pins that used for uart communications (RXD, TXD)
/// are no long available for general purpose I/O.
void uartInit(void);
 
//! Initializes UART0 only.
void uart0Init(void);
 
//! Initializes UART1 only.
void uart1Init(void);
 
//! Initializes transmit and receive buffers.
/// Automatically called from uartInit()
void uart0InitBuffers(void);
void uart1InitBuffers(void);
 
//! Redirects received data to a user function.
///
void uartSetRxHandler(u08 nUart, void (*rx_func)(unsigned char c));
 
//! Sets the uart baud rate.
/// Argument should be in bits-per-second, like \c uartSetBaudRate(9600);
void uartSetBaudRate(u08 nUart, u32 baudrate);
 
//! Returns pointer to the receive buffer structure.
///
cBuffer* uartGetRxBuffer(u08 nUart);
 
//! Returns pointer to the transmit buffer structure.
///
cBuffer* uartGetTxBuffer(u08 nUart);
 
//! Sends a single byte over the uart.
///
void uartSendByte(u08 nUart, u08 data);
 
//! SendByte commands with the UART number hardcoded
/// Use these with printfInit() - example: \c printfInit(uart0SendByte);
void uart0SendByte(u08 data);
void uart1SendByte(u08 data);
 
//! Gets a single byte from the uart receive buffer.
/// Returns the byte, or -1 if no byte is available (getchar-style).
int uart0GetByte(void);
int uart1GetByte(void);
 
//! Gets a single byte from the uart receive buffer.
/// Function returns TRUE if data was available, FALSE if not.
/// Actual data is returned in variable pointed to by "data".
/// Example usage:
/// \code
/// char myReceivedByte;
/// uartReceiveByte(0, &myReceivedByte );
/// \endcode
u08 uartReceiveByte(u08 nUart, u08* data);
 
//! Returns TRUE/FALSE if receive buffer is empty/not-empty.
///
u08 uartReceiveBufferIsEmpty(u08 nUart);
 
//! Flushes (deletes) all data from receive buffer.
///
void uartFlushReceiveBuffer(u08 nUart);
 
//! Add byte to end of uart Tx buffer.
///
void uartAddToTxBuffer(u08 nUart, u08 data);
 
//! AddToTxBuffer commands with the UART number hardcoded
/// Use this with printfInit() - example: \c printfInit(uart0AddToTxBuffer);
void uart0AddToTxBuffer(u08 data);
void uart1AddToTxBuffer(u08 data);
 
//! Begins transmission of the transmit buffer under interrupt control.
///
void uartSendTxBuffer(u08 nUart);
 
//! sends a buffer of length nBytes via the uart using interrupt control.
///
u08 uartSendBuffer(u08 nUart, char *buffer, u16 nBytes);
 
//! interrupt service handlers
void uartTransmitService(u08 nUart);
void uartReceiveService(u08 nUart);
 
#endif
 
/programy/C/avr/gps/vt100.c
0,0 → 1,69
/*! \file vt100.c \brief VT100 terminal function library. */
//*****************************************************************************
//
// File Name : 'vt100.c'
// Title : VT100 terminal function library
// Author : Pascal Stang - Copyright (C) 2002
// Created : 2002.08.27
// Revised : 2002.08.27
// Version : 0.1
// Target MCU : Atmel AVR Series
// Editor Tabs : 4
//
// NOTE: This code is currently below version 1.0, and therefore is considered
// to be lacking in some functionality or documentation, or may not be fully
// tested. Nonetheless, you can expect most functions to work.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
 
#include "global.h"
#include "rprintf.h"
#include "vt100.h"
 
// Program ROM constants
 
// Global variables
 
// Functions
void vt100Init(void)
{
// initializes terminal to "power-on" settings
// ESC c
rprintfProgStrM("\x1B\x63");
}
 
void vt100ClearScreen(void)
{
// ESC [ 2 J
rprintfProgStrM("\x1B[2J");
}
 
void vt100SetAttr(u08 attr)
{
// ESC [ Ps m
rprintf("\x1B[%dm",attr);
}
 
void vt100SetCursorMode(u08 visible)
{
if(visible)
// ESC [ ? 25 h
rprintf("\x1B[?25h");
else
// ESC [ ? 25 l
rprintf("\x1B[?25l");
}
 
void vt100SetCursorPos(u08 line, u08 col)
{
// ESC [ Pl ; Pc H
rprintf("\x1B[%d;%dH",line,col);
}
 
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/programy/C/avr/gps/vt100.h
0,0 → 1,72
/*! \file vt100.h \brief VT100 terminal function library. */
//*****************************************************************************
//
// File Name : 'vt100.h'
// Title : VT100 terminal function library
// Author : Pascal Stang - Copyright (C) 2002
// Created : 2002.08.27
// Revised : 2002.08.27
// Version : 0.1
// Target MCU : Atmel AVR Series
// Editor Tabs : 4
//
// NOTE: This code is currently below version 1.0, and therefore is considered
// to be lacking in some functionality or documentation, or may not be fully
// tested. Nonetheless, you can expect most functions to work.
//
/// \ingroup general
/// \defgroup vt100 VT100 Terminal Function Library (vt100.c)
/// \code #include "vt100.h" \endcode
/// \par Overview
/// This library provides functions for sending VT100 escape codes to
/// control a connected VT100 or ANSI terminal.  Commonly useful functions
/// include setting the cursor position, clearing the screen, setting the text
/// attributes (bold, inverse, blink, etc), and setting the text color.  This
/// library will slowly be expanded to include support for codes as needed and
/// may eventually receive VT100 escape codes too.
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
 
#ifndef VT100_H
#define VT100_H
 
#include "global.h"
 
// constants/macros/typdefs
// text attributes
#define VT100_ATTR_OFF 0
#define VT100_BOLD 1
#define VT100_USCORE 4
#define VT100_BLINK 5
#define VT100_REVERSE 7
#define VT100_BOLD_OFF 21
#define VT100_USCORE_OFF 24
#define VT100_BLINK_OFF 25
#define VT100_REVERSE_OFF 27
 
// functions
 
//! vt100Init() initializes terminal and vt100 library
/// Run this init routine once before using any other vt100 function.
void vt100Init(void);
 
//! vt100ClearScreen() clears the terminal screen
void vt100ClearScreen(void);
 
//! vt100SetAttr() sets the text attributes like BOLD or REVERSE
/// Text written to the terminal after this function is called will have
/// the desired attribuutes.
void vt100SetAttr(u08 attr);
 
//! vt100SetCursorMode() sets the cursor to visible or invisible
void vt100SetCursorMode(u08 visible);
 
//! vt100SetCursorPos() sets the cursor position
/// All text which is written to the terminal after a SetCursorPos command
/// will begin at the new location of the cursor.
void vt100SetCursorPos(u08 line, u08 col);
 
#endif
Property changes:
Added: svn:executable
+*
\ No newline at end of property