Subversion Repositories svnkaklik

Compare Revisions

No changes between revisions

Ignore whitespace Rev 506 → Rev 507

/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