abs
int abs(int x);Description
Computes the absolute value of an integer argument.
Parameters
xReturn value
Absolute value of the argument.
Library
MATH.LIBSee also
fabs
acos
float acos(float x);Description
Computes the arccosine of real
floatvaluex.Parameters
xAssumed to be between -1 and 1.
Return value
Arccosine of the argument.
Ifxis out of bounds, the function returns0and signals a domain error.Library
MATH.LIBSee also
cos, cosh, asin, atan
acot
float acot(float x);Description
Computes the arcotangent of real
floatvaluex.Parameters
xAssumed to be between -INF and +INF.
Return value
Library
MATH.LIBSee also
tan, atan
acsc
float acsc(float x);Description
Computes the arccosecant of real
floatvaluex.Parameters
xAssumed to be between -INF and +INF.
Return value
The arccosecant of the argument.
Library
MATH.LIBSee also
sin, asin
AESdecrypt
void AESdecrypt(char *data, char *expandedkey, int nb, int nk );Description
Decrypts a block of data using an implementation of the Rijndael AES cipher. The encryped block of data is overwritten by the decrypted block of data.
Parameters
dataA block of data to be decrypted.
expandedkeyA set of round keys (generated by
AESexpandKey()).nbThe block size to use. Block is 4 *
nbbytes long.nkThe key size to use. Cipher key is 4 *
nkbytes long.Library
AES_CRYPT.LIB
AESdecryptStream
void AESdecryptStream(AESstreamState *state, char *data, int count);Description
Decrypts an array of bytes using the Rabbit implementation of cipher feedback mode. See
Samples\Crypt\AES_STREAMTEST.Cfor a sample program and a detailed explanation of the encryption/decryption process.Parameters
stateThe
AESstreamStatestructure. This memory must be allocated in the program code before callingAESdecrptyStream():static AESstreamState decrypt_state;dataAn array of bytes that will be decrypted in place.
countLibrary
AES_CRYPT.LIB
AESencrypt
void AESencrypt(char *data, char *expandedkey, int nb, int nk );Description
Encrypts a block of data using an implementation of the Rijndael AES cipher. The block of data is overwritten by the encrypted block of data.
Parameters
dataA block of data to be encrypted
expandedkeyA set of round keys (generated by
AESexpandKey())nbThe block size to use. Block is 4 *
nbbytes longnkThe key size to use. Cipher key is 4 *
nkbytes longReturn value
Library
AES_CRYPT.LIB
AESencryptStream
void AESencryptStream(AESstreamState *state, char *data, int count);Description
Encrypts an array of bytes using the Rabbit implementation of cipher feedback mode. See
Samples\Crypt\AES_STREAMTEST.Cfor a sample program and a detailed explanation of the encryption/decryption process.Parameters
stateThe
AESstreamStatestructure. This memory must be allocated in the program code before callingAESencrptyStream():static AESstreamState encrypt_state;dataAn array of bytes that will be encrypted in place.
countLibrary
AES_CRYPT.LIB
AESexpandKey
void AESexpandKey(char *expanded, char *key, int nb, int nk, int rounds);Description
Prepares a key for use by expanding it into a set of round keys. A key is a "password" to decipher encoded data.
Parameters
expandedA buffer for storing the expanded key. The size of the expanded key is 4 *
nb* (rounds+ 1).keyThe cipher key, the size should be 4 *
nknbThe block size will be 4 *
nbbytes long.nkThe key size will be 4 *
nkbytes long.roundsThe number of cipher rounds to use.
Return value
Library
AES_CRYPT.LIB
AESinitStream
void AESinitStream(AESstreamState *state, char *key, char *init_vector);Description
Sets up
AESstreamStateto begin encrypting or decrypting a stream. EachAESstreamStatestructure can only be used for one direction. SeeSamples\Crypt\AES_STREAMTEST.Cfor a sample program and a detailed explanation of the encryption/decryption process.Parameters
stateAn
AESstreamStatestructure to be initialized. This memory must be allocated in the program code before callingAESinitStream().keyThe 16-byte cipher key, using a
NULLpointer will prevent an existing key from being recalculated.init_vectorA 16-byte array representing the initial state of the feedback registers. Both ends of the stream must begin with the same initialization vector.
Return value
Library
AES_CRYPT.LIB
asec
float asec(float x);Description
Computes the arcsecant of real
floatvaluex.Parameters
xAssumed to be between -INF and +INF.
Return value
The arcsecant of the argument.
Library
MATH.LIBSee also
cos, acos
asin
float asin(float x);Description
Computes the arcsine of real
floatvaluex.Parameters
xAssumed to be between -1 and +1.
Return value
Library
MATH.LIBSee also
sin, acsc
atan
float atan(float x);Description
Computes the arctangent of real
floatvaluex.Parameters
xAssumed to be between -INF and +INF.
Return value
The arctangent of the argument.
Library
MATH.LIBSee also
tan, acot
atan2
float atan2(float y, float x);Description
Computes the arctangent of real
floatvaluey/xto find the angle in radians between the x-axis and the ray through (0,0) and (x,y).Parameters
yThe point corresponding to the y-axis
xThe point corresponding to the x-axis
Return value
If both
yandxare zero, the function returns0and signals a domain error. Otherwise the arctangent ofy/xis returned as follows:Library
MATH.LIBSee also
acos, asin, atan, cos, sin, tan
atof
float atof(char *sptr);Description
ANSI String to Float Conversion (UNIX compatible).
Parameters
sptrReturn value
The converted floating value.
If the conversion is invalid,_xtoxErris set to1. Otherwise_xtoxErris set to0.Library
STRING.LIBSee also
atoi, atol, strtod
atoi
int atoi(char *sptr);Description
ANSI String to Integer Conversion (UNIX compatible).
Parameters
sptrReturn value
Library
STRING.LIBSee also
atol, atof, strtod
atol
long atol(char *sptr);Description
ANSI String to Long Conversion (UNIX compatible).
Parameters
sptrReturn value
The converted long integer value.
Library
STRING.LIBSee also
atoi, atof, strtod
bit
unsigned int bit(void *address, unsigned int bit);Description
Dynamic C may expand this call inline
Reads specified bit at memory address.
bitmay be from 0 to 31. This is equivalent to the following expression, but more efficient: (*(long *)address >> bit) & 1Parameters
addressAddress of byte containing bits 7-0
bitBit location where 0 represents the least significant bit
Return value
1: Specified bit is set.0: Bit is clear.Library
UTIL.LIBSee also
BIT
BIT
unsigned int BIT(void *address, unsigned int bit);Description
Dynamic C may expand this call inline
Reads specified bit at memory address.
bitmay be from 0 to 31. This is equivalent to the following expression, but more efficient:(*(long *)address>>bit) &1Parameters
addressAddress of byte containing bits 7-0
bitBit location where 0 represents the least significant bit
Return value
1if specified bit is set;0if bit is clear.Library
UTIL.LIBSee also
bit
BitRdPortE
root int BitRdPortE(unsigned int port, int bitnumber);Description
Returns 1 or 0 matching the value of the bit read from the specified external I/O port.
Parameters
portAddress of external parallel port data register.
bitnumberReturn value
0or1: The value of the bit read.Library
SYSIO.LIBSee also
RdPortI, BitRdPortI, WrPortI, BitWrPortI, RdPortE, WrPortE, BitWrPortE
BitRdPortI
int BitRdPortI(int port, int bitnumber);Description
Returns 1 or 0 matching the value of the bit read from the specified internal I/O port.
Parameters
portAddress of internal parallel port data register.
bitnumberReturn value
0or1: The value of the bit read.Library
SYSIO.LIBSee also
RdPortI, WrPortI, BitWrPortI, BitRdPortE, RdPortE, WrPortE, BitWrPortE
BitWrPortE
void BitWrPortE( unsigned int port, char *portshadow, int value, int bitcode);Description
Updates shadow register at bitcode with value (0 or 1) and copies shadow to register.
WARNING! A shadow register is required for this function.
Parameters
portAddress of external parallel port data register.
portshadowReference pointer to a variable to shadow the current value of the register.
valueValue of 0 or 1 to be written to the bit position.
bitcodeLibrary
SYSIO.LIBSee also
RdPortI, BitRdPortI, WrPortI, BitWrPortI, BitRdPortE, RdPortE, WrPortE
BitWrPortI
void BitWrPortI( int port, char *portshadow, int value, int bitcode);Description
Updates shadow register at position
bitcodewithvalue(0 or 1); copies shadow to register.WARNING! A shadow register is required for this function.
Parameters
portAddress of internal parallel port data register.
portshadowReference pointer to a variable to shadow the current value of the register.
valueValue of 0 or 1 to be written to the bit position.
bitcodeLibrary
SYSIO.LIBSee also
RdPortI, BitRdPortI, WrPortI, BitRdPortE, RdPortE, WrPortE, BitWrPortE
ceil
float ceil(float x);Description
Computes the smallest integer greater than or equal to the given number.
Parameters
xReturn value
Library
MATH.LIBSee also
floor, fmod
chkHardReset
int chkHardReset( void );Description
This function determines whether this restart of the board is due to a hardware reset. Asserting the RESET line or recycling power are both considered hardware resets. A watchdog timeout is not a hardware reset.
Return value
1: The processor was restarted due to a hardware reset.0: If it was not.Library
Sys.libSee Also
chkSoftReset, chkWDTO, _sysIsSoftReset
chkSoftReset
int chkSoftReset( void );Description
This function determines whether this restart of the board is due to a software reset from Dynamic C or a call to
forceSoftReset().Return value
1: The board was restarted due to a soft reset.0: If it was not.Library
Sys.libSee Also
chkHardReset, chkWDTO, _sysIsSoftReset
chkWDTO
int chkWDTO( void );Description
This function determines whether this restart of the board is due to a watchdog timeout.
Return value
1: If the board was restarted due to a watchdog timeout.0: If it was not.Library
Sys.libSee Also
chkHardReset, chkSoftReset, _sysIsSoftReset
clockDoublerOn
void clockDoublerOn();Description
Enables the Rabbit clock doubler. If the doubler is already enabled, there will be no effect. Also attempts to adjust the communication rate between Dynamic C and the board to compensate for the frequency change. User serial port rates need to be adjusted accordingly. Also note that single-stepping through this routine will cause Dynamic C to lose communication with the target.
Library
SYS.LIBSee also
clockDoublerOff
clockDoublerOff
void clockDoublerOff();Description
Disables the Rabbit clock doubler. If the doubler is already disabled, there will be no effect. Also attempts to adjust the communication rate between Dynamic C and the board to compensate for the frequency change. User serial port rates need to be adjusted accordingly. Also note that single-stepping through this routine will cause Dynamic C to lose communication with the target.
Library
SYS.LIBSee also
clockDoublerOn
CoBegin
void CoBegin(CoData *p);Description
Initialize a costatement structure so the costatement will be executed next time it is encountered.
Parameters
pLibrary
COSTATE.LIB
cof_pktXreceive
int cof_pktXreceive(void *buffer, int buffer_size); X=A|B|C|DDescription
Receives an incoming packet. This function will return after a complete packet has been read into the buffer.
Starting with Dynamic C version 7.25, the functions
cof_pktEreceive()andcof_pktFreceive()are available when using the Rabbit 3000 microprocessor.Parameters
bufferA buffer for the packet to be written into.
buffer_sizeReturn value
>0: The number of bytes in the received packet on success.0: No new packets have been received.-1: The packet is too large for the given buffer.-2: A neededtest_packetfunction is not defined.Library
PACKET.LIB
cof_pktXsend
void cof_pktXsend(void *send_buffer int buffer_length, char delay); X=A|B|C|DDescription
Initiates the sending of a packet of data. The function will exit when the packet is finished transmitting.
Starting with Dynamic C version 7.25, the functions
cof_pktEsend()andcof_pktFsend()are available when using the Rabbit 3000 microprocessor.Parameters
send_bufferbuffer_lengthLength of the data buffer to transmit.
delayThe number of byte times (0-255) to delay before sending data. This is used to implement protocol-specific delays between packets.
Library
PACKET.LIB
cof_serXgetc
int cof_serXgetc(); /* where X = A|B|C|D */Description
This single-user cofunction yields to other tasks until a character is read from port X. This function only returns when a character is successfully written. It is non-reentrant.
Starting with Dynamic C version 7.25, the functions
cof_serEgetc()andcof_serFgetc()may be used with the Rabbit 3000 microprocessor.Return value
An integer with the character read into the low byte.
Library
RS232.LIBExample
// echoes characters
main() {
int c;
serXopen(19200);
loopinit();
while (1) {
loophead();
wfd c = cof_serAgetc();
wfd cof_serAputc(c);
}
serAclose();
}
cof_serXgets
int cof_serXgets(char *s, int max, unsigned long tmout);
/* where X = A|B|C|D */Description
This single-user cofunction reads characters from port X until a
NULLterminator, linefeed, or carriage return character is read,maxcharacters are read, or untiltmoutmilliseconds transpires between characters read. A timeout will never occur if no characters have been received. This function is non-reentrant.It yields to other tasks for as long as the input buffer is locked or whenever the buffer becomes empty as characters are read.
swill always beNULLterminated upon return.Starting with Dynamic C version 7.25, the functions
cof_serEgets()andcof_serFgets()may be used with the Rabbit 3000 microprocessor.Parameters
sCharacter array into which a
NULLterminated string is read.maxThe maximum number of characters to read into s.
tmoutMillisecond wait period to allow between characters before timing out.
Return value
1if CR ormaxbytes read intos.0if function times out before reading CR ormaxbytes.Library
RS232.LIBExample
cof_serXputc
void cof_serXputc(int c); /* where X = A|B|C|D */Description
This single-user cofunction writes a character to serial port X, yielding to other tasks when the input buffer is locked. This function is non-reentrant.
Starting with Dynamic C version 7.25, the functions
cof_serEputc()andcof_serFputc()may be used with the Rabbit 3000 microprocessor.Parameters
cLibrary
RS232.LIBExample
// echoes characters
main() {
int c;
serAopen(19200);
loopinit();
while (1) {
loophead();
wfd c = cof_serAgetc();
wfd cof_serAputc(c);
}
serAclose();
}
cof_serXputs
void cof_serXputs(char *str); /* where X = A|B|C|D */Description
This single-user cofunction writes a
NULLterminated string to port X. It yields to other tasks for as long as the input buffer may be locked or whenever the buffer may become full as characters are written. This function is non-reentrant.Starting with Dynamic C version 7.25, the functions
cof_serEputs()andcof_serFputs()may be used with the Rabbit 3000 microprocessor.Parameters
str
NULL-terminated character string to write.Library
RS232.LIBExample
cof_serXread
int cof_serXread(void* data, int length, unsigned long tmout); /* where X = A|B|C|D */Description
This single-user cofunction reads
lengthcharacters from port X or untiltmoutmilliseconds transpires between characters read. It yields to other tasks for as long as the input buffer is locked or whenever the buffer becomes empty as characters are read. A timeout will never occur if no characters have been read. This function is non-reentrant.Starting with Dynamic C version 7.25, the functions
cof_serEread()andcof_serFread()may be used with the Rabbit 3000 microprocessor.Parameters
dataData structure into which characters are read.
lengthThe number of characters to read into
data.tmoutMillisecond wait period to allow between characters before timing out.
Return value
Number of characters read into
data.Library
RS232.LIBExample
// echoes a block of characters
main() {
int n;
char s[16];
serAopen(19200);
loopinit();
while (1) {
loophead();
costate {
wfd n = cof_serAread(s, 15, 20);
wfd cof_serAwrite(s, n);
}
}
serAclose();
}
cof_serXwrite
void cof_serXwrite(void *data, int length);
/* where X = A|B|C|D */Description
This single-user cofunction writes
lengthbytes to port X. It yields to other tasks for as long as the input buffer is locked or whenever the buffer becomes full as characters are written. This function is non-reentrant.Starting with Dynamic C version 7.25, the functions
cof_serEwrite()andcof_serFwrite()may be used with the Rabbit 3000 microprocessor.Parameters
datalengthNumber of bytes in
datato write.Library
RS232.LIBExample
// writes a block of characters, repeatedly
main() {
const char s[] = "Hello Z-World";
serAopen(19200);
loopinit();
while (1) {
loophead();
costate {
wfd cof_serAwrite(s, strlen(s));
}
}
serAclose();
}
CoPause
void CoPause(CoData *p);Description
Pause execution of a costatement so that it will not run the next time it is encountered unless and until
CoResume(p)orCoBegin(p)are called.Parameters
pLibrary
COSTATE.LIB
CoReset
void CoReset(CoData *p);Description
Initializes a costatement structure so the costatement will not be executed next time it is encountered (unless the costatement is declared to be
always_on).Parameters
pLibrary
COSTATE.LIB
CoResume
void CoResume(CoData *p);Description
Resume execution of a costatement that has been paused.
Parameters
pLibrary
COSTATE.LIB
cos
float cos(float x);Description
Computes the cosine of real float value
x(radians).Parameters
xReturn value
Library
MATH.LIBSee also
acos, cosh, sin, tan
cosh
float cosh(float x);Description
Computes the hyperbolic cosine of real FLOAT value
x.Parameters
xReturn value
Hyperbolic cosine
If |x| > 89.8 (approx.), the function returns INF and signals a range error.Library
MATH.LIBSee also
cos, acos, sin, sinh, tan, tanh
defineErrorHandler
void defineErrorHandler(void *errfcn)Description
Sets the BIOS function pointer for runtime errors to the function pointed to by
errfcn. This user-defined function must be in root memory. Specifyrootat the start of the function definition to ensure this. When a runtime error occurs, the following information is passed to the error handler on the stack:
SP+0 Return address for exceptionRetSP+2 Error code SP+4 0x0000 (can be used for additional information) SP+6 XPC when exception()was called (upper byte)SP+8 Address where exception()was calledParameters
errfcnPointer to user-defined run-time error handler.
Library
SYS.LIB
deg
float deg(float x);Description
Changes
floatradiansxto degreesParameters
xReturn value
Library
MATH.LIBSee also
rad
DelayMs
int DelayMs(long delayms);Description
Millisecond time mechanism for the costatement "waitfor" constructs. The initial call to this function starts the timing. The function returns zero and continues to return zero until the number of milliseconds specified has passed.
Parameters
delaymsThe number of milliseconds to wait.
Return value
1: The specified number of milliseconds have elapsed0: The specified number of milliseconds have not elapsed.Library
COSTATE.LIB
DelaySec
int DelaySec(long delaysec);Description
Second time mechanism for the costatement "waitfor" constructs. The initial call to this function starts the timing. The function returns zero and continues to return zero until the number of seconds specified has passed.
Parameters
delaysecThe number of seconds to wait.
Return value
1: The specified number of seconds have elapsed.0: The specified number of seconds have not elapsed.Library
COSTATE.LIB
DelayTicks
int DelayTicks(unsigned ticks);Description
Tick time mechanism for the costatement "waitfor" constructs. The initial call to this function starts the timing. The function returns zero and continues to return zero until the number of ticks specified has passed.
Parameters
ticksReturn value
1: The specified tick delay has elapsed.0: The specified tick delay has not elapsed.Library
COSTATE.LIB
Disable_HW_WDT
void Disable_HW_WDT();Description
Disables the hardware watchdog timer on the Rabbit processor. Note that the watchdog will be enabled again just by hitting it. The watchdog is hit by the periodic interrupt, which is on by default. This function is useful for special situations such as low power "sleepy mode."
Library
SYS.LIB
errlogGetHeaderInfo
root char* errlogGetHeaderInfo();Description
Reads the error log header and formats the output.
When running stand alone (not talking to Dynamic C), this function reads the header directly from the log buffer. When in debug mode, this function reads the header from the copy in flash.
When a Dynamic C cold boot takes place, the header in RAM is zeroed out to initialize it, but first its contents are copied to an address in the BIOS code before the BIOS in RAM is copied to flash. This means that on the second cold boot, the data structure in flash will be zeroed out. The configuration of the log buffer may still be read, and the log buffer entries are not affected.
Because the exception mechanism resets the processor by causing a watchdog time-out, the number of watchdog time-outs reported by this functions is the number of actual WDTOs plus the number of exceptions.
Return value
A
NULL-terminated string containing the header information:Status Byte: 0
#Exceptions: 5
Index last exception: 5
#SW Resets: 2
#HW Resets: 2
#WD Timeouts: 5The string will contain "Header checksum invalid" if a checksum error occurs. The meaning of the status byte is as follows:
bit 0 - An error has occurred since deployment
bit 1 - The count of SW resets has rolled over.
bit 2 - The count of HW resets has rolled over.
bit 3 - The count of WDTOs has rolled over.
bit 4 - The count of exceptions has rolled over.
bit 5-7 - Not usedThe index of the last exception is the index from the start of the error log entries. If this index does not equal the total exception count minus one, the error log entries have wrapped around the log buffer.
Library
ERRORS.LIB
errlogGetNthEntry
root int errlogGetNthEntry(int N);Description
Loads
errLogEntrystructure with Nth entry of the error buffer. This must be called before the functions below that format the output.Parameters
NIndex of entry to load into errLogEntry
Return value
0: Success, entry checksum OK.
-1: Failure, entry checksum not OK.
Library
ERRORS.LIB
errlogFormatEntry
root char* errlogFormatEntry();Description
Returns a
NULL-terminated string containing the basic information contained in errLogEntry:Error type=240
Address = 00:16aa
Time: 06/11/2001 20:49:29Return value
The
NULL-terminated string described above.Library
ERRORS.LIB
errlogFormatRegDump
root char* errlogFormatRegDump();Description
Returns a
NULL-terminated string containing a register dump using the data in errLogEntry:AF=0000,AF'=0000
HL=00f0,HL'=15e3
BC=16ce,BC'=1600
DE=0000,DE'=1731
IX=d3f1,IY =0560
SP=d3eb,XPC=0000Return value
The
NULL-terminated string described above.Library
ERRORS.LIB
errlogFormatStackDump
root char* errlogFormatStackDump();Description
Returns a
NULL-terminated string containing a stack dump using the data inerrLogEntry.Stack Dump:
0024,04f1,
d378,c146,
c400,a108,
2404,0000,Return value
The
NULL-terminated string describe above.Library
ERRORS.LIB
errlogGetMessage
root char* errlogGetMessage();Description
Returns a
NULL-terminated string containing the 8 byte message inerrLogEntry.Return value
Library
ERRORS.LIB
errlogReadHeader
root int errlogReadHeader();Description
Reads error log header into the structure errlogInfo.
Return value
0: Success, entry checksum OK.-1: Failure, entry checksum not OK.Library
ERRORS.LIB
exception
int exception(int errCode);Description
This function is called by Rabbit libraries when a runtime error occurs. It puts information relevant to the runtime error on the stack and calls the default runtime error handler pointed to by the
ERROR_EXITmacro. To define your own error handler, see thedefineErrorHandler()function.When the error handler is called, the following information will be on the stack:
Return value
Runtime error code passed to it.
Library
ERRORS.LIBSee also
exit
void exit(int exitcode);Description
Stops the program and returns
exitcodeto Dynamic C. Dynamic C uses values above 128 for run-time errors. When not debugging,exitwill run an infinite loop, causing a watchdog timeout if the watchdog is enabled.Parameters
exitcodeError code passed by Dynamic C
Library
SYS.LIB
exp
float exp(float x);Description
Computes the exponential of real
floatvaluex.Parameters
xReturn value
If
x> 89.8 (approx.), the function returns INF and signals a range error. Ifx< -89.8 (approx.), the function returns 0 and signals a range error.Library
MATH.LIBSee also
log, log10, frexp, ldexp, pow, pow10, sqrt
fabs
float fabs(float x);Description
Computes the float absolute value of
float x.Parameters
xReturn value
Library
MATH.LIBSee also
abs
fclose
void fclose(File* f);Description
Parameters
fThe pointer to the file to close.
Library
FILESYSTEM.LIB
fcreate (FS1)
int fcreate(File* f, FileNumber fnum);Description
Creates a file. Before calling this function, a variable of type
Filemust be defined in the application program.Parameters
fThe pointer to the created file.
fnumThis is a user-defined number in the range of 1 to127 inclusive. Each file in the flash file system is assigned a unique number in this range.
Return value
Library
FILESYSTEM.LIB
fcreate (FS2)
int fcreate(File* f, FileNumber name);Description
Create a new file with the given "file name" which is composed of two parts: the low byte is the actual file number (1 to 255 inclusive), and the high byte contains an extent number (1 to
_fs.num_lx) on which to place the file metadata. The extent specified byfs_set_lx()is always used to determine the actual data extent. If the high byte contains 0, then the default metadata extent specified byfs_set_lx()is used. The file descriptor is filled in if successful. The file will be opened for writing, so a further call tofopen_wr()is not necessary.The number of files which may be created is limited by the lower of
FS_MAX_FILESand 255. This limit applies to the entire filesystem (all logical extents).Once a file is created, its data and metadata extent numbers are fixed for the life of the file, i.e. until is is deleted.
When created, no space is allocated in the file system until the first write occurs for the file. Thus, if the system power is cycled after creation but before the first byte is written, the file will be effectively deleted. The first write to a file causes one sector to be allocated for the metadata.
Before calling this function, a variable of type
Filemust be defined in the application program. (Thesizeof()function will return the number of bytes used for theFiledata structure.)Parameters
fPointer to the file descriptor to fill in.
nameFile number including optional metadata extent number.
Return value
ERRNO values
EINVAL- Zero file number requested, or invalid extent number.EEXIST- File with given number already exists.ENFILE- No space is available in the "existing fileable". If this error occurs, increase the definition ofFS_MAX_FILES, which is a#defineconstant which should be declared before#use "fs2.lib".Library
fs2.LIBSee also
fcreate_unused (FS2), fs_set_lx (FS2), fdelete (FS2)
fcreate_unused (FS1)
FileNumber fcreate_unused(File* f);Description
Searches for the first unused file number in the range 1 through 127, and creates a file with that number.
Parameters
fThe pointer to the created file.
Return value
The
FileNumber(1-127) of the new file if success.Library
FILESYSTEM.LIBSee also
fcreate (FS1)
fcreate_unused (FS2)
FileNumber fcreate_unused(File* f);Description
Create a new file and return the "file name" which is a number between 1 and 255. The new file will be created on the current default extent(s) as specified by
fs_set_lx(). Other behavior is the same asfcreate().Parameters
fPointer to file descriptor to fill in.
Return value
>0: Success, theFileNumber(1-255) of the new file.0: Failure.ERRNO value
ENFILE- No unused file number available.Library
fs2.LIBSee also
fcreate (FS2), fs_set_lx (FS2), fdelete (FS2)
fdelete (FS1)
int fdelete(FileNumber fnum);Description
Parameters
fnumA number in the range 1 to 127 inclusive that identifies the file in the flash file system.
Return value
Library
FILESYSTEM.LIB
fdelete (FS2)
int fdelete(FileNumber name);Description
Delete the file with the given number. The specified file must not be open. The file number (i.e. name) is composed of two parts: the low byte contains the actual file number, and the high byte (if not zero) contains the metadata extent number of the file.
Parameters
nameFile number (1 to 255 inclusive).
Return value
Library
fs2.LIBERRNO values
ENOENT- File does not exist, or metadata extent number does not match an existing file.EBUSY- File is open.EIO- I/O error when releasing blocks occupied by this file.See also
fcreate (FS2)
fflush (FS2)
int fflush(File * f);Description
Flush any buffers, associated with the given file, retained in RAM to the underlying hardware device. This ensures that the file is completely written to the filesystem. The file system does not currently perform any buffering, however future revisions of this library may introduce buffering to improve performance.
Parameters
fPointer to open file descriptor.
Return value
ERRNO values
EBADFD- file invalid or not open.EIO- I/O error.Library
fs2.LIBSee also
fftcplx
void fftcplx(int *x, int N, int *blockexp)Description
Computes the complex DFT of the
N-point complex sequence contained in the arrayxand returns the complex result in x.Nmust be a power of 2 and lie between 4 and 1024. An invalidNcauses a RANGE exception. TheN-point complex sequence in arrayxis replaced with itsN-point complex spectrum. The value ofblockexpis increased by 1 each time arrayxhas to be scaled, to avoid arithmetic overflow.Parameters
xPointer to
N-element array of complex fractions.NNumber of complex elements in array
x.blockexpPointer to integer block exponent.
Library
FFT.LIBSee also
fftcplxinv, fftreal, fftrealinv, hanncplx, hannreal, powerspectrum
fftcplxinv
void fftcplxinv(int *x, int N, int *blockexp)Description
Computes the inverse complex DFT of the
N-point complex spectrum contained in the arrayxand returns the complex result inx.Nmust be a power of 2 and lie between 4 and 1024. An invalidNcauses a RANGE exception. The value ofblockexpis increased by 1 each time arrayxhas to be scaled, to avoid arithmetic overflow. The value ofblockexpis also decreased by log2Nto include the 1/Nfactor in the definition of the inverse DFTParameters
xPointer to
N-element array of complex fractions.NNumber of complex elements in array
x.blockexpPointer to integer block exponent.
Library
FFT.LIBSee also
fftcplx, fftreal, fftrealinv, hanncplx, hannreal, powerspectrum
fftreal
void fftreal(int *x, int N, int *blockexp)Description
Computes the
N-point, positive-frequency complex spectrum of the 2N-point real sequence in arrayx. The 2N-point real sequence in arrayxis replaced with itsN-point positive-frequency complex spectrum. The value ofblockexpis increased by 1 each time arrayxhas to be scaled, to avoid arithmetic overflow.The imaginary part of the X[0] term (stored in x[1]) is set to the real part of the fmax term.
The 2
N-point real sequence is stored in natural order. The zeroth element of the sequence is stored inx[0], the first element inx[1], and the kth element in x[k].
Nmust be a power of 2 and lie between 4 and 1024. An invalidNcauses a RANGE exception.Parameters
xPointer to 2
N-point sequence of real fractions.NNumber of complex elements in output spectrum
blockexpPointer to integer block exponent.
Library
FFT.LIBSee also
fftcplx, fftcplxinv, fftrealinv, hanncplx, hannreal, powerspectrum
fftrealinv
void fftrealinv(int *x, int N, int *blockexp)Description
Computes the 2
N-point real sequence corresponding to theN-point, positive-frequency complex spectrum in array x. TheN-point, positive-frequency spectrum contained in arrayxis replaced with its corresponding 2N-point real sequence. The value ofblockexpis increased by 1 each time arrayxhas to be scaled, to avoid arithmetic overflow. The value ofblockexpis also decreased by log2Nto include the 1/Nfactor in the definition of the inverse DFT.The function expects to find the real part of the fmax term in the imaginary part of the zero-frequency
X[0]term (storedx[1]).The 2
N-point real sequence is stored in natural order. The zeroth element of the sequence is stored inx[0], the first element inx[1], and the kth element inx[k].
Nmust be a power of 2 and lie between 4 and 1024. An invalidNcauses a RANGE exception.Parameters
xPointer to
N-element array of complex fractions.NNumber of complex elements in array
x.blockexpPointer to integer block exponent.
Library
FFT.LIBSee also
fftcplx, fftcplxinv, fftreal, hanncplx, hannreal, powerspectrum
flash_erasechip
void flash_erasechip(FlashDescriptor* fd);Description
Erases an entire Flash Memory chip.
NOTE:
fdmust have already been initialized withflash_initbefore calling this function. Seeflash_initdescription for further restrictions.Parameters
fdPointer to flash descriptor of the chip to erase.
Library
FLASH.LIBSee also
flash_erasesector, flash_gettype, flash_init, flash_read, flash_readsector, flash_sector2xwindow, flash_writesector
flash_erasesector
int flash_erasesector(FlashDescriptor* fd, word which);Description
Erases a sector of a Flash Memory chip.
NOTE:
fdmust have already been initialized withflash_initbefore calling this function. Seeflash_initdescription for further restrictions.Parameters
fdPointer to flash descriptor of the chip to erase a sector of.
whichReturn value
Library
FLASH.LIBSee also
flash_erasechip, flash_gettype, flash_init, flash_read, flash_readsector, flash_sector2xwindow, flash_writesector
flash_gettype
int flash_gettype(FlashDescriptor* fd);Description
Returns the 16-bit Flash Memory type of the Flash Memory.
NOTE:
fdmust have already been initialized withflash_initbefore calling this function. Seeflash_initdescription for further restrictions.Parameters
fdThe
FlashDescriptorof the memory to query.Return value
The integer representing the type of the Flash Memory.
Library
FLASH.LIBSee also
flash_erasechip, flash_erasesector, flash_init, flash_read, flash_readsector, flash_sector2xwindow, flash_writesector
flash_init
int flash_init(FlashDescriptor* fd, int mb3cr);Description
Initializes an internal data structure of type
FlashDescriptorwith information about the Flash Memory chip. The Memory Interface Unit bank register (MB3CR) will be assigned the value ofmb3crwhenever a function accesses the Flash Memory referenced byfd. See the Rabbit 2000 Users Manual for the correct chip select and wait state settings.NOTE: Improper use of this function can cause your program to be overwritten or operate incorrectly. This and the other Flash Memory access functions should not be used on the same Flash Memory that your program resides on, nor should they be used on the same region of a second Flash Memory where a file system resides.
Use
WriteFlash()to write to the primary Flash Memory.Parameters
fdThis is a pointer to an internal data structure that holds information about a Flash Memory chip.
mb3crThis is the value to set MB3CR to whenever the Flash Memory is accessed. 0xc2 (i.e., CS2, /OE0, /WE0, 0 WS) is a typical setting for the second Flash Memory on the TCP/IP Dev Kit, the Intellicom, the Advanced Ethernet Core, and the RabbitLink.
Return value
0: Success.1: Invalid Flash Memory type.-1: Attempt made to initialize primary Flash Memory.Library
FLASH.LIBSee also
flash_erasechip, flash_erasesector, flash_gettype, flash_read, flash_readsector, flash_sector2xwindow, flash_writesector
flash_read
int flash_read(FlashDescriptor* fd, word sector, word offset, unsigned long buffer, word length);Description
Reads data from the Flash Memory and stores it in
buffer.NOTE:
fdmust have already been initialized withflash_initbefore calling this function. See theflash_initdescription for further restrictions.Parameters
fdThe
FlashDescriptorof the Flash Memory to read from.sectorThe sector of the Flash Memory to read from.
offsetThe displacement, in bytes, from the beginning of the sector to start reading at.
bufferThe physical address of the destination buffer. TIP: A logical address can be changed to a physical with the function
paddr.lengthReturn value
Library
FLASH.LIBSee also
flash_erasechip, flash_erasesector, flash_gettype, flash_init, flash_readsector, flash_sector2xwindow, flash_writesector, paddr
flash_readsector
int flash_readsector(FlashDescriptor* fd, word sector, unsigned long buffer);Description
Reads the contents of an entire sector of Flash Memory into a buffer.
NOTE:
fdmust have already been initialized withflash_initbefore calling this function. Seeflash_initdescription for further restrictions.Parameters
fdThe
FlashDescriptorof the Flash Memory to read from.sectorbufferThe physical address of the destination buffer. TIP: A logical address can be changed to a physical with the function
paddr.Return value
Library
FLASH.LIBSee also
flash_erasechip, flash_erasesector, flash_gettype, flash_init, flash_read, flash_sector2xwindow, flash_writesector
flash_sector2xwindow
void* flash_sector2xwindow(FlashDescriptor* fd, word sector);Description
This function sets the MB3CR and XPC value so the requested sector falls within the XPC window. The MB3CR is the Memory Interface Unit bank register. XPC is one of four Memory Management Unit registers. See
flash_initdescription for restrictions.Parameters
fdThe
FlashDescriptorof the Flash Memory.sectorThe sector to set the XPC window to.
Return value
The logical offset of the sector.
Library
FLASH.LIBSee also
flash_erasechip, flash_erasesector, flash_gettype, flash_init, flash_read, flash_readsector, flash_writesector
flash_writesector
int flash_writesector(FlashDescriptor* fd, word sector, unsigned long buffer);Description
Writes the contents of
buffertosectoron the Flash Memory referenced byfd. NOTE:fdmust have already been initialized withflash_initbefore calling this function. Seeflash_initdescription for further restrictions.Parameters
fdThe
FlashDescriptorof the Flash Memory to write to.sectorbufferThe physical address of the source. TIP: A logical address can be changed to a physical address with the function
paddrReturn value
Library
FLASH.LIBSee also
flash_erasechip, flash_erasesector, flash_gettype, flash_init, flash_read, flash_readsector, flash_sector2xwindow
floor
float floor(float x);Description
Computes the largest integer less than or equal to the given number.
Parameters
xReturn value
Library
MATH.LIBSee also
ceil, fmod
fmod
float fmod(float x, float y);Description
Parameters
xyReturn value
Returns the remainder of x/y. The remaining part of
xafter all multiples ofyhave been removed. For example, ifxis 22.7 andyis 10.3, the integral division result is 2. Then the remainder is: 22.7 - 2 × 10.3 = 2.1.Library
MATH.LIBSee also
ceil, floor
fopen_rd (FS1)
int fopen_rd(File* f, FileNumber fnum);Description
Parameters
fA pointer to the file to read.
fnumA number in the range 1 to 127 inclusive that identifies the file in the flash file system.
Return value
Library
FILESYSTEM.LIB
fopen_rd (FS2)
int fopen_rd(File* f, FileNumber name);Description
Open file for reading only. See
fopen_wr()for a more detailed description.Parameters
fPointer to file descriptor (uninitialized).
nameFile number (1 to 255 inclusive).
Return value
ERRNO values
ENOENT- File does not exist, or metadata extent number does not match an existing file.Library
fs2.libSee also
fclose, fopen_wr (FS2)
fopen_wr (FS1)
int fopen_wr(File* f, FileNumber fnum);Description
Parameters
fA pointer to the file to write.
fnumA number in the range 1 to 127 inclusive that identifies the file in the flash file system.
Return value
Library
FILESYSTEM.LIB
fopen_wr (FS2)
int fopen_wr(File* f, FileNumber name);Description
Open file for read or write. The given file number is composed of two parts: the low byte contains the file number (1 to 255 inclusive) and the high byte, if not zero, contains the metadata extent number. If the extent number is zero, it defaults to the correct metadata extent - this is for the purpose of validating an expected extent number. Most applications should just pass the file number with zero high byte.
A file may be opened multiple times, with a different file descriptor pointer for each call, which allows the file to be read or written at more than one position at a time. A reference count for the actual file is maintained, so that the file can only be deleted when all file descriptors referring to this file are closed.
fopen_wr()orfopen_rd()must be called before any other function from this library is called that requires aFilepointer. The "current position" is set to zero i.e. the start of the file.When a file is created, it is automatically opened for writing thus a subsequent call to
fopen_wr()is redundant.Parameters
fPointer to file descriptor (uninitialized).
nameFile number (1 to 255 inclusive).
Return value
ERRNO values
ENOENT- File does not exist, or metadata extent number does not match an existing file.Library
fs2.libSee also
fclose, fopen_rd (FS2)
forceSoftReset
void forceSoftReset();Description
Forces the board into a software reset by jumping to the start of the BIOS.
Library
SYS.LIB
fread (FS1)
int fread(File* f, char* buf, int len);Description
Reads
lenbytes from a file pointed to byf, starting at the current offset into the file, into buffer. Data is read into buffer pointed to bybuf.Parameters
fA pointer to the file to read from
bufA pointer to the destination buffer.
lenReturn value
Library
FILESYSTEM.LIB
fread (FS2)
int fread(File* f, void* buf, int len);Description
Read data from the "current position" of the given file. When the file is opened, the current position is 0, i.e. at the start of file. Subsequent reads or writes advance the position by the number of bytes read/written
fseek()can also be used to position the read point.If the application permits, it is much more efficient to read multiple data bytes rather than reading one-by-one.
Parameters
fPointer to file descriptor (initialized by
fopen_rd(),fopen_wr()orfcreate()).bufData buffer located in root data memory or stack. This must be dimensioned with at least len bytes.
lenLength of data to read (0 to 32767 inclusive).
Return value
<len: Partial success. Returns amount successfully read.errnogives further details (probably 0 meaning that end-of-file was encountered).Library
fs2.LIBERRNO values
EBADFD- File descriptor not opened.EINVAL-lenless than zero.0- Success, butlenwas zero or EOF was reached prior to readinglenbytes.EIO- I/O error.See also
fseek (FS2), fwrite (FS2)
frexp
float frexp(float x, int *n);Description
Splits
xinto a fraction and exponent, f*(2**n)Parameters
xnReturn value
The function returns the exponent in the integer
*nand the fraction between 0.5, inclusive and 1.0.Library
MATH.LIBSee also
exp, ldexp
fs_format (FS1)
int fs_format(long reserveblocks, int num_blocks, unsigned long wearlevel);Description
Initializes the internal data structures and file system. All blocks in the file system are erased.
Parameters
reserveblocksStarting address of the flash file system. When
FS_FLASHis defined this value should be 0 or a multiple of the block size. WhenFS_RAMis defined this parameter is ignored.num_blocksThe number of blocks to allocate for the file system. With a default block size of 4096 bytes and a 256K Flash Memory, this value might be 64.
wearlevelThis value should be 1 on a new Flash Memory, and some higher value on an unformatted used Flash Memory. If you are reformatting a Flash Memory you can set
wearlevelto 0 to keep the old wear leveling.Return value
Library
FILESYSTEM.LIBExample
This program can be found in
samples/filesystem/format.c.
fs_format (FS2)
int fs_format(long reserveblocks, int num_blocks, unsigned wearlevel)Description
Format all extents of the file system. This must be called after calling
fs_init(). Only extents that are not defined as reserved are formatted. All files are deleted.Parameters
reserveblocksMust be zero. Retained for backward compatibility.
num_blocksIgnored (backward compatibility).
wearlevelInitial wearlevel value. This should be 1 if you have a new flash, and some larger number if the flash is used. If you are reformatting a flash, you can use 0 to use the old flash wear levels.
Return value
ERRNO values
EINVAL- thereserveblocksparameter was non-zero.EBUSY- one or more files were open.EIO- I/O error during format. If this occurs, retry the format operation If it fails again, there is probably a hardware error.See also
fs_init (FS2), lx_format
fs_init (FS1)
int fs_init(long reserveblocks, int num_blocks);Description
Initialize the internal data structures for an existing file system. Blocks that are used by a file are preserved and checked for data integrity.
Parameters
reserveblocksStarting address of the flash file system. When
FS_FLASHis defined this value should be 0 or a multiple of the block size. WhenFS_RAMis defined this parameter is ignored.num_blocksThe number of blocks that the file system contains. By default the block size is 4096 bytes.
Return Value
Library
FILESYSTEM.LIB
fs_init (FS2)
int fs_init(long reserveblocks, int num_blocks);Description
Initialize the filesystem. The static structure
_fscontains information that defines the number and parameters associated with each extent or "partition". This function must be called before any of the other functions in this library, except forfs_setup(),fs_get_*_lx()andfs_get_lx_size().Pre-main initialization will create up to 3 devices:
The LX numbers of the default devices can be obtained using the
fs_get_flash_lx(),fs_get_ram_lx()andfs_get_other_lx()calls.If none of these devices can be set up successfully,
fs_init()will returnENOSPCwhen called.This function performs complete consistency checks and, if necessary, fixups for each LX. It may take up to several seconds to run. It should only be called once at application initialization time.
Parameters
reserveblocksMust be zero. Retained for backward compatibility.
num_blocksIgnored (backward compatibility).
Return value
ERRNO values
EINVAL- the reserveblocks parameter was non-zero.EIO- I/O error. This indicates a hardware problem.ENOMEM- Insufficient memory for required buffers.ENOSPC- No valid extents obtained e.g. there is no recognized flash or RAM memory device available.Library
fs2.libSee also
fs_setup (FS2), fs_get_flash_lx (FS2)
fs_reserve_blocks (FS1)
int fs_reserve_blocks(int blocks);Description
Sets up a number of blocks that are guaranteed to be available for privileged files. A privileged file has an identifying number in the range 128 through 143. This function is not needed in most cases. If it is used, it should be called immediately after
fs_initorfs_format.Parameters
blocksReturn Value
Library
FILESYSTEM.LIB
fsck (FS1)
int fsck(int flash);Description
Check the filesystem for errors
Parameters
flashA bitmask indicating which checks to NOT perform. The following checks are available:
FSCK_HEADERS- Block headers.FSCK_CHECKSUMS- Data checksums.FSCK_VERSION- Block versions, from a failed write.Return Value
0: Success.!0: Failure, this is a bitmask indicating which checks failed.Library
FILESYSTEM.LIB
fseek (FS1)
int fseek(File* f, long to, char whence);Description
Places the read pointer at a desired location in the file.
Parameters
fA pointer to the file to seek into.
toThe number of bytes to move the read pointer. This can be a positive or negative number.
whenceThe location in the file to offset from. This is one of the following constants.
SEEK_SET- Seek from the beginning of the file.SEEK_CUR- Seek from the current read position in the file.SEEK_END- Seek from the end of the file.Example
To seek to 10 bytes from the end of the file
f, usefseek(f, -10, SEEK_END);. To rewind the filefby 5 bytes, usefseek(f, -5, SEEK_CUR);.Return value
Library
FILESYSTEM.LIB
fseek (FS2)
int fseek(File * f, long where, char whence);Description
Set the current read/write position of the file. Bytes in a file are sequentially numbered starting at zero. If the current position is zero, then the first byte of the file will be read or written. If the position equals the file length, then no data can be read, but any write will append data to the file.
fseek()allows the position to be set relative to the start or end of the file, or relative to its current position.In the special case of
SEEK_RAW, an unspecified number of bytes beyond the "known" end-of-file may be readable. The actual amount depends on the amount of space left in the last internal block of the file. This mode only applies to reading, and is provided for the purpose of data recovery in the case that the application knows more about the file structure than the filesystem.Parameters
fPointer to file descriptor (initialized by
fopen_rd(),fopen_wr()orfcreate()).wherewhence
SEEK_SET: 'where' (non-negative only) is relative to start of file.SEEK_CUR: 'where' (positive or negative) is relative to the current position.SEEK_END: 'where' (non-positive only) is relative to the end of the file.SEEK_RAW: Similar toSEEK_END, except the file descriptor is set in a special mode which allows reading beyond the end of the file.Return value
!0: The computed position was outside of the current file contents, and has been adjusted to the nearest valid position.ERRNO values
Library
fs2.libSee also
ftell (FS2), fread (FS2), fwrite (FS2)
fs_get_flash_lx (FS2)
FSLXnum fs_get_flash_lx(void);Description
Returns the logical extent number of the preferred flash device. This is the second flash if one is available on your hardware, otherwise it is the reserved area in your program flash. In order for the program flash to be available for use by the file system, you must define two constants: the first constant is
XMEM_RESERVE_SIZEnear the top ofBIOS\RABBITBIOS.C. This value is set to the amount of program flash to reserve (in bytes). This is required by the BIOS. The second constant is set in your code before#use "fs2.lib".FS2_USE_PROGRAM_FLASHmust be defined to the number of KB (1024 bytes) that will actually be used by the file system. If this is set to a larger value than the actual amount of reserved space, then only the actual amount will be used.The sample program
SAMPLES\FILESYSTEM\FS2INFO.Cdemonstrates use of this function.This function may be called before calling
fs_init().Return value
0: There is no flash file system available.!0: Logical extent number of the preferred flash.Library
FS2.libSee also
fs_get_ram_lx (FS2), fs_get_other_lx (FS2)
fs_get_lx (FS2)
FSLXnum fs_get_lx(int meta);Description
Return the current extent (LX) number for file creation. Each file has two parts: the main bulk of data, and the metadata which is a relatively small, fixed, amount of data used to journal changes to the file. Both data and metadata can reside on the same extent, or they may be separated.
Parameters
meta
1: return logical extent number for metadata.0: return logical extent number for data.Return value
Library
FS2.libSee also
fcreate (FS2), fs_set_lx (FS2)
fs_get_lx_size (FS2)
long fs_get_lx_size(FSLXnum lxn, int all, word ls_shift);Description
Returns the size of the specified logical extent, in bytes. This information is useful when initially partitioning an LX, or when estimating the capacity of an LX for user data.
allis a flag which indicates whether to return the total data capacity (as if all current files were deleted) or whether to return just the available data capacity. The return value accounts for the packing efficiency which will be less than 100% because of the bookkeeping overhead. It does not account for the free space required when any updates are performed; however this free space may be shared by all files on the LX. It also does not account for the space required for file metadata. You can account for this by adding one logical sector for each file to be created on this LX. You can also specify that the metadata be stored on a different LX by use offs_set_lx().This function may be called either before or after
fs_init(). If called before, then thels_shiftparameter must be set to the value to be used infs_setup(), since the LS size is not known at this point.ls_shiftcan also be passed as zero, in which case the default size will be assumed.allmust be non-zero if called beforefs_init(), since the number of files in use is not yet known.Parameters
lxnLogical extent number to query.
allBoolean: 0 for current free capacity only, 1 for total.
Must use 1 if calling beforefs_init().ls_shiftLogical sector shift i.e. log base 2 of LS size (6 to 13); may be zero to use default.
Return value
0: The specified LX does not exist.!0: Capacity of the LX in bytes.Library
FS2.lib
fs_get_other_lx (FS2)
FSLXnum fs_get_other_lx(void);Description
Returns the logical extent number of the non-preferred flash device. If it exists, this is usually the program flash. See the description under
fs_get_flash_lx()for details about setting up the program flash for use by the filesystem.The sample program
SAMPLES\FILESYSTEM\FS2INFO.Cdemonstrates use of this function.This function may be called before calling
fs_init().Return value
0: There is no other flash filesystem available.!0: Logical extent number of the non-preferred flash.Library
FS2.LIBSee also
fs_get_ram_lx (FS2), fs_get_flash_lx (FS2)
fs_get_ram_lx (FS2)
FSLXnum fs_get_ram_lx(void);Description
Return the logical extent number of the RAM file system device. This is only available if you have defined
FS2_RAM_RESERVEto a non-zero number of bytes in the BIOS.A RAM filesystem is only really useful if you have battery-backed SRAM on the board. You can still use a RAM file system on volatile RAM, but of course files will not persist over power cycles and you should explicitly format the RAM filesystem at power-up.
The sample program
SAMPLES\FILESYSTEM\FS2INFO.Cdemonstrates use of this function.This function may be called before calling
fs_init().Return value
0: There is no RAM filesystem available.!0: Logical extent number of the RAM device.Library
FS2.LIBSee also
fs_get_flash_lx (FS2), fs_get_other_lx (FS2)
fs_set_lx (FS2)
int fs_set_lx(FSLXnum meta, FSLXnum data);Description
Sets the default logical extent (LX) numbers for file creation. Each file has two parts: the main bulk of data, and the metadata which is a relatively small, fixed amount of data used to journal changes to the file. Both data and metadata can reside on the same extent, or they may be separated. The metadata, no matter where it is located, consumes one sector.
The file creation functions allow the metadata extent to be explicitly specified (in the high byte of the file number), however it is usually easier to call
fs_set_lx()to set appropriate defaults. Callingfs_set_lx()is the only way to specify the data extent.If
fs_set_lx()is never called, both data and metadata will default to the first non-reserved extent number.Parameters
metadataReturn value
0: Success.!0: Error, e.g. non-existent LX number.ERRNO values
ENODEV- no such extent number, or extent is reserved.Library
FS2.LIBSee also
fcreate (FS2)
fs_setup (FS2)
FSLXnum fs_setup(FSLXnum lxn, word ls_shift, int reserve_it, void * rfu, int partition_it, word part, word part_ls_shift, int part_reserve, void * part_rfu);Description
To modify or add to the default extents, this function must be called before calling
fs_init(). If called afterfs_init(), the filesystem will be corrupted.
fs_setup()runs in one of two basic modes, determined by thepartition_itparameter. Ifpartition_itis non-zero, then the specified extent (lxn, which must exist), is split into two extents according to the given proportions. Ifpartition_itis zero, then the specified extent must not exist; it is created. This use is beyond the scope of this note, since it involves filesystem internals. The paritioning usage is described here.
partition_itmay beFS_MODIFY_EXTENTin which case the base extent,lxn, is modified to use the specifiedls_shiftandreserve_itparameters (the other parameters are ignored).
partition_itmay be set toFS_PARTITION_FRACTION(other values reserved). This causes extent numberlxnto be split. The first half is still referred to as extentlxn, and the other half is assigned a new extent number, which is returned.The base extent number may itself have been previously partitioned, or it should be 1 for the 2nd flash device, or possibly 2 for the NVRAM device.
Parameters
lxnBase extent number to partition or modify.
ls_shiftNew logical sector size to assign to base partition, or zero to not alter it. This is expressed as the log base 2 of the desired size, and must be a number between 6 and 13 inclusive.
reserve_it
TRUEif base partition is to be marked reserved.rfuA pointer reserved for future use. Pass as
NULL.partition_itMust be set to
FS_PARTITION_FRACTIONorFS_MODIFY_EXTENT. The following parameters are ignored if this parameter is notFS_PARTITION_FRACTION.partThe fraction of the existing base extent to assign to the new extent. This number is expressed as a fixed-point binary number with the binary point to the left of the MSB e.g. 0x3000 assigns 3/16 of the base extent to the new partition, updating the base extent to 13/16 of its original size. The nearest whole number of physical sectors is used for each extent.
part_ls_shiftLogical sector size to assign to the new extent, or zero to use the same LS size as the base extent. Expressed in same units as parameter 2.
part_reserve
TRUEif the new extent is to be reserved.part_rfuA pointer reserved for future use. Pass as
NULL.Return value
0: Failure, extent could not be partitioned.!0: Success, number of the new extent, or same aslxdfor existing extent modification.ERRNO values
ENOSPC- one or other half would contain an unusably small number of logical sectors, or the extent table is full. In the latter case,#define FS_MAX_LXto a larger value.
EINVAL-partition_itset to an invalid value, or other parameter invalid.
ENODEV- specified base extent number not defined.Library
FS2.LIBSee also
fs_init (FS2)
fs_sync (FS2)
int fs_sync(void);Description
Flush any buffers retained in RAM to the underlying hardware device. The file system does not currently perform any buffering, however future revisions of this library may introduce buffering to improve performance. This function is similar to
fflush(), except that the entire file system is synchronized instead of the data for just one file. Usefs_sync()in preference tofflush()if there is only one extent in the filesystem.Return value
ERRNO values
Library
FS2.LIBSee also
fflush (FS2)
ftell (FS1)
long ftell(File* f);Description
Gets the offset from the beginning of a file that the read pointer is currently at.
TIP:
ftell()can be used withfseek()to find the length of a file.
fseek(f, 0, SEEK_END);/* seek to the end of the file */FileLength = ftell(f);/* find the length of the file */Parameters
fA pointer to the file to query.
Return value
The offset in bytes of the read pointer from the beginning of the file: Success.
-1: Failure.Library
FILESYSTEM.LIB
ftell (FS2)
long ftell(File * f);Description
Return the current read/write position of the file. Bytes in a file are sequentially numbered starting at zero. If the current position is zero, then the first byte of the file will be read or written. If the position equals the file length, then no data can be read, but any write will append data to the file.
Note that no checking is done to see if the file descriptor s valid. If the File is not actually open, the return value will be random.
Parameters
fPointer to file descriptor (initialized by
fopen_rd(),fopen_wr()orfcreate()).Return value
Current read/write position (0 to length-of-file).
ERRNO values
Library
fs2.libSee also
fseek (FS2)
fshift
int fshift(File *f, int count, char *buffer);Description
Removes
countnumber of bytes from the beginning of a file and copies them to memory pointed to bybuffer.Parameters
fcount*bufferLocation to store shifted bytes. If this is
NULL, the bytes will be discarded.Return value
Number of bytes shifted out: Success.
0: Error.Library
FILESYSTEM.LIB
fwrite (FS1)
int fwrite(File* f, char* buf, int len);Description
Appends
lenbytes from the source buffer to the end of the file.Parameters
fA pointer to the file to write to.
bufA pointer to the source buffer.
lenReturn value
The number of bytes written: Success.
0: Failure.Library
FILESYSTEM.LIB
fwrite (FS2)
int fwrite(File* f, void* buf, int len);Description
Write data to file opened for writing. The data is written starting at the "current position". This is zero (start of file) when it is opened or created, but may be changed by fread, fwrite, fshift or fseek functions. After writing the data, the current position is advanced to the position just after the last byte written. Thus, sequential calls to
fwrite()will add or append data contiguously.Unlike the previous file system (
FILESYSTEM.LIB), this library allows files to be overwritten not just appended. Internally, overwrite and append are different operations with differing performance, depending on the underlying hardware. Generally, appending is more efficient especially with byte-writable flash memory. If the application allows, it is preferable to use append/shift rather than overwrite. In order to ensure that data is appended, usefseek(f, 0, SEEK_END)before callingfwrite().The same "current position" pointer is used for both read and write. If interspersing read and write, then
fseek()should be used to ensure the correct position for each operation. Alternatively, the same file can be opened twice, with one descriptor used for read and the other for write. This precludes use offshift(), since it does not tolerate shared files.Parameters
fPointer to file descriptor (initialized by
fopen_wr()orfcreate()).bufData buffer located in root data memory or stack.
lenLength of data (0 to 32767 inclusive).
Return value
len: Success.
<len: Partial success. Returns amount successfully written.errnogives more details.0: Failure, orlenwas zero.ERRNO values
EBADFD- File descriptor not opened, or is read-only.EINVAL-lenless than zero.0- Success, butlenwas zero.EIO- I/O error.ENOSPC- extent out of space.Library
fs2.LIBSee also
fread (FS2)
ftoa
int ftoa(float f, char *buf);Description
Converts a float number to a character string.
The character string only displays the mantissa up to 9 digits, no decimal points, and a minus sign if
fis negative. The function returns the exponent (of 10) that should be used to compensate for the string:ftoa(1.0,buf)yieldsbuf="100000000", and returns-8.Parameters
fbufConverted string. The string is no longer than 10 characters long.
Return value
Library
STDIO.LIBSee also
utoa, itoa
getchar
char getchar(void);Description
Busy waits for a character to be typed from the stdio window in Dynamic C. The user should make sure only one process calls this function at a time.
Return value
A character typed in the Stdio window in Dynamic C.
Library
STDIO.LIBSee also
gets, putchar
getcrc
int getcrc(char *dataarray, char count, int accum);Description
Computes the Cyclic Redundancy Check (CRC), or check sum, for
countbytes (maximum 255) of data in buffer. Calls togetcrccan be "concatenated" usingaccumto compute the CRC for a large buffer.Parameters
dataarraycountNumber of bytes. Maximum is 255.
accumReturn value
Library
MATH.LIB
gets
char *gets(char *s);Description
Waits for a string terminated by <CR> at the stdio window. The string returned is
NULL-terminated without the return. The user should make sure only one process calls this function at a time.Parameters
sThe input string is put to the location pointed to by the argument
s. The caller is responsible to make sure the location pointed to bysis big enough for the string.Return value
Same pointer passed in, but string is changed to a
NULL-terminated.Library
STDIO.LIBSee also
puts, getchar
GetVectExtern2000
unsigned GetVectExtern2000();Description
Reads the address of external interrupt table entry. This function really just returns what is present in the table. The return value is meaningless if the address of the external interrupt has not been written.
Return value
Library
SYS.LIBSee also
GetVectIntern, SetVectExtern2000, SetVectIntern
GetVectExtern3000
unsigned GetVectExtern3000(int interruptNum);Description
Function to read the address of an external interrupt table entry for the Rabbit 3000 CPU. This function really just returns whatever value is at the address:
(internal vector table base) + (vectNum*8) + 1.Parameter
interruptNumInterrupt number. Should be 0 or 1.
Return Value
See Also
SetVectExtern3000, SetVectIntern, GetVectIntern
GetVectIntern
unsigned GetVectIntern(int vectNum);Description
Reads the address of the internal interrupt table entry and returns whatever value is at the address
(internal vector table base) + (vectNum*16) + 1.Parameter
vectNumInterrupt number; should be 0-15.
Return value
Library
SYS.LIBSee also
GetVectExtern2000, SetVectExtern2000, SetVectIntern
gps_get_position
int gps_get_position(GPSPositon *newpos, char *sentence);Description
Parses a sentence to extract position data. This function is able to parse any of the following GPS sentence formats: GGA, GLL or RMC.
Parameters
newposA
GPSPositionstructure to fill.sentenceA string containing a line of GPS data. in NMEA-0183 format.
Return value
0: Success.-1: Parsing error.-2: Sentence marked invalid.Library
gps.lib
gps_get_utc
int gps_get_utc(struct tm *newtime, char *sentence);Description
Parses an RMC sentence to extract time data.
Parameters
newtime
tmstructure to fill with new UTC time.sentenceA string containing a line of GPS data in NMEA-0183 format (RMC sentence).
Return value
0: Success.-1: Parsing error.-2: Sentence marked invalid.Library
gps.lib
gps_ground_distance
float gps_ground_distance(GPSPosition *a, GPSPosition *b);Description
Calculates ground distance (in km) between to geographical points. (Uses spherical earth model.)
Parameters
abReturn value
Library
gps.lib
hanncplx
void hanncplx(int *x, int N, int *blockexp);Description
Convolves an
N-point complex spectrum with the three-point Hann kernel. The filtered spectrum replaces the original spectrum.The function produces the same results as would be obtained by multiplying the corresponding time sequence by the Hann raised-cosine window.
The zero-crossing width of the main lobe produced by the Hann window is 4 DFT bins. The adjacent sidelobes are 32 db below the main lobe. Sidelobes decay at an asymptotic rate of 18 db per octave.
Nmust be a power of 2 and lie between 4 and 1024. An invalidNcauses a RANGE exception.Parameters
xPointer to
N-element array of complex fractions.NNumber of complex elements in array
x.blockexpPointer to integer block exponent.
Library
FFT.LIBSee also
fftcplx, fftcplxinv, fftreal, fftrealinv, hanncplx, powerspectrum
hannreal
void hannreal(int *x, int N, int *blockexp);Description
Convolves an
N-point positive-frequency complex spectrum with the three-point Hann kernel. The function produces the same results as would be obtained by multiplying the corresponding time sequence by the Hann raised-cosine window.The zero-crossing width of the main lobe produced by the Hann window is 4 DFT bins. The adjacent sidelobes are 32 db below the main lobe. Sidelobes decay at an asymptotic rate of 18 db per octave.
The imaginary part of the dc term (stored in
x[1]) is considered to be the real part of the fmax term. The dc and fmax spectral components take part in the convolution along with the other spectral components. The real part of fmax component affects the real part of the X[N-1] component (and vice versa), and should not arbitrarily be set to zero unless these components are unimportant.Parameters
xPointer to
N-element array of complex fractions.NNumber of complex elements in array
x.blockexpPointer to integer block exponent.
Return value
None. The filtered spectrum replaces the original spectrum.
Library
FFT.LIBSee also
fftcplx, fftcplxinv, fftreal, fftrealinv, hanncplx, powerspectrum
HDLCdropX
int HDLCdropX(); /* Where X is E or F */Description
Drops the next received packet, freeing up its buffer. This must be used if the packet has been examined with
HDLCpeekX()and is no longer needed. A call toHDLCreveiceX()is the only other way to free up the buffer.This function is intended for use with the Rabbit 3000 microprocessor.
Return Value
1: Packet dropped.0: No received packets were available.Library
HDLC_PACKET.LIB
HDLCerrorX
int HDLCerrorX(unsigned long *bufptr, int *lenptr);
/* Where X is E or F */Description
This function returns a set of possible error flags as an integer. A received packet with errors is automatically dropped.
Masks are used to check which errors have occurred. The masks are:
HDLC_NOBUFFER- driver ran out of buffers for received packets.
HDLC_OVERRUN- a byte was overwritten and lost before the ISR could retreive it.
HDLC_OVERFLOW- a received packet was too long for the buffers.
HDLC_ABORTED- a received packet was aborted by the sender during tranmission.This function is intended for use with the Rabbit 3000 microprocessor.
Return Value
Library
HDLC_PACKET.LIB
HDLCopenX
int HDLCopenX(long baud, char encoding, unsigned long buffers, int buffer_count, int buffer_size); /* Where X is E or F */Description
Opens serial port E or F in HDLC mode. Sets up buffers to hold received packets. This function is intended for use with the Rabbit 3000 microprocessor.
Parameters
baudThe baud rate for the serial port. Due to imitations in the baud generator, non-standard baud rates will be approximated within 5% of the value requested.
encodingThe bit encoding mode to use. Macro labels for the available options are:
- ·
HDLC_NRZ
- ·
HDLC_NRZI
- ·
HDLC_MANCHESTER
- ·
HDLC_BIPHASE_SPACE
- ·
HDLC_BIPHASE_MARKSee the HDLC documentation for more detail on these modes.
buffersA pointer to the start of the extended momory block containing the receive buffers. This block must be allocated beforehand by the user. The size of the block should be:
(# of buffers) * ((size of buffer) + 4)buffer_countThe number of buffers in the block pointed to by
buffer.buffer_sizeThe capacity of each buffer in the block pointed to by
buffer.Return Value
1if the actual baud rate is within 5% of the requested baud rate,0otherwise.Library
HDLC_PACKET.LIB
HDLCpeekX
int HDLCpeekX(unsigned long *bufptr, int *lenptr);
/* Where X is E or F */Description
Reports the location and size of the next available received packet if one is available. This function can be used to effeciently inspect a received packet without actually copying it into a root memory buffer. Once inspected, the buffer can be received normally (see
HDLCreceiveX()), or dropped (seeHDLCdropX()).This function is intended for use with the Rabbit 3000 microprocessor.
Parameters
bufptrPointer to location in xmem of the received packet.
lenptrPointer to the size of the received packet.
Return Value
1: The pointersbufptrandlenptrhave been set for the received packet.0: No received packets available.Library
HDLC_PACKET.LIB
HDLCreceiveX
int HDLCreceiveX (char *rx_buffer, int length);
/* Where X is E or F */Description
Copies a received packet into
rx_bufferif there is one. Packets are received in the order they arrive, even if multiple packets are currently stored in buffers.This function is intended for use with the Rabbit 3000 microprocessor.
Parameters
rx_bufferPointer to the buffer to copy a received packet into.
lengthSize of the buffer pointed to by
rx_buffer.Return Value
≥
0: Size of received packet.-1: No packets are available to receive.
-2: The buffer is not large enough for the received packet. In this case, the packet remains in the receive buffer)Library
HDLC_PACKET.LIB
HDLCsendX
int HDLCsendX(char *tx_buffer, int length); /* Where X is E or F */Description
Transmits a packet out serial port E or F in HDLC mode. The tx_buffer is read directly while transmitting, therefore it cannot be altered until a subsequent call to
HDLCsendingX()returns false, indicating that the driver is done with it.This function is intended for use with the Rabbit 3000 microprocessor.
Parameters
tx_bufferA pointer to the packet to be sent. This buffer must not change while tranmitting (see above.)
lengthThe size of the buffer (in bytes).
Return Value
1: Sending packet0: Cannot send, another packet is currently being transmitted.Library
HDLC_PACKET.LIB
HDLCsendingX
int HDLCsendingX(); /* Where X is E or F */Description
Returns true if a packet is currently being transmitted. This function is intended for use with the Rabbit 3000 microprocessor.
Return Value
1: Currently sending a packet.0: Transmitter is idle.Library
HDLC_PACKET.LIB
hitwd
void hitwd();Description
Hits the watchdog timer, postponing a hardware reset for 2 seconds. Unless the watchdog timer is disabled, a program must call this function periodically, or the controller will automatically reset itself. If the virtual driver is enabled (which it is by default), it will call
hitwdin the background. The virtual driver also makes additional "virtual" watchdog timers available.Library
VDRIVER.LIB
htoa
char *htoa(int value, char *buf);Description
Converts integer
valueto hexadecimal number and puts result intobuf.Parameters
valuebufCharacter string of converted number
Return value
Pointer to end (
NULLterminator) of string inbuf.Library
STDIO.LIBSee also
itoa, utoa, ltoa
IntervalMs
int IntervalMs( long ms );Description
Similar to
DelayMsbut provides a periodic delay based on the time from the previous call. Intended for use withwaitfor.Parameters
msThe number of milliseconds to wait.
Return value
0: Not finished.1: Delay has expired.Library
COSTATE.LIB
IntervalSec
int IntervalSec( long sec );Description
Similar to
DelayMsbut provides a periodic delay based on the time from the previous call. Intended for use withwaitfor.Parameters
secThe number of seconds to delay.
Return value
0: Not finished.1: Delay has expired.Library
COSTATE.LIB
IntervalTick
int IntervalTick( long tick );Description
Provides a periodic delay based on the time from the previous call. Intended for use with
waitfor. A tick is 1/1024 seconds.Parameters
tickReturn value
0: Not finished.1: Delay has expired.Library
COSTATE.LIB
ipres
void ipres(void);Description
Dynamic C expands this call inline. Restore previous interrupt priority by rotating the IP register.
Library
UTIL.LIBSee also
ipset
ipset
void ipset(int priority);Description
Dynamic C expands this call inline. Replaces current interrupt priority with another by rotating the new priority into the IP register.
Parameters
priorityInterrupt priority range 0-3, lowest to highest priority.
Library
UTIL.LIBSee also
ipres
isalnum
int isalnum(int c);Description
Tests for an alphabetic or numeric character, (A to Z, a to z and 0 to 9).
Parameters
cReturn value
0if not an alphabetic or numeric character.!0otherwise.Library
STRING.LIBSee also
isalpha, isdigit, ispunct
isalpha
int isalpha(int c);Description
Tests for an alphabetic character, (A to Z, or a to z).
Parameters
cReturn value
0if not a alphabetic character.!0otherwise.Library
STRING.LIBSee also
isalnum, isdigit, ispunct
iscntrl
int iscntrl(int c);Description
Tests for a control character: 0 <=
c<= 31 orc== 127.Parameters
cReturn value
0if not a control character.!0otherwise.Library
STRING.LIBSee also
isalpha, isalnum, isdigit, ispunct
isCoDone
int isCoDone(CoData *p);Description
Determine if costatement is initialized and not running.
Parameters
pReturn value
1if costatement is initialized and not running.0otherwise.Library
COSTATE.LIB
isCoRunning
int isCoRunning(CoData *p);Description
Determine if costatement is stopped or running.
Parameters
pReturn value
1if costatement is running.0otherwise.Library
COSTATE.LIB
isdigit
int isdigit(int c);Description
Tests for a decimal digit: 0 - 9
Parameters
cReturn value
0if not a decimal digit.!0otherwise.Library
STRING.LIBSee also
isxdigit, isalpha, isalpha
isgraph
int isgraph(int c);Description
Tests for a printing character other than a space: 33 <=
c<= 126Parameters
cReturn value
0:cis not a printing character.!0:cis a printing character.Library
STRING.LIBSee also
isprint, isalpha, isalnum, isdigit, ispunct
islower
int islower(int c);Description
Tests for lower case character.
Parameters
cReturn value
0if not a lower case character.!0otherwise.Library
STRING.LIBSee also
tolower, toupper, isupper
isspace
int isspace(int c);Description
Tests for a white space, character, tab, return, newline, vertical tab, form feed, and space: 9 <=
c<= 13 andc== 32 .Parameters
cReturn value
Library
STRING.LIBSee also
ispunct
isprint
int isprint(int c);Description
Tests for printing character, including space: 32 <=
c<= 126Parameters
cReturn value
0if not a printing character,!0otherwise.Library
STRING.LIBSee also
isdigit, isxdigit, isalpha, ispunct, isspace, isalnum, isgraph
ispunct
int ispunct(int c);Description
Tests for a punctuation character.
space 32 ! " # $ % & ' ( ) * + , - . / 33 <= c<= 47: ; < = > ? @ 58 <= c<= 64[\] ^ _ ` 91 <= c<= 96{|} ~ 123 <= c<= 126Parameters
cReturn value
0if not a character.!0otherwise.Library
STRING.LIBSee also
isspace
isupper
int isupper(int c);Description
Tests for upper case character.
Parameters
cReturn value
Library
STRING.LIBSee also
tolower, toupper, islower
isxdigit
int isxdigit(int c);Description
Tests for a hexadecimal digit: 0 - 9, A - F, a - f
Parameters
cReturn value
0if not a hexadecimal digit,!0otherwise.Library
STRING.LIBSee also
isdigit, isalpha, isalpha
itoa
char *itoa(int value, char *buf);Description
Places up to a 5-digit character string, with a minus sign in the leftmost digit when appropriate, at
*buf. The string represents value, a signed number.Leading zeros are suppressed in the character string, except for one zero digit when
value= 0. The longest possible string is "-32768."Parameters
value16-bit signed number to convert
bufCharacter string of converted number in base 10
Return value
Pointer to the end (
NULLterminator) of the string inbuf.Library
STDIO.LIBSee also
atoi, utoa, ltoa
i2c_check_ack
int i2c_check_ack();Description
Checks if slave pulls data low for ACK on clock pulse. Allows for clocks stretching on SCL going high.
Return value
0: ACK sent from slave.1: NAK sent from slave.-1: Timeout occurred.Library
I2C.LIBSee also
Technical Note 215, Using the I2C Bus with a Rabbit Microprocessor.
i2c_init
void i2c_init();Description
Sets up the SCL and SDA port pins for open-drain output.
Library
I2C.LIBSee also
Technical Note 215, Using the I2C Bus with a Rabbit Microprocessor.
i2c_read_char
int i2c_read_char(char *ch);Description
Reads 8 bits from the slave. Allows for clocks stretching on all SCL going high. This is not in the protocol for I2C, but allows I2C slaves to be implemented on slower devices.
Parameters
chA one character return buffer.
Return value
0: Success.-1: Clock stretching timeout.Library
I2C.LIBSee also
Technical Note 215, Using the I2C Bus with a Rabbit Microprocessor.
i2c_send_ack
int i2c_send_ack();Description
Sends ACK sequence to slave. ACK is usually sent after a successful transfer, where more bytes are going to be read.
Return value
0: Success.-1: Clock stretching timeout.Library
I2C.LIBSee also
Technical Note 215, Using the I2C Bus with a Rabbit Microprocessor.
i2c_send_nak
int i2c_send_nak();Description
Sends NAK sequence to slave. NAK is often sent when the transfer is finished.
Return value
0: Success.-1: Clock stretching timeout.Library
I2C.LIBSee also
Technical Note 215, Using the I2C Bus with a Rabbit Microprocessor.
i2c_start_tx
int i2c_start_tx();Description
Initiates I2C transmission by sending the start sequence, which is defined as a high to low transition on SDA while SCL is high. The point being that SDA is supposed to remain stable while SCL is high. If it does not, then that indicates a start (S) or stop (P) condition. This function first waits for possible clock stretching, which is when a bus peripheral holds SCK low.
Return value
0: Success.-1: Clock stretching timeout.Library
I2C.LIBSee also
Technical Note 215, Using the I2C Bus with a Rabbit Microprocessor.
i2c_startw_tx
int i2c_startw_tx();Description
Initiates I2C transmission by sending the start sequence, which is defined as a high to low transition on SDA while SCL is high. The point being that SDA is supposed to remain stable while SCL is high. If it does not, then that indicates a start (S) or stop (P) condition. This function first waits for possible clock stretching, which is when a bus peripheral holds SCK low.
This function is essentially the same as
i2c_start_tx()with the addition of a clock stretch delay, which is 2000 "counts," inserted after the start sequence. (A count is an iteration through a loop.)Return value
0: Success.-1: Clock stretching timeout.Library
I2C.LIBSee also
Technical Note 215, Using the I2C Bus with a Rabbit Microprocessor.
i2c_stop_tx
void i2c_stop_tx();Description
Sends the stop sequence to the slave, which is defined as bringing SDA high while SCL is high, i.e., the clock goes high, then data goes high.
Library
I2C.LIBSee also
Technical Note 215, Using the I2C Bus with a Rabbit Microprocessor.
i2c_write_char
int i2c_write_char(char d);Description
Sends 8 bits to slave. Checks if slave pulls data low for ACK on clock pulse. Allows for clocks stretching on SCL going high.
Parameters
dReturn value
0: Success.-1: Clock stretching timeout.1: NAK sent from slave.Library
I2C.LIBSee also
Technical Note 215, Using the I2C Bus with a Rabbit Microprocessor.
kbhit
int kbhit();Description
Detects keystrokes in the Dynamic C Stdio window.
Return value
!0if a key has been pressed,0otherwise.Library
UTIL.LIB
labs
long labs(long x);Description
Computes the long integer absolute value of long integer
x.Parameters
xReturn value
Library
MATH.LIBSee also
abs, fabs
ldexp
float ldexp(float x, int n);Description
Parameters
xThe value between 0.5 inclusive, and 1.0
nReturn value
Library
MATH.LIBSee also
frexp, exp
log
float log(float x);Description
Computes the logarithm, base e, of real
floatvaluex.Parameters
xReturn value
The function returns -INF and signals a domain error when
x0.
Library
MATH.LIBSee also
exp, log10
log10
float log10(float x);Description
Computes the base 10 logarithm of real
floatvaluex.Parameters
xReturn value
The function returns -INF and signals a domain error when
x0.
Library
MATH.LIBSee also
log, exp
longjmp
void longjmp(jmp_buf env, int val);Description
Restores the stack environment saved in array
env[ ]. See the description ofsetjmpfor details of use.Parameters
envEnvironment previously saved with
setjmp.valLibrary
SYS.LIBSee also
setjmp
loophead
void loophead();Description
This function should be called within the main loop in a program. It is necessary for proper single-user cofunction abandonment handling.
When two costatements are requesting access to a single-user cofunction, the first request is honored and the second request is held. When
loophead()notices that the first caller is not being called each time around the loop, it cancels the request, calls the abandonment code and allows the second caller in.See
Samples\Cofunc\Cofaband.cfor sample code showing abandonment handling.Parameters
Library
COFUNC.LIB
loopinit
void loopinit();Description
This function should be called in the beginning of a program that uses single-user cofunctions. It initializes internal data structures that are used by
loophead().Parameters
Library
COFUNC.LIB
ltoa
char *ltoa(long num, char *ibuf)Description
This function outputs a signed long number to the character array.
Parameters
numibufReturn value
Pointer to the same array passed in to hold the result.
Library
STDIO.LIBSee also
ltoa
ltoan
int ltoan(long num);Description
This function returns the number of characters required to display a signed long number.
Parameters
numReturn value
The number of characters to display signed long number.
Library
STDIO.LIBSee also
ltoa
lx_format
int lx_format(FSLXnum lxn, long wearlevel);Description
Format a specified file system extent. This must not be called before calling
fs_init(). All files which have either or both metadata and data on this extent are deleted. Formatting can be quite slow (depending on hardware) so it is best performed after power-up, if at all.Parameters
lxnLogical extent number (1.._fs.num_lx inclusive).
wearlevelInitial wearlevel value. This should be 1 if you have a new flash, and some larger number if the flash is used. If you are reformatting a flash, you can use 0 to use the old flash wear levels.
Return value
ERRNO values
ENODEV- no such extent number, or extent is reserved.EBUSY- one or more files were open on this extent.EIO- I/O error during format. If this occurs, retry the format operation. If it fails again, there is probably a hardware error.Library
fs2.LIBSee also
fs_init, fs_format
md5_append
void md5_append(md5_state_t *pms, char *data, int nbytes);Description
This function will take a buffer and compute the MD5 hash of its contents, combined with all previous data passed to it. This function can be called several times to generate the hash of a large amount of data
Parameters
md5_appendPointer to the
md5_state_tstructure that was initialized bymd5_init.dataPointer to the data to be hashed.
nbytesLength of the data to be hashed.
Library
MD5.LIB
md5_init
void md5_init(md5_state_t *pms);Description
Initialize the MD5 hash process. Initial values are generated for the structure, and this structure will identify a particular transaction in all subsequent calls to the md5 library.
Parameter
pmsPointer to the
md5_state_tstructure.Library
MD5.LIB
md5_finish
void md5_finish(md5_state_t *pms, char digest[16]);Description
Completes the hash of all the received data and generates the final hash value.
Parameters
pmsPointer to the
md5_state_tstructure that was initialized bymd5_init.digestThe 16-byte array that the hash value will be written into.
Library
MD5.LIB
memchr
void *memchr(void *src, int ch, unsigned int n);Description
Searches up to
ncharacters at memory pointed to bysrcfor characterch.Parameters
srcchnReturn value
Pointer to first occurrence of
chif found withinncharacters. Otherwise returnsNULL.Library
STRING.LIBSee also
strrchr, strstr
memcmp
int memcmp(void *s1, void *s2, size_t n);Description
Performs unsigned character by character comparison of two memory blocks of length
n.Parameters
s1s2nMaximum number of bytes to compare.
Return value
<0: A character instr1is less than the corresponding character instr2.0:str1is identical tostr2.>0: A character instr1is greater than the corresponding character instr2.Library
STRING.LIBSee also
strncmp
memcpy
void *memcpy(void *dst, void *src, unsigned int n);Description
Copies a block of bytes from one destination to another. Overlap is handled correctly.
Parameters
dstsrcnReturn value
Library
STRING.LIBSee also
memmove, memset
memmove
void *memmove(void *dst, void *src, unsigned int n);Description
Copies a block of bytes from one destination to another. Overlap is handled correctly.
Parameters
dstsrcnReturn value
Library
STRING.LIBSee also
memcpy, memset
memset
void *memset(void *dst, int chr, unsigned int n);Description
Sets the first
nbytes of a block of memory to byte destination.Parameters
dstchrnLibrary
STRING.LIB
mktime
unsigned long mktime(struct tm *timeptr);Description
Converts the contents of structure pointed to by
timeptrinto seconds.struct tm {
char tm_sec; // seconds 0-59
char tm_min; // 0-59
char tm_hour; // 0-23
char tm_mday; // 1-31
char tm_mon; // 1-12
char tm_year; // 80-147 (1980-2047)
char tm_wday; // 0-6 0==sunday
};Parameters
timeptrReturn value
Time in seconds since January 1, 1980.
Library
RTCLOCK.LIBSee also
mktm, tm_rd, tm_wr
mktm
unsigned int mktm(struct tm *timeptr, unsigned long time);Description
Converts the seconds (
time) to date and time and fills in the fields of thetmstructure with the result.struct tm {
char tm_sec; // seconds 0-59
char tm_min; // 0-59
char tm_hour; // 0-23
char tm_mday; // 1-31
char tm_mon; // 1-12
char tm_year; // 80-147 (1980-2047)
char tm_wday; // 0-6 0==sunday
};Parameters
timeptrAddress to store date and time into structure:
timeSeconds since January 1, 1980.
Return value
Library
RTCLOCK.LIBSee also
mktime, tm_rd, tm_wr
modf
float modf(float x, int *n);Description
Splits
xinto a fraction and integer,f + n.Parameters
xnReturn value
The integer part in
*nand the fractional part satisfies|f| < 1.0Library
MATH.LIBSee also
fmod, ldexp
OS_ENTER_CRITICAL
void OS_ENTER_CRITICAL();Description
Enter a critical section. Interrupts will be disabled until
OS_EXIT_CRITICAL()is called. Task switching is disabled. This function must be used with great care, since misuse can greatly increase the latency of your application. Note that nestingOS_ENTER_CRITICAL()calls will work correctly.Library
UCOS2.LIB
OS_EXIT_CRITICAL
void OS_EXIT_CRITICAL();Description
Exit a critical section. If the corresponding previous
OS_ENTER_CRITICAL()call disabled interrupts (that is, interrupts were not already disabled), then interrupts will be enabled. Otherwise, interrupts will remain disabled. Hence, nesting calls toOS_ENTER_CRITICAL()will work correctly.Library
UCOS2.LIB
OSInit
void OSInit(void);Description
Initializes µC/OS-II data; must be called before any other µC/OS-II functions are called.
Library
UCOS2.LIBSee also
OSTaskCreate, OSTaskCreateExt, OSStart
OSMboxAccept
void *OSMboxAccept (OS_EVENT *OSMboxAccept);Description
Checks the mailbox to see if a message is available. Unlike
OSMboxPend(),OSMboxAccept()does not suspend the calling task if a message is not available.Parameters
OSMboxAcceptPointer to the mailbox's event control block.
Return value
Pointer to available message, or a
NULLpointer if there is no available message or an error condition exists.Library
UCOS2.LIBSee also
OSMboxCreate, OSMboxPend, OSMboxPost, OSMboxQuery
OSMboxCreate
OS_EVENT *OSMboxCreate (void *msg);Description
Creates a message mailbox if event control blocks are available.
Parameters
msgPointer to a message to put in the mailbox.
Return value
Pointer to mailbox's event control block, or
NULLpointer if no event control block was available.Library
UCOS2.LIBSee also
OSMboxAccept, OSMboxPend, OSMboxPost, OSMboxQuery
OSMboxPend
void *OSMboxPend(OS_EVENT *pevent, INT16U timeout, INT8U *err);Description
Waits for a message to be sent to a mailbox.
Parameters
peventPointer to mailbox's event control block.
timeoutAllows task to resume execution if a message was not received by the number of clock ticks specified. Specifying 0 means the task is willing to wait forever.
errPointer to a variable for holding an error code.
Return value
Pointer to a message or, if a timeout or error condition occurs, a
NULLpointer.Library
UCOS2.LIBSee also
OSMboxAccept, OSMboxCreate, OSMboxPost, OSMboxQuery
OSMboxPost
INT8U OSMboxPost (OS_EVENT *pevent, void *msg);Description
Sends a message to the specified mailbox
Parameters
peventPointer to mailbox's event control block.
msgPointer to message to be posted. A
NULLpointer must not be sent.Return value
OS_NO_ERRThe call was successful and the message was sent.
OS_MBOX_FULLThe mailbox already contains a message. Only one message at a time can be sent and thus, the message MUST be consumed before another can be sent.
OS_ERR_EVENT_TYPEAttempting to post to a non-mailbox.
Library
UCOS2.LIBSee also
OSMboxAccept, OSMboxCreate, OSMboxPend, OSMboxQuery
OSMboxQuery
INT8U OSMboxQuery (OS_EVENT *pevent, OS_MBOX_DATA *pdata);Description
Obtains information about a message mailbox.
Parameters
peventPointer to message mailbox's event control block.
pdataPointer to a data structure for information about the message mailbox
Return value
OS_NO_ERRThe call was successful and the message was sent.
OS_ERR_EVENT_TYPEAttempting to obtain data from a non mailbox.
Library
UCOS2.LIBSee also
OSMboxAccept, OSMboxCreate, OSMboxPend, OSMboxPost
OSMemCreate
OS_MEM *OSMemCreate (void *addr, INT32U nblks, INT32U blksize, INT8U *err);Description
Creates a fixed-sized memory partition that will be managed by µC/OS-II.
Parameters
addrPointer to starting address of the partition.
nblksNumber of memory blocks to create in the partition.
blksizeThe size (in bytes) of the memory blocks.
errPointer to variable containing an error message.
Return value
Pointer to the created memory partition control block if one is available,
NULLpointer otherwise.Library
UCOS2.LIBSee also
OSMemGet, OSMemPut, OSMemQuery
OSMemGet
void *OSMemGet (OS_MEM *pmem, INT8U *err);Description
Gets a memory block from the specified partition.
Parameters
pmemPointer to partition's memory control block
errPointer to variable containing an error message
Return value
Pointer to a memory block or a
NULLpointer if an error condition is detected.Library
UCOS2.LIBSee also
OSMemCreate, OSMemPut, OSMemQuery
OSMemPut
INT8U OSMemPut(OS_MEM *pmem, void *pblk);Description
Returns a memory block to a partition.
Parameters
pmemPointer to the partition's memory control block.
pblkPointer to the memory block being released.
Return value
OS_NO_ERRThe memory block was inserted into the partition.
OS_MEM_FULLIf returning a memory block to an already FULL memory partition. (More blocks were freed than allocated!)
Library
UCOS2.LIBSee also
OSMemCreate, OSMemGet, OSMemQuery
OSMemQuery
INT8U OSMemQuery (OS_MEM *pmem, OS_MEM_DATA *pdata);Description
Determines the number of both free and used memory blocks in a memory partition.
Parameters
pmemPointer to partition's memory control block.
pdataPointer to structure for holding information about the partition.
Return value
OS_NO_ERRThis function always returns no error.
Library
UCOS2.LIBSee also
OSMemCreate, OSMemGet, OSMemPut
OSQAccept
void *OSQAccept (OS_EVENT *pevent);Description
Checks the queue to see if a message is available. Unlike
OSQPend(), withOSQAccept()the calling task is not suspended if a message is unavailable.Parameters
peventPointer to the message queue's event control block.
Return value
Pointer to message in the queue if one is available,
NULLpointer otherwise.Library
UCOS2.LIBSee also
OSQCreate, OSQFlush, OSQPend, OSQPost, OSQPostFront, OSQQuery
OSQCreate
OS_EVENT *OSQCreate (void **start, INT16U qsize);Description
Creates a message queue if event control blocks are available.
Parameters
startPointer to the base address of the message queue storage area. The storage area MUST be declared an array of pointers to void:
void *MessageStorage[qsize].qsizeNumber of elements in the storage area.
Return value
Pointer to message queue's event control block or
NULLpointer if no event control blocks were available.Library
UCOS2.LIBSee also
OSQAccept, OSQFlush, OSQPend, OSQPost, OSQPostFront, OSQQuery
OSQFlush
INT8U OSQFlush (OS_EVENT *pevent);Description
Flushes the contents of the message queue.
Parameters
peventPointer to message queue's event control block.
Return value
OS_NO_ERR: Success.OS_ERR_EVENT_TYPE: A pointer to a queue was not passed.OS_ERR_PEVENT_NULL: Ifpeventis aNULLpointer.Library
UCOS2.LIBSee also
OSQAccept, OSQCreate, OSQPend, OSQPost, OSQPostFront, OSQQuery
OSQPend
void *OSQPend (OS_EVENT *pevent, INT16U timeout, INT8U *err);Description
Waits for a message to be sent to a queue.
Parameters
peventPointer to message queue's event control block.
timeoutAllow task to resume execution if a message was not received by the number of clock ticks specified. Specifying 0 means the task is willing to wait forever.
errPointer to a variable for holding an error code.
Return value
Pointer to a message or, if a timeout occurs, a
NULLpointer.Library
UCOS2.LIBSee also
OSQAccept, OSQCreate, OSQFlush, OSQPost, OSQPostFront, OSQQuery
OSQPost
INT8U OSQPost (OS_EVENT *pevent, void *msg);Description
Sends a message to the specified queue.
Parameters
peventPointer to message queue's event control block.
msgPointer to the message to send.
NULLpointer must not be sent.Return value
OS_NO_ERR: The call was successful and the message was sent.OS_Q_FULL: The queue cannot accept any more messages because it is full.OS_ERR_EVENT_TYPE: If a pointer to a queue not passed.OS_ERR_PEVENT_NULL: Ifpeventis aNULLpointer.OS_ERR_POST_NULL_PTR: If attempting to post to aNULLpointer.Library
UCOS2.LIBSee also
OSQAccept, OSQCreate, OSQFlush, OSQPend, OSQPostFront, OSQQuery
OSQPostFront
INT8U OSQPostFront (OS_EVENT *pevent, void *msg);Description
Sends a message to the specified queue, but unlike
OSQPost(), the message is posted at the front instead of the end of the queue. UsingOSQPostFront()allows 'priority' messages to be sent.Parameters
peventPointer to message queue's event control block.
msgPointer to the message to send.
NULLpointer must not be sent.Return value
OS_NO_ERR- The call was successful and the message was sent.OS_Q_FULL- The queue cannot accept any more messages because it is full.OS_ERR_EVENT_TYPE- A pointer to a queue was not passed.OS_ERR_PEVENT_NULL- Ifpeventis aNULLpointer.OS_ERR_POST_NULL_PTR- Attempting to post to a non mailbox.Library
UCOS2.LIBSee also
OSQAccept, OSQCreate, OSQFlush, OSQPend, OSQPost, OSQQuery
OSQQuery
INT8U OSQQuery (OS_EVENT *pevent, OS_Q_DATA *pdata);Description
Obtains information about a message queue.
Parameters
peventPointer to message queue's event control block.
pdataPointer to a data structure for message queue information.
Return value
OS_NO_ERR- The call was successful and the message was sent.OS_ERR_EVENT_TYPE- Attempting to obtain data from a non queue.OS_ERR_PEVENT_NULL- If pevent is aNULLpointer.Library
UCOS2.LIBSee also
OSQAccept, OSQCreate, OSQFlush, OSQPend, OSQPost, OSQPostFront
OSSchedLock
void OSSchedLock(void);Description
Prevents task rescheduling. This allows an application to prevent context switches until it is ready for them. There must be a matched call to
OSSchedUnlock()for every call toOSSchedLock().Library
UCOS2.LIBSee also
OSSchedUnlock
OSSchedUnlock
void OSSchedUnlock(void);Description
Allow task rescheduling. There must be a matched call to
OSSchedUnlock()for every call toOSSchedLock().Library
UCOS2.LIBSee also
OSSchedLock
OSSemAccept
INT16U OSSemAccept (OS_EVENT *pevent);Description
This function checks the semaphore to see if a resource is available or if an event occurred. Unlike
OSSemPend(),OSSemAccept()does not suspend the calling task if the resource is not available or the event did not occur.Parameters
peventPointer to the desired semaphore's event control block
Return value
Semaphore value:
If>0, semaphore value is decremented; value is returned before the decrement.
If0, then either resource is unavailable, event did not occur, orNULLor invalid pointer was passed to the function.Library
UCOS2.LIBSee also
OSSemCreate, OSSemPend, OSSemPost, OSSemQuery
OSSemCreate
OS_EVENT *OSSemCreate (INT16U cnt);Description
Parameters
cntThe initial value of the semaphore.
Return value
Pointer to the event control block (
OS_EVENT) associated with the created semaphore, orNULLif no event control block is available.Library
UCOS2.LIBSee also
OSSemAccept, OSSemPend, OSSemPost, OSSemQuery
OSSemPend
void OSSemPend (OS_EVENT *pevent, INT16U timeout, INT8U *err);Description
Parameters
peventPointer to the desired semaphore's event control block
timeoutTime in clock ticks to wait for the resource. If 0, the task will wait until the resource becomes available or the event occurs.
errLibrary
UCOS2.LIBSee also
OSSemAccept, OSSemCreate, OSSemPost, OSSemQuery
OSSemPost
INT8U OSSemPost (OS_EVENT *pevent);Description
This function signals a semaphore.
Parameters
peventPointer to the desired semaphore's event control block
Return value
OS_NO_ERR- The call was successful and the semaphore was signaled.OS_SEM_OVF- If the semaphore count exceeded its limit. In other words, you have signalled the semaphore more often than you waited on it with eitherOSSemAccept()orOSSemPend().OS_ERR_EVENT_TYPE- If a pointer to a semaphore not passed.OS_ERR_PEVENT_NULL- Ifpeventis aNULLpointer.Library
UCOS2.LIBSee also
OSSemAccept, OSSemCreate, OSSemPend, OSSemQuery
OSSemQuery
INT8U OSSemQuery (OS_EVENT *pevent, OS_SEM_DATA *pdata);Description
Obtains information about a semaphore.
Parameters
peventPointer to the desired semaphore's event control block
pdataPointer to a data structure that will hold information about the semaphore.
Return value
OS_NO_ERR- The call was successful and the message was sent.OS_ERR_EVENT_TYPE- Attempting to obtain data from a non semaphore.OS_ERR_PEVENT_NULL- If pevent is aNULLpointer.Library
UCOS2.LIBSee also
OSSemAccept, OSSemCreate, OSSemPend, OSSemPost
OSSetTickPerSec
INT16U OSSetTickPerSec(INT16U TicksPerSec);Description
Sets the amount of ticks per second (from 1 - 2048). Ticks per second defaults to 64. If this function is used, the
#define OS_TICKS_PER_SECneeds to be changed so that the time delay functions work correctly. Since this function uses integer division, the actual ticks per second may be slightly different that the desired ticks per second.Parameters
TicksPerSecReturn value
The actual ticks per second set, as an unsigned 16-bit integer.
Library
UCOS2.LIBSee also
OSStart
OSStart
void OSStart(void);Description
Starts the multitasking process, allowing µC/OS-II to manage the tasks that have been created. Before
OSStart()is called,OSInit()MUST have been called and at least one task MUST have been created. This function callsOSStartHighRdywhich callsOSTaskSwHook and setsOSRunningto TRUE.Library
UCOS2.LIBSee also
OSTaskCreate, OSTaskCreateExt
OSStatInit
void OSStatInit(void);Description
Library
UCOS2.LIB
OSTaskChangePrio
INT8U OSTaskChangePrio (INT8U oldprio, INT8U newprio);Description
Allows a task's priority to be changed dynamically. Note that the new priority MUST be available.
Parameters
oldprioThe priority level to change from.
newprioThe priority level to change to.
Return value
OS_NO_ERR- The call was successful.OS_PRIO_INVALID- The priority specified is higher that the maximum allowed (i.e. ≥OS_LOWEST_PRIO).OS_PRIO_EXIST- The new priority already exist.OS_PRIO_ERR- There is no task with the specified OLD priority (i.e. the OLD task does not exist).Library
UCOS2.LIB
OSTaskCreate
INT8U OSTaskCreate(void (*task)(), void *pdata, INT16U stk_size, INT8U prio);Description
Creates a task to be managed by µC/OS-II. Tasks can either be created prior to the start of multitasking or by a running task. A task cannot be created by an ISR.
Parameters
taskPointer to the task's starting address.
pdataPointer to a task's initial parameters.
stk_sizepriorThe task's unique priority number.
Return value
OS_NO_ERR- The call was successful.OS_PRIO_EXIT- Task priority already exists (each task MUST have a unique priority).OS_PRIO_INVALID- The priority specified is higher than the maximum allowed (i.e. ≥OS_LOWEST_PRIO).Library
UCOS2.LIBSee also
OSTaskCreateExt
OSTaskCreateExt
INT8U OSTaskCreateExt (void (*task)(), void *pdata, INT8U prio, INT16U id, INT16U stk_size, void *pext, INT16U opt);Description
Creates a task to be managed by µC/OS-II. Tasks can either be created prior to the start of multitasking or by a running task. A task cannot be created by an ISR. This function is similar to
OSTaskCreate()except that it allows additional information about a task to be specified.Parameters
taskpdataPointer to optional data area; used to pass parameters to the task at start of execution.
prioThe task's unique priority number; the lower the number the higher the priority.
idThe task's identification number (0...65535).
stk_sizeSize of the stack in number of elements. If
OS_STKis set toINT8U,stk_sizecorresponds to the number of bytes available. IfOS_STKis set toINT16U,stk_sizecontains the number of 16-bit entries available. Finally, ifOS_STKis set toINT32U,stk_sizecontains the number of 32-bit entries available on the stack.pextPointer to a user-supplied Task Control Block (TCB) extension.
optThe lower 8 bits are reserved by µC/OS-II. The upper 8 bits control application-specific options. Select an option by setting the corresponding bit(s).
Return value
OS_NO_ERR- The call was successful.OS_PRIO_EXIT- Task priority already exists (each task MUST have a unique priority).OS_PRIO_INVALID- The priority specified is higher than the maximum allowed (i.e. ≥OS_LOWEST_PRIO).Library
UCOS2.LIBSee also
OSTaskCreate
OSTaskCreateHook
void OSTaskCreateHook(OS_TCB *ptcb);Description
Called by µC/OS-II whenever a task is created. This call-back function resides in
UCOS2.LIBand extends functionality during task creation by allowing additional information to be passed to the kernel, anything associated with a task. This function can also be used to trigger other hardware, such as an oscilloscope. Interrupts are disabled during this call, therefore, it is recommended that code be kept to a minimum.Parameters
ptcbPointer to the TCB of the task being created.
Library
UCOS2.LIBSee also
OSTaskDelHook
OSTaskDel
INT8U OSTaskDel (INT8U prio);Description
Deletes a task. The calling task can delete itself by passing either its own priority number or
OS_PRIO_SELFif it doesn't know its priority number. The deleted task is returned to the dormant state and can be re-activated by creating the deleted task again.Parameters
prioReturn value
OS_NO_ERR- The call was successful.OS_TASK_DEL_IDLE- Attempting to delete uC/OS-II's idle task.OS_PRIO_INVALID- The priority specified is higher than the maximum allowed (i.e. ≥OS_LOWEST_PRIO) or,OS_PRIO_SELFnot specified.OS_TASK_DEL_ERR- The task to delete does not exist.OS_TASK_DEL_ISR- Attempting to delete a task from an ISR.Library
UCOS2.LIBSee also
OSTaskDelReq
OSTaskDelHook
void OSTaskDelHook(OS_TCB *ptcb);Description
Called by µC/OS-II whenever a task is deleted. This call-back function resides in
UCOS2.LIB. Interrupts are disabled during this call, therefore, it is recommended that code be kept to a minimum.Parameters
ptcbPointer to TCB of task being deleted.
Library
UCOS2.LIBSee also
OSTaskCreateHook
OSTaskDelReq
INT8U OSTaskDelReq (INT8U prio);Description
Notifies a task to delete itself. A well-behaved task is deleted when it regains control of the CPU by calling
OSTaskDelReq (OSTaskDelReq)and monitoring the return value.Parameters
prioThe priority of the task that is being asked to delete itself.
OS_PRIO_SELFis used when asking whether another task wants the current task to be deleted.Return value
OS_NO_ERR- The task exists and the request has been registered.OS_TASK_NOT_EXIST- The task has been deleted. This allows the caller to know whether the request has been executed.OS_TASK_DEL_IDLE- If requesting to delete uC/OS-II's idletask.OS_PRIO_INVALID- The priority specified is higher than the maximum allowed (i.e. ≥OS_LOWEST_PRIO) or,OS_PRIO_SELFis not specified.OS_TASK_DEL_REQ- A task (possibly another task) requested that the running task be deleted.Library
UCOS2.LIBSee also
OSTaskDel
OSTaskQuery
INT8U OSTaskQuery (INT8U prio, OS_TCB *pdata);Description
Obtains a copy of the requested task's TCB.
Parameters
priopdataReturn value
OS_NO_ERR- The requested task is suspended.OS_PRIO_INVALID- The priority you specify is higher than the maximum allowed (i.e. ≥OS_LOWEST_PRIO) or,OS_PRIO_SELFis not specified.OS_PRIO_ERR- The desired task has not been created.Library
UCOS2.LIB
OSTaskResume
INT8U OSTaskResume (INT8U prio);Description
Resumes a suspended task. This is the only call that will remove an explicit task suspension.
Parameters
prioThe priority of the task to resume.
Return value
OS_NO_ERR- The requested task is resumed.OS_PRIO_INVALID- The priority specified is higher than the maximum allowed (i.e. ≥OS_LOWEST_PRIO).OS_TASK_NOT_SUSPENDED- The task to resume has not been suspended.Library
UCOS2.LIBSee also
OSTaskSuspend
OSTaskStatHook
void OSTaskStatHook();Description
Called every second by µC/OS-II's statistics task. This function resides in
UCOS2.LIBand allows an application to add functionality to the statistics task.Library
UCOS2.LIB
OSTaskStkChk
INT8U OSTaskStkChk (INT8U prio, OS_STK_DATA *pdata);Description
Check the amount of free memory on the stack of the specified task.
Parameters
priopdataPointer to a data structure of type
OS_STK_DATA.Return value
OS_NO_ERR- The call was successful.OS_PRIO_INVALID- The priority you specify is higher than the maximum allowed (i.e. >OS_LOWEST_PRIO) or,OS_PRIO_SELFnot specified.OS_TASK_NOT_EXIST- The desired task has not been created.OS_TASK_OPT_ERR- IfOS_TASK_OPT_STK_CHKwas NOT specified when the task was created.Library
UCOS2.LIBSee also
OSTaskCreateExt
OSTaskSuspend
INT8U OSTaskSuspend (INT8U prio);Description
Suspends a task. The task can be the calling task if the priority passed to
OSTaskSuspend()is the priority of the calling task orOS_PRIO_SELF. This function should be used with great care. If a task is suspended that is waiting for an event (i.e. a message, a semaphore, a queue ...) the task will be prevented from running when the event arrives.Parameters
prioThe priority of the task to suspend.
Return value
OS_NO_ERR- The requested task is suspended.OS_TASK_SUS_IDLE- Attempting to suspend the idle task (not allowed).OS_PRIO_INVALID- The priority specified is higher than the maximum allowed (i.e. ≥OS_LOWEST_PRIO) or,OS_PRIO_SELFis not specified .OS_TASK_SUS_PRIO- The task to suspend does not exist.Library
UCOS2.LIBSee also
OSTaskResume
OSTaskSwHook
void OSTaskSwHook();Description
Called whenever a context switch happens. The TCB for the task that is ready to run is accessed via the global variable
OSTCBHighRdy, and the TCB for the task that is being switched out is accessed via the global variableOSTCBCur.Library
UCOS2.LIB
OSTimeDly
void OSTimeDly (INT16U ticks);Description
Delays execution of the task for the specified number of clock ticks. No delay will result if
ticksis 0. Ifticksis >0, then a context switch will result.Parameters
ticksNumber of clock ticks to delay the task.
Library
UCOS2.LIBSee also
OSTimeDlyHMSM, OSTimeDlyResume, OSTimeDlySec
OSTimeDlyHMSM
INT8U OSTimeDlyHMSM (INT8U hours, INT8U minutes, INT8U seconds, INT16U milli);Description
Delays execution of the task until specified amount of time expires. This call allows the delay to be specified in hours, minutes, seconds and milliseconds instead of ticks. The resolution on the milliseconds depends on the tick rate. For example, a 10 ms delay is not possible if the ticker interrupts every 100 ms. In this case, the delay would be set to 0. The actual delay is rounded to the nearest tick.
Parameters
hoursNumber of hours that the task will be delayed (max. is 255)
minutessecondsmilliNumber of milliseconds (max. 999)
Return value
OS_NO_ERR
OS_TIME_INVALID_MINUTES
OS_TIME_INVALID_SECONDS
OS_TIME_INVALID_MS
OS_TIME_ZERO_DLYLibrary
UCOS2.LIBSee also
OSTimeDly, OSTimeDlyResume, OSTimeDlySec
OSTimeDlyResume
INT8U OSTimeDlyResume (INT8U prio);Description
Resumes a task that has been delayed through a call to either
OSTimeDly()orOSTimeDlyHMSM(). Note that this function MUST NOT be called to resume a task that is waiting for an event with timeout. This situation would make the task look like a timeout occurred (unless this is the desired effect). Also, a task cannot be resumed that has calledOSTimeDlyHMSM()with a combined time that exceeds 65535 clock ticks. In other words, if the clock tick runs at 100 Hz then, a delayed task will not be able to be resumed that calledOSTimeDlyHMSM(0, 10, 55, 350)or higher.Parameters
prioPriority of the task to resume.
Return value
OS_NO_ERR- Task has been resumed.OS_PRIO_INVALID- The priority you specify is higher than the maximum allowed (i.e. ≥OS_LOWEST_PRIO).OS_TIME_NOT_DLY- Task is not waiting for time to expire.OS_TASK_NOT_EXIST- The desired task has not been created.Library
UCOS2.LIBSee also
OSTimeDly, OSTimeDlyHMSM, OSTimeDlySec
OSTimeDlySec
INT8U OSTimeDlySec (INT16U seconds);Description
Delays execution of the task until
secondsexpires. This is a low-overhead version ofOSTimeDlyHMSMfor seconds only.Parameters
secondsThe number of seconds to delay.
Return value
OS_NO_ERR- The call was successful.OS_TIME_ZERO_DLY- A delay of zero seconds was requested.Library
UCOS2.LIBSee also
OSTimeDly, OSTimeDlyHMSM, OSTimeDlyResume
OSTimeGet
INT32U OSTimeGet (void);Description
Obtain the current value of the 32-bit counter that keeps track of the number of clock ticks.
Return value
Library
UCOS2.LIBSee also
OSTimeSet
OSTimeSet
void OSTimeSet (INT32U ticks);Description
Sets the 32-bit counter that keeps track of the number of clock ticks.
Parameters
ticksLibrary
UCOS2.LIBSee also
OSTimeGet
OSTimeTickHook
void OSTimeTickHook();Description
This function, as included with Dynamic C, is a stub that does nothing except return. It is called every clock tick. If the user chooses to rewrite this function, code should be kept to a minimum as it will directly affect interrupt latency. This function must preserve any registers it uses, other than the ones that are preserved prior to the call to
OSTimeTickHookat the beginning of the periodic interrupt (periodic_isrinVDRIVER.LIB). Therefore,OSTimeTickHookshould be written in assembly. The registers saved byperiodic_israre: AF,IP, HL,DE and IX.Library
UCOS2.LIB
OSVersion
INT16U OSVersion (void);Description
Returns the version number of µC/OS-II. The returned value corresponds to µC/OS-II's version number multiplied by 100; i.e., version 2.00 would be returned as 200.
Return value
Version number multiplied by 100.
Library
UCOS2.LIB
outchrs
char outchrs(char c, int n, int (*putc) () );Description
Use
putcto outputntimes the characterc.Parameters
cnputcRoutine to output one character. The function pointed to by
putcshould take a character argument.Return value
Library
STDIO.LIBSee also
outstr
outstr
char *outstr(char *string, int (*putc)() );Description
Output the string pointed to by
stringvia calls toputc.putcshould take a one-character parameter.Parameters
stringputcRoutine to output one character. The function pointed to by
putcshould take a character argument.Return value
Pointer to
NULLat end of string.Library
STDIO.LIBSee also
outchrs
paddr
unsigned long paddr(void* pointer);Description
Converts a logical pointer into its physical address. Use caution when converting address in the E000-FFFF range. Returns the address based on the XPC on entry.
Parameters
pointerReturn value
The physical address of the pointer.
Library
XMEM.LIB
pktXclose
void pktXclose();Description
Disables serial port X, where X is A|B|C|D. Starting with Dynamic C version 7.25, the functions
pktEclose()andpktFclose()may be used with the Rabbit 3000 microprocessor.Library
PACKET.LIB
pktXgetErrors
char pktXgetErrors();Description
Gets a bit field with flags set for any errors that occured on port X, where X is A|B|C|D. These flags are then cleared, so that a particular error will only cause the flag to be set once.
Starting with Dynamic C version 7.25, the functions
pktEgetErrors()andpktFgetErrors()may be used with the Rabbit 3000 microprocessor.Return value
A bit field with flags for various errors. The errors along with their bit masks are as follows:
PKT_BUFFEROVERFLOW0x01PKT_RXOVERRUN0x02PKT_PARITYERROR0x04PKT_NOBUFFER0x08
Library
PACKET.LIB
pktXinitBuffers
int pktXinitBuffers(int buf_count, int buf_size); X = A|B|C|DDescription
Allocates extended memory for channel X receive buffers. This function should not be called more than once in a program. The total memory allocated is buf_count*(buf_size + 2) bytes.
Starting with Dynamic C version 7.25, the functions
pktEinitBuffers()andpktFinitBuffers()may be used with the Rabbit 3000 microprocessor.Parameters
buf_countThe number of buffers to allocate. Each buffer can store one received packet. Increasing this number allows for more pending packets and a larger latency time before packets must be processed by the user's program.
buf_sizeThe number of bytes each buffer can accomodate. This should be set to the size of the largest possible packet that can be expected.
Return value
1: Success, extended memory was allocated.0: Failure, no memory allocated, the packet channel cannot be used.Library
PACKET.LIB
pktXopen
int pktXopen(long baud, int mode, char options, int (*test_packet)());Description
Opens serial port X, where X is A|B|C|D. Starting with Dynamic C version 7.25, the functions
pktEopen()andpktFopen()may be used with the Rabbit 3000 microprocessor.Parameters
baudBits per second of data transfer: minimum is 2400.
modeType of packet scheme used, the options are:
- ·
PKT_GAPMODE
- ·
PKT_9BITMODE
- ·
PKT_CHARMODEoptionsFurther specification for the packet scheme. The value of this depends on the mode used:
·
- · gap mode - minimum gap size(in byte times)
- · 9-bit mode - type of 9-bit protocol
PKT_RABBITSTARTBYTE
·PKT_LOWSTARTBYTE
·PKT_HIGHSTARTBYTE
- · char mode - character marking start of packet
test_packetPointer to a function that tests for completeness of a packet. The function should return 1 if the packet is complete, or 0 if more data should be read in. For gap mode the test function is not used and should be set to
NULL.Return value
1: The baud set on the rabbit is the same as the input baud.0: The baud set on the rabbit does not match the input baud.Library
PACKET.LIB
pktXreceive
int pktXreceive(void *buffer, int buffer_size);Description
Gets a received packet, if there is one, from serial port X, where X is A|B|C|D. Starting with Dynamic C version 7.25, the functions
pktEreceive()andpktFreceive()may be used with the Rabbit 3000 microprocessor.Parameters
bufferA buffer for the packet to be written into.
buffer_sizeReturn value
>0: Number of bytes in the successfully received packet.
0: No new packet has been received.-1: The packet is too large for the given buffer-2: A neededtest_packetfunction is not definedLibrary
PACKET.LIB
pktXsend
int pktXsend(void *send_buffer, int buffer_length, char delay);Description
Initiates the sending of a packet of data using serial port X, where X is A|B|C|D. This function will always return immediately. If there is already a packet being transmitted, this call will return 0 and the packet will not be transmitted, otherwise it will return 1.
pktXsending()checks if the packet is done transmitting. The system will be using the buffer until then.Starting with Dynamic C version 7.25, the functions
pktEsend()andpktFsend()may be used with the Rabbit 3000 microprocessor.Parameters
send_bufferbuffer_lengthLength of the data buffer to transmit
delayThe number of byte times to delay before sending the data (0-255) This is used to implement protocol-specific delays between packets
Return value
1: The packet is going to be transmitted.0: There is already a packet transmitting, and the new packet was refused.Library
PACKET.LIB
pktXsending
int pktXsending();Description
Tests if a packet is currently being sent on serial port X, where X=A|B|C|D. If
pktXsending()returns true, the transmitter is busy and cannot accept another packet.Starting with Dynamic C version 7.25, the functions
pktEsending()andpktFsending()may be used with the Rabbit 3000 microprocessor.Return value
1: A packet is being transmitted.0: Port X is idle, ready for a new packet.Library
PACKET.LIB
pktXsetParity
void pktXsetParity(char mode);Description
Configures parity generation and checking. Can also configure for 2 stop bits.
Starting with Dynamic C version 7.25, the functions
pktEsetParity()andpktFsetParity()may be used with the Rabbit 3000 microprocessor.Parameters
mode
- ·
PKT_NOPARITY- no parity bit (8N1 format, default)
- ·
PKT_OPARITY- odd parity (8O1 format)
- ·
PKT_EPARITY- even parity (8E1 format)
- ·
PKT_TWOSTOP- an extra stop bit (8N2 format)Library
PACKET.LIB
poly
float poly(float x, int n, float c[]);Description
Computes polynomial value by Horner's method. For example, for the fourth-order polynomial
10x4- 3x2+ 4x + 6,nwould be 4 and the coefficients would bec[4] = 10.0
c[3] = 0.0
c[2] = -3.0
c[1] = 4.0
c[0] = 6.0Parameters
xncArray containing the coefficients of each power of
x.Return value
Library
MATH.LIB
pow
float pow(float x, float y);Description
Parameters
xyReturn value
Library
MATH.LIBSee also
exp, pow10, sqrt
pow10
float pow10(float x);Description
Parameters
xReturn value
Library
MATH.LIBSee also
pow, exp, sqrt
powerspectrum
void powerspectrum(int *x, int N, *int blockexp);Description
Computes the power spectrum from a complex spectrum according to
- Power[k] = (Re X[k])2 + (Im X[k])2
The
N-point power spectrum replaces theN-point complex spectrum. The power of each complex spectral component is computed as a 32-bit fraction. Its more significant 16-bits replace the imaginary part of the component; its less significant 16-bits replace the real part.If the complex input spectrum is a positive-frequency spectrum computed by
fftreal(),the imaginary part of the X[0] term (storedx[1]) will contain the real part of the fmax term and will affect the calculation of the dc power. If the dc power or the fmax power is important, the fmax term should be retrieved fromx[1]andx[1]set to zero before callingpowerspectrum().The power of the kth term can be retrieved via
P[k]=*(long*)&x[2k]*2^blockexp.The value of
blockexpis first doubled to reflect the squaring operation applied to all elements in arrayx. Then it is further increased by 1 to reflect an inherent division-by-two that occurs during the squaring operation.Parameters
xpointer to
N-element array of complex fractions.Nnumber of complex elements in array
x.blockexppointer to integer block exponent.
Library
FFT.LIBSee also
fftcplx, fftcplxinv, fftreal, fftrealinv, hanncplx, hannreal
premain
void premain();Description
Dynamic C calls
premainto start initialization functions such asVdInit. The final thingpremaindoes is callmain. This function should never be called by an application program. It is included here for informational purposes only.Library
PROGRAM.LIB
printf
int printf(char *fmt, ...);Description
This function is similar to
sprintf(), but outputs the formatted string to the Stdio window in Dynamic C. Please refer to the description ofsprintf()for more details.This function is task reentrant.
Prior to Dynamic C 7.25, it would work only with the controller in program mode connected to the PC running Dynamic C. As of Dynamic C 7.25, it is possible to redirect printf output to a serial port during run mode by defining a macro to specify the serial port. See the sample program
/SAMPLES/STDIO_SERIAL.Cfor more information.Parameters
format...Return Value
Library
STDIO.LIBSee also
sprintf
putchar
void putchar(int ch);Description
Puts a single character to Stdout. The user should make sure only one process calls this function at a time.
Parameters
chLibrary
STDIO.LIBSee also
puts, getchar
puts
int puts(char *s);Description
This function displays the string on the stdio window in Dynamic C. The Stdio window is responsible for interpreting any escape code sequences contained in the string. Only one process at a time should call this function.
Parameters
sPointer to string argument to be displayed.
Return value
Library
STDIO.LIBSee also
putchar, gets
pwm_init
unsigned long pwm_init(unsigned long frequency);Description
Sets the base frequency for the pulse width modulation (PWM) and enables the PWM driver on all four channels. The base frequency is the frequency without pulse spreading. Pulse spreading (see
pwm_set()) will increase the frequency by a factor of 4.This function is intended for use with the Rabbit 3000 microprocessor.
Parameter
frequencyReturn Value
The actual frequency that was set. This will be the closest possible match to the requested frequency.
Library
R3000.LIB
pwm_set
int pwm_set(int channel, int duty_cycle, int options);Description
Sets a duty cycle for one of the pulse width modulation (PWM) channels. The duty cycle can be a value from 0 to 1024, where 0 is logic low the whole time, and 1024 is logic high the whole time. Option flags are used to enable features on an individual PWM channel. Bit masks for these are:
PWM_SPREAD- sets pulse spreading. The duty cycle is spread over four seperate pulses to increase the pulse frequency.
PWM_OPENDRAIN- sets the PWM output pin to be open-drain instead of a normal push-pull logic output.This function is intended for use with the Rabbit 3000 microprocessor.
Parameters
channelduty_cycleoptionscombination of optional flags(see above)
Return Value
0: Success.-1: Error, an invalid channel number is used.-2: Error, requestedduty_cycleis invalid.Library
R3000.LIB
qd_error
char qd_error(int channel);Description
Gets the current error bits for that qd channel. This function is intended to be used with the Rabbit 3000 microprocessor.
Parameters
channelThe channel to read errors from (currently 1 or 2).
Return Value
Set of error flags, that can be decoded with the following masks:
Library
R3000.LIB
qd_init
void qd_init(int iplevel);Description
Initializes the quadrature decoders and sets up the ISR. This must be called before any other QD functions are used. Sets up the lower nibble of port F to be the QD input pins.
This function is intended for use with the Rabbit 3000 microprocessor.
Parameters
iplevelThe interrupt priority for the ISR that handles the count overflow. This should usually be 1.
Library
R3000.LIB
qd_read
long qd_read(int channel);Description
Reads the current quadrature decoder count. Since this function waits for a clear reading, it can potentially block if there is enough flutter in the decoder count.
This function is intended to be used with the Rabbit 3000 microprocessor.
Parameters
channelThe channel to read (currently 1 or 2).
Return Value
Returns a signed long for the current count.
Library
R3000.LIB
qd_zero
void qd_zero(int channel);Description
Sets the count for a channel to 0. This function is intended to be used with the Rabbit 3000 microprocessor.
Parameters
channelThe channel to reset (currently 1 or 2)
Library
R3000.LIB
qsort
int qsort(char *base, unsigned n, unsigned s, int (*cmp) ());Description
Quick sort with center pivot, stack control, and easy-to-change comparison method. This version sorts fixed-length data items. It is ideal for integers, longs, floats and packed string data without delimiters.
Can sort raw integers, longs, floats or strings. However, the string sort is not efficient.
Parameters
baseBase address of the raw string data
nscmpUser-supplied compare routine for two block pointers,
pandq, that returns an int with the same rules used by Unixstrcmp(p,q):= 0: Blocks p and q are equal
< 0: p is less than q
> 0: p is greater than qBeware of using ordinary
strcmp()--it requires aNULLat the end of each string.Return value
0if the operation is successful.Library
SYS.LIBExample
Output from the above sample program:0. -90, 12
1. -2, 1
2. 1, 3
3. 3, -2
4. 7, 16
5. 9, 7
6. 10, 9
7. 12, 34
8. 16, -90
9. 34, 10
rad
float rad(float x);Description
Convert degrees (360 for one rotation) to radians (2
for a rotation).
Parameters
xReturn value
The radians equivalent of degree.
Library
SYS.LIBSee also
deg
rand
float rand(void);Description
Returns a uniformly distributed random number in the range 0.0
v < 1.0. Uses algorithm:
rand = (5*rand)modulo 232A default seed value is set on startup, but can be changed with the
srand()function.rand()is not reentrant.Return value
A uniformly distributed random number: 0.0
![]()
v< 1.0.Library
MATH.LIBSee also
randb, randg, srand
randb
float randb(void);Description
rand = (5*rand)modulo 232A default seed value is set on startup, but can be changed with the
srand()function.randb()is not reentrant.Return value
Returns a uniformly distributed random number: -1.0
![]()
v< 1.0.Library
MATH.LIBSee also
rand, randg, srand
randg
float randg(void);Description
Returns a gaussian-distributed random number in the range -16.0
v < 16.0 with a standard deviation of approximately 2.6. The distribution is made by adding 16 random numbers (see
rand()). This function is not task reentrant.Return value
A gaussian distributed random number: -16.0
![]()
v<16.0.Library
MATH.LIBSee also
rand, randb, srand
RdPortE
int RdPortE(unsigned int port);Description
Reads an external I/O register specified by the argument.
Parameters
portAddress of external parallel port data register.
Return value
Returns an integer, the lower 8 bits of which contain the result of reading the port specified by the argument. Upper byte contains zero.
Library
SYSIO.LIBSee also
RdPortI, BitRdPortI, WrPortI, BitWrPortI, BitRdPortE, WrPortE, BitWrPortE
RdPortI
int RdPortI(int port);Description
Reads an internal I/O port specified by the argument.
Parameters
portAddress of internal parallel port data register.
Return value
Returns an integer, the lower 8 bits of which contain the result of reading the port specified by the argument. Upper byte contains zero.
Library
SYSIO.LIBSee also
RdPortE, BitRdPortI, WrPortI, BitWrPortI, BitRdPortE, WrPortE, BitWrPortE
read_rtc
unsigned long read_rtc(void);Description
Reads the Real-time Clock (RTC) directly. Use with caution! In most cases use long variable
SEC_TIMER,which contains the same result, unless the RTC has been changed since the start of the program. If you are running the processor off the 32 kHz crystal, useread_rtc_32kHz()instead.Return value
Time in seconds since January 1, 1980 (if RTC set correctly).
Library
RTCLOCK.LIBSee also
write_rtc
read_rtc_32kHz
unsigned long read_rtc_32kHz(void);Description
Reads the real-time clock directly when the Rabbit processor is running off the 32 kHz oscillator. See
read_rtcfor more details.Return value
Time in seconds since January 1, 1980 (if RTC set correctly).
Library
RTCLOCK.LIB
readUserBlock
int readUserBlock(void *dest, int addr, int numbytes);Description
Reads a number of bytes from the user block on the primary flash to a buffer in root memory. NOTE: Portions of the user block may be used by the BIOS for your board to store values. For example, any board with an A to D converter will require the BIOS to write calibration constants to the user block. For some versions of the BL2000 and the BL2100 this memory area is 0x1C00 to 0x1FFF. See the user's manual for your particular board for more information before overwriting any part of the user block. Also, see the Rabbit 2000 Microprocessor Designer's Handbook for more information on the user block.
Parameters
destPointer to destination to copy data to.
addrAddress offset in user block to read from.
numbytesReturn value
0: Success-1: Invalid address or rangeLibrary
IDBLOCK.LIBSee also
writeUserBlock
res
void res(void *address, unsigned int bit);Description
Dynamic C may expand this call inline
Clears specified bit at memory address to 0. bit may be from 0 to 31. This is equivalent to the following expression, but more efficient:
*(long *)address &= ~(1L << bit)Parameters
addressAddress of byte containing bits 7-0
bitBit location where 0 represents the least significant bit
Library
UTIL.LIBSee also
RES
RES
void RES(void *address, unsigned int bit);Description
Dynamic C may expand this call inline.
Clears specified bit at memory address to 0. bit may be from 0 to 31. This is equivalent to the following expression, but more efficient:
*(long *)address &= ~(1L << bit)Parameters
addressAddress of byte containing bits 7-0
bitBit location where 0 represents the least significant bit
Library
UTIL.LIBSee also
res
ResetErrorLog
void ResetErrorLog();Description
This function resets the exception and restart type counts in the error log buffer header. This function is not called by default from anywhere. It should be used to initialized the error log when a board is programmed by means other than Dynamic C, cloning, the Rabbit Field Utility (RFU), or a service processor. For example, if boards are mass produced with pre-programmed flash chips, then the test program that runs on the boards should call this function.
Library
ERRORS.LIB
root2xmem
int root2xmem(unsigned long dest, void *src, unsigned len);Description
Stores
lencharacters from logical addresssrcto physical addressdest.Parameters
destsrclenReturn value
0: Success-1: Attempt to write flash memory area, nothing written-2: Source not all in rootLibrary
XMEM.LIBSee also
xalloc, xmem2root
runwatch
void runwatch();Description
Runs and updates watch expressions if Dynamic C has requested it with a Ctrl-U. Should be called periodically in user program.
Library
SYS.LIB
serCheckParity
int serCheckParity(char rx_byte, char parity);Description
This function is different from the other serial routines in that it does not specify a particular serial port. This function takes any 8-bit character and tests it for correct parity. It will return true if the parity of
rx_bytematches the parity specified. This function is useful for checking individual characters when using a 7-bit data protocol.Parameters
rx_byteThe 8 bit character being tested for parity.
parityThe character `O' for odd parity, or the character `E' for even parity.
Return value
1: Parity of the byte being tested matches the parity supplied as an argument.0: Parity of the byte does not match.Library
RS232.LIB
serXclose
void serXclose(); /* where X = A|B|C|D */Description
Disables serial port X. This function is non-reentrant.
Starting with Dynamic C version 7.25, the functions
serEclose()andserFclose()may be used with the Rabbit 3000 microprocessor.Library
RS232.LIB
serXdatabits
void serXdatabits(state); /* where X = A|B|C|D */Description
Sets the number of data bits in the serial format for this channel. Currently seven or eight bit modes are supported. A call to
serXopen()must be made before calling this function. This function is non-reentrant.Starting with Dynamic C version 7.25, the functions
serEdatabits()andserFdatabits()may be used with the Rabbit 3000 microprocessor.Parameters
stateAn integer indicating what bit mode to use. It is best to use one of the macros provided for this:
PARAM_7BITConfigures serial port to use seven bit data.
PARAM_8BITConfigures serial port to use eight bit data (default).
Library
RS232.LIB
serXflowcontrolOff
void serXflowcontrolOff(); /* where X = A|B|C|D */Description
Turns off hardware flow control for serial port X. A call to
serXopen()must be made before calling this function. This function is non-reentrant.Starting with Dynamic C version 7.25, the functions
serEflowcontrolOff()andserFflowcontrolOff()may be used with the Rabbit 3000 microprocessor.Library
RS232.LIB
serXflowcontrolOn
void serXflowcontrolOn(); /* where X = A|B|C|D */Description
Turns on hardware flow control for channel X. This enables two digital lines that handle flow control, CTS (clear to send) and RTS (ready to send). CTS is an input that will be pulled active low by the other system when it is ready to receive data. The RTS signal is an output that the system uses to indicate that it is ready to receive data; it is driven low when data can be received. A call to
serXopen()must be made before calling this function.This function is non-reentrant.
Starting with Dynamic C version 7.25, the functions
serEflowcontrolOn()andserFflowcontrolOn()may be used with the Rabbit 3000 microprocessor.If pins for the flow control lines are not explicitly defined, defaults will be used and compiler warnings will be issued. The locations of the flow control lines are specified using a set of 5 macros.
SERX_RTS_PORTData register for the parallel port that the RTS line is on. e.g. PCDR
SERA_RTS_SHADOWShadow register for the RTS line's parallel port. e.g. PCDRShadow
SERA_RTS_BITThe bit number for the RTS line
SERA_CTS_PORTData register for the parallel port that the CTS line is on
SERA_CTS_BITThe bit number for the CTS line
Library
RS232.LIB
serXgetc
int serXgetc(); /* where X = A|B|C|D */Description
Get next available character from serial port X read buffer. This function is non-reentrant.
Starting with Dynamic C version 7.25, the functions
serEgetc()andserFgetc()may be used with the Rabbit 3000 microprocessor.Return value
Success: the next character in the low byte,
0in the high byte
Failure:-1Library
RS232.LIBExample
// echoes characters
main() {
int c;
serAopen(19200);
while (1) {
if ((c = serAgetc()) != -1) {
serAputc(c);
}
}
serAclose()
}
serXgetError
int serXgetError(); /* where X = A|B|C|D */Description
Returns a byte of error flags, with bits set for any errors that occurred since the last time this function was called. Any bits set will be automatically cleared when this function is called, so a particular error will only be reported once. This function is non-reentrant.
The flags are checked with bitmasks to determine which errors occurred. Error bitmasks:
Starting with Dynamic C version 7.25, the functions
serEgetError()andserFgetError()may be used with the Rabbit 3000 microprocessor.Return value
Library
RS232.LIB
serXopen
int serXopen(long baud); /* where X = A|B|C|D */Description
Opens serial port X. This function is non-reentrant.
The user must define the buffer sizes for each port being used with the buffer size macros
XINBUFSIZEandXOUTBUFSIZE. The values must be a power of 2 minus 1, e.g.
#define XINBUFSIZE 63
#define XOUTBUFSIZE 127Defining the buffer sizes to 2n - 1 makes the circular buffer operations very efficient. If a value not equal to 2n- 1 is defined, a default of 31 is used and a compiler warning is given.
Starting with Dynamic C version 7.25, the functions
serEopen()andserFopen()may be used with the Rabbit 3000 microprocessor.Note: The alternate pins on parallel port D can be used for serial port B by defining
SERB_USEPORTDat the beginning of a program. See the section on parallel port D in the Rabbit documentation for more detail on the alternate serial port pins.Parameters
baudBits per second of data transfer. Note that the baud rate must be greater than or equal to the peripheral clock frequency ÷ 8192.
Return value
1: The baud rate achieved on the Rabbit is the same as the input baud rate. The software was able to calculate a valid divisor for the requested baud rate within 5%.
0: The baud rate achieved on the Rabbit does not match the input baud rate.Library
RS232.LIBSee also
serXgetc, serXpeek, serXputs, serXwrite, cof_serXgetc,
cof_serXgets, cof_serXread, cof_serXputc, cof_serXputs,
cof_serXwrite, serXclose
serXparity
void serXparity(int parity_mode); /* where X = A|B|C|D */Description
Sets parity mode for channel X. A call to
serXopen()must be made before calling this function.Parity generation for 8 bit data can be unusually slow due to the current method for generating high 9th bits. Whenever, a 9th high bit is needed, the UART is disabled for approximately 10 baud times to create a long stop bit that should be recognized by the receiver as a high 9th bit.
The long delay is imposed because we are using the serial port itself to handle timing for the delay. Creating a shorter delay would the require use of some other timer resource.
This function is non-reentrant.
Starting with Dynamic C version 7.25, the functions
serEparity()andserFparity()may be used with the Rabbit 3000 microprocessor.Parameters
parity_modeAn integer indicating what parity mode to use. It is best to use one of the macros provided:
- ·
PARAM_NOPARITY- Disables parity handling (default).
- ·
PARAM_OPARITY- Configures serial port to check/generate for odd parity.
- ·
PARAM_EPARITY- Configures serial port to check/generate for even parity.
- ·
PARAM_2STOP- Configures serial port to generate 2 stop bits.Library
RS232.LIB
serXpeek
int serXpeek(); /* where X = [A|B|C|D] */Description
Returns 1st character in input buffer X, without removing it from the buffer. This function is non-reentrant.
Starting with Dynamic C version 7.25, the functions
serEpeek()andserFpeek()may be used with the Rabbit 3000 microprocessor.Return value
An integer with 1st character in buffer in the low byte
-1if the buffer is emptyLibrary
RS232.LIB
serXputc
int serXputc(char c); /* where X = A|B|C|D */Description
Writes a character to serial port X write buffer. This function is non-reentrant.
Starting with Dynamic C version 7.25, the functions
serEputc()andserFputc()may be used with the Rabbit 3000 microprocessor.Parameters
cCharacter to write to serial port X write buffer.
Return value
0if buffer locked or full,1if character sent.Library
RS232.LIBExample
main() { // echoes characters
int c;
serAopen(19200);
while (1) {
if ((c = serAgetc()) != -1) {
serAputc(c);
}
}
serAclose();
}
serXputs
int serXputs(char* s); /* where X = A|B|C|D */Description
Calls
serXwrite(s, strlen(s)). This function is non-reentrant.Starting with Dynamic C version 7.25, the functions
serEputs()andserFputs()may be used with the Rabbit 3000 microprocessor.Parameters
s
NULL-terminated character string to writeReturn value
The number of characters actually sent from serial port X.
Library
RS232.LIBExample
// writes a null-terminated string of characters, repeatedly
main() {
const char s[] = "Hello Z-World";
serAopen(19200);
while (1) {
serAputs(s);
}
serAclose();
}
serXrdFlush
void serXrdFlush(); /* where X = A|B|C|D */Description
Flushes serial port X input buffer. This function is non-reentrant.
Starting with Dynamic C version 7.25, the functions
serErdFlush()andserFrdFlush()may be used with the Rabbit 3000 microprocessor.Library
RS232.LIB
serXrdFree
int serXrdFree(); /* where X = A|B|C|D */Description
Calculates the number of characters of unused data space. This function is non-reentrant.
Starting with Dynamic C version 7.25, the functions
serErdFree()andserFrdFree()may be used with the Rabbit 3000 microprocessor.Return value
The number of chars it would take to fill input buffer X.
Library
RS232.LIB
serXrdUsed
int serXrdUsed(); /* where X = A|B|C|D */Description
Calculates the number of characters ready to read from the serial port receive buffer. This function is non-reentrant.
Starting with Dynamic C version 7.25, the functions
serErdUsed()andserFrdUsed()may be used with the Rabbit 3000 microprocessor.Return value
The number of characters currently in serial port X receive buffer.
Library
RS232.LIB
serXread
int serXread(void *data, int length, unsigned long tmout);
/* where X = A|B|C|D */Description
Reads
lengthbytes from serial port X or untiltmoutmilliseconds transpires between bytes. The countdown oftmoutdoes not begin until a byte has been received. A timeout occurs immediately if there are no characters to read. This function is non-reentrant.Starting with Dynamic C version 7.25, the functions
serEread()andserFread()may be used with the Rabbit 3000 microprocessor.Parameters
dataData structure to read from serial port X
lengthtmoutMaximum wait in milliseconds for any byte from previous one
Return value
The number of bytes read from serial port X.
Library
RS232.LIBExample
// echoes a blocks of characters
main() {
int n;
char s[16];
serAopen(19200);
while (1) {
if ((n = serAread(s, 15, 20)) > 0) {
serAwrite(s, n);
}
}
serAclose();
}
serXwrFlush
void serXwrFlush(); /* where X = A|B|C|D */Description
Flushes serial port X transmit buffer. This function is non-reentrant.
Starting with Dynamic C version 7.25, the functions
serEwrFlush()andserFwrFlush()may be used with the Rabbit 3000 microprocessor.Library
RS232.LIB
serXwrFree
int serXwrfree(); /* where X = A|B|C|D */Description
Calculates the free space in the serial port transmit buffer. This function is non-reentrant.
Starting with Dynamic C version 7.25, the functions
serEwrFree()andserFwrFree()may be used with the Rabbit 3000 microprocessor.Return value
The number of characters the serial port transmit buffer can accept before becoming full.
Library
RS232.LIB
serXwrite
int serXwrite(void *data, int length); /* where X = A|B|C|D */Description
Transmits
lengthbytes to serial port X. This function is non-reentrant.Starting with Dynamic C version 7.25, the functions
serEwrite()andserFwrite()may be used with the Rabbit 3000 microprocessor.Parameters
dataData structure to write to serial port X.
lengthReturn value
The number of bytes successfully written to the serial port.
Library
RS232.LIBExample
// writes a block of characters, repeatedly
main() {
const char s[] = "Hello Z-World";
serAopen(19200);
while (1) {
serAwrite(s, strlen(s));
}
serAclose();
}
set
void set(void *address, unsigned int bit);Description
Dynamic C may expand this call inline
Sets specified bit at memory address to 1. bit may be from 0 to 31. This is equivalent to the following expression, but more efficient:
*(long *)address |= 1L << bitParameters
addressAddress of byte containing bits 7-0
bitBit location where 0 represents the least significant bit
Library
UTIL.LIBSee also
SET
SET
void SET(void *address, unsigned int bit);Description
Dynamic C may expand this call inline
Sets specified bit at memory address to 1. bit may be from 0 to 31. This is equivalent to the following expression, but more efficient:
*(long *)address |= 1L << bitParameters
addressAddress of byte containing bits 7-0
bitBit location where 0 represents the least significant bit
Library
UTIL.LIBSee also
set
set32kHzDivider
void set32kHzDivider(int setting);Description
Sets the expanded 32kHz oscillator divider for the Rabbit 3000 processor. This function does not enable running the 32kHz oscillator instead of the main clock. This function will affect the actual rate used by the processor when the 32kHz oscillator has been enabled to run by a call to
use32kHzOsc().This function is not task reentrant.
Parameter
setting32kHz divider setting. The following are valid:
- ·
OSC32DIV_1- don't divide 32kHz oscillator
- ·
OSC32DIV_2- divide 32kHz oscillator by two
- ·
OSC32DIV_4- divide 32kHz oscillator by four
- ·
OSC32DIV_8- divide 32kHz oscillator by eight
- ·
OSC32DIV_16- divide 32kHz oscillator by sixteenLibrary
SYS.LIBSee Also
useClockDivider, useClockDivider3000, useMainOsc, use32kHzOsc
setClockModulation
void setClockModulation(int setting);Description
Changes the setting of the Rabbit 3000 CPU clock moduation. Calling this function will force a 500 clock delay before the setting is changed to ensure that the previous moduation setting has cleared before the next one is set. See the Rabbit 3000 Microprocessor User's Manual for more details about clock modulation for EMI reduction.
Parameter
settingClock modulation setting. Allowed values are:
- · 0 = no modulation
- · 1 = weak modulation
- · 2 = strong modulation
Library
SYS.LIB
setjmp
int setjmp(jmp_buf env);Description
Store the PC (program counter), SP (stack pointer) and other information about the current state into
env. The saved information can be restored by executinglongjmp().switch (setjmp(e)) {
case 0: // first time
f(); // try to execute f(), may call longjmp()
break; // if we get here, f() was successful
case 1: // to get here, f() called longjmp()/* do exception handling */break;
case 2: // like above, but different exception code
...
}
f() {
g()
...
}
g() {
...
longjmp(e,2); // exception code 2, jump to setjmp()statement,
// setjmp() returns 2, so execute
// case 2 in the switch statement
}Parameters
envInformation about the current state
Return value
Returns zero if it is executed. After
longjmp()is executed, the program counter, stack pointer and etc. are restored to the state whensetjmp()was executed the first time. However, this timesetjmp()returns whatever value is specified by thelongjmp()statement.Library
SYS.LIBSee also
longjmp
SetVectExtern2000
unsigned SetVectExtern2000(int priority, void *isr);Description
Sets up the external interrupt table vectors for external interrupts 0 and 1. This function is presently used for Rabbit 2000 microprocessors because of the way they handle interrupts. Once this function is called, both external interrupts 0 and 1 must be enabled with the same priority level. The priority level should be set higher than all other interrupts currently running. (All system interrupts in the BIOS run at interrupt priority 1.) The interrupt priority is set via the control register I0CR for external interrupt 0 and I1CR for external interrupt 1.
The actual priority used by the interrupt service routine (ISR) is passed to this function.
Parameters
priorityPriority the ISR should run at. Valid values are 1, 2 or 3.
isrISR handler address. Must be a root address.
Return value
Address of vector table entry, or zero if
priorityis not valid.Library
SYS.LIBSee also
GetVectExtern2000, SetVectIntern, GetVectIntern
SetVectExtern3000
unsigned SetVectExtern3000(int interruptNum, void *isr);DESCRIPTION
Function to set one of the external interrupt jump table entries for the Rabbit 3000 CPU. All Rabbit interrupts use jump vectors. See
SetVectIntern()for more information.Parameters
interruptNumExternal interrupt number. 0 and 1 are the only valid values.
isrISR handler address. Must be a root address.
Return Value
Library
SYS.LIBSee Also
GetVectExtern3000, SetVectIntern, GetVectIntern
SetVectIntern
unsigned SetVectIntern(int vectNum, void *isr);Description
Sets an internal interrupt table entry. All Rabbit interrupts use jump vectors. This function writes a
jpinstruction (0xC3) followed by the 16 bit ISR address to the appropriate location in the vector table. The location in RAM of the vector table is determined and set by the BIOS automatically at startup. The start of the table is always on a 0x100 boundary.It is perfectly permissible to have ISRs in xmem and do long jumps to them from the vector table. It is even possible to place the entire body of the ISR in the vector table if it is 16 bytes long or less, but this function only sets up jumps to 16 bit addresses.
The following table shows the
vectNumargument that should be used for each peripheral or RST. The offset into the vector table is also shown. The following vectors are for the Rabbit 2000 and 3000.
System Management
(periodic interrupt)RST 10 instruction RST 38 instruction Slave Port Timer A Timer B Serial Port A Serial Port B Serial Port C Serial Port D The following vectors are for the Rabbit 3000 processor only:
SetVectIntern (continued)
The following three RSTs are included for completeness, but should not be set by the user normally as they are used by Dynamic C
Parameters
vectNumInterrupt number. See the above table for valid values.
isrISR handler address. Must be a root address.
Return value
Address of vector table entry, or zero if
vectNumis not valid.Library
SYS.LIBSee also
GetVectExtern2000, SetVectExtern2000, GetVectIntern
sin
float sin(float x);Description
Parameters
xReturn value
Library
MATH.LIBSee also
sinh, asin, cos, tan
sinh
float sinh(float x);Description
Computes the hyperbolic sine of
x.Parameters
xReturn value
If
x> 89.8 (approx.), the function returns INF and signals a range error. Ifx< -89.8 (approx.), the function returns -INF and signals a range error.Library
MATH.LIBSee also
sin, asin, cosh, tanh
SPIinit
void SPIinit ();Description
Initialize the SPI port parameters for a serial interface only. This function does nothing for a parallel interface. A description of the values that the user may define before the
#use SPI.LIBstatement is found at the top of the libraryLib\Spi\Spi.lib.Library
SPI.LIBSee also
SPIRead, SPIWrite, SPIWrRd
SPIRead
void SPIRead ( void *DestAddr, int ByteCount );Description
Reads a block of bytes from the SPI port. Note: the device Chip Select must already be active. The variable
SPIxorneeds to be set to either 0x00 or 0xFF depending on whether or not the received signal needs to be inverted. Most applications will not need inversion.SPIinit()sets the value ofSPIxorto 0x00.Parameters
DestAddrByteCountReturn value
Library
SPI.LIBSee also
SPIinit, SPIWrite, SPIWrRd
SPIWrite
int SPIWrite ( void *SrcAddr, int ByteCount );Description
Write a block of bytes to the SPI port. Note: the device Chip Select must already be active.
Parameters
SrcAddrByteCountReturn value
Library
SPI.LIBSee also
SPIinit, SPIRead, SPIWrRd
SPIWrRd
void SPIWrRd ( void *SrcAddr, void *DstAddr, int ByteCount );Description
Read and Write a block of bytes from/to the SPI port. The device Chip Select must already be active
Parameters
SrcAddrDstAddrByteCountNumber of bytes to read/write. The maximum value is 255 bytes. This limit is not checked! The receive buffer MUST be at least as large as the number of bytes!
Return value
Library
SPI.LIBSee Also
SPIinit, SPIRead, SPIWrite
sprintf
int sprintf(char *buffer, char *format, ...);Description
This function takes a string (pointed to by
format), arguments of the format, and outputs the formatted string tobuffer(pointed to bybuffer). The user should make sure that:
there are enough arguments after
formatto fill in the format parameters in the format stringthe types of arguments after
formatmatch the format fields informatthe buffer is large enough to hold the longest possible formatted string
The following is a short list of possible format parameters in the format string. For more details, refer to any C language book.
%d decimal integer (expects type
int)
%u decimal unsigned integer (expects typeunsignedint)
%x hexadecimal integer (expects typesignedintorunsignedint)
%s a string (not interpreted, expects type (char*))
%f a float (expects typefloat)For example,
sprintf(buffer,"%s=%x","variable x",256);should put the stringvariable x=100intobuffer.This function can be called by processes of different priorities.
Parameters
bufferResult string of the formatted string.
format...Return Value
Library
STDIO.LIBSee also
printf
sqrt
float sqrt(float x);Description
Calculate the square root of
x.Parameters
xReturn value
Library
MATH.LIBSee also
exp, pow, pow10
srand
void srand(unsigned long seed)Description
Sets the seed value for the
rand()function.Parameter
seedLibrary
MATH.LIBSee also
rand, randb, randg
strcat
char *strcat(char *dst, char *src);Description
Appends one string to another.
Parameters
dstPointer to location to destination string.
srcPointer to location to source string.
Return value
Pointer to destination string.
Library
STRING.LIBSee also
strncat
strchr
char *strchr(char *src, char ch);Description
Scans a string for the first occurrence of a given character.
Parameters
srcchReturn value
Pointer to the first occurrence of
chinsrc.NULLifchis not found.Library
STRING.LIBSee also
strrchr, strtok
strcmp
int strcmp(char *str1, char *str2)Description
Performs unsigned character by character comparison of two
NULL-terminated strings.Parameters
str1str2Return value
<0:str1is less thanstr2because
character instr1is less than corresponding character instr2, orstr1is shorter than but otherwise identical tostr2.
>0:str1is greater thanstr2because
character instr1is greater than corresponding character instr2, orstr2is shorter than but otherwise identical tostr1.Library
STRING.LIBSee also
strncmp, strcmpi, strncmpi
strcmpi
int *strcmpi(char *str1, char *str2);Description
Performs case-insensitive unsigned character by character comparison of two
NULL-terminated strings.Parameters
str1str2Return value
<0:str1is less thanstr2because
character instr1is less than corresponding character instr2, orstr1is shorter than but otherwise identical tostr2.
>0:str1is greater thanstr2because
character instr1is greater than corresponding character instr2, orstr2is shorter than but otherwise identical tostr1.Library
STRING.LIBSee also
strncmpi, strncmp, strcmp
strcpy
char *strcpy(char *dst, char *src);Description
Copies one string into another string including the
NULLterminator.Parameters
dstPointer to location to receive string.
srcPointer to location to supply string.
Return value
Pointer to destination string.
Library
STRING.LIBSee also
strncpy
strcspn
unsigned int strcspn(char *s1, char *s2);Description
Scans a string for the occurrence of any of the characters in another string.
Parameters
s1s2Return value
Returns the position (less one) of the first occurrence of a character in
s1that matches any character ins2.Library
STRING.LIBSee also
strchr, strrchr, strtok
strlen
int strlen(char *s);Description
Calculate the length of a string.
Parameters
sReturn value
Library
STRING.LIB
strncat
char *strncat(char *dst, char *src, unsigned int n);Description
Appends one string to another up to and including the
NULLterminator or untilncharacters are transferred, followed by aNULLterminator.Parameters
dstPointer to location to receive string.
srcPointer to location to supply string.
nMaximum number of bytes to copy. If equal to zero, this function has no effect.
Return value
Pointer to destination string.
Library
STRING.LIBSee also
strcat
strncmp
int strncmp(char *str1, char *str2, n)Description
Performs unsigned character by character comparison of two strings of length
n.Parameters
str1str2nMaximum number of bytes to compare. If zero, both strings are considered equal.
Return value
<0:str1is less thanstr2because
char instr1is less than corresponding char instr2.
>0:str1is greater thanstr2because
char instr1is greater than corresponding char instr2.Library
STRING.LIBSee also
strcmp, strcmpi, strncmpi
strncmpi
int strncmpi(char *str1, char *str2, unsigned n)Description
Performs case-insensitive unsigned character by character comparison of two strings of length
n.Parameters
str1str2nMaximum number of bytes to compare, if zero then strings are considered equal
Return value
<0:str1is less thanstr2because
char instr1is less than corresponding char instr2.
>0:str1is greater thanstr2because
char instr1is greater than corresponding char instr2.Library
STRING.LIBSee also
strcmpi, strcmp, strncmp
strncpy
char *strncpy(char *dst, char *src, unsigned int n);Description
Copies a given number of characters from one string to another and padding with
NULLcharacters or truncating as necessary.Parameters
dstPointer to location to receive string.
srcPointer to location to supply string.
nMaximum number of bytes to copy. If equal to zero, this function has no effect.
Return value
Pointer to destination string.
Library
STRING.LIBSee also
strcpy
strpbrk
char *strpbrk(char *s1, char *s2);Description
Scans a string for the first occurrence of any character from another string.
Parameters
s1s2Return value
Pointer pointing to the first occurrence of a character contained in
s2ins1. ReturnsNULLif not found.Library
STRING.LIBSee also
strchr, strrchr, strtok
strrchr
char *strrchr(char *s, int c);Description
Similar to
strchr, except this function searches backward from the end ofsto the beginning.Parameters
scReturn value
Pointer to last occurrence of
cins. Ifcis not found ins, returnNULL.Library
STRING.LIBSee also
strchr, strcspn, strtok
strspn
size_t strspn(char *src, char *brk);Description
Scans a string for the first segment in
srccontaining only characters specified inbrk.Parameters
srcbrkReturn value
Returns the length of the segment.
Library
STRING.LIB
strstr
char *strstr(char *s1, char *s2);Description
Finds a substring specified by
s2in strings1.Parameters
s1s2Return value
Pointer pointing to the first occurrence of substring
s2ins1. ReturnsNULLifs2is not found ins1.Library
STRING.LIBSee also
strcspn, strrchr, strtok
strtod
float strtod(char *s, char **tailptr);Description
ANSI string to float conversion.
Parameters
stailptrPointer to a pointer of character. The next conversion may resume at the location specified by
*tailptr.Return value
Library
STRING.LIBSee also
atof
strtok
char *strtok(char *src, char *brk);Description
Scans
srcfor tokens separated by delimiter characters specified inbrk.First call with non-
NULLforsrc. Subsequent calls withNULLforsrccontinue to search tokens in the string. If a token is found (i.e., delineators found), replace the first delimiter insrcwith aNULLterminator so thatsrcpoints to a properNULL-terminated token.Parameters
srcString to be scanned, must be in SRAM, cannot be a constant. In contrast, strings initialized when they are declared are stored in Flash Memory, and are treated as constants.
brkReturn value
Pointer to a token. If no delimiter (therefore no token) is found, returns
NULL.Library
STRING.LIBSee also
strchr, strrchr, strstr, strcspn
strtol
long strtol(char *sptr, char **tailptr, int base);Description
ANSI string to long conversion.
Parameters
sptrtailptrAssigned the last position of the conversion. The next conversion may resume at the location specified by
*tailptr.baseIndicates the radix of conversion.
Return value
Library
STRING.LIBSee also
atoi, atol
_sysIsSoftReset
void _sysIsSoftReset();Description
This function determines whether this restart of the board is due to a software reset from Dynamic C or a call to
forceReset(). If it was a soft reset, this function then does the following:Calls
_prot_init()to initialize the protected variable mechanisms. It is up to the user to initialize protected variables.Calls
sysResetChain(). The user my attach functions to this chain to perform additional startup actions (for example, initializing protected variables). If a soft reset did not take place, this function calls_prot_recover()to recover any protected variables.Library
SYS.LIBSee Also
chkHardReset, chkSoftReset, chkWDTO
sysResetChain
void sysResetChain ( void );Description
This is a function chain that should be used to initialize protected variables. By default, it's empty.
Library
SYS.LIB
tan
float tan(float x);Description
Compute the tangent of the argument.
Parameters
xReturn value
Returns the tangent of
x, where -8 × PI![]()
x+8 × PI. If
xis out of bounds, the function returns 0 and signals a domain error. If the value ofxis too close to a multiple of 90° (PI/2) the function returns INF and signals a range error.Library
MATH.LIBSee also
atan, cos, sin, tanh
tanh
float tanh(float x);Description
Computes the hyperbolic tangent of argument.
Parameters
xReturn value
Returns the hyperbolic tangent of
x. Ifx> 49.9 (approx.), the function returns INF and signals a range error. Ifx< -49.9 (approx.), the function returns -INF and signals a range error.Library
MATH.LIBSee also
atan, cosh, sinh, tan
tm_rd
int tm_rd(struct tm *t);Description
Reads the current system time from
SEC_TIMERinto the structuret. WARNING: The variableSEC_TIMERis initialized when a program is started. If you change the Real Time Clock (RTC), this variable will not be updated until you restart a program, and thetm_rdfunction will not return the time that the RTC has been reset to. Theread_rtcfunction will read the actual RTC and can be used if necessary.Parameters
tAddress of structure to store time data
struct tm {
char tm_sec; // seconds 0-59
char tm_min; // 0-59
char tm_hour; // 0-23
char tm_mday; // 1-31
char tm_mon; // 1-12
char tm_year; // 80-147 (1980-2047)
char tm_wday; // 0-6 0==Sunday
};Return value
0: Successful.-1: Clock read failed.Library
RTCLOCK.LIBSee also
mktm, mktime, tm_wr
tm_wr
int tm_wr(struct tm *t);Description
Sets the system time from a
tmstruct. It is important to note that althoughtm_rd()reads theSEC_TIMERvariable, not the RTC,tm_wr()writes to the RTC directly, andSEC_TIMERis not changed until the program is restarted. The reason for this is so that theDelaySec()function continues to work correctly after setting the system time. To maketm_rd()match the new time written to the RTC without restarting the program, the following should be done:
tm_wr(tm);
SEC_TIMER = mktime(tm);But this could cause problems if a
waitfor(DelaySec(n))is pending completion in a cooperative multitasking program or if theSEC_TIMERvariable is being used in another way the user, so user beware.Parameters
tPointer to structure to read date and time from.
struct tm {
char tm_sec; // seconds 0-59
char tm_min; // 0-59
char tm_hour; // 0-23
char tm_mday; // 1-31
char tm_mon; // 1-12
char tm_year; // 80-147 (1980-2047)
char tm_wday; // 0-6 0==Sunday
};Return value
Library
RTCLOCK.LIBSee also
mktm, mktime, tm_rd
tolower
int tolower(int c);Description
Convert alphabetic character to lower case.
Parameters
cReturn value
Lower case alphabetic character.
Library
STRING.LIBSee also
toupper, isupper, islower
toupper
int toupper(int c);Description
Convert alphabetic character to uppercase.
Parameters
cReturn value
Upper case alphabetic character.
Library
STRING.LIBSee also
tolower, isupper, islower
updateTimers
void updateTimers();Description
Updates the values of
TICK_TIMER,MS_TIMER, andSEC_TIMERwhile running off the 32 kHz oscillator. Since the periodic interrupt is disabled when running at 32 kHz, these values will not updated unless this function is called.Library
SYS.LIBSee also
useMainOsc, use32kHzOsc
use32kHzOsc
void use32kHzOsc();Description
Sets the Rabbit processor to use the 32kHz real-time clock oscillator for both the CPU and peripheral clock, and shuts off the main oscillator. If this is already set, there is no effect. This mode should provide greatly reduced power consumption. Serial communications will be lost since typical baud rates cannot be made from a 32kHz clock. Also note that this function disables the periodic interrupt, so
waitforand related statements will not work properly (although costatements in general will still work). In addition, the values inTICK_TIMER,MS_TIMER, andSEC_TIMERwill not be updated unless you call the functionupdateTimers()frequently in your code. In addition, you will need to callhitwd()periodically to hit the hardware watchdog timer since the periodic interrupt normally handles that, or disable the watchdog timer before calling this function. The watchdog can be disabled withDisable_HW_WDT().
use32kHzOsc()is not task reentrant.Library
SYS.LIBSee also
useMainOsc, useClockDivider, updateTimers
useClockDivider
void useClockDivider();Description
Sets the Rabbit processor to use the main oscillator divided by 8 for the CPU (but not the peripheral clock). If this is already set, there is no effect. Because the peripheral clock is not affected, serial communications should still work. This function also enables the periodic interrupt in case it was disabled by a call to
use32kHzOsc(). This function is not task reentrant.Library
SYS.LIBSee also
useMainOsc, use32kHzOsc
useClockDivider3000
void useClockDivider3000(int setting);Description
Sets the expanded clock divider options for the Rabbit 3000 processor. This function will also affect the peripheral clock--use
useClockDivider()to divide the processor clock by eight but not affect the peripheral clock. Target communications will be lost after changing this setting because of the baud rate change. This function also enables the periodic interrupt in case it was disabled by a call touser32kHzOsc().This function is not task reentrant.
Parameter
settingDivider setting. The following are valid:
- ·
CLKDIV_2- divide main processor clock by two
- ·
CLKDIV_4- divide main processor clock by four
- ·
CLKDIV_6- divide main processor clock by six
- ·
CLKDIV_8- divide main processor clock by eightReturn Value
Library
SYS.LIBSee Also
useClockDivider, useMainOsc, use32kHzOsc, set32kHzDivider
useMainOsc
void useMainOsc();Description
Sets the Rabbit processor to use the main oscillator for both the CPU and peripheral clock. If this is already set, there is no effect. This function also enables the periodic interrupt in case it was disabled by a call to
use32kHzOsc(), and updates theTICK_TIMER,MS_TIMER, andSEC_TIMERvariables from the real-time clock. This function is not task reentrant.Library
sys.libSee also
use32kHzOsc, useClockDivider
utoa
char *utoa(unsigned value, char *buf);Description
Places up to 5 digit character string at
*bufrepresenting value of unsigned number. Suppresses leading zeros, but leaves one zero digit for value = 0. Max = 65535. 73 program bytes.Parameters
valuebufCharacter string of converted number
Return value
Pointer to
NULLat end of string.Library
STDIO.LIBSee also
itoa, htoa, ltoa
VdGetFreeWd
int VdGetFreeWd(char count);Description
Returns a free virtual watchdog and initializes that watchdog so that the virtual driver begins counting it down from
count. The number of virtual watchdogs available is determined byN_WATCHDOG, which is 5 by default, but can be defined by the user:#define N_WATCHDOG 10. The virtual driver is called every 0.00048828125 sec. On every 128th call to it (62.5 ms), the virtual watchdogs are counted down. If any virtual watchdog reaches 0, this is a fatal error. Once a virtual watchdog is active, it should reset periodically with a call toVdHitWdto prevent this. The count is decremented, tested and, if 0, a fatal error occurs.Parameters
countReturn value
Integer id number of an unused virtual watchdog timer.
Library
VDRIVER.LIB
VdHitWd
int VdHitWd(int ndog);Description
Resets virtual watchdog counter to N counts where N is the argument to the call to
VdGetFreeWd()that obtained the virtual watchdogndog. The virtual driver counts down watchdogs every 62.5 ms. If a virtual watchdog reaches 0, this is a fatal error. Once a virtual watchdog is active it should reset periodically with a call toVdHitWd()to prevent this. If count = 2 theVdHitWd()will need to be called again for virtual watchdogndogwithin 62.5 ms. If count = 255,VdHitWd()will need to be called again for virtual watchdogndogwithin 15.9375 seconds.Parameters
ndogId of virtual watchdog returned by
VdGetFreeWd()Library
VDRIVER.LIB
VdInit
void VdInit(void);Description
Initializes the Virtual Driver for all Rabbit boards. Supports
DelayMs(),DelaySec(),DelayTick().VdInit()is called by the BIOS unless it has been disabled.Library
VDRIVER.LIB
VdReleaseWd
int VdReleaseWd(int ndog);Description
Deactivates a virtual watchdog and makes it available for
VdGetFreeWd().Parameters
ndogHandle returned by
VdGetFreeWd()Return value
0:ndogout of range.1: Success.Library
VDRIVER.LIBExample
WriteFlash2
int WriteFlash2(unsigned long flashDst, void* rootSrc, int len);Description
Write
lenbytes fromrootSrcto physical addressflashDston the 2nd flash device. The source must be in root. TheflashDstaddress must be in the range 0x00040000-0x0007FFFF. (256kb is the maximum size visible on the second flash by this function).This function is not reentrant.
NOTE This function should NOT be used if you are using the second flash device for a flash file system. This function is extremely dangerous when used with large-sector flash. Don't do it. Parameters
flashDstPhysical address of the flash destination
rootSrclenReturn value
0: Success.-1: Attempt to write non-2nd flash area, nothing written.-2:rootsrcnot in root.-3: Time out while writing flash.-4: Attempt to write to ID block-5: Sector erase needed; write abortedLibrary
XMEM.LIB
write_rtc
void write_rtc(unsigned long int time);Description
Writes a 32 bit seconds value to the RTC, zeros other bits. This function does not stop or delay periodic interrupt. It does not affect the
SEC_TIMERorMS_TIMERvariables.Parameters
time32-bit value representing the number of seconds since January 1, 1980.
Library
RTCLOCK.CSee also
read_rtc
writeUserBlock
int writeUserBlock(int addr, void *source, int numbytes);Description
Z-World boards have a System ID Block located on the primary flash. (See the Rabbit 2000 Microprocessor Designer's Handbook for more information on the System ID Block.) Version 2 and later of this ID block has a pointer to a User ID Block: a place intended for storing calibration constants, passwords, and other non-volatile data.
The User ID Block is recommended for storing all non-file data. This is where calibration constants are stored for boards with analog I/O. Space here is limited to as small as
(8K - sizeof(SysIDBlock))bytes, or less, if there are calibration constants.
writeUserBlock()writes a number of bytes from root memory to the user block. This block is protected from normal writes to the flash device and can only be accessed through this function.
NOTE See the manual for your particular board for more information before overwriting any part of the user block. If the version of the System ID block doesn't support the User ID block, or no System ID block is present, then 8K bytes starting 16K bytes from the top of the primary flash are designated the User ID block area. However, to prevent errors arisng from incompatible large sector configuartions, this will only work if the flash type is small sector. Z-World manufactured boards with large sector flash will have valid System and User ID blocks, so this should not be problem on Z-World boards.
If users create boards with large sector flash, they must install System ID blocks version 2 or greater to use or modify this function.
Parameters
addrAddress offset in user block to write to.
sourcePointer to source to copy data from.
numbytesReturn value
0: Successful.-1: Invalid address or range.Library
IDBLOCK.LIBSee also
readUserBlock
WrPortE
void WrPortE(unsigned int port, char *portshadow, int data_value);Description
Writes an external I/O register with 8 bits and updates shadow for that register. The variable names must be of the form
portandportshadowfor the most efficient operation. ANULLpointer may be substituted if shadow support is not desired or needed.Parameters
portAddress of external data register.
portshadowReference pointer to a variable shadowing the register data. Substitute with
NULLpointer (or 0) if shadowing is not required.data_valueValue to be written to the data register
Library
SYSIO.LIBSee also
RdPortI, BitRdPortI, WrPortI, BitWrPortI, RdPortE, BitRdPortE, BitWrPortE
WrPortI
void WrPortI(int port, char *portshadow, int data_value);Description
Writes an internal I/O register with 8 bits and updates shadow for that register.
Parameters
portportshadowReference pointer to a variable shadowing the register data. Substitute with
NULLpointer (or 0) if shadowing is not required.data_valueValue to be written to the data register
Library
SYSIO.LIBSee also
RdPortI, BitRdPortI, BitRdPortE, BitWrPortI, RdPortE, WrPortE, BitWrPortE
xalloc
long xalloc(long sz)Description
Allocates the specified number of bytes in extended memory.
Parameters
szReturn value
The 20-bit physical address of the allocated data: Success.
0: Failure.Note: This return value cannot be used with pointer arithmetic.
Library
STACK.LIBSee also
root2xmem, xmem2root
xmem2root
int xmem2root(void *dest, unsigned long int src, unsigned int len);Description
Stores
lencharacters from physical addresssrcto logical addressdest.Parameters
destsrclenReturn value
0: Success.-1: Attempt to write flash memory area, nothing written.-2: Destination not all in root.Library
XMEM.LIBSee also
root2xmem, xalloc
xmem2xmem
int xmem2xmem(unsigned long dest, unsigned long src, unsigned len);Description
Stores
lencharacters from physical addresssrcto physical addressdest.Parameters
destPhysical address of destination
srcPhysical address of source data
lenLength of source data in bytes
Return value
0: Success.-1: Attempt to write Flash Memory area, nothing written.Library
XMEM.LIB
| Z-World http://www.zworld.com Voice: (530) 757-3737 FAX: (530) 757-3792 sales@zworld.com |