0% found this document useful (0 votes)
1K views103 pages

Embedded C Programming and The ATMEL AVR 2nd Edition

The document provides a reference for library functions available in CodeVisionAVR. It begins with an introduction to library functions and how they are called from code using header files. It then lists the library functions grouped by their header file names, followed by detailed descriptions and examples of each function in alphabetical order.

Uploaded by

LSLLSL
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views103 pages

Embedded C Programming and The ATMEL AVR 2nd Edition

The document provides a reference for library functions available in CodeVisionAVR. It begins with an introduction to library functions and how they are called from code using header files. It then lists the library functions grouped by their header file names, followed by detailed descriptions and examples of each function in alphabetical order.

Uploaded by

LSLLSL
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 103

APPENDIX Librar y Functions Reference

INTRODUCTION Much of the programming power and convenience of the C language lies in its built- in or librar! functions" #hese are routines that accomplish man! of the more common tas$s that face a C programmer" As with all C functions !ou call the librar! functions from !our code b! using the function name and either passing values to the function or receiving the values returned b! the function" In order to ma$e use of the functions the programmer needs to $now what parameters the function is e%pecting to be passed to it and the nature of an! values returned from it" #his information is made clear b! the protot!pe for the function" #he function protot!pes are contained in a set of header files that the programmer &includes' in the code" #here are man! librar! functions available in most C compilers gathered into groups b! function" #his grouping avoids having to include a whole host of unneeded func- tion protot!pes in ever! program" (or e%ample the function protot!pes for the group of routines concerned with the standard input and output routines are contained in a header file called stdio"h" If programmers wish to use some of these functions the! would put the following statement into the beginning of their code)
#include <stdio.h>

*ith the header file included the functions concerned with standard I+, such as the printf function -referred to in earlier chapters. are made available to the programmer" #his reference section describes each of the librar! functions available in Code/isionA/0" A comprehensive list grouped b! their header file names is followed b! a detailed description and e%ample of each function in alphabetical order"

121

34

FUNCTIONS LISTED BY LIBRARY FILE bcd"h


unsigned char bcd2bin(unsigned char n); unsigned char bin2bcd(unsigned char n);

ct!pe"h
unsigned char isalnum(char c); unsigned char isalpha(char c); unsigned char isascii(char c); unsigned char iscntrl(char c); unsigned char isdigit(char c); unsigned char islower(char c); unsigned char isprint(char c); unsigned char ispunct(char c); unsigned char isspace(char c); unsigned char isupper(char c); unsigned char isxdigit(char c); unsigned char toint(char c); char tolower(char c); char toupper(char c); char toascii(char c);

dela!"h gra!"h void delay_ms(unsigned int n);


unsigned unsigned unsigned unsigned unsigned unsigned char gray2binc(unsigned char n); int gray2bin(unsigned int n); long gray2binl(unsigned long n); char bin2grayc(unsigned char n); int bin2gray(unsigned int n); long bin2grayl(unsigned long n); void delay_us(unsigned int n);

math"h

unsigned char cabs(signed char x); unsigned int abs(int x); unsigned long labs(long x); loat abs( loat x); signed char cmax(signed char a!signed char b); int max(int a!int b); long lmax(long a!long b); loat max( loat a! loat b); signed char cmin(signed char a!signed char b); int min(int a!int b); long lmin(long a!long b); loat min( loat a! loat b);

signed char csign(signed char x); signed char sign(int x); signed char lsign(long x); signed char sign( loat x); unsigned char is"rt(unsigned int x); unsigned int ls"rt(unsigned long x); loat s"rt( loat x); loat loor( loat x); loat ceil( loat x); loat mod( loat x! loat y); loat mod ( loat x! loat #ipart); loat ldexp( loat x!int expon); loat rexp( loat x!int #expon); loat exp( loat x); loat log( loat x); loat log$%( loat x); loat pow( loat x! loat y); loat sin( loat x); loat cos( loat x); loat tan( loat x); loat sinh( loat x); loat cosh( loat x); loat tanh( loat x); loat asin( loat x); loat acos( loat x); loat atan( loat x); loat atan2( loat y! loat x);

mem"h
void po&eb(unsigned int addr!unsigned char data); void po&ew(unsigned int addr!unsigned int data); unsigned char pee&b(unsigned int addr); unsigned int pee&w(unsigned int addr);

sleep"h
void void void void void void void sleep_enable(void); sleep_disable(void); idle(void); powerdown(void); powersave(void); standby(void); extended_standby(void);

spi"h
unsigned char spi(unsigned char data);

stdio"h
char getchar(void); void putchar(char c); void puts(char #str); void puts (char lash #str); char #gets(char #str!unsigned int len); void print (char lash # mtstr); void sprint (char #str! char lash # mtstr); signed char scan (char lash # mtstr); signed char sscan (char #str! char lash # mtstr); void vprint (char lash # mtstr! va_list argptr); void vsprint (char #str! char lash # mtstr! val_list argptr);

stdlib"h
int atoi(char #str); long atol(char #str); loat ato (char #str); void itoa(int n!char #str); void ltoa(long int n!char #str); void toa( loat n!unsigned char decimals!char #str); void toe( loat n!unsigned char decimals!char #str); void srand(int seed); int rand(void); void #malloc(unsigned int si'e) void #calloc(unsigned int num! unsigned int si'e) void #realloc(void #ptr! unsigned int si'e) void ree(void #ptr)

string"h
char #strcat(char #str$!char #str2); char #strcat (char #str$!char lash #str2); char #strchr(char #str!char c); signed char strcmp(char #str$!char #str2); signed char strcmp (char #str$!char lash #str2); char #strcpy(char #dest!char #src); char #strcpy (char #dest!char lash #src); unsigned char strcspn(char #str!char #set); unsigned char strcspn (char #str!char lash #set); unsigned int strlen(char #str); unsigned int strlen (char lash #str); char #strncat(char #str$!char #str2!unsigned char n); char #strncat (char #str$!char lash #str2!unsigned char n); signed char strncmp(char #str$!char #str2!unsigned char n); signed char strncmp (char #str$!char lash #str2!unsigned char n); char #strncpy(char #dest!char #src!unsigned char n); char #strncpy (char #dest!char lash #src!unsigned char n);

char #strpbr&(char #str!char #set); char #strpbr& (char #str!char lash #set); char strpos(char #str!char c); char #strrchr(char #str!char c); char #strrpbr&(char #str!char #set); char #strrpbr& (char #str!char lash #set); signed char strrpos(char #str!char c); char #strstr(char #str$!char #str2); char #strstr (char #str$!char lash #str2); unsigned char strspn(char #str!char #set); unsigned char strspn (char #str!char lash #set); char #strto&(char #str$!char lash #str2); void #memccpy(void #dest!void #src!char c!unsigned n); void #memchr(void #bu !unsigned char c!unsigned n); signed char memcmp(void #bu $!void #bu 2!unsigned n); signed char memcmp (void #bu $!void lash #bu 2!unsigned n); void #memcpy(void #dest!void #src!unsigned n); void #memcpy (void #dest!void lash #src!unsigned n); void #memmove(void #dest!void #src!unsigned n); void #memset(void #bu !unsigned char c!unsigned n);

abs 5include 6math"h7 unsigned int abs-int %.8 unsigned char cabs-signed char %.8 unsigned long labs-long %.8 float fabs-float %.8 #he abs function returns the absolute value of the integer x. #he cabs, labs, and fabs functions return the absolute value of the signed char long and float variable x as an unsigned char unsigned long and float value respectivel!" 0eturns) Absolute value of x si9ed according to the function called
#include <math.h> void main() ( unsigned int int_pos_val; unsigned long long_pos_val; )) get absolute value o int_pos_val * abs(+$,-./); an integer

)) get absolute value o a long long_pos_val * labs(+$2-%%%); while($) ( 0 0

0esults)
int_pos_val * $,-./ long_pos_val * $2-%%%

acos 5include 6math"h7 float acos-float %.8 #he acos function calculates the arc cosine of the floating point number x. #he result is in the range of :;+< to ;+<" #he variable x must be in the range of := to =" 0eturns) acos-%. in the range of :;+< to ;+< where x is in the range of := to =
#include <math.h> void main() ( loat new_val; new_val * acos(%.1.-); while($) ( 0 0

0esults) new>val ? @"2@2 asin 5include 6math"h7 float asin-float %.8 #he asin function calculates the arc sine of the floating point number x. #he result is in the range of :;+< to ;+<" #he variable x must be in the range of := to =" 0eturns) asin-%. in the range of :;+< to ;+< where x is in the range of := to =
#include <math.h> void main()

( loat new_val; new_val * asin(%.1.-); while($) ( 0 0

0esults) new>val ? ="@A2 atan 5include 6math"h7 float atan-float %.8 #he atan function calculates the arc tangent of the floating point number x. #he result is in the range of :;+< to ;+<" 0eturns) atan-%. in the range of :;+< to ;+<
#include <math.h> void main() ( loat new_val; new_val * atan($.$/-); while($) ( 0 0

0esults) new>val ? @"42< atan2 5include 6math"h7 float atan<-float ! float %.8 #he atan2 function calculates the arc tangent of the floating point numbers y/x. #he result is in the range of :; to ;" 0eturns) atan-!+%. in the range of :; to ;
#include <math.h> void main()

( loat new_val; new_val * atan2(2.2/! -.$2); while($) ( 0 0

0esults) new>val ? @"B<4 atof, atoi, ato 5include 6stdlib"h7 float atof-char Cstr.8 int atoi-char Cstr.8 long atol-char Cstr.8 #he atof function converts the ADCII character string pointed to b! str to its floating point eEuivalent" #he atoi and atol functions convert the string to an integer or long integer re- spectivel!" All three functions s$ip leading white space characters" Numbers ma! also be preceded b! F and : signs" /alid numeric characters are the digits 0 through 9. #he function atof also accepts the decimal point as a valid numeric character" ,nce a non:white space character is encountered the conversion to a numeric eEuivalent starts" #he conversion stops when the first non-numeric character is encountered" If no numeric characters are found the functions return 9ero" All three functions return signed values" 0eturns)
G atof atoi and atol return 9ero if no numeric data is found G atof : floating point eEuivalent of the ADCII string pointed to b! str G atoi : signed integer eEuivalent of the ADCII string pointed to b! str G atol : signed long integer eEuivalent of the ADCII string pointed to b! str
#include <mega$3.h> #include <stdio.h> #include <stdlib.h> )) this to include putchar and print 4

)# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%%

#de ine :;<_=>?@A_8=>B?6 $% void main(void) ( char mystr5:;<_=>?@A_8=>B?6C$7; int myint; char c; )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; while ($) ( c * %; puts (J=nter a signed integer number ollowed by 4KnKrJ); while (c < :;<_=>?@A_8=>B?6) ( mystr5cCC7 * getchar(); )) wait or a character )) i it is our terminating character! then "uit4 i (mystr5c+$7 ** L4L) brea&; 0 mystr5c7 * LK%L; )) null terminate the string4 myint * atoi(mystr); )) convert

print (JAour integer value isM NdKnKrJ!myint); 0 0

0esults) #he following is transmitted b! the HDA0#"


=nter a signed integer number ollowed by 4

,nce IJK is received the string is converted and the result is transmitted to the HDA0#" bc!2bin 5include 6bcd"h7 unsigned char bcd<bin-unsigned char n.8 #he bcd2bin function converts a binar! coded decimal -bcd. value to a binar! value" In binar! coded decimal representation the upper nibble of the value represents the =@s digit of

a decimal value" #he lower nibble of the value represents the =s digit of a decimal value" n must be a value between @d and 33d" 0eturns) Linar! value of n
#include <bcd.h> void main() ( unsigned char bcd_value! bin_value; bcd_value * %x$-; )# bcd representation o bin_value * bcd2bin(bcd_value); while($) ( 0 0 decimal $- #)

0esults) bin>value ? =2-? @%@(. bin2bc! 5include 6bcd"h7 unsigned char bin<bcd-unsigned char n.8 #he bin2bcd function converts a binar! value to a binar! coded decimal -bcd. value" In binar! coded decimal representation the upper nibble of the value represents the =@s digit of a decimal value" #he lower nibble of the value represents the =s digit of a decimal value" n must be a value between @d and 33d" 0eturns) Linar! coded decimal value of n
#include <bcd.h> void main() ( unsigned char bin_value! bcd_value; bin_value * %x%O; )# $- decimal #) bcd_value * bin2bcd(bin_value); while($) ( 0 0

0esults) bcd>value ? @%=2

bin2"rayc , bin2"ray, bin2"ray 5include 6gra!"h7 unsigned char bin<gra!c-unsigned char n.8 unsigned int bin<gra!-unsigned int n.8 unsigned long bin<gra!l-unsigned long n.8 #he bin2gray functions convert the binar! value n to a Mra!-coded value" Mra! codes were developed to prevent noise in s!stems where analog-to-digital conversions were being performed" Mra! codes have the advantage over binar! numbers in that onl! one bit in the code changes between successive numbers" #he bin2gray functions bin2grayc, bin2gray, and bin2grayl are tailored for unsigned char unsigned int and unsigned long variables respectivel!" #able A:= lists the Mra! codes and their binar! and decimal eEuivalents for values @ through =2"

Decimal Number @ = < 1 B 2 A N 4 3 =@ == =< =1 =B =2

Binary Equivalent B3 B2 B1 B0 @ @ @ @ @ @ @ @ = = = = = = = = @ @ @ @ = = = = @ @ @ @ = = = = @ @ = = @ @ = = @ @ = = @ @ = = @ = @ = @ = @ = @ = @ = @ = @ =

Gray Code Equivalent B3 B2 B1 B0 @ @ @ @ @ @ @ @ = = = = = = = = @ @ @ @ = = = = = = = = @ @ @ @ @ @ = = = = @ @ @ @ = = = = @ @ @ = = @ @ = = @ @ = = @ @ = = @

Tab e A#$

Gray Code Equivalents of Deci al and !inary "alues

0eturns) Linar! value of n


#include <gray.h> void main() ( unsigned char gray_char! bin_char; bin_char * %x%.; gray_char * bin2gray(bin_char); while($) ( 0 0

0esults) gra!>char ? B ca oc 5include 6stdlib"h7 void Ccalloc-unsigned int num unsigned int si9e.8 #he calloc function allocates a memor! bloc$ in the heap for an arra! of nu elements each element having the length of si#e b!tes" ,n return the function returns a pointer to the start of the memor! bloc$ which is filled with 9eros" #he allocated memor! bloc$ occupies si#eFB b!tes in the heap" #his must be ta$en into account when specif!ing the heap si9e in the ProOectPConfigurePC CompilerPCode Meneration menu" 0eturns) If successful in finding contiguous free memor! of the appropriate si9e returns a pointer to the memor! bloc$" If unsuccessful returns a null pointer"
#include <mega$3.h> )# include the standard input)output library #) #include <stdio.h> )# include the variable length argument lists macros #) #include <stdlib.h> #de ine xtal 3%%%%%%8 #de ine baud ,3%% )) declaring a pointer! but not reserving memory struct two_d #two_d_p; struct two_d #start_two_d_p; int memory_si'e; or the array4

struct two_d ( int index; int value; 0; void main(void) ( int i; )) DE;@? initiali'ation )) Hommunication ParametersM 1 Iata! $ Etop! >o Parity )) DE;@? @eceiverM Qn )) DE;@? ?ransmitterM Qn )) DE;@? :odeM ;synchronous )) DE;@? 9aud rateM ,3%% DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; D9@@6*%x%%; D9@@8*xtal)$3)baud+$; while ($) ( puts (JKnKr6ow much memory should R illS(=>?=@)KnKrJ); i (scan (JNdJ!Gmemory_si'e) 4* +$) ( i ((memory_si'e#si'eo (struct two_d)) < (_6=;P_ERT=_ + /)) ( print (JKnKr?han&s! RFll try4KnKrJ); )) try to get enough memory start_two_d_p * calloc(memory_si'e!si'eo (struct two_d)); two_d_p * start_two_d_p; i (two_d_p 4* >D88) ( print (JKnKrRnitial Ualues4KnKrJ); or (i*%;i<memory_si'e;iCC) ( print (JN%/< N%/<KnKrJ!two_d_p+>index! two_d_p+>value); two_d_p+>index * i; two_d_p+>value * i C $%%%; )) change the value two_d_pCC; )) move the pointer orward4 0

print (JKnKr:odi ied Ualues4KnKrJ); two_d_p * start_two_d_p; )) print the new values4 or (i*%;i<memory_si'e;iCC) ( print (JN%/< N%/<KnKrJ!two_d_p+>index! two_d_p+>value); two_d_pCC; )) move the pointer orward4 0 )) ree the calloc memory ree(start_two_d_p); 0 else print (JOailed to calloc correctly.KnKrJ); 0 else ( print (JKnKr6eap si'e limit is NdKnKrJ!_6=;P_ERT=_+/); 0 0 0 0 or next time4

0esults) #he HDA0# transmits at 3A@@ baud


6ow much memory should R illS(=>?=@)

#hen it waits until a number is entered followed b! a newline character" ,nce this is received -2 for e%ample. it transmits
?han&s! RFll try4 Rnitial Ualues4 %%%% %%%% %%%% %%%% %%%% %%%% %%%% %%%% %%%% %%%% :odi ied Ualues4 %%%% %2=1 %%%$ %2=, %%%2 %2=; %%%2 %2=9 %%%/ %2=H

cabs 5include 6math"h7 unsigned char cabs-signed char %.8 0eturns) Absolute value of x Dee abs. cei 5include 6math"h7 float ceil-float %.8 #he ceil function returns the smallest integer value that is not less than the floating point number x. In other words the ceil function rounds x up to the ne%t integer value and returns that value" 0eturns) Dmallest integer value that is not less than the floating point number x
#include <math.h> void main() ( loat new_val; new_val * ceil(2.-2$); while($) ( 0 0

0esults) new>val ? 1 c%a& 5include 6math"h7 signed char cma%-signed char a signed char b.8 0eturns) Ma%imum value of a or b Dee ax. c%in 5include 6math"h7 signed char cmin-signed char a signed char b.8

0eturns) Minimum value of a or b Dee in. cos 5include 6math"h7 float cos-float %.8 #he cos function calculates the cosine of the floating point number x. #he angle x is e%pressed in radians" 0eturns) cos-%.
#include <math.h> void main() ( loat new_val; new_val * cos(-.$2$); while($) ( 0 0

0esults) new>val ? @"13N cos' 5include 6math"h7 float cosh-float %.8 #he cos$ function calculates the h!perbolic cosine of the floating point number x. #he angle x is e%pressed in radians" 0eturns) cosh-%.
#include <math.h> void main() ( loat new_val; new_val * cosh(-.$2$); while($) ( 0 0

0esults) new>val ? 41"N2B

1N@

csi"n 5include 6math"h7 signed char csign-signed char %.8 0eturns) := @ or = if x is negative 9ero or positive respectivel! Dee sign. !e ay(%s 5include 6dela!"h7 void dela!>ms-unsigned int n.8 #he delay% s function generates a dela! of n milliseconds before returning" #he interrupts must be turned off around the call to the delay% s function or the dela! will be much longer than intended" #he actual dela! depends on the cloc$ cr!stal freEuenc!" #herefore it is important to specif! the correct cloc$ freEuenc!" #his can be done either in the ProOectP ConfigurePC Compiler menu or with the statement &define xtal x', where x' is the cloc$ freEuenc! in Qert9" 0eturns) None
#include <delay.h> #include <mega$3.h> #include <stdio.h> )# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% void main(void) ( unsigned int pause_time; )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13;

( ppendi x ()'ib r a r y * unction s +e fe r ence 1A3

while ($) ( puts (J6ow many milliseconds should R pauseS(=>?=@)KnKrJ); i (scan (JNuKnJ!Gpause_time) 4* +$) ( print (J?han&s4 RFll pause or Nu milliseconds.KnKrJ! pause_time); )) disable interrupts #asm(JcliJ); delay_ms(pause_time); )) enable interrupts #asm(JseiJ); 0 0 0

0esults) #he microprocessor transmits


6ow many milliseconds should R pauseS (=>?=@)

#hen it waits until a number is entered followed b! a newline character" ,nce this is received -<@@@ for e%ample. it transmits
?han&s4 RFll pause or 2%%% milliseconds.

#hen after an appropriate pause -< seconds in our e%ample. the first prompt is again transmitted" !e ay(us 5include 6dela!"h7 void dela!>us-unsigned int n.8 #he delay%us function generates a dela! of n microseconds before returning" n must be a constant e%pression" #he interrupts must be turned off around the call to the delay%us function or the dela! will be much longer than intended" #he actual dela! depends on the cloc$ cr!stal freEuenc!" #herefore it is important to specif! the correct cloc$ freEuenc!" #his can be done either in the ProOectPConfigurePC Compiler menu or with the statement &define xtal x', where x' is the cloc$ freEuenc! in Qert9" 0eturns) None
#include <delay.h> #include <mega$3.h> #include <stdio.h>

( ppendi x ()'ib r a r y * unction s +e fe r ence ==2

)# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% void main(void) ( unsigned int pause_time; )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; while ($) ( puts (J6ow many thousands o uEeconds should R pauseSKrJ); puts (J=nter a number between $ and -. Press =>[email protected]); i (scan (JNuKnJ!Gpause_time) 4* +$) ( i ((pause_time > %) GG (pause_time < 3)) ( print (JRFll pause N$u%%% microseconds.KnKrJ! pause_time); )) disable interrupts #asm(JcliJ); switch (pause_time) ( case $M delay_us($%%%); brea&; case 2M delay_us(2%%%); brea&; case 2M delay_us(2%%%); brea&; case /M delay_us(/%%%); brea&;

==A

case -M delay_us(-%%%); brea&; de aultM brea&; 0 )) enable interrupts #asm(JseiJ); 0 else puts (J6uhSKnKrJ); 0 0 0

0esults) #he microprocessor transmits


6ow many thousands o uEeconds should R pauseS =nter a number between $ and -. Press =>?=@.

#hen it waits until a number is entered followed b! a newline character" ,nce this is received -< for e%ample. it transmits
RFll pause 2%%% microseconds.

#hen after an appropriate pause -< milliseconds in our e%ample. the first prompt is again transmitted" e&) 5include 6math"h7 float e%p-float %.8 #he exp function calculates the natural -base e. e%ponential of the variable x. 0eturns) ex
#include <math.h> void main() ( loat new_val; new_val * exp(-); while($) ( 0 0

0esults) new>val ? e2 ? =B4"B=1 e&ten!e!(stan!by 5include 6sleep"h7 void e%tended>standb!-void.8 #he extended%standby function puts the A/0 microcontroller into e%tended standb! mode" #his is a sleep mode and similar to the po,erdo,n function" Dee po,erdo,n in this appendi% for the function use" Dee the Atmel datasheets for the complete description of this sleep mode as it applies to a particular A/0 device" E%tended standb! sleep mode is not available on all A/0 devices" *fabs 5include 6math"h7 float fabs-float %.8 0eturns) Absolute value of x Dee abs. f oor 5include 6math"h7 float floor-float %.8 #he floor function returns integer value of the floating point number x. #his is the largest whole number that is less than or eEual to x. 0eturns) Integer portion of x
#include <math.h> void main() ( loat new_val; new_val * while($) ( 0 0 loor(2.-2$);

0esults) new>val ? <

f%a& 5include 6math"h7 float fma%-float a float b.8 0eturns) Ma%imum value of a or b Dee ax. f%in 5include 6math"h7 float fmin-float a float b.8 0eturns) Minimum value of a or b Dee in. f%o! 5include 6math"h7 float fmod-float % float !.8 #he f od function returns the remainder of x divided b! y. #his is a modulo function specif- icall! designed for float t!pe variables" #he modulo operator --. is used to perform the modulo operation on integer variable t!pes" 0eturns) 0emainder of x divided b! y
#include <math.h> void main() ( loat remains; remains * while($) ( 0 0 mod(2-.3! 1);

0esults) remains ? ="A free 5include 6stdlib"h7 void free-void Cptr.8

#he free function frees memor! allocated in the heap b! alloc, calloc, or realloc functions and pointed to b! ptr. After being freed the memor! bloc$ is available for new allocation" If ptr is null then it is ignored" 0eturns) None Dee alloc. fre&) 5include 6math"h7 float fre%p-float % int Ce%pon.8 #he frexp function returns the mantissa of the floating point number x, or @ if x is @" #he power of < e%ponent of x is stored at the location pointed to b! expon. If x is @ the value stored at expon is also @" In other words if the following call is made
y * rexp(x! expon);

the relationshp between expon, x, and the return value y can be e%pressed as
x * y # 2 expon

0eturns) Mantissa of x in the range @"2 to ="@ or @ if x is @


#include <mega$3.h> #include <math.h> void main(void) ( loat x!'; int y; loat a!c; int b; loat d! ; int e; x * 2.$/$-,; '* rexp(x!Gy); a * %.$/$-,; c* rexp(a!Gb); d * ..%.%%%; * rexp(d!Ge);

while ($) ( 0 0

0esults)
x y ' a b c d e * * * * * * * * * 2.$/$-,% 2 %..1-2,1 %.$/$-,% +2 %.-3323% %..%.%%% % %..%.%%%

fsi"n 5include 6math"h7 signed char fsign-float %.8 0eturns) := @ or = if x is negative 9ero or positive respectivel! Dee sign. ftoa 5include 6stdlib"h7 void ftoa-float n unsigned char decimals char Cstr.8 #he ftoa function converts the floating point value n to its ADCII character string eEuivalent" #he value is represented with the specified number of decimal places" #he string is stored at the location specified b! .str. #a$e care to ensure that the memor! allocated for str is large enough to hold the entire value plus a null-terminating character" 0eturns) None
#include <mega$3.h> #include <stdio.h> #include <stdlib.h> )) this to include putchar and print 4

)# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%%

void main(void) ( char mystr5$$7; )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; toa($2/.%.-/.%2$!2!mystr); puts (J?he loating point value isM J); puts(mystr); while ($) ( 0 0

0esults) #he HDA0# transmits at 3A@@ baud


?he loating point value isM $2/.%.--

ftoe 5include 6stdlib"h7 void ftoe-float n unsigned char decimals char Cstr.8 #he ftoe function converts the floating point value n to its ADCII character string eEuivalent" #he value is represented as a mantissa with the specified number of decimal places and an integer power of =@ e%ponent" #he string is stored at the location specified b! .str. #a$e care to ensure that the memor! allocated for str is large enough to hold the entire value plus a null terminating character" 0eturns) None
#include <mega$3.h> #include <stdio.h> #include <stdlib.h> )) this to include putchar and print 4

)# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8

)# 9aud rate #) #de ine baud ,3%% void main(void) ( char mystr5$$7; )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; toe(%.%%$2/.!2!mystr); puts (J?he loating point value isM J); puts(mystr); while ($) ( 0 0

0esults) #he HDA0# transmits at 3A@@ baud


?he loating point value isM $.2-e+2

"etc'ar 5include 6stdio"h7 char getchar-void.8 #he getc$ar function is a standard C language I+, function but it has been adapted to wor$ on embedded microcontrollers with limited resources" #he getc$ar function returns a charac- ter received b! the HDA0#" #his function uses polling to get the character from the HDA0#" As a result the function waits indefinitel! for a character to be received before returning" Prior to this function being used the HDA0# must be initiali9ed and the HDA0# receiver must be enabled" If another peripheral is to be used for receiving the getc$ar function can be modified accordingl!" #he source for this function is in the stdio"h file" If !ou want to replace the standard librar! getc$ar with !our own version !ou must do three things" (irst !ou must place the new getc$ar function in the "c file before including the

standard librar!" Decond !ou must follow the new getc$ar function with a definition statement telling the compiler to ignore an! other getc$ar functions that it finds" (inall! include the standard librar!" Put together the code might appear as
char getchar(void) ( )) your getchar routine statements here 0 #de ine _;8?=@>;?=_B=?H6;@_ #include <stdio.h> )) the rest o the source ile4

#he standard getc$ar/0 returns) char received b! the HDA0#


#include <mega$3.h> #include <stdio.h> )# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% void main(void) ( char &; )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; while ($) ( )# receive the character #) &*getchar(); )# and echo it bac& #) putchar(&); 0 0

0esults) Characters received b! the HDA0# are echoed bac$ out of the HDA0# until power is removed from the processor"

+"ets 5include 6stdio"h7 char Cgets-char Cstr unsigned int len.8 #he .gets function reads characters from the HDA0# using the getc$ar function until a new- line character is encountered and places them in the string pointed to b! str. #he newline character is replaced b! IR@K and a pointer to str is returned" If len characters are read before the newline character is read then the function terminates the string str with IR@K and returns" Prior to this function being used the HDA0# must be initiali9ed and the HDA0# receiver must be enabled" 0eturns) Pointer to the string str
#include <mega$3.h> #include <stdio.h> )# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% void main(void) ( char your_name5$$7;

)) room

or $% chars plus termination

)# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; puts (JPlease enter your name and press return.KrJ); puts (J(Qnly $% characters are allowed)KrJ); gets(your_name!$%); )) up to $% chars4 print (J6i Ns4KnKrJ!your_name); while ($) ( 0 0

0esults) #he HDA0# transmits the prompt for a name)


Please enter your name and press return. (Qnly $% characters are allowed.)

#hen the microprocessor waits for either a newline character or =@ characters to be received b! the HDA0#" Assume the string &Sane Doe' is received followed b! the newline charac- ter" #he following is transmitted)
6i Vane Ioe4

"ray2binc "ray2bin 5include 6gra!"h7

"ray2bin,

unsigned char gra!<binc-unsigned char n.8 unsigned int gra!<bin-unsigned int n.8 unsigned long gra!<binl-unsigned long n.8 #he gray2bin functions convert the Mra!-coded decimal value n to a binar! coded value" Mra! codes were developed to prevent noise in s!stems where analog-to-digital conversions were being performed" Mra! codes have the advantage over binar! numbers in that onl! one bit in the code changes between successive numbers" #he gray2bin functions gray2binc, gray2bin, and gray2binl are tailored for unsigned char unsigned int and unsigned long vari- ables respectivel!" #able A:= in the bin2gray function description lists the Mra! codes and their binar! eEuivalents for values @ through =2" 0eturns) Linar! value of n
#include <gray.h> void main() ( unsigned char gray_char! bin_char; gray_char * %x%/; )# gray representation o bin_char * gray2bin(gray_char); while($) ( 0 0 decimal . #)

0esults) bin>char ? N i! e 5include 6sleep"h7 void idle-void.8

#he idle function puts the A/0 microcontroller into idle mode" #he function sleep%enable must be called prior to this function being used" In idle mode the CPH is stopped but the timers+counters watchdog timer and the interrupt s!stem continue to run" As such the microcontroller can wa$e up from either internal or e%ternal interrupts" Hpon wa$ing up from an interrupt the MCH e%ecutes the interrupt and then continues e%ecuting at the instruction following the sleep command -called b! the idle function." 0eturns) None Dee sleep%enable for a code e%ample" isa nu% 5include 6ct!pe"h7 unsigned char isalnum-char c.8 #he isalnu function tests c to see if it is an alphanumeric character" 0eturns) = if c is alphanumeric
#include <ctype.h> void main() ( unsigned char c_alnum_ lag! d_alnum_ lag; c_alnum_ lag * isalnum(L$L); )) test the ;EHRR value o d_alnum_ lag * isalnum($); )) test the value $ while($) ( 0 0

$ (%x2$)

0esults)
c_alnum_ lag * $ d_alnum_ lag * %

isa )'a 5include 6ct!pe"h7 unsigned char isalpha-char c.8 #he isalp$a function tests c to see if it is an alphabetic character" 0eturns) = if c is alphabetic
#include <ctype.h>

void main() ( unsigned char c_alpha_ lag! d_alpha_ lag; c_alpha_ lag * isalpha(LaL); )) test the ;EHRR character LaL d_alpha_ lag * isalpha(L$L); )) test the ;EHRR character L$L while($) ( 0 0

0esults)
c_alpha_ lag * $ d_alpha_ lag * %

isascii 5include 6ct!pe"h7 unsigned char isascii-char c.8 #he isascii function tests c to see if it is an ADCII character" ADCII characters range from @d to =<Nd" 0eturns) = if c is ADCII
#include <ctype.h> void main() ( unsigned char c_ascii_ lag! d_ascii_ lag; c_ascii_ lag * isascii(LaL); )) test the ;EHRR character a d_ascii_ lag * isascii($-2); )) test the value $-2 while($) ( 0 0

0esults)
c_ascii _ lag * $ d_ascii _ lag * %

iscntr 5include 6ct!pe"h7 unsigned char iscntrl -char c.8 #he iscntrl function tests c to see if it is a control character" Control characters range from @d to 1=d and =<Nd"

0eturns) = if c is a control character


#include <ctype.h> void main() ( unsigned char c_iscntrl_ lag! d_iscntrl_ lag; c_iscntrl_ lag * iscntrl(LKtL); )) test the control )) character! hori'ontal tab d_iscntrl_ lag * iscntrl(LaL); )) test the ;EHRR character a while($) ( 0 0

0esults)
c_iscntrl_ lag * $ d_iscntrl_ lag * %

is!i"it 5include 6ct!pe"h7 unsigned char isdigit-char c.8 #he isdigit function tests c to see if it is an ADCII representation of a decimal digit" 0eturns) = if c is a decimal digit
#include <ctype.h> void main() ( unsigned char c_isdigit_ lag! d_isdigit_ lag; c_isdigit_ lag * isdigit(L$L); )) test the ;EHRR character $ d_isdigit_ lag * isdigit(LaL); )) test the ;EHRR character a while($) ( 0 0

0esults)
c_digit_ lag * $ d_digit_ lag * %

is o,er 5include 6ct!pe"h7 unsigned char islower-char c.8 #he islo,er function tests c to see if it is a lowercase alphabetic character"

0eturns) = if c is a lowercase alphabetic character


#include <ctype.h> void main() ( unsigned char c_islower_ lag! d_islower_ lag; c_islower_ lag * islower(L;L); )) test the ;EHRR character ; d_islower_ lag * islower(LaL); )) test the ;EHRR character a while($) ( 0 0

0esults)
c_islower_ lag * % d_islower_ lag * $

is)rint 5include 6ct!pe"h7 unsigned char isprint-char c.8 #he isprint function tests c to see if it is a printable character" Printable characters are between 1<d and =<Nd" 0eturns) = if c is a printable character
#include <ctype.h> void main() ( unsigned char c_isprint_ lag! d_isprint_ lag; c_isprint_ lag * isprint(L;L); )) test the ;EHRR character ; d_isprint_ lag * isprint(%x%2); )) test the control )) character! bac&space while($) ( 0 0

0esults)
c_isprint_ lag * $ d_isprint_ lag * %

is)unct 5include 6ct!pe"h7 unsigned char ispunct-char c.8

#he ispunct function tests c to see if it is a punctuation character" All characters that are not control characters and not alphanumeric characters are considered to be punctuation characters" 0eturns) = if c is a punctuation character
#include <ctype.h> void main() ( unsigned char c_ispunct_ lag! d_ispunct_ lag; c_ispunct_ lag * ispunct(L!L); )) test the ;EHRR character! comma d_ispunct_ lag * ispunct(LKtL); )) test the hori'ontal tab )) character while($) ( 0 0

0esults)
c_ispunct_ lag * $ d_ispunct_ lag * %

is-r t 5include 6math"h7 unsigned char isErt-unsigned int %.8 0eturns) #he sEuare root of the unsigned integer variable x Dee sqrt. iss)ace 5include 6ct!pe"h7 unsigned char isspace-char c.8 #he isspace function tests c to see if it is a white space character" Characters such as space line feed and hori9ontal tab are considered white space characters" 0eturns) = if c is a white space character
#include <ctype.h> void main() ( unsigned char c_isspace_ lag! d_isspace_ lag; c_isspace_ lag * isspace(L;L); )) test the ;EHRR character ; d_isspace_ lag * isspace(LKtL); )) test the hori'ontal tab )) character

while($) ( 0 0

0esults)
c_isspace_ lag * % d_isspace_ lag * $

isu))er 5include 6ct!pe"h7 unsigned char isupper-char c.8 #he isupper function tests c to see if it is an uppercase alphabetic character" 0eturns) = if c is an uppercase alphabetic character
#include <ctype.h> void main() ( unsigned char c_isupper_ lag! d_isupper_ lag; c_isupper_ lag * isupper(L;L); )) test the ;EHRR character ; d_isupper_ lag * isupper(LaL); )) test the ;EHRR character a while($) ( 0 0

0esults)
c_isupper_ lag * $ d_isupper_ lag * %

is&!i"it 5include 6ct!pe"h7 unsigned char is%digit-char c.8 #he isxdigit function tests c to see if it is an ADCII representation of a he%adecimal digit" 0eturns) = if c is a he%adecimal digit
#include <ctype.h> void main() ( unsigned char c_isxdigit_ lag! d_isxdigit_ lag; c_isxdigit_ lag * isxdigit(LaL); )) test the ;EHRR character a d_isxdigit_ lag * isxdigit(L'L); )) test the ;EHRR character '

while($) ( 0 0

0esults)
c_isxdigit_ lag * $ d_isxdigit_ lag * %

itoa 5include 6stdlib"h7 void itoa-int Cstr.8 n char

#he itoa function converts the signed integer value n to its ADCII character string eEuivalent" #he string is stored at the location specified b! .str. #a$e care to ensure that the mem- or! allocated for str is large enough to hold the entire value plus a termination character" 0eturns) None
#include <mega$3.h> #include <stdio.h> )) this to include putchar and print 4 #include <stdlib.h> )# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% void main(void) ( char mystr5$%7; )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; itoa(+$22$!mystr); puts (J?he value isM KrJ); puts(mystr);

while ($) ( 0 0

0esults) #he HDA0# transmits at 3A@@ baud


?he value isM +$22$

abs 5include 6math"h7 unsigned long labs-long %.8 0eturns) Absolute value of x Dee abs. !e&) 5include 6math"h7 float lde%p-float % int e%pon.8 #he ldexp function calculates the value of x multiplied b! the result of < raised to the power of expon. 0eturns) x C <e%pon
#include <math.h> void main() ( loat new_val; new_val * ldexp(-!2); while($) ( 0 0

0esults) new>val ? 2 C <1 ? B@ %a& 5include 6math"h7 long lma%-long a long b.8

0eturns) Ma%imum value of a or b Dee ax. %in 5include 6math"h7 long lmin-long a long b.8 0eturns) Minimum value of a or b Dee in. o" 5include 6math"h7 float log-float %.8 #he log function calculates the base e or natural logarithm of the floating point value x. x must be a positive non9ero value" 0eturns) log-%.
#include <math.h> void main() ( loat new_val; new_val * log(-); while($) ( 0 0

0esults) new>val ? ="A@3 o"$. 5include 6math"h7 float log=@-float %.8 #he log10 function calculates the base =@ logarithm of the floating point value x. x must be a positive non9ero value" 0eturns) log=@-%.
#include <math.h>

void main() ( loat new_val; new_val * log$%(-); while($) ( 0 0

0esults) new>val ? @"A33 si"n 5include 6math"h7 signed char lsign-long %.8 0eturns) := @ or = if x is negative 9ero or positive respectivel! Dee sign. s-r t 5include 6math"h7 unsigned int lsErt-unsigned long %.8 0eturns) #he sEuare root of the unsigned long variable x Dee sqrt. toa 5include 6stdlib"h7 void ltoa-long Cstr.8 n char

#he ltoa function converts the long signed integer value n to its ADCII character string eEuivalent" #he string is stored at the location specified b! .str. #a$e care to ensure that the memor! allocated for str is large enough to hold the entire value plus a nullterminating character" 0eturns) None
#include <mega$3.h> #include <stdio.h> #include <stdlib.h> )) this to include putchar and print 4

)# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8

)# 9aud rate #) #de ine baud ,3%% void main(void) ( char mystr5$$7; )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; ltoa($2%%2$!mystr); puts (J?he long signed integer value isM KrJ); puts(mystr); while ($) ( 0 0

0esults) #he HDA0# transmits at 3A@@ baud


?he long signed integer value isM $2%%2$

%a oc 5include 6stdlib"h7 void Cmalloc-unsigned int si9e.8 #he alloc function allocates a memor! bloc$ in the heap with the length of si#e b!tes" ,n return the function returns a pointer to the start of the memor! bloc$ which is filled with 9eros" #he allocated memor! bloc$ occupies si#eFB b!tes in the heap" #his must be ta$en into account when specif!ing the heap si9e in the ProOectPConfigurePC CompilerPCode Meneration menu" 0eturns) If successful in finding contiguous free memor! with si#e b!tes returns a pointer to the memor! bloc$" If unsuccessful returns a null pointer"
#include <mega$3.h> )# include the standard input)output library #) #include <stdio.h>

)# include the variable length argument lists macros #) #include <stdlib.h> #de ine xtal 3%%%%%%8 #de ine baud ,3%% )) declaring a pointer! but not reserving memory char #cptr; char #start_cptr; int memory_si'e; void main(void) ( int i; )) DE;@? initiali'ation )) Hommunication ParametersM 1 Iata! $ Etop! >o Parity )) DE;@? @eceiverM Qn )) DE;@? ?ransmitterM Qn )) DE;@? :odeM ;synchronous )) DE;@? 9aud rateM ,3%% DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; D9@@6*%x%%; D9@@8*xtal)$3)baud+$; while ($) ( puts (JKnKr6ow much memory should R illS(=>?=@)KnKrJ); i (scan (JNdJ!Gmemory_si'e) 4* +$) ( i (memory_si'e < (_6=;P_ERT=_ + /)) ( print (JKnKr?han&s! RFll try4KnKrJ); )) try to get enough memory start_cptr * malloc(memory_si'e); cptr * start_cptr; i (cptr 4* >D88) ( print (JKnKrRnitial Ualues4KnKrJ); or (i*%;i<memory_si'e;iCC) ( ))print the initial value print (JN%2< J!#cptr); or the array4

#cptr * (char)i C $; )) change the value cptrCC; )) move the pointer orward4 i (((iC$)N$%) ** %) print (JKnKrJ); 0 print (JKnKr:odi ied Ualues4KnKrJ); cptr * start_cptr; )) print the new values4 or (i*%;i<memory_si'e;iCC) ( )) print the modi ied value4 print (JN%2< J!#cptrCC); i (((iC$)N$%) ** %) print (JKnKrJ); 0 )) ree the mallocFd memory or next time4 ree(start_cptr); 0 else print (JOailed to malloc correctly.KnKrJ); 0 else ( print (JKnKr6eap si'e limit is NdKnKrJ!_6=;P_ERT=_+/); 0 0 0 0

0esults) #he HDA0# transmits at 3A@@ baud


6ow much memory should R illS(=>?=@)

#hen it waits until a number is entered followed b! a newline character" ,nce this is received -=2 for e%ample. it transmits
?han&s! RFll try4 Rnitial Ualues4 %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% :odi ied Ualues4 %$ %2 %2 %/ %- %3 %. %1 %, %; %9 %H %I %= %O

%a& 5include 6math"h7 int ma%-int a int b.8

signed char cma%-signed char a signed char b.8 long lma%-long a long b.8 float fma%-float a float b.8 #he ax function returns the ma%imum of the two integer values a and b as an integer" #he c ax, l ax, and f ax functions return the ma%imum of the two signed char long and float values as a signed char long and float value respectivel!" 0eturns) Ma%imum value of a and b si9ed according to the function called
#include <math.h> void main() ( int big_int; signed char a_char! b_char! big_char; big_int * a_char * b_char * big_char while($) ( 0 0 max($2%%! 22$%); ))get the maximum o 22; %x.;; * cmax(a_char!b_char); the values

0esults)
big_int * 22$% big_char * %x.;

+%e%cc)y 5include 6string"h7 (or the #INT memor! model)


void #memccpy(void #dest! void #src! char c! unsigned char n);

(or the DMAUU memor! model)


void #memccpy(void #dest! void #src! char c! unsigned int n);

#he function e ccpy copies at most n b!tes from the memor! location pointed to b! src to the memor! location dst until the character c is copied" #he dst and src memor! bloc$s must not overlap" e ccpy returns a null pointer if the last character copied was c. If c is not copied within the n b!tes then a pointer to the ne%t location in dst -which is calculated as dst F n F =. is returned"

0eturns) Null pointer if c is copied to dst8 otherwise returns dstFnF=


#include <string.h> char inputstr57 * JW$$.2#J; char outputstr$537; char outputstr2537; void #a! #b; void main(void) ( a * memccpy(outputstr$!inputstr!L.L!2); b * memccpy(outputstr2!inputstr!L.L!/); while ($) ( 0 0

0esults)
outputstr$ * JW$$J a * outputstr$ C 2 C $ * G(outputstr$5/7) outputstr2 * JW$$.J b * >D88

+%e%c'r 5include 6string"h7 (or the #INT memor! model)


void #memchr(void #bu ! unsigned char c! unsigned char n);

(or the DMAUU memor! model)


void #memchr(void #bu ! unsigned char c! unsigned int n);

#he function e c$r searches memor! starting at the location pointed to b! buf for the first occurrence of the character c or until n b!tes have been searched" If c is found in buf within n b!tes a pointer to c is returned" If c is not found a null pointer is returned" 0eturns) Pointer to the character c in buf if c is found8 otherwise NHUU is returned
#include <string.h> char inputstr57 * JW$$.2#J; char #a; char #b; void main(void) (

a * memchr(inputstr!L.L!2); b * memchr(inputstr!L.L!-); while ($) ( 0 0

0esults)
a * >D88 b * G(inputstr527) * J.2#J

%e%c%), %e%c%)f 5include 6string"h7 (or the #INT memor! model)


signed char memcmp(void #bu $! void #bu 2! unsigned char n); signed char memcmp (void #bu $! void lash #bu 2! unsigned char n);

(or the DMAUU memor! model)


signed char memcmp(void #bu $! void #bu 2! unsigned int n); signed char memcmp (void #bu $! void lash #bu 2! unsigned int n);

#he functions e c p and e c pf compare the contents of the memor! pointed to b! buf1 to the memor! pointed to b! buf2 one b!te at a time" #he functions return after comparing two uneEual b!tes or after n b!tes are compared whichever comes first" 0eturns)
G signed char 6 @ if .buf1 6 .buf2 G signed char ? @ if .buf1 ? .buf2 G signed char 7 @ if .buf1 7 .buf2
#include <string.h> char inputstr$57 * Jname aJ; char inputstr257 * Jname bJ; void main(void) ( signed char a; signed char b; signed char c;

a * memcmp(inputstr$!inputstr2!-); b * memcmp(inputstr$!inputstr2!3); c * memcmp (inputstr$!Jname $J!3); while ($) ( 0 0

0esults)
a * % b * %xOO c * %x2%

+%e%c)y, +%e%c)yf 5include 6string"h7 (or the #INT memor! model)


void #memcpy(void #dest! void #src! unsigned char n);

(or the DMAUU memor! model)


void #memcpy(void #dest! void #src! unsigned int n);

(or either model when src is in (UADQ)


void #memcpy (void #dest! void #src! unsigned int n);

#he functions e cpy and e cpyf cop! n b!tes from the memor! location pointed to b! src to the memor! location pointed to b! dst. (or the function e cpy, the dst and src memor! bloc$s must not overlap" #his is not a concern with e cpyf, because the src in e cpyf must be located in (UADQ" If the memor! bloc$s do overlap use e ove instead of e cpy. 0eturns) Pointer to dest
#include <string.h> char char void char void inputstr57 * JW$$.2#J; outputstr537; #a; outputstr 537; #b;

void main(void) ( a * memcpy(outputstr!inputstrC$!/); outputstr5/7 * LK%L; )) null terminate our new string

b * memcpy (outputstr !J6ello Xorld4J!-); outputstr 5-7 * LK%L; )) null terminate our new string4 while ($) ( 0 0

0esults)
outputstr * J$$.2J a * J$$.2J outputstr * J6elloJ b * J6elloJ

+%e%%o/e 5include 6string"h7 (or the #INT memor! model)


void #memmove(void #dest! void #src! unsigned char n);

(or the DMAUU memor! model)


void #memmove(void #dest! void #src! unsigned int n);

#he e ove function copies n b!tes from the memor! pointed to b! src to the memor! pointed to b! dest. Hnli$e e cpy, the src and dest ma! overlap when calling e ove. 0eturns) dest
#include <string.h> char inputstr$57 * Jabc$J; char #a; void main(void) ( )) move the string one place to the right a * memmove(G(inputstr$5$7)!inputstr$!2); while ($) ( 0 0

0esults)
a * JabcJ inputstr$ * JaabcJ

+%e%set 5include 6string"h7 (or the #INT memor! model)


void #memset(void #bu ! unsigned char c! unsigned char n);

(or the DMAUU memor! model)


void #memset(void #bu ! unsigned char c! unsigned int n);

#he

e set function fills n b!tes of the memor! pointed to b! buf with the character c.
#include <string.h> char inputstr$57 * Jabc$J; char #a; void main(void) ( )) starting a ter a! ill in with some 2Fs a * memset(G(inputstr$5$7)!L2L!2); while ($) ( 0 0

0eturns) buf

0esults)
a * J222J inputstr$ * Ja222J

%in 5include 6math"h7 int min-int a int b.8 signed char cmin-signed char a signed char b.8 long lmin-long a long b.8 float fmin-float a float b.8 #he in function returns the minimum of the two integer values a and b as an integer" #he c in, l in, and f in functions return the minimum of the two signed char long and float values as a signed char long and float value respectivel!"

0eturns) Minimum value of a and b si9ed according to the function called


#include <math.h> void main() ( int little_int; signed char a_char! b_char! little_char; little_int * min($2%%! 22$%); ))get the minimum o a_char * 22; b_char * %x.;; little_char * cmin(a_char!b_char); while($) ( 0 0 the values

0esults)
little_int * $2%% little_char * 22

%o!f 5include 6math"h7 float modf-float Cipart.8 % float

#he odf function splits the floating point number x into its integer and fractional components" #he fractional part of x is returned as a signed floating point number" #he integer part is stored as a floating point number at ipart. Notice that the address of the variable to hold the integer portion not the variable itself is passed to odf. Loth the integer and the floating point results have the same sign as x. 0eturns)
G (ractional portion of the floating point number x as a signed floating point number G Dets the value at the address pointed to b! .ipart to the integer part of x
#include <math.h> void main() ( loat integer_portion!

ract_portion;

ract_portion * mod (+/-..! Ginteger_portion);

while($) ( 0 0

0esults)
ract_portion * +.. integer_portion * +/-

)ee0b, )ee0, 5include 6mem"h7 unsigned char pee$b-unsigned int addr.8 unsigned int pee$w-unsigned int addr.8 #he pee2b function reads the value of D0AM at the address addr. #he pee2, function reads an unsigned integer value from the D0AM at the address addr. #he pee2, function reads the UDL first from address addr and then reads the MDL of data from addr31. /alues can be directl! written to the D0AM b! using the po2eb and po2e, functions" 0eturns) None Dee po2eb, po2e, e%ample" )o0eb, )o0e, 5include 6mem"h7 void po$eb-unsigned int addr unsigned char data.8 void po$ew-unsigned int addr unsigned int data.8 #he po2eb function writes the value of data to the D0AM at the address addr. #he po2e, function writes the integer value of data to the D0AM at the address addr. #he po2e, func- tion writes the UDL of data first to address addr, and then writes the MDL of data to addr31. /alues can be read from the D0AM b! using the pee2b and pee2, functions" 0eturns) None
#include <mega$3.h> #include <mem.h>

for

the

code

)# the structure Jal aJ is stored in E@;: at address 23%h #) struct x ( unsigned char b; unsigned int w; 0 al a Y%x23%;

void main(void) ( unsigned int unsigned int unsigned int unsigned int

read_b; read_w; read_b2; read_w2;

:HDH@ * %xH%; )) enable external E@;: with $ wait state al a.b * %x$$; al a.w * %x2222; )) initiali'e the value at %x23% )) initiali'e the value at %x23$

read_b * (unsigned int) pee&b(%x23%); read_w * pee&w(%x23$); po&eb(%x23%!%x;;); po&ew(%x23$!%x99HH); )) place %x;; at address %x23% )) place %xHH at address %x23$ and )) %x99 at address %x2332

read_b2 * (unsigned int) al a.b; read_w2 * al a.w; while ($) ( 0 0

0esults)

read_b * %x%%$$ read_w * %x2222 read_b2 * %x%%;; read_w2 * %x99HH

)o, 5include 6math"h7 float pow-float % float !.8 #he po, function calculates x raised to the power of y. 0eturns) xy
#include <math.h> void main() (

loat new_val; new_val * pow(2!-); while($) ( 0 0

0esults)

new>val ? 1="3

)o,er!o,n 5include 6sleep"h7 void powerdown-void.8 #he po,erdo,n function puts the A/0 microcontroller into power-down mode" #he function sleep%enable, must be called prior to this function being used" In power-down mode the e%ternal oscillator is stopped while the e%ternal interrupts and the watchdog -if enabled. continue operating" ,nl! an e%ternal reset a watchdog reset -if enabled. or an e%ternal level interrupt can wa$e up the MCH" Hpon wa$ing up from an interrupt the MCH e%ecutes the interrupt and then continues e%ecuting at the instruction following the sleep command -called b! po,erdo,n." 0eturns) None
#include #include #include #include <mega$3.h> <stdio.h> <sleep.h> <delay.h>

)# "uart' crystal re"uency 56'7 #) #de ine xtal 3%%%%%%8 )# 9aud rate #) #de ine baud ,3%% interrupt 5=<?_R>?$7 void int$_isr(void) ( puts (JR was interrupted4KrJ); 0 void main(void) ( PQ@?I * %xOO; II@I * %x%%;

)) turn on internal pull+up on pin2 )) ma&e R>?$ (PQ@?I pin 2) an input

)) low level interrupt on R>?$ )) turn on R>?$ interrupts BRH@Z*%x1%; :HDH@*%x%%; :HDHE@*%x%%; BRO@*%x1%; )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; #asm(JseiJ); sleep_enable(); )) enable interrupts )) enable us to go to sleep when we are ready4

puts (J@eset QccurredKrJ); while ($) ( puts (JBood >ight4KrJ); puts (JR am going to sleep until you bug me4KrJ); delay_ms($%%); )) wait or string to be transmitted4 powerdown(); )) enter powerdown until R>?$ wa&es us up 0 0

0esults) #he microprocessor transmits


@eset Qccurred Bood >ight4 R am going to sleep until you bug me4

#hen it enters powerdown sleep mode and wa$es up onl! when an IN#= interrupt occurs b! P,0#D pin 1 being held low or an e%ternal reset occurs" Hpon wa$ing up it continues e%ecuting at the instruction following the powerdown" Hpon wa$ing up it will transmit the following continuousl! while P,0#D pin 1 is low)
R was interrupted4

#he microprocessor continues to run the while loop until power is removed" )o,ersa/e 5include 6sleep"h7

void powersave-void.8 #he po,ersave function puts the A/0 microcontroller into powersave mode" #his is a sleep mode and ver! similar to the po,erdo,n function" Dee po,erdo,n in this appendi% for the function use" Dee the Atmel datasheets for the complete description of this sleep mode as it applies to a particular A/0 device" Powersave sleep mode is not available on all A/0 devices" )rintf 5include 6stdio"h7 void printf-char flash Cfmtstr V """W.8 arg= arg<

#he printf function transmits formatted te%t according to the format specifiers in the f tstr string" #he transmittal is performed using the putc$ar function" #he standard putc$ar function defaults to transmitting using the HDA0#" Qowever it is possible to use an alternate putc$ar function to redirect the data" Dee putc$ar for details" #he implementation of printf is a reduced version of the standard C function" #his was nec- essar! due to the specific needs of an embedded s!stem and because the full implementation would reEuire a large amount of memor! space" In order to reduce code si9e the user can specif! what options the printf is reEuired to support for their specific application" #hese options can be accessed under the ProOectPConfigurePC CompilerP Code Meneration -s.printf (eatures option" #he format specifier string f tstr is a constant and must be located in (UADQ memor! and has the following format)
N5 lags75width75.precision75l7type_char

#he optional flags characters are)


: Ueft Oustifies the result padding on the right with spaces" If this flag is not present the result is right-Oustified padded on the left with 9eroes or spaces" (orces a plus or minus sign to preceded the numerical value"

-space character. A space character forces a space to precede a positive number" If the value to be printed is negative a minus sign precedes the value"

#he optional ,idt$ specifier sets the minimal width of an output value" If the result of the conversion is wider than the field width the field is e%panded to accommodate the result" #he following ,idt$ specifiers are supported)
n (orces at least n characters to be output" If the result has less than n characters then its field is padded with spaces" If the : flag is used the result field is padded on the right otherwise it is padded on the left"

@n

(orces at least n characters to be output" If the result has fewer than n characters it is padded on the left with 9eroes"

#he optional precision specifier sets the ma%imal number of characters or minimal number of integer digits that ma! be outputted" #he precision specifier alwa!s begins with a I"K in order to separate it from the ,idt$ specifier" #he following precision specifiers are supported)
"@ "n Dets the precision to = for the IiK IdK IuK I%K and IXK t!pe characters" (orces n characters or n decimal places to be output" Dpecificall! for the IiK IdK IuK I%K and IXK conversion t!pe characters if the value has fewer than n digits then it is padded on the left with 9eros" If the value has more than n digits then it will not be truncated" (or the IsK and IpK conversion t!pe characters no more than n characters from the string are output"#he IeK IEK and If K conversion t!pe characters are output with n digits to the right of the decimal point"#he precision specifier has no effect on the IcK conversion t!pe character"

If no precision specifier is entered the precision is set to = for the IiK IdK IuK I%K and IXK con- version t!pe characters" (or the IsK and IpK converstion t!pe characters the char string is output up to the first null character" #he optional IlK -lower case IUK. input si9e modifier specifies that the function argument must be treated as a long integer for the IiK IdK IuK I%K and IXK conversion t!pe characters" #he following conversion t!pe characters type c$ar, are supported)
c d i u % X e E f s p XX ,utputs the ne%t argument as an ADCII character ,utputs the ne%t argument as a decimal integer ,utputs the ne%t argument as a decimal integer ,utputs the ne%t argument as an unsigned decimal integer ,utputs the ne%t argument as an unsigned he%adecimal integer using lowercase letters ,utputs the ne%t argument as an unsigned he%adecimal integer using uppercase letters ,utputs the ne%t argument as a float formatted in scientific notation V-Wd"ddddd eV-Wdd ,utputs the ne%t argument as a float formatted in scientific notation V-Wd"ddddd EV-Wdd ,utputs the ne%t argument as a float formatted as V-Wddd"ddddd ,utputs the ne%t argument as a null terminated character string located in D0AM ,utputs the ne%t argument as a null terminated character string located in (UADQ ,utputs the X character

0eturns) None
#include <mega$3.h> #include <stdio.h> )# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% void main(void) ( unsigned int [; char c; )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; or ([*%;[<*-%%;[C*2-%) ( )) print the current value o [ print (JIecimalM NuKt6exadecimalM N<KnKrJ![![); print (JTero Padded IecimalM N%uKnKrJ![); print (JOour Iigit 8ower Hase 6exadecimalM N%/xKrKnKnJ![); 0 while ($) ( )# receive the character #) c*getchar(); )# and echo it bac& #) print (J?he received character was NcKnKrJ!c); 0 0

0esults) #he following is output b! the microprocessor to the HDA0# at startup"


IecimalM % 6exidecimalM % Tero Padded IecimalM %%%%% Oour Iigit 8ower Hase 6exadecimalM %%%%

IecimalM 2-% 6exidecimalM O; Tero Padded IecimalM %%2-% Oour Iigit 8ower Hase 6exadecimalM %% a IecimalM -%% 6exidecimalM $O/ Tero Padded IecimalM %%-%% Oour Iigit 8ower Hase 6exadecimalM %$ /

#hen an! character received b! the HDA0# is transmitted bac$ preceded b! the specified string" (or e%ample if the character I9K is received this te%t is sent to the transmitter"
?he received character was '.

)utc'ar 5include 6stdio"h7 void putchar-char.8 #he putc$ar function is a standard C language I+, function but it has been adapted to wor$ on embedded microcontrollers with limited resources" #he putc$ar function transmits a character using the HDA0#" #his function uses polling to transmit the character using the HDA0#" As a result the function waits indefinitel! for a character to be transmitted before returning" Prior to this function being used the HDA0# must be initiali9ed and the HDA0# transmitter must be enabled" If another peripheral is to be used for transmitting the putc$ar function can be modified ac- cordingl!" #he source for this function is in the stdio"h file" If !ou want to replace the standard librar! putc$ar with !our own version !ou must do three things" (irst !ou must place the new putc$ar function in the "c file before including the stan- dard librar!" Decond !ou must follow the new putc$ar function with a definition statement telling the compiler to ignore an! other putc$ar functions that it finds" (inall! include the standard librar!" Put together the code might appear as
void ( 0 #de ine _;8?=@>;?=_PD?H6;@_ #include <stdio.h> )) the rest o the source ile4 putchar (void) )) your putchar routine statements here

#he standard putc$ar/0 returns) None


#include <mega$3.h> #include <stdio.h>

)# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% void main(void) ( char &; )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; while ($) ( )# receive the character #) &*getchar(); )# and echo it bac& #) putchar(&); 0 0

0esults) Characters received b! the HDA0# are echoed bac$ from the HDA0# until power is removed from the processor" )uts 5include 6stdio"h7 void Cstr.8 puts-char

#he puts function transmits the string str using the standard putc$ar function or an alternate putc$ar function if one has been defined" #he string must be null-terminated" A newline character is appended to the end of the string when it is transmitted" (inall! the string must be located in D0AM" -Dee putsf for strings located in (UADQ". #he putc$ar function defaults to transmitting characters using the HDA0#" 0eturns) None
#include <mega$3.h> #include <stdio.h>

)# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% char hello_str57 * J6ello XorldJ; void main(void) ( )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; puts(hello_str); while ($) ( 0 0

0esults) &Qello *orld' with line feed but not carriage return is transmitted using the HDA0#" )utsf 5include 6stdio"h7 void Cstr.8 putsf-char flash

#he putsf function transmits the contant string str using the standard putc$ar function or an alternate putc$ar function if one has been defined" #he string must be null-terminated" A newline character is appended to the end of the string when it is transmitted" (inall! the string must be located in (UADQ" -Dee puts for strings located in 0AM". #he putc$ar func- tion defaults to transmitting characters using the HDA0#" 0eturns) None
#include <mega$3.h> #include <stdio.h> )# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8

)# 9aud rate #) #de ine baud ,3%% char lash hello_str57 * J6ello XorldJ;

void main(void) ( )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; puts (hello_str); while ($) ( 0 0

0esults) &Qello *orld' with line feed but not carriage return is transmitted using the HDA0#" ran! 5include 6stdlib"h7 int rand-void.8 #he rand function returns a pseudo-random number between @ and 1<NAN" 0eturns) None
#include <mega$3.h> #include <stdio.h> #include <stdlib.h> )) this to include putchar and print 4

)# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% void main(void) (

int seed; int rand_num; )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; puts (J=nter a seed value ollowed by =>?=@. J); scan (JNdKnJ!Gseed); srand(seed); )) seed the generator puts (JKnKrEend anything to get a pseudo+random number4KnKrJ); while ($) ( getchar(); )) this will return when EQ:=?6R>B is received rand_num * rand(); print (JNdKnKrJ!rand_num); 0 0

0esults) #he HDA0# transmits at 3A@@ baud


=nter a seed value ollowed by =>?=@.

,nce a value is entered the following is printed)


Eend anything to get a pseudo+random number4

Hpon the receipt of an! character b! the HDA0# the ne%t random number is transmitted" Notice that if !ou start with the same seed !ou get the same number seEuence each time" rea oc 5include 6stdlib"h7 void Crealloc-void Cptr unsigned int si9e.8 #he realloc function changes the si9e of a memor! bloc$ previousl! allocated in the heap b! alloc or calloc. #he si#e argument specifies the new si9e of the memor! bloc$" ,n success the function returns a pointer to the start of the newl! allocated memor! bloc$ the contents of which are a cop! of the previousl! allocated bloc$ of memor!" If the newl! allocated memor! bloc$ is larger in si9e than the old one the si9e difference is not filled with 9eros" #he allocated memor! bloc$ occupies si#eFB b!tes in the heap" #his must be ta$en into account when specif!ing the heap si9e in the ProOectPConfigurePC CompilerP Code Mener- ation menu"

0eturns) If successful in finding contiguous free memor! with si#e b!tes returns a pointer to the memor! bloc$" If unsuccessful returns a null pointer"
void main(void) ( int i; cptr * >D88; )) initiali'e the pointers to null4 start_cptr * >D88; )) DE;@? initiali'ation )) Hommunication ParametersM 1 Iata! $ Etop! >o Parity )) DE;@? @eceiverM Qn )) DE;@? ?ransmitterM Qn )) DE;@? :odeM ;synchronous )) DE;@? 9aud rateM ,3%% DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; D9@@6*%x%%; D9@@8*xtal)$3)baud+$; while ($) ( puts (JKnKr6ow much memory should R illS(=>?=@)KnKrJ); i (scan (JNdJ!Gmemory_si'e) 4* +$) ( i (memory_si'e < (_6=;P_ERT=_ + /)) ( print (JKnKr?han&s! RFll try4KnKrJ); )) try to get enough memory i (start_cptr ** >D88) start_cptr * malloc(memory_si'e); else start_cptr * realloc(start_cptr!memory_si'e); cptr * start_cptr; i (cptr 4* >D88) ( print (JKnKrRnitial Ualues4KnKrJ); or (i*%;i<memory_si'e;iCC) ( print (JN%2< J!#cptr);))print the initial value #cptr * (char)i C $; )) change the value cptrCC; )) move the pointer orward4 i (((iC$)N$%) ** %)

print (JKnKrJ); 0 print (JKnKr:odi ied Ualues4KnKrJ); cptr * start_cptr; )) print the new values4 or (i*%;i<memory_si'e;iCC) ( )) print the modi ied value4 print (JN%2< J!#cptrCC); i (((iC$)N$%) ** %) print (JKnKrJ); 0 0 else print (JOailed to realloc correctly.KnKrJ); 0 else ( print (JKnKr6eap si'e limit is NdKnKrJ!_6=;P_ERT=_+/); 0 0 0 )) i we were going on to do other things we would L reeL the )) memory here4 ree(start_cptr); 0

0esults) #he HDA0# transmits at 3A@@ baud


6ow much memory should R illS(=>?=@)

#hen it waits until a number is entered followed b! a newline character" ,nce this is received -=2 for e%ample. it transmits
?han&s! RFll try4 Rnitial Ualues4 xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx :odi ied Ualues4 %$ %2 %2 %/ %- %3 %. %1 %, %; %9 %H %I %= %O

Note that the xxKs above represent the fact that these values are dependent upon what was previousl! in the memor! locations allocated using realloc. scanf 5include 6stdio"h7 signed char scanf-char flash Cfmtstr.8

#he scanf function inputs values from a te%t string according to the format specifiers in the f tstr string and places the values in memor! locations also specified b! f tstr. #he format- ting section of the f tstr string is enclosed in Euotes and uses format specifiers listed below to tell scanf what $inds of values are to be read" #he second part of f tstr lists the addresses of where the read values are to be stored" A##EN#I,NJ It is important to alwa!s specif! a pointer to the variable to receive the value in the f tstr of the scanf function not the variable itself" (ailing to pass pointers to the scanf function causes erratic results because values are being stored in the memor! locations re- lated to the value of the variable passed instead of being stored at the address of the variable" #he receiving of characters is performed using the getc$ar function" #he getc$ar function de- faults to receiving using the HDA0#" An alternate getc$ar function can be defined to receive the data from an alternate source" Dee getc$ar for details" #he format specifier string f tstr is a constant and must be located in (UADQ memor!" #he implementation of scanf is a reduced version of the standard C function" #his was necessar! due to the specific needs of an embedded s!stem and because the full implementation would reEuire a large amount of memor!" #he following format specifiers are available)
Xc Xd Xi Xu X% Xs Inputs the ne%t argument as an ADCII character Inputs the ne%t argument as a decimal integer Inputs the ne%t argument as a decimal integer Inputs the ne%t argument as an unsigned decimal integer Inputs the ne%t argument as an unsigned he%adecimal integer Inputs the ne%t argument as a null terminated character string

0eturns) Number of successful entries or a := if an error occurred


#include <mega$3.h> #include <stdio.h> )# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% void main(void) ( char your_initial; int your_number;

)# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; while ($) ( puts (JKnKrJ); puts (JPlease enter your irst initial ollowed by KrJ); puts (Ja comma then your avorite number.KrJ); puts (JPress =nter to inish.KrJ); )) tell scan what to loo& or )) >Q?RH= the ;II@=EE=E o the variables are sent to scan 4 i (scan (JNc!NdKnJ!Gyour_initial!Gyour_number) ** 2) ( print (JNc! congrats4 Aou got a NdNN on your exam4KnKrJ! your_initial! your_number); 0 else puts (JR didnFt understand. Please try again.KnKrJ); 0 0

0esults) #he HDA0# transmits the prompt for an initial and a number"
Please enter your irst initial ollowed by a comma then your avorite number. Press =nter to inish.

#he scanf function waits for the initial comma number and newline character before con- tinuing" If the user enters
E! 22

the following is printed)


E! congrats4 Aou got a 22N on your exam4

If the user enters something li$e


E! ;H

#hen an error occurs and this is printed)


R didnFt understand. Please try again.

si"n 5include 6math"h7 signed char sign-int %.8 signed char csign-signed char %.8 signed char lsign -long %.8 signed char fsign -float %.8 #he sign function returns the sign of the integer x. It returns := if the sign of x is negative @ if x is 9ero or = if x is a positive value" #he csign, lsign, and fsign functions return the sign of the signed char long and float variable x, respectivel!" 0eturns)
G := if x is a negative value G @ if x is 9ero G = if x is a positive value
#include <math.h> void main() ( signed char pos_sign; signed char neg_sign; signed char 'ero_sign; neg_sign * sign(+$,-./); pos_sign * lsign($2-%%%); 'ero_sign * csign(%); while($) ( 0 0 )) get the sign o )) get the sign o )) get the sign o an integer a long a char

0esults)
pos_sign * $ neg_sign * +$ 'ero_sign * %

sin 5include 6math"h7 float sin-float %.8

#he sin function calculates the sine of the floating point number x. #he angle x is e%pressed in radians" 0eturns) sin-%.
#include <math.h> void main() ( loat new_val; new_val * sin(-.$2$); while($) ( 0 0

0esults) new>val ? :@"3=4 sin' 5include 6math"h7 float sinh-float %.8 #he sin$ function calculates the h!perbolic sine of the floating point number x. #he angle x is e%pressed in radians" 0eturns) sinh-%.
#include <math.h> void main() ( loat new_val; new_val * sinh(-.$2$); while($) ( 0 0

0esults) new>val ? 41"NB4 s ee)(!isab e 5include 6sleep"h7 void sleep>disable-void.8

#he sleep%disable function clears the DE bit in the MCHC0 register" #his prevents the microcontroller from accidentall! entering sleep mode" 0eturns) None
#include #include #include #include <mega$3.h> <stdio.h> <sleep.h> <delay.h>

)# "uart' crystal re"uency 56'7 #) #de ine xtal 3%%%%%%8 )# 9aud rate #) #de ine baud ,3%% interrupt 5=<?_R>?$7 void int$_isr(void) ( puts (JR was interrupted4KrJ); 0 void main(void) ( PQ@?I * %xOO; II@I * %x%%; :HDH@ * %x%%; BR:E\ * %x1%;

)) turn on internal pull+up on pin2 )) ma&e R>?$ (PQ@?I pin 2) an input )) low level interrupt on R>?$ )) turn on R>?$ interrupts

)# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; #asm(JseiJ); sleep_enable(); )) enable interrupts )) enable us to go to sleep when we are ready4

puts (J@eset QccurredKrJ); while ($) ( puts (JBood >ight4KrJ); puts (JR am going to sleep until you bug me4KrJ);

delay_ms($%%); )) wait or string to be transmitted4 idle(); )) enter idle until R>?$ wa&es us up sleep_disable(); )) stop uture sleeps 0 0

0esults) #he microprocessor transmits


@eset Qccurred Bood >ight4 R am going to sleep until you bug me4

#hen it enters idle sleep mode and wa$es up onl! when an IN#= interrupt occurs b! P,0#D pin 1 being held low or an e%ternal reset occurs" Hpon wa$ing up it continues e%- ecuting at the instruction following the idle function" It transmits the following continu- ousl! while P,0#D pin 1 is held low)
R was interrupted4

#he ne%t line disables entering sleep mode" Do although the microprocessor tries to call idle to go to sleep it does not" #he microprocessor continuousl! prints the above lines without a pause until power is removed" s ee)(enab e 5include 6sleep"h7 void sleep>enable-void.8 #he sleep%enable function sets the DE bit in the MCHC0 register" #his bit must be set to allow the microcontroller to enter sleep mode when the DUEEP instruction is e%ecuted" *hen in sleep mode some features of the microcontroller are stopped allowing it to consume less power" Depending on the t!pe of sleep the microcontroller can be awa$ened b! internal or e%ternal interrupts" #he particular sleep modes available depend upon the microcontroller being used" 0efer to Atmel A/0 datasheets for the t!pes of sleep modes and their availabilit!" 0eturns) None
#include #include #include #include <mega$3.h> <stdio.h> <sleep.h> <delay.h>

)# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%%

void main(void) ( PQ@?I * %x%/; II@I * %xO9; :HDH@ * %x%%; BRO@ * %x/%;

)) turn on internal pull+up on pin2 )) ma&e R>?% (PQ@?I pin 2) an input )) low level interrupt on R>?% )) turn on R>?% interrupts

)# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; #asm(JseiJ); sleep_enable(); )) enable interrupts )) enable us to go to sleep when we are ready4

puts (J@eset QccurredJ); while ($) ( puts (JBood >ight4J); puts (JR am going to sleep until you bug me4J); idle(); )) enter idle until R>?% wa&es us up puts (JR was interrupted4J); sleep_disable(); )) stop uture sleeps 0 0

0esults) #he microprocessor transmits


@eset Qccurred Bood >ight4 R am going to sleep until you bug me4

#hen it enters idle sleep mode and wa$es up onl! when an IN#@ interrupt occurs b! P,0#D pin < being held low or an e%ternal reset occurs" Hpon wa$ing up it continues e%ecuting at the instruction following the idle function" Hpon wa$ing up it will transmit
R was interrupted4

#he microprocessor continues to run the while loop until power is removed"

s)i 5include 6spi"h7 unsigned char spi-unsigned char data.8 Derial Peripheral Interface -DPI. allows high-speed s!nchronous data transfer between devices" Man! of the Atmel A/0 devices have hardware DPI ports" DPI ports allow data to be simultaneousl! transmitted and received over three connections) cloc$ master-in-slave-out -MID,. and master-out-slave-in -M,DI." #he master generates the cloc$ signal and places data on the M,DI pin s!nchroni9ed to the cloc$ signal" #he slave places data on the MID, line also s!nchroni9ed with the cloc$" In this wa! data is transmitted and received b! both the master and the slave at the same time" ,nce the DPI port is initiali9ed data transfer begins b! placing data on the DPI data register if the microcontroller is the master" ,therwise the microcontroller must wait for the cloc$ from the master to transfer the data" After the data transfer is complete the DPI data register contains the value read from the other device" Dee the Atmel A/0 datasheets for the reEuirements for initiali9ing the DPI port" #he DPI functions are intended for eas! interfacing between C programs and various peripherals using the DPI bus" #he function spi loads the DPI data register with the b!te data, and then waits for the hardware to complete cloc$ing the data out and reading the data from the peripheral device" ,nce the transfer is complete the spi function returns the data from the DPI data register" Polling is used b! spi to determine when the transfer is complete so the DPI interrupts do not need to be enabled before this function is called" 0eturns) Character read from the DPI data register after the completion of the transfer
#include #include #include #include <mega$3.h> <delay.h> <spi.h> <stdio.h> rom an ;tmel ;?/-I%1$ Olash

)) ?his example reads the status )) memory chip )) over EPR. #de ine xtal .2.2%%%8 int stats; void main(void) ( char [un&; PQ@?; * %xOO; PQ@?9 * %x%%; PQ@?H * %x%%; PQ@?I * %x$%;

)) clear port registers

II@; II@9 II@H II@I

* * * *

%x%2; %x9O; %x%2; %xOO;

)) )) )) ))

all all all all

inputs! except the lights4 outputs! except :REQ pin4 inputs except or bit % and $ outputs

)# Eerial Peripheral inter ace setup #) EPH@ * %x-=; E@=B * %x%%; BR:E\ * %x%%; ))Iisable interrupts ))no external interrupts

)# DE;@? #) )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; delay_ms(2%%%); )) wait or things to get stable PQ@?I./ * %; )) pull the chip select line low delay_ms(-); )) to get status send command %x-. %x%% )) status is returned while the second byte o the command is )) being sent spi(%x-.); ))byte $ stats * (int) spi(%x%%); ))byte 2 PQ@?I./ * $; )) release the chip select line print (JEtatusM N<KnKrJ!stats); while($) ( 0 0

0esults) #he microprocessor transmits at 2NA@@ baud on power-up


EtatusM ;%

s)rintf 5include 6stdio"h7 void sprintf-char Cstr char flash Cfmtstr V arg= arg< " " "W.8 #he sprintf function copies the formatted te%t according to the format specifiers in the f tstr string to the string str. A null termination is appended to the end of str after the formatted

te%t is copied to it" #he memor! for str should be large enough to accommodate the copied te%t and the null termination" #he format specifier string f tstr is a constant and must be located in (UADQ memor!" sprintf interprets f tstr in the e%act same manner as printf interprets f tstr. Dee printf for more information on format specifiers" s-r t 5include 6math"h7 float sErt-float %.8 unsigned char isErt-unsigned int %.8 unsigned int lsErt -unsigned long %.8 #he sqrt function returns as a floating point variable the sEuare root of the positive floating point variable x. #he isqrt and lsqrt functions return the sEuare root of unsigned integer and unsigned long variables x, respectivel!" Notice the reduction in si9e from unsigned integer to unsigned char and from unsigned long to unsigned integer in the isqrt and lsqrt functions" 0eturns) sqrt : the sEuare root of the positive floating point variable x isqrt : the sEuare root of the unsigned integer variable x as an unsigned char lsqrt : the sEuare root of the unsigned long variable x as an unsigned integer
#include <math.h> void main() ( unsigned char my_i_s"rt; unsigned int my_l_s"rt; loat my_ _s"rt; my_ _s"rt * s"rt(3./); )) get the s"uare root o a loat my_l_s"rt * ls"rt(2-%%%%); )) get the s"uare root o a long value my_i_s"rt * is"rt(1$); )) get the s"uare root o an int value while($) ( 0 0

0esults)
my_ _s"rt * 2.-2% my_l_s"rt * -%% my_i_s"rt * ,

sran! 5include 6stdlib"h7 void srand-int seed.8 #he srand function sets the seed value used b! the pseudo-random number generator rand. 0eturns) None Dee rand for a code e%ample" sscanf 5include 6stdio"h7 signed char sscanf-char Cfmtstr.8 Cstr char flash

#he sscanf function inputs values from the te%t string str, located in D0AM according to the format specifiers in the f tstr string and places the values into memor! locations also spec- ified b! f tstr. #he formatting section of the f tstr string is enclosed in Euotes and uses for- mat specifiers listed below to tell sscanf what $inds of values are to be read" #he second part of f tstr lists the addresses of where the read values are to be stored" A##EN#I,NJ It is important to alwa!s specif! a pointer to the variable to receive the value in the f tstr of the sscanf function and not the variable itself" (ailing to pass pointers to the sscanf function causes erratic results because values are being stored in the memor! locations related to the value of the variable passed instead of being stored at the address of the variable" #he format specifier string f tstr is a constant and must be located in (UADQ memor!" #he implementation of sscanf is a reduced version of the standard C function" #his was necessar! due to the specific needs of an embedded s!stem and because the full implementation would reEuire a large amount of memor! space" #he following format specifiers are available)
Xc Xd Xi Xu X% Xs Inputs the ne%t argument as an ADCII character Inputs the ne%t argument as a decimal integer Inputs the ne%t argument as a decimal integer Inputs the ne%t argument as an unsigned decimal integer Inputs the ne%t argument as an unsigned he%adecimal integer Inputs the ne%t argument as a null-terminated character string

0eturns) Number of successful entries or a := if an error occurred


#include <mega$3.h>

#include <stdio.h>

)# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% char EQO?X;@=_U=@ERQ>57 * J2.-bJ; void main(void) ( char version_letter; int ma[or_version; int minor_version; char results; )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; )) tell sscan what to loo& or )) >Q?RH= the ;II@=EE=E o the variables are sent to sscan 4 results * sscan (EQO?X;@=_U=@ERQ>!JNd.NdNcJ!Gma[or_version! Gminor_version!Gversion_letter); i ( (results 4* +$) print (J:a[or UersionM Nd! :inor Uersion Nd! 8etter Nc.KnKrJ! ma[or_version! minor_version! version_letter); 0 else puts (J;n error occurred. Eomething is not right4KrJ);

while ($) ( 0 0

0esults) #he HDA0# transmits the following)


:a[or UersionM 2! :inor Uersion -! 8etter b.

stan!by 5include 6sleep"h7 void standb!-void.8 #he standby function puts the A/0 microcontroller into standb! mode" #his is a sleep mode and similar to the po,erdo,n function" Dee po,erdo,n in this appendi% for the function use" Dee the Atmel datasheets for the complete description of this sleep mode as it applies to a particular A/0 device" Dtandb! sleep mode is not available on all A/0 devices" +strcat, +strcatf 5include 6string"h7 char Cstrcat-char Cstr= char Cstr<.8 char Cstrcatf-char Cstr<.8 Cstr= char flash

#he strcat and strcatf functions concatenate string str2 onto the end of string str1. #he memor! allocated for str1 must be long enough to accommodate the new longer string plus the null-terminating character or else une%pected results occur" (or the function strcatf, str2 must point to a string located in (UADQ" A pointer to str1 is returned" 0eturns) Cstr1 -a pointer to the null-terminated concatenation of strings str1 and str2.
#include <mega$3.h> #include <stdio.h> #include <string.h> )# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% void main(void) ( char stra57 * JabcJ; char strb5$%7; )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%;

DHE@9*%xI1; DHE@H*%x13; strcpy (strb!Jxy'J); strcat(strb!stra); strcat (strb!J$22J); puts(strb); while ($) ( 0 0 )) initiali'e strb4 )) add stra to strb )) add a lash string too4 )) put it out to the DE;@?4

0esults) #he HDA0# transmits at 3A@@ baud


xy'abc$22

+strc'r 5include 6string"h7 char Cstrchr-char Cstr char c.8 #he strc$r function locates the first occurrence of the character c in the string str. If the char- acter c is not found within the string then a null pointer is returned" 0eturns) A pointer to the first occurrence character c in string str8 if c is not found in str, a null pointer is returned
#include <mega$3.h> #include <stdio.h> #include <string.h> )# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% void main(void) ( char stra57 * J$22./-J; char #strb; )) no need to allocate space! pointing )) into stra ] already allocated4 )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$;

)# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; strb * strchr(stra!L.L); print (JOull EtringM NsKnKr>ew EtringM NsKnKrJ!stra!strb); #strb * LSL; )) replace the decimal point with a S print (J:odi ied stringM NsKnKrJ!stra); while ($) ( 0 0

0esults) #he HDA0# transmits at 3A@@ baud


Oull EtringM $22./>ew EtringM ./:odi ied EtringM $22S/-

strc%), strc%)f 5include 6string"h7 signed char strcmp-char Cstr= char Cstr<.8 signed char strcmpf-char Cstr= Cstr<.8 char flash

#he strc p and strc pf functions compare string str1 with string str2. (or the function strc pf, the str2 must point to a string located in (UADQ" #he functions start comparing with the first character in each string" *hen the character in str1 fails to match the character in str2, the difference in the character values is used to determine the return value of the function" #he return value of the function is the result of the subtraction of the ADCII code of the character from str2 from the ADCII code of the character from str1. 0eturns)
G negative value if str1 6 str2 4 9ero if str1 ? str2 4 positive value if str1 7 str2
#include <string.h> char stra57 char strb57 signed char signed char * JgeorgeJ; * JgeorgieJ; result; result ;

void main(void) ( result * strcmp(stra! strb); result * strcmp (stra! JgeorgeJ); while ($) ( 0 0

0esults)
result * %xOH result * % (LeL ] LiL < %)

+strc)y, +strc)yf 5include 6string"h7 char Cstrcp!-char Cdest char Csrc.8 char Cstrcp!f-char Cdest char flash Csrc.8 #he strcpy and strcpyf functions cop! the string pointed to b! src to the location pointed to b! dest. #he null-terminating character of the src string is the last character copied to the dest string" #he memor! allocated for the dest string must be large enough to hold the entire src string plus the null-terminating character" 0eturns) Pointer to dest
#include <mega$3.h> #include <stdio.h> #include <string.h> )# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% void main(void) ( char stra57 * J6elloJ; char strb537; char strc537;

)# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; strcpy(strb!stra); strcpy (strc!JXorldJ); puts(strb); puts(strc); while ($) ( 0 0 )) copy stra to strb )) copy JXorldJ to strc

)) transmit strb )) transmit strc

0esults) #he HDA0# transmits at 3A@@ baud


6ello Xorld

#he line feed between the lines is from calling the puts function" puts appends a line feed at the end of the string as it sends it to the HDA0#" strcs)n, strcs)nf 5include 6string"h7 unsigned char strcspn-char Cstr Cset.8 char

unsigned char strcspnf-char Cstr char flash Cset.8 #he strcspn and strcspnf functions return the inde% of the first character in the string str that matches a character in the string set. If none of the characters in the string str is in the string set, the length of str is returned" If the first character in the string str is in the string set, 9ero is returned" (or the function strspnf, the string set must be located in (UADQ" 0eturns) Inde% of the first character in str that is in set
#include <string.h> void main(void) ( char set57 * J$22/-3.1,%+()J; char stra57 * J$.1%%.---.$2$2J; char index_$; char index_2;

index_$ * strcspn(stra!set); index_2 * strcspn (stra!J.+()J); while ($) ( 0 0

0esults)
index_$ * % index_2 * $

str en, str enf 5include 6string"h7 (or the #INT memor! model)
unsigned char strlen(char #str);

(or the DMAUU memor! model)


unsigned int strlen(char #str);

(or either memor! model)


unsigned int strlen (char lash #str);

#he strlen and strlenf functions return the length of the string str, not counting the null terminator" (or the strlen function with the #INT memor! model in use the length can be from @ to <22" If the DMAUU memor! model is in use and strlen is called the length can be from @ to A2 212" #he function strlenf returns the length of a string located in (UADQ" #his length can be from @ to A2 212 regardless of the memor! model in use" 0eturns) Uength of the string str
#include <string.h> void main(void) ( char stra57 * J$22/-3.1,%J; unsigned char len$; unsigned int len2; len$ * strlen(stra); len2 * strlen (Jabcde ghi[&lmnop"rstuvwxy'J); while ($) ( 0 0

0esults)
len$ * $% len2 * 23

+strncat, +strncatf 5include 6string"h7 char Cstrncat-char Cstr= char Cstr< unsigned char n.8 char Cstrncatf-char Cstr= char flash Cstr< unsigned char n.8 #he strncat and strncatf functions concatenate a ma%imum of n characters from string str2 onto the end of string str1. #he memor! allocated for str1 must be long enough to accommodate the new longer string plus the null-terminating character or else une%pected results occur" (or the function strncatf, str2 must point to a string located in flash" A pointer to str1 is returned" 0eturns) Cstr1 -a pointer to the null-terminated concatenation of strings str1 and str2.
#include <mega$3.h> #include <stdio.h> #include <string.h> )# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% void main(void) ( char stra57 * JabcJ; char strb517; )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; strcpy (strb!Jxy'J); strncat(strb!stra!2); strncat (strb!J$22J!$); )) initiali'e strb4 )) add stra to strb )) add a lash string too4

puts(strb); while ($) ( 0 0

)) put it out to the DE;@?4

0esults) #he HDA0# transmits at 3A@@ baud


xy'ab$

strnc%), strnc%)f 5include 6string"h7 signed char strncmp-char Cstr= char Cstr< unsigned char n.8 signed char strcnmpf-char Cstr= char flash Cstr< unsigned char n.8 #he strnc p and strnc pf functions compare at most n characters from string str1 to string str2. (or the function strnc pf, str2 must point to a string located in (UADQ" #he functions start comparing with the first character in each string" *hen the character in str1 fails to match the character in str2, the difference in the character values is used to determine the return value of the function" #he return value of the function is the result of the subtraction of the ADCII code of the character from str2 from the ADCII code of the character from str1. An! differences between the strings be!ond the nt$ character are ignored" 0eturns)
G negative value if str1 6 str2 4 9ero if str1 ? str2 4 positive value if str1 7 str2
#include <string.h> void main(void) ( char stra57 char strb57 signed char signed char

* JgeorgeJ; * JgeorgieJ; result; result ;

result * strncmp(stra! strb!-); result * strncmp (stra! JgeorgeJ!3); while ($) ( 0 0

=4@

0esults)
result * % result * %

+strnc)y, +strnc)yf 5include 6string"h7 char Cstrncp!-char Cdest char Csrc unsigned char n.8 char Cstrncp!f-char Cdest char flash Csrc unsigned char n.8 #he strncpy and strncpyf functions cop! up to n characters from the string pointed to b! src to the location pointed to b! dest. If there are fewer than n characters in the src string then the src string is copied to dest and null-terminating characters are appended until the total number of characters copied to dest is n. If src string is longer than or eEual in length to n, then no terminating character is copied or appended to dest. 0eturns) Pointer to dest
#include <mega$3.h> #include <stdio.h> #include <string.h> )# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% char stra57 * J6elloJ; char strb57 * J6=88QJ; char strc537; void main(void) ( )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; strncpy(strb!stra!2); )) copy stra to strb

strncpy (strc!JXorldJ!$%); )) copy JXorldJ to strc print (JNs NsKnKrJ!strb!strc); while ($) ( 0 0

0esults) Dince &2' is less than the total length of &stra' the first three letters are copied over &strb' but no terminating null is copied" As a result the original null termination is used to terminate &strb'" Do the HDA0# transmits at 3A@@ baud
6el8Q Xorld

+str)br0, +str)br0f 5include 6string"h7 char Cstrpbr$-char Cset.8 char Cstrpbr$f-char Cset.8 Cstr char

Cstr char flash

#he strpbr2 and strpbr2f functions search the string str for the first occurrence of a character from the string set. If there is a match the function returns a pointer to the character in the string str. If there is not a match a null pointer is returned" (or the function strpbr2f, the string set must be located in (UADQ" 0eturns) Pointer to the first character in str that matches a character in set
#include <mega$3.h> #include <stdio.h> #include <string.h> )# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% void main(void) ( char stra57 * J$$)2-)%%J; char set57 * J).!4+J; char strb57 * J>ovember 2-! 2%%%J; char #pos; char # pos;

)# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13;

pos * strpbr&(stra!set); )) ind irst )) occurrence o something4 pos * strpbr& (strb!J!.+J); print (JRnitial IateM NsKnKrJ!stra); print (JEtring ollowing matchM NsKnKrJ!pos); print (JVust the yearM NsKnKrJ! posC$); while ($) ( 0 0

0esults) #he HDA0# transmits at 3A@@ baud


Rnitial IateM $$)2-)%% Etring ollowing matchM )2-)%% Vust the yearM 2%%%

str)os 5include 6string"h7 char strpos-char Cstr char c.8 #he strpos function locates the first occurrence of the character c in the string str. #he inde% of the first occurrence of c is returned" If the character c is not found within the string then := is returned" 0eturns) Inde% of the first occurrence character c in string str5 if c is not found in str, := is returned
#include <mega$3.h> #include <stdio.h> #include <string.h> )# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%%

void main(void) ( char stra57 * J$$)2-)2%%%J; char month_day; char day_year; )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; month_day * strpos(stra!L)L); day_year * strrpos(stra!L)L); )) ind irst slash character )) ind last slash character

print (JEtarting EtringM NsKnKrJ!stra); )) replace slash character with dashes stra5month_day7 * L+L; stra5day_year7 * L+L; print (J:odi ied stringM NsKnKrJ!stra); while ($) ( 0 0

0esults) #he HDA0# transmits at 3A@@ baud


Etarting EtringM $$)2-)2%%% :odi ied EtringM $$+2-+2%%%

+strrc'r 5include 6string"h7 char Cstrrchr-char Cstr char c.8 #he strrc$r function locates the last occurrence of the character c in the string str. If the character c is not found within the string then a null pointer is returned" 0eturns) Pointer to the last occurrence of character c in string str5 if c is not found in str, a null pointer is returned
#include <mega$3.h> #include <stdio.h> #include <string.h>

)# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% void main(void) ( char stra57 * J$22./-..1,J; char #strb; )) no need to allocate space! pointing )) into stra ] already allocated4 )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; strb * strrchr(stra!L.L); print (JOull EtringM NsKnKr>ew EtringM NsKnKrJ!stra!strb); #strb * L3L; )) replace the decimal point with a print (J:odi ied stringM NsKnKrJ!stra); while ($) ( 0 0

0esults) #he HDA0# transmits at 3A@@ baud


Oull EtringM $22./-..1, >ew EtringM ..1, :odi ied EtringM $22./-3.1,

+strr)br0, +strr)br0f 5include 6string"h7 char Cstrrpbr$-char Cset.8 char Cstrrpbr$f-char Cset.8 Cstr char

Cstr char flash

#he strrpbr2 and strrpbr2f functions search the string str for the last occurrence of a character from the string set. If there is a match the function returns a pointer to the character in the string str. If there is not a match a null pointer is returned" (or the function strrpbr2f, the string set must be located in (UADQ"

0eturns) Pointer to the last character in str that matches a character in set
#include <mega$3.h> #include <stdio.h> #include <string.h> )# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% void main(void) ( char stra57 * J$$)2-)%%J; char set57 * J).!4+J; char strb57 * J>ovember 2-! 2%%%J; char #pos; char # pos; )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; pos * strrpbr&(stra!set); )) ind last )) occurrence o something4 pos * strrpbr& (strb!J!.+YWJ); print (JAear in $$)2-)%%M NsKnKrJ!pos); print (JEtring ollowing matchM NsKnKrJ! pos); while ($) ( 0 0

0esults) #he HDA0# transmits at 3A@@ baud


Aear in $$)2-)%%M )%% Etring ollowing matchM ! 2%%%

strr)os 5include 6string"h7 char strrpos-char Cstr char c.8

#he strrpos function locates the last occurrence of the character c in the string str. #he inde% of the last occurrence of c is returned" If the character c is not found within the string then := is returned" 0eturns) Inde% of the last occurrence of character c in string str 8 if c is not found in str, := is returned
#include <mega$3.h> #include <stdio.h> #include <string.h> )# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% void main(void) ( char stra57 * J$$)2-)2%%%J; char month_day; char day_year; )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; month_day * strpos(stra!L)L); day_year * strrpos(stra!L)L); )) )) ind irst slash character ind last slash character

print (JEtarting EtringM NsKnKrJ!stra); )) replace slash character with dashes stra5month_day7 * L+L; stra5day_year7 * L+L; print (J:odi ied stringM NsKnKrJ!stra); while ($) ( 0 0

0esults) #he HDA0# transmits at 3A@@ baud


Etarting EtringM $$)2-)2%%% :odi ied EtringM $$+2-+2%%%

strs)n, strs)nf 5include 6string"h7 unsigned char strspn-char Cstr char Cset.8 unsigned char strspnf-char Cstr char flash Cset.8 #he strspn and strspnf functions return the inde% of the first character in the string str that does not match a character in the string set. If all characters in the string str are in the string set, the length of str is returned" If no characters in the string str are in the string set, 9ero is returned" (or the function strspnf, the string set must be located in (UADQ" 0eturns) Inde% of the first character in str that is not in set
#include <string.h> void main(void) ( char set57 * J$22/-3.1,%+()J; char stra57 * J$.1%%.---.$2$2J; char index_$; char index_2; index_$ * strspn(stra!set); index_2 * strspn (stra!J.$22/-3.1,%+()J); while ($) ( 0 0

0esults)
index_$ * $ index_2 * $/

+strstr, +strstrf 5include 6string"h7 char Cstrstr-char Cstr= char Cstr<.8 char Cstrstr-char Cstr= char flash Cstr<.8 #he strstr and strstrf functions search string str1 for the first occurrence of string str2. If str2 is found within str1, then a pointer to the first character of str2 in str1 is returned" If str2 is

not found in str1, then a null is returned" (or the function strstrf, the string str2 must be located in (UADQ" 0eturns) Pointer to the first character of str2 in str1 or null if str2 is not in str1
#include <mega$3.h> #include <stdio.h> #include <string.h> )# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% void main(void) ( char stra57 * J@ed Breen 9lueJ; char strb57 * JBreenJ; char #ptr; char #ptr ; )# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; )) grab a pointer to where Breen is ptr * strstr(stra!strb); )) grab a pointer to where the ptr * strstr (stra! J9J); print print print print irst 9 is

(JEtarting EtringM NsKnKrJ!stra); (JEearch EtringM NsKnKrJ!strb); (J@esults Etring $M NsKnKrJ!ptr); (J@esults Etring 2M NsKnKrJ!ptr );

while ($) ( 0 0

0esults) #he HDA0# transmits at 3A@@ baud


Etarting EtringM @ed Breen 9lue Eearch EtringM Breen @esults Etring $M Breen 9lue @esults Etring 2M 9lue

+str to0 5include 6string"h7 char Cstrto$-char Cstr<.8 Cstr= char flash

#he function strto2 scans string str1 for the first to$en not contained in the string str2 located in (UADQ" #he function e%pects str1 to consist of a seEuence of te%t to$ens separated b! one or more characters from the string str2 -to$en separators." #his function ma! be called repetitivel! to parse through a string -str1. and retrieve to$ens that are separated b! $nown characters -str2." #he first call to strto2 with a non-null pointer for str1 returns a pointer to the first character of the first to$en in str1. #he function searches for the end of the to$en and places a nulltermination character at the first to$en separator -character from str2. following the to$en" DubseEuent calls to strto2 with a null passed for str1 return the ne%t to$en from str1 in seEuence until no more to$ens e%ist in str1. *hen no more to$ens are found a null is returned" Note that strto2 modifies str1 b! placing the null-termination characters after each to$en" #o preserve str1, ma$e a cop! of it before calling strto2. 0eturns) Pointer to the ne%t to$en in str1 or null if no more to$ens e%ist in str1
#include <mega$3.h> #include <stdio.h> #include <string.h> )# "uart' crystal re"uency 56'7 #) #de ine xtal .2.2%%%8 )# 9aud rate #) #de ine baud ,3%% char mytext57 * J(111)...+2222J; char lash separators57 * J()+J; void main(void) ( char area_code5/7; char #pre ix; char #post ix; char bac&up_copy5$/7;

)# initiali'e the DE;@?Fs baud rate #) D9@@6*%x%%; D9@@8*xtal)$3)baud+$; )# initiali'e the DE;@? control register @< G ?< enabled! no interrupts! 1 data bits #) DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; )) we want to &eep the original around too4 strcpy(bac&up_copy!mytext); )) grab a pointer to the area code strcpy(area_code!strto&(mytext! separators)); )) grab a pointer to the pre ix pre ix * strto&(%! separators); )) grab a pointer to the post ix post ix * strto&(%! separators);

print print print print

(JEtarting EtringM NsKnKrJ!bac&up_copy); (J;rea HodeM NsKnKrJ!area_code); (JPre ixM NsKnKrJ!pre ix); (JPost ixM NsKnKrJ!post ix);

while ($) ( 0 0

0esults) #he HDA0# transmits at 3A@@ baud


Etarting EtringM (111)...+2222 ;rea HodeM 111 Pre ixM ... Post ixM 2222

tan 5include 6math"h7 float tan-float %.8 #he tan function calculates the tangent of the floating point number x. #he angle x is e%pressed in radians" 0eturns) tan-%.

#include <math.h> void main() ( loat new_val; new_val * tan(-.$2$); while($) ( 0 0

0esults) new>val ? :<"1@3 tan' 5include 6math"h7 float tanh-float %.8 #he tan$ function calculates the h!perbolic tangent of the floating point number x. #he angle x is e%pressed in radians" 0eturns) tanh-%.
#include <math.h> void main() ( loat new_val; new_val * tanh(-.$2$); while($) ( 0 0

0esults) new>val ? @"333 toascii 5include 6ct!pe"h7 unsigned char toascii-char c.8 #he toascii function converts character c to a N-bit ADCII format" #his is performed b! the following definition)
#de ine toascii(c) (c) G %x.

0eturns) the ADCII value of c -values between @ and =<N.


#include <ctype.h> void main() ( char ascii_value; ascii_value * toascii(%x9$); while ($) ( 0 0

0esults) ascii>value ? @%1= ? I=K toint 5include 6ct!pe"h7 unsigned char toint-char c.8 #he toint function interprets the ADCII character c as a he%adecimal digit and returns an unsigned char from @ to =2" If the character is not a valid he%adecimal digit the function returns @" 0eturns) Hnsigned character from @ to =2 representing ADCII character c
#include <ctype.h> void main() ( unsigned char hex_value; hex_value * toint(LaL); while ($) ( 0 0

0esults) he%>value ? @%@a to o,er 5include 6ct!pe"h7 char tolower-char c.8 #he tolo,er function converts the ADCII character c from an uppercase character to a lowercase character" If c is a lowercase character c is returned unchanged" 0eturns) ADCII character c as a lowercase character
#include <ctype.h> void main() (

char lower_case_c; lower_case_c * tolower(LDL); while($) ( 0 0

0esults) lower>case>c ? IuK tou))er 5include 6ct!pe"h7 char toupper-char c.8 #he toupper function converts the ADCII character c from a lowercase character to an uppercase character" If c is an uppercase character c is returned unchanged" 0eturns) ADCII character c as an uppercase character
#include <ctype.h> void main() ( char upper_case_c; upper_case_c * toupper(LuL); while($) ( 0 0

0esults) upper>case>c ? IHK /)rintf 5include 6stdio"h7 void vprintf-char flash Cfmtstr va>list argptr.8 #he vprintf function is identical to the function printf e%cept that argptr is a pointer to a variable-length list of arguments" #his pointer is of the t!pe va%list. #he va%list t!pe is de- fined in the header file stdarg"h" 0eturns) None
#include <mega$3.h> )# include the standard input)output library #) #include <stdio.h> )# include the variable length argument lists macros #) #include <stdarg.h> #de ine xtal 3%%%%%%8 #de ine baud ,3%%

)# create custom print routine with a variable length argument list #) void custom_print(char lash #cp_ mtstr! int data_len! ...) ( int i; int total; )# total o the integer arguments #) va_list cp_argptr; )# pointer to a variable length argument list #) total * %; )# clear the tally #) )# initiali'e the variable length argument list pointer #) va_start(cp_argptr! data_len); print (JEtart o Hustom :essageKnKrJ); unction #)

)# use vprint to print out the values passed to our vprint (cp_ mtstr! cp_argptr);

)# now use the va_arg macro to return the values as integers #) or (i*%;i<data_len;iCC) total C* va_arg(cp_argptr!int); )# print the custom in ormation about the data sent4 #) print (Jdata_lenM NdKnKrJ!data_len); print (Jtotal valueM NdKnKrJ!total); print (J=nd o Hustom :essageKnKrJ); )# cleanup by calling the va_end macro to terminate the use o the pointer #) va_end(cp_argptr); 0 void main(void) ( )) DE;@? initiali'ation )) Hommunication ParametersM 1 Iata! $ Etop! >o Parity )) DE;@? @eceiverM Qn )) DE;@? ?ransmitterM Qn )) DE;@? :odeM ;synchronous )) DE;@? 9aud rateM ,3%% DHE@;*%x%%; DHE@9*%xI1; DHE@H*%x13; D9@@6*%x%%; D9@@8*xtal)$3)baud+$; custom_print(J:essage dataM Nd Nd Nd Nd Nd NdKnKrJ!3!$!2!2!.!,!1);

while ($) ; 0

0esults) #he HDA0# transmits at 3A@@ baud


Etart o Hustom :essage :essage dataM $ 2 2 . , 1 Iata_lenM 3 total valueM 2% =nd o Hustom :essage

/s)rintf 5include 6stdio"h7 void vsprintf-char Cstr char flash Cfmtstr argptr.8 va>list

#he vsprintf function performs almost e%actl! as vprintf performs e%cept that vsprintf copies the formatted te%t according to the format specifiers in the f tstr string to the string str instead of to the HDA0#" A null termination is appended to the end of str after the for- matted te%t is copied to it" #he memor! for str should be large enough to accommodate the copied te%t and the null termination" Dee printf for more information on format specifiers and vprintf for a code e%ample"

6$is page intentionally left blan2

7nde x

=3N

You might also like