You are on page 1of 31

22/09/2016

PICCLibraryTutorials

SHOP
TUTORIALS
8051
8051tutorials
Starter8051
AVR
AVRTutorials
StarterAVR
Atmega32Breakout
Atmega128Breakout
OneMicroATmega128
OneMicroATmega32
Arduino
ArduinoTutorials
ExploreM3
Tit
Atmega128Breakout
OneMicroATmega128
OneMicroATmega32
PIC
PICTutorials
StarterPIC16F877
StarterPIC18F45xx
StarterPIC18F4520
OneMicroATmega128
OneMicroATmega32
ARM
LPC1768Tutorials
ExploreM3BareMetal
LPC2148Tutorials
StarterPIC18F4520
OneMicroATmega128
OneMicroATmega32
DIY
DIYHobbyKits
ExploreM3BareMetal
LPC2148Tutorials
StarterPIC18F4520
OneMicroATmega128
OneMicroATmega32
Wireless
WiFiESP8266
ExploreM3BareMetal
LPC2148Tutorials
StarterPIC18F4520
OneMicroATmega128
OneMicroATmega32
RTOS
FreeRTOSwithArduino
RTOSTutorials
LPC2148Tutorials
StarterPIC18F4520
OneMicroATmega128
OneMicroATmega32
Login

ExploreEmbedded
SearchTutorials

https://exploreembedded.com/wiki/PIC_C_Library#UART

1/31

22/09/2016

PICCLibraryTutorials

8051
8051tutorials
Starter8051
AVR
AVRTutorials
StarterAVR
Atmega32Breakout
Atmega128Breakout
OneMicroATmega128
OneMicroATmega32
Arduino
ArduinoTutorials
ExploreM3
Tit
Atmega128Breakout
OneMicroATmega128
OneMicroATmega32
PIC
PICTutorials
StarterPIC16F877
StarterPIC18F45xx
StarterPIC18F4520
OneMicroATmega128
OneMicroATmega32
ARM
LPC1768Tutorials
ExploreM3BareMetal
LPC2148Tutorials
StarterPIC18F4520
OneMicroATmega128
OneMicroATmega32
DIY
DIYHobbyKits
ExploreM3BareMetal
LPC2148Tutorials
StarterPIC18F4520
OneMicroATmega128
OneMicroATmega32
Wireless
WiFiESP8266
ExploreM3BareMetal
LPC2148Tutorials
StarterPIC18F4520
OneMicroATmega128
OneMicroATmega32
RTOS
FreeRTOSwithArduino
RTOSTutorials
LPC2148Tutorials
StarterPIC18F4520
OneMicroATmega128
OneMicroATmega32

PICCLibrary

https://exploreembedded.com/wiki/PIC_C_Library#UART

2/31

22/09/2016

PICCLibraryTutorials

Contents
1Introduction
1.1Overview:
1.2Reference:
1.3Feedback:
1.4Disclaimer:
2ADC
2.1ADC_Init()
2.2ADC_StartConversion()
3Delay
3.1delay_us()
3.2delay_ms()
3.3delay_sec()
4Lcd_8_bitMode
4.1LCD_Init()
4.2LCD_Clear()
4.3LCD_GoToLineOne()
4.4LCD_GoToLineTwo()
4.5LCD_GoToXY()
4.6LCD_CmdWrite()
4.7LCD_DataWrite()
4.8LCD_DisplayString()
4.9LCD_DisplayNumber()
4.10LCD_ScrollMessage()
4.11LCD_DisplayRtcTime()
4.12LCD_DisplayRtcDate()
5Lcd_4_bitMode
5.1LCD_Init()
5.2LCD_CmdWrite()
5.3LCD_DataWrite()
6Keypad
6.1KEYPAD_Init()
6.2KEYPAD_WaitForKeyRelease()
6.3KEYPAD_WaitForKeyPress()
6.4KEYPAD_ScanKey()
6.5KEYPAD_GetKey()
7UART
7.1UART_Init()
7.2UART_RxChar()
7.3UART_TxChar()
7.4UART_TxString()
7.5UART_RxString()
7.6UART_TxNumber()
8I2C
8.1I2C_Clock()
8.2I2C_Start()
8.3I2C_Stop()
8.4I2C_Write()
8.5I2C_Read()
8.6I2C_Ack()
8.7I2C_NoAck()
9Ds1307_RTC
9.1DS1307_Init()
9.2DS1307_Write()
9.3DS1307_Read()
9.4DS1307_SetTime()
9.5DS1307_SetDate()
9.6DS1307_GetTime()
9.7DS1307_GetDate()
10EEPROM
10.1EEPROM_WriteByte()
10.2EEPROM_ReadByte()
10.3EEPROM_WriteNBytes()
10.4EEPROM_ReadNBytes()
10.5EEPROM_WriteString()
https://exploreembedded.com/wiki/PIC_C_Library#UART

3/31

22/09/2016

PICCLibraryTutorials

10.6EEPROM_ReadString()
10.7EEPROM_Erase()
11PICLibraryUsageGuide

Introduction
Overview:
Thismanualisdesignedtohelpembeddedprogrammersandstudents,rapidlyexploitthePic(16f877A)Controllerforembeddedapplications.
ThismanualhasbeentargetedatembeddedsystemsprogrammersandStudentswhohavebasicknowledgeofPic(16f877A/PIC18f)
architectureandCLanguage.
Thismanualprovidesthereferencetoallthelibraryfunctionswhicharegroupedunderrespective.cfile.The.cfilesconventionisasperthe
peripherals.Theperipherals(lcd,keypad..)areconnectedtodefaultPORTswhichcanbeconnecttorequiredPORTsbychangingthe#define..

Reference:
Itisrecommendedtogothroughthebelowreferencedocumentsanddatasheetsbeforeinterfacinganyperipherals.
1.ThePicMicrocontrollerandEmbeddedSystemsbyMuhammadAliMazidi.
2.Pic16f877ADataSheet.
3.EmbeddedCbyMichaelJPont.
4.Anyofthe16x2lcddatasheet.
5.RTCDS1307fromDallasSemiconductors.

Feedback:
Suggestionsforadditionsandimprovementsincodeanddocumentationarealwayswelcome.Pleasesendyourfeedbackviaemailto
feedback@xplorelabz.com

Disclaimer:
ThelibrarieshavebeentestedforPic16f877Aondifferentdevelopmentboards.WestronglybelievethatthelibraryworksonanyPic16f877A
boards.However,XploreLabzdisclaimsanykindofhardwarefailureresultingoutofusageoflibraries,directlyorindirectly.Documentation
maybesubjecttochangewithoutpriornotice.
Theusageoftoolsandsoftwaredemonstratedinthedocumentareforeducationalpurposeonly,allrightspertainingtothesebelongtothe
respectiveowners.Usersmustensurelicensetermsareadheredto,foranyuseofthedemonstratedsoftware.
GNUGENERALPUBLICLICENSE:ThelibrarycodeinthisdocumentislicensedunderGNUGeneralPublicLicense(GPL)Copyright(C)
2012.Everyoneispermittedtocopyanddistributeverbatimcopiesofthislicensedocument,butchangingitisnotallowed.Sincethelibraryis
licensedfreeofcharge,thereisnowarrantyforthelibrariesandtheentireriskofthequalityandperformanceiswiththeuser.
Errorsandomissionsshouldbereportedto:feedback@xplorelabz.com

ADC
PicADClibrary.

Filename:adc.c
Controller:Pic16f877A
Oscillator:20MHz
Author:XploreLabz
website:www.xplorelabz.com
Reference:Pic16f877adataSheet
#include<htc.h>
#include"delay.h"
#include"adc.h"
https://exploreembedded.com/wiki/PIC_C_Library#UART

4/31

22/09/2016

PICCLibraryTutorials

ADC_Init()
Description:ThisfunctioninitializestheADCcontrolregisters.
I/PArguments:none
Returnvalue:none

voidADC_Init()
{
ADCON0=0x00;//samplingfreq=osc_freq/2,ADCoffinitially
ADCON1=0x80;//Allpinsareconfiguredasadcandtheresultisrightjustified
}

ADC_StartConversion()
Description:ThisfunctiondoestheADCconversioinfortheSelectedChannelandreturnstheconverted10bitresult.
I/PArguments:char(channelnumber).
Returnvalue:int(10bitADCresult)

unsignedintADC_StartConversion(unsignedcharchannel)
{
ADCON0=((1<<ADON)|(channel<<3));//selectparticularchannelandturnONadc
delay_us(50);

GO=1;//StartADCconversion
while(GO==1);//Waitfortheconversiontocomplete

return((ADRESH<<8)+ADRESL);//returnrightjustified10bitresult
}

Delay
PICdelaylibrarywiththecrystalfrequency20Mhz

Filename:delay.c
Controller:Pic16F877A
Oscillator:20MHz
Author:XploreLabz
website:www.xplorelabz.com

#include<htc.h>
#defineDelayCountFor1msec300

delay_us()
Description:Thisfunctionisusedgeneratedelayinus.
Itgenaratesaapproximatedelayof3usforeachcount
if50ispassedastheargumentthenitgeneratesadelayofapprx150us.
https://exploreembedded.com/wiki/PIC_C_Library#UART

5/31

22/09/2016

PICCLibraryTutorials

I/PArguments:unsignedint
Returnvalue:none

voiddelay_us(unsignedintus_count)
{
while(us_count!=0)
{

us_count;

}
}

delay_ms()
Description:Thisfunctionisusedgeneratedelayinms.
Itgenaratesaapproximatedelayof1msforeachcount
if1000ispassedastheargumentthenitgeneratesdelayofapprx1000ms(1sec)
I/PArguments:unsignedint
Returnvalue:none

voiddelay_ms(unsignedintms_count)
{
while(ms_count!=0)

delay_us(DelayCountFor1msec);

ms_count;

//delay_usiscalledtogenerate1msdelay

delay_sec()
Description:Thisfunctionisusedgeneratedelayinsec.
Itgenaratesaapproximatedelayof1secforeachcount,
if10ispassedastheargumentthenitgeneratesdelayofapprx10sec
I/PArguments:unsignedchar
Returnvalue:none

Note:
Amaxof255secdelaycanbegeneratedwsingthisfunction.
voiddelay_sec(unsignedcharsec_count)
{

while(sec_count!=0)

delay_ms(1000);
//delay_msiscalledtogenerate1secdelay

sec_count;

}
}

Lcd_8_bitMode
https://exploreembedded.com/wiki/PIC_C_Library#UART

6/31

22/09/2016

PICCLibraryTutorials

PICLCDlibraryfor8bitmode

Filename:lcd_8_bit.c
Controller:Pic16F877A
Oscillator:20MHz
Author:XploreLabz
website:www.xplorelabz.com
Note:
PinconnectionforLCDdisplayin8bitmodeisasshownbelow.
BydefaulttheLCDisconnectedtoPORTB.
ThecodecanbemodifiedtoconnecttheLCDtoanyofthePORTsbychangingthe"#definedatabusPORTB".

#include<htc.h>
#include"delay.h"
#include"lcd.h"

#definedatabusPORTB//
LCDdatabusconnectedtoPORTB

#defineDataBusDirectionTRISB//DataandControlbusdirectionconfigregisters
#defineControlBusDirectionTRISD

#definersRD0
//RegisterselectpinconnectedtoPORTD.0
#definerwRD1
//ReadWritepinconnectedtoPORTD.1
#defineenRD2
//EnablepinconnectedtoPORTD.2

/*16x2LCDSpecification*/
#defineLCDMaxLines2
#defineLCDMaxChars16
#defineLineOne0x80
#defineLineTwo0xc0

#defineBlankSpace''

LCD_Init()
Functionname:LCD_Init()
Description:Thisfunctionisusedtoinitializethelcdin8bitmode.
I/PArguments:none
Returnvalue:none
voidLCD_Init()
{
delay_us(5000);

https://exploreembedded.com/wiki/PIC_C_Library#UART

7/31

22/09/2016

PICCLibraryTutorials

DataBusDirection=0x00;//Configuredataandcontrolbusasoutput
ControlBusDirection=0x00;

LCD_CmdWrite(0x38);//LCD2lines,5*7matrix
LCD_CmdWrite(0x0E); //DisplayONcursorON
LCD_CmdWrite(0x01); //CleartheLCD
LCD_CmdWrite(0x80); //MovetheCursortoFirstlineFirstPosition

LCD_Clear()
Description:ThisfunctionclearstheLCDandmovesthecursortofirstPosition.
I/PArguments:none
Returnvalue:none

voidLCD_Clear()
{
LCD_CmdWrite(0x01); //CleartheLCDandgotoFirstlineFirstPosition
LCD_CmdWrite(LineOne);
}

LCD_GoToLineOne()
Description:ThisfunctionmovestheCursortoFirstlineFirstPosition.
I/PArguments:none
Returnvalue:none

voidLCD_GoToLineOne()
{
LCD_CmdWrite(LineOne);
}

//MovetheCursortoFirstlineFirstPosition

LCD_GoToLineTwo()
Description:ThisfunctionmovestheCursortoSecondlineFirstPosition.
I/PArguments:none
Returnvalue:none

voidLCD_GoToLineTwo()
{
LCD_CmdWrite(LineTwo);
}

//MovetheCursortoSecondlineFirstPosition

LCD_GoToXY()
https://exploreembedded.com/wiki/PIC_C_Library#UART

8/31

22/09/2016

PICCLibraryTutorials

Description:ThisfunctionmovestheCursortospecifiedposition.
I/PArguments:charrow,charcol
1.row>linenumber(line1=0,line2=1),
1.For2lineLCDtheI/Pargumentshouldbeeither0or1.
2.col>charnumber.
1.For16charLCDtheI/Pargumentshouldbebetwen015.
Returnvalue:none

voidLCD_GoToXY(charrow,charcol)
{
charpos;

if(row<LCDMaxLines)
{

pos=LineOne|(row<<6);//takethelinenumber

//row0>pos=0x80row1>pos=0xc0

if(col<LCDMaxChars)

pos=pos+col;//takethecharnumber

//nowpospointstothegivenXYpos

LCD_CmdWrite(pos);
//MovetheCursortospecifiedPosition
}
}

LCD_CmdWrite()
Description:ThisfunctionsendsacommandtoLCDinthefollowingsteps.
step1:SendtheI/PcommandtoLCD.
step2:SelecttheControlRegisterbymakingRSlow.
step3:SelectWriteoperationmakingRWlow.
step4:SendaHightoLowpulseonEnablePINwithsomedelay_us.
I/PArguments:8bitcommandsupportedbyLCD.
Returnvalue:none

voidLCD_CmdWrite(charcmd)
{

databus=cmd;//SendthecommandtoLCD
rs=0;//SelecttheCommandRegisterbypullingRSLOW
rw=0;//SelecttheWriteOperationbypullingRWLOW
en=1;//SendaHightoLowPusleatEnablePin
delay_us(10);
en=0;

delay_ms(1);
}

LCD_DataWrite()
Description:ThisfunctionsendsacharactertobedisplayedonLCDinthefollowingsteps.
step1:SendthecharactertoLCD.
step2:SelecttheDataRegisterbymakingRShigh.
step3:SelectWriteoperationmakingRWlow.
step4:SendaHightoLowpulseonEnablePINwithsomedelay_us.
I/PArguments:ASCIIvalueofthechartobedisplayed.
Returnvalue:none
https://exploreembedded.com/wiki/PIC_C_Library#UART

9/31

22/09/2016

PICCLibraryTutorials

voidLCD_DataWrite(chardat)
{

databus=dat;//SendthedatatoLCD
rs=1;

//SelecttheDataRegisterbypullingRSHIGH
rw=0;

//SelecttheWriteOperationbypullingRWLOW
en=1;

//SendaHightoLowPusleatEnablePin
delay_us(10);
en=0;

delay_ms(1);

LCD_DisplayString()
Description:ThisfunctionisusedtodisplaytheASCIIstringonthelcd.
1.Thestring_ptrpointstothefirstcharofthestringandtraversestilltheend(NULLCHAR).
2.EachtimeacharissenttoLCD_DataWritefuntiontodisplay.
I/PArguments:String(Addressofthestring)tobedisplayed.
Returnvalue:none

voidLCD_DisplayString(char*string_ptr)
{
while(*string_ptr)
LCD_DataWrite(*string_ptr++);
}

LCD_DisplayNumber()
Functionname:LCD_DisplayNumber()
I/PArguments:unsignedint
Returnvalue:none
Description:Thisfunctionisusedtodisplaya5digitinteger(065535).
ex:
1.ifthenumberis12345then12345isdisplayed.
2.ifthenumberis123then00123isdisplayed.

voidLCD_DisplayNumber(unsignedintnum)
{
LCD_DataWrite((num/10000)+0x30);
https://exploreembedded.com/wiki/PIC_C_Library#UART

10/31

22/09/2016

PICCLibraryTutorials

num=num%10000;

LCD_DataWrite((num/1000)+0x30);
num=num%1000;

LCD_DataWrite((num/100)+0x30);
num=num%100;

LCD_DataWrite((num/10)+0x30);

LCD_DataWrite((num%10)+0x30);

LCD_ScrollMessage()
Description:Thisfunctionscrollsthegivenmessageonthefirstline.
1.16charsaredisplayedatatime.
2.Pointerisincrementedtoskipachareachtimetogivetheillusionofmovingchars.
3.Ifthecharsarelessthan16,thentheBlankSpacesaredisplayed.
I/PArguments:char*msg_ptr(msg_ptr>pointertothestringtobescrolled)
Returnvalue:none

voidLCD_ScrollMessage(char*msg_ptr)
{
unsignedchari,j;
LCD_CmdWrite(0x0c);

//DisabletheCursor
for(i=0;msg_ptr[i];i++)//Looptodisplaythecompletestring
{//eachtime16charsaredisplayedand
//pointerisincrementedtopointtonextchar

LCD_GoToLineOne();//MovetheCursortofirstline

for(j=0;j<LCDMaxChars&&msg_ptr[i+j];j++)//looptoDisplayfirst16Chars

LCD_DataWrite(msg_ptr[i+j]);//ortillNullchar

for(j=j;j<LCDMaxChars;j++)//Ifthecharsarebelow16
LCD_DataWrite(BlankSpace);//thendisplayblankspaces

delay_ms(300);
}
LCD_CmdWrite(0x0E);

//EnabletheCursor
}

LCD_DisplayRtcTime()
I/PArguments:charhour,charmin,charsec(hour,min,secshouldbepackedBCDformat,asreadfromDS1307)
Returnvalue:none
Description:Thisfunctiondisplayhour,min,secreadfromDS1307.

https://exploreembedded.com/wiki/PIC_C_Library#UART

11/31

22/09/2016

PICCLibraryTutorials

voidLCD_DisplayRtcTime(charhour,charmin,charsec)
{
LCD_DataWrite(((hour>>4)&0x0f)+0x30);
LCD_DataWrite((hour&0x0f)+0x30);
LCD_DataWrite(':');

LCD_DataWrite(((min>>4)&0x0f)+0x30);
LCD_DataWrite((min&0x0f)+0x30);
LCD_DataWrite(':');

LCD_DataWrite(((sec>>4)&0x0f)+0x30);
LCD_DataWrite((sec&0x0f)+0x30);

LCD_DisplayRtcDate()
I/PArguments:charday,charmonth,charyear(day,month,yearshouldbepackedBCDformat,asreadfromDS1307)
Returnvalue:none
Description:Thisfunctiondisplayday,month,yearreadfromDS1307.

voidLCD_DisplayRtcDate(charday,charmonth,charyear)
{
LCD_DataWrite(((day>>4)&0x0f)+0x30);
LCD_DataWrite((day&0x0f)+0x30);
LCD_DataWrite('/');

LCD_DataWrite(((month>>4)&0x0f)+0x30);

LCD_DataWrite((month&0x0f)+0x30);
LCD_DataWrite('/');

LCD_DataWrite(((year>>4)&0x0f)+0x30);

LCD_DataWrite((year&0x0f)+0x30);

Lcd_4_bitMode
PicLCDlibraryfor4bitmode

Filename:lcd_4_bit.c
Controller:Pic16F877A
Oscillator:20MHz
Author:XploreLabz
website:www.xplorelabz.com
Note:
PinconnectionforLCDdisplayin4bitmode.
BydefaulttheLCDisconnectedtoPORTB.
ThecodecanbemodifiedtoconnecttheLCDtoanyofthePORTsbychangingthe"#definedatabusPORTB".

https://exploreembedded.com/wiki/PIC_C_Library#UART

12/31

22/09/2016

PICCLibraryTutorials

#include<htc.h>
#include"delay.h"
#include"lcd.h"

#definedatabusPORTB//LCDdatabusconnectedtoPORTB
#defineDataBusDirectionTRISB//DataandControlbusdirectionconfigregisters

#definersRB0
//RegisterselectpinconnectedtoPORTB.0
#definerwRB1
//ReadWritepinconnectedtoPORTB.1
#defineenRB2
//EnablepinconnectedtoPORTB.2
/*16x2LCDSpecification*/
#defineLCDMaxLines2
#defineLCDMaxChars16
#defineLineOne0x80
#defineLineTwo0xc0
#defineBlankSpace''

LCD_Init()
Description:Thisfunctionisusedtoinitializethelcdin4bitmode.
Functionname:LCD_Init()
I/PArguments:none
Returnvalue:none

voidLCD_Init()
{
delay_us(5000);
DataBusDirection=0x00;//Configuredataandcontrolbusasoutput
LCD_CmdWrite(0x02); //InitilizetheLCDin4bitMode
LCD_CmdWrite(0x28);
LCD_CmdWrite(0x0E); //DisplayONcursorON
LCD_CmdWrite(0x01); //CleartheLCD
LCD_CmdWrite(0x80); //MovetheCursortoFirstlineFirstPosition

}
https://exploreembedded.com/wiki/PIC_C_Library#UART

13/31

22/09/2016

PICCLibraryTutorials

LCD_CmdWrite()
Description:ThisfunctionsendsacommandtoLCDinthefollowingsteps.
step1:SendtheHigherNibbleoftheI/PcommandtoLCD.
step2:SelecttheControlRegisterbymakingRSlow.
step3:SelectWriteoperationmakingRWlow.
step4:SendaHightoLowpulseonEnablePINwithsomedelay_us.
step5:SendtheLowerNibbleoftheI/PcommandtoLCD.
step6:SelecttheControlRegisterbymakingRSlow.
step7:SelectWriteoperationmakingRWlow.
step8:SendaHightoLowpulseonEnablePINwithsomedelay_us.
I/PArguments:8bitcommandsupportedbyLCD
Returnvalue:none

voidLCD_CmdWrite(charcmd)
{
databus=(cmd&0xf0);//SendtheHigherNibbleofthecommandtoLCD
rs=0;

//SelecttheCommandRegisterbypullingRSLOW
rw=0;

//SelecttheWriteOperationbypullingRWLOW
en=1;

//SendaHightoLowPusleatEnablePin
delay_us(10);
en=0;

delay_us(10);

//waitforsometime

databus=((cmd<<4)&0xf0);//SendtheLowerNibbleofthecommandtoLCD
rs=0;

//SelecttheCommandRegisterbypullingRSLOW
rw=0;

//SelecttheWriteOperationbypullingRWLOW
en=1;

//SendaHightoLowPusleatEnablePin
delay_us(10);
en=0;

delay_ms(1);
}

LCD_DataWrite()
Functionname:LCD_DataWrite()
Description:ThisfunctionsendsacharactertobedisplayedonLCDinthefollowingsteps.
step1:SendthehighernibbleofthecharactertoLCD.
step2:SelecttheDataRegisterbymakingRShigh.
step3:SelectWriteoperationmakingRWlow.
step4:SendaHightoLowpulseonEnablePINwithsomedelay_us.
step5:waitforsometime
step6:SendthelowernibbleofthecharactertoLCD.
step7:SelecttheDataRegisterbymakingRShigh.
step8:SelectWriteoperationmakingRWlow.
step9:SendaHightoLowpulseonEnablePINwithsomedelay_us.
I/PArguments:ASCIIvalueofthechartobedisplayed.
Returnvalue:none

voidLCD_DataWrite(chardat)
{

databus=(dat&0xf0);
rs=1;

rw=0;

en=1;

delay_us(10);

//SendtheHigherNibbleoftheDatatoLCD
//SelecttheDataRegisterbypullingRSHIGH
//SelecttheWriteOperationbypullingRWLOW
//SendaHightoLowPusleatEnablePin

https://exploreembedded.com/wiki/PIC_C_Library#UART

14/31

22/09/2016

en=0;

delay_us(10);

databus=((dat<<4)&0xf0);
rs=1;

rw=0;

en=1;

delay_us(10);
en=0;

delay_ms(1);

PICCLibraryTutorials

//waitforsometime.
//SendtheLowerNibbleoftheDatatoLCD
//SelecttheDataRegisterbypullingRSHIGH
//SelecttheWriteOperationbypullingRWLOW
//SendaHightoLowPusleatEnablePin

Keypad
PIC4x4KeypadLibrary

Filename:keypad.c
Controller:Pica6f877A
Oscillator:20MHz
Author:XploreLabz
website:www.xplorelabz.com
Note:
Rowsareconnectedtolower4bitsofPORTC.
Colsareconnectedtohigher4bitsofPORTC.

#include<htc.h>
#include"keypad.h"
#include"delay.h"

#defineRowColDirectionTRISC//DataDirectionConfigurationforkeypad

#defineROWPORTC//LowerfourbitsofP1areusedasROWs
#defineCOLPORTC//HigherfourbitsofP1areusedasCOLs

KEYPAD_Init()
Description:Thisfunctiontherowsandcolumsforkeypadscan
ROWlinesareconfiguredasOutput.
https://exploreembedded.com/wiki/PIC_C_Library#UART

15/31

22/09/2016

PICCLibraryTutorials

ColumnLinesareconfiguredasInput.
I/PArguments:none
Returnvalue:none

voidKEYPAD_Init()
{
RowColDirection=0x0f;//ConfigureRowlinesasO/PandColumnlinesasI/P
}

KEYPAD_WaitForKeyRelease()
Description:Thisfunctionwaitstillthepreviouskeyisreleased.
AlltheROWlinesarepulledhigh.
ColumnLinesarereadtocheckthekeypress.
IfalltheKeysarereleasedthenColumnlineswillbelow(0x00).
I/PArguments:none
Returnvalue:none
voidKEYPAD_WaitForKeyRelease()
{
unsignedcharkey;
do

{
ROW=0xF0;//PulltheROWlinestohighandColumnlineslow.

key=COL&0x0f;//ReadtheColumns,tocheckthekeypress
}while(key!=0x00);//WaittilltheKeyisreleased,
//IfnoKeyispressed,Columnlineswillbelow(0x00)
}

KEYPAD_WaitForKeyPress()
Description:Thisfunctionwaitstillanewkeyispressed.
AlltheROWlinesarepulledhigh.
ColumnLinesarereadtocheckthekeypress.
IfanyKeyispressedthencorrespondingColumnLinegoeshigh.
WaitforSometimeandperformtheaboveoperationtoensuretheTrueKeyPressbeforedecodingtheKEY.
I/PArguments:none
Returnvalue:none

voidKEYPAD_WaitForKeyPress()
{
unsignedcharkey;
do
{

do
{

ROW=0xF0;
//PulltheROWlinestohighandColumnlineslow.

key=COL&0x0F;
//ReadtheColumns,tocheckthekeypress

}while(key==0x00);//WaittilltheKeyispressed,

//ifaKeyispressedthecorrespondingColumnlinegohigh

delay_ms(1);
//Waitforsometime(debounceTime);

ROW=0xF0;

//Afterdebouncetime,performtheaboveoperation

key=COL&0x0F;
//toensuretheKeypress.

https://exploreembedded.com/wiki/PIC_C_Library#UART

16/31

22/09/2016

PICCLibraryTutorials

}while(key==0x00);

KEYPAD_ScanKey()
Description:Thisfunctionscansalltherowstodecodethekeypressed.
EachtimeaROWlineispulledhightodetecttheKEY.
ColumnLinesarereadtocheckthekeypress.
IfanyKeyispressedthencorrespondingColumnLinegoeshigh.
ReturntheScanCode(CombinationofROW&COL)fordecodingthekey.
I/PArguments:none
Returnvalue:char>ScancodeoftheKeyPressed

unsignedcharKEYPAD_ScanKey()
{

unsignedcharScanKey=0x10,i,key;

for(i=0;i<0x04;i++)//ScanAllthe4Rowsforkeypress
{
ROW=ScanKey;//Select1RowatatimeforScanningtheKey
key=COL&0x0F;//ReadtheColumn,forkeypress

if(key!=0x00)//IftheKEYpressisdetectedfortheselected
break;//ROWthenstopScanning,

ScanKey=(ScanKey<<1);//RotatetheScanKeytoSCANtheremainingRows
}

key=key|ScanKey;//RetuntherowandCOLstatustodecodethekey
return(key);
}

KEYPAD_GetKey()
Description:ThisfunctionwaitstillakeyispressedandretunsitsASCIIValue
Waittillthepreviouskeyisreleased..
Waitforthenewkeypress.
Scanalltherowsoneatatimeforthepressedkey.
DecodethekeypresseddependingonROWCOLcombinationandretunsitsASCIIvalue.
I/PArguments:none
Returnvalue:char>ASCIIvalueoftheKeyPressed

unsignedcharKEYPAD_GetKey()
{

unsignedcharkey;

KEYPAD_WaitForKeyRelease();//Waitforthepreviouskeyrelease
delay_ms(1);

KEYPAD_WaitForKeyPress();//Waitforthenewkeypress
key=KEYPAD_ScanKey();//Scanforthekeypressed.

switch(key)//Decodethekey
https://exploreembedded.com/wiki/PIC_C_Library#UART

17/31

22/09/2016

PICCLibraryTutorials

{
case0x11:key='7';break;
case0x12:key='8';break;
case0x14:key='9';break;
case0x18:key='%';break;

case0x21:key='4';break;

case0x22:key='5';break;

case0x24:key='6';break;

case0x28:key='*';break;

case0x41:key='1';break;

case0x42:key='2';break;

case0x44:key='3';break;

case0x48:key='';break;

case0x81:key='N';break;

case0x82:key='0';break;

case0x84:key='=';break;

case0x88:key='+';break;
default:key='z';
}
return(key);//Returnthekey
}

UART
PICUARTlibraryforSerialCommunicationfor9600baudrateat20MHz

Filename:uart.c
Controller:Pic16F877A
Oscillator:20MHz
Author:XploreLabz
website:www.xplorelabz.com
#include<htc.h>

UART_Init()
Description:ThisfunctionisusedtoinitializetheUARTat9600baudratebybelowconfiguration.
TXSTAisconfiguredforAsynchronousmode,8bitdata&transmitterenabled.
RCSTAisconfiguredforcontinousreceiveenable.
SPBRGisconfigured9600Baudrateat20MHz.
I/PArguments:none
Returnvalue:none

voidUART_Init()
{
TRISC=0x80;//ConfigureRxpinasinputandTxasoutput

TXSTA=0x20;//Asynchronousmode,8bitdata&enabletransmitter

RCSTA=0x90;//8bitcontinousreceiveenable

SPBRG=31;//9600Baudrateat20MHz
}

UART_RxChar()
Description:ThisfunctionisusedtoreceiveacharfromUARTmodule.
Itwaitstillacharisreceivedie.tillRCIFisset,
RCIFwillbesetonceaCHARisreceived.
FinallyitclearstheRCIFfornextcycleandreturnsthereceivedchar.
I/PArguments:none
Returnvalue:char
https://exploreembedded.com/wiki/PIC_C_Library#UART

18/31

22/09/2016

PICCLibraryTutorials

charUART_RxChar()
{
while(RCIF==0);//Waittillthedataisreceived
RCIF=0;//Clearreceiverflag
return(RCREG);//Returnthereceiveddatatocallingfunction
}

UART_TxChar()
Description:ThisfunctionisusedtotransmitacharthroughUARTmodule.
Itwaitstillpreviouscharistransmittedie.tillTXIFisset.
TXIFwillbesetonceaCHARistransmitted.
ItclearstheTXIFfornextoperation.
FinallytheChartobetransmittedisloadedintoTXREG.
I/PArguments:char>datatobetransmitted.
Returnvalue:none
voidUART_TxChar(charch)
{
while(TXIF==0);//Waittillthetransmitterregisterbecomesempty

TXIF=0;//Cleartransmitterflag
TXREG=ch;//loadthechrthetobetransmittedintotransmitreg
}

UART_TxString()
Description:ThisfunctionisusedtotransmittheASCIIstringthroughUART.
Thestring_ptrpointstothefirstcharofthestring.
Anditisincrementedeachtimetotraversetilltheend(NULLCHAR).
EachtimeacharissenttoUART_TxChar()funtotransmititthroughUART
I/PArguments:String(Addressofthestring)tobetransmitted.
Returnvalue:none

voidUART_TxString(char*string_ptr)
{
while(*string_ptr)
UART_TxChar(*string_ptr++);
}

UART_RxString()
Description:
ThisfunctionisusedtoreceiveaASCIIstringthroughUARTtillthecarriage_return/New_line.
Thestring_ptrpointstothebeginingofthestringandeachtimeUART_RxChar()functioniscalledtoreceiveacharandcopyit
intothebuffer(STRING)andincrmentstring_ptr.
Oncethecarriage_return/New_lineisencounteredtheloopisbreakedandtheStringisNULLterminated.
I/PArguments:*string_ptr(Addressofthestringwherethereceiveddataneedstobestored)
Returnvalue:none
NOTE:
ThereceivedcharisECHOEDback,ifnotrequiredthencommentUART_TxChar(ch)inthecode.
BackSlashisnottakencare.
https://exploreembedded.com/wiki/PIC_C_Library#UART

19/31

22/09/2016

PICCLibraryTutorials

voidUART_RxString(char*string_ptr)
{
charch;
while(1)
{
ch=UART_RxChar();//Receiveachar
UART_TxChar(ch);//Echobackthereceivedchar

if((ch=='\r')||(ch=='\n'))//readtillenterkeyispressed
{

//onceenterkeyispressed
*string_ptr=0;//nullterminatethestring
break;

//andbreaktheloop
}
*string_ptr=ch;//copythecharintostring.
string_ptr++;

//andincrementthepointer
}
}

UART_TxNumber()
I/PArguments:unsignedint.
Returnvalue:none
Description:Thisfunctionisusedtotransmita5digitinteger(065535).
ex:
1.ifthenumberis12345then12345istransmitted.
2.ifthenumberis123then00123istransmitted.

voidUART_TxNumber(unsignedintnum)
{

UART_TxChar((num/10000)+0x30);

num=num%10000;

UART_TxChar((num/1000)+0x30);

num=num%1000;

UART_TxChar((num/100)+0x30);

num=num%100;

UART_TxChar((num/10)+0x30);

UART_TxChar((num%10)+0x30);
}

I2C
https://exploreembedded.com/wiki/PIC_C_Library#UART

20/31

22/09/2016

PICCLibraryTutorials

PICI2Clibrary

Filename:I2C.c
Controller:Pic16f877A(PICfamily)
Oscillator:11.0592MHz
Author:XploreLabz
website:www.xplorelabz.com
Note:
TheSDAandSCLlinesareconnectedtoPORTC.4andPORTC.3
ThecodecanbemodifiedtoconnecttheSDAandSCLtoanyofthePORTsbychangingthe#define

#include<reg51.h>
#include"delay.h"
#include"i2c.h"

sbitSCL=RC3;//SCLConnectedtoPORTC.3
sbitSDA=RC4;//SDAConnectedtoPORTC.4

I2C_Clock()
Description:ThisfunctionisusedtogenerateaclockpulseonSCLline.
I/PArguments:none
Returnvalue:none

voidI2C_Clock(void)
{
delay_us(1);
SCL=1;//WaitforSometimeandPulltheSCLlineHigh

delay_us(1);//WaitforSometime
SCL=0;//PullbacktheSCLlinelowtoGenerateaclockpulse
}

I2C_Start()
I/PArguments:none
Returnvalue:none
Description:ThisfunctionisusedtogenerateI2CStartCondition.
StartCondition:SDAgoeslowwhenSCLisHigh.

voidI2C_Start()
{
SCL=0;//PullSCLlow

SDA=1;//PullSDAHigh
delay_us(1);
https://exploreembedded.com/wiki/PIC_C_Library#UART

21/31

22/09/2016

PICCLibraryTutorials

SCL=1;//PullSCLhigh
delay_us(1);

SDA=0;//NowPullSDALOW,togeneratetheStartCondition
delay_us(1);

SCL=0;//FinallyCleartheSCLtocompletethecycle
}

I2C_Stop()
I/PArguments:none
Returnvalue:none
Description:ThisfunctionisusedtogenerateI2CStopCondition.
StopCondition:SDAgoesHighwhenSCLisHigh.

voidI2C_Stop(void)
{
SCL=0;//PullSCLlow
delay_us(1);

SDA=0;//PullSDAlow
delay_us(1);

SCL=1;//PullSCLHigh
delay_us(1);

SDA=1;//NowPullSDAHigh,togeneratetheStopCondition
}

I2C_Write()
I/PArguments:unsignedchar>8bitdatatobesent.
Returnvalue:none
Description:ThisfunctionisusedtosendabyteonSDAlineusingI2Cprotocol
8bitdataissentbitbybitoneachclockcycle.
MSB(bit)issentfirstandLSB(bit)issentatlast.
DataissentwhenSCLislow.

voidI2C_Write(unsignedchardat)
{
unsignedchari;

for(i=0;i<8;i++)//loop8timestosend1byteofdata
{
SDA=dat&0x80;//SendBitbyBitonSDAline
I2C_Clock();//GenerateClockatSCL
dat=dat<<1;
}
SDA=1;//SetSDAatlast
}
https://exploreembedded.com/wiki/PIC_C_Library#UART

22/31

22/09/2016

PICCLibraryTutorials

I2C_Read()
I/PArguments:none
Returnvalue:Unsignedchar(receivedbyte)
Description:ThisfunisusedtoreceiveabyteonSDAlineusingI2Cprotocol.
8bitdataisreceivedbitbybiteachclockandfinallypackedintoByte.
MSB(bit)isreceivedfirstandLSB(bit)isreceivedatlast.

unsignedcharI2C_Read(void)
{
unsignedchari,dat=0x00;

SDA=1;//MakeSDAasI/P
for(i=0;i<8;i++)//loop8timestoread1byteofdata
{
delay_us(1);
SCL=1;//PullSCLHigh
delay_us(1);

dat=dat<<1;//datisShiftedeachtimeand
dat=dat|SDA;//ORedwiththereceivedbittopackintobyte

SCL=0;//ClearSCLtocompletetheClock
}
returndat;//FinallyreturnthereceivedByte*
}

I2C_Ack()
Description:ThisfunctionisusedtogenerateathePositiveACKpulseonSDAafterreceivingabyte.
I/PArguments:none.
Returnvalue:none

voidI2C_Ack()
{
SDA=0;//PullSDAlowtoindicatePositiveACK
I2C_Clock();//GeneratetheClock
SDA=1;//PullSDAbacktoHigh(IDLEstate)
}

I2C_NoAck()
Description:ThisfunctionisusedtogenerateatheNegative/NOACKpulseonSDAafterreceivingallbytes.
I/PArguments:none
Returnvalue:none

voidI2C_NoAck()
{
SDA=1;//PullSDAhightoindicateNegative/NOACK
I2C_Clock();//GeneratetheClock
SCL=1;//SetSCL*/
}
https://exploreembedded.com/wiki/PIC_C_Library#UART

23/31

22/09/2016

PICCLibraryTutorials

Ds1307_RTC
PICDS1307library

Filename:DS1307.c
Controller:Pic16f877A(PICfamily)
Oscillator:11.0592MHz
Author:XploreLabz
website:www.xplorelabz.com

#include"ds1307.h"
#include"i2c.h"
#include"delay.h"

Belowvaluesarefixedandshouldnotbechanged.
ReferDs1307DataSheetformoreinfo.
#defineDS1307_ID0xD0//DS1307ID

#defineSEC_ADDRESS0x00//AddresstoaccessDs1307SECregister
#defineDATE_ADDRESS0x04//AddresstoaccessDs1307DATEregister
#defineCONTROL0x07//AddresstoaccessDs1307CONTROLregister

DS1307_Init()
Description:ThisfunctionisusedtoinitializetheDs1307RTC.
Ds1307icisenabledbysendingtheDS1307idontheI2Cbus.
AfterselectingDS1307,write0x00intoControlregisterofDs1307
I/PArguments:none
Returnvalue:none

voidDS1307_Init()
{
I2C_Start();//StartI2Ccommunication

DS1307_Write(DS1307_ID);//ConnecttoDS1307bysendingitsIDonI2cBus
DS1307_Write(CONTROL);//SelecttheDs1307ControlRegistertoconfigureDs1307

DS1307_Write(0x00);//Write0x00toControlregistertodisableSQWOut

I2C_Stop();//StopI2CcommunicationafterinitilizingDS1307

DS1307_Write()
Description:ThisfunctionisusedtowriteabyteofdataintoDs1307RTC.
ThisfunctioncallsI2C_writefunctiontoperformthesame.
I/PArguments:char>DatatobewrittenintoDS1307.
Returnvalue:none
https://exploreembedded.com/wiki/PIC_C_Library#UART

24/31

22/09/2016

PICCLibraryTutorials

voidDS1307_Write(unsignedchardat)
{
I2C_Write(dat);//ConnecttoDS1307bysendingitsIDonI2cBus
I2C_Clock();
}

DS1307_Read()
Description:ThisfunctionisusedtoreadabyteofdatafromDs1307RTC.
ThisfunctioncallsI2C_Readfunctiontoperformthesame.
I/PArguments:char>DatatobewrittenintoDS1307.
Returnvalue:none

unsignedcharDS1307_Read()
{
unsignedchardat;
dat=I2C_Read();//ConnecttoDS1307bysendingitsIDonI2cBus
return(dat);
}

DS1307_SetTime()
Description:ThisfunctionisusedtosetTime(hh,mm,ss)intotheDs1307RTC.
Ds1307icisenabledbysendingtheDS1307idontheI2Cbus.
AfterselectingDS1307,selecttheRAMaddress0x00topointtosec
InitilzeSec,MIN,Houroneaftertheother.
StoptheI2ccommunication.
I/PArguments:char,char,char>hh,mm,sstoinitilizethetimeintoDS1307.
Returnvalue:none

voidDS1307_SetTime(unsignedcharhh,unsignedcharmm,unsignedcharss)
{
I2C_Start();//StartI2Ccommunication

DS1307_Write(DS1307_ID);//connecttoDS1307bysendingitsIDonI2cBus
DS1307_Write(SEC_ADDRESS);//SelecttheSECRAMaddress

DS1307_Write(ss);//WriteseconRAMaddress00H
DS1307_Write(mm);//WriteminonRAMaddress01H
DS1307_Write(hh);//WritehouronRAMaddress02H

I2C_Stop();//StopI2CcommunicationafterSettingtheTime
}

DS1307_SetDate()
Description:ThisfunctionisusedtosetDate(dd,mm,yy)intotheDs1307RTC.
Ds1307icisenabledbysendingtheDS1307idontheI2Cbus.
AfterselectingDS1307,selecttheRAMaddress0x04topointtoday
InitilzeDay,MonthandYearoneaftertheother.
StoptheI2ccommunication.
I/PArguments:char,char,char>day,month,yeartoinitilizetheDateintoDS1307.
https://exploreembedded.com/wiki/PIC_C_Library#UART

25/31

22/09/2016

PICCLibraryTutorials

Returnvalue:none

voidDS1307_SetDate(unsignedchardd,unsignedcharmm,unsignedcharyy)
{
I2C_Start();//StartI2Ccommunication

DS1307_Write(DS1307_ID);//connecttoDS1307bysendingitsIDonI2cBus
DS1307_Write(DATE_ADDRESS);//RequestDAYRAMaddressat04H

DS1307_Write(dd);//WritedateonRAMaddress04H
DS1307_Write(mm);//WritemonthonRAMaddress05H
DS1307_Write(yy);//WriteyearonRAMaddress06h

I2C_Stop();//StopI2CcommunicationafterSettingtheDate
}

DS1307_GetTime()
Description:ThisfunctionisusedtogettheTime(hh,mm,ss)fromDs1307RTC.
Ds1307icisenabledbysendingtheDS1307idontheI2Cbus.
AfterselectingDS1307,selecttheRAMaddress0x00topointtosec
GetSec,MIN,Houroneaftertheother.
StoptheI2ccommunication.
I/PArguments:char*,char*,char*>pointerstogetthehh,mm,ss.
Returnvalue:none

voidDS1307_GetTime(unsignedchar*h_ptr,unsignedchar*m_ptr,unsignedchar*s_ptr)
{
I2C_Start();//StartI2Ccommunication

DS1307_Write(DS1307_ID);//connecttoDS1307bysendingitsIDonI2cBus
DS1307_Write(SEC_ADDRESS);//RequestSecRAMaddressat00H

I2C_Stop();//StopI2CcommunicationafterselectingSecRegister

I2C_Start();//StartI2Ccommunication
DS1307_Write(0xD1);//connecttoDS1307(underReadmode)
//bysendingitsIDonI2cBus

*s_ptr=DS1307_Read();I2C_Ack();//readsecondandreturnPositiveACK
*m_ptr=DS1307_Read();I2C_Ack();//readminuteandreturnPositiveACK
*h_ptr=DS1307_Read();I2C_NoAck();//readhourandreturnNegative/NoACK

I2C_Stop();//StopI2CcommunicationafterreadingtheTime
}

DS1307_GetDate()
Description:ThisfunctionisusedtogettheDate(y,m,d)fromDs1307RTC.
Ds1307icisenabledbysendingtheDS1307idontheI2Cbus.
AfterselectingDS1307,selecttheRAMaddress0x00topointtoDAY
GetDay,Month,Yearoneaftertheother.
StoptheI2ccommunication.
I/PArguments:char*,char*,char*>pointerstogetthey,m,d.
Returnvalue:none
https://exploreembedded.com/wiki/PIC_C_Library#UART

26/31

22/09/2016

PICCLibraryTutorials

voidDS1307_GetDate(unsignedchar*d_ptr,unsignedchar*m_ptr,unsignedchar*y_ptr)
{
I2C_Start();//StartI2Ccommunication

DS1307_Write(DS1307_ID);//connecttoDS1307bysendingitsIDonI2cBus
DS1307_Write(DATE_ADDRESS);//RequestDAYRAMaddressat04H

I2C_Stop();//StopI2CcommunicationafterselectingDAYRegister

I2C_Start();//StartI2Ccommunication
DS1307_Write(0xD1);//connecttoDS1307(underReadmode)
//bysendingitsIDonI2cBus

*d_ptr=DS1307_Read();I2C_Ack();//readDayandreturnPositiveACK
*m_ptr=DS1307_Read();I2C_Ack();//readMonthandreturnPositiveACK
*y_ptr=DS1307_Read();I2C_NoAck();//readYearandreturnNegative/NoACK

I2C_Stop();//StopI2CcommunicationafterreadingtheTime
}

EEPROM
Pic16f877AEEPROMlibrary

Filename:eeprom.c
Controller:Pic16f877A
Oscillator:20MHz
Author:XploreLabz
website:www.xplorelabz.com

#include<htc.h>
#include"delay.h"

EEPROM_WriteByte()
Description:ThisfunctionisusedtowritethedataatspecifiedEEPROM_address..
I/PArguments:char,char>eeprom_addressatwhicheeprom_dataistobewritten.
Returnvalue:none

voidEEPROM_WriteByte(unsignedchareeprom_Address,unsignedchareeprom_Data)
{
while(RD||WR);//checktheWR&RDbittoseeifaRD/WRisinprogress
EEADR=eeprom_Address;//WritetheaddresstoEEADR.
//Makesurethattheaddressisnotlargerthanthememorysize
EEDATA=eeprom_Data;//loadthe8bitdatavaluetobewrittenintheEEDATAregister.
WREN=1;//SettheWRENbittoenableeepromoperation.
EECON2=0x55;//Executethespecialinstructionsequence
EECON2=0xaa;//Referthedatasheetformoreinfo
WR=1;//SettheWRbittotriggertheeepromwriteoperation.
delay_us(10);
WREN=0;//Disableeepromoperation.
}
https://exploreembedded.com/wiki/PIC_C_Library#UART

27/31

22/09/2016

PICCLibraryTutorials

EEPROM_ReadByte()
Description:ThisfunctionisusedtoreadthedatafromspecifiedEEPROM_address.
I/PArguments:char>eeprom_addressfromwhereeeprom_dataistoberead.
Returnvalue:char>datareadfromEeprom.

unsignedcharEEPROM_ReadByte(unsignedchareeprom_Address)
{
while(RD||WR);//checktheWR&RDbittoseeifaRD/WRisinprogress
EEADR=eeprom_Address;//WritetheaddresstoEEADR.
//Makesurethattheaddressisnotlargerthanthememorysize
RD=1;//SettheWRbittotriggertheeepromreadoperation.
delay_us(50);
return(EEDATA);//Returnthedatareadformeeprom.
}

EEPROM_WriteNBytes()
Description:ThisfunctionisusedtowriteNbytesofdataatspecifiedEEPROM_address.
EEPROM_WriteByte()functioniscalledtowriteabyteatatime.
Source(RAM)anddestination(EEPROM)addressareincrementedaftereachwrite
NoOfBytesisDecementedeachtimeabyteiswritten.
AboveOperationiscarriedouttillallthebytesarewritten(NoOfBytes!=0).
I/PArguments:
1.char,>eeprom_addressfromwheretheNbytesaretobewritten.
2.char*>PointertotheNbytesofdatatobewritten.
3.char>Numberofbytestobewritten.
Returnvalue:none

voidEEPROM_WriteNBytes(unsignedcharEepromAddr,unsignedchar*RamAddr,charNoOfBytes)
{
while(NoOfBytes!=0)
{

EEPROM_WriteByte(EepromAddr,*RamAddr);//WriteabytefromRAMtoEEPROM

EepromAddr++;

//IncerementtheEepromAddress

RamAddr++;

//IncrementtheRAMAddress

NoOfBytes;

//DecrementNoOfBytesafterwritingeachByte

}
}

EEPROM_ReadNBytes()
Description:ThisfunctionisusedtoReadNbytesofdatafromspecifiedEEPROM_address.
EEPROM_ReadByte()funciscalledtoreadabyteatatime.
Source(RAM)anddestination(EEPROM)addressareincrementedeachtime.
NoOfBytesisDecementedafterabyteisread.
AboveOperationiscarriedouttillallthebytesareread(NoOfBytes!=0).
I/PArguments:
1.char,>eeprom_addressfromwheretheNbytesistoberead.
2.char*>PointerintowhichtheNbytesofdataistoberead.
https://exploreembedded.com/wiki/PIC_C_Library#UART

28/31

22/09/2016

PICCLibraryTutorials

3.char>NumberofbytestobeRead
Returnvalue:none

voidEEPROM_ReadNBytes(unsignedcharEepromAddr,unsignedchar*RamAddr,charNoOfBytes)
{
while(NoOfBytes!=0)

*RamAddr=EEPROM_ReadByte(EepromAddr);//ReadabytefromEEPROMtoRAM

EepromAddr++;

//IncerementtheEepromAddress

RamAddr++;

//IncrementtheRAMAddress

NoOfBytes;

//DecrementNoOfBytesafterReadingeachByte

}
}

EEPROM_WriteString()
Description:ThisfunctionisusedtoWriteaStringatspecifiedEEPROM_address.
EEPROM_WriteByte()functioniscalledtowriteabyteatatime.
Source(RAM)anddestination(EEPOM)addressareincrementedeachtime.
AboveOperationiscarriedouttillNullcharisidentified.
I/PArguments:
1.char,>eeprom_addresswheretheStringistobewritten.
2.char*>PointertoStringwhichhastobewritten.
Returnvalue:none
NOTE:
Nullcharisalsowrittenintotheeeprom.
voidEEPROM_WriteString(unsignedchareeprom_address,unsignedchar*source_address)
{
do

EEPROM_WriteByte(eeprom_address,*source_address);//WriteabytefromRAMtoEEPROM

source_address++;

//IncerementtheRAMAddress

eeprom_address++;

//IncrementtheEepromAddress

}while(*(source_address1)!=0);
}

EEPROM_ReadString()
Description:ThisfunctionisusedtoReadaStringfromspecifiedEEPROM_address.
EEPROM_ReadByte()functioniscalledtoreadabyteatatime.
Source(EEPROM)anddestination(RAM)addressareincrementedeachtime.
AboveOperationiscarriedouttillNullcharisidentified.
I/PArguments:
1.char,>eeprom_addressfromwheretheStringistoberead.
2.char*>PointerintowhichtheStringistoberead.
Returnvalue:none

https://exploreembedded.com/wiki/PIC_C_Library#UART

29/31

22/09/2016

PICCLibraryTutorials

voidEEPROM_ReadString(unsignedchareeprom_address,unsignedchar*destination_address)
{
chareeprom_data;

do

eeprom_data=EEPROM_ReadByte(eeprom_address);//ReadabytefromEEPROMtoRAM

*destination_address=eeprom_data;//CopythedataintoStringBuffer

destination_address++;

//IncerementtheRAMAddress

eeprom_address++;

//IncrementtheEepromAddress

}while(eeprom_data!=0);
}

EEPROM_Erase()
Description:ThisfunctionisusedtoerasetheentireEeprommemory.
Eepromisfilledwith0xFFtoaccomplishtheEepromErase.
EEPROM_WriteByte()functioniscalledtowriteabyteatatime.
Wholememory(0255)istraversedandfilledwith0xFF
I/PArguments:none
Returnvalue:none

voidEEPROM_Erase()
{

unsignedchareeprom_address;

for(eeprom_address=0;eeprom_address<255;eeprom_address++)

EEPROM_WriteByte(eeprom_address,0xff);//WriteEachmemorylocationwithOxFF

}
}

PICLibraryUsageGuide
PICLibraryUsageGuide
Retrievedfrom"http://exploreembedded.com/wiki/index.php?title=PIC_C_Library&oldid=1362"
Category:
CodeLibraries
WearecurrentlycrowdfundingourlatestARMCortexM3board,getanearlybirdversionat$15(INR1000)whichincludesfreeshipping
SupportExploreM3
Contact
FAQ
Terms
Warranty
Shipping
About
Whybuyfromus?
SubscribetohearaboutourlatestExplorations!
name@example.com

SUBSCRIBE

https://exploreembedded.com/wiki/PIC_C_Library#UART

30/31

22/09/2016

PICCLibraryTutorials

Contact
About
Warranty
Terms&Conditions

https://exploreembedded.com/wiki/PIC_C_Library#UART

31/31

You might also like