/Designs/skrysohledac2/SW/AVRProject.sln
1,7 → 1,7

Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AVRProject", "AVRProject.vcproj", "{38E1D1A1-FC7A-4A6C-9127-1A1C2FEF668D}"
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AVRProject", "AVRProject.vcproj", "{E81EE5C5-BF61-4F63-97E0-F94397BD48AF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
9,10 → 9,10
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{38E1D1A1-FC7A-4A6C-9127-1A1C2FEF668D}.Debug|Win32.ActiveCfg = Debug|Win32
{38E1D1A1-FC7A-4A6C-9127-1A1C2FEF668D}.Debug|Win32.Build.0 = Debug|Win32
{38E1D1A1-FC7A-4A6C-9127-1A1C2FEF668D}.Release|Win32.ActiveCfg = Release|Win32
{38E1D1A1-FC7A-4A6C-9127-1A1C2FEF668D}.Release|Win32.Build.0 = Release|Win32
{E81EE5C5-BF61-4F63-97E0-F94397BD48AF}.Debug|Win32.ActiveCfg = Debug|Win32
{E81EE5C5-BF61-4F63-97E0-F94397BD48AF}.Debug|Win32.Build.0 = Debug|Win32
{E81EE5C5-BF61-4F63-97E0-F94397BD48AF}.Release|Win32.ActiveCfg = Release|Win32
{E81EE5C5-BF61-4F63-97E0-F94397BD48AF}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
/Designs/skrysohledac2/SW/AVRProject.vcproj
3,7 → 3,7
ProjectType="Visual C++"
Version="8,00"
Name="AVRProject"
ProjectGUID="{38E1D1A1-FC7A-4A6C-9127-1A1C2FEF668D}"
ProjectGUID="{E81EE5C5-BF61-4F63-97E0-F94397BD48AF}"
Keyword="MakeFileProj"
>
<Platforms>
86,58 → 86,114
Name="Resource Files"
Filter="ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
>
</Filter>
<Filter
Name="avrlib"
>
<File
RelativePath="..\..\gps.c"
RelativePath=".\avrlibdefs.h"
>
</File>
<File
RelativePath="..\..\gps.h"
RelativePath=".\avrlibtypes.h"
>
</File>
<File
RelativePath="..\..\lcd_hd44780.c"
RelativePath=".\buffer.c"
>
</File>
<File
RelativePath="..\..\lcd_hd44780.h"
RelativePath=".\buffer.h"
>
</File>
<File
RelativePath="makefile"
RelativePath=".\gps.c"
>
</File>
<File
RelativePath="..\..\nmea.c"
RelativePath=".\gps.h"
>
</File>
<File
RelativePath="..\..\nmea.h"
RelativePath=".\lcd_hd44780.c"
>
</File>
<File
RelativePath="..\..\rprintf.c"
RelativePath=".\lcd_hd44780.h"
>
</File>
<File
RelativePath="..\..\rprintf.h"
RelativePath=".\lcdconf.h"
>
</File>
<File
RelativePath="..\..\tsip.c"
RelativePath=".\nmea.c"
>
</File>
<File
RelativePath="..\..\tsip.h"
RelativePath=".\nmea.h"
>
</File>
<File
RelativePath="..\..\utm.c"
RelativePath=".\port128.h"
>
</File>
<File
RelativePath="..\..\utm.h"
RelativePath=".\rprintf.c"
>
</File>
<File
RelativePath=".\rprintf.h"
>
</File>
<File
RelativePath=".\timer.c"
>
</File>
<File
RelativePath=".\timer.h"
>
</File>
<File
RelativePath=".\tsip.c"
>
</File>
<File
RelativePath=".\tsip.h"
>
</File>
<File
RelativePath=".\uart.c"
>
</File>
<File
RelativePath=".\uart.h"
>
</File>
<File
RelativePath=".\uart2.c"
>
</File>
<File
RelativePath=".\uart2.h"
>
</File>
<File
RelativePath=".\utm.c"
>
</File>
<File
RelativePath=".\utm.h"
>
</File>
<File
RelativePath=".\vt100.c"
>
</File>
<File
RelativePath=".\vt100.h"
>
</File>
</Filter>
</Files>
<Globals>
/Designs/skrysohledac2/SW/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
/Designs/skrysohledac2/SW/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
/Designs/skrysohledac2/SW/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;
}
 
/Designs/skrysohledac2/SW/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
//@}
/Designs/skrysohledac2/SW/gps.c
0,0 → 1,144
/*! \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 <stdio.h>
 
#include "global.h"
#include "rprintf.h"
#include "gps.h"
#include "lcd_hd44780.h"
#include "utm.h" // Lat Lon to UTM conversion
 
// 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("PosLat: "); rprintfFloat(8, GpsInfo.PosLLA.lat.f); rprintfCRLF();
rprintfProgStrM("PosLon: "); rprintfFloat(8, GpsInfo.PosLLA.lon.f); 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.VelHS.updates); rprintfCRLF();
 
}
 
void gpsInfoPrintLCD(void)
{
lcd_gotoxy(1,1);
rprintfStr(GPSlat);
// rprintfFloatMy(2, GpsInfo.PosLLA.lat.f);
// rprintfFloatMy(6, (GpsInfo.PosLLA.lat.f-trunc(GpsInfo.PosLLA.lat.f))*60);
rprintfCRLF();
lcd_gotoxy(12,1);
rprintfFloat(4, GpsInfo.PosLLA.alt.f);
lcd_gotoxy(10,2);
// rprintfFloat(6, GpsInfo.PosLLA.TimeOfFix.f+20000);
rprintfFloat(6, GpsInfo.PosLLA.TimeOfFix.f+10000);
lcd_gotoxy(1,2);
rprintfStr(GPSlon);
// rprintfFloatMy(2, GpsInfo.PosLLA.lon.f);
// rprintfFloatMy(6, (GpsInfo.PosLLA.lon.f-trunc(GpsInfo.PosLLA.lon.f))*60);
rprintfCRLF();
lcd_gotoxy(10,1);
rprintfNum(10,2,0,'*',GpsInfo.numSVs);
rprintfCRLF();
}
 
void gpsInfoPrintLCD2(void)
{
int utmXZone;
char utmYZone;
double easting;
double northing;
 
lcd_gotoxy(1,1);
 
LatLonToUtmWGS84(&utmXZone, &utmYZone, &easting, &northing, GpsInfo.PosLLA.lat.f, GpsInfo.PosLLA.lon.f);
 
rprintfFloatMy(7, northing);
rprintfProgStrM(" ");
// rprintfCRLF();
lcd_gotoxy(12,1);
rprintfFloat(4, GpsInfo.PosLLA.alt.f);
lcd_gotoxy(10,2);
// rprintfFloat(6, GpsInfo.PosLLA.TimeOfFix.f+20000);
rprintfFloat(6, GpsInfo.PosLLA.TimeOfFix.f+10000);
lcd_gotoxy(1,2);
rprintfNum(10,2,0,'*',utmXZone);
rprintfChar(utmYZone);
rprintfFloatMy(6, easting);
rprintfProgStrM(" ");
// rprintfCRLF();
lcd_gotoxy(9,1);
rprintfNum(10,3,0,'*',GpsInfo.numSVs);
rprintfCRLF();
}
/Designs/skrysohledac2/SW/gps.h
0,0 → 1,124
/*! \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"
 
char GPSlat[10];
char GPSlon[10];
 
// 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);
void gpsInfoPrintLCD(void);
void gpsInfoPrintLCD2(void);
 
#endif
/Designs/skrysohledac2/SW/gpstest.c
96,7 → 96,7
 
lcd_init(); // Init LCD (interface and display module)
rprintfInit(lcd_putc);
rprintfProgStrM("Ahoj..."); rprintfCRLF();
rprintfProgStrM("Ahoj...xxxxx"); rprintfCRLF();
_delay_ms(500);
lcd_clear();
 
134,10 → 134,12
else
gpsInfoPrintLCD2();
 
sbi(DDRC, 0); // sets PC0 to be an output
/*
sbi(DDRC, 0); // sets PC0 to be an output
cbi(PORTC, 0); // sets PC0 to output a LOW
_delay_ms(5);
sbi(PORTC, 0); // sets PC0 to output a HIGH
*/
}
}
 
/Designs/skrysohledac2/SW/lcd_hd44780.c
0,0 → 1,485
/* ---------------------------------------------------------------------------
* AVR_MLIB - HD 44780 LCD Display Driver
* www.mlab.cz miho 2008
* ---------------------------------------------------------------------------
* LCD display driver for standard Hitachi 1/2/4 line character LCD modules
* for AVR processors. It uses 4 or 8 bit interface without readback.
* In the Examples section there is a demo application for this library.
* ---------------------------------------------------------------------------
* 00.00 2008/03/28 First Version
* ---------------------------------------------------------------------------
*/
 
#include "lcd_hd44780.h"
 
// Check Defined Values and use Default Values if possible
// -------------------------------------------------------
// 1 / 2 / 4 Line
#ifndef LCD_CHARS
#if LCD_LINES > 2
#error "LCD: Undefined LCD_CHARS"
#else
// Dafault Value
#define LCD_CHARS 20
#endif
#endif
 
#ifndef LCD_LINE_1
// Address of the 1st char on the 1st line
#define LCD_LINE_1 0
#endif
 
#ifndef LCD_LINE_2
// Address of the 1st char on the 2nd line
#define LCD_LINE_2 64
#endif
 
#ifndef LCD_LINE_3
// Address of the 1st char on the 3rd line
#define LCD_LINE_3 LCD_CHARS
#endif
 
#ifndef LCD_LINE_4
// Address of the 1st char on the 4th line
#define LCD_LINE_4 (LCD_LINE_2 + LCD_CHARS)
#endif
 
// Data Interface
#if LCD_INTERFACE_BITS == 4
#define LCD_DATA_MASK (0x0F << LCD_DATA_BIT)
#elif LCD_INTERFACE_BITS==8
#define LCD_DATA_MASK (0xFF << LCD_DATA_BIT)
#else
#error "LCD: Wrong Value: LCD_INTERFACE_BITS"
#endif
 
#if LCD_DATA_MASK > 0xFF
#error "LCD: Value too Big: LCD_DATA_BIT"
#endif
 
#define LCD_E_PORT PORT(LCD_E)
#define LCD_E_DDR DDR(LCD_E)
 
#define LCD_RS_PORT PORT(LCD_RS)
#define LCD_RS_DDR DDR(LCD_RS)
 
#define LCD_DATA_PORT PORT(LCD_DATA)
#define LCD_DATA_DDR DDR(LCD_DATA)
 
#ifdef LCD_RW
#define LCD_RW_PORT PORT(LCD_RW)
#define LCD_RW_DDR DDR(LCD_RW)
#endif
 
 
// LCD Chip Commands
// -----------------
 
// Comand Clear LCD Display
#define LCD_HD44780_CLR 0x01
 
// Command Home Cursor
#define LCD_HD44780_HOME 0x02
 
// Command Entry Mode (increment/decrement, shift/no shift)
#define LCD_HD44780_ENTMODE(inc, shift) \
(0x04 | ((inc)? 0x02: 0) | ((shift)? 1: 0))
 
#define LCD_HD44780_ENTMODE_DEF LCD_HD44780_ENTMODE(1,0) // Increment Position, No Shift
 
// Command Display Controll (display on/off, cursor on/off, cursor blinking on/off)
#define LCD_HD44780_DISPCTL(disp, cursor, blink) \
(0x08 | ((disp)? 0x04: 0) | ((cursor)? 0x02: 0) | ((blink)? 1: 0))
 
#define LCD_HD44780_CURSORON LCD_HD44780_DISPCTL(1,1,0) // on, cursor on,
#define LCD_HD44780_CURSOROFF LCD_HD44780_DISPCTL(1,0,0) // on, cursor off
 
// Command Cursor or Display Shift (shift display/cursor, left/right)
#define LCD_HD44780_SHIFT(shift, right) \
(0x10 | ((shift)? 0x08: 0) | ((right)? 0x04: 0))
 
#define LCD_HD44780_CURSORLEFT LCD_HD44780_SHIFT(0,0)
#define LCD_HD44780_CURSORRIGHT LCD_HD44780_SHIFT(0,1)
 
// Command Function Set ( 4/8-bit interface / 1 or 2 lines )
#define LCD_HD44780_4BIT1LINE 0x20 // 4-bit 1-line font 5x7
#define LCD_HD44780_4BIT2LINES 0x28 // 4-bit 2-lines font 5x7
#define LCD_HD44780_8BIT1LINE 0x30 // 8-bit 1-line font 5x7
#define LCD_HD44780_8BIT2LINES 0x38 // 8-bit 2-lines font 5x7
 
// Select Apropriate Mode
#if LCD_INTERFACE_BITS==4
#if LCD_LINES == 1
#define LCD_HD44780_FNSET LCD_HD44780_4BIT1LINE // 4-bit 1-line
#else
#define LCD_HD44780_FNSET LCD_HD44780_4BIT2LINES // 4-bit 2-lines
#endif
#elif LCD_INTERFACE_BITS==8
#if LCD_LINES == 1
#define LCD_HD44780_FNSET LCD_HD44780_8BIT1LINE // 8-bit 1-line
#else
#define LCD_HD44780_FNSET LCD_HD44780_8BIT2LINES // 8-bit 2-lines
#endif
#endif
 
 
// User Defined Chars
// ------------------
 
// Definitions only.
// Because these definitions may be sent to lcd via printf,
// it is impossible to contain 0 bytes (end of string in C)
// so we ored 0x80 to each byte
 
#define LCD_CHAR_SPACE "\x80\x80\x80\x80\x80\x80\x80\x80" /* space (blank char) */
#define LCD_CHAR_BAT100 "\x8E\x9F\x9F\x9F\x9F\x9F\x9F\x1F" /* symbol battery full */
#define LCD_CHAR_BAT50 "\x8E\x9F\x91\x91\x93\x97\x9F\x1F" /* symbol baterry half */
#define LCD_CHAR_BAT0 "\x8E\x9F\x91\x91\x91\x91\x91\x1F" /* symbol baterry empty */
#define LCD_CHAR_UP "\x80\x84\x8E\x95\x84\x84\x84\x80" /* symbol arrow up */
#define LCD_CHAR_DOWN "\x80\x84\x84\x84\x95\x8E\x84\x80" /* symbol arrow down */
#define LCD_CHAR_LUA "\x84\x8E\x91\x91\x9F\x91\x91\x80" /* A s carkou */
#define LCD_CHAR_LLA "\x81\x82\x8E\x81\x9F\x91\x8F\x80" /* a s carkou */
#define LCD_CHAR_HUC "\x8A\x8E\x91\x90\x90\x91\x8E\x80" /* C s hackem */
#define LCD_CHAR_HLC "\x8A\x84\x8E\x90\x90\x91\x8E\x80" /* c s hackem */
#define LCD_CHAR_HUD "\x8A\x9C\x92\x91\x91\x92\x9C\x80" /* D s hackem */
#define LCD_CHAR_HLD "\x85\x83\x8D\x93\x91\x91\x8F\x80" /* d s hackem */
#define LCD_CHAR_LUE "\x84\x9F\x90\x90\x9E\x90\x9F\x80" /* E s carkou */
#define LCD_CHAR_LLE "\x81\x82\x8E\x91\x9F\x90\x8E\x80" /* e s carkou */
#define LCD_CHAR_HUE "\x8A\x9F\x90\x9E\x90\x90\x9F\x80" /* E s hackem */
#define LCD_CHAR_HLE "\x8A\x84\x8E\x91\x9F\x90\x8E\x80" /* e s hackem */
#define LCD_CHAR_LUI "\x84\x8E\x84\x84\x84\x84\x8E\x80" /* I s carkou */
#define LCD_CHAR_LLI "\x82\x84\x80\x8C\x84\x84\x8E\x80" /* i s carkou */
#define LCD_CHAR_HUN "\x8A\x95\x91\x99\x95\x93\x91\x80" /* N s hackem */
#define LCD_CHAR_HLN "\x8A\x84\x96\x99\x91\x91\x91\x80" /* n s hackem */
#define LCD_CHAR_LUO "\x84\x8E\x91\x91\x91\x91\x8E\x80" /* O s carkou */
#define LCD_CHAR_LLO "\x82\x84\x8E\x91\x91\x91\x8E\x80" /* o s carkou */
#define LCD_CHAR_HUR "\x8A\x9E\x91\x9E\x94\x92\x91\x80" /* R s hackem */
#define LCD_CHAR_HLR "\x8A\x84\x96\x99\x90\x90\x90\x80" /* r s hackem */
#define LCD_CHAR_HUS "\x8A\x8F\x90\x8E\x81\x81\x9E\x80" /* S s hackem */
#define LCD_CHAR_HLS "\x8A\x84\x8E\x90\x8E\x81\x9E\x80" /* s s hackem */
#define LCD_CHAR_HUT "\x8A\x9F\x84\x84\x84\x84\x84\x80" /* T s hackem */
#define LCD_CHAR_HLT "\x8A\x8C\x9C\x88\x88\x89\x86\x80" /* t s hackem */
#define LCD_CHAR_LUU "\x82\x95\x91\x91\x91\x91\x8E\x80" /* U s carkou */
#define LCD_CHAR_LLU "\x82\x84\x91\x91\x91\x93\x8D\x80" /* u s carkou */
#define LCD_CHAR_CUU "\x86\x97\x91\x91\x91\x91\x8E\x80" /* U s krouzkem */
#define LCD_CHAR_CLU "\x86\x86\x91\x91\x91\x91\x8E\x80" /* u s krouzkem */
#define LCD_CHAR_LUY "\x82\x95\x91\x8A\x84\x84\x84\x80" /* Y s carkou */
#define LCD_CHAR_LLY "\x82\x84\x91\x91\x8F\x81\x8E\x80" /* y s carkou */
#define LCD_CHAR_HUZ "\x8A\x9F\x81\x82\x84\x88\x9F\x80" /* Z s hackem */
#define LCD_CHAR_HLZ "\x8A\x84\x9F\x82\x84\x88\x9F\x80" /* z s hackem */
 
 
// Program
// -------
 
 
static int8_t lcd_posx; // Mirror Register with Position X (1..LCD_CHARS)
#if LCD_LINES > 1
static int8_t lcd_posy; // Mirror Register with Position Y (1..LCD_LINES)
#endif
 
 
// Send a Nibble or Byte to the LCD COntroller
static void
lcd_send_nibble(uint8_t rs, uint8_t data)
{
// Select Register or Data
if (rs)
LCD_RS_PORT |= (1<<LCD_RS_BIT);
else
LCD_RS_PORT &= ~(1<<LCD_RS_BIT);
 
// Put 4bit/8bit data
LCD_DATA_PORT = (LCD_DATA_PORT & ~LCD_DATA_MASK) | ((data<<LCD_DATA_BIT)&LCD_DATA_MASK);
_delay_us(1); // Data Setup Time
 
// Click Enable on and off
LCD_E_PORT |= 1<<LCD_E_BIT;
_delay_us(1);
LCD_E_PORT &= ~(1<<LCD_E_BIT);
_delay_us(40);
}
 
 
// Send a Byte to the LCD Controller
#if LCD_INTERFACE_BITS == 4
static void
lcd_send_byte(uint8_t rs, uint8_t data)
{
lcd_send_nibble(rs, data >> 4); // High Order Data
lcd_send_nibble(rs, data); // Low Order Data
}
#else
#define lcd_send_byte lcd_send_nibble
#endif
 
 
// Send a Command to the LCD Controller (RS=0)
#define lcd_send_cmd(n) lcd_send_byte(0, (n))
 
 
// Send a Data Byte to the LCD Controller (RS=1)
#define lcd_send_data(n) lcd_send_byte(1, (n))
 
 
// Goto Home
void
lcd_home()
{
lcd_send_cmd(LCD_HD44780_HOME); // Zero Cursor Position and Offset
#if LCD_LINES > 1
lcd_posx=lcd_posy=1;
#else
lcd_posx=1;
#endif
_delay_ms(2);
}
 
 
// Clear Display
void
lcd_clear()
{
lcd_send_cmd(LCD_HD44780_CLR); // Clear Memory
_delay_ms(2);
}
 
 
// Switch Cursor On
void
lcd_cursor_on()
{
lcd_send_cmd(LCD_HD44780_CURSORON);
}
 
 
// Switch Cursor Off
void
lcd_cursor_off()
{
lcd_send_cmd(LCD_HD44780_CURSOROFF);
}
 
 
// Clear Display and Goto Home with no Cursor
void
lcd_clear_home()
{
lcd_clear(); // Clear Memory
lcd_home(); // Zero Cursor Position and Offset
lcd_cursor_off(); // No Cursor
}
 
 
// Move to Position (1,1 is the first position)
void lcd_gotoxy(uint8_t x, uint8_t y)
{
uint8_t Adr;
 
Adr=x-1;
#if LCD_LINES > 1
switch (y)
{
case 2:
Adr+=LCD_LINE_2;
break;
#if LCD_LINES > 2
case 3:
Adr+=LCD_LINE_3;
break;
case 4:
Adr+=LCD_LINE_4;
break;
#endif
}
#endif
 
lcd_send_cmd(0x80 | (Adr & 0x7F) );
lcd_posx=x;
#if LCD_LINES > 1
lcd_posy=y;
#endif
}
 
 
// Increment Position
void
lcd_inc_pos()
{
// Next Position
lcd_posx++;
 
// Correct End of Line
#if LCD_LINES == 1
if (lcd_posx > 40)
lcd_posx = 1;
#elif LCD_LINES == 2
if (lcd_posx > 40)
{
lcd_posx = 1;
lcd_posy++; // on the Next Line
}
#elif LCD_LINES > 2
if ( ((lcd_posy & 1) && (lcd_posx > LCD_CHARS)) // Odd Lines are Short
|| (lcd_posx > 40-LCD_CHARS) ) // Memory is up to 40 Bytes
{
lcd_posx = 1; // Position 1
lcd_posy++; // on the Next Line
}
#endif
 
// Correct End of Last Line
#if LCD_LINES > 1
if (lcd_posy > LCD_LINES)
{
lcd_posy = 1;
}
#endif
}
 
// Decrement Position
void
lcd_dec_pos()
{
// Correct Beginning of Line
if (--lcd_posx==0) // Step Left
{ // If Beginning of the Line
#if LCD_LINES > 1
if(--lcd_posy==0); // Step Up
lcd_posy = LCD_LINES; // If we are on Top Go to the Bottom
#endif
#if LCD_LINES <= 2
lcd_posx = 40;
#else
if(lcd_posy & 1) // If Odd Line (the Short One)
lcd_posx = LCD_CHARS; // Set End of the Short Line
else // Else
lcd_posx = 40-LCD_CHARS; // Set End of Long Line
#endif
}
}
 
// Move Cursor Left
void
lcd_cursor_left()
{
lcd_send_cmd(LCD_HD44780_CURSORLEFT);
lcd_dec_pos();
}
 
 
// Move Cursor Right
void
lcd_cursor_right()
{
lcd_send_cmd(LCD_HD44780_CURSORRIGHT);
lcd_inc_pos();
}
 
 
// Init LCD Display
void
lcd_init(void)
{
// Port Init Direction
LCD_E_PORT &= ~_BV(LCD_E_BIT); // Enable off
LCD_E_DDR |= _BV(LCD_E_BIT); // Enable as Output
LCD_RS_DDR |= _BV(LCD_RS_BIT); // Register Select as Output
#ifdef LCD_RW
LCD_RW_DDR |= _BV(LCD_RW_BIT); // Read Write as Output
#endif
LCD_DATA_DDR |= LCD_DATA_MASK; // Data as Output
 
// Initial Delay
_delay_ms(40); // Delay for Vcc
 
// Sync 8/4 bit Interface
#if LCD_INTERFACE_BITS == 4
lcd_send_nibble(0, LCD_HD44780_8BIT1LINE >> 4); // 8 bit mode - sync nibble/byte
_delay_ms(4.1);
lcd_send_nibble(0, LCD_HD44780_8BIT1LINE >> 4);
_delay_us(100);
lcd_send_nibble(0, LCD_HD44780_8BIT1LINE >> 4);
// Set 4 bit mode
lcd_send_nibble(0, LCD_HD44780_FNSET >> 4);
#elif LCD_INTERFACE_BITS == 8
lcd_send_nibble(0, LCD_HD44780_8BIT1LINE); // 8 bit mode - sync nibble/byte
_delay_ms(4.1);
lcd_send_nibble(0, LCD_HD44780_8BIT1LINE);
_delay_us(100);
lcd_send_nibble(0, LCD_HD44780_8BIT1LINE);
#endif
 
// Set and Init
lcd_send_cmd(LCD_HD44780_FNSET); // 4/8 bits 1/2 lines
lcd_send_cmd(LCD_HD44780_ENTMODE_DEF); // increment/decrement, shift/no shift
lcd_clear_home(); // display on, no cursor, clear and home
}
 
 
// LCD Char Output
int
lcd_putc(char c)
{
static uint8_t mode=0;
 
switch (c)
{
case '\f':
lcd_clear_home(); // Clear Display
break;
 
case '\n':
#if LCD_LINES > 1
if (lcd_posy <= LCD_LINES) // Go to the Next Line
lcd_posy++;
#endif
 
case '\r':
#if LCD_LINES > 1
lcd_gotoxy(1,lcd_posy); // Go to the Beginning of the Line
#else
lcd_home();
#endif
break;
 
case '\b':
lcd_cursor_left(); // Cursor (Position) Move Back
break;
 
default:
if (mode==0 && c=='\v') // Startr of Definition String
{
mode=1; // Mode Next Char will be Defined Char
break;
}
if (mode==1) // First Char is Position Number
{
lcd_send_cmd(0x40 | ((c & 0x07)<<3) ); // Set CGRAM Address
mode++; // Mode Define Char Patern
break;
}
if (mode==2 && c=='\v') // End of Definition String
{
mode=0;
#if LCD_LINES > 1
lcd_gotoxy(lcd_posx,lcd_posy);
#else
lcd_gotoxy(lcd_posx,1);
#endif
break;
}
if (mode != 2) // Ordinary Chars
{
if (c<0x20) // Remap User Defind Char
c &= 0x07; // from rage 0x10-0x1F to 0x00-0x0f
lcd_inc_pos(); // Next Position
}
lcd_send_data(c); // Send Byte to LCD
break;
}
return 0; // Success
}
 
 
/Designs/skrysohledac2/SW/lcd_hd44780.h
0,0 → 1,164
/* ---------------------------------------------------------------------------
* AVR_MLIB - HD 44780 LCD Display Driver
* www.mlab.cz miho 2008
* ---------------------------------------------------------------------------
* LCD display driver for standard Hitachi 1/2/4 line character LCD modules
* for AVR processors. It uses 4 or 8 bit interface without readback.
* In the Examples section there is a demo application for this library.
* ---------------------------------------------------------------------------
* 00.00 2008/03/28 First Version
* ---------------------------------------------------------------------------
*/
 
 
// What should be set and done before here
// ---------------------------------------
//
// #include <stdio.h> // If you want to use printf, ...
//
// #define LCD_DATA B // 4 or 8 bits field (lsb bit of the port)
// #define LCD_DATA_BIT 4
//
// #define LCD_RS D // Register Select (port and bit)
// #define LCD_RS_BIT 4
//
// #define LCD_E D // Enable (port and bit)
// #define LCD_E_BIT 3
//
//
// // LCD Display Parameters
// #define LCD_INTERFACE_BITS 4 // 4 or 8 bit interface
// #define LCD_LINES 1 // 1 or 2 or 4 lines
// #define LCD_CHARS 20 // usualy 16 or 20, important for 4 line display only
//
// #include "lcd_hd44780.h" // Use LCD Library
//
//
// How to use the library
// ----------------------
//
// void lcd_init(void) // Init LCD Display
//
// void lcd_home() // Goto Home
//
// void lcd_clear() // Clear Display
//
// void lcd_clear_home() // Clear Display and Goto Home with no Cursor
//
// void lcd_cursor_on() // Switch Cursor On
//
// void lcd_cursor_off() // Switch Cursor Off
//
// void lcd_cursor_left() // Move Cursor Left
//
// void lcd_cursor_right() // Move Cursor Right
//
// void lcd_gotoxy(uint8_t x, uint8_t y) // Move to Position (1,1 is the first position)
//
// int lcd_putc(char c) // LCD Char Output
//
// int lcd_putc_stream(char c, FILE *unused) // LCD Char Output (for Stream Library)
//
//
// How to use printf
// -----------------
//
// 1) Define FILE structure
//
// static FILE lcd_stream = FDEV_SETUP_STREAM(lcd_putc_stream, NULL, _FDEV_SETUP_WRITE);
//
// 2) Connect it with standard output
//
// stdout = &lcd_stream; // Connect stdout to LCD Stream
//
// 3) Use printf
//
// printf("\fHello World!\n------------");
//
// 4) Use special chars
//
// \f - clear display and goto home
// \n - goto the beginning of the next line
// \r - goto to the beginning of curent line
// \b - backspace
// \v - start and end definition of user defined char
//
//
// How to use User Defined symbols
// -------------------------------
//
// That is easy. Just print the definition to lcd. Look at the example
//
// printf("\v" "\x10" LCD_CHAR_BAT50 "\v"); // definition (redefines CGRAM content of the LCD)
// printf("Battery Status \x10"); // usage
//
// \v starts the definition
// \x10 first (of eight) user defined char
// LCD_CHAR_BAT50 half battery symbol, you can define more symbols here (up to 8)
// \v end of definition
//
 
#include "global.h"
#include <avr/io.h> // Device Specific Defines
#include <stdio.h>
#include <util/delay.h> // Delay Routines
 
// IO Pins MACROS
#define GLUE(a,b) a##b
#define PORT(a) GLUE(PORT,a)
#define PIN(a) GLUE(PIN,a)
#define DDR(a) GLUE(DDR,a)
 
 
 
// LCD Port Settings
#define LCD_DATA A // 4 or 8 bits field (lsb port)
#define LCD_DATA_BIT 4
 
#define LCD_RS C // Register Select
#define LCD_RS_BIT 2
 
#define LCD_E C // Enable
#define LCD_E_BIT 4
 
// LCD Display Parameters
#define LCD_INTERFACE_BITS 4 // 4 or 8 bit interface
#define LCD_LINES 2 // 1 or 2 or 4 lines
#define LCD_CHARS 18 // usualy 16 or 20, important for 4 line display only
 
// Goto Home
void lcd_home(void);
 
// Clear Display
void lcd_clear(void);
 
// Switch Cursor On
void lcd_cursor_on(void);
 
// Switch Cursor Off
void lcd_cursor_off(void);
 
// Clear Display and Goto Home with no Cursor
void lcd_clear_home(void);
 
// Move to Position (1,1 is the first position)
void lcd_gotoxy(uint8_t x, uint8_t y);
 
// Increment Position
void lcd_inc_pos(void);
 
// Decrement Position
void lcd_dec_pos(void);
 
// Move Cursor Left
void lcd_cursor_left(void);
 
// Move Cursor Right
void lcd_cursor_right(void);
 
// Init LCD Display
void lcd_init(void);
 
// LCD Char Output
int lcd_putc(char c);
 
/Designs/skrysohledac2/SW/makefile
30,7 → 30,8
# They will be compiled in the order you list them, so it's probably best
# to list $(TRG).c, your top-level target file, last.
 
SRC = $(AVRLIB)/buffer.c $(AVRLIB)/uart2.c $(AVRLIB)/rprintf.c $(AVRLIB)/timer.c $(AVRLIB)/vt100.c $(AVRLIB)/tsip.c $(AVRLIB)/nmea.c $(AVRLIB)/gps.c $(AVRLIB)/lcd_hd44780.c $(TRG).c $(AVRLIB)/utm.c
# SRC = $(AVRLIB)/buffer.c $(AVRLIB)/uart2.c $(AVRLIB)/rprintf.c $(AVRLIB)/timer.c $(AVRLIB)/vt100.c $(AVRLIB)/tsip.c $(AVRLIB)/nmea.c $(AVRLIB)/gps.c $(AVRLIB)/lcd_hd44780.c $(AVRLIB)/utm.c $(TRG).c
SRC = buffer.c uart2.c rprintf.c timer.c vt100.c tsip.c nmea.c gps.c lcd_hd44780.c utm.c $(TRG).c
 
#put additional assembler source file here
# The ASRC line allows you to list files which contain assembly code/routines that
78,15 → 79,15
uart.o : uart.c uart.h global.h
uart2.o : uart2.c uart2.h global.h
rprintf.o : rprintf.c rprintf.h
a2d.o : a2d.c a2d.h
#a2d.o : a2d.c a2d.h
timer.o : timer.c timer.h global.h
pulse.o : pulse.c pulse.h timer.h global.h
#pulse.o : pulse.c pulse.h timer.h global.h
lcd.o : lcd.c lcd.h lcdconf.h global.h
i2c.o : i2c.c i2c.h global.h
spi.o : spi.c spi.h global.h
swpwm.o : swpwm.c swpwm.h global.h
servo.o : servo.c servo.h global.h
swuart.o : swuart.c swuart.h global.h
#i2c.o : i2c.c i2c.h global.h
#spi.o : spi.c spi.h global.h
#swpwm.o : swpwm.c swpwm.h global.h
#servo.o : servo.c servo.h global.h
#swuart.o : swuart.c swuart.h global.h
tsip.o : tsip.c tsip.h global.h
nmea.o : nmea.c nmea.h global.h
vt100.o : vt100.c vt100.h global.h
/Designs/skrysohledac2/SW/nmea.c
0,0 → 1,263
/*! \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);
memcpy(&GPSlat,&packet[i],9);
GPSlat[9]=0;
// 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
//!!!KAKL 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);
memcpy(&GPSlon,&packet[i]+1,9);
GPSlat[9]=0;
// 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++;
}
 
/Designs/skrysohledac2/SW/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
/Designs/skrysohledac2/SW/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
/Designs/skrysohledac2/SW/rprintf.c
0,0 → 1,833
/*! \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
 
void rprintfFloatMy(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++)
{
if(place == 0.1)
{
rprintfChar('.');
}
 
digit = (x/place);
 
if(digit | firstplace | (place == 1.0))
{
firstplace = TRUE;
rprintfChar(digit+0x30);
}
else
rprintfChar(' ');
x -= (digit*place);
place /= 10.0;
}
}
 
 
#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;
}
 
*/
/Designs/skrysohledac2/SW/rprintf.h
0,0 → 1,193
/*! \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
 
void rprintfFloatMy(char numDigits, double x);
 
// 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
//@}
/Designs/skrysohledac2/SW/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]();
}
/Designs/skrysohledac2/SW/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
/Designs/skrysohledac2/SW/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);
*/
}
 
/Designs/skrysohledac2/SW/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
/Designs/skrysohledac2/SW/uart.c
0,0 → 1,283
/*! \file uart.c \brief UART driver with buffer support. */
// *****************************************************************************
//
// File Name : 'uart.c'
// Title : UART driver with buffer support
// Author : Pascal Stang - Copyright (C) 2000-2002
// Created : 11/22/2000
// Revised : 06/09/2003
// Version : 1.3
// Target MCU : ATMEL AVR Series
// Editor Tabs : 4
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
// *****************************************************************************
 
#include <avr/io.h>
#include <avr/interrupt.h>
 
#include "buffer.h"
#include "uart.h"
 
// UART global variables
// flag variables
volatile u08 uartReadyTx; ///< uartReadyTx flag
volatile u08 uartBufferedTx; ///< uartBufferedTx flag
// receive and transmit buffers
cBuffer uartRxBuffer; ///< uart receive buffer
cBuffer uartTxBuffer; ///< uart transmit buffer
unsigned short uartRxOverflow; ///< receive overflow counter
 
#ifndef UART_BUFFERS_EXTERNAL_RAM
// using internal ram,
// automatically allocate space in ram for each buffer
static char uartRxData[UART_RX_BUFFER_SIZE];
static char uartTxData[UART_TX_BUFFER_SIZE];
#endif
 
typedef void (*voidFuncPtru08)(unsigned char);
volatile static voidFuncPtru08 UartRxFunc;
 
// enable and initialize the uart
void uartInit(void)
{
// initialize the buffers
uartInitBuffers();
// initialize user receive handler
UartRxFunc = 0;
 
// enable RxD/TxD and interrupts
outb(UCR, BV(RXCIE)|BV(TXCIE)|BV(RXEN)|BV(TXEN));
 
// set default baud rate
uartSetBaudRate(UART_DEFAULT_BAUD_RATE);
// initialize states
uartReadyTx = TRUE;
uartBufferedTx = FALSE;
// clear overflow count
uartRxOverflow = 0;
// enable interrupts
sei();
}
 
// create and initialize the uart transmit and receive buffers
void uartInitBuffers(void)
{
#ifndef UART_BUFFERS_EXTERNAL_RAM
// initialize the UART receive buffer
bufferInit(&uartRxBuffer, uartRxData, UART_RX_BUFFER_SIZE);
// initialize the UART transmit buffer
bufferInit(&uartTxBuffer, uartTxData, UART_TX_BUFFER_SIZE);
#else
// initialize the UART receive buffer
bufferInit(&uartRxBuffer, (u08*) UART_RX_BUFFER_ADDR, UART_RX_BUFFER_SIZE);
// initialize the UART transmit buffer
bufferInit(&uartTxBuffer, (u08*) UART_TX_BUFFER_ADDR, UART_TX_BUFFER_SIZE);
#endif
}
 
// redirects received data to a user function
void uartSetRxHandler(void (*rx_func)(unsigned char c))
{
// set the receive interrupt to run the supplied user function
UartRxFunc = rx_func;
}
 
// set the uart baud rate
void uartSetBaudRate(u32 baudrate)
{
// calculate division factor for requested baud rate, and set it
u16 bauddiv = ((F_CPU+(baudrate*8L))/(baudrate*16L)-1);
outb(UBRRL, bauddiv);
#ifdef UBRRH
outb(UBRRH, bauddiv>>8);
#endif
}
 
// returns the receive buffer structure
cBuffer* uartGetRxBuffer(void)
{
// return rx buffer pointer
return &uartRxBuffer;
}
 
// returns the transmit buffer structure
cBuffer* uartGetTxBuffer(void)
{
// return tx buffer pointer
return &uartTxBuffer;
}
 
// transmits a byte over the uart
void uartSendByte(u08 txData)
{
// wait for the transmitter to be ready
while(!uartReadyTx);
// send byte
outb(UDR, txData);
// set ready state to FALSE
uartReadyTx = FALSE;
}
 
// gets a single byte from the uart receive buffer (getchar-style)
int uartGetByte(void)
{
u08 c;
if(uartReceiveByte(&c))
return c;
else
return -1;
}
 
// gets a byte (if available) from the uart receive buffer
u08 uartReceiveByte(u08* rxData)
{
// make sure we have a receive buffer
if(uartRxBuffer.size)
{
// make sure we have data
if(uartRxBuffer.datalength)
{
// get byte from beginning of buffer
*rxData = bufferGetFromFront(&uartRxBuffer);
return TRUE;
}
else
{
// no data
return FALSE;
}
}
else
{
// no buffer
return FALSE;
}
}
 
// flush all data out of the receive buffer
void uartFlushReceiveBuffer(void)
{
// flush all data from receive buffer
//bufferFlush(&uartRxBuffer);
// same effect as above
uartRxBuffer.datalength = 0;
}
 
// return true if uart receive buffer is empty
u08 uartReceiveBufferIsEmpty(void)
{
if(uartRxBuffer.datalength == 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
 
// add byte to end of uart Tx buffer
u08 uartAddToTxBuffer(u08 data)
{
// add data byte to the end of the tx buffer
return bufferAddToEnd(&uartTxBuffer, data);
}
 
// start transmission of the current uart Tx buffer contents
void uartSendTxBuffer(void)
{
// turn on buffered transmit
uartBufferedTx = TRUE;
// send the first byte to get things going by interrupts
uartSendByte(bufferGetFromFront(&uartTxBuffer));
}
/*
// transmit nBytes from buffer out the uart
u08 uartSendBuffer(char *buffer, u16 nBytes)
{
register u08 first;
register u16 i;
 
// check if there's space (and that we have any bytes to send at all)
if((uartTxBuffer.datalength + nBytes < uartTxBuffer.size) && nBytes)
{
// grab first character
first = *buffer++;
// copy user buffer to uart transmit buffer
for(i = 0; i < nBytes-1; i++)
{
// put data bytes at end of buffer
bufferAddToEnd(&uartTxBuffer, *buffer++);
}
 
// send the first byte to get things going by interrupts
uartBufferedTx = TRUE;
uartSendByte(first);
// return success
return TRUE;
}
else
{
// return failure
return FALSE;
}
}
*/
// UART Transmit Complete Interrupt Handler
UART_INTERRUPT_HANDLER(SIG_UART_TRANS)
{
// check if buffered tx is enabled
if(uartBufferedTx)
{
// check if there's data left in the buffer
if(uartTxBuffer.datalength)
{
// send byte from top of buffer
outb(UDR, bufferGetFromFront(&uartTxBuffer));
}
else
{
// no data left
uartBufferedTx = FALSE;
// return to ready state
uartReadyTx = TRUE;
}
}
else
{
// we're using single-byte tx mode
// indicate transmit complete, back to ready
uartReadyTx = TRUE;
}
}
 
// UART Receive Complete Interrupt Handler
UART_INTERRUPT_HANDLER(SIG_UART_RECV)
{
u08 c;
// get received char
c = inb(UDR);
 
// if there's a user function to handle this receive event
if(UartRxFunc)
{
// call it and pass the received data
UartRxFunc(c);
}
else
{
// otherwise do default processing
// put received char in buffer
// check if there's space
if( !bufferAddToEnd(&uartRxBuffer, c) )
{
// no space in buffer
// count overflow
uartRxOverflow++;
}
}
}
/Designs/skrysohledac2/SW/uart.h
0,0 → 1,232
/*! \file uart.h \brief UART driver with buffer support. */
//*****************************************************************************
//
// File Name : 'uart.h'
// Title : UART driver with buffer support
// Author : Pascal Stang - Copyright (C) 2000-2002
// Created : 11/22/2000
// Revised : 02/01/2004
// Version : 1.3
// Target MCU : ATMEL AVR Series
// Editor Tabs : 4
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
/// \ingroup driver_avr
/// \defgroup uart UART Driver/Function Library (uart.c)
/// \code #include "uart.h" \endcode
/// \par Overview
/// This library provides both buffered and unbuffered transmit and receive
/// functions for the AVR processor UART.  Buffered access means that the
/// UART can transmit and receive data in the "background", while your code
/// continues executing.  Also included are functions to initialize the
/// UART, set the baud rate, flush the buffers, and check buffer status.
///
/// \note For full text output functionality, you may wish to use the rprintf
/// functions along with this driver.
///
/// \par About UART operations
/// Most Atmel AVR-series processors contain one or more hardware UARTs
/// (aka, serial ports). UART serial ports can communicate with other
/// serial ports of the same type, like those used on PCs. In general,
/// UARTs are used to communicate with devices that are RS-232 compatible
/// (RS-232 is a certain kind of serial port).
/// \par
/// By far, the most common use for serial communications on AVR processors
/// is for sending information and data to a PC running a terminal program.
/// Here is an exmaple:
/// \code
/// uartInit(); // initialize UART (serial port)
/// uartSetBaudRate(9600); // set UART speed to 9600 baud
/// rprintfInit(uartSendByte); // configure rprintf to use UART for output
/// rprintf("Hello World\r\n"); // send "hello world" message via serial port
/// \endcode
///
/// \warning The CPU frequency (F_CPU) must be set correctly in \c global.h
/// for the UART library to calculate correct baud rates. Furthermore,
/// certain CPU frequencies will not produce exact baud rates due to
/// integer frequency division round-off. See your AVR processor's
/// datasheet for full details.
//
//*****************************************************************************
//@{
 
#ifndef UART_H
#define UART_H
 
#include "global.h"
#include "buffer.h"
 
//! Default uart baud rate.
/// This is the default speed after a uartInit() command,
/// and can be changed by using uartSetBaudRate().
#define UART_DEFAULT_BAUD_RATE 9600
 
// buffer memory allocation defines
// buffer sizes
#ifndef UART_TX_BUFFER_SIZE
//! Number of bytes for uart transmit buffer.
/// Do not change this value in uart.h, but rather override
/// it with the desired value defined in your project's global.h
#define UART_TX_BUFFER_SIZE 0x0040
#endif
#ifndef UART_RX_BUFFER_SIZE
//! Number of bytes for uart receive buffer.
/// Do not change this value in uart.h, but rather override
/// it with the desired value defined in your project's global.h
#define UART_RX_BUFFER_SIZE 0x0040
#endif
 
// define this key if you wish to use
// external RAM for the UART buffers
//#define UART_BUFFER_EXTERNAL_RAM
#ifdef UART_BUFFER_EXTERNAL_RAM
// absolute address of uart buffers
#define UART_TX_BUFFER_ADDR 0x1000
#define UART_RX_BUFFER_ADDR 0x1100
#endif
 
//! Type of interrupt handler to use for uart interrupts.
/// Value may be SIGNAL or INTERRUPT.
/// \warning Do not change unless you know what you're doing.
#ifndef UART_INTERRUPT_HANDLER
#define UART_INTERRUPT_HANDLER SIGNAL
#endif
 
// compatibility with most newer processors
#ifdef UCSRB
#define UCR UCSRB
#endif
// compatibility with old Mega processors
#if defined(UBRR) && !defined(UBRRL)
#define UBRRL UBRR
#endif
// compatibility with megaXX8 processors
#if defined(__AVR_ATmega88__) || \
defined(__AVR_ATmega168__) || \
defined(__AVR_ATmega644__)
#define UDR UDR0
#define UCR UCSR0B
#define RXCIE RXCIE0
#define TXCIE TXCIE0
#define RXC RXC0
#define TXC TXC0
#define RXEN RXEN0
#define TXEN TXEN0
#define UBRRL UBRR0L
#define UBRRH UBRR0H
#define SIG_UART_TRANS SIG_USART_TRANS
#define SIG_UART_RECV SIG_USART_RECV
#define SIG_UART_DATA SIG_USART_DATA
#endif
// compatibility with mega169 processors
#if defined(__AVR_ATmega169__)
#define SIG_UART_TRANS SIG_USART_TRANS
#define SIG_UART_RECV SIG_USART_RECV
#define SIG_UART_DATA SIG_USART_DATA
#endif
// compatibility with dual-uart processors
// (if you need to use both uarts, please use the uart2 library)
#if defined(__AVR_ATmega161__)
#define UDR UDR0
#define UCR UCSR0B
#define UBRRL UBRR0
#define SIG_UART_TRANS SIG_UART0_TRANS
#define SIG_UART_RECV SIG_UART0_RECV
#define SIG_UART_DATA SIG_UART0_DATA
#endif
#if defined(__AVR_ATmega128__)
#ifdef UART_USE_UART1
#define UDR UDR1
#define UCR UCSR1B
#define UBRRL UBRR1L
#define UBRRH UBRR1H
#define SIG_UART_TRANS SIG_UART1_TRANS
#define SIG_UART_RECV SIG_UART1_RECV
#define SIG_UART_DATA SIG_UART1_DATA
#else
#define UDR UDR0
#define UCR UCSR0B
#define UBRRL UBRR0L
#define UBRRH UBRR0H
#define SIG_UART_TRANS SIG_UART0_TRANS
#define SIG_UART_RECV SIG_UART0_RECV
#define SIG_UART_DATA SIG_UART0_DATA
#endif
#endif
 
// functions
 
//! Initializes uart.
/// \note After running this init function, the processor
/// I/O pins that used for uart communications (RXD, TXD)
/// are no long available for general purpose I/O.
void uartInit(void);
 
//! Initializes transmit and receive buffers.
/// Automatically called from uartInit()
void uartInitBuffers(void);
 
//! Redirects received data to a user function.
///
void uartSetRxHandler(void (*rx_func)(unsigned char c));
 
//! Sets the uart baud rate.
/// Argument should be in bits-per-second, like \c uartSetBaudRate(9600);
void uartSetBaudRate(u32 baudrate);
 
//! Returns pointer to the receive buffer structure.
///
cBuffer* uartGetRxBuffer(void);
 
//! Returns pointer to the transmit buffer structure.
///
cBuffer* uartGetTxBuffer(void);
 
//! Sends a single byte over the uart.
/// \note This function waits for the uart to be ready,
/// therefore, consecutive calls to uartSendByte() will
/// go only as fast as the data can be sent over the
/// serial port.
void uartSendByte(u08 data);
 
//! Gets a single byte from the uart receive buffer.
/// Returns the byte, or -1 if no byte is available (getchar-style).
int uartGetByte(void);
 
//! Gets a single byte from the uart receive buffer.
/// Function returns TRUE if data was available, FALSE if not.
/// Actual data is returned in variable pointed to by "data".
/// Example usage:
/// \code
/// char myReceivedByte;
/// uartReceiveByte( &myReceivedByte );
/// \endcode
u08 uartReceiveByte(u08* data);
 
//! Returns TRUE/FALSE if receive buffer is empty/not-empty.
///
u08 uartReceiveBufferIsEmpty(void);
 
//! Flushes (deletes) all data from receive buffer.
///
void uartFlushReceiveBuffer(void);
 
//! Add byte to end of uart Tx buffer.
/// Returns TRUE if successful, FALSE if failed (no room left in buffer).
u08 uartAddToTxBuffer(u08 data);
 
//! Begins transmission of the transmit buffer under interrupt control.
///
void uartSendTxBuffer(void);
 
//! Sends a block of data via the uart using interrupt control.
/// \param buffer pointer to data to be sent
/// \param nBytes length of data (number of bytes to sent)
u08 uartSendBuffer(char *buffer, u16 nBytes);
 
#endif
//@}
 
 
/Designs/skrysohledac2/SW/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);
}
/Designs/skrysohledac2/SW/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
 
/Designs/skrysohledac2/SW/utm.c
24,9 → 24,9
 
*/
 
#include "stdafx.h"
#include "Common.h"
#include "osgb.h"
//#include "stdafx.h"
//#include "Common.h"
//#include "osgb.h"
#include "utm.h"
#include <math.h>
 
117,8 → 117,8
// asterisk character ('*').
//=======================================================================
 
void LatLonToUtm (double a, double f, int& utmXZone, char& utmYZone,
double& easting, double& northing, double lat, double lon)
void LatLonToUtm (double a, double f, int* utmXZone, char* utmYZone,
double* easting, double* northing, double lat, double lon)
{
double recf;
double b;
142,24 → 142,26
double nfn;
 
if (lon <= 0.0) {
utmXZone = 30 + (int)(lon / 6.0);
*utmXZone = 30 + (int)(lon / 6.0);
} else {
utmXZone = 31 + (int)(lon / 6.0);
*utmXZone = 31 + (int)(lon / 6.0);
}
if (lat < 84.0 && lat >= 72.0) {
// Special case: zone X is 12 degrees from north to south, not 8.
utmYZone = cArray[19];
*utmYZone = cArray[19];
} else {
utmYZone = cArray[(int)((lat + 80.0) / 8.0)];
*utmYZone = cArray[(int)((lat + 80.0) / 8.0)];
}
if (lat >= 84.0 || lat < -80.0) {
// Invalid coordinate; the vertical zone is set to the invalid
// character.
utmYZone = '*';
*utmYZone = '*';
}
 
double latRad = lat * deg2rad;
double lonRad = lon * deg2rad;
double latRad = lat * (M_PI/180);
double lonRad = lon * (M_PI/180);
// double latRad = lat * deg2rad;
// double lonRad = lon * deg2rad;
recf = 1.0 / f;
b = a * (recf - 1.0) / recf;
eSquared = CalculateESquared (a, b);
175,7 → 177,7
dp = 35.0 * a * ((tn * tn * tn) - (tn * tn * tn * tn) + 11.0
* (tn * tn * tn * tn * tn) / 16.0) / 48.0;
ep = 315.0 * a * ((tn * tn * tn * tn) - (tn * tn * tn * tn * tn)) / 512.0;
olam = (utmXZone * 6 - 183) * deg2rad;
olam = (*utmXZone * 6 - 183) * (M_PI/180);
dlam = lonRad - olam;
s = sin (latRad);
c = cos (latRad);
188,12 → 190,12
t3 = sn * s * (c * c * c) * ok * (5.0 - (t * t) + 9.0 * eta + 4.0
* (eta * eta)) / 24.0;
if (latRad < 0.0) nfn = 10000000.0; else nfn = 0;
northing = nfn + t1 + (dlam * dlam) * t2 + (dlam * dlam * dlam
*northing = nfn + t1 + (dlam * dlam) * t2 + (dlam * dlam * dlam
* dlam) * t3 + (dlam * dlam * dlam * dlam * dlam * dlam) + 0.5;
t6 = sn * c * ok;
t7 = sn * (c * c * c) * (1.0 - (t * t) + eta) / 6.0;
easting = fe + dlam * t6 + (dlam * dlam * dlam) * t7 + 0.5;
if (northing >= 9999999.0) northing = 9999999.0;
*easting = fe + dlam * t6 + (dlam * dlam * dlam) * t7 + 0.5;
if (*northing >= 9999999.0) *northing = 9999999.0;
}
 
//=======================================================================
203,187 → 205,9
// LatLonToUtm() member function.)
//=======================================================================
 
void LatLonToUtmWGS84 (int& utmXZone, char& utmYZone,
double& easting, double& northing, double lat, double lon)
void LatLonToUtmWGS84 (int* utmXZone, char* utmYZone,
double* easting, double* northing, double lat, double lon)
{
LatLonToUtm (6378137.0, 1 / 298.257223563, utmXZone, utmYZone,
easting, northing, lat, lon);
}
 
 
 
 
//=======================================================================
// Purpose:
// This function converts the specified UTM coordinate to a lat/lon
// coordinate.
// Pre:
// - utmXZone must be between 1 and 60, inclusive.
// - utmYZone must be one of: CDEFGHJKLMNPQRSTUVWX
// Parameters:
// double a:
// Ellipsoid semi-major axis, in meters. (For WGS84 datum, use 6378137.0)
// double f:
// Ellipsoid flattening. (For WGS84 datum, use 1 / 298.257223563)
// int utmXZone:
// The horizontal zone number of the UTM coordinate.
// char utmYZone:
// The vertical zone letter of the UTM coordinate.
// double easting, double northing:
// The UTM coordinate to convert.
// double& lat:
// Upon exit, lat contains the latitude.
// double& lon:
// Upon exit, lon contains the longitude.
// Notes:
// The code in this function is a C conversion of some of the source code
// from the Mapping Datum Transformation Software (MADTRAN) program, written
// in PowerBasic. To get the source code for MADTRAN, go to:
//
// http://164.214.2.59/publications/guides/MADTRAN/index.html
//
// and download MADTRAN.ZIP
//=======================================================================
 
void UtmToLatLon (double a, double f, int utmXZone, char utmYZone,
double easting, double northing, double& lat, double& lon)
{
double recf;
double b;
double eSquared;
double e2Squared;
double tn;
double ap;
double bp;
double cp;
double dp;
double ep;
double nfn;
double tmd;
double sr;
double sn;
double ftphi;
double s;
double c;
double t;
double eta;
double de;
double dlam;
double olam;
 
recf = 1.0 / f;
b = a * (recf - 1) / recf;
eSquared = CalculateESquared (a, b);
e2Squared = CalculateE2Squared (a, b);
tn = (a - b) / (a + b);
ap = a * (1.0 - tn + 5.0 * ((tn * tn) - (tn * tn * tn)) / 4.0 + 81.0 *
((tn * tn * tn * tn) - (tn * tn * tn * tn * tn)) / 64.0);
bp = 3.0 * a * (tn - (tn * tn) + 7.0 * ((tn * tn * tn)
- (tn * tn * tn * tn)) / 8.0 + 55.0 * (tn * tn * tn * tn * tn) / 64.0)
/ 2.0;
cp = 15.0 * a * ((tn * tn) - (tn * tn * tn) + 3.0 * ((tn * tn * tn * tn)
- (tn * tn * tn * tn * tn)) / 4.0) / 16.0;
dp = 35.0 * a * ((tn * tn * tn) - (tn * tn * tn * tn) + 11.0
* (tn * tn * tn * tn * tn) / 16.0) / 48.0;
ep = 315.0 * a * ((tn * tn * tn * tn) - (tn * tn * tn * tn * tn)) / 512.0;
if ((utmYZone <= 'M' && utmYZone >= 'C')
|| (utmYZone <= 'm' && utmYZone >= 'c')) {
nfn = 10000000.0;
} else {
nfn = 0;
}
tmd = (northing - nfn) / ok;
sr = sphsr (a, eSquared, 0.0);
ftphi = tmd / sr;
double t10, t11, t14, t15;
for (int i = 0; i < 5; i++) {
t10 = sphtmd (ap, bp, cp, dp, ep, ftphi);
sr = sphsr (a, eSquared, ftphi);
ftphi = ftphi + (tmd - t10) / sr;
}
sr = sphsr (a, eSquared, ftphi);
sn = sphsn (a, eSquared, ftphi);
s = sin (ftphi);
c = cos (ftphi);
t = s / c;
eta = e2Squared * (c * c);
de = easting - fe;
t10 = t / (2.0 * sr * sn * (ok * ok));
t11 = t * (5.0 + 3.0 * (t * t) + eta - 4.0 * (eta * eta) - 9.0 * (t * t)
* eta) / (24.0 * sr * (sn * sn * sn) * (ok * ok * ok * ok));
lat = ftphi - (de * de) * t10 + (de * de * de * de) * t11;
t14 = 1.0 / (sn * c * ok);
t15 = (1.0 + 2.0 * (t * t) + eta) / (6 * (sn * sn * sn) * c
* (ok * ok * ok));
dlam = de * t14 - (de * de * de) * t15;
olam = (utmXZone * 6 - 183.0) * deg2rad;
lon = olam + dlam;
lon *= rad2deg;
lat *= rad2deg;
}
 
//=======================================================================
// Purpose:
// This function converts the specified UTM coordinate to a lat/lon
// coordinate in the WGS84 datum. (See the comment block for the
// UtmToLatLon() member function.
//=======================================================================
 
void UtmToLatLonWGS84 (int utmXZone, char utmYZone, double easting,
double northing, double& lat, double& lon)
{
UtmToLatLon (6378137.0, 1 / 298.257223563, utmXZone, utmYZone,
easting, northing, lat, lon);
}
 
//=======================================================================
/**
@func Build a position string
@parm target. must be 30 characters or longer.
*/
//=======================================================================
 
void CUtmPoint::GetString(TCHAR *position) const
{
_stprintf(position,
_T("%02d%c %06d %07d"),
m_xzone, m_yzone,
(int)m_easting,
(int)m_northing);
}
 
//=======================================================================
/**
@func get the position of a UTM point
@parm point out
*/
//=======================================================================
 
void CUtmPoint::ToPosition(CPosition &pos) const
{
double lat,lon;
UtmToLatLonWGS84(m_xzone,m_yzone,m_easting,m_northing,
lat,lon);
pos.Clear();
pos.SetLatitude(lat);
pos.SetLongitude(lon);
}
 
//=======================================================================
/**
@func turn a position into a UTM point
@parm position
@rdesc true if it was in range
*/
//=======================================================================
 
bool CUtmPoint::FromPosition(const CPosition &pos)
{
Clear();
if(!IsPositionInUtmSpace(pos))
return false;
LatLonToUtmWGS84(m_xzone,m_yzone,m_easting,m_northing,
pos.GetLatitude(),
pos.GetLongitude());
return true;
}
/Designs/skrysohledac2/SW/utm.h
10,7 → 10,6
* @doc
*
************************************************************************/
#pragma once
 
//=======================================================================
/**
17,86 → 16,6
* UTM support goes here
*/
//=======================================================================
class CUtmPoint
{
protected:
double m_easting;
double m_northing;
int m_xzone;
char m_yzone;
public:
void LatLonToUtmWGS84 (int* utmXZone, char* utmYZone,
double* easting, double* northing, double lat, double lon);
 
//=======================================================================
//=======================================================================
CUtmPoint()
{Clear();}
 
//=======================================================================
//=======================================================================
CUtmPoint(const CPosition &p)
{
FromPosition(p);
}
 
//=======================================================================
//=======================================================================
CUtmPoint(const CUtmPoint& that)
{
m_easting=that.m_easting;
m_northing=that.m_northing;
m_xzone=that.m_xzone;
m_yzone=that.m_yzone;
}
 
//=======================================================================
//=======================================================================
void Clear()
{
m_easting=m_northing=0;
m_xzone=0;
m_yzone=0;
}
 
//=======================================================================
/**
@func Build a position string
@parm target. must be 30 characters or longer.
*/
//=======================================================================
 
void GetString(TCHAR *position) const;
 
//=======================================================================
/**
@func get the position of a UTM point
@parm point out
*/
//=======================================================================
 
void ToPosition(CPosition &pos) const;
 
//=======================================================================
/**
@func turn a position into a UTM point
@parm position
@rdesc true if it was in range
*/
//=======================================================================
 
bool FromPosition(const CPosition &pos);
 
//=======================================================================
/**
range test
*/
//=======================================================================
 
static bool IsPositionInUtmSpace(const CPosition &pos)
{ return pos.GetLatitude()<=84 && pos.GetLatitude()>=-80;}
 
 
 
};