0% found this document useful (0 votes)
8 views

MikroC Library

Uploaded by

learnwithimed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

MikroC Library

Uploaded by

learnwithimed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 465

MikroC Library

Built-in Routines

Hardware Libraries
 ADC Library
 CAN Library
 CANSPI Library
 Compact Flash Library
 EEPROM Library
 Epson S1D13700 Graphic Lcd Library
 Ethernet PIC18FxxJ60 Library
 Flash Memory Library
 Graphic Lcd Library
 I²C Library
 Keypad Library
 Lcd Library
 Manchester Code Library
 Memory Manager Library
 Multi Media Card Library
 OneWire Library
 Peripheral Pin Select Library
 Port Expander Library
 PS/2 Library
 PWM Library
 RS-485 Library
 Software I²C Library
 Software SPI Library
 Software UART Library
 Sound Library
 SPI Library
 SPI Remappable Library
 SPI Ethernet Library
 SPI Ethernet ENC24J600 Library
 SPI Graphic Lcd Library
 SPI Lcd Library
 SPI Lcd8 Library
 SPI T6963C Graphic Lcd Library
 T6963C Graphic Lcd Library
 TFT Display Library
 TFT 16-bit Display Library
 Touch Panel Library
 Touch Panel TFT Display Library
 UART Library
 UART Remappable Library
 USB Library

Miscellaneous Libraries
 Button Library
 Conversions Library
 PrintOut Library

www.raguvaran.puzl.com
 Setjmp Library
 Sprint Library
 Time Library
 Trigonometry Library

Built-in Routines
The mikroC PRO for PIC compiler provides a set of useful built-in utility functions.

The Lo, Hi, Higher, Highest routines are implemented as macros. If you want to use these functions you
must include built_in.h header file (located in the include folder of the compiler) into your project.
The Delay_us and Delay_ms routines are implemented as “inline”; i.e. code is generated in the place of a
call, so the call doesn’t count against the nested call limit.
The Vdelay_ms, Vdelay_advanced_ms, Delay_Cyc, Get_Fosc_kHz and Get_Fosc_Per_Cyc are actual C routines.
Their sources can be found in Delays.c file located in the uses folder of the compiler.
 Lo
 Hi
 Higher
 Highest
 LoWord
 HiWord
 Delay_us
 Delay_ms
 Vdelay_ms
 Vdelay_Advanced_ms
 Delay_Cyc
 Clock_kHz
 Clock_MHz
 Get_Fosc_kHz
 Swap

Lo

Prototype #define Lo(param) ((char *)&param)[0]

Returns Lowest 8 bits (byte) of param, bits 7..0.

Description Function returns the lowest byte of param. Function does not interpret bit patterns
of param – it merely returns 8 bits as found in register.
This is an “inline” routine; code is generated in the place of the call, so the call doesn’t
count against the nested call limit.

Requires None.

Example d = 0x12345678;
tmp = Lo(d); // Equals 0x78

Lo(d) = 0xAA; // d equals 0x123456AA

www.raguvaran.puzl.com
Hi

Prototype #define Hi(param) ((char *)&param)[1]

Returns Returns next to the lowest byte of param, bits 8..15.

Description Function returns next to the lowest byte of param. Function does not interpret bit
patterns of param – it merely returns 8 bits as found in register.
This is an “inline” routine; code is generated in the place of the call, so the call doesn’t
count against the nested call limit.

Requires None.

Example d = 0x12345678;
tmp = Hi(d); // Equals 0x56

Hi(d) = 0xAA; // d equals 0x1234AA78

Higher

Prototype #define Higher(param) ((char *)&param)[2]

Returns Returns next to the highest byte of param, bits 16..23.

Description Function returns next to the highest byte of param. Function does not interpret bit
patterns of param – it merely returns 8 bits as found in register.
This is an “inline” routine; code is generated in the place of the call, so the call doesn’t
count against the nested call limit.

Requires None.

Example d = 0x12345678;
tmp = Higher(d); // Equals 0x34

Higher(d) = 0xAA; // d equals 0x12AA5678

Highest

Prototype #define Highest(param) ((char *)&param)[3]

www.raguvaran.puzl.com
Returns Returns the highest byte of param, bits 24..31.

Description Function returns the highest byte of param. Function does not interpret bit patterns
of param – it merely returns 8 bits as found in register.
This is an “inline” routine; code is generated in the place of the call, so the call doesn’t
count against the nested call limit.

Requires None.

Example d = 0x12345678;
tmp = Highest(d); // Equals 0x12

Highest(d) = 0xAA; // d equals 0xAA345678

LoWord

Prototype unsigned int LoWord(unsigned long number);

Description The function returns low word of number. The function does not interpret bit patterns
of number – it merely returns 16 bits as found in register.
This is an “inline” routine; code is generated in the place of the call, so the call doesn’t
count against the nested call limit.

Parameters  number: input number

Returns Low word of number, bits 15..0.

Requires Nothing.

Example d = 0x12345678;
tmp = LoWord(d); // Equals 0x5678

LoWord(d) = 0xAAAA; // d equals 0x1234AAAA

Notes None.

HiWord

Prototype unsigned int HiWord(unsigned long number);

Description The function returns high word of number. The function does not interpret bit patterns
of number – it merely returns 16 bits as found in register.
This is an “inline” routine; code is generated in the place of the call, so the call doesn’t
count against the nested call limit.

Parameters  number: input number

www.raguvaran.puzl.com
Returns High word of number, bits 31..16.

Requires Nothing.

Example d = 0x12345678;
tmp = HiWord(d); // Equals 0x1234

HiWord(d) = 0xAAAA; // d equals 0xAAAA5678

Notes None.

Delay_us

Prototype void Delay_us(const unsigned long time_in_us);

Returns Nothing.

Description Creates a software delay in duration of time_in_us microseconds (a constant). Range of


applicable constants depends on the oscillator frequency.
This is an “inline” routine; code is generated in the place of the call, so the call doesn’t
count against the nested call limit. This routine generates nested loops using
registersR13, R12, R11 and R10. The number of used registers varies from 0 to 4,
depending on requested time_in_us.

Requires Nothing.

Example Delay_us(1000); /* One millisecond pause */

Delay_ms

Prototype void Delay_ms(const unsigned long time_in_ms);

Returns Nothing.

Description Creates a software delay in duration of time_in_ms milliseconds (a constant). Range of


applicable constants depends on the oscillator frequency.
This is an “inline” routine; code is generated in the place of the call, so the call doesn’t
count against the nested call limit. This routine generates nested loops using
registersR13, R12, R11 and R10. The number of used registers varies from 0 to 4,
depending on requested time_in_ms.

Requires Nothing.

www.raguvaran.puzl.com
Example Delay_ms(1000); /* One second pause */

Vdelay_ms

Prototype void Vdelay_ms(unsigned time_in_ms);

Returns Nothing.

Description Creates a software delay in duration of time_in_ms milliseconds (a variable). Generated


delay is not as precise as the delay created by Delay_ms.
Note that Vdelay_ms is library function rather than a built-in routine; it is presented in
this topic for the sake of convenience.

Requires Nothing.

Example pause = 1000;


// ...
Vdelay_ms(pause); // ~ one second pause

VDelay_Advanced_ms

Prototype void VDelay_Advanced_ms(unsigned time_in_ms, unsigned Current_Fosc_kHz);

Returns Nothing.

Description Creates a software delay in duration of time_in_ms milliseconds (a variable), for a given
oscillator frequency. Generated delay is not as precise as the delay created
by Delay_ms.
Note that Vdelay_ms is library function rather than a built-in routine; it is presented in
this topic for the sake of convenience.

Requires Nothing.

Example pause = 1000;


fosc = 10000;

VDelay_Advanced_ms(pause, fosc); // Generates approximately one second pause,


for a oscillator frequency of 10 MHz

Delay_Cyc

Prototype void Delay_Cyc(char Cycles_div_by_10);

www.raguvaran.puzl.com
Returns Nothing.

Description Creates a delay based on MCU clock. Delay lasts for 10 times the input parameter in
MCU cycles.

Note that Delay_Cyc is library function rather than a built-in routine; it is presented in
this topic for the sake of convenience. There are limitations for Cycles_div_by_10
value. Value Cycles_div_by_10 must be between 3 and 255.

Requires Nothing.

Example Delay_Cyc(10); /* Hundred MCU cycles pause */

Clock_kHz

Prototype unsigned Clock_kHz(void);

Returns Device clock in kHz, rounded to the nearest integer.

Description Function returns device clock in kHz, rounded to the nearest integer.

This is an “inline” routine; code is generated in the place of the call, so the call doesn’t
count against the nested call limit.

Requires Nothing.

Example clk = Clock_kHz();

Clock_MHz

Prototype unsigned short Clock_MHz(void);

Returns Device clock in MHz, rounded to the nearest integer.

Description Function returns device clock in MHz, rounded to the nearest integer.

This is an “inline” routine; code is generated in the place of the call, so the call doesn’t
count against the nested call limit.

Requires Nothing.

Example clk = Clock_MHz();

www.raguvaran.puzl.com
Get_Fosc_kHz

Prototype unsigned long Get_Fosc_kHz(void);

Returns Device clock in kHz, rounded to the nearest integer.

Description Function returns device clock in kHz, rounded to the nearest integer.

Note that Get_Fosc_kHz is library function rather than a built-in routine; it is presented
in this topic for the sake of convenience.

Requires Nothing.

Example clk = Get_Fosc_kHz();

Swap

Prototype char swap(char input);

Returns Swapped nibbles of the input byte.

Description Function swaps nibbles of the input parameter.


This is an “inline” routine; code is generated in the place of the call, so the call doesn’t
count against the nested call limit.

Requires Nothing.

Example char input, swapped_input;

input = 0xAF;
swapped_input = swap(input); // routine will return 0xFA i.e. swapped nibbles of
the input parameter

www.raguvaran.puzl.com
ADC Library
ADC (Analog to Digital Converter) module is available with a number of PIC MCU modules. ADC is an
electronic circuit that converts continuous signals to discrete digital numbers. ADC Library provides you
a comfortable work with the module.

Library Routines
 ADC_Init
 ADC_Get_Sample
 ADC_Read

ADC_Init

Prototype void ADC_Init();

Returns Nothing.

Description This routine initializes PIC’s internal ADC module to work with RC clock. Clock
determines the time period necessary for performing AD conversion (min 12TAD).

Requires  MCU with built-in ADC module.

Example ADC_Init(); // Initialize ADC module with default settings

ADC_Get_Sample

Prototype unsigned ADC_Get_Sample(unsigned short channel);

Returns 10 or 12-bit unsigned value read from the specified channel (MCU dependent).

Description The function aquires analog value from the specified channel.

Parameter channel represents the channel from which the analog value is to be
acquired. Refer to the appropriate datasheet for channel-to-pin mapping.

Note : This function doesn't work with the external voltage reference source,
only with the internal voltage reference.

Parameters  channel represents the channel from which the analog value is to be
acquired.

Requires  The MCU with built-in ADC module.


 Prior to using this routine, ADC module needs to be initialized.
See ADC_Init.
 Before using the function, be sure to configure the appropriate TRISx bits
to designate pins as inputs.

www.raguvaran.puzl.com
Example unsigned adc_value;
...
adc_value = ADC_Get_Sample(2); // read analog value from ADC module channel 2

ADC_Read

Prototype unsigned ADC_Read(unsigned short channel);

Returns 10 or 12-bit unsigned value read from the specified channel (MCU dependent).

Description Initializes PIC’s internal ADC module to work with RC clock. Clock determines the time
period necessary for performing AD conversion (min 12TAD).

Parameter channel represents the channel from which the analog value is to be
acquired. Refer to the appropriate datasheet for channel-to-pin mapping.

Note : This function doesn't work with the external voltage reference source,
only with the internal voltage reference.

Requires Nothing.

Example unsigned tmp;


...
tmp = ADC_Read(2); // Read analog value from channel 2

Library Example
This example code reads analog value from channel 2 and displays it on PORTB and PORTC.

Copy Code To Clipboard

unsigned int temp_res;

void main() {
ANSEL = 0x04; // Configure AN2 pin as analog
ANSELH = 0; // Configure other AN pins as digital I/O
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;

TRISA = 0xFF; // PORTA is input


TRISC = 0; // PORTC is output
TRISB = 0; // PORTB is output

do {
temp_res = ADC_Read(2); // Get 10-bit results of AD conversion
PORTB = temp_res; // Send lower 8 bits to PORTB
PORTC = temp_res >> 8; // Send 2 most significant bits to RC1, RC0
} while(1);
}

www.raguvaran.puzl.com
HW Connection

ADC HW connection

CAN Library
The mikroC PRO for PIC provides a library (driver) for working with the CAN module.
The CAN is a very robust protocol that has error detection and signalization, self–checking and fault
confinement. Faulty CAN data and remote frames are re-transmitted automatically, similar to the
Ethernet.

Data transfer rates depend on distance. For example, 1 Mbit/s can be achieved at network lengths below
40m while 250 Kbit/s can be achieved at network lengths below 250m. The greater distance the lower
maximum bitrate that can be achieved. The lowest bitrate defined by the standard is 200Kbit/s. Cables
used are shielded twisted pairs.

CAN supports two message formats:


 Standard format, with 11 identifier bits and
 Extended format, with 29 identifier bits

Important :

 Consult the CAN standard about CAN bus termination resistance.


 CAN routines are currently supported for P18XXX8, P18F4480, P18F4580, P18F2580 and
P18F2480 PIC MCUs.

Library Routines
 CANSetOperationMode
 CANGetOperationMode
 CANInitialize
 CANSetBaudRate
 CANSetMask
 CANSetFilter
 CANRead

www.raguvaran.puzl.com
 CANWrite

CANSetOperationMode

Prototype void CANSetOperationMode(unsigned short mode, unsigned short wait_flag);

Returns Nothing.

Description Sets CAN to requested mode, i.e. copies mode to CANSTAT. Parameter mode needs to be
one of CAN_OP_MODE constants (see CAN constants).
Parameter wait_flag needs to be either 0 or 0xFF:
 If set to 0xFF, this is a blocking call – the function won’t “return” until the
requested mode is set.
 If 0, this is a non-blocking call. It does not verify if CAN module is
switched to requested mode or not. Caller must use CANGetOperationMode to
verify correct operation mode before performing mode specific operation.

Requires CAN routines are currently supported for P18XXX8, P18F4480, P18F4580, P18F2580
and P18F2480 PIC MCUs. Microcontroller must be connected to CAN transceiver
(MCP2551 or similar) which is connected to CAN bus.

Example CANSetOperationMode(_CAN_MODE_CONFIG, 0xFF);

CANGetOperationMode

Prototype unsigned short CANGetOperationMode();

Returns Current opmode.

Description Function returns current operational mode of CAN module.

Requires CAN routines are currently supported for P18XXX8, P18F4480, P18F4580, P18F2580
and P18F2480 PIC MCUs. Microcontroller must be connected to CAN transceiver
(MCP2551 or similar) which is connected to CAN bus.

Example if (CANGetOperationMode() == _CAN_MODE_NORMAL) { ... };

CANInitialize

Prototy void CANInitialize(char SJW, char BRP, char PHSEG1, char PHSEG2, char PROPSE
pe G, char CAN_CONFIG_FLAGS);

www.raguvaran.puzl.com
Returns Nothing.

Descript Initializes CAN. All pending transmissions are aborted. Sets all mask registers to 0 to allow
ion all messages. The Config mode is internaly set by this function. Upon a execution of this
function Normal mode is set.
Filter registers are set according to flag value:

if (CAN_CONFIG_FLAGS & _CAN_CONFIG_VALID_XTD_MSG != 0)


// Set all filters to XTD_MSG
else if (config & _CAN_CONFIG_VALID_STD_MSG != 0)
// Set all filters to STD_MSG
else
// Set half the filters to STD, and the rest to XTD_MSG
Parameters:

 SJW as defined in datasheet (1–4)


 BRP as defined in datasheet (1–64)
 PHSEG1 as defined in datasheet (1–8)
 PHSEG2 as defined in datasheet (1–8)
 PROPSEG as defined in datasheet (1–8)
 CAN_CONFIG_FLAGS is formed from predefined constants (see CAN constants)

Require CAN routines are currently supported for P18XXX8, P18F4480, P18F4580, P18F2580 and
s P18F2480 PIC MCUs. Microcontroller must be connected to CAN transceiver (MCP2551 or
similar) which is connected to CAN bus.

Example init = _CAN_CONFIG_SAMPLE_THRICE &


_CAN_CONFIG_PHSEG2_PRG_ON &
_CAN_CONFIG_STD_MSG &
_CAN_CONFIG_DBL_BUFFER_ON &
_CAN_CONFIG_VALID_XTD_MSG &
_CAN_CONFIG_LINE_FILTER_OFF;
...
CANInitialize(1, 1, 3, 3, 1, init); // initialize CAN

CANSetBaudRate

Prototy void CANSetBaudRate(char SJW, char BRP, char PHSEG1, char PHSEG2, char PROPS
pe EG, char CAN_CONFIG_FLAGS);

Returns Nothing.

Descript Sets CAN baud rate. Due to complexity of CAN protocol, you cannot simply force a bps
ion value. Instead, use this function when CAN is in Config mode. Refer to datasheet for
details.
Parameters:

 SJW as defined in datasheet (1–4)


 BRP as defined in datasheet (1–64)
 PHSEG1 as defined in datasheet (1–8)

www.raguvaran.puzl.com
 PHSEG2 as defined in datasheet (1–8)
 PROPSEG as defined in datasheet (1–8)
 CAN_CONFIG_FLAGS is formed from predefined constants (see CAN constants)

Require CAN must be in Config mode; otherwise the function will be ignored.
s CAN routines are currently supported for P18XXX8, P18F4480, P18F4580, P18F2580 and
P18F2480 PIC MCUs. Microcontroller must be connected to CAN transceiver (MCP2551 or
similar) which is connected to CAN bus.

Exampl init = _CAN_CONFIG_SAMPLE_THRICE &


_CAN_CONFIG_PHSEG2_PRG_ON &
e _CAN_CONFIG_STD_MSG &
_CAN_CONFIG_DBL_BUFFER_ON &
_CAN_CONFIG_VALID_XTD_MSG &
_CAN_CONFIG_LINE_FILTER_OFF;
...
CANSetBaudRate(1, 1, 3, 3, 1, init);

CANSetMask

Prototype void CANSetMask(char CAN_MASK, long value, char CAN_CONFIG_FLAGS);

Returns Nothing.

Description Function sets mask for advanced filtering of messages. Given value is bit adjusted to
appropriate buffer mask registers.
Parameters:

 CAN_MASK is one of predefined constant values (see CAN constants)


 value is the mask register value
 CAN_CONFIG_FLAGS selects type of message to filter,
either _CAN_CONFIG_XTD_MSG or _CAN_CONFIG_STD_MSG

Requires CAN must be in Config mode; otherwise the function will be ignored.
CAN routines are currently supported for P18XXX8, P18F4480, P18F4580, P18F2580
and P18F2480 PIC MCUs. Microcontroller must be connected to CAN transceiver
(MCP2551 or similar) which is connected to CAN bus.

Example // Set all mask bits to 1, i.e. all filtered bits are relevant:
CANSetMask(_CAN_MASK_B1, -1, _CAN_CONFIG_XTD_MSG);

// Note that -1 is just a cheaper way to write 0xFFFFFFFF.


Complement will do the trick and fill it up with ones.

www.raguvaran.puzl.com
CANSetFilter

Prototype void CANSetFilter(char CAN_FILTER, long value, char CAN_CONFIG_FLAGS);

Returns Nothing.

Description Function sets message filter. Given value is bit adjusted to appropriate buffer mask
registers.
Parameters:

 CAN_FILTER is one of predefined constant values (see CAN constants)


 value is the filter register value
 CAN_CONFIG_FLAGS selects type of message to filter,
either _CAN_CONFIG_XTD_MSG or _CAN_CONFIG_STD_MSG

Requires CAN must be in Config mode; otherwise the function will be ignored.
CAN routines are currently supported for P18XXX8, P18F4480, P18F4580, P18F2580
and P18F2480 PIC MCUs. Microcontroller must be connected to CAN transceiver
(MCP2551 or similar) which is connected to CAN bus.

Example // Set id of filter B1_F1 to 3:


CANSetFilter(_CAN_FILTER_B1_F1, 3, _CAN_CONFIG_XTD_MSG);

CANRead

Prototype char CANRead(long *id, char *data, char *datalen, char *CAN_RX_MSG_FLAGS)
;

Returns Message from receive buffer or zero if no message found.

Descriptio Function reads message from receive buffer. If at least one full receive buffer is found,
n it is extracted and returned. If none found, function returns zero.

Parameters:

 id is message identifier
 data is an array of bytes up to 8 bytes in length
 datalen is data length, from 1–8.
 CAN_RX_MSG_FLAGS is value formed from constants (see CAN constants)

Requires CAN must be in mode in which receiving is possible.


CAN routines are currently supported for P18XXX8, P18F4480, P18F4580, P18F2580
and P18F2480 PIC MCUs. Microcontroller must be connected to CAN transceiver
(MCP2551 or similar) which is connected to CAN bus.

Example char rcv, rx, len, data[8];


long id;

// ...

www.raguvaran.puzl.com
rx = 0;
// ...
rcv = CANRead(id, data, len, rx);

CANWrite

Prototype unsigned
short CANWrite(long id, char *data, char datalen, char CAN_TX_MSG_FLAGS);

Returns Returns zero if message cannot be queued (buffer full).

Description If at least one empty transmit buffer is found, function sends message on queue for
transmission. If buffer is full, function returns 0.

Parameters:

 id is CAN message identifier. Only 11 or 29 bits may be used depending


on message type (standard or extended)
 data is array of bytes up to 8 bytes in length
 datalen is data length from 1–8
 CAN_TX_MSG_FLAGS is value formed from constants (see CAN constants)

Requires CAN must be in Normal mode.


CAN routines are currently supported for P18XXX8, P18F4480, P18F4580, P18F2580
and P18F2480 PIC MCUs. Microcontroller must be connected to CAN transceiver
(MCP2551 or similar) which is connected to CAN bus.

Example char tx, data;


long id;

// ...
tx = _CAN_TX_PRIORITY_0 &
_CAN_TX_XTD_FRAME;
// ...
CANWrite(id, data, 2, tx);

CAN Constants
There is a number of constants predefined in CAN library. To be able to use the library effectively, you
need to be familiar with these. You might want to check the example at the end of the chapter.

CAN_OP_MODE
CAN_OP_MODE constants define CAN operation mode. Function CANSetOperationMode expects one of these
as its argument:
const char
_CAN_MODE_BITS = 0xE0, // Use this to access opmode bits
_CAN_MODE_NORMAL = 0x00,
_CAN_MODE_SLEEP = 0x20,
_CAN_MODE_LOOP = 0x40,
_CAN_MODE_LISTEN = 0x60,
_CAN_MODE_CONFIG = 0x80;

www.raguvaran.puzl.com
CAN_CONFIG_FLAGS
CAN_CONFIG_FLAGS constants define flags related to CAN module configuration.
Functions CANInitialize and CANSetBaudRate expect one of these (or a bitwise combination) as their
argument:
const char
_CAN_CONFIG_DEFAULT = 0xFF, // 11111111

_CAN_CONFIG_PHSEG2_PRG_BIT = 0x01,
_CAN_CONFIG_PHSEG2_PRG_ON = 0xFF, // XXXXXXX1
_CAN_CONFIG_PHSEG2_PRG_OFF = 0xFE, // XXXXXXX0

_CAN_CONFIG_LINE_FILTER_BIT = 0x02,
_CAN_CONFIG_LINE_FILTER_ON = 0xFF, // XXXXXX1X
_CAN_CONFIG_LINE_FILTER_OFF = 0xFD, // XXXXXX0X

_CAN_CONFIG_SAMPLE_BIT = 0x04,
_CAN_CONFIG_SAMPLE_ONCE = 0xFF, // XXXXX1XX
_CAN_CONFIG_SAMPLE_THRICE = 0xFB, // XXXXX0XX

_CAN_CONFIG_MSG_TYPE_BIT = 0x08,
_CAN_CONFIG_STD_MSG = 0xFF, // XXXX1XXX
_CAN_CONFIG_XTD_MSG = 0xF7, // XXXX0XXX

_CAN_CONFIG_DBL_BUFFER_BIT = 0x10,
_CAN_CONFIG_DBL_BUFFER_ON = 0xFF, // XXX1XXXX
_CAN_CONFIG_DBL_BUFFER_OFF = 0xEF, // XXX0XXXX

_CAN_CONFIG_MSG_BITS = 0x60,
_CAN_CONFIG_ALL_MSG = 0xFF, // X11XXXXX
_CAN_CONFIG_VALID_XTD_MSG = 0xDF, // X10XXXXX
_CAN_CONFIG_VALID_STD_MSG = 0xBF, // X01XXXXX
_CAN_CONFIG_ALL_VALID_MSG = 0x9F; // X00XXXXX
You may use bitwise AND (&) to form config byte out of these values. For example:
Copy Code To Clipboard

init = _CAN_CONFIG_SAMPLE_THRICE &

_CAN_CONFIG_PHSEG2_PRG_ON &

_CAN_CONFIG_STD_MSG &

_CAN_CONFIG_DBL_BUFFER_ON &

_CAN_CONFIG_VALID_XTD_MSG &

_CAN_CONFIG_LINE_FILTER_OFF;

...

CANInitialize(1, 1, 3, 3, 1, init); // initialize CAN

CAN_TX_MSG_FLAGS
CAN_TX_MSG_FLAGS are flags related to transmission of a CAN message:
const char
_CAN_TX_PRIORITY_BITS = 0x03,

www.raguvaran.puzl.com
_CAN_TX_PRIORITY_0 = 0xFC, // XXXXXX00
_CAN_TX_PRIORITY_1 = 0xFD, // XXXXXX01
_CAN_TX_PRIORITY_2 = 0xFE, // XXXXXX10
_CAN_TX_PRIORITY_3 = 0xFF, // XXXXXX11

_CAN_TX_FRAME_BIT = 0x08,
_CAN_TX_STD_FRAME = 0xFF, // XXXXX1XX
_CAN_TX_XTD_FRAME = 0xF7, // XXXXX0XX

_CAN_TX_RTR_BIT = 0x40,
_CAN_TX_NO_RTR_FRAME = 0xFF, // X1XXXXXX
_CAN_TX_RTR_FRAME = 0xBF; // X0XXXXXX
You may use bitwise AND (&) to adjust the appropriate flags. For example:
Copy Code To Clipboard

// form value to be used with CANSendMessage:


send_config = _CAN_TX_PRIORITY_0 &
_CAN_TX_XTD_FRAME &
_CAN_TX_NO_RTR_FRAME;
...
CANSendMessage(id, data, 1, send_config);

CAN_RX_MSG_FLAGS
CAN_RX_MSG_FLAGS are flags related to reception of CAN message. If a particular bit is set; corresponding
meaning is TRUE or else it will be FALSE.
const char
_CAN_RX_FILTER_BITS = 0x07, // Use this to access filter bits
_CAN_RX_FILTER_1 = 0x00,
_CAN_RX_FILTER_2 = 0x01,
_CAN_RX_FILTER_3 = 0x02,
_CAN_RX_FILTER_4 = 0x03,
_CAN_RX_FILTER_5 = 0x04,
_CAN_RX_FILTER_6 = 0x05,
_CAN_RX_OVERFLOW = 0x08, // Set if Overflowed else cleared
_CAN_RX_INVALID_MSG = 0x10, // Set if invalid else cleared
_CAN_RX_XTD_FRAME = 0x20, // Set if XTD message else cleared
_CAN_RX_RTR_FRAME = 0x40, // Set if RTR message else cleared
_CAN_RX_DBL_BUFFERED = 0x80; // Set if this message was hardware double-buffered
You may use bitwise AND (&) to adjust the appropriate flags. For example:
Copy Code To Clipboard

if (MsgFlag & _CAN_RX_OVERFLOW != 0) {


...
// Receiver overflow has occurred.
// We have lost our previous message.
}

CAN_MASK
CAN_MASK constants define mask codes. Function CANSetMask expects one of these as its argument:
#const char
_CAN_MASK_B1 = 0,
_CAN_MASK_B2 = 1;

CAN_FILTER
CAN_FILTER constants define filter codes. Function CANSetFilter expects one of these as its argument:
const char
_CAN_FILTER_B1_F1 = 0,

www.raguvaran.puzl.com
_CAN_FILTER_B1_F2 = 1,
_CAN_FILTER_B2_F1 = 2,
_CAN_FILTER_B2_F2 = 3,
_CAN_FILTER_B2_F3 = 4,
_CAN_FILTER_B2_F4 = 5;

Library Example
This is a simple demonstration of CAN Library routines usage. First node initiates the communication
with the second node by sending some data to its address. The second node responds by sending back
the data incremented by 1. First node then does the same and sends incremented data back to second
node, etc.

Code for the first CAN node:

Copy Code To Clipboard

unsigned char Can_Init_Flags, Can_Send_Flags, Can_Rcv_Flags; // can flags


unsigned char Rx_Data_Len; // received data length in bytes
char RxTx_Data[8]; // can rx/tx data buffer
char Msg_Rcvd; // reception flag
const long ID_1st = 12111, ID_2nd = 3; // node IDs
long Rx_ID;

void main() {

PORTC = 0; // clear PORTC


TRISC = 0; // set PORTC as output

Can_Init_Flags = 0; //
Can_Send_Flags = 0; // clear flags
Can_Rcv_Flags = 0; //

Can_Send_Flags = _CAN_TX_PRIORITY_0 & // form value to be used


_CAN_TX_XTD_FRAME & // with CANWrite
_CAN_TX_NO_RTR_FRAME;

Can_Init_Flags = _CAN_CONFIG_SAMPLE_THRICE & // form value to be used


_CAN_CONFIG_PHSEG2_PRG_ON & // with CANInit
_CAN_CONFIG_XTD_MSG &
_CAN_CONFIG_DBL_BUFFER_ON &
_CAN_CONFIG_VALID_XTD_MSG;

CANInitialize(1,3,3,3,1,Can_Init_Flags); // Initialize CAN module


CANSetOperationMode(_CAN_MODE_CONFIG,0xFF); // set CONFIGURATION mode
CANSetMask(_CAN_MASK_B1,-1,_CAN_CONFIG_XTD_MSG); // set all mask1 bits to ones
CANSetMask(_CAN_MASK_B2,-1,_CAN_CONFIG_XTD_MSG); // set all mask2 bits to ones
CANSetFilter(_CAN_FILTER_B2_F4,ID_2nd,_CAN_CONFIG_XTD_MSG);// set id of filter B2_F4 to 2nd node
ID

CANSetOperationMode(_CAN_MODE_NORMAL,0xFF); // set NORMAL mode

RxTx_Data[0] = 9; // set initial data to be sent

CANWrite(ID_1st, RxTx_Data, 1, Can_Send_Flags); // send initial message

while(1) { // endless loop


Msg_Rcvd = CANRead(&Rx_ID , RxTx_Data , &Rx_Data_Len, &Can_Rcv_Flags); // receive message
if ((Rx_ID == ID_2nd) && Msg_Rcvd) { // if message received
check id
PORTC = RxTx_Data[0]; // id correct, output
data at PORTC
RxTx_Data[0]++ ; // increment received
data

www.raguvaran.puzl.com
Delay_ms(10);
CANWrite(ID_1st, RxTx_Data, 1, Can_Send_Flags); // send incremented
data back
}
}
}

Code for the second CAN node:

Copy Code To Clipboard

unsigned char Can_Init_Flags, Can_Send_Flags, Can_Rcv_Flags; // can flags


unsigned char Rx_Data_Len; // received data length in bytes
char RxTx_Data[8]; // can rx/tx data buffer
char Msg_Rcvd; // reception flag
const long ID_1st = 12111, ID_2nd = 3; // node IDs
long Rx_ID;

void main() {

PORTC = 0; // clear PORTC


TRISC = 0; // set PORTC as output

Can_Init_Flags = 0; //
Can_Send_Flags = 0; // clear flags
Can_Rcv_Flags = 0; //

Can_Send_Flags = _CAN_TX_PRIORITY_0 & // form value to be used


_CAN_TX_XTD_FRAME & // with CANWrite
_CAN_TX_NO_RTR_FRAME;

Can_Init_Flags = _CAN_CONFIG_SAMPLE_THRICE & // form value to be used


_CAN_CONFIG_PHSEG2_PRG_ON & // with CANInit
_CAN_CONFIG_XTD_MSG &
_CAN_CONFIG_DBL_BUFFER_ON &
_CAN_CONFIG_VALID_XTD_MSG &
_CAN_CONFIG_LINE_FILTER_OFF;

CANInitialize(1,3,3,3,1,Can_Init_Flags); // initialize external CAN module


CANSetOperationMode(_CAN_MODE_CONFIG,0xFF); // set CONFIGURATION mode
CANSetMask(_CAN_MASK_B1,-1,_CAN_CONFIG_XTD_MSG); // set all mask1 bits to ones
CANSetMask(_CAN_MASK_B2,-1,_CAN_CONFIG_XTD_MSG); // set all mask2 bits to ones
CANSetFilter(_CAN_FILTER_B2_F3,ID_1st,_CAN_CONFIG_XTD_MSG);// set id of filter B2_F3 to 1st node
ID

CANSetOperationMode(_CAN_MODE_NORMAL,0xFF); // set NORMAL mode

while (1) { // endless loop


Msg_Rcvd = CANRead(&Rx_ID , RxTx_Data , &Rx_Data_Len, &Can_Rcv_Flags); // receive message
if ((Rx_ID == ID_1st) && Msg_Rcvd) { // if message received
check id
PORTC = RxTx_Data[0]; // id correct, output
data at PORTC
RxTx_Data[0]++ ; // increment received
data
CANWrite(ID_2nd, RxTx_Data, 1, Can_Send_Flags); // send incremented
data back
}
}
}

www.raguvaran.puzl.com
HW Connection

Example of interfacing CAN transceiver with MCU and bus

CANSPI Library
The SPI module is available with a number of the PIC compliant MCUs. The mikroC PRO for PIC provides
a library (driver) for working with mikroElektronika's CANSPI Add-on boards (with MCP2515 or
MCP2510) via SPI interface.
The CAN is a very robust protocol that has error detection and signalization, self–checking and fault
confinement. Faulty CAN data and remote frames are re-transmitted automatically, similar to the
Ethernet.
In the mikroC PRO for PIC, each routine of the CAN library has its own CANSPI counterpart with identical
syntax. For more information on Controller Area Network, consult the CAN Library. Note that an effective
communication speed depends on SPI and certainly is slower than "real" CAN.

Data transfer rates depend on distance. For example, 1 Mbit/s can be achieved at network lengths below
40m while 250 Kbit/s can be achieved at network lengths below 250m. The greater distance the lower

www.raguvaran.puzl.com
maximum bitrate that can be achieved. The lowest bitrate defined by the standard is 200Kbit/s. Cables
used are shielded twisted pairs.

CAN supports two message formats:


 Standard format, with 11 identifier bits and
 Extended format, with 29 identifier bits

Important :

 Consult the CAN standard about CAN bus termination resistance.


 An effective CANSPI communication speed depends on SPI and certainly is slower than
“real” CAN.
 The library uses the SPI module for communication. User must initialize
appropriate SPI module before using the CANSPI Library.
 For MCUs with two SPI modules it is possible to initialize both of them and then switch by
using the SPI_Set_Active routine.
 CANSPI module refers to mikroElektronika's CANSPI Add-on board connected to SPI module
of MCU.

Library Dependency Tree

External dependencies of CANSPI Library


The following variables
must be defined in all Description
Example :
projects :
using CANSPI Library:

Chip Select
extern sfr sbit CanSpi_CS; sbit CanSpi_CS at RC0_bit;
line.

extern sfr
sbit CanSpi_Rst; Reset line. sbit CanSpi_Rst at RC2_bit;

Direction of
extern sfr
sbit CanSpi_CS_Direction; the Chip sbit CanSpi_CS_Direction at TRISC0_bit;
Select pin.

Direction of
extern sfr
sbit CanSpi_Rst_Direction; the Reset sbit CanSpi_Rst_Direction at TRISC2_bit;
pin.

Library Routines
 CANSPISetOperationMode
 CANSPIGetOperationMode
 CANSPIInitialize
 CANSPISetBaudRate
 CANSPISetMask
 CANSPISetFilter

www.raguvaran.puzl.com
 CANSPIRead
 CANSPIWrite

CANSPISetOperationMode

Prototype void CANSPISetOperationMode(char mode, char WAIT);

Returns Nothing.

Description Sets the CANSPI module to requested mode.


Parameters :

 mode: CANSPI module operation mode. Valid


values: CANSPI_OP_MODE constants (see CANSPI constants).
 WAIT: CANSPI mode switching verification request. If WAIT == 0, the call is
non-blocking. The function does not verify if the CANSPI module is
switched to requested mode or not. Caller must
use CANSPIGetOperationMode to verify correct operation mode before
performing mode specific operation. If WAIT != 0, the call is blocking – the
function won’t “return” until the requested mode is set.

Requires The CANSPI routines are supported only by MCUs with the SPI module.
MCU has to be properly connected to mikroElektronika's CANSPI Extra Board or similar
hardware. See connection example at the bottom of this page.

Example // set the CANSPI module into configuration mode (wait inside
CANSPISetOperationMode until this mode is set)
CANSPISetOperationMode(_CANSPI_MODE_CONFIG, 0xFF);

CANSPIGetOperationMode

Prototype char CANSPIGetOperationMode();

Returns Current operation mode.

Description The function returns current operation mode of the CANSPI module.
Check CANSPI_OP_MODE constants (see CANSPI constants) or device datasheet for
operation mode codes.

Requires The CANSPI routines are supported only by MCUs with the SPI module.
MCU has to be properly connected to mikroElektronika's CANSPI Extra Board or similar
hardware. See connection example at the bottom of this page.

Example // check whether the CANSPI module is in Normal mode and if it is do something.
if (CANSPIGetOperationMode() == _CANSPI_MODE_NORMAL) {
...
}

www.raguvaran.puzl.com
CANSPIInitialize

Prototy void CANSPIInitialize( char SJW, char BRP, char PHSEG1, char PHSEG2, char PR
pe OPSEG, char CANSPI_CONFIG_FLAGS);

Returns Nothing.

Descrip Initializes the CANSPI module.


tion Stand-Alone CAN controller in the CANSPI module is set to:
 Disable CAN capture
 Continue CAN operation in Idle mode
 Do not abort pending transmissions
 Fcan clock : 4*Tcy (Fosc)
 Baud rate is set according to given parameters
 CAN mode : Normal
 Filter and mask registers IDs are set to zero
 Filter and mask message frame type is set according
to CANSPI_CONFIG_FLAGS value
SAM, SEG2PHTS, WAKFIL and DBEN bits are set according to CANSPI_CONFIG_FLAGS value.
Parameters:

 SJW as defined in CAN controller's datasheet


 BRP as defined in CAN controller's datasheet
 PHSEG1 as defined in CAN controller's datasheet
 PHSEG2 as defined in CAN controller's datasheet
 PROPSEG as defined in CAN controller's datasheet
 CANSPI_CONFIG_FLAGS is formed from predefined constants (see CANSPI
constants)

Require Global variables :


s
 CanSpi_CS: Chip Select line
 CanSpi_Rst: Reset line
 CanSpi_CS_Direction: Direction of the Chip Select pin
 CanSpi_Rst_Direction: Direction of the Reset pin
must be defined before using this function.

The CANSPI routines are supported only by MCUs with the SPI module.
The SPI module needs to be initialized. See
the SPIx_Init and SPIx_Init_Advanced routines.
MCU has to be properly connected to mikroElektronika's CANSPI Extra Board or similar
hardware. See connection example at the bottom of this page.

Exampl // CANSPI module connections


sbit CanSpi_CS at RC0_bit;
e sbit CanSpi_CS_Direction at TRISC0_bit;
sbit CanSpi_Rst at RC2_bit;
sbit CanSpi_Rst_Direction at TRISC2_bit;
// End CANSPI module connections

// initialize the CANSPI module with the appropriate baud rate and message acceptance
flags along with the sampling rules

www.raguvaran.puzl.com
char CanSPi_Init_Flags;
...
CanSPi_Init_Flags = _CANSPI_CONFIG_SAMPLE_THRICE & // form value to be used
_CANSPI_CONFIG_PHSEG2_PRG_ON & // with CANSPIInitialize
_CANSPI_CONFIG_XTD_MSG &
_CANSPI_CONFIG_DBL_BUFFER_ON &
_CANSPI_CONFIG_VALID_XTD_MSG;
...
SPI1_Init(); // initialize SPI module
CANSPIInitialize(1,3,3,3,1,CanSpi_Init_Flags); // initialize external CANSPI
module

CANSPISetBaudRate

Prototy void CANSPISetBaudRate( char SJW, char BRP, char PHSEG1, char PHSEG2, char PR
pe OPSEG, char CANSPI_CONFIG_FLAGS);

Returns Nothing.

Descrip Sets the CANSPI module baud rate. Due to complexity of the CAN protocol, you can not
tion simply force a bps value. Instead, use this function when the CANSPI module is in Config
mode.
SAM, SEG2PHTS and WAKFIL bits are set according to CANSPI_CONFIG_FLAGS value. Refer to
datasheet for details.
Parameters:

 SJW as defined in CAN controller's datasheet


 BRP as defined in CAN controller's datasheet
 PHSEG1 as defined in CAN controller's datasheet
 PHSEG2 as defined in CAN controller's datasheet
 PROPSEG as defined in CAN controller's datasheet
 CANSPI_CONFIG_FLAGS is formed from predefined constants (see CANSPI
constants)

Require The CANSPI module must be in Config mode, otherwise the function will be ignored.
s See CANSPISetOperationMode.
The CANSPI routines are supported only by MCUs with the SPI module.
MCU has to be properly connected to mikroElektronika's CANSPI Extra Board or similar
hardware. See connection example at the bottom of this page.

Exampl // set required baud rate and sampling rules


char canspi_config_flags;
e ...
CANSPISetOperationMode(CANSPI_MODE_CONFIG,0xFF); // set CONFIGURATION
mode (CANSPI module mast be in config mode for baud rate settings)
canspi_config_flags = _CANSPI_CONFIG_SAMPLE_THRICE &
_CANSPI_CONFIG_PHSEG2_PRG_ON &
_CANSPI_CONFIG_STD_MSG &
_CANSPI_CONFIG_DBL_BUFFER_ON &
_CANSPI_CONFIG_VALID_XTD_MSG &
_CANSPI_CONFIG_LINE_FILTER_OFF;
CANSPISetBaudRate(1, 1, 3, 3, 1, canspi_config_flags);

www.raguvaran.puzl.com
CANSPISetMask

Prototype void CANSPISetMask(char CANSPI_MASK, long val, char CANSPI_CONFIG_FLAGS);

Returns Nothing.

Description Configures mask for advanced filtering of messages. The parameter value is bit-
adjusted to the appropriate mask registers.
Parameters:

 CANSPI_MASK: CANSPI module mask number. Valid


values: CANSPI_MASK constants (see CANSPI constants)
 val: mask register value
 CANSPI_CONFIG_FLAGS: selects type of message to filter. Valid values:
 _CANSPI_CONFIG_ALL_VALID_MSG,
 _CANSPI_CONFIG_MATCH_MSG_TYPE & _CANSPI_CONFIG_STD_MSG,
 _CANSPI_CONFIG_MATCH_MSG_TYPE & _CANSPI_CONFIG_XTD_MSG.
(see CANSPI constants)

Requires The CANSPI module must be in Config mode, otherwise the function will be ignored.
See CANSPISetOperationMode.
The CANSPI routines are supported only by MCUs with the SPI module.
MCU has to be properly connected to mikroElektronika's CANSPI Extra Board or similar
hardware. See connection example at the bottom of this page.

Example // set the appropriate filter mask and message type value
CANSPISetOperationMode(_CANSPI_MODE_CONFIG,0xFF); // set
CONFIGURATION mode (CANSPI module must be in config mode for mask settings)

// Set all B1 mask bits to 1 (all filtered bits are relevant):


// Note that -1 is just a cheaper way to write 0xFFFFFFFF.
// Complement will do the trick and fill it up with ones.
CANSPISetMask(_CANSPI_MASK_B1, -1, _CANSPI_CONFIG_MATCH_MSG_TYPE &
_CANSPI_CONFIG_XTD_MSG);

CANSPISetFilter

Prototype void CANSPISetFilter(char CANSPI_FILTER, long val, char CANSPI_CONFIG_FLAG


S);

Returns Nothing.

Descriptio Configures message filter. The parameter value is bit-adjusted to the appropriate filter
n registers.
Parameters:

www.raguvaran.puzl.com
 CANSPI_FILTER: CANSPI module filter number. Valid
values: CANSPI_FILTER constants (see CANSPI constants)
 val: filter register value
 CANSPI_CONFIG_FLAGS: selects type of message to filter. Valid values:
 _CANSPI_CONFIG_ALL_VALID_MSG,
 _CANSPI_CONFIG_MATCH_MSG_TYPE & _CANSPI_CONFIG_STD_MSG,
 _CANSPI_CONFIG_MATCH_MSG_TYPE & _CANSPI_CONFIG_XTD_MSG.
(see CANSPI constants)

Requires The CANSPI module must be in Config mode, otherwise the function will be ignored.
See CANSPISetOperationMode.
The CANSPI routines are supported only by MCUs with the SPI module.
MCU has to be properly connected to mikroElektronika's CANSPI Extra Board or similar
hardware. See connection example at the bottom of this page.

Example // set the appropriate filter value and message type


CANSPISetOperationMode(_CANSPI_MODE_CONFIG,0xFF); // set
CONFIGURATION mode (CANSPI module must be in config mode for filter settings)

/* Set id of filter B1_F1 to 3: */


CANSPISetFilter(_CANSPI_FILTER_B1_F1, 3, _CANSPI_CONFIG_XTD_MSG);

CANSPIRead

Prototype char CANSPIRead(long *id, char *rd_data, char *data_len, char *CANSPI_RX_M
SG_FLAGS);

Returns  0 if nothing is received


 0xFF if one of the Receive Buffers is full (message received)

Descriptio If at least one full Receive Buffer is found, it will be processed in the following way:
n
 Message ID is retrieved and stored to location provided by
the id parameter
 Message data is retrieved and stored to a buffer provided by
the rd_data parameter
 Message length is retrieved and stored to location provided by
the data_len parameter
 Message flags are retrieved and stored to location provided by
the CANSPI_RX_MSG_FLAGS parameter
Parameters:

 id: message identifier storage address


 rd_data: data buffer (an array of bytes up to 8 bytes in length)
 data_len: data length storage address.
 CANSPI_RX_MSG_FLAGS: message flags storage address

Requires The CANSPI module must be in a mode in which receiving is possible.


See CANSPISetOperationMode.
The CANSPI routines are supported only by MCUs with the SPI module.
MCU has to be properly connected to mikroElektronika's CANSPI Extra Board or similar
hardware. See connection example at the bottom of this page.

www.raguvaran.puzl.com
Example // check the CANSPI module for received messages. If any was received do something.
char msg_rcvd, rx_flags, data_len;
char data[8];
long msg_id;
...
CANSPISetOperationMode(_CANSPI_MODE_NORMAL,0xFF); // set NORMAL
mode (CANSPI module must be in mode in which receive is possible)
...
rx_flags = 0; // clear message flags
if (msg_rcvd = CANSPIRead(msg_id, data, data_len, rx_flags)) {
...
}

CANSPIWrite

Prototype char CANSPIWrite(long id, char *wr_data, char data_len, char CANSPI_TX_MSG
_FLAGS);

Returns  0 if all Transmit Buffers are busy


 0xFF if at least one Transmit Buffer is available

Descriptio If at least one empty Transmit Buffer is found, the function sends message in the queue
n for transmission.

Parameters:

 id:CAN message identifier. Valid values: 11 or 29 bit values, depending on


message type (standard or extended)
 wr_data: data to be sent (an array of bytes up to 8 bytes in length)
 data_len: data length. Valid values: 1 to 8
 CANSPI_RX_MSG_FLAGS: message flags

Requires The CANSPI module must be in mode in which transmission is possible.


See CANSPISetOperationMode.
The CANSPI routines are supported only by MCUs with the SPI module.
MCU has to be properly connected to mikroElektronika's CANSPI Extra Board or similar
hardware. See connection example at the bottom of this page.

Example // send message extended CAN message with the appropriate ID and data
char tx_flags;
char data[8];
long msg_id;
...
CANSPISetOperationMode(_CANSPI_MODE_NORMAL,0xFF); // set NORMAL
mode (CANSPI must be in mode in which transmission is possible)

tx_flags = _CANSPI_TX_PRIORITY_0 & _CANSPI_TX_XTD_FRAME; // set message


flags
CANSPIWrite(msg_id, data, 2, tx_flags);

CANSPI Constants
There is a number of constants predefined in the CANSPI library. You need to be familiar with them in
order to be able to use the library effectively. Check the example at the end of the chapter.

www.raguvaran.puzl.com
CANSPI_OP_MODE
The CANSPI_OP_MODE constants define CANSPI operation mode.
Function CANSPISetOperationMode expects one of these as it's argument:
const char
_CANSPI_MODE_BITS = 0xE0, // Use this to access opmode bits
_CANSPI_MODE_NORMAL = 0x00,
_CANSPI_MODE_SLEEP = 0x20,
_CANSPI_MODE_LOOP = 0x40,
_CANSPI_MODE_LISTEN = 0x60,
_CANSPI_MODE_CONFIG = 0x80;

CANSPI_CONFIG_FLAGS
The CANSPI_CONFIG_FLAGS constants define flags related to the CANSPI module configuration. The
functions CANSPIInitialize, CANSPISetBaudRate, CANSPISetMask and CANSPISetFilter expect one of
these (or a bitwise combination) as their argument:
const char
_CANSPI_CONFIG_DEFAULT = 0xFF, // 11111111

_CANSPI_CONFIG_PHSEG2_PRG_BIT = 0x01,
_CANSPI_CONFIG_PHSEG2_PRG_ON = 0xFF, // XXXXXXX1
_CANSPI_CONFIG_PHSEG2_PRG_OFF = 0xFE, // XXXXXXX0

_CANSPI_CONFIG_LINE_FILTER_BIT = 0x02,
_CANSPI_CONFIG_LINE_FILTER_ON = 0xFF, // XXXXXX1X
_CANSPI_CONFIG_LINE_FILTER_OFF = 0xFD, // XXXXXX0X

_CANSPI_CONFIG_SAMPLE_BIT = 0x04,
_CANSPI_CONFIG_SAMPLE_ONCE = 0xFF, // XXXXX1XX
_CANSPI_CONFIG_SAMPLE_THRICE = 0xFB, // XXXXX0XX

_CANSPI_CONFIG_MSG_TYPE_BIT = 0x08,
_CANSPI_CONFIG_STD_MSG = 0xFF, // XXXX1XXX
_CANSPI_CONFIG_XTD_MSG = 0xF7, // XXXX0XXX

_CANSPI_CONFIG_DBL_BUFFER_BIT = 0x10,
_CANSPI_CONFIG_DBL_BUFFER_ON = 0xFF, // XXX1XXXX
_CANSPI_CONFIG_DBL_BUFFER_OFF = 0xEF, // XXX0XXXX

_CANSPI_CONFIG_MSG_BITS = 0x60,
_CANSPI_CONFIG_ALL_MSG = 0xFF, // X11XXXXX
_CANSPI_CONFIG_VALID_XTD_MSG = 0xDF, // X10XXXXX
_CANSPI_CONFIG_VALID_STD_MSG = 0xBF, // X01XXXXX
_CANSPI_CONFIG_ALL_VALID_MSG = 0x9F; // X00XXXXX

You may use bitwise AND (&) to form config byte out of these values. For example:
Copy Code To Clipboard

init = _CANSPI_CONFIG_SAMPLE_THRICE &

_CANSPI_CONFIG_PHSEG2_PRG_ON &

_CANSPI_CONFIG_STD_MSG &

_CANSPI_CONFIG_DBL_BUFFER_ON &

_CANSPI_CONFIG_VALID_XTD_MSG &

www.raguvaran.puzl.com
_CANSPI_CONFIG_LINE_FILTER_OFF;

...

CANSPIInitialize(1, 1, 3, 3, 1, init); // initialize CANSPI

CANSPI_TX_MSG_FLAGS
CANSPI_TX_MSG_FLAGS are flags related to transmission of a CAN message:
const char
_CANSPI_TX_PRIORITY_BITS = 0x03,
_CANSPI_TX_PRIORITY_0 = 0xFC, // XXXXXX00
_CANSPI_TX_PRIORITY_1 = 0xFD, // XXXXXX01
_CANSPI_TX_PRIORITY_2 = 0xFE, // XXXXXX10
_CANSPI_TX_PRIORITY_3 = 0xFF, // XXXXXX11

_CANSPI_TX_FRAME_BIT = 0x08,
_CANSPI_TX_STD_FRAME = 0xFF, // XXXXX1XX
_CANSPI_TX_XTD_FRAME = 0xF7, // XXXXX0XX

_CANSPI_TX_RTR_BIT = 0x40,
_CANSPI_TX_NO_RTR_FRAME = 0xFF, // X1XXXXXX
_CANSPI_TX_RTR_FRAME = 0xBF; // X0XXXXXX
You may use bitwise AND (&) to adjust the appropriate flags. For example:
Copy Code To Clipboard

/* form value to be used as sending message flag : */


send_config = _CANSPI_TX_PRIORITY_0 &
_CANSPI_TX_XTD_FRAME &
_CANSPI_TX_NO_RTR_FRAME;
...
CANSPIWrite(id, data, 1, send_config);

CANSPI_RX_MSG_FLAGS
CANSPI_RX_MSG_FLAGS are flags related to reception of CAN message. If a particular bit is set then
corresponding meaning is TRUE or else it will be FALSE.
const char
_CANSPI_RX_FILTER_BITS = 0x07, // Use this to access filter bits
_CANSPI_RX_FILTER_1 = 0x00,
_CANSPI_RX_FILTER_2 = 0x01,
_CANSPI_RX_FILTER_3 = 0x02,
_CANSPI_RX_FILTER_4 = 0x03,
_CANSPI_RX_FILTER_5 = 0x04,
_CANSPI_RX_FILTER_6 = 0x05,

_CANSPI_RX_OVERFLOW = 0x08, // Set if Overflowed else cleared


_CANSPI_RX_INVALID_MSG = 0x10, // Set if invalid else cleared
_CANSPI_RX_XTD_FRAME = 0x20, // Set if XTD message else cleared
_CANSPI_RX_RTR_FRAME = 0x40, // Set if RTR message else cleared
_CANSPI_RX_DBL_BUFFERED = 0x80; // Set if this message was hardware double-buffered

You may use bitwise AND (&) to adjust the appropriate flags. For example:
Copy Code To Clipboard

if (MsgFlag & _CANSPI_RX_OVERFLOW != 0) {


...

www.raguvaran.puzl.com
// Receiver overflow has occurred.
// We have lost our previous message.
}

CANSPI_MASK
The CANSPI_MASK constants define mask codes. Function CANSPISetMask expects one of these as it's
argument:
const char
_CANSPI_MASK_B1 = 0,
_CANSPI_MASK_B2 = 1;

CANSPI_FILTER
The CANSPI_FILTER constants define filter codes. Functions CANSPISetFilter expects one of these as it's
argument:
const char
_CANSPI_FILTER_B1_F1 = 0,
_CANSPI_FILTER_B1_F2 = 1,
_CANSPI_FILTER_B2_F1 = 2,
_CANSPI_FILTER_B2_F2 = 3,
_CANSPI_FILTER_B2_F3 = 4,
_CANSPI_FILTER_B2_F4 = 5;

Library Example
This is a simple demonstration of CANSPI Library routines usage. First node initiates the communication
with the second node by sending some data to its address. The second node responds by sending back
the data incremented by 1. First node then does the same and sends incremented data back to second
node, etc.

Code for the first CANSPI node:

Copy Code To Clipboard

unsigned char Can_Init_Flags, Can_Send_Flags, Can_Rcv_Flags; // can flags


unsigned char Rx_Data_Len; // received data length in bytes
char RxTx_Data[8]; // can rx/tx data buffer
char Msg_Rcvd; // reception flag
const long ID_1st = 12111, ID_2nd = 3; // node IDs
long Rx_ID;

// CANSPI module connections


sbit CanSpi_CS at RC0_bit;
sbit CanSpi_CS_Direction at TRISC0_bit;
sbit CanSpi_Rst at RC2_bit;
sbit CanSpi_Rst_Direction at TRISC2_bit;
// End CANSPI module connections

void main() {

ANSEL = 0; // Configure AN pins as digital I/O


ANSELH = 0;

PORTB = 0; // clear PORTB


TRISB = 0; // set PORTB as output

Can_Init_Flags = 0; //
Can_Send_Flags = 0; // clear flags
Can_Rcv_Flags = 0; //

www.raguvaran.puzl.com
Can_Send_Flags = _CANSPI_TX_PRIORITY_0 & // form value to be used
_CANSPI_TX_XTD_FRAME & // with CANSPIWrite
_CANSPI_TX_NO_RTR_FRAME;

Can_Init_Flags = _CANSPI_CONFIG_SAMPLE_THRICE & // Form value to be used


_CANSPI_CONFIG_PHSEG2_PRG_ON & // with CANSPIInit
_CANSPI_CONFIG_XTD_MSG &
_CANSPI_CONFIG_DBL_BUFFER_ON &
_CANSPI_CONFIG_VALID_XTD_MSG;

SPI1_Init(); // initialize SPI1 module

CANSPIInitialize(1,3,3,3,1,Can_Init_Flags); // Initialize external CANSPI


module
CANSPISetOperationMode(_CANSPI_MODE_CONFIG,0xFF); // set CONFIGURATION mode
CANSPISetMask(_CANSPI_MASK_B1,-1,_CANSPI_CONFIG_XTD_MSG); // set all mask1 bits to ones
CANSPISetMask(_CANSPI_MASK_B2,-1,_CANSPI_CONFIG_XTD_MSG); // set all mask2 bits to ones
CANSPISetFilter(_CANSPI_FILTER_B2_F4,ID_2nd,_CANSPI_CONFIG_XTD_MSG);// set id of filter B2_F4 to
2nd node ID

CANSPISetOperationMode(_CANSPI_MODE_NORMAL,0xFF); // set NORMAL mode

RxTx_Data[0] = 9; // set initial data to be sent

CANSPIWrite(ID_1st, RxTx_Data, 1, Can_Send_Flags); // send initial message

while(1) { // endless loop


Msg_Rcvd = CANSPIRead(&Rx_ID , RxTx_Data , &Rx_Data_Len, &Can_Rcv_Flags);// receive message
if ((Rx_ID == ID_2nd) && Msg_Rcvd) { // if message
received check id
PORTB = RxTx_Data[0]; // id correct, output
data at PORTC
RxTx_Data[0]++ ; // increment received
data
Delay_ms(10);
CANSPIWrite(ID_1st, RxTx_Data, 1, Can_Send_Flags); // send incremented
data back
}
}
}

Code for the second CANSPI node:

Copy Code To Clipboard

unsigned char Can_Init_Flags, Can_Send_Flags, Can_Rcv_Flags; // can flags


unsigned char Rx_Data_Len; // received data length in bytes
char RxTx_Data[8]; // can rx/tx data buffer
char Msg_Rcvd; // reception flag
const long ID_1st = 12111, ID_2nd = 3; // node IDs
long Rx_ID;

// CANSPI module connections


sbit CanSpi_CS at RC0_bit;
sbit CanSpi_CS_Direction at TRISC0_bit;
sbit CanSpi_Rst at RC2_bit;
sbit CanSpi_Rst_Direction at TRISC2_bit;
// End CANSPI module connections

void main() {

www.raguvaran.puzl.com
ANSEL = 0; // Configure AN pins as digital I/O
ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;

PORTB = 0; // clear PORTB


TRISB = 0; // set PORTB as output

Can_Init_Flags = 0; //
Can_Send_Flags = 0; // clear flags
Can_Rcv_Flags = 0; //

Can_Send_Flags = _CANSPI_TX_PRIORITY_0 & // form value to be used


_CANSPI_TX_XTD_FRAME & // with CANSPIWrite
_CANSPI_TX_NO_RTR_FRAME;

Can_Init_Flags = _CANSPI_CONFIG_SAMPLE_THRICE & // Form value to be used


_CANSPI_CONFIG_PHSEG2_PRG_ON & // with CANSPIInit
_CANSPI_CONFIG_XTD_MSG &
_CANSPI_CONFIG_DBL_BUFFER_ON &
_CANSPI_CONFIG_VALID_XTD_MSG &
_CANSPI_CONFIG_LINE_FILTER_OFF;

SPI1_Init(); // initialize SPI1


module

CANSPIInitialize(1,3,3,3,1,Can_Init_Flags); // initialize
external CANSPI module
CANSPISetOperationMode(_CANSPI_MODE_CONFIG,0xFF); // set CONFIGURATION
mode
CANSPISetMask(_CANSPI_MASK_B1,-1,_CANSPI_CONFIG_XTD_MSG); // set all mask1
bits to ones
CANSPISetMask(_CANSPI_MASK_B2,-1,_CANSPI_CONFIG_XTD_MSG); // set all mask2
bits to ones
CANSPISetFilter(_CANSPI_FILTER_B2_F3,ID_1st,_CANSPI_CONFIG_XTD_MSG); // set id of filter
B2_F3 to 1st node ID

CANSPISetOperationMode(_CANSPI_MODE_NORMAL,0xFF); // set NORMAL mode

while (1) { // endless loop


Msg_Rcvd = CANSPIRead(&Rx_ID , RxTx_Data , &Rx_Data_Len, &Can_Rcv_Flags); // receive message
if ((Rx_ID == ID_1st) && Msg_Rcvd) { // if message
received check id
PORTB = RxTx_Data[0]; // id correct,
output data at PORTC
RxTx_Data[0]++ ; // increment
received data
CANSPIWrite(ID_2nd, RxTx_Data, 1, Can_Send_Flags); // send incremented
data back
}
}
}

HW Connection

www.raguvaran.puzl.com
Example of interfacing CAN transceiver MCP2510 with MCU via SPI interface

Compact Flash Library


The Compact Flash Library provides routines for accessing data on Compact Flash card (abbr. CF further
in text). CF cards are widely used memory elements, commonly used with digital cameras. Great
capacity and excellent access time of only a few microseconds make them very attractive for
microcontroller applications.

In CF card, data is divided into sectors. One sector usually comprises 512 bytes. Routines for file
handling, the Cf_Fat routines, are not performed directly but successively through 512B buffer.

Important :
 Routines for file handling can be used only with FAT16 file system.
 Library functions create and read files from the root directory only.

www.raguvaran.puzl.com
 Library functions populate both FAT1 and FAT2 tables when writing to files, but the file data
is being read from the FAT1 table only; i.e. there is no recovery if the FAT1 table gets
corrupted.
 If MMC/SD card has Master Boot Record (MBR), the library will work with the first available
primary (logical) partition that has non-zero size. If MMC/SD card has Volume Boot Record
(i.e. there is only one logical partition and no MBRs), the library works with entire card as a
single partition. For more information on MBR, physical and logical drives,
primary/secondary partitions and partition tables, please consult other resources, e.g.
Wikipedia and similar.
 Before writing operation, make sure not to overwrite boot or FAT sector as it could make
your card on PC or digital camera unreadable. Drive mapping tools, such as Winhex, can be
of great assistance.

Library Dependency Tree

External dependencies of Compact Flash Library


The following
variables must be
defined in all Description
Example :
projects using :
Compact Flash
Library:

Compact
extern sfr
Flash Data char CF_Data_Port at PORTD;
char CF_Data_Port;
Port.
extern sfr Ready signal sbit CF_RDY at RB7_bit;
sbit CF_RDY; line.

extern sfr sbit CF_WE; Write Enable sbit CF_WE at LATB6_bit;


signal line.

Output
extern sfr sbit CF_OE; Enable sbit CF_OE at LATB5_bit;
signal line.
extern sfr Chip Detect sbit CF_CD1 at RB4_bit;
sbit CF_CD1; signal line.
extern sfr Chip Enable sbit CF_CE1 at LATB3_bit;
sbit CF_CE1; signal line.

extern sfr sbit CF_A2; Address pin sbit CF_A2 at LATB2_bit;


2.

extern sfr sbit CF_A1; Address pin sbit CF_A1 at LATB1_bit;


1.

extern sfr sbit CF_A0; Address pin sbit CF_A0 at LATB0_bit;


0.
extern sfr
Direction of sbit CF_RDY_direction at TRISB7_bit;
sbit CF_RDY_direction;

www.raguvaran.puzl.com
the Ready
pin.

Direction of
extern sfr
the Write sbit CF_WE_direction at TRISB6_bit;
sbit CF_WE_direction;
Enable pin.

Direction of
extern sfr
the Output sbit CF_OE_direction at TRISB5_bit;
sbit CF_OE_direction;
Enable pin.

Direction of
extern sfr
the Chip sbit CF_CD1_direction at TRISB4_bit;
sbit CF_CD1_direction;
Detect pin.

Direction of
extern sfr
the Chip sbit CF_CE1_direction at TRISB3_bit;
sbit CF_CE1_direction;
Enable pin.

Direction of
extern sfr
the Address sbit CF_A2_direction at TRISB2_bit;
sbit CF_A2_direction;
2 pin.

Direction of
extern sfr
the Address sbit CF_A1_direction at TRISB1_bit;
sbit CF_A1_direction;
1 pin.

Direction of
extern sfr
the Address sbit CF_A0_direction at TRISB0_bit;
sbit CF_A0_direction;
0 pin.

Library Routines
 Cf_Init
 Cf_Detect
 Cf_Enable
 Cf_Disable
 Cf_Read_Init
 Cf_Read_Byte
 Cf_Write_Init
 Cf_Write_Byte
 Cf_Read_Sector
 Cf_Write_Sector

Routines for file handling:

 Cf_Fat_Init
 Cf_Fat_QuickFormat
 Cf_Fat_Assign
 Cf_Fat_Reset
 Cf_Fat_Read
 Cf_Fat_Rewrite
 Cf_Fat_Append
 Cf_Fat_Delete
 Cf_Fat_Write
 Cf_Fat_Set_File_Date

www.raguvaran.puzl.com
 Cf_Fat_Get_File_Date
 Cf_Fat_Get_File_Date_Modified
 Cf_Fat_Get_File_Size
 Cf_Fat_Get_Swap_File

The following routine is for the internal use by compiler only:

 Cf_Issue_ID_Command

Cf_Init

Prototype void Cf_Init();

Returns Nothing.

Description Initializes ports appropriately for communication with CF card.

Requires Global variables :

 CF_Data_Port : Compact Flash data port


 CF_RDY : Ready signal line
 CF_WE : Write enable signal line
 CF_OE : Output enable signal line
 CF_CD1 : Chip detect signal line
 CF_CE1 : Enable signal line
 CF_A2 : Address pin 2
 CF_A1 : Address pin 1
 CF_A0 : Address pin 0

 CF_RDY_direction : Direction of the Ready pin


 CF_WE_direction : Direction of the Write enable pin
 CF_OE_direction : Direction of the Output enable pin
 CF_CD1_direction : Direction of the Chip detect pin
 CF_CE1_direction : Direction of the Chip enable pin
 CF_A2_direction : Direction of the Address 2 pin
 CF_A1_direction : Direction of the Address 1 pin
 CF_A0_direction : Direction of the Address 0 pin
must be defined before using this function.

Example // set compact flash pinout


char Cf_Data_Port at PORTD;

sbit CF_RDY at RB7_bit;


sbit CF_WE at LATB6_bit; // for writing to output pin always use latch (PIC18
family)
sbit CF_OE at LATB5_bit; // for writing to output pin always use latch (PIC18
family)
sbit CF_CD1 at RB4_bit;
sbit CF_CE1 at LATB3_bit; // for writing to output pin always use latch (PIC18
family)
sbit CF_A2 at LATB2_bit; // for writing to output pin always use latch (PIC18
family)
sbit CF_A1 at LATB1_bit; // for writing to output pin always use latch (PIC18

www.raguvaran.puzl.com
family)
sbit CF_A0 at LATB0_bit; // for writing to output pin always use latch (PIC18
family)

sbit CF_RDY_direction at TRISB7_bit;


sbit CF_WE_direction at TRISB6_bit;
sbit CF_OE_direction at TRISB5_bit;
sbit CF_CD1_direction at TRISB4_bit;
sbit CF_CE1_direction at TRISB3_bit;
sbit CF_A2_direction at TRISB2_bit;
sbit CF_A1_direction at TRISB1_bit;
sbit CF_A0_direction at TRISB0_bit;
// end of cf pinout
...
Cf_Init(); // initialize CF

Cf_Detect

Prototype unsigned short Cf_Detect(void);

Returns  1 - if CF card was detected


 0 - otherwise

Description Checks for presence of CF card by reading the chip detect pin.

Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.

Example // Wait until CF card is inserted:


do
asm nop;
while (!Cf_Detect());

Cf_Enable

Prototype void Cf_Enable(void);

Returns Nothing.

Description Enables the device. Routine needs to be called only if you have disabled the device by
means of the Cf_Disable routine. These two routines in conjunction allow you to
free/occupy data line when working with multiple devices.

Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.

Example // enable compact flash


Cf_Enable();

Cf_Disable

Prototype void Cf_Disable(void);

www.raguvaran.puzl.com
Returns Nothing.

Description Routine disables the device and frees the data lines for other devices. To enable the
device again, call Cf_Enable. These two routines in conjunction allow you to
free/occupy data line when working with multiple devices.

Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.

Example // disable compact flash


Cf_Disable();

Cf_Read_Init

Prototype void Cf_Read_Init(unsigned long address, unsigned short sector_count);

Returns Nothing.

Description Initializes CF card for reading.

Parameters :

 address: the first sector to be prepared for reading operation.


 sector_count: number of sectors to be prepared for reading operation.

Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.

Example // initialize compact flash for reading from sector 590


Cf_Read_Init(590, 1);

Cf_Read_Byte

Prototype unsigned short Cf_Read_Byte(void);

Returns Returns a byte read from Compact Flash sector buffer.

Note : Higher byte of the unsigned return value is cleared.

Description Reads one byte from Compact Flash sector buffer location currently pointed to by
internal read pointers. These pointers will be autoicremented upon reading.

Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
CF card must be initialized for reading operation. See Cf_Read_Init.

Example // Read a byte from compact flash:


char data;
...

www.raguvaran.puzl.com
data = Cf_Read_Byte();

Cf_Write_Init

Prototype void Cf_Write_Init(unsigned long address, unsigned short sectcnt);

Returns Nothing.

Description Initializes CF card for writing.

Parameters :

 address: the first sector to be prepared for writing operation.


 sectcnt: number of sectors to be prepared for writing operation.

Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.

Example // initialize compact flash for writing to sector 590


Cf_Write_Init(590, 1);

Cf_Write_Byte

Prototype void Cf_Write_Byte(unsigned short data_);

Returns Nothing.

Description Writes a byte to Compact Flash sector buffer location currently pointed to by writing
pointers. These pointers will be autoicremented upon reading. When sector buffer is
full, its contents will be transfered to appropriate flash memory sector.

Parameters :

 data_: byte to be written.

Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
CF card must be initialized for writing operation. See Cf_Write_Init.

Example char data_ = 0xAA;


...
Cf_Write_Byte(data_);

Cf_Read_Sector

Prototype void Cf_Read_Sector(unsigned long sector_number, unsigned short *buffer);

www.raguvaran.puzl.com
Returns Nothing.

Description Reads one sector (512 bytes). Read data is stored into buffer provided by
the buffer parameter.
Parameters :

 sector_number: sector to be read.


 buffer: data buffer of at least 512 bytes in length.

Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.

Example // read sector 22


unsigned short data[512];
...
Cf_Read_Sector(22, data);

Cf_Write_Sector

Prototype void Cf_Write_Sector(unsigned long sector_number, unsigned


short *buffer);

Returns Nothing.

Description Writes 512 bytes of data provided by the buffer parameter to one CF sector.
Parameters :

 sector_number: sector to be written to.


 buffer: data buffer of 512 bytes in length.

Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.

Example // write to sector 22


unsigned short data[512];
...
Cf_Write_Sector(22, data);

Cf_Fat_Init

Prototype unsigned short Cf_Fat_Init();

Returns  0 - if CF card was detected and successfully initialized


 1 - if FAT16 boot sector was not found
 255 - if card was not detected

Description Initializes CF card, reads CF FAT16 boot sector and extracts necessary data needed by
the library.

www.raguvaran.puzl.com
Requires Nothing.

Example // Init the FAT library


if (!Cf_Fat_Init()) { // Init the FAT library
...
}

Cf_Fat_QuickFormat

Prototype unsigned char Cf_Fat_QuickFormat(char *cf_fat_label);

Returns  0 - if CF card was detected, successfully formated and initialized


 1 - if FAT16 format was unseccessful
 255 - if card was not detected

Description Formats to FAT16 and initializes CF card.

Parameters :

 cf_fat_label: volume label (11 characters in length). If less than 11


characters are provided, the label will be padded with spaces. If null string
is passed, the volume will not be labeled.

Note :
 This routine can be used instead or in conjunction
with Cf_Fat_Init routine.
 If CF card already contains a valid boot sector, it will remain unchanged
(except volume label field) and only FAT and ROOT tables will be erased.
Also, the new volume label will be set.

Requires Nothing.

Example //--- format and initialize the FAT library -


if (!Cf_Fat_QuickFormat(&cf_fat_label)) {
...
}

Cf_Fat_Assign

Prototype unsigned short Cf_Fat_Assign(char *filename, char file_cre_attr);

Returns  0 if file does not exist and no new file is created.


 1 if file already exists or file does not exist but a new file is created.

Description Assigns file for file operations (read, write, delete...). All subsequent file operations will
be applied over the assigned file.

Parameters :

www.raguvaran.puzl.com
 filename: name of the file that should be assigned for file operations. The
file name should be in DOS 8.3 (file_name.extension) format. The file
name and extension will be automatically padded with spaces by the library
if they have less than length required (i.e. "mikro.tx" -> "mikro .tx "), so
the user does not have to take care of that. The file name and extension
are case insensitive. The library will convert them to proper case
automatically, so the user does not have to take care of that.
Also, in order to keep backward compatibility with the first version of this
library, file names can be entered as UPPERCASE string of 11 bytes in
length with no dot character between the file name and extension (i.e.
"MIKROELETXT" -> MIKROELE.TXT). In this case the last 3 characters of
the string are considered to be file extension.

 file_cre_attr: file creation and attributs flags. Each bit corresponds to


the appropriate file attribut:
Bit Mask Description

0 0x01 Read Only

1 0x02 Hidden

2 0x04 System

3 0x08 Volume Label

4 0x10 Subdirectory

5 0x20 Archive

6 0x40 Device (internal use only, never found on disk)

File creation flag. If the file does not exist and this flag is set, a new file
7 0x80
with specified name will be created.

Note : Long File Names (LFN) are not supported.

Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.

Example // create file with archive attributes if it does not already exist
Cf_Fat_Assign("MIKRO007.TXT",0xA0);

Cf_Fat_Reset

Prototype void Cf_Fat_Reset(unsigned long *size);

www.raguvaran.puzl.com
Returns Nothing.

Description Opens currently assigned file for reading.

Parameters :

 size: buffer to store file size to. After file has been open for reading its
size is returned through this parameter.

Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
File must be previously assigned. See Cf_Fat_Assign.

Example unsigned long size;


...
Cf_Fat_Reset(size);

Cf_Fat_Read

Prototype void Cf_Fat_Read(unsigned short *bdata);

Returns Nothing.

Description Reads a byte from currently assigned file opened for reading. Upon function execution
file pointers will be set to the next character in the file.

Parameters :

 bdata: buffer to store read byte to. Upon this function execution read byte
is returned through this parameter.

Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
File must be previously assigned. See Cf_Fat_Assign.
File must be open for reading. See Cf_Fat_Reset.

Example char character;


...
Cf_Fat_Read(&character);

Cf_Fat_Rewrite

Prototype void Cf_Fat_Rewrite();

Returns Nothing.

Description Opens currently assigned file for writing. If the file is not empty its content will be
erased.

www.raguvaran.puzl.com
Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
The file must be previously assigned. See Cf_Fat_Assign.

Example // open file for writing


Cf_Fat_Rewrite();

Cf_Fat_Append

Prototype void Cf_Fat_Append();

Returns Nothing.

Description Opens currently assigned file for appending. Upon this function execution file pointers
will be positioned after the last byte in the file, so any subsequent file writing operation
will start from there.

Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
File must be previously assigned. See Cf_Fat_Assign.

Example // open file for appending


Cf_Fat_Append();

Cf_Fat_Delete

Prototype void Cf_Fat_Delete();

Returns Nothing.

Description Deletes currently assigned file from CF card.

Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
File must be previously assigned. See Cf_Fat_Assign.

Example // delete current file


Cf_Fat_Delete();

Cf_Fat_Write

Prototype void Cf_Fat_Write(char *fdata, unsigned data_len);

www.raguvaran.puzl.com
Returns Nothing.

Description Writes requested number of bytes to currently assigned file opened for writing.

Parameters :

 fdata: data to be written.


 data_len: number of bytes to be written.

Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
File must be previously assigned. See Cf_Fat_Assign.
File must be open for writing. See Cf_Fat_Rewrite or Cf_Fat_Append.

Example char file_contents[42];


...
Cf_Fat_Write(file_contents, 42); // write data to the assigned file

Cf_Fat_Set_File_Date

Prototype void Cf_Fat_Set_File_Date(unsigned int year, unsigned


short month, unsigned short day, unsigned short hours, unsigned
short mins, unsigned shortseconds);

Returns Nothing.

Description Sets the date/time stamp. Any subsequent file writing operation will write this stamp to
currently assigned file's time/date attributs.

Parameters :

 year: year attribute. Valid values: 1980-2107


 month: month attribute. Valid values: 1-12
 day: day attribute. Valid values: 1-31
 hours: hours attribute. Valid values: 0-23
 mins: minutes attribute. Valid values: 0-59
 seconds: seconds attribute. Valid values: 0-59

Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
File must be previously assigned. See Cf_Fat_Assign.
File must be open for writing. See Cf_Fat_Rewrite or Cf_Fat_Append.

Example Cf_Fat_Set_File_Date(2005,9,30,17,41,0);

Cf_Fat_Get_File_Date

www.raguvaran.puzl.com
Prototype void Cf_Fat_Get_File_Date(unsigned int *year, unsigned
short *month, unsigned short *day, unsigned short *hours, unsigned
short *mins);

Returns Nothing.

Description Reads time/date attributes of currently assigned file.

Parameters :

 year: buffer to store year attribute to. Upon function execution year
attribute is returned through this parameter.
 month: buffer to store month attribute to. Upon function execution month
attribute is returned through this parameter.
 day: buffer to store day attribute to. Upon function execution day
attribute is returned through this parameter.
 hours: buffer to store hours attribute to. Upon function execution hours
attribute is returned through this parameter.
 mins: buffer to store minutes attribute to. Upon function execution
minutes attribute is returned through this parameter.

Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
File must be previously assigned. See Cf_Fat_Assign.

Example unsigned year;


char month, day, hours, mins;
...
Cf_Fat_Get_File_Date(&year, &month, &day, &hours, &mins);

Cf_Fat_Get_File_Date_Modified

Prototype void Cf_Fat_Get_File_Date_Modified(unsigned int *year, unsigned


short *month, unsigned short *day, unsigned short *hours, unsigned
short *mins);

Returns Nothing.

Description Retrieves the last modification date/time of the currently assigned file.

Parameters :

 year: buffer to store year of modification attribute to. Upon function


execution year of modification attribute is returned through this parameter.
 month: buffer to store month of modification attribute to. Upon function
execution month of modification attribute is returned through this
parameter.
 day: buffer to store day of modification attribute to. Upon function
execution day of modification attribute is returned through this parameter.
 hours: buffer to store hours of modification attribute to. Upon function
execution hours of modification attribute is returned through this

www.raguvaran.puzl.com
parameter.
 mins: buffer to store minutes of modification attribute to. Upon function
execution minutes of modification attribute is returned through this
parameter.

Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
File must be previously assigned. See Cf_Fat_Assign.

Example unsigned year;


char month, day, hours, mins;
...
Cf_Fat_Get_File_Date_Modified(&year, &month, &day, &hours, &mins);

Cf_Fat_Get_File_Size

Prototype unsigned long Cf_Fat_Get_File_Size();

Returns Size of the currently assigned file in bytes.

Description This function reads size of currently assigned file in bytes.

Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
File must be previously assigned. See Cf_Fat_Assign.

Example unsigned long my_file_size;


...
my_file_size = Cf_Fat_Get_File_Size();

Cf_Fat_Get_Swap_File

Prototype unsigned long Cf_Fat_Get_Swap_File(unsigned


long sectors_cnt, char *filename, char file_attr);

Returns  Number of the start sector for the newly created swap file, if there was
enough free space on CF card to create file of required size.
 0 - otherwise.

Description This function is used to create a swap file of predefined name and size on the CF
media. If a file with specified name already exists on the media, search for consecutive
sectors will ignore sectors occupied by this file. Therefore, it is recommended to erase
such file if it exists before calling this function. If it is not erased and there is still
enough space for a new swap file, this function will delete it after allocating new
memory space for a new swap file.

The purpose of the swap file is to make reading and writing to CF media as fast as
possible, by using the Cf_Read_Sector() and Cf_Write_Sector() functions directly,
without potentially damaging the FAT system. Swap file can be considered as a
"window" on the media where the user can freely write/read data. It's main purpose in
the mikroC's library is to be used for fast data acquisition; when the time-critical

www.raguvaran.puzl.com
acquisition has finished, the data can be re-written into a "normal" file, and formatted
in the most suitable way.
Parameters:

 sectors_cnt: number of consecutive sectors that user wants the swap file
to have.
 filename: name of the file that should be assigned for file operations. The
file name should be in DOS 8.3 (file_name.extension) format. The file
name and extension will be automatically padded with spaces by the library
if they have less than length required (i.e. "mikro.tx" -> "mikro .tx "), so
the user does not have to take care of that. The file name and extension
are case insensitive. The library will convert them to proper case
automatically, so the user does not have to take care of that.
Also, in order to keep backward compatibility with the first version of this
library, file names can be entered as UPPERCASE string of 11 bytes in
length with no dot character between the file name and extension (i.e.
"MIKROELETXT" -> MIKROELE.TXT). In this case the last 3 characters of
the string are considered to be file extension.

 file_attr: file creation and attributs flags. Each bit corresponds to the
appropriate file attribut:
Bit Mask Description

0 0x01 Read Only

1 0x02 Hidden

2 0x04 System

3 0x08 Volume Label

4 0x10 Subdirectory

5 0x20 Archive

6 0x40 Device (internal use only, never found on disk)

7 0x80 Not used

Note : Long File Names (LFN) are not supported.

Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.

Example //-------------- Try to create a swap file with archive atribute, whose size will
be at least 1000 sectors.
// If it succeeds, it sends the No. of start sector over UART
unsigned long size;
...
size = Cf_Fat_Get_Swap_File(1000, "mikroE.txt", 0x20);
if (size) {
UART1_Write(0xAA);
UART1_Write(Lo(size));
UART1_Write(Hi(size));
UART1_Write(Higher(size));

www.raguvaran.puzl.com
UART1_Write(Highest(size));
UART1_Write(0xAA);
}

Library Example
This example consists of several blocks that demonstrate various aspects ofusage of the Cf_Fat16
library. These are:

 Creation of new file and writing down to it;


 Opening existing file and re-writing it (writing from start-of-file);
 Opening existing file and appending data to it (writing from end-of-file);
 Opening a file and reading data from it (sending it to USART terminal);
 Creating and modifying several files at once;
 Reading file contents;
 Deleting file(s);
 Creating the swap file (see Help for details);
Copy Code To Clipboard

// set compact flash pinout


char Cf_Data_Port at PORTD;

sbit CF_RDY at RB7_bit;


sbit CF_WE at LATB6_bit; // for writing to output pin always use latch (PIC18 family)
sbit CF_OE at LATB5_bit; // for writing to output pin always use latch (PIC18 family)
sbit CF_CD1 at RB4_bit;
sbit CF_CE1 at LATB3_bit; // for writing to output pin always use latch (PIC18 family)
sbit CF_A2 at LATB2_bit; // for writing to output pin always use latch (PIC18 family)
sbit CF_A1 at LATB1_bit; // for writing to output pin always use latch (PIC18 family)
sbit CF_A0 at LATB0_bit; // for writing to output pin always use latch (PIC18 family)

sbit CF_RDY_direction at TRISB7_bit;


sbit CF_WE_direction at TRISB6_bit;
sbit CF_OE_direction at TRISB5_bit;
sbit CF_CD1_direction at TRISB4_bit;
sbit CF_CE1_direction at TRISB3_bit;
sbit CF_A2_direction at TRISB2_bit;
sbit CF_A1_direction at TRISB1_bit;
sbit CF_A0_direction at TRISB0_bit;
// end of cf pinout

const LINE_LEN = 39;


char err_txt[20] = "FAT16 not found";
char file_contents[LINE_LEN] = "XX CF FAT16 library by Anton Rieckertn";
char filename[14] = "MIKRO00x.TXT"; // File names
unsigned short loop, loop2;
unsigned long i, size;
char Buffer[512];

// UART1 write text and new line (carriage return + line feed)
void UART1_Write_Line(char *uart_text) {
UART1_Write_Text(uart_text);
UART1_Write(13);
UART1_Write(10);
}

// Creates new file and writes some data to it


void M_Create_New_File() {
filename[7] = 'A';
Cf_Fat_Set_File_Date(2005,6,21,10,35,0); // Set file date & time info
Cf_Fat_Assign(&filename, 0xA0); // Find existing file or create a new one
Cf_Fat_Rewrite(); // To clear file and start with new data

www.raguvaran.puzl.com
for(loop = 1; loop <= 99; loop++) {
UART1_Write('.');
file_contents[0] = loop / 10 + 48;
file_contents[1] = loop % 10 + 48;
Cf_Fat_Write(file_contents, LINE_LEN-1); // write data to the assigned file
}
}

// Creates many new files and writes data to them


void M_Create_Multiple_Files() {
for(loop2 = 'B'; loop2 <= 'Z'; loop2++) {
UART1_Write(loop2); // signal the progress
filename[7] = loop2; // set filename
Cf_Fat_Set_File_Date(2005,6,21,10,35,0); // Set file date & time info
Cf_Fat_Assign(&filename, 0xA0); // find existing file or create a new one
Cf_Fat_Rewrite(); // To clear file and start with new data
for(loop = 1; loop <= 44; loop++) {
file_contents[0] = loop / 10 + 48;
file_contents[1] = loop % 10 + 48;
Cf_Fat_Write(file_contents, LINE_LEN-1); // write data to the assigned file
}
}
}

// Opens an existing file and rewrites it


void M_Open_File_Rewrite() {
filename[7] = 'C';
Cf_Fat_Assign(&filename, 0);
Cf_Fat_Rewrite();
for(loop = 1; loop <= 55; loop++) {
file_contents[0] = loop / 10 + 48;
file_contents[1] = loop % 10 + 48;
Cf_Fat_Write(file_contents, LINE_LEN-1); // write data to the assigned file
}
}

// Opens an existing file and appends data to it


// (and alters the date/time stamp)
void M_Open_File_Append() {
filename[7] = 'B';
Cf_Fat_Assign(&filename, 0);
Cf_Fat_Set_File_Date(2009, 1, 23, 17, 22, 0);
Cf_Fat_Append(); // Prepare file for append
Cf_Fat_Write(" for mikroElektronika 2010n", 27); // Write data to assigned file
}

// Opens an existing file, reads data from it and puts it to UART


void M_Open_File_Read() {
char character;

filename[7] = 'B';
Cf_Fat_Assign(&filename, 0);
Cf_Fat_Reset(&size); // To read file, procedure returns size of file
for (i = 1; i <= size; i++) {
Cf_Fat_Read(&character);
UART1_Write(character); // Write data to UART
}
}

// Deletes a file. If file doesn't exist, it will first be created


// and then deleted.
void M_Delete_File() {
filename[7] = 'F';
Cf_Fat_Assign(filename, 0);
Cf_Fat_Delete();
}

www.raguvaran.puzl.com
// Tests whether file exists, and if so sends its creation date
// and file size via UART
void M_Test_File_Exist() {
unsigned long fsize;
unsigned int year;
unsigned short month, day, hour, minute;
unsigned char outstr[12];

filename[7] = 'B'; //uncomment this line to search for file that DOES exists
// filename[7] = 'F'; //uncomment this line to search for file that DOES NOT exist
if (Cf_Fat_Assign(filename, 0)) {
//--- file has been found - get its date
Cf_Fat_Get_File_Date(&year, &month, &day, &hour, &minute);
UART1_Write_Text(" created: ");
WordToStr(year, outstr);
UART1_Write_Text(outstr);
ByteToStr(month, outstr);
UART1_Write_Text(outstr);
WordToStr(day, outstr);
UART1_Write_Text(outstr);
WordToStr(hour, outstr);
UART1_Write_Text(outstr);
WordToStr(minute, outstr);
UART1_Write_Text(outstr);

//--- file has been found - get its modified date


Cf_Fat_Get_File_Date_Modified(&year, &month, &day, &hour, &minute);
UART1_Write_Text(" modified: ");
WordToStr(year, outstr);
UART1_Write_Text(outstr);
ByteToStr(month, outstr);
UART1_Write_Text(outstr);
WordToStr(day, outstr);
UART1_Write_Text(outstr);
WordToStr(hour, outstr);
UART1_Write_Text(outstr);
WordToStr(minute, outstr);
UART1_Write_Text(outstr);

//--- get file size


fsize = Cf_Fat_Get_File_Size();
LongToStr((signed long)fsize, outstr);
UART1_Write_Line(outstr);
}
else {
//--- file was not found - signal it
UART1_Write(0x55);
Delay_ms(1000);
UART1_Write(0x55);
}
}

// Tries to create a swap file, whose size will be at least 100


// sectors (see Help for details)
void M_Create_Swap_File() {
unsigned int i;

for(i=0; i<512; i++)


Buffer[i] = i;

size = Cf_Fat_Get_Swap_File(5000, "mikroE.txt", 0x20); // see help on this function for


details

if (size) {
LongToStr((signed long)size, err_txt);
UART1_Write_Line(err_txt);

www.raguvaran.puzl.com
for(i=0; i<5000; i++) {
Cf_Write_Sector(size++, Buffer);
UART1_Write('.');
}
}
}

// Main. Uncomment the function(s) to test the desired operation(s)


void main() {
#define COMPLETE_EXAMPLE // comment this line to make simpler/smaller example
ADCON1 |= 0x0F; // Configure AN pins as digital
CMCON |= 7; // Turn off comparators

// Initialize UART1 module


UART1_Init(19200);
Delay_ms(10);

UART1_Write_Line("PIC-Started"); // PIC present report

// use fat16 quick format instead of init routine if a formatting is needed


if (Cf_Fat_Init() == 0) {
Delay_ms(2000); // wait for a while until the card is stabilized
// period depends on used CF card
//--- Test start
UART1_Write_Line("Test Start.");
//--- Test routines. Uncomment them one-by-one to test certain features
M_Create_New_File();
#ifdef COMPLETE_EXAMPLE
M_Create_Multiple_Files();
M_Open_File_Rewrite();
M_Open_File_Append();
M_Open_File_Read();
M_Delete_File();
M_Test_File_Exist();
M_Create_Swap_File();
#endif
UART1_Write_Line("Test End.");

}
else {
UART1_Write_Line(err_txt); // Note: Cf_Fat_Init tries to initialize a card more than once.
// If card is not present, initialization may last longer
(depending on clock speed)
}

www.raguvaran.puzl.com
HW Connection

Pin diagram of CF memory card

www.raguvaran.puzl.com
EEPROM Library
EEPROM data memory is available with a number of PIC MCUs. mikroC PRO for PIC includes library for
comfortable work with EEPROM.

Library Routines
 EEPROM_Read
 EEPROM_Write

EEPROM_Read

Prototype // for PIC16


unsigned short EEPROM_Read(unsigned short address);
// for PIC18
unsigned short EEPROM_Read(unsigned int address);

Returns Returns byte from specified address.

Description Reads data from specified address. Parameter address is MCU dependent; for PIC16
family it is of short type, and for PIC18 family it is of integer type.

Requires Requires EEPROM module.


Ensure minimum 20ms delay between successive use of
routines EEPROM_Write and EEPROM_Read. Although PIC will write the correct
value, EEPROM_Read might return an undefined result.

Example unsigned short take;


...
take = EEPROM_Read(0x3F);

EEPROM_Write

Prototype // for PIC16


void EEPROM_Write(unsigned short address, unsigned short data);
// for PIC18
void EEPROM_Write(unsigned int address, unsigned short data);

Returns Nothing.

Description Writes data to specified address. Parameter address is MCU dependent; for PIC16
family it is of short type, and for PIC18 family it is of integer type.
Be aware that all interrupts will be disabled during execution of EEPROM_Write routine
(GIE bit of INTCON register will be cleared). Routine will restore previous state of this
bit on exit.

Requires Requires EEPROM module.


Ensure minimum 20ms delay between successive use of
routines EEPROM_Write and EEPROM_Read. Although PIC will write the correct
value, EEPROM_Read might return an undefined result.

www.raguvaran.puzl.com
Example EEPROM_Write(0x32, 19);

Library Example
The example demonstrates use of EEPROM Library.
Copy Code To Clipboard

char ii; // loop variable

void main(){
ANSEL = 0; // Configure AN pins as digital I/O
ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;

PORTB = 0;
PORTC = 0;
PORTD = 0;

TRISB = 0;
TRISC = 0;
TRISD = 0;

for(ii = 0; ii < 32; ii++) // Fill data buffer


EEPROM_Write(0x80+ii, ii); // Write data to address 0x80+ii

EEPROM_Write(0x02,0xAA); // Write some data at address 2


EEPROM_Write(0x50,0x55); // Write some data at address 0150

Delay_ms(1000); // Blink PORTB and PORTC LEDs


PORTB = 0xFF; // to indicate reading start
PORTC = 0xFF;
Delay_ms(1000);
PORTB = 0x00;
PORTC = 0x00;
Delay_ms(1000);

PORTB = EEPROM_Read(0x02); // Read data from address 2 and display it on PORTB


PORTC = EEPROM_Read(0x50); // Read data from address 0x50 and display it on PORTC

Delay_ms(1000);

for(ii = 0; ii < 32; ii++) { // Read 32 bytes block from address 0x80
PORTD = EEPROM_Read(0x80+ii); // and display data on PORTD
Delay_ms(250);
}
}

www.raguvaran.puzl.com
Epson S1D13700 Graphic Lcd Library
The mikroC PRO for PIC provides a library for working with Glcds based on Epson S1D13700 controller.

The S1D13700 Glcd is capable of displaying both text and graphics on an LCD panel. The S1D13700
Glcd allows layered text and graphics, scrolling of the display in any direction, and partitioning of the
display into multiple screens.
It includes 32K bytes of embedded SRAM display memory which is used to store text, character codes,
and bit-mapped graphics.

The S1D13700 Glcd handles display controller functions including :

 Transferring data from the controlling microprocessor to the buffer memory


 Reading memory data, converting data to display pixels
 Generating timing signals for the LCD panel
The S1D13700 Glcd is designed with an internal character generator which supports 160, 5x7 pixel
characters in internal mask ROM (CGROM) and 64, 8x8 pixel characters incharacter generator RAM
(CGRAM).
When the CGROM is not used, up to 256, 8x16 pixel characters are supported in CGRAM.

External dependencies of the Epson S1D13700 Graphic Lcd Library


The following variables
must be defined in all Description
Example :
projects using S1D13700 :
Graphic Lcd library:
extern sfr System data char S1D13700_DATA at PORTD;
char S1D13700_DATA; bus.
extern sfr sbit S1D13700_WR; Write signal. sbit S1D13700_WR at LATC2_bit;

extern sfr sbit S1D13700_RD; Read signal. sbit S1D13700_RD at LATC1_bit;

extern sfr sbit S1D13700_A0; System sbit S1D13700_A0 at LATC0_bit;


Address pin.

extern sfr sbit S1D13700_RES; Reset sbit S1D13700_RES at LATC4_bit;


signal.
extern sfr sbit S1D13700_CS; Chip select. sbit S1D13700_CS at LATC4_bit;

Direction of
extern sfr the system sbit S1D13700_DATA_Direction at TRISD;
sbit S1D13700_DATA_Direction; data bus
pins.

Direction of
extern sfr
the Write sbit S1D13700_WR_Direction atTRISC2_bit;
sbit S1D13700_WR_Direction;
pin.

Direction of
extern sfr
the Read sbit S1D13700_RD_Direction atTRISC1_bit;
sbit S1D13700_RD_Direction;
pin.

Direction of
extern sfr
the System sbit S1D13700_A0_Direction atTRISC2_bit;
sbit S1D13700_A0_Direction;
Address pin.

www.raguvaran.puzl.com
Direction of
extern sfr
the Reset sbit S1D13700_RES_Direction atTRISC0_bit;
sbit S1D13700_RES_Direction;
pin.

Direction of
extern sfr
the Chip sbit S1D13700_CS_Direction atTRISC4_bit;
sbit S1D13700_CS_Direction;
select pin.

Library Routines
 S1D13700_Init
 S1D13700_Write_Command
 S1D13700_Write_Parameter
 S1D13700_Read_Parameter
 S1D13700_Fill
 S1D13700_GrFill
 S1D13700_TxtFill
 S1D13700_Display_GrLayer
 S1D13700_Display_TxtLayer
 S1D13700_Set_Cursor
 S1D13700_Display_Cursor
 S1D13700_Write_Char
 S1D13700_Write_Text
 S1D13700_Dot
 S1D13700_Line
 S1D13700_H_Line
 S1D13700_V_Line
 S1D13700_Rectangle
 S1D13700_Box
 S1D13700_Rectangle_Round_Edges
 S1D13700_Rectangle_Round_Edges_Fill
 S1D13700_Circle
 S1D13700_Circle_Fill
 S1D13700_Image
 S1D13700_PartialImage

S1D13700_Init

Prototype void S1D13700_Init(unsigned int width, unsigned char height);

Returns Nothing.

Description Initializes S1D13700 Graphic Lcd controller.

Parameters :

 width: width of the Glcd panel.


 height: height of the Glcd panel.

Requires Global variables :

 S1D13700_Data_Port: Data Bus Port.

www.raguvaran.puzl.com
 S1D13700_WR: Write signal pin.
 S1D13700_RD: Read signal pin.
 S1D13700_A0: Command/Data signal pin.
 S1D13700_RES: Reset signal pin.
 S1D13700_CS: Chip Select signal pin.

 S1D13700_Data_Port_Direction: Data Bus Port Direction.


 S1D13700_WR_Direction: Direction of Write signal pin.
 S1D13700_RD_Direction: Direction of Read signal pin.
 S1D13700_A0_Direction: Direction of Command/Data signal pin.
 S1D13700_RES_Direction: Direction of Reset signal pin.
 S1D13700_CS_Direction: Direction of Chip Select signal pin.
must be defined before using this function.

Example // S1D13700 module connections


char S1D13700_Data_Port at PORTD;
sbit S1D13700_WR at LATC2_bit;
sbit S1D13700_RD at LATC1_bit;
sbit S1D13700_A0 at LATC0_bit;
sbit S1D13700_RES at LATC4_bit;
sbit S1D13700_CS at LATC5_bit;

char S1D13700_Data_Port_Direction at TRISD;


sbit S1D13700_WR_Direction at TRISC2_bit;
sbit S1D13700_RD_Direction at TRISC1_bit;
sbit S1D13700_A0_Direction at TRISC0_bit;
sbit S1D13700_RES_Direction at TRISC4_bit;
sbit S1D13700_CS_Direction at TRISC5_bit;
// End of S1D13700 module connections
...
// init display for 320 pixel width, 240 pixel height
S1D13700_Init(320, 240);

S1D13700_Write_Command

Prototype void S1D13700_Write_Command(char command);

Returns Nothing.

Description Writes a command to S1D13700 controller.

Parameters :

 command: command to be issued :

Value Description

S1D13700_SYSTEM_SET General system settings.

S1D13700_POWER_SAVE Enter into power saving mode.

S1D13700_DISP_ON Turn the display on.

www.raguvaran.puzl.com
S1D13700_DISP_OFF Turn the display off.

S1D13700_SCROLL Setup text and graphics address regions.

S1D13700_CS_RIGHT Cursor moves right after write to display memory.

S1D13700_CS_LEFT Cursor moves left after write to display memory.

S1D13700_CS_UP Cursor moves up after write to display memory.

S1D13700_CS_DOWN Cursor moves down after write to display memory.

S1D13700_OVLAY Configure how layers overlay.

S1D13700_CGRAM_ADR Configure character generator RAM address.

S1D13700_HDOT_SCR Set horizontal scroll rate.

S1D13700_CSRW Set the cursor address.

S1D13700_CSRR Read the cursor address.

S1D13700_GRAYSCALE Selects the gray scale depth, in bits-per-pixel (bpp).

S1D13700_MEMWRITE Write to display memory.

S1D13700_MEMREAD Read from display memory.

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example // Turn the display on


S1D13700_Write_Command(S1D13700_DISP_ON);

S1D13700_Write_Parameter

Prototype void S1D13700_Write_Parameter(char parameter);

Returns Nothing.

Description Writes a parameter to S1D13700 controller.

Parameters :

 parameter: parameter to be written.

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.


Previously, a command must be sent through S1D13700_Write_Command routine.

www.raguvaran.puzl.com
Example S1D13700_Write_Command(S1D13700_CSRW); // set cursor address
S1D13700_Write_Parameter(Lo(start)); // send lower byte of cursor address
S1D13700_Write_Parameter(Hi(start)); // send higher byte cursor address

S1D13700_Read_Parameter

Prototype char S1D13700_Read_Parameter();

Returns Nothing.

Description Reads a parameter from GLCD port.

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example parameter = S1D13700_Read_Parameter();

S1D13700_Fill

Prototype void S1D13700_Fill(char d, unsigned int start, unsigned int len);

Returns Nothing.

Description Fills Glcd memory block with given byte.

Parameters :

 d: byte to be written.
 start: starting address of the memory block.
 len: length of the memory block in bytes.

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example // from the starting address of 0x3000, fill the memory block size of 0x7FFF with
0x20
S1D13700_Fill(0x20, 0x3000, 0x7FFF);

S1D13700_GrFill

Prototype void S1D13700_GrFill(char d);

Returns Nothing.

Description Fill graphic layer with appropriate value (0 to clear).

www.raguvaran.puzl.com
Parameters :

 d: value to fill graphic layer with.

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example // clear current graphic panel


S1D13700_GrFill(0);

S1D13700_TxtFill

Prototype void S1D13700_TxtFill(char d);

Returns Nothing.

Description Fill current text panel with appropriate value (0 to clear).

Parameters :

 d: this value will be used to fill text panel.

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example // clear current text panel


S1D13700_TxtFill(0);

S1D13700_Display_GrLayer

Prototype void S1D13700_Display_GrLayer(char mode);

Returns Nothing.

Description Display selected graphic layer.

Parameters :

 mode: graphic layer mode. Valid values :

Value Description

S1D13700_LAYER_OFF Turn off graphic layer.

S1D13700_LAYER_ON Turn on graphic layer.

S1D13700_LAYER_FLASH_2Hz Turn on graphic layer and flash it at the rate of 2 Hz.

S1D13700_LAYER_FLASH_16Hz Turn on graphic layer and flash it at the rate of 16 Hz.

www.raguvaran.puzl.com
Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example // Turn on graphic layer


S1D13700_Display_GrLayer(S1D13700_LAYER_ON);

S1D13700_Display_TxtLayer

Prototype void S1D13700_Display_TxtLayer(char mode);

Returns Nothing.

Description Display selected text layer.

Parameters :

 mode: text layer mode. Valid values :

Value Description

S1D13700_LAYER_OFF Turn off graphic layer.

S1D13700_LAYER_ON Turn on graphic layer.

S1D13700_LAYER_FLASH_2Hz Turn on graphic layer and flash it at the rate of 2 Hz.

S1D13700_LAYER_FLASH_16Hz Turn on graphic layer and flash it at the rate of 16 Hz.

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example // Display on text layer


S1D13700_Display_TxtLayer(S1D13700_LAYER_ON);

S1D13700_Set_Cursor

Prototype void S1D13700_Set_Cursor(char width, char height, char mode);

Returns Nothing.

Description Sets cursor properties.

Parameters :

 width: in pixels-1 (must be less than or equal to the horizontal char size).
 height: in lines-1 (must be less than or equal to the vertical char size).
 mode: cursor mode. Valid values :

Value Description

www.raguvaran.puzl.com
S1D13700_CURSOR_UNDERSCORE Set cursor shape - underscore.

S1D13700_CURSOR_BLOCK Set cursor shape - block.

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example // set cursor with the following properties : width 5px, height 10px, cursor
shape - block
S1D13700_Set_Cursor(5, 10, S1D13700_CURSOR_BLOCK);

S1D13700_Display_Cursor

Prototype void S1D13700_Display_Cursor(char mode);

Returns Nothing.

Description Displays cursor.

Parameters :

 mode: mode parameter. Valid values:

Value Description

S1D13700_CURSOR_OFF Turn off graphic layer.

S1D13700_CURSOR_ON Turn on graphic layer.

S1D13700_CURSOR_FLASH_2Hz Turn on graphic layer and flash it at the rate of 2 Hz.

S1D13700_CURSOR_FLASH_16Hz Turn on graphic layer and flash it at the rate of 16 Hz.

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example // set cursor on


S1D13700_Display_Cursor(S1D13700_CURSOR_ON);

S1D13700_Write_Char

Prototype void S1D13700_Write_Char(unsigned char c, unsigned int x, unsigned


int y, unsigned char mode);

Returns Nothing.

Description Writes a char in the current text layer of Glcd at coordinates (x, y).

www.raguvaran.puzl.com
Parameters :

 c: char to be written.
 x: char position on x-axis (column).
 y: char position on y-axis (row).
 mode: mode parameter. Valid values :

Value Description

In the OR-Mode, text and graphics can be displayed and the data is
logically "OR-ed".
S1D13700_OVERLAY_OR This is the most common way of combining text and graphics, for
example labels on buttons.

In this mode, the text and graphics data are combined via the logical
S1D13700_OVERLAY_XOR "exclusive OR".<="" td="" style="margin: 0px; padding: 0px; ">

The text and graphic data shown on display are combined via the
S1D13700_OVERLAY_AND logical "AND function".

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example S1D13700_Write_Char('A',22,23,S1D13700_OVERLAY_OR);

S1D13700_Write_Text

Prototype void S1D13700_Write_Text(unsigned char *str, unsigned char x, unsigned


char y, char mode);

Returns Nothing.

Description Writes text in the current text panel of Glcd at coordinates (x, y).

Parameters :

 str: text to be written.


 x: text position on x-axis (column).
 y: text position on y-axis (row).
 mode: mode parameter. Valid values :

Value Description

In the OR-Mode, text and graphics can be displayed and the data is
logically "OR-ed".
S1D13700_OVERLAY_OR This is the most common way of combining text and graphics, for
example labels on buttons.

In this mode, the text and graphics data are combined via the logical
S1D13700_OVERLAY_XOR "exclusive OR".<="" td="" style="margin: 0px; padding: 0px; ">

The text and graphic data shown on display are combined via the
S1D13700_OVERLAY_AND logical "AND function".

www.raguvaran.puzl.com
Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example S1D13700_Write_Text("EPSON LIBRARY DEMO, WELCOME !", 0, 0, S1D13700_OVERLAY_OR);

S1D13700_Dot

Prototype void S1D13700_Dot(unsigned int x, unsigned int y, unsigned short color);

Returns Nothing.

Description Draws a dot in the current graphic panel of Glcd at coordinates (x, y).

Parameters :

 x: dot position on x-axis.


 y: dot position on y-axis.
 color: color parameter. Valid values :

Value Description

S1D13700_BLACK Black color.

S1D13700_WHITE White color.

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example S1D13700_Dot(50, 50, S1D13700_WHITE);

S1D13700_Line

Prototype void S1D13700_Line(unsigned int x0, unsigned int y0, unsigned


int x1, unsigned int y1, unsigned char pcolor);

Returns Nothing.

Description Draws a line from (x0, y0) to (x1, y1).

Parameters :

 x0: x coordinate of the line start.


 y0: y coordinate of the line end.
 x1: x coordinate of the line start.
 y1: y coordinate of the line end.
 pcolor: color parameter. Valid values :

Value Description

www.raguvaran.puzl.com
S1D13700_BLACK Black color.

S1D13700_WHITE White color.

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example S1D13700_Line(0, 0, 239, 127, S1D13700_WHITE);

S1D13700_H_Line

Prototype void S1D13700_H_Line(unsigned int x_start, unsigned int x_end, unsigned


int y_pos, unsigned short color);

Returns Nothing.

Description Draws a horizontal line.

Parameters :

 x_start: x coordinate of the line start.


 x_end: x coordinate of the line end.
 y_pos: line position on the y axis.
 pcolor: color parameter. Valid values :

Value Description

S1D13700_BLACK Black color.

S1D13700_WHITE White color.

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example S1D13700_Line(0, 0, 239, 127, S1D13700_WHITE);

S1D13700_V_Line

Prototype void S1D13700_V_Line(unsigned int y_start, unsigned int y_end, unsigned


int x_pos, unsigned short color);

Returns Nothing.

Description Draws a horizontal line.

Parameters :

 y_start: y coordinate of the line start.

www.raguvaran.puzl.com
 y_end: y coordinate of the line end.
 x_pos: line position on the x axis.
 pcolor: color parameter. Valid values :

Value Description

S1D13700_BLACK Black color.

S1D13700_WHITE White color.

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example S1D13700_Line(0, 0, 239, 127, S1D13700_WHITE);

S1D13700_Rectangle

Prototype void S1D13700_Rectangle(unsigned int x0, unsigned int y0, unsigned


int x1, unsigned int y1, unsigned char pcolor);

Returns Nothing.

Description Draws a rectangle on Glcd.

Parameters :

 x0: x coordinate of the upper left rectangle corner.


 y0: y coordinate of the upper left rectangle corner.
 x1: x coordinate of the lower right rectangle corner.
 y1: y coordinate of the lower right rectangle corner.
 pcolor: color parameter. Valid values :

Value Description

S1D13700_BLACK Black color.

S1D13700_WHITE White color.

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example S1D13700_rectangle(20, 20, 219, 107, S1D13700_WHITE);

S1D13700_Box

Prototype void S1D13700_Box(unsigned int x0, unsigned int y0, unsigned


int x1, unsigned int y1, unsigned char pcolor);

Returns Nothing.

www.raguvaran.puzl.com
Description Draws a box on Glcd.

Parameters :

 x0: x coordinate of the upper left box corner.


 y0: y coordinate of the upper left box corner.
 x1: x coordinate of the lower right box corner.
 y1: y coordinate of the lower right box corner.
 pcolor: color parameter. Valid values :

Value Description

S1D13700_BLACK Black color.

S1D13700_WHITE White color.

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example S1D13700_Box(0, 119, 239, 127, S1D13700_WHITE);

S1D13700_Rectangle_Round_Edges

Prototype void S1D13700_Rectangle_Round_Edges(unsigned int x_upper_left, unsigned


int y_upper_left, unsigned int x_bottom_right, unsigned
int y_bottom_right,unsigned short round_radius, unsigned short color);

Returns Nothing.

Description Draws a rounded edge rectangle on Glcd.

Parameters :

 x_upper_left: x coordinate of the upper left rectangle corner.


 y_upper_left: y coordinate of the upper left rectangle corner.
 x_bottom_right: x coordinate of the lower right rectangle corner.
 y_bottom_right: y coordinate of the lower right rectangle corner.
 round_radius: radius of the rounded edge.
 pcolor: color parameter. Valid values :

Value Description

S1D13700_BLACK Black color.

S1D13700_WHITE White color.

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example S1D13700_Rectangle_Round_Edges(20, 20, 219, 107, 12, S1D13700_WHITE);

www.raguvaran.puzl.com
S1D13700_Rectangle_Round_Edges_Fill

Prototype void S1D13700_Rectangle_Round_Edges_Fill(unsigned int x0, unsigned


int y0, unsigned int x1, unsigned int y1, unsigned
short round_radius, unsigned short color);

Returns Nothing.

Description Draws a filled rounded edge rectangle on Glcd.

Parameters :

 x_upper_left: x coordinate of the upper left rectangle corner.


 y_upper_left: y coordinate of the upper left rectangle corner.
 x_bottom_right: x coordinate of the lower right rectangle corner.
 y_bottom_right: y coordinate of the lower right rectangle corner.
 round_radius: radius of the rounded edge.
 pcolor: color parameter. Valid values :

Value Description

S1D13700_BLACK Black color.

S1D13700_WHITE White color.

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example S1D13700_Rectangle_Round_Edges_Fill(20, 20, 219, 107, 12, S1D13700_WHITE);

S1D13700_Circle

Prototype void S1D13700_Circle(unsigned int x_center, unsigned


int y_center, unsigned int radius, unsigned short color);

Returns Nothing.

Description Draws a circle on Glcd.

Parameters :

 x_center: x coordinate of the circle center.


 y_center: y coordinate of the circle center.
 radius: radius size.
 color: color parameter. Valid values :

Value Description

S1D13700_BLACK Black color.

www.raguvaran.puzl.com
S1D13700_WHITE White color.

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example S1D13700_Circle(120, 64, 110, S1D13700_WHITE);

S1D13700_Circle_Fill

Prototype void S1D13700_Circle_Fill(unsigned int x_center, unsigned


int y_center, unsigned int radius, unsigned short color);

Returns Nothing.

Description Draws a filled circle on Glcd.

Parameters :

 x_center: x coordinate of the circle center.


 y_center: y coordinate of the circle center.
 radius: radius size.
 color: color parameter. Valid values :

Value Description

S1D13700_BLACK Black color.

S1D13700_WHITE White color.

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example S1D13700_Circle_Fill(120, 64, 110, S1D13700_WHITE);

S1D13700_Image

Prototype void S1D13700_Image(const code char *pic);

Returns Nothing.

Description Displays bitmap on Glcd.

Parameters :

 image: image to be displayed. Bitmap array is located in code memory.

Note : Image dimension must match the display dimension.

www.raguvaran.puzl.com
Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example S1D13700_Image(image);

S1D13700_PartialImage

Prototype void S1D13700_PartialImage(unsigned int x_left, unsigned


int y_top, unsigned int width, unsigned int height, unsigned
int picture_width, unsigned int picture_height, code const unsigned
short * image);

Returns Nothing.

Description Displays a partial area of the image on a desired location.

Parameters :

 x_left: x coordinate of the desired location (upper left coordinate).


 y_top: y coordinate of the desired location (upper left coordinate).
 width: desired image width.
 height: desired image height.
 picture_width: width of the original image.
 picture_height: height of the original image.
 image: image to be displayed. Bitmap array is located in code memory.

Note : Image dimension must match the display dimension.

Requires Glcd module needs to be initialized. See the S1D13700_Init routine.

Example // Draws a 10x15 part of the image starting from the upper left corner on the
coordinate (10,12). Original image size is 16x32.
S1D13700_PartialImage(10, 12, 10, 15, 16, 32, image);

www.raguvaran.puzl.com
Ethernet PIC18FxxJ60 Library
PIC18FxxJ60 family of microcontrollers feature an embedded Ethernet controller module. This is a
complete connectivity solution, including full implementations of both Media Access Control (MAC) and
Physical Layer transceiver (PHY) modules. Two pulse transformers and a few passive components are all
that are required to connect the microcontroller directly to an Ethernet network.
The Ethernet module meets all of the IEEE 802.3 specifications for 10-BaseT connectivity to a twisted-
pair network. It incorporates a number of packet filtering schemes to limit incoming packets. It also
provides an internal DMA module for fast data throughput and hardware assisted IP checksum
calculations. Provisions are also made for two LED outputs to indicate link and network activity
This library provides the posibility to easily utilize ethernet feature of the above mentioned MCUs.

Ethernet PIC18FxxJ60 library supports:

 IPv4 protocol.
 ARP requests.
 ICMP echo requests.
 UDP requests.
 TCP requests (no stack, no packet reconstruction).
 ARP client with cache.
 DNS client.
 UDP client.
 DHCP client.
 packet fragmentation is NOT supported.

Important :
 Global library variable Ethernet_userTimerSec is used to keep track of time for all client
implementations (ARP, DNS, UDP and DHCP). It is user responsibility to increment this
variable each second in it's code if any of the clients is used.
 For advanced users there are header files ("eth_j60LibDef.h" and "eth_j60LibPrivate.h")
in Uses\P18 folder of the compiler with description of all routines and global variables,
relevant to the user, implemented in the Ethernet PIC18FxxJ60 Library.

Library Routines
 Ethernet_Init
 Ethernet_Enable
 Ethernet_Disable
 Ethernet_doPacket
 Ethernet_putByte
 Ethernet_putBytes
 Ethernet_putString
 Ethernet_putConstString
 Ethernet_putConstBytes
 Ethernet_getByte
 Ethernet_getBytes
 Ethernet_UserTCP
 Ethernet_UserUDP
 Ethernet_getIpAddress
 Ethernet_getGwIpAddress
 Ethernet_getDnsIpAddress
 Ethernet_getIpMask
 Ethernet_confNetwork
 Ethernet_arpResolve

www.raguvaran.puzl.com
 Ethernet_sendUDP
 Ethernet_dnsResolve
 Ethernet_initDHCP
 Ethernet_doDHCPLeaseTime
 Ethernet_renewDHCP

Ethernet_Init

Prototype void Ethernet_Init(unsigned char *mac, unsigned char *ip, unsigned


char fullDuplex);

Returns Nothing.

Description This is MAC module routine. It initializes Ethernet controller. This function is internaly
splited into 2 parts to help linker when coming short of memory.
Ethernet controller settings (parameters not mentioned here are set to default):

 receive buffer start address : 0x0000.


 receive buffer end address : 0x19AD.
 transmit buffer start address: 0x19AE.
 transmit buffer end address : 0x1FFF.
 RAM buffer read/write pointers in auto-increment mode.
 receive filters set to default: CRC + MAC Unicast + MAC Broadcast in OR
mode.
 flow control with TX and RX pause frames in full duplex mode.
 frames are padded to 60 bytes + CRC.
 maximum packet size is set to 1518.
 Back-to-Back Inter-Packet Gap: 0x15 in full duplex mode; 0x12 in half
duplex mode.
 Non-Back-to-Back Inter-Packet Gap: 0x0012 in full duplex
mode; 0x0C12 in half duplex mode.
 half duplex loopback disabled.
 LED configuration: default (LEDA-link status, LEDB-link activity).
Parameters:

 mac: RAM buffer containing valid MAC address.


 ip: RAM buffer containing valid IP address.
 fullDuplex: ethernet duplex mode switch. Valid values: 0 (half duplex
mode) and 1 (full duplex mode).

Note : If a DHCP server is to be used, IP address should be set to 0.0.0.0.

Requires Nothing.

Example #define Ethernet_HALFDUPLEX 0


#define Ethernet_FULLDUPLEX 1

unsigned char myMacAddr[6] = {0x00, 0x14, 0xA5, 0x76, 0x19, 0x3f}; // my MAC
address
unsigned char myIpAddr = {192, 168, 1, 60 }; // my IP addr

www.raguvaran.puzl.com
Ethernet_Init(myMacAddr, myIpAddr, Ethernet_FULLDUPLEX);

Ethernet_Enable

Prototype void Ethernet_Enable(unsigned char enFlt);

Returns Nothing.

Description This is MAC module routine. This routine enables appropriate network traffic on
the MCU's internal Ethernet module by the means of it's receive filters (unicast,
multicast, broadcast, crc). Specific type of network traffic will be enabled if a
corresponding bit of this routine's input parameter is set. Therefore, more than one
type of network traffic can be enabled at the same time. For this purpose, predefined
library constants (see the table below) can be ORed to form appropriate input value.
Parameters:

 enFlt: network traffic/receive filter flags. Each bit corresponds to the


appropriate network traffic/receive filter:
Predefined library
Bit Mask Description
const

MAC Broadcast traffic/receive filter flag.


0 0x01 When set, MAC broadcast traffic will be _Ethernet_BROADCAST
enabled.

MAC Multicast traffic/receive filter flag.


1 0x02 When set, MAC multicast traffic will be _Ethernet_MULTICAST
enabled.

2 0x04 not used none

3 0x08 not used none

4 0x10 not used none

CRC check flag. When set, packets with


5 0x20 _Ethernet_CRC
invalid CRC field will be discarded.

6 0x40 not used none

MAC Unicast traffic/receive filter flag.


7 0x80 When set, MAC unicast traffic will be _Ethernet_UNICAST
enabled.

Note :
 Advanced filtering available in the MCU's internal Ethernet
module such as Pattern Match, Magic Packet and Hash

www.raguvaran.puzl.com
Table can not be enabled by this routine.
Additionaly, all filters, except CRC, enabled with this routine
will work in OR mode, which means that packet will be received
if any of the enabled filters accepts it.
 This routine will change receive filter configuration on-the-
fly. It will not, in any way, mess with enabling/disabling
receive/transmit logic or any other part of the MCU's internal
Ethernet module.
The MCU's internal Ethernet module should be properly
cofigured by the means of Ethernet_Init routine.

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example Ethernet_Enable(_Ethernet_CRC | _Ethernet_UNICAST); // enable CRC checking and


Unicast traffic

Ethernet_Disable

Prototype void Ethernet_Disable(unsigned char disFlt);

Returns Nothing.

Description This is MAC module routine. This routine disables appropriate network traffic on
the MCU's internal Ethernet module by the means of it's receive filters (unicast,
multicast, broadcast, crc). Specific type of network traffic will be disabled if a
corresponding bit of this routine's input parameter is set. Therefore, more than one
type of network traffic can be disabled at the same time. For this purpose, predefined
library constants (see the table below) can be ORed to form appropriate input value.
Parameters:

 disFlt: network traffic/receive filter flags. Each bit corresponds to the


appropriate network traffic/receive filter:
Predefined library
Bit Mask Description
const

MAC Broadcast traffic/receive filter flag.


0 0x01 When set, MAC broadcast traffic will be _Ethernet_BROADCAST
disabled.

MAC Multicast traffic/receive filter flag.


1 0x02 When set, MAC multicast traffic will be _Ethernet_MULTICAST
disabled.

2 0x04 not used none

3 0x08 not used none

www.raguvaran.puzl.com
4 0x10 not used none

CRC check flag. When set, CRC check


5 0x20 will be disabled and packets with _Ethernet_CRC
invalid CRC field will be accepted.

6 0x40 not used none

MAC Unicast traffic/receive filter flag.


7 0x80 When set, MAC unicast traffic will be _Ethernet_UNICAST
disabled.

Note :
 Advance filtering available in the MCU's internal Ethernet
module such as Pattern Match, Magic Packet and Hash
Table can not be disabled by this routine.
 This routine will change receive filter configuration on-the-
fly. It will not, in any way, mess with enabling/disabling
receive/transmit logic or any other part of the MCU's internal
Ethernet module.
 The MCU's internal Ethernet module should be properly
cofigured by the means of Ethernet_Init routine.

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example Ethernet_Disable(_Ethernet_CRC | _Ethernet_UNICAST); // disable CRC checking and


Unicast traffic

Ethernet_doPacket

Prototype unsigned char Ethernet_doPacket();

Returns  0 - upon successful packet processing (zero packets received or received


packet processed successfuly).
 1 - upon reception error or receive buffer corruption. Ethernet controller
needs to be restarted.
 2 - received packet was not sent to us (not our IP, nor IP broadcast
address).
 3 - received IP packet was not IPv4.
 4 - received packet was of type unknown to the library.

Description This is MAC module routine. It processes next received packet if such exists. Packets
are processed in the following manner:
 ARP & ICMP requests are replied automatically.
 upon TCP request the Ethernet_UserTCP function is called for further
processing.
 upon UDP request the Ethernet_UserUDP function is called for further
processing.

www.raguvaran.puzl.com
Note : Ethernet_doPacket must be called as often as possible in user's code.

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example if (Ethernet_doPacket() == 0) { // process received packets


...
}

Ethernet_putByte

Prototype void Ethernet_putByte(unsigned char v);

Returns Nothing.

Description This is MAC module routine. It stores one byte to address pointed by the current
Ethernet controller's write pointer (EWRPT).
Parameters:

 v: value to store

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example char data_;


...
Ethernet_putByte(data_); // put an byte into Ethernet controller's buffer

Ethernet_putBytes

Prototype void Ethernet_putBytes(unsigned char *ptr, unsigned int n);

Returns Nothing.

Description This is MAC module routine. It stores requested number of bytes into Ethernet
controller's RAM starting from current Ethernet controller's write pointer (EWRPT)
location.
Parameters:

 ptr: RAM buffer containing bytes to be written into Ethernet


controller's RAM.
 n: number of bytes to be written.

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example char *buffer = "mikroElektronika";


...
Ethernet_putBytes(buffer, 16); // put an RAM array into Ethernet controller's

www.raguvaran.puzl.com
buffer

Ethernet_putConstBytes

Prototype void Ethernet_putConstBytes(const unsigned char *ptr, unsigned int n);

Returns Nothing.

Description This is MAC module routine. It stores requested number of const bytes into Ethernet
controller's RAM starting from current Ethernet controller's write pointer (EWRPT)
location.
Parameters:

 ptr: const buffer containing bytes to be written into Ethernet


controller's RAM.
 n: number of bytes to be written.

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example const char *buffer = "mikroElektronika";


...
Ethernet_putConstBytes(buffer, 16); // put a const array into Ethernet
controller's buffer

Ethernet_putString

Prototype unsigned int Ethernet_putString(unsigned char *ptr);

Returns Number of bytes written into Ethernet controller's RAM.

Description This is MAC module routine. It stores whole string (excluding null termination) into
Ethernet controller's RAM starting from current Ethernet controller's write pointer
(EWRPT) location.
Parameters:

 ptr: string to be written into Ethernet controller's RAM.

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example char *buffer = "mikroElektronika";


...
Ethernet_putString(buffer); // put a RAM string into Ethernet controller's buffer

www.raguvaran.puzl.com
Ethernet_putConstString

Prototype unsigned int Ethernet_putConstString(const unsigned char *ptr);

Returns Number of bytes written into Ethernet controller's RAM.

Description This is MAC module routine. It stores whole const string (excluding null termination)
into Ethernet controller's RAM starting from current Ethernet controller's write pointer
(EWRPT) location.
Parameters:

 ptr: const string to be written into Ethernet controller's RAM.

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example const char *buffer = "mikroElektronika";


...
Ethernet_putConstString(buffer); // put a const string into Ethernet controller's
buffer

Ethernet_getByte

Prototype unsigned char Ethernet_getByte();

Returns Byte read from Ethernet controller's RAM.

Description This is MAC module routine. It fetches a byte from address pointed to by current
Ethernet controller's read pointer (ERDPT).

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example char buffer;


...
buffer = Ethernet_getByte(); // read a byte from Ethernet controller's buffer

Ethernet_getBytes

Prototype void Ethernet_getBytes(unsigned char *ptr, unsigned int addr, unsigned


int n);

Returns Nothing.

Description This is MAC module routine. It fetches equested number of bytes from Ethernet
controller's RAM starting from given address. If value of 0xFFFF is passed as the
address parameter, the reading will start from current Ethernet controller's read
pointer (ERDPT) location.

www.raguvaran.puzl.com
Parameters:

 ptr: buffer for storing bytes read from Ethernet controller's RAM.
 addr: Ethernet controller's RAM start address. Valid values: 0..8192.
 n: number of bytes to be read.

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example char buffer[16];


...
Ethernet_getBytes(buffer, 0x100, 16); // read 16 bytes, starting from address
0x100

Ethernet_UserTCP

Prototype unsigned int Ethernet_UserTCP(unsigned char *remoteHost, unsigned


int remotePort, unsigned int localPort, unsigned
int reqLength, TEthPktFlags*flags);

Returns  0 - there should not be a reply to the request.


 Length of TCP/HTTP reply data field - otherwise.

Description This is TCP module routine. It is internally called by the library. The user accesses to
the TCP/HTTP request by using some of the Ethernet_get routines. The user puts data
in the transmit buffer by using some of the Ethernet_put routines. The function must
return the length in bytes of the TCP/HTTP reply, or 0 if there is nothing to transmit. If
there is no need to reply to the TCP/HTTP requests, just define this function with
return(0) as a single statement.
Parameters:

 remoteHost: client's IP address.


 remotePort: client's TCP port.
 localPort: port to which the request is sent.
 reqLength: TCP/HTTP request data field length.
 flags: structure consisted of two bit fields :
Copy Code To Clipboard

typedef struct {
unsigned canCloseTCP: 1; // flag which closes socket
unsigned isBroadcast: 1; // flag which denotes that the IP package
has been received via subnet broadcast address (not used for PIC16
family)
} TEthPktFlags;

Note : The function source code is provided with appropriate


example projects. The code should be adjusted by the user to achieve
desired reply.

Requires Ethernet module has to be initialized. See Ethernet_Init.

www.raguvaran.puzl.com
Example This function is internally called by the library and should not be called by the user's
code.

Ethernet_UserUDP

Prototype unsigned int Ethernet_UserUDP(unsigned char *remoteHost, unsigned


int remotePort, unsigned int destPort, unsigned
int reqLength, TEthPktFlags*flags);

Returns  0 - there should not be a reply to the request.


 Length of UDP reply data field - otherwise.

Description This is UDP module routine. It is internally called by the library. The user accesses to
the UDP request by using some of the Ethernet_get routines. The user puts data in the
transmit buffer by using some of the Ethernet_put routines. The function must return
the length in bytes of the UDP reply, or 0 if nothing to transmit. If you don't need to
reply to the UDP requests, just define this function with a return(0) as single
statement.
Parameters:

 remoteHost: client's IP address.


 remotePort: client's port.
 destPort: port to which the request is sent.
 flags: structure consisted of two bit fields :
Copy Code To Clipboard

typedef struct {
unsigned canCloseTCP: 1; // flag which closes TCP socket (not
relevant to UDP)
unsigned isBroadcast: 1; // flag which denotes that the IP package
has been received via subnet broadcast address (not used for PIC16
family)
} TEthPktFlags;

Note : The function source code is provided with appropriate


example projects. The code should be adjusted by the user to achieve
desired reply.

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example This function is internally called by the library and should not be called by the user's
code.

www.raguvaran.puzl.com
Ethernet_getIpAddress

Prototype unsigned char * Ethernet_getIpAddress();

Returns Pointer to the global variable holding IP address.

Description This routine should be used when DHCP server is present on the network to fetch
assigned IP address.

Note : User should always copy the IP address from the RAM location returned
by this routine into it's own IP address buffer. These locations should not be altered by
the user in any case!

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example unsigned char ipAddr[4]; // user IP address buffer


...
memcpy(ipAddr, Ethernet_getIpAddress(), 4); // fetch IP address

Ethernet_getGwIpAddress

Prototype unsigned char * Ethernet_getGwIpAddress();

Returns Pointer to the global variable holding gateway IP address.

Description This routine should be used when DHCP server is present on the network to fetch
assigned gateway IP address.

Note : User should always copy the IP address from the RAM location returned
by this routine into it's own gateway IP address buffer. These locations should not be
altered by the user in any case!

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example unsigned char gwIpAddr[4]; // user gateway IP address buffer


...
memcpy(gwIpAddr, Ethernet_getGwIpAddress(), 4); // fetch gateway IP address

Ethernet_getDnsIpAddress();

Prototype unsigned char * Ethernet_getDnsIpAddress

Returns Pointer to the global variable holding DNS IP address.

Description This routine should be used when DHCP server is present on the network to fetch
assigned DNS IP address.

Note : User should always copy the IP address from the RAM location returned
by this routine into it's own DNS IP address buffer. These locations should not be

www.raguvaran.puzl.com
altered by the user in any case!

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example unsigned char dnsIpAddr[4]; // user DNS IP address buffer


...
memcpy(dnsIpAddr, Ethernet_getDnsIpAddress(), 4); // fetch DNS server address

Ethernet_getIpMask

Prototype unsigned char * Ethernet_getIpMask()

Returns Pointer to the global variable holding IP subnet mask.

Description This routine should be used when DHCP server is present on the network to fetch
assigned IP subnet mask.

Note : User should always copy the IP address from the RAM location returned
by this routine into it's own IP subnet mask buffer. These locations should not be
altered by the user in any case!

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example unsigned char IpMask[4]; // user IP subnet mask buffer


...
memcpy(IpMask, Ethernet_getIpMask(), 4); // fetch IP subnet mask

Ethernet_confNetwork

Prototype void Ethernet_confNetwork(char *ipMask, char *gwIpAddr, char *dnsIpAddr);

Returns Nothing.

Description Configures network parameters (IP subnet mask,


gateway IP address, DNS IP address) when DHCP is not used.
Parameters:

 ipMask: IP subnet mask.


 gwIpAddr gateway IP address.
 dnsIpAddr: DNS IP address.

Note : The above mentioned network parameters should be set by this routine
only if DHCP module is not used. Otherwise DHCP will override these settings.

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example unsigned char ipMask[4] = {255, 255, 255, 0 }; // network mask (for example
: 255.255.255.0)
unsigned char gwIpAddr[4] = {192, 168, 1, 1 }; // gateway (router) IP

www.raguvaran.puzl.com
address
unsigned char dnsIpAddr[4] = {192, 168, 1, 1 }; // DNS server IP address
...
Ethernet_confNetwork(ipMask, gwIpAddr, dnsIpAddr); // set network configuration
parameters

Ethernet_arpResolve

Prototype unsigned char *Ethernet_arpResolve(unsigned char *ip, unsigned char tmax);

Returns  MAC address behind the IP address - the requested IP address was
resolved.
 0 - otherwise.

Description This is ARP module routine. It sends an ARP request for given IP address and waits
for ARP reply. If the requested IP address was resolved, an ARP cash entry is used for
storing the configuration. ARP cash can store up to 3 entries. For ARP cash structure
refer to "eth_j60LibDef.h" header file in the compiler's Uses/P18 folder.
Parameters:

 ip: IP address to be resolved.


 tmax: time in seconds to wait for an reply.

Note : The Ethernet services are not stopped while this routine waits
for ARP reply. The incoming packets will be processed normaly during this time.

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example unsigned char IpAddr[4] = {192, 168, 1, 1 }; // IP address


...
Ethernet_arpResolve(IpAddr, 5); // get MAC address behind the above IP address,
wait 5 secs for the response

Ethernet_sendUDP

Prototype unsigned char Ethernet_sendUDP(unsigned char *destIP, unsigned


int sourcePort, unsigned int destPort, unsigned char *pkt, unsigned
int pktLen);

Returns  1 - UDP packet was sent successfuly.


 0 - otherwise.

Description This is UDP module routine. It sends an UDP packet on the network.
Parameters:

 destIP: remote host IP address.


 sourcePort: local UDP source port number.
 destPort: destination UDP port number.

www.raguvaran.puzl.com
 pkt: packet to transmit.
 pktLen: length in bytes of packet to transmit.

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example unsigned char IpAddr[4] = {192, 168, 1, 1 }; // remote IP address


...
Ethernet_sendUDP(IpAddr, 10001, 10001, "Hello", 5); // send Hello message to the
above IP address, from UDP port 10001 to UDP port 10001

Ethernet_dnsResolve

Prototype unsigned char *Ethernet_dnsResolve(unsigned char *host, unsigned


char tmax);

Returns  pointer to the location holding the IP address - the requested host name
was resolved.
 0 - otherwise.

Description This is DNS module routine. It sends an DNS request for given host name and waits
for DNS reply. If the requested host name was resolved, it's IP address is stored in
library global variable and a pointer containing this address is returned by the
routine. UDP port 53 is used as DNS port.
Parameters:

 host: host name to be resolved.


 tmax: time in seconds to wait for an reply.
The above mentioned network parameters should be set by this routine only
if DHCP module is not used. Otherwise DHCP will override these settings.

Note :
 The Ethernet services are not stopped while this routine waits
for DNS reply. The incoming packets will be processed normaly during this
time.
 User should always copy the IP address from the RAM location returned
by this routine into it's own resolved host IP address buffer. These
locations should not be altered by the user in any case!

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example unsigned char * remoteHostIpAddr[4]; // user host IP address buffer


...
// SNTP server:
// Zurich, Switzerland: Integrated Systems Lab, Swiss Fed. Inst. of Technology
// 129.132.2.21: swisstime.ethz.ch
// Service Area: Switzerland and Europe
memcpy(remoteHostIpAddr, Ethernet_dnsResolve("swisstime.ethz.ch", 5), 4);

www.raguvaran.puzl.com
Ethernet_initDHCP

Prototype unsigned char Ethernet_initDHCP(unsigned char tmax);

Returns  1 - network parameters were obtained successfuly.


 0 - otherwise.

Description This is DHCP module routine. It sends an DHCP request for network parameters (IP,
gateway, DNS addresses and IP subnet mask) and waits for DHCP reply. If the
requested parameters were obtained successfuly, their values are stored into the
library global variables.
These parameters can be fetched by using appropriate library IP get routines:
 Ethernet_getIpAddress - fetch IP address.
 Ethernet_getGwIpAddress - fetch gateway IP address.
 Ethernet_getDnsIpAddress - fetch DNS IP address.
 Ethernet_getIpMask - fetch IP subnet mask.
UDP port 68 is used as DHCP client port and UDP port 67 is used as DHCP server port.
Parameters:

 tmax: time in seconds to wait for an reply.

Note :
 The Ethernet services are not stopped while this routine waits
for DNS reply. The incoming packets will be processed normaly during this
time.
 When DHCP module is used, global library
variable Ethernet_userTimerSec is used to keep track of time. It is user
responsibility to increment this variable each second in it's code.

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example ...
Ethernet_initDHCP(5); // get network configuration from DHCP server, wait 5 sec
for the response
...

Ethernet_doDHCPLeaseTime

Prototype unsigned char Ethernet_doDHCPLeaseTime();

Returns  0 - lease time has not expired yet.


 1 - lease time has expired, it's time to renew it.

Description This is DHCP module routine. It takes care of IP address lease time by decrementing
the global lease time library counter. When this time expires, it's time to
contact DHCPserver and renew the lease.

Requires Ethernet module has to be initialized. See Ethernet_Init.

www.raguvaran.puzl.com
Example while(1) {
...
if(Ethernet_doDHCPLeaseTime())
... // it's time to renew the IP address lease
}

Ethernet_renewDHCP

Prototype unsigned char Ethernet_renewDHCP(unsigned char tmax);

Returns  1 - upon success (lease time was renewed).


 0 - otherwise (renewal request timed out).

Description This is DHCP module routine. It sends IP address lease time renewal request
to DHCP server.
Parameters:

 tmax: time in seconds to wait for an reply.

Requires Ethernet module has to be initialized. See Ethernet_Init.

Example while(1) {
...
if(Ethernet_doDHCPLeaseTime())
Ethernet_renewDHCP(5); // it's time to renew the IP address lease, with 5
secs for a reply
...
}

Library Example
This code shows how to use the PIC18FxxJ60 Ethernet library :

 the board will reply to ARP & ICMP echo requests


 the board will reply to UDP requests on any port :
 returns the request in upper char with a header made of remote host IP & port
number
 the board will reply to HTTP requests on port 80, GET method with pathnames :
 / will return the HTML main page
 /s will return board status as text string
 /t0 ... /t7 will toggle RD0 to RD7 bit and return HTML main page
 all other requests return also HTML main page.
Copy Code To Clipboard

#include "__EthJ60.h"

#define Ethernet_HALFDUPLEX 0

#define Ethernet_FULLDUPLEX 1

www.raguvaran.puzl.com
/************************************************************
* ROM constant strings
*/
const unsigned char httpHeader[] = "HTTP/1.1 200 OKnContent-type: " ; // HTTP header
const unsigned char httpMimeTypeHTML[] = "text/htmlnn" ; // HTML MIME type
const unsigned char httpMimeTypeScript[] = "text/plainnn" ; // TEXT MIME type
unsigned char httpMethod[] = "GET /";
/*
* web page, splited into 2 parts :
* when coming short of ROM, fragmented data is handled more efficiently by linker
*
* this HTML page calls the boards to get its status, and builds itself with javascript
*/
const char *indexPage = // Change the IP address of the page to be refreshed
"<meta http-equiv="refresh" content="3;url=http://192.168.20.60">
<HTML><HEAD></HEAD><BODY>
<h1>PIC18FxxJ60 Mini Web Server</h1>
<a href=/>Reload</a>
<script src=/https/www.scribd.com/s></script>
<table><tr><td valign=top><table border=1 style="font-size:20px ;font-family: terminal ;">
<tr><th colspan=2>ADC</th></tr>
<tr><td>AN2</td><td><script>document.write(AN2)</script></td></tr>
<tr><td>AN3</td><td><script>document.write(AN3)</script></td></tr>
</table></td><td><table border=1 style="font-size:20px ;font-family: terminal ;">
<tr><th colspan=2>PORTB</th></tr>
<script>
var str,i;
str="";
for(i=0;i<8;i++)
{str+="<tr><td bgcolor=pink>BUTTON #"+i+"</td>";
if(PORTB&(1<<i)){str+="<td bgcolor=red>ON";}
else {str+="<td bgcolor=#cccccc>OFF";}
str+="</td></tr>";}
document.write(str) ;
</script>
" ;

const char *indexPage2 = "</table></td><td>


<table border=1 style="font-size:20px ;font-family: terminal ;">
<tr><th colspan=3>PORTD</th></tr>
<script>
var str,i;
str="";
for(i=0;i<3;i++)
{str+="<tr><td bgcolor=yellow>LED #"+i+"</td>";
if(PORTD&(1<<i)){str+="<td bgcolor=red>ON";}
else {str+="<td bgcolor=#cccccc>OFF";}
str+="</td><td><a href=/https/www.scribd.com/t"+i+">Toggle</a></td></tr>";}
document.write(str) ;
</script>
</table></td></tr></table>
This is HTTP request #<script>document.write(REQ)</script></BODY></HTML>
" ;

/***********************************
* RAM variables
*/
unsigned char myMacAddr[6] = {0x00, 0x14, 0xA5, 0x76, 0x19, 0x3f} ; // my MAC address
unsigned char myIpAddr[4] = {192, 168, 20, 60 } ; // my IP address
unsigned char gwIpAddr[4] = {192, 168, 20, 6 } ; // gateway (router) IP
address
unsigned char ipMask[4] = {255, 255, 255, 0 } ; // network mask (for
example : 255.255.255.0)
unsigned char dnsIpAddr[4] = {192, 168, 20, 1 } ; // DNS server IP address

www.raguvaran.puzl.com
unsigned char getRequest[15] ; // HTTP request buffer
unsigned char dyna[30] ; // buffer for dynamic
response
unsigned long httpCounter = 0 ; // counter of HTTP
requests

/*******************************************
* functions
*/

/*
* put the constant string pointed to by s to the Ethernet controller's transmit buffer.
*/
/*unsigned int putConstString(const char *s)
{
unsigned int ctr = 0 ;

while(*s)
{
Ethernet_putByte(*s++) ;
ctr++ ;
}
return(ctr) ;
}*/
/*
* it will be much faster to use library Ethernet_putConstString routine
* instead of putConstString routine above. However, the code will be a little
* bit bigger. User should choose between size and speed and pick the implementation that
* suites him best. If you choose to go with the putConstString definition above
* the #define line below should be commented out.
*
*/
#define putConstString Ethernet_putConstString

/*
* put the string pointed to by s to the Ethernet controller's transmit buffer
*/
/*unsigned int putString(char *s)
{
unsigned int ctr = 0 ;

while(*s)
{
Ethernet_putByte(*s++) ;

ctr++ ;
}
return(ctr) ;
}*/
/*
* it will be much faster to use library Ethernet_putString routine
* instead of putString routine above. However, the code will be a little
* bit bigger. User should choose between size and speed and pick the implementation that
* suites him best. If you choose to go with the putString definition above
* the #define line below should be commented out.
*
*/
#define putString Ethernet_putString

/*
* this function is called by the library
* the user accesses to the HTTP request by successive calls to Ethernet_getByte()
* the user puts data in the transmit buffer by successive calls to Ethernet_putByte()
* the function must return the length in bytes of the HTTP reply, or 0 if nothing to transmit
*
* if you don't need to reply to HTTP requests,

www.raguvaran.puzl.com
* just define this function with a return(0) as single statement
*
*/
unsigned int Ethernet_UserTCP(unsigned char *remoteHost, unsigned int remotePort, unsigned int
localPort, unsigned int reqLength, TEthPktFlags *flags)
{
unsigned int len = 0 ; // my reply length
unsigned char i ; // general purpose char

// should we close tcp socket after response is sent?


// library closes tcp socket by default if canClose flag is not reset here
// flags->canCloseTCP = 0; // 0 - do not close socket
// otherwise - close socket

if(localPort != 80) // I listen only to web request on port 80


{
return(0) ;
}

// get 10 first bytes only of the request, the rest does not matter here
for(i = 0 ; i < 10 ; i++)
{
getRequest[i] = Ethernet_getByte() ;
}
getRequest[10] = 0 ;

if(memcmp(getRequest, httpMethod, 5)) // only GET method is supported here


{
return(0) ;
}

httpCounter++ ; // one more request done

if(getRequest[5] == 's') // if request path name starts with s, store


dynamic data in transmit buffer
{
// the text string replied by this request can be interpreted as javascript
statements
// by browsers

len = putConstString(httpHeader) ; // HTTP header


len += putConstString(httpMimeTypeScript) ; // with text MIME type

// add AN2 value to reply


IntToStr(ADC_Read(2), dyna) ;
len += putConstString("var AN2=") ;
len += putString(dyna) ;
len += putConstString(";") ;

// add AN3 value to reply


IntToStr(ADC_Read(3), dyna) ;
len += putConstString("var AN3=") ;
len += putString(dyna) ;
len += putConstString(";") ;

// add PORTB value (buttons) to reply


len += putConstString("var PORTB=") ;
IntToStr(PORTB, dyna) ;
len += putString(dyna) ;
len += putConstString(";") ;

// add PORTD value (LEDs) to reply


len += putConstString("var PORTD=") ;
IntToStr(PORTD, dyna) ;
len += putString(dyna) ;
len += putConstString(";") ;

www.raguvaran.puzl.com
// add HTTP requests counter to reply
IntToStr(httpCounter, dyna) ;
len += putConstString("var REQ=") ;
len += putString(dyna) ;
len += putConstString(";") ;
}
else if(getRequest[5] == 't') // if request path name starts
with t, toggle PORTD (LED) bit number that comes after
{
unsigned char bitMask = 0 ; // for bit mask

if(isdigit(getRequest[6])) // if 0 <= bit number <= 9, bits 8


& 9 does not exist but does not matter
{
bitMask = getRequest[6] - '0' ; // convert ASCII to integer
bitMask = 1 << bitMask ; // create bit mask
PORTD ^= bitMask ; // toggle PORTD with xor operator
}
}

if(len == 0) // what do to by default


{
len = putConstString(httpHeader) ; // HTTP header
len += putConstString(httpMimeTypeHTML) ; // with HTML MIME type
len += putConstString(indexPage) ; // HTML page first part
len += putConstString(indexPage2) ; // HTML page second part
}

return(len) ; // return to the library with the


number of bytes to transmit
}

/*
* this function is called by the library
* the user accesses to the UDP request by successive calls to Ethernet_getByte()
* the user puts data in the transmit buffer by successive calls to Ethernet_putByte()
* the function must return the length in bytes of the UDP reply, or 0 if nothing to transmit
*
* if you don't need to reply to UDP requests,
* just define this function with a return(0) as single statement
*
*/
unsigned int Ethernet_UserUDP(unsigned char *remoteHost, unsigned int remotePort, unsigned int
destPort, unsigned int reqLength, TEthPktFlags *flags)
{
unsigned int len ; // my reply length

// reply is made of the remote host IP address in human readable format


ByteToStr(remoteHost[0], dyna) ; // first IP address byte
dyna[3] = '.' ;
ByteToStr(remoteHost[1], dyna + 4) ; // second
dyna[7] = '.' ;
ByteToStr(remoteHost[2], dyna + 8) ; // third
dyna[11] = '.' ;
ByteToStr(remoteHost[3], dyna + 12) ; // fourth

dyna[15] = ':' ; // add separator

// then remote host port number


WordToStr(remotePort, dyna + 16) ;
dyna[21] = '[' ;
WordToStr(destPort, dyna + 22) ;
dyna[27] = ']' ;
dyna[28] = 0 ;

// the total length of the request is the length of the dynamic string plus the text of
the request

www.raguvaran.puzl.com
len = 28 + reqLength;

// puts the dynamic string into the transmit buffer


Ethernet_putBytes(dyna, 28) ;

// then puts the request string converted into upper char into the transmit buffer
while(reqLength--)
{
Ethernet_putByte(toupper(Ethernet_getByte())) ;
}

return(len) ; // back to the library with the length of the UDP reply
}

/*
* main entry
*/
void main()
{
ADCON1 = 0x0B ; // ADC convertors will be used with AN2 and AN3
CMCON = 0x07 ; // turn off comparators

PORTA = 0 ;
TRISA = 0xfc ; // set PORTA as input for ADC
// except RA0 and RA1 which will be used as
// ethernet's LEDA and LEDB

PORTB = 0 ;
TRISB = 0xff ; // set PORTB as input for buttons

PORTD = 0 ;
TRISD = 0 ; // set PORTD as output

/*
* Initialize Ethernet controller
*/
Ethernet_Init(myMacAddr, myIpAddr, Ethernet_FULLDUPLEX) ;

// dhcp will not be used here, so use preconfigured addresses


Ethernet_confNetwork(ipMask, gwIpAddr, dnsIpAddr) ;

while(1) // do forever
{
/*
* if necessary, test the return value to get error code
*/
Ethernet_doPacket() ; // process incoming Ethernet packets

/*
* add your stuff here if needed
* Ethernet_doPacket() must be called as often as possible
* otherwise packets could be lost
*/
}
}

Flash Memory Library

www.raguvaran.puzl.com
This library provides routines for accessing microcontroller Flash memory. Note that prototypes differ for
PIC16 and PIC18 families.

Important : Due to the P16/P18 family flash specifics, flash library is MCU dependent. Since the
P18 family differ significantlly in number of bytes that can be erased and/or written to specific MCUs, the
appropirate suffix is added to the names of functions in order to make it easier to use them.

Flash memory operations are MCU dependent :

1. Read operation supported. For this group of MCU's only read function is implemented.
2. Read and Write operations supported (write is executed as erase-and-write). For this
group of MCU's read and write functions are implemented. Note that write operation which is
executed as erase-and-write, may write less bytes than it erases.
3. Read, Write and Erase operations supported. For this group of MCU's read, write and
erase functions are implemented. Further more, flash memory block has to be erased prior
to writting (write operation is not executed as erase-and-write).

Please refer to MCU datasheet before using flash library.

Library Routines
 FLASH_Read
 FLASH_Read_N_Bytes
 FLASH_Write
 FLASH_Write_8
 FLASH_Write_16
 FLASH_Write_32
 FLASH_Write_64
 FLASH_Erase
 FLASH_Erase_64
 FLASH_Erase_1024
 FLASH_Erase_Write
 FLASH_Erase_Write_64
 FLASH_Erase_Write_1024

FLASH_Read

Prototype // for PIC16


unsigned FLASH_Read(unsigned address);
// for PIC18
unsigned short FLASH_Read(long address);

Returns Returns data byte from Flash memory.

Description Reads data from the specified address in Flash memory.

Requires Nothing.

Example // for PIC18


unsigned short tmp;
...
tmp = FLASH_Read(0x0D00);

www.raguvaran.puzl.com
...

FLASH_Read_N_Bytes

Prototype void FLASH_Read_N_Bytes(long address, char* data_, unsigned int N);

Returns Nothing.

Description Reads N data from the specified address in Flash memory to varibale pointed by data

Requires Nothing.

Example FLASH_Read_N(0x0D00,data_buffer,sizeof(data_buffer));

FLASH_Write

Prototype // for PIC16


void FLASH_Write(unsigned address, unsigned int* data);
// for PIC18
void FLASH_Write_8(long address, char* data);
void FLASH_Write_16(long address, char* data);
void FLASH_Write_32(long address, char* data);
void FLASH_Write_64(long address, char* data);

Returns Nothing.

Description Writes block of data to Flash memory. Block size is MCU dependent.

P16: This function may erase memory segment before writing block of data to it (MCU
dependent). Furthermore, memory segment which will be erased may be greater than
the size of the data block that will be written (MCU dependent). Therefore it is
recommended to write as many bytes as you erase. FLASH_Write writes 4 flash
memory locations in a row, so it needs to be called as many times as it is necessary to
meet the size of the data block that will be written.
P18: This function does not perform erase prior to write.

Requires Flash memory that will be written may have to be erased before this function is called
(MCU dependent). Refer to MCU datasheet for details.

Example Write consecutive values in 64 consecutive locations, starting from 0x0D00:

unsigned short toWrite[64];


...
// initialize array:
for (i = 0; i < 64; i++)
toWrite[i] = i;

www.raguvaran.puzl.com
// write contents of the array to the address 0x0D00:
FLASH_Write_64(0x0D00, toWrite);

FLASH_Erase

Prototype // for PIC16


void FLASH_Erase(unsigned address);
// for PIC18
void FLASH_Erase_64(long address);
void FLASH_Erase_1024(long address);

Returns Nothing.

Description Erases memory block starting from a given address. For P16 familly is implemented
only for those MCU's whose flash memory does not support erase-and-write operations
(refer to datasheet for details).

Requires Nothing.

Example Erase 64 byte memory memory block, starting from address 0x0D00:

FLASH_Erase_64(0x0D00);

FLASH_Erase_Write

Prototype // for PIC18


void FLASH_Erase_Write_64(long address, char* data);
void FLASH_Erase_Write_1024(long address, char* data);

Returns None.

Description Erase then write memory block starting from a given address.

Requires Nothing.

Example char toWrite[64];


int i;
...
// initialize array:
for(i=0; i<64; i++) toWrite[i]=i;

// erase block of memory at address 0x0D00 then write contents of the array to
the address 0x0D00:
FLASH_Erase_Write_64(0x0D00, toWrite);

www.raguvaran.puzl.com
Library Example
The example demonstrates simple write to the flash memory for PIC16F887, then reads the data and
displays it on PORTB and PORTC.

Copy Code To Clipboard

char i = 0;
unsigned int addr, data_, dataAR[4][4] = {{0x3FAA+0, 0x3FAA+1, 0x3FAA+2, 0x3FAA+3},
{0x3FAA+4, 0x3FAA+5, 0x3FAA+6, 0x3FAA+7},
{0x3FAA+8, 0x3FAA+9, 0x3FAA+10, 0x3FAA+11},
{0x3FAA+12, 0x3FAA+13, 0x3FAA+14, 0x3FAA+15}};

void main() {
ANSEL = 0; // Configure AN pins as digital
ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;
PORTB = 0; // Initial PORTB value
TRISB = 0; // Set PORTB as output
PORTC = 0; // Initial PORTC value
TRISC = 0; // Set PORTC as output
Delay_ms(500);

// All block writes


// to program memory are done as 16-word erase by
// eight-word write operations. The write operation is
// edge-aligned and cannot occur across boundaries.
// Therefore it is recommended to perform flash writes in 16-word chunks.
// That is why lower 4 bits of start address [3:0] must be zero.
// Since FLASH_Write routine performs writes in 4-word chunks,
// we need to call it 4 times in a row.
addr = 0x0430; // starting Flash address, valid for P16F887
for (i = 0; i < 4; i++){ // Write some data to Flash
Delay_ms(100);
FLASH_Write(addr+i*4, dataAR[i]);
}
Delay_ms(500);

addr = 0x0430;
for (i = 0; i < 16; i++){
data_ = FLASH_Read(addr++); // P16's FLASH is 14-bit wide, so
Delay_us(10); // two MSB's will always be '00'
PORTB = data_; // Display data on PORTB (LS Byte)
PORTC = data_ >> 8; // and PORTC (MS Byte)
Delay_ms(500);
}
}

Graphic Lcd Library


The mikroC PRO for PIC provides a library for operating Graphic Lcd 128x64 (with commonly used
Samsung KS108/KS107 controller).

For creating a custom set of Glcd images use Glcd Bitmap Editor Tool.

Important : PIC16 family of MCUs does not support working with external resources.

Library Dependency Tree

www.raguvaran.puzl.com
External dependencies of Graphic Lcd Library
The following variables must
Description
be defined in all projects Example :
:
using Graphic Lcd Library:
extern sfr Glcd Data char GLCD_DataPort at PORTD;
char GLCD_DataPort; Port.
extern sfr Chip Select sbit GLCD_CS1 at RB0_bit;
sbit GLCD_CS1; 1 line.
extern sfr Chip Select sbit GLCD_CS2 at RB1_bit;
sbit GLCD_CS2; 2 line.

extern sfr sbit GLCD_RS;


Register sbit GLCD_RS at RB2_bit;
select line.

extern sfr sbit GLCD_RW;


Read/Write sbit GLCD_RW at RB3_bit;
line.
extern sfr sbit GLCD_EN; Enable line. sbit GLCD_EN at RB4_bit;

extern sfr
Reset line. sbit GLCD_RST at RB5_bit;
sbit GLCD_RST;

Direction of
extern sfr the Chip sbit GLCD_CS1_Direction at TRISB0_bit;
sbit GLCD_CS1_Direction; Select 1
pin.
Direction of
extern sfr the Chip sbit GLCD_CS2_Direction at TRISB1_bit;
sbit GLCD_CS2_Direction; Select 2
pin.
Direction of
extern sfr
the Register sbit GLCD_RS_Direction at TRISB2_bit;
sbit GLCD_RS_Direction;
select pin.
Direction of
extern sfr the sbit GLCD_RW_Direction at TRISB3_bit;
sbit GLCD_RW_Direction; Read/Write
pin.
Direction of
extern sfr
the Enable sbit GLCD_EN_Direction at TRISB4_bit;
sbit GLCD_EN_Direction;
pin.
Direction of
extern sfr
the Reset sbit GLCD_RST_Direction at TRISB5_bit;
sbit GLCD_RST_Direction;
pin.

Library Routines
Basic routines:

 Glcd_Init
 Glcd_Set_Side
 Glcd_Set_X

www.raguvaran.puzl.com
 Glcd_Set_Page
 Glcd_Read_Data
 Glcd_Write_Data
 Glcd_Set_Ext_Buffer

Advanced routines:

 Glcd_Fill
 Glcd_Dot
 Glcd_Line
 Glcd_V_Line
 Glcd_H_Line
 Glcd_Rectangle
 Glcd_Rectangle_Round_Edges
 Glcd_Rectangle_Round_Edges_Fill
 Glcd_Box
 Glcd_Circle
 Glcd_Circle_Fill
 Glcd_Set_Font
 Glcd_Set_Font_Adv
 Glcd_Set_Ext_Font_Adv
 Glcd_Write_Char
 Glcd_Write_Char_Adv
 Glcd_Write_Text
 Glcd_Write_Text_Adv
 Glcd_Write_Const_Text_Adv
 Glcd_Image
 Glcd_Ext_Image
 Glcd_PartialImage
 Glcd_Ext_PartialImage

Glcd_Init

Prototype void Glcd_Init();

Returns Nothing.

Description Initializes the Glcd module. Each of the control lines is both port and pin configurable, while data lines must be
on a single port (pins <0:7>).

Requires Global variables :

 GLCD_CS1 : Chip select 1 signal pin


 GLCD_CS2 : Chip select 2 signal pin
 GLCD_RS : Register select signal pin
 GLCD_RW : Read/Write Signal pin
 GLCD_EN : Enable signal pin
 GLCD_RST : Reset signal pin
 GLCD_DataPort : Data port

 GLCD_CS1_Direction : Direction of the Chip select 1 pin


 GLCD_CS2_Direction : Direction of the Chip select 2 pin
 GLCD_RS_Direction : Direction of the Register select signal pin

www.raguvaran.puzl.com
 GLCD_RW_Direction : Direction of the Read/Write signal pin
 GLCD_EN_Direction : Direction of the Enable signal pin
 GLCD_RST_Direction : Direction of the Reset signal pin
must be defined before using this function.

Example // glcd pinout settings


char GLCD_DataPort at PORTD;

sbit GLCD_CS1 at RB0_bit;


sbit GLCD_CS2 at RB1_bit;
sbit GLCD_RS at RB2_bit;
sbit GLCD_RW at RB3_bit;
sbit GLCD_EN at RB4_bit;
sbit GLCD_RST at RB5_bit;

sbit GLCD_CS1_Direction at TRISB0_bit;


sbit GLCD_CS2_Direction at TRISB1_bit;
sbit GLCD_RS_Direction at TRISB2_bit;
sbit GLCD_RW_Direction at TRISB3_bit;
sbit GLCD_EN_Direction at TRISB4_bit;
sbit GLCD_RST_Direction at TRISB5_bit;
...
ANSEL = 0;
ANSELH = 0;
Glcd_Init();

Glcd_Set_Side

Prototype void Glcd_Set_Side(unsigned short x_pos);

Returns Nothing.

Description Selects Glcd side. Refer to the Glcd datasheet for detailed explanation.

Parameters :

 x_pos: position on x-axis. Valid values: 0..127


The parameter x_pos specifies the Glcd side: values from 0 to 63 specify the left side, values from 64 to 127
specify the right side.

Note : For side, x axis and page layout explanation see schematic at the bottom of this page.

Requires Glcd needs to be initialized, see Glcd_Init routine.

Example The following two lines are equivalent, and both of them select the left side of Glcd:

Glcd_Select_Side(0);
Glcd_Select_Side(10);

Glcd_Set_X

Prototype void Glcd_Set_X(unsigned short x_pos);

www.raguvaran.puzl.com
Returns Nothing.

Description Sets x-axis position to x_pos dots from the left border of Glcd within the selected side.
Parameters :

 x_pos: position on x-axis. Valid values: 0..63

Note : For side, x axis and page layout explanation see schematic at the bottom of this page.

Requires Glcd needs to be initialized, see Glcd_Init routine.

Example Glcd_Set_X(25);

Glcd_Set_Page

Prototype void Glcd_Set_Page(unsigned short page);

Returns Nothing.

Description Selects page of the Glcd.

Parameters :

 page: page number. Valid values: 0..7

Note : For side, x axis and page layout explanation see schematic at the bottom of this page.

Requires Glcd needs to be initialized, see Glcd_Init routine.

Example Glcd_Set_Page(5);

Glcd_Read_Data

Prototype unsigned short Glcd_Read_Data();

Returns One byte from Glcd memory.

Description Reads data from from the current location of Glcd memory and moves to the next location.

Requires Glcd needs to be initialized, see Glcd_Init routine.


Glcd side, x-axis position and page should be set first. See functions Glcd_Set_Side, Glcd_Set_X,
and Glcd_Set_Page.

Example unsigned short data;


...
data = Glcd_Read_Data();

www.raguvaran.puzl.com
Glcd_Write_Data

Prototype void Glcd_Write_Data(unsigned short ddata);

Returns Nothing.

Description Writes one byte to the current location in Glcd memory and moves to the next location.

Parameters :

 ddata: data to be written

Requires Glcd needs to be initialized, see Glcd_Init routine.


Glcd side, x-axis position and page should be set first. See functions Glcd_Set_Side, Glcd_Set_X,
and Glcd_Set_Page.

Example unsigned short data_;


...
Glcd_Write_Data(data_);

Glcd_Set_Ext_Buffer

Prototype void Glcd_Set_Ext_Buffer(char* (*getExtDataPtr)(unsigned


long offset, unsigned int count, unsigned int *num));

Returns Nothing.

Description Function sets pointer to the user function which manipulates the external resource.

Parameters :

 offset - offset from the beginning of the resource from where the data is requested.
 count - requested number of bytes.
 num - variable for holding the returned number ob byte (less or equal to the number of acqired
bytes).

Requires Glcd module needs to be initialized. See the Glcd_Init routine.

Example char* ReadExternalBuffer(unsigned long offset, unsigned int count, unsigned int
*num){
unsigned long start_sector;
unsigned int pos;

start_sector = Mmc_Get_File_Write_Sector() + offset/512;


pos = (unsigned long)offset%512;

if(start_sector == currentSector+1){
Mmc_Multi_Read_Buffer(EXT_BUFFER);
currentSector = start_sector;
}else
if(start_sector != currentSector){
Mmc_Multi_Read_Stop();
Mmc_Multi_Read_Start(start_sector);

www.raguvaran.puzl.com
Mmc_Multi_Read_Buffer(EXT_BUFFER);
currentSector = start_sector;
}

if(count>512-pos){
*num = 512-pos;
}
else
*num = count;

return EXT_BUFFER+pos;
}

Glcd_Set_Ext_Buffer(ReadExternalBuffer);

Glcd_Fill

Prototype void Glcd_Fill(unsigned short pattern);

Returns Nothing.

Description Fills Glcd memory with the byte pattern.


Parameters :

 pattern: byte to fill Glcd memory with


To clear the Glcd screen, use Glcd_Fill(0).
To fill the screen completely, use Glcd_Fill(0xFF).

Requires Glcd needs to be initialized, see Glcd_Init routine.

Example // Clear screen


Glcd_Fill(0);

Glcd_Dot

Prototype void Glcd_Dot(unsigned short x_pos, unsigned short y_pos, unsigned


short color);

Returns Nothing.

Description Draws a dot on Glcd at coordinates (x_pos, y_pos).


Parameters :

 x_pos: x position. Valid values: 0..127


 y_pos: y position. Valid values: 0..63
 color: color parameter. Valid values: 0..2
The parameter color determines a dot state: 0 clears dot, 1 puts a dot, and 2 inverts dot state.

Note : For x and y axis layout explanation see schematic at the bottom of this page.

Requires Glcd needs to be initialized, see Glcd_Init routine.

www.raguvaran.puzl.com
Example // Invert the dot in the upper left corner
Glcd_Dot(0, 0, 2);

Glcd_Line

Prototype void Glcd_Line(int x_start, int y_start, int x_end, int y_end, unsigned
short color);

Returns Nothing.

Description Draws a line on Glcd.

Parameters :

 x_start: x coordinate of the line start. Valid values: 0..127


 y_start: y coordinate of the line start. Valid values: 0..63
 x_end: x coordinate of the line end. Valid values: 0..127
 y_end: y coordinate of the line end. Valid values: 0..63
 color: color parameter. Valid values: 0..2
The parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot.

Requires Glcd needs to be initialized, see Glcd_Init routine.

Example // Draw a line between dots (0,0) and (20,30)


Glcd_Line(0, 0, 20, 30, 1);

Glcd_V_Line

Prototype void Glcd_V_Line(unsigned short y_start, unsigned short y_end, unsigned


short x_pos, unsigned short color);

Returns Nothing.

Description Draws a vertical line on Glcd.

Parameters :

 y_start: y coordinate of the line start. Valid values: 0..63


 y_end: y coordinate of the line end. Valid values: 0..63
 x_pos: x coordinate of vertical line. Valid values: 0..127
 color: color parameter. Valid values: 0..2
The parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot.

Requires Glcd needs to be initialized, see Glcd_Init routine.

Example // Draw a vertical line between dots (10,5) and (10,25)


Glcd_V_Line(5, 25, 10, 1);

Glcd_H_Line

www.raguvaran.puzl.com
Prototype void Glcd_H_Line(unsigned short x_start, unsigned short x_end, unsigned
short y_pos, unsigned short color);

Returns Nothing.

Description Draws a horizontal line on Glcd.

Parameters :

 x_start: x coordinate of the line start. Valid values: 0..127


 x_end: x coordinate of the line end. Valid values: 0..127
 y_pos: y coordinate of horizontal line. Valid values: 0..63
 color: color parameter. Valid values: 0..2
The parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot.

Requires Glcd needs to be initialized, see Glcd_Init routine.

Example // Draw a horizontal line between dots (10,20) and (50,20)


Glcd_H_Line(10, 50, 20, 1);

Glcd_Rectangle

Prototype void Glcd_Rectangle(unsigned short x_upper_left, unsigned


short y_upper_left, unsigned short x_bottom_right, unsigned
short y_bottom_right,unsigned short color);

Returns Nothing.

Description Draws a rectangle on Glcd.

Parameters :

 x_upper_left: x coordinate of the upper left rectangle corner. Valid values: 0..127
 y_upper_left: y coordinate of the upper left rectangle corner. Valid values: 0..63
 x_bottom_right: x coordinate of the lower right rectangle corner. Valid values: 0..127
 y_bottom_right: y coordinate of the lower right rectangle corner. Valid values: 0..63
 color: color parameter. Valid values: 0..2
The parameter color determines the color of the rectangle border: 0 white, 1 black, and 2 inverts each dot.

Requires Glcd needs to be initialized, see Glcd_Init routine.

Example // Draw a rectangle between dots (5,5) and (40,40)


Glcd_Rectangle(5, 5, 40, 40, 1);

Glcd_Rectangle_Round_Edges

Prototype void Glcd_Rectangle_Round_Edges(unsigned short x_upper_left, unsigned


short y_upper_left, unsigned short x_bottom_right, unsigned
shorty_bottom_right, unsigned short round_radius, unsigned short color);

www.raguvaran.puzl.com
Returns Nothing.

Description Draws a rounded edge rectangle on Glcd.

Parameters :

 x_upper_left: x coordinate of the upper left rectangle corner. Valid values: 0..127
 y_upper_left: y coordinate of the upper left rectangle corner. Valid values: 0..63
 x_bottom_right: x coordinate of the lower right rectangle corner. Valid values: 0..127
 y_bottom_right: y coordinate of the lower right rectangle corner. Valid values: 0..63
 round_radius: radius of the rounded edge.
 color: color parameter. Valid values: 0..2
The parameter color determines the color of the rectangle border: 0 white, 1 black, and 2 inverts each dot.

Requires Glcd needs to be initialized, see Glcd_Init routine.

Example // Draw a rounded edge rectangle between dots (5,5) and (40,40) with the radius of
12
Glcd_Rectangle_Round_Edges(5, 5, 40, 40, 12, 1);

Glcd_Rectangle_Round_Edges_Fill

Prototype void Glcd_Rectangle_Round_Edges_Fill(unsigned short x_upper_left, unsigned


short y_upper_left, unsigned short x_bottom_right, unsigned
shorty_bottom_right, unsigned short round_radius, unsigned short color);

Returns Nothing.

Description Draws a filled rounded edge rectangle on Glcd with color.

Parameters :

 x_upper_left: x coordinate of the upper left rectangle corner. Valid values: 0..127
 y_upper_left: y coordinate of the upper left rectangle corner. Valid values: 0..63
 x_bottom_right: x coordinate of the lower right rectangle corner. Valid values: 0..127
 y_bottom_right: y coordinate of the lower right rectangle corner. Valid values: 0..63
 round_radius: radius of the rounded edge
 color: color parameter. Valid values: 0..2
The parameter color determines the color of the rectangle border: 0 white, 1 black, and 2 inverts each dot.

Requires Glcd needs to be initialized, see Glcd_Init routine.

Example // Draws a filled rounded edge rectangle between dots (5,5) and (40,40) with the
radius of 12
Glcd_Rectangle_Round_Edges_Fill(5, 5, 40, 40, 12, 1);

Glcd_Box

Prototype void Glcd_Box(unsigned short x_upper_left, unsigned


short y_upper_left, unsigned short x_bottom_right, unsigned

www.raguvaran.puzl.com
short y_bottom_right, unsigned short color);

Returns Nothing.

Description Draws a box on Glcd.

Parameters :

 x_upper_left: x coordinate of the upper left box corner. Valid values: 0..127
 y_upper_left: y coordinate of the upper left box corner. Valid values: 0..63
 x_bottom_right: x coordinate of the lower right box corner. Valid values: 0..127
 y_bottom_right: y coordinate of the lower right box corner. Valid values: 0..63
 color: color parameter. Valid values: 0..2
The parameter color determines the color of the box fill: 0 white, 1 black, and 2 inverts each dot.

Requires Glcd needs to be initialized, see Glcd_Init routine.

Example // Draw a box between dots (5,15) and (20,40)


Glcd_Box(5, 15, 20, 40, 1);

Glcd_Circle

Prototype void Glcd_Circle(int x_center, int y_center, int radius, unsigned


short color);

Returns Nothing.

Description Draws a circle on Glcd.

Parameters :

 x_center: x coordinate of the circle center. Valid values: 0..127


 y_center: y coordinate of the circle center. Valid values: 0..63
 radius: radius size
 color: color parameter. Valid values: 0..2
The parameter color determines the color of the circle line: 0 white, 1 black, and 2 inverts each dot.

Requires Glcd needs to be initialized, see Glcd_Init routine.

Example // Draw a circle with center in (50,50) and radius=10


Glcd_Circle(50, 50, 10, 1);

Glcd_Circle_Fill

Prototype void Glcd_Circle_Fill(int x_center, int y_center, int radius, unsigned


short color);

Returns Nothing.

www.raguvaran.puzl.com
Description Draws a filled circle on Glcd.

Parameters :

 x_center: x coordinate of the circle center. Valid values: 0..127


 y_center: y coordinate of the circle center. Valid values: 0..63
 radius: radius size
 color: color parameter. Valid values: 0..2
The parameter color determines the color of the circle line: 0 white, 1 black, and 2 inverts each dot.

Requires Glcd needs to be initialized, see Glcd_Init routine.

Example // Draws a filled circle with center in (50,50) and radius=10


Glcd_Circle_Fill(50, 50, 10, 1);

Glcd_Set_Font

Prototype void Glcd_Set_Font(const char *activeFont, unsigned


short aFontWidth, unsigned short aFontHeight, unsigned int aFontOffs);

Returns Nothing.

Description Sets font that will be used with Glcd_Write_Char and Glcd_Write_Text routines.
Parameters :

 activeFont: font to be set. Needs to be formatted as an array of char


 aFontWidth: width of the font characters in dots.
 aFontHeight: height of the font characters in dots.
 aFontOffs: number that represents difference between the mikroC PRO for PIC character set
and regular ASCII set (eg. if 'A' is 65 in ASCII character, and 'A' is 45 in the mikroC PRO for PIC
character set, aFontOffs is 20). Demo fonts supplied with the library have an offset of 32, which
means that they start with space.
The user can use fonts given in the file “__Lib_GLCDFonts” file located in the Uses folder or create his own
fonts.

List of supported fonts:


 Font_Glcd_System3x5
 Font_Glcd_System5x7
 Font_Glcd_5x7
 Font_Glcd_Character8x7
For the sake of the backward compatibility, these fonts are supported also:

 System3x5 (equivalent to Font_Glcd_System3x5)


 FontSystem5x7_v2 (equivalent to Font_Glcd_System5x7)
 font5x7 (equivalent to Font_Glcd_5x7)
 Character8x7 (equivalent to Font_Glcd_Character8x7)

Requires Glcd needs to be initialized, see Glcd_Init routine.

Example // Use the custom 5x7 font "myfont" which starts with space (32):
Glcd_Set_Font(&myfont, 5, 7, 32);

www.raguvaran.puzl.com
Glcd_Set_Font_Adv

Prototype void Glcd_Set_Font_Adv(const far char *activeFont, unsigned


char font_color, char font_orientation);

Description Sets font that will be used with Glcd_Write_Char_Adv and Glcd_Write_Text_Adv routines.

Parameters  activeFont: font to be set. Needs to be formatted as an array of char.


 font_color: sets font color.
 font_orientation: sets font orientation.

Returns Nothing.

Requires Glcd needs to be initialized, see Glcd_Init routine.

Example Glcd_Set_Font_Adv(&myfont, 0, 0);

Notes None.

Glcd_Set_Ext_Font_Adv

Prototype void Glcd_Set_Ext_Font_Adv(unsigned long activeFont, unsigned


int font_color, char font_orientation);

Description Sets font that will be used with Glcd_Write_Char_Adv and Glcd_Write_Text_Adv routines. Font is located in an
external resource.

Parameters  activeFont: font to be set. This parameter represents the address in the exteral resource from
where the font data begins.
 font_color: sets font color.
 font_orientation: sets font orientation.

Returns Nothing.

Requires Glcd needs to be initialized, see Glcd_Init routine.

Example Glcd_Set_Ext_Font_Adv(173296, 5, 7, 32);

Notes None.

Glcd_Write_Char

Prototype void Glcd_Write_Char(unsigned short chr, unsigned short x_pos, unsigned


short page_num, unsigned short color);

www.raguvaran.puzl.com
Returns Nothing.

Description Prints character on the Glcd.

Parameters :

 chr: character to be written


 x_pos: character starting position on x-axis. Valid values: 0..(127-FontWidth)
 page_num: the number of the page on which character will be written. Valid values: 0..7
 color: color parameter. Valid values: 0..2
The parameter color determines the color of the character: 0 white, 1 black, and 2 inverts each dot.

Note : For x axis and page layout explanation see schematic at the bottom of this page.

Requires Glcd needs to be initialized, see Glcd_Init routine. Use Glcd_Set_Font to specify the font for display; if no font is
specified, then default Font_Glcd_System5x7 font supplied with the library will be used.

Example // Write character 'C' on the position 10 inside the page 2:


Glcd_Write_Char('C', 10, 2, 1);

Glcd_Write_Char_Adv

Prototype void Glcd_Write_Char_Adv(unsigned char ch, unsigned int x, unsigned int y);

Returns Nothing.

Description Writes a char on the glcd at coordinates (x, y).

 ch: char to be written.


 x: char position on x-axis.
 y: char position on y-axis.

Requires glcd module needs to be initialized. See the Glcd_Init routine.

Example Glcd_Write_Char_Adv('A',22,23,);

Glcd_Write_Text

Prototype void Glcd_Write_Text(char *text, unsigned short x_pos, unsigned


short page_num, unsigned short color);

Returns Nothing.

Description Prints text on Glcd.

Parameters :

www.raguvaran.puzl.com
 text: text to be written
 x_pos: text starting position on x-axis.
 page_num: the number of the page on which text will be written. Valid values: 0..7
 color: color parameter. Valid values: 0..2
The parameter color determines the color of the text: 0 white, 1 black, and 2 inverts each dot.

Note : For x axis and page layout explanation see schematic at the bottom of this page.

Requires Glcd needs to be initialized, see Glcd_Init routine. Use Glcd_Set_Font to specify the font for display; if no font is
specified, then default Font_Glcd_System5x7 font supplied with the library will be used.

Example // Write text "Hello world!" on the position 10 inside the page 2:
Glcd_Write_Text("Hello world!", 10, 2, 1);

Glcd_Write_Text_Adv

Prototype void Glcd_Write_Text_Adv(unsigned char *text, unsigned int x, unsigned


int y);

Returns Nothing.

Description Writes text on the glcd at coordinates (x, y).

Parameters :

 text: text to be written.


 x: text position on x-axis.
 y: text position on y-axis.

Requires Glcd module needs to be initialized. See the Glcd_Init routine.

Example Glcd_Write_Text_Adv("GLCD LIBRARY DEMO, WELCOME !", 0, 0,);

Glcd_Write_Const_Text_Adv

Prototype void Glcd_Write_Const_Text_Adv(const far char *ctext, unsigned


int x, unsigned int y);

Returns Nothing.

Description Writes text located in the program memory on the glcd at coordinates (x, y).

Parameters :

 text: text to be written.


 x: text position on x-axis.
 y: text position on y-axis.

Requires Glcd module needs to be initialized. See the Glcd_Init routine.

www.raguvaran.puzl.com
Example const ctext[] = "mikroElektronika"
...
Glcd_Write_Const_Text_Adv(ctext, 0, 0,)

Glcd_Image

Prototype void Glcd_Image(code const unsigned short *image);

Returns Nothing.

Description Displays bitmap on Glcd.

Parameters :

 image: image to be displayed. Bitmap array must be located in code memory.


Use the mikroC PRO for PIC integrated Glcd Bitmap Editor to convert image to a constant array suitable for
displaying on Glcd.

Requires Glcd needs to be initialized, see Glcd_Init routine.

Example // Draw image my_image on Glcd


Glcd_Image(my_image);

Glcd_Ext_Image

Prototype void Glcd_Ext_Image(unsigned long image);

Description Displays a bitmap from an external resource.

Parameters  image: image to be displayed. This parameter represents the address in the exteral resource from
where the image data begins.

Returns Nothing.

Requires Glcd needs to be initialized, see Glcd_Init routine.

Example Glcd_Ext_Image(153608);

Notes Use the mikroC PRO for PIC32 integrated Glcd Bitmap Editor, Tools > Glcd Bitmap Editor, to convert image
to a constant array suitable for displaying on Glcd.

Glcd_PartialImage

Prototype void Glcd_PartialImage(unsigned int x_left, unsigned int y_top, unsigned


int width, unsigned int height, unsigned int picture_width, unsigned
intpicture_height, code const unsigned short * image);

www.raguvaran.puzl.com
Returns Nothing.

Description Displays a partial area of the image on a desired location.

Parameters :

 x_left: x coordinate of the desired location (upper left coordinate).


 y_top: y coordinate of the desired location (upper left coordinate).
 width: desired image width.
 height: desired image height.
 picture_width: width of the original image.
 picture_height: height of the original image.
 image: image to be displayed. Bitmap array is located in code memory.
Use the integrated Glcd Bitmap Editor (menu option Tools › Glcd Bitmap Editor) to convert image to a constant
array suitable for displaying on Glcd.

Requires Glcd needs to be initialized, see Glcd_Init routine.

Example // Draws a 10x15 part of the image starting from the upper left corner on the
coordinate (10,12). Original image size is 16x32.
Glcd_PartialImage(10, 12, 10, 15, 16, 32, image);

Glcd_Ext_PartialImage

Prototype void Glcd_Ext_PartialImage(unsigned int x_left, unsigned int y_top, unsigned


int width, unsigned int height, unsigned int picture_width, unsigned
int picture_height, unsigned long image);

Description Displays a partial area of the image, located on an external resource, on a desired location of the screen.

Parameters  x_left: x coordinate of the desired location (upper left coordinate).


 y_top: y coordinate of the desired location (upper left coordinate).
 width: desired image width.
 height: desired image height.
 picture_width: width of the original image.
 picture_height: height of the original image.
 image: image to be displayed. This parameter represents the address in the exteral resource from
where the image data begins.

Returns Nothing.

Requires Glcd needs to be initialized, see Glcd_Init routine.

Example Glcd_Ext_PartialImage(10, 12, 10, 15, 16, 32, 0);

Notes Use the mikroC PRO for PIC32 integrated Glcd Bitmap Editor, Tools > Glcd Bitmap Editor, to convert image
to a constant array suitable for displaying on Glcd.

Library Example

www.raguvaran.puzl.com
The following example demonstrates routines of the Glcd library: initialization, clear(pattern fill), image
displaying, drawing lines, circles, boxes and rectangles, text displaying and handling.

Copy Code To Clipboard

//Declarations------------------------------------------------------------------
const code char truck_bmp[1024];
//--------------------------------------------------------------end-declarations

// Glcd module connections


char GLCD_DataPort at PORTD;

sbit GLCD_CS1 at RB0_bit;


sbit GLCD_CS2 at RB1_bit;
sbit GLCD_RS at RB2_bit;
sbit GLCD_RW at RB3_bit;
sbit GLCD_EN at RB4_bit;
sbit GLCD_RST at RB5_bit;

sbit GLCD_CS1_Direction at TRISB0_bit;


sbit GLCD_CS2_Direction at TRISB1_bit;
sbit GLCD_RS_Direction at TRISB2_bit;
sbit GLCD_RW_Direction at TRISB3_bit;
sbit GLCD_EN_Direction at TRISB4_bit;
sbit GLCD_RST_Direction at TRISB5_bit;
// End Glcd module connections

void delay2S(){ // 2 seconds delay function


Delay_ms(2000);
}

void main() {
unsigned short ii;
char *someText;

#define COMPLETE_EXAMPLE // comment this line to make simpler/smaller


example
ANSEL = 0; // Configure AN pins as digital
ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;

Glcd_Init(); // Initialize GLCD


Glcd_Fill(0x00); // Clear GLCD

while(1) {
#ifdef COMPLETE_EXAMPLE
Glcd_Image(truck_bmp); // Draw image
delay2S(); delay2S();
#endif

Glcd_Fill(0x00); // Clear GLCD

Glcd_Box(62,40,124,56,1); // Draw box


Glcd_Rectangle(5,5,84,35,1); // Draw rectangle
Glcd_Line(0, 0, 127, 63, 1); // Draw line
delay2S();

for(ii = 5; ii < 60; ii+=5 ){ // Draw horizontal and vertical lines


Delay_ms(250);
Glcd_V_Line(2, 54, ii, 1);
Glcd_H_Line(2, 120, ii, 1);
}

delay2S();

www.raguvaran.puzl.com
Glcd_Fill(0x00); // Clear GLCD
#ifdef COMPLETE_EXAMPLE
Glcd_Set_Font(Font_Glcd_Character8x7, 8, 7, 32); // Choose font, see __Lib_GLCDFonts.c
in Uses folder
#endif
Glcd_Write_Text("mikroE", 1, 7, 2); // Write string

for (ii = 1; ii <= 10; ii++) // Draw circles


Glcd_Circle(63,32, 3*ii, 1);
delay2S();

Glcd_Box(12,20, 70,57, 2); // Draw box


delay2S();

#ifdef COMPLETE_EXAMPLE
Glcd_Fill(0xFF); // Fill GLCD

Glcd_Set_Font(Font_Glcd_Character8x7, 8, 7, 32); // Change font


someText = "8x7 Font";
Glcd_Write_Text(someText, 5, 0, 2); // Write string
delay2S();

Glcd_Set_Font(Font_Glcd_System3x5, 3, 5, 32); // Change font


someText = "3X5 CAPITALS ONLY";
Glcd_Write_Text(someText, 60, 2, 2); // Write string
delay2S();

Glcd_Set_Font(Font_Glcd_System5x7, 5, 7, 32); // Change font


someText = "5x7 Font";
Glcd_Write_Text(someText, 5, 4, 2); // Write string
delay2S();

Glcd_Set_Font(Font_Glcd_5x7, 5, 7, 32); // Change font


someText = "5x7 Font (v2)";
Glcd_Write_Text(someText, 50, 6, 2); // Write string
delay2S();
#endif
}
}

HW Connection

www.raguvaran.puzl.com
Glcd HW connection

I²C Library
The I²C full master MSSP module is available with a number of PIC MCU models. mikroC PRO for PIC
provides library which supports the master I²C mode.

Important :

www.raguvaran.puzl.com
 Some MCUs have multiple I²C modules. In order to use the desired I²C library routine,
simply change the number 1 in the prototype with the appropriate module number,
i.e.I2C2_Init(100000);

Library Routines
 I2C1_Init
 I2C1_Start
 I2C1_Repeated_Start
 I2C1_Is_Idle
 I2C1_Rd
 I2C1_Wr
 I2C1_Stop

I2C1_Init

Prototype void I2C1_Init(const unsigned long clock);

Returns Nothing.

Description Initializes I²C with desired clock (refer to device data sheet for correct values in respect with Fosc). Needs to be
called before using other functions of I²C Library.
You don’t need to configure ports manually for using the module; library will take care of the initialization.

Requires Library requires MSSP module on PORTB or PORTC.

Note : Calculation of the I²C clock value is carried out by the compiler, as it would produce a relatively
large code if performed on the library level. Therefore, compiler needs to know the value of the parameter in the
compile time. That is why this parameter needs to be a constant, and not a variable.

Example I2C1_Init(100000);

I2C1_Start

Prototype unsigned short I2C1_Start(void);

Returns If there is no error, function returns 0.

Description Determines if I²C bus is free and issues START signal.

Requires I²C must be configured before using this function. See I2C1_Init.

Example I2C1_Start();

I2C1_Repeated_Start

Prototype void I2C1_Repeated_Start(void);

www.raguvaran.puzl.com
Returns Nothing.

Description Issues repeated START signal.

Requires I²C must be configured before using this function. See I2C1_Init.

Example I2C1_Repeated_Start();

I2C1_Is_Idle

Prototype unsigned short I2C1_Is_Idle(void);

Returns Returns 1 if I²C bus is free, otherwise returns 0.

Description Tests if I²C bus is free.

Requires I²C must be configured before using this function. See I2C1_Init.

Example if (I2C1_Is_Idle()) {...}

I2C1_Rd

Prototype unsigned short I2C1_Rd(unsigned short ack);

Returns Returns one byte from the slave.

Description Reads one byte from the slave, and sends not acknowledge signal if parameter ack is 0, otherwise it
sends acknowledge.

Requires I²C must be configured before using this function. See I2C1_Init.
Also, START signal needs to be issued in order to use this function. See I2C1_Start.

Example Read data and send not acknowledge signal:


unsigned short take;
...
take = I2C1_Rd(0);

I2C1_Wr

Prototype unsigned short I2C1_Wr(unsigned short data_);

Returns Returns 0 if there were no errors.

Description Sends data byte (parameter data) via I²C bus.

www.raguvaran.puzl.com
Requires I²C must be configured before using this function. See I2C1_Init.
Also, START signal needs to be issued in order to use this function. See I2C1_Start.

Example I2C1_Write(0xA3);

I2C1_Stop

Prototype void I2C1_Stop(void);

Returns Nothing.

Description Issues STOP signal.

Requires I²C must be configured before using this function. See I2C1_Init.

Example I2C1_Stop();

Library Example
This code demonstrates use of I²C library. PIC MCU is connected (SCL, SDA pins) to 24c02 EEPROM.
Program sends data to EEPROM (data is written at address 2). Then, we read data via I²C from EEPROM
and send its value to PORTB, to check if the cycle was successful (see the figure below how to interface
24c02 to PIC).
Copy Code To Clipboard

void main(){
ANSEL = 0; // Configure AN pins as digital I/O
ANSELH = 0;
PORTB = 0;
TRISB = 0; // Configure PORTB as output

I2C1_Init(100000); // initialize I2C communication


I2C1_Start(); // issue I2C start signal
I2C1_Wr(0xA2); // send byte via I2C (device address + W)
I2C1_Wr(2); // send byte (address of EEPROM location)
I2C1_Wr(0xAA); // send data (data to be written)
I2C1_Stop(); // issue I2C stop signal

Delay_100ms();

I2C1_Start(); // issue I2C start signal


I2C1_Wr(0xA2); // send byte via I2C (device address + W)
I2C1_Wr(2); // send byte (data address)
I2C1_Repeated_Start(); // issue I2C signal repeated start
I2C1_Wr(0xA3); // send byte (device address + R)
PORTB = I2C1_Rd(0u); // Read the data (NO acknowledge)
I2C1_Stop(); // issue I2C stop signal
}

HW Connection

www.raguvaran.puzl.com
Interfacing 24c02 to PIC via I²C

Keypad Library
The mikroC PRO for PIC provides a library for working with 4x4 keypad. The library routines can also be
used with 4x1, 4x2, or 4x3 keypad. For connections explanation see schematic at the bottom of this
page.

External dependencies of Keypad Library

www.raguvaran.puzl.com
The following variable must be
defined in all projects using Description : Example :
Keypad Library:
extern sfr
Keypad Port. char keypadPort at PORTD;
char keypadPort;

Library Routines
 Keypad_Init
 Keypad_Key_Press
 Keypad_Key_Click

Keypad_Init

Prototype void Keypad_Init(void);

Returns Nothing.

Description Initializes port for working with keypad.

Requires Global variable :


 keypadPort - Keypad port
must be defined before using this function.

Example // Keypad module connections


char keypadPort at PORTD;
// End of keypad module connections
...
Keypad_Init();

Keypad_Key_Press

Prototype char Keypad_Key_Press(void);

Returns The code of a pressed key (1..16).

If no key is pressed, returns 0.

Description Reads the key from keypad when key gets pressed.

Requires Port needs to be initialized for working with the Keypad library, see Keypad_Init.

Example char kp;


...
kp = Keypad_Key_Press();

Keypad_Key_Click

www.raguvaran.puzl.com
Prototype char Keypad_Key_Click(void);

Returns The code of a clicked key (1..16).

If no key is clicked, returns 0.

Description Call to Keypad_Key_Click is a blocking call: the function waits until some key is pressed and released. When
released, the function returns 1 to 16, depending on the key. If more than one key is pressed simultaneously the
function will wait until all pressed keys are released. After that the function will return the code of the first
pressed key.

Requires Port needs to be initialized for working with the Keypad library, see Keypad_Init.

Example char kp;


...
kp = Keypad_Key_Click();

Library Example
This is a simple example of using the Keypad Library. It supports keypads with 1..4 rows and 1..4
columns. The code being returned by Keypad_Key_Click() function is in range from 1..16. In this
example, the code returned is transformed into ASCII codes [0..9,A..F] and displayed on Lcd. In
addition, a small single-byte counter displays in the second Lcd row number of key presses.

Copy Code To Clipboard

unsigned short kp, cnt, oldstate = 0;


char txt[6];

// Keypad module connections


char keypadPort at PORTD;
// End Keypad module connections

// LCD module connections


sbit LCD_RS at RB4_bit;
sbit LCD_EN at RB5_bit;
sbit LCD_D4 at RB0_bit;
sbit LCD_D5 at RB1_bit;
sbit LCD_D6 at RB2_bit;
sbit LCD_D7 at RB3_bit;

sbit LCD_RS_Direction at TRISB4_bit;


sbit LCD_EN_Direction at TRISB5_bit;
sbit LCD_D4_Direction at TRISB0_bit;
sbit LCD_D5_Direction at TRISB1_bit;
sbit LCD_D6_Direction at TRISB2_bit;
sbit LCD_D7_Direction at TRISB3_bit;
// End LCD module connections

void main() {
cnt = 0; // Reset counter
Keypad_Init(); // Initialize Keypad
ANSEL = 0; // Configure AN pins as digital I/O
ANSELH = 0;
Lcd_Init(); // Initialize LCD
Lcd_Cmd(_LCD_CLEAR); // Clear display
Lcd_Cmd(_LCD_CURSOR_OFF); // Cursor off
Lcd_Out(1, 1, "1");
Lcd_Out(1, 1, "Key :"); // Write message text on LCD

www.raguvaran.puzl.com
Lcd_Out(2, 1, "Times:");

do {
kp = 0; // Reset key code variable

// Wait for key to be pressed and released


do
// kp = Keypad_Key_Press(); // Store key code in kp variable
kp = Keypad_Key_Click(); // Store key code in kp variable
while (!kp);
// Prepare value for output, transform key to it's ASCII value
switch (kp) {
//case 10: kp = 42; break; // '*' // Uncomment this block for keypad4x3
//case 11: kp = 48; break; // '0'
//case 12: kp = 35; break; // '#'
//default: kp += 48;

case 1: kp = 49; break; // 1 // Uncomment this block for keypad4x4


case 2: kp = 50; break; // 2
case 3: kp = 51; break; // 3
case 4: kp = 65; break; // A
case 5: kp = 52; break; // 4
case 6: kp = 53; break; // 5
case 7: kp = 54; break; // 6
case 8: kp = 66; break; // B
case 9: kp = 55; break; // 7
case 10: kp = 56; break; // 8
case 11: kp = 57; break; // 9
case 12: kp = 67; break; // C
case 13: kp = 42; break; // *
case 14: kp = 48; break; // 0
case 15: kp = 35; break; // #
case 16: kp = 68; break; // D

if (kp != oldstate) { // Pressed key differs from previous


cnt = 1;
oldstate = kp;
}
else { // Pressed key is same as previous
cnt++;
}

Lcd_Chr(1, 10, kp); // Print key ASCII value on LCD

if (cnt == 255) { // If counter varialble overflow


cnt = 0;
Lcd_Out(2, 10, " ");
}

WordToStr(cnt, txt); // Transform counter value to string


Lcd_Out(2, 10, txt); // Display counter value on LCD
} while (1);
}

HW Connection

www.raguvaran.puzl.com
4x4 Keypad connection scheme

Lcd Library
The mikroC PRO for PIC provides a library for communication with Lcds (with HD44780 compliant
controllers) through the 4-bit interface. An example of Lcd connections is given on the schematic at the
bottom of this page.

For creating a set of custom Lcd characters use Lcd Custom Character Tool.

Library Dependency Tree

www.raguvaran.puzl.com
External dependencies of Lcd Library
The following variables must
Description
be defined in all projects using Example :
:
Lcd Library :

extern sfr Register


sbit LCD_RS at RB4_bit;
sbit LCD_RS: Select line.

extern sfr
Enable line. sbit LCD_EN at RB5_bit;
sbit LCD_EN:

extern sfr
Data 7 line. sbit LCD_D7 at RB3_bit;
sbit LCD_D7;

extern sfr
Data 6 line. sbit LCD_D6 at RB2_bit;
sbit LCD_D6;

extern sfr
Data 5 line. sbit LCD_D5 at RB1_bit;
sbit LCD_D5;

extern sfr
Data 4 line. sbit LCD_D4 at RB0_bit;
sbit LCD_D4;

Register
extern sfr Select
sbit LCD_RS_Direction at TRISB4_bit;
sbit LCD_RS_Direction; direction
pin.

Enable
extern sfr
direction sbit LCD_EN_Direction at TRISB5_bit;
sbit LCD_EN_Direction;
pin.

Data 7
extern sfr
direction sbit LCD_D7_Direction at TRISB3_bit;
sbit LCD_D7_Direction;
pin.

Data 6
extern sfr
direction sbit LCD_D6_Direction at TRISB2_bit;
sbit LCD_D6_Direction;
pin.

extern sfr
Data 5 sbit LCD_D5_Direction at TRISB1_bit;
sbit LCD_D5_Direction;
direction

www.raguvaran.puzl.com
pin.

Data 4
extern sfr
direction sbit LCD_D4_Direction at TRISB0_bit;
sbit LCD_D4_Direction;
pin.

Library Routines
 Lcd_Init
 Lcd_Out
 Lcd_Out_Cp
 Lcd_Chr
 Lcd_Chr_Cp
 Lcd_Cmd

Lcd_Init
Prototype void Lcd_Init();

Returns Nothing.

Description Initializes Lcd module.

Requires Global variables:

 LCD_D7: Data bit 7


 LCD_D6: Data bit 6
 LCD_D5: Data bit 5
 LCD_D4: Data bit 4
 LCD_RS: Register Select (data/instruction) signal pin
 LCD_EN: Enable signal pin

 LCD_D7_Direction: Direction of the Data 7 pin


 LCD_D6_Direction: Direction of the Data 6 pin
 LCD_D5_Direction: Direction of the Data 5 pin
 LCD_D4_Direction: Direction of the Data 4 pin
 LCD_RS_Direction: Direction of the Register Select pin
 LCD_EN_Direction: Direction of the Enable signal pin
must be defined before using this function.

Example // Lcd pinout settings


sbit LCD_RS at RB4_bit;
sbit LCD_EN at RB5_bit;
sbit LCD_D7 at RB3_bit;
sbit LCD_D6 at RB2_bit;
sbit LCD_D5 at RB1_bit;

www.raguvaran.puzl.com
sbit LCD_D4 at RB0_bit;

// Pin direction
sbit LCD_RS_Direction at TRISB4_bit;
sbit LCD_EN_Direction at TRISB5_bit;
sbit LCD_D7_Direction at TRISB3_bit;
sbit LCD_D6_Direction at TRISB2_bit;
sbit LCD_D5_Direction at TRISB1_bit;
sbit LCD_D4_Direction at TRISB0_bit;
...

Lcd_Init();

Lcd_Out
Prototype void Lcd_Out(char row, char column, char *text);

Returns Nothing.

Description Prints text on Lcd starting from specified position. Both string variables and literals can be passed as a text.

Parameters :

 row: starting position row number


 column: starting position column number
 text: text to be written

Requires The Lcd module needs to be initialized. See Lcd_Init routine.

Example // Write text "Hello!" on Lcd starting from row 1, column 3:


Lcd_Out(1, 3, "Hello!");

Lcd_Out_Cp
Prototype void Lcd_Out_Cp(char *text);

Returns Nothing.

www.raguvaran.puzl.com
Description Prints text on Lcd at current cursor position. Both string variables and literals can be passed as a text.

Parameters :

 text: text to be written

Requires The Lcd module needs to be initialized. See Lcd_Init routine.

Example // Write text "Here!" at current cursor position:


Lcd_Out_Cp("Here!");

Lcd_Chr
Prototype void Lcd_Chr(char row, char column, char out_char);

Returns Nothing.

Description Prints character on Lcd at specified position. Both variables and literals can be passed as a character.

Parameters :

 row: writing position row number


 column: writing position column number
 out_char: character to be written

Requires The Lcd module needs to be initialized. See Lcd_Init routine.

Example // Write character "i" at row 2, column 3:


Lcd_Chr(2, 3, 'i');

Lcd_Chr_Cp
Prototype void Lcd_Chr_Cp(char out_char);

Returns Nothing.

www.raguvaran.puzl.com
Description Prints character on Lcd at current cursor position. Both variables and literals can be passed as a character.

Parameters :

 out_char: character to be written

Requires The Lcd module needs to be initialized. See Lcd_Init routine.

Example // Write character "e" at current cursor position:


Lcd_Chr_Cp('e');

Lcd_Cmd
Prototype void Lcd_Cmd(char out_char);

Returns Nothing.

Description Sends command to Lcd.

Parameters :

 out_char: command to be sent

Note : Predefined constants can be passed to the function, see Available Lcd Commands.

Requires The Lcd module needs to be initialized. See Lcd_Init table.

Example // Clear Lcd display:


Lcd_Cmd(_LCD_CLEAR);

Available Lcd Commands


Lcd Command Purpose

_LCD_FIRST_ROW Move cursor to the 1st row

_LCD_SECOND_ROW Move cursor to the 2nd row

www.raguvaran.puzl.com
Lcd Command Purpose

_LCD_THIRD_ROW Move cursor to the 3rd row

_LCD_FOURTH_ROW Move cursor to the 4th row

_LCD_CLEAR Clear display

_LCD_RETURN_HOME Return cursor to home position, returns a shifted display to its original position. Display data
RAM is unaffected.

_LCD_CURSOR_OFF Turn off cursor

_LCD_UNDERLINE_ON Underline cursor on

_LCD_BLINK_CURSOR_ON Blink cursor on

_LCD_MOVE_CURSOR_LEFT Move cursor left without changing display data RAM

_LCD_MOVE_CURSOR_RIGHT Move cursor right without changing display data RAM

_LCD_TURN_ON Turn Lcd display on

_LCD_TURN_OFF Turn Lcd display off

_LCD_SHIFT_LEFT Shift display left without changing display data RAM

_LCD_SHIFT_RIGHT Shift display right without changing display data RAM

Library Example
The following code demonstrates usage of the Lcd Library routines:

Copy Code To Clipboard

// LCD module connections


sbit LCD_RS at RB4_bit;

www.raguvaran.puzl.com
sbit LCD_EN at RB5_bit;
sbit LCD_D4 at RB0_bit;
sbit LCD_D5 at RB1_bit;
sbit LCD_D6 at RB2_bit;
sbit LCD_D7 at RB3_bit;

sbit LCD_RS_Direction at TRISB4_bit;


sbit LCD_EN_Direction at TRISB5_bit;
sbit LCD_D4_Direction at TRISB0_bit;
sbit LCD_D5_Direction at TRISB1_bit;
sbit LCD_D6_Direction at TRISB2_bit;
sbit LCD_D7_Direction at TRISB3_bit;
// End LCD module connections

char txt1[] = "mikroElektronika";


char txt2[] = "EasyPIC6";
char txt3[] = "Lcd4bit";
char txt4[] = "example";

char i; // Loop variable

void Move_Delay() { // Function used for text moving


Delay_ms(500); // You can change the moving speed here
}

void main(){
ANSEL = 0; // Configure AN pins as digital I/O
ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;

Lcd_Init(); // Initialize LCD

Lcd_Cmd(_LCD_CLEAR); // Clear display


Lcd_Cmd(_LCD_CURSOR_OFF); // Cursor off
Lcd_Out(1,6,txt3); // Write text in first row

Lcd_Out(2,6,txt4); // Write text in second row


Delay_ms(2000);
Lcd_Cmd(_LCD_CLEAR); // Clear display

Lcd_Out(1,1,txt1); // Write text in first row


Lcd_Out(2,5,txt2); // Write text in second row

Delay_ms(2000);

// Moving text
for(i=0; i<4; i++) { // Move text to the right 4 times
Lcd_Cmd(_LCD_SHIFT_RIGHT);
Move_Delay();
}

while(1) { // Endless loop


for(i=0; i<8; i++) { // Move text to the left 7 times
Lcd_Cmd(_LCD_SHIFT_LEFT);
Move_Delay();
}

for(i=0; i<8; i++) { // Move text to the right 7 times


Lcd_Cmd(_LCD_SHIFT_RIGHT);

www.raguvaran.puzl.com
Move_Delay();
}
}
}

Lcd HW connection

Manchester Code Library


The mikroC PRO for PIC provides a library for handling Manchester coded signals. The Manchester code
is a code in which data and clock signals are combined to form a single self-synchronizing data stream;
each encoded bit contains a transition at the midpoint of a bit period, the direction of transition
determines whether the bit is 0 or 1; the second half is the true bit value and the first half is the
complement of the true bit value (as shown in the figure below).

www.raguvaran.puzl.com
Important :
 The Manchester receive routines are blocking calls (Man_Receive_Init and Man_Synchro).
This means that MCU will wait until the task has been performed (e.g. byte is received,
synchronization achieved, etc).
 Manchester code library implements time-based activities, so interrupts need to be disabled
when using it.

External dependencies of Manchester Code Library


The following variables must
be defined in all projects
Description: Example:
using Manchester Code
Library:
extern sfr
Receive line. sbit MANRXPIN at RC0_bit;
sbit MANRXPIN;

extern sfr Transmit sbit MANTXPIN at RC1_bit;


sbit MANTXPIN; line.
Direction of
extern sfr
the Receive sbit MANRXPIN_Direction at TRISC0_bit;
sbit MANRXPIN_Direction;
pin.
Direction of
extern sfr
the Transmit sbit MANTXPIN_Direction at TRISC1_bit;
sbit MANTXPIN_Direction;
pin.

Library Routines
 Man_Receive_Init
 Man_Receive
 Man_Send_Init
 Man_Send
 Man_Synchro
 Man_Break

www.raguvaran.puzl.com
The following routines are for the internal use by compiler only:

 Manchester_0
 Manchester_1
 Manchester_Out

Man_Receive_Init

Prototype unsigned int Man_Receive_Init();

Returns  0 - if initialization and synchronization were successful.


 1 - upon unsuccessful synchronization.
 255 - upon user abort.

Description The function configures Receiver pin and performs synchronization procedure in order to retrieve baud rate out of
the incoming signal.

Note : In case of multiple persistent errors on reception, the user should call this routine once again
or Man_Synchro routine to enable synchronization.

Requires Global variables :


 MANRXPIN : Receive line
 MANRXPIN_Direction : Direction of the receive pin
must be defined before using this function.

Example // Initialize Receiver


sbit MANRXPIN at RC0_bit;
sbit MANRXPIN_Direction at TRISC0_bit;
...
Man_Receive_Init();

Man_Receive

Prototype unsigned char Man_Receive(unsigned char *error);

Returns A byte read from the incoming signal.

Description The function extracts one byte from incoming signal.

Parameters :

 error: error flag. If signal format does not match the expected, the error flag will be set to
non-zero.

Requires To use this function, the user must prepare the MCU for receiving. See Man_Receive_Init.

Example unsigned char data = 0, error = 0;


...
data = Man_Receive(&error);
if (error)
{ /* error handling */ }

www.raguvaran.puzl.com
Man_Send_Init

Prototype void Man_Send_Init();

Returns Nothing.

Description The function configures Transmitter pin.

Requires Global variables :


 MANTXPIN : Transmit line
 MANTXPIN_Direction : Direction of the transmit pin
must be defined before using this function.

Example // Initialize Transmitter:


sbit MANTXPIN at RC1_bit;
sbit MANTXPIN_Direction at TRISC1_bit;
...
Man_Send_Init();

Man_Send

Prototype void Man_Send(unsigned char tr_data);

Returns Nothing.

Description Sends one byte.

Parameters :

 tr_data: data to be sent

Note : Baud rate used is 500 bps.

Requires To use this function, the user must prepare the MCU for sending. See Man_Send_Init.

Example unsigned char msg;


...
Man_Send(msg);

Man_Synchro

Prototype unsigned char Man_Synchro();

Returns  255 - if synchronization was not successful.


 Half of the manchester bit length, given in multiples of 10us - upon successful synchronization.

www.raguvaran.puzl.com
Description Measures half of the manchester bit length with 10us resolution.

Requires To use this function, you must first prepare the MCU for receiving. See Man_Receive_Init.

Example unsigned int man__half_bit_len;


...
man__half_bit_len = Man_Synchro();

Man_Break

Prototype void Man_Break();

Returns Nothing.

Description Man_Receive is blocking routine and it can block the program flow. Call this routine from interrupt to unblock
the program execution. This mechanism is similar to WDT.

Note : Interrupts should be disabled before using Manchester routines again (see note at the top of this
page).

Requires Nothing.

Example char data1, error, counter = 0;

void interrupt {

if (INTCON.T0IF) {
if (counter >= 20) {
Man_Break();
counter = 0; // reset counter
}
else
counter++; // increment counter

INTCON.T0IF = 0; // Clear Timer0 overflow interrupt flag

}
}

void main() {

OPTION_REG = 0x04; // TMR0 prescaler set to 1:32

...

Man_Receive_Init();

...

// try Man_Receive with blocking prevention mechanism


INTCON.GIE = 1; // Global interrupt enable
INTCON.T0IE = 1; // Enable Timer0 overflow interrupt
data1 = Man_Receive(&error);
INTCON.GIE = 0; // Global interrupt disable

...

www.raguvaran.puzl.com
}

Library Example
The following code is code for the Manchester receiver, it shows how to use the Manchester Library for
receiving data:

Copy Code To Clipboard

// LCD module connections


sbit LCD_RS at RB4_bit;
sbit LCD_EN at RB5_bit;
sbit LCD_D4 at RB0_bit;
sbit LCD_D5 at RB1_bit;
sbit LCD_D6 at RB2_bit;
sbit LCD_D7 at RB3_bit;

sbit LCD_RS_Direction at TRISB4_bit;


sbit LCD_EN_Direction at TRISB5_bit;
sbit LCD_D4_Direction at TRISB0_bit;
sbit LCD_D5_Direction at TRISB1_bit;
sbit LCD_D6_Direction at TRISB2_bit;
sbit LCD_D7_Direction at TRISB3_bit;
// End LCD module connections

// Manchester module connections


sbit MANRXPIN at RC0_bit;
sbit MANRXPIN_Direction at TRISC0_bit;
sbit MANTXPIN at RC1_bit;
sbit MANTXPIN_Direction at TRISC1_bit;
// End Manchester module connections

char error, ErrorCount, temp;

void main() {
ErrorCount = 0;
ANSEL = 0; // Configure AN pins as digital I/O
ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;
TRISC.F5 = 0;
Lcd_Init(); // Initialize LCD
Lcd_Cmd(_LCD_CLEAR); // Clear LCD display

Man_Receive_Init(); // Initialize Receiver

while (1) { // Endless loop

Lcd_Cmd(_LCD_FIRST_ROW); // Move cursor to the 1st row

while (1) { // Wait for the "start" byte


temp = Man_Receive(&error); // Attempt byte receive
if (temp == 0x0B) // "Start" byte, see Transmitter example
break; // We got the starting sequence
if (error) // Exit so we do not loop forever
break;
}

do
{
temp = Man_Receive(&error); // Attempt byte receive
if (error) { // If error occured

www.raguvaran.puzl.com
Lcd_Chr_CP('?'); // Write question mark on LCD
ErrorCount++; // Update error counter
if (ErrorCount > 20) { // In case of multiple errors
temp = Man_Synchro(); // Try to synchronize again
//Man_Receive_Init(); // Alternative, try to Initialize Receiver again
ErrorCount = 0; // Reset error counter
}
}
else { // No error occured
if (temp != 0x0E) // If "End" byte was received(see Transmitter
example)
Lcd_Chr_CP(temp); // do not write received byte on LCD
}
Delay_ms(25);
}
while (temp != 0x0E) ; // If "End" byte was received exit do loop
}
}

The following code is code for the Manchester transmitter, it shows how to use the Manchester Library
for transmitting data:

Copy Code To Clipboard

// Manchester module connections


sbit MANRXPIN at RC0_bit;
sbit MANRXPIN_Direction at TRISC0_bit;
sbit MANTXPIN at RC1_bit;
sbit MANTXPIN_Direction at TRISC1_bit;
// End Manchester module connections

char index, character;


char s1[] = "mikroElektronika";

void main() {

ANSEL = 0; // Configure AN pins as digital I/O


ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;

Man_Send_Init(); // Initialize transmitter

while (1) { // Endless loop


Man_Send(0x0B); // Send "start" byte
Delay_ms(100); // Wait for a while

character = s1[0]; // Take first char from string


index = 0; // Initialize index variable
while (character) { // String ends with zero
Man_Send(character); // Send character
Delay_ms(90); // Wait for a while
index++; // Increment index variable
character = s1[index]; // Take next char from string
}
Man_Send(0x0E); // Send "end" byte
Delay_ms(1000);
}
}

Connection Example

www.raguvaran.puzl.com
Simple Transmitter connection

Simple Receiver connection

Memory Manager Library


This library provides routines for manipulating dynamic memory allocation. Dynamic memory allocation
(also known as heap-based memory allocation) is the allocation of memory storage for use in a program
during the runtime of that program.
Dynamically allocated memory exists until it is released. This is in contrast to static memory allocation,
which has a fixed duration. It is said that an object so allocated has a dynamic lifetime.

www.raguvaran.puzl.com
The heap memory size can be configured in the Edit Project window. Also, user can override heap
memory size in the code, by setting the HEAP_SIZE constant.

Library Routines
 MM_Init
 Malloc
 Free
 MM_LargestFreeMemBlock
 MM_TotalFreeMemSize

MM_Init

Prototype void MM_Init();

Description Sets Heap size.

Parameters None.

Returns Nothing.

Requires Nothing.

Example MM_Init(); // set Heap size

Notes None.

Malloc

Prototype void *Malloc(unsigned long Size);

Description Allocates a block of size bytes of memory, returning a pointer to the beginning of the block. The content of the
newly allocated block of memory is not initialized, remaining with indeterminate values..

Parameters  Size: Size of the memory block, in bytes.

Returns Returns a pointer to the memory block allocated by the function.


If the function failed to allocate the requested block of memory, a null pointer is returned.

Requires Nothing.

Example int *pi; // pointer to integer


int ai[100]; // array of integers

www.raguvaran.puzl.com
void main() {
pi = (int *)Malloc(sizeof ai); // pi will point to a memory block where the array
is allocated
}

Notes The type of this pointer is always void, which can be cast to the desired type of data pointer in order to be
dereferenceable.

Free

Prototype void Free(char * P, unsigned long Size);

Description This function is used to free memory block allocated by Malloc.

Parameters  P: pointer to the memory block


 Size: actual size of the memory block.

Returns Nothing.

Requires Nothing.

Example int *pi; // pointer to integer


int ai[100]; // array of integers

void main() {
pi = (int *)Malloc(sizeof ai); // pi will point to a memory block in the Heap
where the array is allocated
Free(pi, sizeof(pi)); // frees memory block from the Heap allocated by
Malloc, pointed to by the pi pointer
}

Notes None.

MM_LargestFreeMemBlock

Prototype unsigned long MM_LargestFreeMemBlock();

Description This function is used to determine largest available free memory block for the Heap.

Parameters None.

Returns Largest free memory block for the Heap.

www.raguvaran.puzl.com
Requires Nothing.

Example unsigned long block;

void main() {
block = MM_LargestFreeMemBlock();
}

Notes None.

MM_TotalFreeMemSize

Prototype unsigned long MM_TotalFreeMemSize();

Description This function is used to determine total free memory size.

Parameters None.

Returns Total free memory size.

Requires Nothing.

Example unsigned long total;

void main() {
block = MM_TotalFreeMemSize();
}

Notes None.

Multi Media Card Library


The Multi Media Card (MMC) is a Flash memory card standard. MMC cards are currently available in sizes
up to and including 32 GB and are used in cellular phones, digital audio players, digital cameras
and PDA’s.
mikroC PRO for PIC provides a library for accessing data on Multi Media Card via SPI communication.
This library also supports SD (Secure Digital) and high capacity SDHC (Secure Digital High Capacity)
memory cards .

Secure Digital Card


Secure Digital (SD) is a Flash memory card standard, based on the older Multi Media Card (MMC)
format.
SD cards are currently available in sizes of up to and including 2 GB, and are used in digital cameras,

www.raguvaran.puzl.com
digital camcorders, handheld computers, media players, mobile phones, GPS receivers, video games
and PDAs.

Secure Digital High Capacity Card


SDHC (Secure Digital High Capacity, SD 2.0) is an extension of the SD standard which increases card's
storage capacity up to 32 GB by using sector addressing instead of byte addressing in the previous SD
standard.
SDHC cards share the same physical and electrical form factor as older (SD 1.x) cards, allowing SDHC-
devices to support both newer SDHC cards and older SD-cards. The current standard limits the
maximum capacity of an SDHC card to 32 GB.
Important :
 Routines for file handling can be used only with FAT16 file system.
 Library functions create and read files from the root directory only.
 Library functions populate both FAT1 and FAT2 tables when writing to files, but the file data
is being read from the FAT1 table only; i.e. there is no recovery if the FAT1 table gets
corrupted.
 If MMC/SD card has Master Boot Record (MBR), the library will work with the first available
primary (logical) partition that has non-zero size. If MMC/SD card has Volume Boot Record
(i.e. there is only one logical partition and no MBRs), the library works with entire card as a
single partition. For more information on MBR, physical and logical drives,
primary/secondary partitions and partition tables, please consult other resources, e.g.
Wikipedia and similar.
 Before write operation, make sure you don’t overwrite boot or FAT sector as it could make
your card on PC or digital camera unreadable. Drive mapping tools, such as Winhex, can be
of a great assistance.
 Library uses SPI module for communication. The user must initialize the appropriate SPI
module before using the MMC Library.
 For MCUs with multiple SPI modules it is possible to initialize all of them and then switch by
using the SPI_Set_Active() function. See the SPI Library functions.
 MMC FAT 16 Library works with PIC18 family only.
The SPI module has to be initialized through SPIx_Init_Advanced routine with the following parameters:
 SPI Master
 Primary prescaler 64
 Data sampled in the middle of data output time
 Clock idle low
 Serial output data changes on transition form low to high edge

Tip : Once the MMC/SD card is initialized, SPI module can be reinitialized at higher a speed. See
the Mmc_Init and Mmc_Fat_Init routines.

Library Dependency Tree

External dependencies of MMC Library


The following variable must be defined Description
Example :
in all projects using MMC library: :

www.raguvaran.puzl.com
extern sfr Chip select sbit Mmc_Chip_Select at RC0_bit;
sbit Mmc_Chip_Select; pin.
Direction of
extern sfr
the chip sbit Mmc_Chip_Select_Direction atTRISC0_bit;
sbit Mmc_Chip_Select_Direction;
select pin.

Library Routines
 Mmc_Init
 Mmc_Read_Sector
 Mmc_Write_Sector
 Mmc_Read_Cid
 Mmc_Read_Csd
 Mmc_Multi_Read_Start
 Mmc_Multi_Read_Sector
 Mmc_Multi_Read_Stop

Routines for file handling:

 Mmc_Fat_Init
 Mmc_Fat_QuickFormat
 Mmc_Fat_Assign
 Mmc_Fat_Reset
 Mmc_Fat_Read
 Mmc_Fat_Rewrite
 Mmc_Fat_Append
 Mmc_Fat_Delete
 Mmc_Fat_Write
 Mmc_Fat_Set_File_Date
 Mmc_Fat_Get_File_Date
 Mmc_Fat_Get_File_Date_Modified
 Mmc_Fat_Get_File_Size
 Mmc_Get_File_Write_Sector
 Mmc_Fat_Get_Swap_File
 Mmc_Fat_Tell
 Mmc_Fat_Seek
 Mmc_Fat_Rename
 Mmc_Fat_MakeDir
 Mmc_Fat_RenameDir
 Mmc_Fat_RemoveDir
 Mmc_Fat_ChangeDir
 Mmc_Fat_Exists
 Mmc_Fat_Dir

Mmc_Init

Prototype unsigned char Mmc_Init();

Returns  0 - if MMC/SD card was detected and successfully initialized


 1 - otherwise

Description Initializes MMC through hardware SPI interface.


Mmc_Init needs to be called before using other functions of this library.

www.raguvaran.puzl.com
Requires The appropriate hardware SPI module must be previously initialized.
Global variables :
 Mmc_Chip_Select: Chip Select line
 Mmc_Chip_Select_Direction: Direction of the Chip Select pin
must be defined before using this function.

Example // MMC module connections


sfr sbit Mmc_Chip_Select at RC0_bit;
sfr sbit Mmc_Chip_Select_Direction at TRISC0_bit;
// MMC module connections
...
SPI1_Init();

error = Mmc_Init(); // Init with CS line at RC0_bit

Mmc_Read_Sector

Prototype unsigned char Mmc_Read_Sector(unsigned long sector, char *dbuff);

Returns  0 - if reading was successful


 1 - if an error occurred

Description The function reads one sector (512 bytes) from MMC card.

Parameters:

 sector: MMC/SD card sector to be read.


 dbuff: buffer of minimum 512 bytes in length for data storage.

Requires MMC/SD card must be initialized. See Mmc_Init.

Example // read sector 510 of the MMC/SD card


unsigned int error;
unsigned long sectorNo = 510;
char dataBuffer[512];
...
error = Mmc_Read_Sector(sectorNo, dataBuffer);

Mmc_Write_Sector

Prototype unsigned char Mmc_Write_Sector(unsigned long sector, char *dbuff);

Returns  0 - if writing was successful


 1 - if there was an error in sending write command
 2 - if there was an error in writing (data rejected)

Description The function writes 512 bytes of data to one MMC card sector.

Parameters:

 sector: MMC/SD card sector to be written to.


 dbuff: data to be written (buffer of minimum 512 bytes in length).

www.raguvaran.puzl.com
Requires MMC/SD card must be initialized. See Mmc_Init.

Example // write to sector 510 of the MMC/SD card


unsigned int error;
unsigned long sectorNo = 510;
char dataBuffer[512];
...
error = Mmc_Write_Sector(sectorNo, dataBuffer);

Mmc_Read_Cid

Prototype unsigned char Mmc_Read_Cid(char *data_cid);

Returns  0 - if CID register was read successfully


 1 - if there was an error while reading

Description The function reads 16-byte CID register.

Parameters:

 data_cid: buffer of minimum 16 bytes in length for storing CID register content.

Requires MMC/SD card must be initialized. See Mmc_Init.

Example unsigned int error;


char dataBuffer[16];
...
error = Mmc_Read_Cid(dataBuffer);

Mmc_Read_Csd

Prototype unsigned char Mmc_Read_Csd(char *data_csd);

Returns  0 - if CSD register was read successfully


 1 - if there was an error while reading

Description The function reads 16-byte CSD register.

Parameters:

 data_csd: buffer of minimum 16 bytes in length for storing CSD register content.

Requires MMC/SD card must be initialized. See Mmc_Init.

Example unsigned int error;


char dataBuffer[16];
...
error = Mmc_Read_Csd(dataBuffer);

Mmc_Multi_Read_Start

www.raguvaran.puzl.com
Prototype unsigned int Mmc_Multi_Read_Start(unsigned long sector);

Description The function starts multi read mode, sectors are sequentially read starting from the sector given in the function
argument.

Parameters  sector: starting sector number.

Returns  0 - if multi read start was successful.


 1 - ir error occured.

Requires MMC/SD card must be initialized. See Mmc_Init.

Example unsigned int error;


char sector;
...
error = Mmc_Multi_Read_Start(sector);

Notes None.

Mmc_Multi_Read_Sector

Prototype void Mmc_Multi_Read_Sector(char *dbuff);

Description The function reads sectors in multi read mode and places them in the buffer given as the function argument. Next
function call reads the subsequent sector. Buffer size should be 512B.

Parameters  dbuff: buffer for holding the sector data.

Returns Nothing.

Requires MMC/SD card must be initialized. See Mmc_Init.

Example unsigned int error;


...
Mmc_Multi_Read_Sector(buffer);

Notes None.

Mmc_Multi_Read_Stop

Prototype unsigned int Mmc_Multi_Read_Stop();

www.raguvaran.puzl.com
Description The function stops multi read mode sequence.

Parameters None.

Returns  0 - if stop was successful.


 1 - ir error was detected.

Requires MMC/SD card must be initialized. See Mmc_Init.

Example Mmc_Multi_Read_Stop;

Notes None.

Mmc_Fat_Init

Prototype unsigned short Mmc_Fat_Init();

Returns  0 - if MMC/SD card was detected and successfully initialized


 1 - if FAT16 boot sector was not found
 255 - if MMC/SD card was not detected

Description Initializes MMC/SD card, reads MMC/SD FAT16 boot sector and extracts necessary data needed by the library.

Note : MMC/SD card has to be formatted to FAT16 file system.

Requires Global variables :


 Mmc_Chip_Select: Chip Select line
 Mmc_Chip_Select_Direction: Direction of the Chip Select pin
must be defined before using this function.
The appropriate hardware SPI module must be previously initialized. See
the SPI1_Init, SPI1_Init_Advanced routines.

Example // MMC module connections


sfr sbit Mmc_Chip_Select at RC0_bit;
sfr sbit Mmc_Chip_Select_Direction at TRISC0_bit;
// MMC module connections

// Initialize SPI1 module


SPI1_Init_Advanced(_SPI_MASTER_OSC_DIV64, _SPI_DATA_SAMPLE_MIDDLE,_SPI_CLK_IDLE_LOW,
_SPI_LOW_2_HIGH);

// use fat16 quick format instead of init routine if a formatting is needed


if (!Mmc_Fat_Init()) {
// reinitialize SPI1 at higher speed
SPI1_Init_Advanced(_SPI_MASTER_OSC_DIV4, _SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_LOW,
_SPI_LOW_2_HIGH);
...
}

Mmc_Fat_QuickFormat

www.raguvaran.puzl.com
Prototype unsigned char Mmc_Fat_QuickFormat(char *mmc_fat_label);

Returns  0 - if MMC/SD card was detected, successfully formated and initialized


 1 - if FAT16 format was unsuccessful
 255 - if MMC/SD card was not detected

Description Formats to FAT16 and initializes MMC/SD card.

Parameters:

 mmc_fat_label: volume label (11 characters in length). If less than 11 characters are provided,
the label will be padded with spaces. If null string is passed volume will not be labeled

Note :
 This routine can be used instead or in conjunction with Mmc_Fat_Init routine.
 If MMC/SD card already contains a valid boot sector, it will remain unchanged (except volume
label field) and only FAT and ROOT tables will be erased. Also, the new volume label will be set.

Requires The appropriate hardware SPI module must be previously initialized.

Example // Format and initialize MMC/SD card and MMC_FAT16 library globals
if (!Mmc_Fat_QuickFormat(&mmc_fat_label)) {
...
}

Mmc_Fat_Assign

Prototype unsigned short Mmc_Fat_Assign(char *filename, char file_cre_attr);

Returns  1 - if file already exists or file does not exist but a new file is created.
 0 - if file does not exist and no new file is created.

Description Assigns file for file operations (read, write, delete...). All subsequent file operations will be applied on an
assigned file.

Parameters:

 filename: name of the file that should be assigned for file operations. File name should be in
DOS 8.3 (file_name.extension) format. The file name and extension will be automatically padded
with spaces by the library if they have less than length required (i.e. "mikro.tx" -> "mikro .tx "), so
the user does not have to take care of that. The file name and extension are case insensitive. The
library will convert them to proper case automatically, so the user does not have to take care of
that.
 file_cre_attr: file creation and attributs flags. Each bit corresponds to the appropriate file
attribut:
Bit Mask Description

0 0x01 Read Only

1 0x02 Hidden

2 0x04 System

www.raguvaran.puzl.com
3 0x08 Volume Label

4 0x10 Subdirectory

5 0x20 Archive

6 0x40 Device (internal use only, never found on disk)

File creation flag. If file does not exist and this flag is set, a new file with
7 0x80
specified name will be created.

Note : Long File Names (LFN) are not supported.

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.

Example // create file with archive attribut if it does not already exist
Mmc_Fat_Assign("MIKRO007.TXT",0xA0);

Mmc_Fat_Reset

Prototype void Mmc_Fat_Reset(unsigned long *size);

Returns Nothing.

Description Procedure resets the file pointer (moves it to the start of the file) of the assigned file, so that the file can be read.

Parameters:

 size: buffer to store file size to. After file has been open for reading, its size is returned through
this parameter.

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
The file must be previously assigned. See Mmc_Fat_Assign.

Example unsigned long size;


...
Mmc_Fat_Reset(&size);

Mmc_Fat_Read

Prototype void Mmc_Fat_Read(unsigned short *bdata);

www.raguvaran.puzl.com
Returns Nothing.

Description Reads a byte from the currently assigned file opened for reading. Upon function execution, file pointers will be
set to the next character in the file.

Parameters:

 bdata: buffer to store read byte to. Upon this function execution read byte is returned through
this parameter.

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
The file must be previously assigned. See Mmc_Fat_Assign.
The file must be opened for reading. See Mmc_Fat_Reset.

Example char character;


...
Mmc_Fat_Read(&character);

Mmc_Fat_Rewrite

Prototype void Mmc_Fat_Rewrite();

Returns Nothing.

Description Opens the currently assigned file for writing. If the file is not empty its content will be erased.

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
The file must be previously assigned. See Mmc_Fat_Assign.

Example // open file for writing


Mmc_Fat_Rewrite();

Mmc_Fat_Append

Prototype void Mmc_Fat_Append();

Returns Nothing.

Description Opens the currently assigned file for appending. Upon this function execution file pointers will be positioned after
the last byte in the file, so any subsequent file write operation will start from there.

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
The file must be previously assigned. See Mmc_Fat_Assign.

Example // open file for appending


Mmc_Fat_Append();

www.raguvaran.puzl.com
Mmc_Fat_Delete

Prototype void Mmc_Fat_Delete();

Returns Nothing.

Description Deletes currently assigned file from MMC/SD card.

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
The file must be previously assigned. See Mmc_Fat_Assign.

Example // delete current file


Mmc_Fat_Delete();

Mmc_Fat_Write

Prototype void Mmc_Fat_Write(char *fdata, unsigned data_len);

Returns Nothing.

Description Writes requested number of bytes to the currently assigned file opened for writing.

Parameters:

 fdata: data to be written.


 data_len: number of bytes to be written.

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
The file must be previously assigned. See Mmc_Fat_Assign.
The file must be opened for writing. See Mmc_Fat_Rewrite or Mmc_Fat_Append.

Example Mmc_Fat_Write(txt,255);
Mmc_Fat_Write("Hello world",255);

Mmc_Fat_Set_File_Date

Prototype void Mmc_Fat_Set_File_Date(unsigned int year, unsigned short month, unsigned


short day, unsigned short hours, unsigned short mins, unsigned
shortseconds);

Returns Nothing.

Description Sets the date/time stamp. Any subsequent file write operation will write this stamp to the currently assigned file's
time/date attributs.

Parameters:

www.raguvaran.puzl.com
 year: year attribute. Valid values: 1980-2107
 month: month attribute. Valid values: 1-12
 day: day attribute. Valid values: 1-31
 hours: hours attribute. Valid values: 0-23
 mins: minutes attribute. Valid values: 0-59
 seconds: seconds attribute. Valid values: 0-59

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
The file must be previously assigned. See Mmc_Fat_Assign.
The file must be opened for writing. See Mmc_Fat_Rewrite or Mmc_Fat_Append.

Example // April 1st 2005, 18:07:00


Mmc_Fat_Set_File_Date(2005, 4, 1, 18, 7, 0);

Mmc_Fat_Get_File_Date

Prototype void Mmc_Fat_Get_File_Date(unsigned int *year, unsigned


short *month, unsigned short *day, unsigned short *hours, unsigned
short *mins);

Returns Nothing.

Description Reads time/date attributes of the currently assigned file.

Parameters:

 year: buffer to store year attribute to. Upon function execution year attribute is returned through
this parameter.
 month: buffer to store month attribute to. Upon function execution month attribute is returned
through this parameter.
 day: buffer to store day attribute to. Upon function execution day attribute is returned through
this parameter.
 hours: buffer to store hours attribute to. Upon function execution hours attribute is returned
through this parameter.
 mins: buffer to store minutes attribute to. Upon function execution minutes attribute is returned
through this parameter.

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
The file must be previously assigned. See Mmc_Fat_Assign.

Example // get Date/time of file


unsigned yr;
char mnth, dat, hrs, mins;
...
file_Name = "MYFILEABTXT";
Mmc_Fat_Assign(file_Name);
Mmc_Fat_Get_File_Date(&yr, &mnth, &day, &hrs, &mins);

Mmc_Fat_Get_File_Date_Modified

Prototype void Mmc_Fat_Get_File_Date_Modified(unsigned int *year, unsigned


short *month, unsigned short *day, unsigned short *hours, unsigned

www.raguvaran.puzl.com
short *mins);

Returns Nothing.

Description Retrieves the last modification date/time for the currently selected file.

Parameters:

 year: buffer to store year of modification attribute to. Upon function execution year of
modification attribute is returned through this parameter.
 month: buffer to store month of modification attribute to. Upon function execution month of
modification attribute is returned through this parameter.
 day: buffer to store day of modification attribute to. Upon function execution day of
modification attribute is returned through this parameter.
 hours: buffer to store hours of modification attribute to. Upon function execution hours of
modification attribute is returned through this parameter.
 mins: buffer to store minutes of modification attribute to. Upon function execution minutes of
modification attribute is returned through this parameter.

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
The file must be previously assigned. See Mmc_Fat_Assign.

Example // get modification Date/time of file


unsigned yr;
char mnth, dat, hrs, mins;
...
file_Name = "MYFILEABTXT";
Mmc_Fat_Assign(file_Name);
Mmc_Fat_Get_File_Date_Modified(&yr, &mnth, &day, &hrs, &mins);

Mmc_Fat_Get_File_Size

Prototype unsigned long Mmc_Fat_Get_File_Size();

Returns Size of the currently assigned file in bytes.

Description This function reads size of the currently assigned file in bytes.

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
The file must be previously assigned. See Mmc_Fat_Assign.

Example // get Date/time of file


unsigned yr;
char mnth, dat, hrs, mins;
...
file_name = "MYFILEXXTXT";
Mmc_Fat_Assign(file_name);
mmc_size = Mmc_Fat_Get_File_Size;

Mmc_Get_File_Write_Sector

www.raguvaran.puzl.com
Prototype unsigned long Mmc_Get_File_Write_Sector();

Description This function returns the current file write sector.

Parameters None.

Returns This function returns the current file write sector.

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
The file must be previously assigned. See Mmc_Fat_Assign.

Example unsigned long sector;


...
sector = Mmc_Get_File_Write_Sector();

Notes None.

Mmc_Fat_Get_Swap_File

Prototype unsigned long Mmc_Fat_Get_Swap_File(unsigned long sectors_cnt, char*


filename, char file_attr);

Returns  Number of the start sector for the newly created swap file, if there was enough free space on the
MMC/SD card to create file of required size.
 0 - otherwise.

Description This function is used to create a swap file of predefined name and size on the MMC/SD media. If a file with
specified name already exists on the media, search for consecutive sectors will ignore sectors occupied by this
file. Therefore, it is recommended to erase such file if it already exists before calling this function. If it is not
erased and there is still enough space for a new swap file, this function will delete it after allocating new memory
space for a new swap file.

The purpose of the swap file is to make reading and writing to MMC/SD media as fast as possible, by using
the Mmc_Read_Sector() and Mmc_Write_Sector() functions directly, without potentially damaging the FAT
system. The swap file can be considered as a "window" on the media where the user can freely write/read data. Its
main purpose in the library is to be used for fast data acquisition; when the time-critical acquisition has finished,
the data can be re-written into a "normal" file, and formatted in the most suitable way.
Parameters:

 sectors_cnt: number of consecutive sectors that user wants the swap file to have.
 filename: name of the file that should be assigned for file operations. File name should be in
DOS 8.3 (file_name.extension) format. The file name and extension will be automatically padded
with spaces by the library if they have less than length required (i.e. "mikro.tx" -> "mikro .tx "), so
the user does not have to take care of that. The file name and extension are case insensitive. The
library will convert them to proper case automatically, so the user does not have to take care of
that.

www.raguvaran.puzl.com
Also, in order to keep backward compatibility with the first version of this library, file names can
be entered as UPPERCASE string of 11 bytes in length with no dot character between file name
and extension (i.e. "MIKROELETXT" -> MIKROELE.TXT). In this case the last 3 characters of
the string are considered to be file extension.

 file_attr: file creation and attributs flags. Each bit corresponds to the appropriate file attribut:

Bit Mask Description

0 0x01 Read Only

1 0x02 Hidden

2 0x04 System

3 0x08 Volume Label

4 0x10 Subdirectory

5 0x20 Archive

6 0x40 Device (internal use only, never found on disk)

7 0x80 Not used

Note : Long File Names (LFN) are not supported.

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.

Example //-------------- Tries to create a swap file, whose size will be at least 100
sectors.
//If it succeeds, it sends the No. of start sector over UART
void M_Create_Swap_File(){
size = Mmc_Fat_Get_Swap_File(100);
if (size <> 0) {
UART1_Write(0xAA);
UART1_Write(Lo(size));
UART1_Write(Hi(size));
UART1_Write(Higher(size));
UART1_Write(Highest(size));
UART1_Write(0xAA);
}
}

Mmc_Fat_Tell

Prototype unsigned long Mmc_Fat_Tell();

Description This routine is used to retrieve the cursor position within an opened file.

Parameters None.

www.raguvaran.puzl.com
Returns Returns the cursor position in currently assigned file.

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
The file must be previously assigned. See Mmc_Fat_Assign.

Example unsigned long position;

position = Mmc_Fat_Tell();

Notes None.

Mmc_Fat_Seek

Prototype unsigned long Mmc_Fat_Seek(unsigned long position);

Description This routine is used to set the cursor position within an opened file and returns the cursor's new position within an
opened file.

Parameters  position: desired position on which we want to place the cursor.

Returns Returns the cursor's new position in currently assigned file.

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
The file must be previously assigned. See Mmc_Fat_Assign.

Example unsigned long position;

position = Mmc_Fat_Seek(1000);

Notes If the desired cursor position exceeds file size, the cursor will be placed at the end of the file.

Mmc_Fat_Rename

Prototype char Mmc_Fat_Rename(char *newname);

Description This function renames the currently assigned file.

Parameters  newname: new file name.

Returns  0 - if renaming was successful


 255 - if an error occurred

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
The file must be previously assigned. See Mmc_Fat_Assign.

www.raguvaran.puzl.com
Example if (0 == Mmc_Fat_Rename("NEWNAME.TXT")) { // if rename operation was successful...
...
}

Notes None.

Mmc_Fat_MakeDir

Prototype char Mmc_Fat_MakeDir(char *name, char attrib);

Description This function creates a new directory.

Parameters  name: directory name.


 attrib: directory attribute.

Returns  0 - directory creation was successful


 255 - if an error occurred

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.

Example if (0 == Mmc_Fat_MakeDir("DIR_A")) { // create DIR_A directory


...
}

Notes None.

Mmc_Fat_RenameDir

Prototype char Mmc_Fat_RenameDir(char *oldname, char *newname);

Description This function renames a directory.

Parameters  oldname: old directory name.


 newname: new directory name.

Returns  0 - if renaming was successful


 255 - if an error occurred

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.

Example if (0 == Mmc_Fat_RenameDir("DIR_A", "DIR_B")) { // if rename operation was


successful...
...
}

Notes None.

www.raguvaran.puzl.com
Mmc_Fat_RemoveDir

Prototype char Mmc_Fat_RemoveDir(char *name);

Description This function removes a directory from the current directory.

Parameters  name: directory name.

Returns  0 - if removing was successful


 255 - if an error occurred

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.

Example if (0 == Mmc_Fat_RemoveDir("DIR_A")) { // if removing operation was successful...


...
}

Notes Recursive removing is not supported, i.e. the directory must be empty before it can be removed.

Mmc_Fat_ChangeDir

Prototype char Mmc_Fat_ChangeDir(char *name);

Description This function changes the current directory to name.

Parameters  name: directory name.

Returns  0 - if directory change was successful


 255 - if an error occurred

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.

Example // enter DIR_A directory


if (0 == Mmc_Fat_ChangeDir("DIR_A")) {
...
}

// go to parent directory
if (0 == Mmc_Fat_ChangeDir("..")) {
...
}

// go to root directory
if (0 == Mmc_Fat_ChangeDir("\")) {
...
}

Notes Special directory names like "." and ".." are also supported.

www.raguvaran.puzl.com
Mmc_Fat_Exists

Prototype char Mmc_Fat_Exists(char *name);

Description This function returns information on file/directory existence.

Parameters  name: file/directory name.

Returns  0 - if process was successful


 255 - if an error occurred

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.

Example status = Mmc_Fat_Exists("X_FILES.TXT");

if (1 == status) { ... } // if the file was found...

else if (0 == status) { ... } // or if the file was not found...

else { ... } // or if there was an error during function call,


// which needs to be handled separately.

Notes None.

Mmc_Fat_Dir

Prototype char Mmc_Fat_Dir(void (*print)(char ch))

Description This routine displays contents of the current directory via user-defined medium (i.e. UART module, a file on
FAT16 file system). The function displays character by character.

Parameters  ch: function pointer to a routine which will display contents of the current directory.

Returns This routine will return the basic information on files/directories in the current directory.

Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.

Example // Displaying routine


void PrintChar(char ch) {
UART1_Write(ch);
}

...

Mmc_Fat_Dir(PrintChar);

Notes None.

www.raguvaran.puzl.com
Library Example
The following example demonstrates MMC library test. Upon flashing, insert a MMC/SD card into the
module, when you should receive the "Init-OK" message. Then, you can experiment with MMC read and
write functions, and observe the results through the Usart Terminal.

Copy Code To Clipboard

// MMC module connections


sbit Mmc_Chip_Select at LATC0_bit; // for writing to output pin always use latch (PIC18
family)
sbit Mmc_Chip_Select_Direction at TRISC0_bit;
// eof MMC module connections

const LINE_LEN = 43;


char err_txt[20] = "FAT16 not found";
char file_contents[LINE_LEN] = "XX MMC/SD FAT16 library by Anton Rieckertn";
char filename[14] = "MIKRO00x.TXT"; // File names
unsigned short loop, loop2;
unsigned long i, size;
char Buffer[512];

// UART1 write text and new line (carriage return + line feed)
void UART1_Write_Line(char *uart_text) {
UART1_Write_Text(uart_text);
UART1_Write(13);
UART1_Write(10);
}

// Creates new file and writes some data to it


void M_Create_New_File() {
filename[7] = 'A';
Mmc_Fat_Set_File_Date(2010, 4, 19, 9, 0, 0); // Set file date & time info
Mmc_Fat_Assign(&filename, 0xA0); // Find existing file or create a new one
Mmc_Fat_Rewrite(); // To clear file and start with new data
for(loop = 1; loop <= 99; loop++) {
UART1_Write('.');
file_contents[0] = loop / 10 + 48;
file_contents[1] = loop % 10 + 48;
Mmc_Fat_Write(file_contents, LINE_LEN-1); // write data to the assigned file
}
}

// Creates many new files and writes data to them


void M_Create_Multiple_Files() {
for(loop2 = 'B'; loop2 <= 'Z'; loop2++) {
UART1_Write(loop2); // signal the progress
filename[7] = loop2; // set filename
Mmc_Fat_Set_File_Date(2010, 4, 19, 9, 0, 0); // Set file date & time info
Mmc_Fat_Assign(&filename, 0xA0); // find existing file or create a new one
Mmc_Fat_Rewrite(); // To clear file and start with new data
for(loop = 1; loop <= 44; loop++) {
file_contents[0] = loop / 10 + 48;
file_contents[1] = loop % 10 + 48;
Mmc_Fat_Write(file_contents, LINE_LEN-1); // write data to the assigned file
}
}
}

// Opens an existing file and rewrites it


void M_Open_File_Rewrite() {
filename[7] = 'C';
Mmc_Fat_Assign(&filename, 0);
Mmc_Fat_Rewrite();
for(loop = 1; loop <= 55; loop++) {
file_contents[0] = loop / 10 + 48;

www.raguvaran.puzl.com
file_contents[1] = loop % 10 + 48;
Mmc_Fat_Write(file_contents, LINE_LEN-1); // write data to the assigned file
}
}

// Opens an existing file and appends data to it


// (and alters the date/time stamp)
void M_Open_File_Append() {
filename[7] = 'B';
Mmc_Fat_Assign(&filename, 0);
Mmc_Fat_Set_File_Date(2010, 4, 19, 9, 20, 0);
Mmc_Fat_Append(); // Prepare file for append
Mmc_Fat_Write(" for mikroElektronika 2010n", 27); // Write data to assigned file
}

// Opens an existing file, reads data from it and puts it to UART


void M_Open_File_Read() {
char character;

filename[7] = 'B';
Mmc_Fat_Assign(&filename, 0);
Mmc_Fat_Reset(&size); // To read file, procedure returns size of file
for (i = 1; i <= size; i++) {
Mmc_Fat_Read(&character);
UART1_Write(character); // Write data to UART
}
}

// Deletes a file. If file doesn't exist, it will first be created


// and then deleted.
void M_Delete_File() {
filename[7] = 'F';
Mmc_Fat_Assign(filename, 0);
Mmc_Fat_Delete();
}

// Tests whether file exists, and if so sends its creation date


// and file size via UART
void M_Test_File_Exist() {
unsigned long fsize;
unsigned int year;
unsigned short month, day, hour, minute;
unsigned char outstr[12];

filename[7] = 'B'; //uncomment this line to search for file that DOES exists
// filename[7] = 'F'; //uncomment this line to search for file that DOES NOT exist
if (Mmc_Fat_Assign(filename, 0)) {
//--- file has been found - get its create date
Mmc_Fat_Get_File_Date(&year, &month, &day, &hour, &minute);
UART1_Write_Text(" created: ");
WordToStr(year, outstr);
UART1_Write_Text(outstr);
ByteToStr(month, outstr);
UART1_Write_Text(outstr);
WordToStr(day, outstr);
UART1_Write_Text(outstr);
WordToStr(hour, outstr);
UART1_Write_Text(outstr);
WordToStr(minute, outstr);
UART1_Write_Text(outstr);

//--- file has been found - get its modified date


Mmc_Fat_Get_File_Date_Modified(&year, &month, &day, &hour, &minute);
UART1_Write_Text(" modified: ");
WordToStr(year, outstr);
UART1_Write_Text(outstr);
ByteToStr(month, outstr);

www.raguvaran.puzl.com
UART1_Write_Text(outstr);
WordToStr(day, outstr);
UART1_Write_Text(outstr);
WordToStr(hour, outstr);
UART1_Write_Text(outstr);
WordToStr(minute, outstr);
UART1_Write_Text(outstr);

//--- get file size


fsize = Mmc_Fat_Get_File_Size();
LongToStr((signed long)fsize, outstr);
UART1_Write_Line(outstr);
}
else {
//--- file was not found - signal it
UART1_Write(0x55);
Delay_ms(1000);
UART1_Write(0x55);
}
}

// Tries to create a swap file, whose size will be at least 100


// sectors (see Help for details)
void M_Create_Swap_File() {
unsigned int i;

for(i=0; i<512; i++)


Buffer[i] = i;

size = Mmc_Fat_Get_Swap_File(5000, "mikroE.txt", 0x20); // see help on this function for


details

if (size) {
LongToStr((signed long)size, err_txt);
UART1_Write_Line(err_txt);

for(i=0; i<5000; i++) {


Mmc_Write_Sector(size++, Buffer);
UART1_Write('.');
}
}
}

// Main. Uncomment the function(s) to test the desired operation(s)


void main() {
#define COMPLETE_EXAMPLE // comment this line to make simpler/smaller example
ADCON1 |= 0x0F; // Configure AN pins as digital
CMCON |= 7; // Turn off comparators

// Initialize UART1 module


UART1_Init(19200);
Delay_ms(10);

UART1_Write_Line("PIC-Started"); // PIC present report

// Initialize SPI1 module


SPI1_Init_Advanced(_SPI_MASTER_OSC_DIV64, _SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_LOW,
_SPI_LOW_2_HIGH);

// use fat16 quick format instead of init routine if a formatting is needed


if (Mmc_Fat_Init() == 0) {
// reinitialize spi at higher speed
SPI1_Init_Advanced(_SPI_MASTER_OSC_DIV4, _SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_LOW,
_SPI_LOW_2_HIGH);
//--- Test start
UART1_Write_Line("Test Start.");

www.raguvaran.puzl.com
//--- Test routines. Uncomment them one-by-one to test certain features
M_Create_New_File();
#ifdef COMPLETE_EXAMPLE
M_Create_Multiple_Files();
M_Open_File_Rewrite();
M_Open_File_Append();
M_Open_File_Read();
M_Delete_File();
M_Test_File_Exist();
M_Create_Swap_File();
#endif
UART1_Write_Line("Test End.");

}
else {
UART1_Write_Line(err_txt); // Note: Mmc_Fat_Init tries to initialize a card more than once.
// If card is not present, initialization may last longer
(depending on clock speed)
}

HW Connection

MMC interface

www.raguvaran.puzl.com
OneWire Library
The OneWire library provides routines for communication via the Dallas OneWire protocol, e.g. with
DS18x20 digital thermometer. OneWire is a Master/Slave protocol, and all communication cabling
required is a single wire. OneWire enabled devices should have open collector drivers (with single pull-up
resistor) on the shared data line.

Slave devices on the OneWire bus can even get their power supply from data line. For detailed
schematic see device datasheet.

Some basic characteristics of this protocol are:

 single master system,


 low cost,
 low transfer rates (up to 16 kbps),
 fairly long distances (up to 300 meters),
 small data transfer packages.

Each OneWire device also has a unique 64-bit registration number (8-bit device type, 48-bit serial
number and 8-bit CRC), so multiple slaves can co-exist on the same bus.

Important :
 Oscillator frequency Fosc needs to be at least 4MHz in order to use the routines with Dallas
digital thermometers.
 This library implements time-based activities, so interrupts need to be disabled when using
OneWire library.

Library Routines
 Ow_Reset
 Ow_Read
 Ow_Write

Ow_Reset

Prototype unsigned short Ow_Reset(unsigned short *port, unsigned short pin);

www.raguvaran.puzl.com
Returns  0 if the device is present
 1 if the device is not present

Description Issues OneWire reset signal for DS18x20.

Parameters :

 port: OneWire bus port


 pin: OneWire bus pin

Requires Devices compliant with the Dallas OneWire protocol.

Example To reset the DS1820 that is connected to the RE2 pin:

Ow_Reset(&PORTE, 2);

Ow_Read

Prototype unsigned short Ow_Read(unsigned short *port, unsigned short pin);

Returns Data read from an external device over the OneWire bus.

Description Reads one byte of data via the OneWire bus.

Parameters :

 port: OneWire bus port


 pin: OneWire bus pin

Requires Devices compliant with the Dallas OneWire protocol.

Example // Read a byte from the One-Wire Bus


unsigned short tmp;
...
tmp = Ow_Read(&PORTE, 2);

Ow_Write

Prototype void Ow_Write(unsigned short *port, unsigned short pin, unsigned short par);

Returns Nothing.

Description Writes one byte of data via the OneWire bus.

Parameters :

www.raguvaran.puzl.com
 port: OneWire bus port
 pin: OneWire bus pin
 par: data to be written

Requires Devices compliant with the Dallas OneWire protocol.

Example // Send a byte to the One-Wire Bus


Ow_Write(&PORTE, 2, 0xCC);

Library Example
This example reads the temperature using DS18x20 connected to pin PORTE.B2. After reset, MCU
obtains temperature from the sensor and prints it on the Lcd. Make sure to pull-up PORTE.B2 line and to
turn off the PORTE LEDs.

Copy Code To Clipboard

// LCD module connections


sbit LCD_RS at RB4_bit;
sbit LCD_EN at RB5_bit;
sbit LCD_D4 at RB0_bit;
sbit LCD_D5 at RB1_bit;
sbit LCD_D6 at RB2_bit;
sbit LCD_D7 at RB3_bit;

sbit LCD_RS_Direction at TRISB4_bit;


sbit LCD_EN_Direction at TRISB5_bit;
sbit LCD_D4_Direction at TRISB0_bit;
sbit LCD_D5_Direction at TRISB1_bit;
sbit LCD_D6_Direction at TRISB2_bit;
sbit LCD_D7_Direction at TRISB3_bit;
// End LCD module connections

// Set TEMP_RESOLUTION to the corresponding resolution of used DS18x20 sensor:


// 18S20: 9 (default setting; can be 9,10,11,or 12)
// 18B20: 12
const unsigned short TEMP_RESOLUTION = 9;

char *text = "000.0000";


unsigned temp;

void Display_Temperature(unsigned int temp2write) {


const unsigned short RES_SHIFT = TEMP_RESOLUTION - 8;
char temp_whole;
unsigned int temp_fraction;

// Check if temperature is negative


if (temp2write & 0x8000) {
text[0] = '-';
temp2write = ~temp2write + 1;
}

// Extract temp_whole
temp_whole = temp2write >> RES_SHIFT ;

// Convert temp_whole to characters


if (temp_whole/100)

www.raguvaran.puzl.com
text[0] = temp_whole/100 + 48;
else
text[0] = '0';

text[1] = (temp_whole/10)%10 + 48; // Extract tens digit


text[2] = temp_whole%10 + 48; // Extract ones digit

// Extract temp_fraction and convert it to unsigned int


temp_fraction = temp2write << (4-RES_SHIFT);
temp_fraction &= 0x000F;
temp_fraction *= 625;

// Convert temp_fraction to characters


text[4] = temp_fraction/1000 + 48; // Extract thousands digit
text[5] = (temp_fraction/100)%10 + 48; // Extract hundreds digit
text[6] = (temp_fraction/10)%10 + 48; // Extract tens digit
text[7] = temp_fraction%10 + 48; // Extract ones digit

// Print temperature on LCD


Lcd_Out(2, 5, text);
}

void main() {
ANSEL = 0; // Configure AN pins as digital I/O
ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;

Lcd_Init(); // Initialize LCD


Lcd_Cmd(_LCD_CLEAR); // Clear LCD
Lcd_Cmd(_LCD_CURSOR_OFF); // Turn cursor off
Lcd_Out(1, 1, " Temperature: ");
// Print degree character, 'C' for Centigrades
Lcd_Chr(2,13,223); // Different LCD displays have different char
code for degree
// If you see greek alpha letter try typing 178
instead of 223

Lcd_Chr(2,14,'C');

//--- Main loop


do {
//--- Perform temperature reading
Ow_Reset(&PORTE, 2); // Onewire reset signal
Ow_Write(&PORTE, 2, 0xCC); // Issue command SKIP_ROM
Ow_Write(&PORTE, 2, 0x44); // Issue command CONVERT_T
Delay_us(120);

Ow_Reset(&PORTE, 2);
Ow_Write(&PORTE, 2, 0xCC); // Issue command SKIP_ROM
Ow_Write(&PORTE, 2, 0xBE); // Issue command READ_SCRATCHPAD

temp = Ow_Read(&PORTE, 2);


temp = (Ow_Read(&PORTE, 2) << 8) + temp;

//--- Format and display result on Lcd


Display_Temperature(temp);

Delay_ms(500);
} while (1);
}

www.raguvaran.puzl.com
HW Connection

www.raguvaran.puzl.com
Example of DS1820 connection

Peripheral Pin Select Library

www.raguvaran.puzl.com
Peripheral Pin Select Library allows remapping of peripherals on the following MCU's: 18F2xJ11,
18F4xJ11, 18F2xJ50 and 18F4xJ50.

A key difference between pin select and non-pin select peripherals is that pin select peripherals are not
associated with a default I/O pin.
The peripheral must always be assigned to a specific I/O pin before it can be used. In contrast, non pin
selectable peripherals are always available on a default pin, assuming that the peripheral is active and
not conflicting with another peripheral.

Library Routines
 Unlock_IOLOCK
 Lock_IOLOCK
 PPS_Mapping
 PPS_Mapping_NoLock

Unlock_IOLOCK

Prototype void Unlock_IOLOCK();

Returns Nothing.

Description Unlocks I/O pins for Peripheral Pin Mapping.

Requires Nothing.

Example Unlock_IOLOCK();

Lock_IOLOCK

Prototype void Lock_IOLOCK();

Returns Nothing.

Description Locks I/O pins for Peripheral Pin Mapping.

Requires Nothing.

Example Lock_IOLOCK();

www.raguvaran.puzl.com
PPS_Mapping

Prototype char PPS_Mapping(char rp_num, char input_output, char funct_name);

Returns  0 - if peripheral pin mapping wasn't successful.


 255 - if peripheral pin mapping was successful.

Description Sets desired internal MCU module to be mapped with the requested pins.

Parameters :

 rp_num: Remappable pin number. Consult the appropriate datasheet for adequate values.
 input_output: Sets requested pin to be used as an input or output.
 funct_name: Selects internal MCU module for usage.

Requires Nothing.

Example PPS_Mapping(15, _INPUT, _RX2_DT2); // Sets pin 15 to be Input, and maps RX2/DT2
Input to it
PPS_Mapping(5, _OUTPUT, _TX2_CK2); // Sets pin 5 to be Output, and maps EUSART2
Asynchronous Transmit/Synchronous Clock Output to it

PPS_Mapping_NoLock

Prototype char PPS_Mapping_NoLock(char rp_num, char input_output, char funct_name);

Returns  0 - if peripheral pin mapping wasn't successful.


 255 - if peripheral pin mapping was successful.

Description Sets desired internal MCU module to be mapped on the requested pins.

This function doesn't use Unlock_IOLOCK and Lock_IOLOCK routines, so the user must call them before and
after this function call (very useful if IOL1WAY bit is set, when after one lock sequence it is not possible to unlock
it).
Parameters :

 rp_num: Remappable pin number. Consult the appropriate datasheet for adequate values.
 input_output: Sets requested pin to be used as an input or output.
 funct_name: Selects internal MCU module for usage.

Parameters

Requires Nothing.

Example Unlock_IOLOCK()

PPS_Mapping_NoLock(15, _INPUT, _RX2_DT2); // Sets pin 15 to be Input, and maps


RX2/DT2 Input to it

www.raguvaran.puzl.com
PPS_Mapping_NoLock(5, _OUTPUT, _TX2_CK2); // Sets pin 5 to be Output, and maps
EUSART2 Asynchronous Transmit/Synchronous Clock Output to it

Lock_IOLOCK()

Available Parameters

Function Name (Input) Description

_INT1 External Interrupt 1

_INT2 External Interrupt 2

_INT3 External Interrupt 3

_T0CKI Timer0 External Clock Input

_T3CKI Timer3 External Clock Input

_CCP1 Input Capture 1

_CCP2 Input Capture 2

_T1G Timer1 Gate Input

_T3G Timer3 Gate Input

_RX2_DT2 RX2/DT2 Input

_CK2 EUSART2 Synchronous Clock Input

_SDI2 SPI2 Data Input

_SCK2IN SPI2 Clock Input

_SS2IN SPI2 Slave Select Input

_FLT0 PWM Fault Input

Function Name (Output) Description

_NULL The NULL function is assigned to all RPn outputs at device Reset and disables the RPn output function.

_C1OUT Comparator 1 Output

www.raguvaran.puzl.com
Function Name (Input) Description

_C2OUT Comparator 2 Output

_TX2_CK2 EUSART2 Asynchronous Transmit/Synchronous Clock Output

_DT2 EUSART2 Synchronous Transmit

_SDO2 SPI2 Data Output

_SCK2 SPI2 Clock Output

_SSDMA SPI DMA Slave Select

_ULPOUT Ultra Low-Power Wake-up Event

_CCP1_P1A ECCP1 Compare or PWM Output Channel A

_P1B ECCP1 Enhanced PWM Output, Channel B

_P1C ECCP1 Enhanced PWM Output, Channel C

_P1D ECCP1 Enhanced PWM Output, Channel D

_CCP2_P2A ECCP2 Compare or PWM Output

_P2B ECCP2 Enhanced PWM Output, Channel B

_P2C ECCP2 Enhanced PWM Output, Channel C

_P2D ECCP2 Enhanced PWM Output, Channel D

Input/Output Parameter Description

_INPUT Sets selected pin as input

_OUTPUT Sets selected pin as output

www.raguvaran.puzl.com
Port Expander Library
The mikroC PRO for PIC provides a library for communication with the Microchip’s Port Expander
MCP23S17 via SPI interface. Connections of the PIC compliant MCU and MCP23S17 is given on the
schematic at the bottom of this page.
Important :
 The library uses the SPI module for communication. User must initialize the appropriate SPI
module before using the Port Expander Library.
 Library does not use Port Expander interrupts.

Library Dependency Tree

External dependencies of Port Expander Library


The following variables must be
Description
defined in all projects using Port Example :
:
Expander Library:
extern sfr
Reset line. sbit SPExpanderRST at RC0_bit;
sbit SPExpanderRST;

extern sfr sbit SPExpanderCS;


Chip Select sbit SPExpanderCS at RC1_bit;
line.
Direction of
extern sfr
the Reset sbit SPExpanderRST_Direction atTRISC0_bit;
sbit SPExpanderRST_Direction;
pin.
Direction of
extern sfr
the Chip sbit SPExpanderCS_Direction atTRISC1_bit;
sbit SPExpanderCS_Direction;
Select pin.

Library Routines
 Expander_Init
 Expander_Init_Advanced
 Expander_Read_Byte
 Expander_Write_Byte
 Expander_Read_PortA
 Expander_Read_PortB
 Expander_Read_PortAB
 Expander_Write_PortA
 Expander_Write_PortB
 Expander_Write_PortAB
 Expander_Set_DirectionPortA
 Expander_Set_DirectionPortB
 Expander_Set_DirectionPortAB
 Expander_Set_PullUpsPortA
 Expander_Set_PullUpsPortB
 Expander_Set_PullUpsPortAB

www.raguvaran.puzl.com
Expander_Init

Prototype void Expander_Init(char ModuleAddress);

Returns Nothing.

Description Initializes Port Expander using SPI communication.

Port Expander module settings :

 hardware addressing enabled


 automatic address pointer incrementing disabled (byte mode)
 BANK_0 register adressing
 slew rate enabled
Parameters :

 ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page

Requires Global variables :


 SPExpanderCS: Chip Select line
 SPExpanderRST: Reset line
 SPExpanderCS_Direction: Direction of the Chip Select pin
 SPExpanderRST_Direction: Direction of the Reset pin
must be defined before using this function.

SPI module needs to be initialized. See SPIx_Init and SPIx_Init_Advanced routines.

Example // Port Expander module connections


sbit SPExpanderRST at RC0_bit;
sbit SPExpanderCS at RC1_bit;
sbit SPExpanderRST_Direction at TRISC0_bit;
sbit SPExpanderCS_Direction at TRISC1_bit;
// End Port Expander module connections

...

ANSEL = 0; // Configure AN pins as digital I/O


ANSELH = 0;

// If Port Expander Library uses SPI module


SPI1_Init(); // Initialize SPI module used with PortExpander
Expander_Init(0); // Initialize Port Expander

Expander_Init_Advanced

Prototype void Expander_Init_Advanced(char *rstPort, char rstPin, char haen);

Returns Nothing.

Description Initializes Port Expander using SPI communication.

Parameters :

www.raguvaran.puzl.com
 rstPort: Port Expander's reset port
 rstPin: Port Expander's reset pin
 haen: Enable hardware addressing. Valid values :
 0 - hardware addressing disabled
 1 - hardware addressing enabled

Requires  SPExpanderCS: Chip Select line


 SPExpanderRST: Reset line
 SPExpanderCS_Direction: Direction of the Chip Select pin
 SPExpanderRST_Direction: Direction of the Reset pin
must be defined before using this function.

SPI module needs to be initialized. See SPIx_Init and SPIx_Init_Advanced routines.

Example // Port Expander module connections


sbit SPExpanderRST at RC0_bit;
sbit SPExpanderCS at RC1_bit;
sbit SPExpanderRST_Direction at TRISC0_bit;
sbit SPExpanderCS_Direction at TRISC1_bit;
// End Port Expander module connections

...

ANSEL = 0; // Configure AN pins as digital I/O


ANSELH = 0;

// If Port Expander Library uses SPI module


SPI1_Init(); // Initialize SPI module used with PortExpander
Expander_Init_Advanced(&PORTB, 0, 0); // Initialize Port Expander

Expander_Read_Byte

Prototype char Expander_Read_Byte(char ModuleAddress, char RegAddress);

Returns Byte read.

Description The function reads byte from Port Expander.

Parameters :

 ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
 RegAddress: Port Expander's internal register address

Requires Port Expander must be initialized. See Expander_Init.

Example // Read a byte from Port Expander's register


char read_data;
...
read_data = Expander_Read_Byte(0,1);

www.raguvaran.puzl.com
Expander_Write_Byte

Prototype void Expander_Write_Byte(char ModuleAddress, char RegAddress, char Data);

Returns Nothing.

Description Routine writes a byte to Port Expander.

Parameters :

 ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
 RegAddress: Port Expander's internal register address
 Data_: data to be written

Requires Port Expander must be initialized. See Expander_Init.

Example // Write a byte to the Port Expander's register


Expander_Write_Byte(0,1,0xFF);

Expander_Read_PortA

Prototype char Expander_Read_PortA(char ModuleAddress);

Returns Byte read.

Description The function reads byte from Port Expander's PortA.

Parameters :

 ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page

Requires Port Expander must be initialized. See Expander_Init.


Port Expander's PortA should be configured as input.
See Expander_Set_DirectionPortA and Expander_Set_DirectionPortAB routines.

Example // Read a byte from Port Expander's PORTA


char read_data;
...
Expander_Set_DirectionPortA(0,0xFF); // set expander's porta to be input
...
read_data = Expander_Read_PortA(0);

Expander_Read_PortB

Prototype char Expander_Read_PortB(char ModuleAddress);

Returns Byte read.

www.raguvaran.puzl.com
Description The function reads byte from Port Expander's PortB.

Parameters :

 ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page

Requires Port Expander must be initialized. See Expander_Init.


Port Expander's PortB should be configured as input.
See Expander_Set_DirectionPortB and Expander_Set_DirectionPortAB routines.

Example // Read a byte from Port Expander's PORTB


char read_data;
...
Expander_Set_DirectionPortB(0,0xFF); // set expander's portb to be input
...
read_data = Expander_Read_PortB(0);

Expander_Read_PortAB

Prototype unsigned int Expander_Read_PortAB(char ModuleAddress);

Returns Word read.

Description The function reads word from Port Expander's ports. PortA readings are in the higher byte of the result. PortB
readings are in the lower byte of the result.

Parameters :

 ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page

Requires Port Expander must be initialized. See Expander_Init.


Port Expander's PortA and PortB should be configured as inputs.
See Expander_Set_DirectionPortA, Expander_Set_DirectionPortB and Expander_Set_DirectionPortAB routines.

Example // Read a byte from Port Expander's PORTA and PORTB


unsigned int read_data;
...
Expander_Set_DirectionPortAB(0,0xFFFF); // set expander's porta and portb to
be input
...
read_data = Expander_Read_PortAB(0);

Expander_Write_PortA

Prototype void Expander_Write_PortA(char ModuleAddress, char Data_);

Returns Nothing.

Description The function writes byte to Port Expander's PortA.

www.raguvaran.puzl.com
Parameters :

 ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
 Data_: data to be written

Requires Port Expander must be initialized. See Expander_Init.


Port Expander's PortA should be configured as output.
See Expander_Set_DirectionPortA and Expander_Set_DirectionPortAB routines.

Example // Write a byte to Port Expander's PORTA

...
Expander_Set_DirectionPortA(0,0x00); // set expander's porta to be output
...
Expander_Write_PortA(0, 0xAA);

Expander_Write_PortB

Prototype void Expander_Write_PortB(char ModuleAddress, char Data_);

Returns Nothing.

Description The function writes byte to Port Expander's PortB.

Parameters :

 ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
 Data_: data to be written

Requires Port Expander must be initialized. See Expander_Init.


Port Expander's PortB should be configured as output.
See Expander_Set_DirectionPortB and Expander_Set_DirectionPortAB routines.

Example // Write a byte to Port Expander's PORTB

...
Expander_Set_DirectionPortB(0,0x00); // set expander's portb to be output
...
Expander_Write_PortB(0, 0x55);

Expander_Write_PortAB

Prototype void Expander_Write_PortAB(char ModuleAddress, unsigned int Data_);

Returns Nothing.

Description The function writes word to Port Expander's ports.

Parameters :

www.raguvaran.puzl.com
 ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
 Data_: data to be written. Data to be written to PortA are passed in Data's higher byte. Data to
be written to PortB are passed in Data's lower byte

Requires Port Expander must be initialized. See Expander_Init.


Port Expander's PortA and PortB should be configured as outputs.
See Expander_Set_DirectionPortA, Expander_Set_DirectionPortB and Expander_Set_DirectionPortAB routines.

Example // Write a byte to Port Expander's PORTA and PORTB

...
Expander_Set_DirectionPortAB(0,0x0000); // set expander's porta and portb to
be output
...
Expander_Write_PortAB(0, 0xAA55);

Expander_Set_DirectionPortA

Prototype void Expander_Set_DirectionPortA(char ModuleAddress, char Data_);

Returns Nothing.

Description The function sets Port Expander's PortA direction.

Parameters :

 ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
 Data_: data to be written to the PortA direction register. Each bit corresponds to the appropriate
pin of the PortA register. Set bit designates corresponding pin as input. Cleared bit designates
corresponding pin as output.

Requires Port Expander must be initialized. See Expander_Init.

Example // Set Port Expander's PORTA to be output


Expander_Set_DirectionPortA(0,0x00);

Expander_Set_DirectionPortB

Prototype void Expander_Set_DirectionPortB(char ModuleAddress, char Data_);

Returns Nothing.

Description The function sets Port Expander's PortB direction.

Parameters :

 ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
 Data_: data to be written to the PortB direction register. Each bit corresponds to the appropriate
pin of the PortB register. Set bit designates corresponding pin as input. Cleared bit designates
corresponding pin as output.

www.raguvaran.puzl.com
Requires Port Expander must be initialized. See Expander_Init.

Example // Set Port Expander's PORTB to be input


Expander_Set_DirectionPortB(0,0xFF);

Expander_Set_DirectionPortAB

Prototype void Expander_Set_DirectionPortAB(char ModuleAddress, unsigned


int Direction);

Returns Nothing.

Description The function sets Port Expander's PortA and PortB direction.

Parameters :

 ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
 Direction: data to be written to direction registers. Data to be written to the PortA direction
register are passed in Direction's higher byte. Data to be written to the PortB direction register
are passed in Direction's lower byte. Each bit corresponds to the appropriate pin of the
PortA/PortB register. Set bit designates corresponding pin as input. Cleared bit designates
corresponding pin as output.

Requires Port Expander must be initialized. See Expander_Init.

Example // Set Port Expander's PORTA to be output and PORTB to be input


Expander_Set_DirectionPortAB(0,0x00FF);

Expander_Set_PullUpsPortA

Prototype void Expander_Set_PullUpsPortA(char ModuleAddress, char Data_);

Returns Nothing.

Description The function sets Port Expander's PortA pull up/down resistors.

Parameters :

 ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
 Data_: data for choosing pull up/down resistors configuration. Each bit corresponds to the
appropriate pin of the PortA register. Set bit enables pull-up for corresponding pin.

Requires Port Expander must be initialized. See Expander_Init.

Example // Set Port Expander's PORTA pull-up resistors


Expander_Set_PullUpsPortA(0, 0xFF);

www.raguvaran.puzl.com
Expander_Set_PullUpsPortB

Prototype void Expander_Set_PullUpsPortB(char ModuleAddress, char Data_);

Returns Nothing.

Description The function sets Port Expander's PortB pull up/down resistors.

Parameters :

 ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
 Data_: data for choosing pull up/down resistors configuration. Each bit corresponds to the
appropriate pin of the PortB register. Set bit enables pull-up for corresponding pin.

Requires Port Expander must be initialized. See Expander_Init.

Example // Set Port Expander's PORTB pull-up resistors


Expander_Set_PullUpsPortB(0, 0xFF);

Expander_Set_PullUpsPortAB

Prototype void Expander_Set_PullUpsPortAB(char ModuleAddress, unsigned int PullUps);

Returns Nothing.

Description The function sets Port Expander's PortA and PortB pull up/down resistors.

Parameters :

 ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
 PullUps: data for choosing pull up/down resistors configuration. PortA pull up/down resistors
configuration is passed in PullUps's higher byte. PortB pull up/down resistors configuration is
passed in PullUps's lower byte. Each bit corresponds to the appropriate pin of the PortA/PortB
register. Set bit enables pull-up for corresponding pin.

Requires Port Expander must be initialized. See Expander_Init.

Example // Set Port Expander's PORTA and PORTB pull-up resistors


Expander_Set_PullUpsPortAB(0, 0xFFFF);

Library Example
The example demonstrates how to communicate with Port Expander MCP23S17.

Note that Port Expander pins A2 A1 A0 are connected to GND so Port Expander Hardware Address is 0.
Copy Code To Clipboard

// Port Expander module connections


sbit SPExpanderRST at RC0_bit;
sbit SPExpanderCS at RC1_bit;

www.raguvaran.puzl.com
sbit SPExpanderRST_Direction at TRISC0_bit;
sbit SPExpanderCS_Direction at TRISC1_bit;
// End Port Expander module connections

unsigned char i = 0;

void main() {
ANSEL = 0; // Configure AN pins as digital I/O
ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;

TRISB = 0; // Set PORTB as output


PORTB = 0xFF;

// If Port Expander Library uses SPI1 module


SPI1_Init(); // Initialize SPI module used with PortExpander

// If Port Expander Library uses SPI2 module


// SPI2_Init(); // Initialize SPI module used with PortExpander

Expander_Init(0); // Initialize Port Expander

Expander_Set_DirectionPortA(0, 0x00); // Set Expander's PORTA to be output

Expander_Set_DirectionPortB(0,0xFF); // Set Expander's PORTB to be input


Expander_Set_PullUpsPortB(0,0xFF); // Set pull-ups to all of the Expander's PORTB pins

while(1) { // Endless loop


Expander_Write_PortA(0, i++); // Write i to expander's PORTA
PORTB = Expander_Read_PortB(0); // Read expander's PORTB and write it to LEDs
Delay_ms(100);
}

www.raguvaran.puzl.com
HW Connection

Port Expander HW connection

www.raguvaran.puzl.com
PS/2 Library
The mikroC PRO for PIC provides a library for communication with the common PS/2 keyboard.

Important :

 The library does not utilize interrupts for data retrieval, and requires the oscillator clock to
be at least 6MHz.
 The pins to which a PS/2 keyboard is attached should be connected to the pull-up resistors.
 Although PS/2 is a two-way communication bus, this library does not provide MCU-to-
keyboard communication; e.g. pressing the Caps Lock key will not turn on the Caps Lock LED.

External dependencies of PS/2 Library


The following variables must be
Description
defined in all projects using Example :
:
PS/2 Library:

PS/2 Data
extern sfr sbit PS2_Data; sbit PS2_Data at RC0_bit;
line.

extern sfr PS/2 Clock


sbit PS2_Clock at RC1_bit;
sbit PS2_Clock; line.

Direction
extern sfr
of the PS/2 sbit PS2_Data_Direction at TRISC0_bit;
sbit PS2_Data_Direction;
Data pin.

Direction
extern sfr
of the PS/2 sbit PS2_Clock_Direction at TRISC1_bit;
sbit PS2_Clock_Direction;
Clock pin.

Library Routines
 Ps2_Config
 Ps2_Key_Read

Ps2_Config

Prototype void Ps2_Config();

Returns Nothing.

Description Initializes the MCU for work with the PS/2 keyboard.

www.raguvaran.puzl.com
Requires Global variables :

 PS2_Data: Data signal line


 PS2_Clock: Clock signal line in
 PS2_Data_Direction: Direction of the Data pin
 PS2_Clock_Direction: Direction of the Clock pin
must be defined before using this function.

Example sbit PS2_Data at RC0_bit;


sbit PS2_Clock at RC1_bit;
sbit PS2_Data_Direction at TRISC0_bit;
sbit PS2_Clock_Direction at TRISC1_bit;
...
Ps2_Config(); // Init PS/2 Keyboard

Ps2_Key_Read

Prototype unsigned short Ps2_Key_Read(unsigned short *value, unsigned


short *special, unsigned short *pressed);

Returns  1 if reading of a key from the keyboard was successful


 0 if no key was pressed

Description The function retrieves information on key pressed.

Parameters :

 value: holds the value of the key pressed. For characters, numerals, punctuation marks, and
space value will store the appropriate ASCII code. Routine “recognizes” the function
of Shift and Caps Lock , and behaves appropriately. For special function keys see Special Function
Keys Table.
 special: is a flag for special function keys ( F1 , Enter , Esc , etc). If key pressed is one of
these, special will be set to 1, otherwise 0.
 pressed: is set to 1 if the key is pressed, and 0 if it is released.

Requires PS/2 keyboard needs to be initialized. See Ps2_Config routine.

Example unsigned short keydata = 0, special = 0, down = 0;


...
// Press Enter to continue:
do {
if (Ps2_Key_Read(&keydata, &special, &down)) {
if (down && (keydata == 16)) break;
}
} while (1);

Special Function Keys

Key Value returned

F1 1

www.raguvaran.puzl.com
Key Value returned

F2 2

F3 3

F4 4

F5 5

F6 6

F7 7

F8 8

F9 9

F10 10

F11 11

F12 12

Enter 13

Page Up 14

Page Down 15

Backspace 16

Insert 17

Delete 18

Windows 19

Ctrl 20

Shift 21

Alt 22

Print Screen 23

www.raguvaran.puzl.com
Key Value returned

Pause 24

Caps Lock 25

End 26

Home 27

Scroll Lock 28

Num Lock 29

Left Arrow 30

Right Arrow 31

Up Arrow 32

Down Arrow 33

Escape 34

Tab 35

Library Example
This simple example reads values of the pressed keys on the PS/2 keyboard and sends them via UART.
Copy Code To Clipboard

unsigned short keydata = 0, special = 0, down = 0;

sbit PS2_Data at RC0_bit;


sbit PS2_Clock at RC1_bit;
sbit PS2_Data_Direction at TRISC0_bit;
sbit PS2_Clock_Direction at TRISC1_bit;

void main() {

ANSEL = 0; // Configure AN pins as digital I/O


ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;

UART1_Init(19200); // Initialize UART module at 19200 bps


Ps2_Config(); // Init PS/2 Keyboard
Delay_ms(100); // Wait for keyboard to finish
UART1_Write_Text("Ready");
UART1_Write(10); // Line Feed
UART1_Write(13); // Carriage return

www.raguvaran.puzl.com
do {
if (Ps2_Key_Read(&keydata, &special, &down)) {
if (down && (keydata == 16)) { // Backspace
UART1_Write(0x08);
}
else if (down && (keydata == 13)) { // Enter
UART1_Write('r'); // send carriage return to usart terminal
//Usart_Write('n'); // uncomment this line if usart terminal also
expects line feed
// for new line transition
}
else if (down && !special && keydata) {
UART1_Write(keydata);
}
}
Delay_ms(1); // debounce
} while (1);
}

HW Connection

Example of PS2 keyboard connection

PWM Library
CCP module is available with a number of PIC MCUs. mikroC PRO for PIC provides library which
simplifies using PWM HW Module.

Important :
 Some MCUs have multiple CCP modules. In order to use the desired CCP library routine,
simply change the number 1 in the prototype with the appropriate module number,
i.e.PWM2_Start();.
 All PWM modules use Timer2 for its operation, so you can not set different frequencies for
different PWM modules.

www.raguvaran.puzl.com
Library Routines
 PWM1_Init
 PWM1_Set_Duty
 PWM1_Start
 PWM1_Stop

PWM1_Init

Prototype void PWM1_Init(const long freq);

Returns Nothing.

Description Initializes the PWM module with duty ratio 0. Parameter freq is a desired PWM frequency in Hz (refer to device
data sheet for correct values in respect with Fosc).
This routine needs to be called before using other functions from PWM Library.

Requires MCU must have CCP module.

Note : Calculation of the PWM frequency value is carried out by the compiler, as it would produce a
relatively large code if performed on the library level.
Therefore, compiler needs to know the value of the parameter in the compile time. That is why this parameter
needs to be a constant, and not a variable.

Example Initialize PWM module at 5KHz:

PWM1_Init(5000);

PWM1_Set_Duty

Prototype void PWM1_Set_Duty(unsigned short duty_ratio);

Returns Nothing.

Description Sets PWM duty ratio. Parameter duty takes values from 0 to 255, where 0 is 0%, 127 is 50%, and 255 is 100%
duty ratio. Other specific values for duty ratio can be calculated as (Percent*255)/100.

Requires MCU must have CCP module. PWM1_Init must be called before using this routine.

Example Set duty ratio to 75%:

PWM1_Set_Duty(192);

PWM1_Start

Prototype void PWM1_Start(void);

Returns Nothing.

www.raguvaran.puzl.com
Description Starts PWM.

Requires MCU must have CCP module. PWM1_Init must be called before using this routine.

Example PWM1_Start();

PWM1_Stop

Prototype void PWM1_Stop(void);

Returns Nothing.

Description Stops PWM.

Requires MCU must have CCP module. PWM1_Init must be called before using this routine. PWM1_Start should be
called before using this routine, otherwise it will have no effect as the PWM module is not running.

Example PWM1_Stop();

Library Example
The example changes PWM duty ratio on RC1 and RC2 pins continually. If LED is connected to these
pins, you can observe the gradual change of emitted light.
Copy Code To Clipboard

unsigned short current_duty, old_duty, current_duty1, old_duty1;

void InitMain() {
ANSEL = 0; // Configure AN pins as digital
ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;

PORTA = 255;
TRISA = 255; // configure PORTA pins as input
PORTB = 0; // set PORTB to 0
TRISB = 0; // designate PORTB pins as output
PORTC = 0; // set PORTC to 0
TRISC = 0; // designate PORTC pins as output
PWM1_Init(5000); // Initialize PWM1 module at 5KHz
PWM2_Init(5000); // Initialize PWM2 module at 5KHz
}

void main() {
InitMain();
current_duty = 16; // initial value for current_duty
current_duty1 = 16; // initial value for current_duty1

PWM1_Start(); // start PWM1


PWM2_Start(); // start PWM2
PWM1_Set_Duty(current_duty); // Set current duty for PWM1
PWM2_Set_Duty(current_duty1); // Set current duty for PWM2

while (1) { // endless loop


if (RA0_bit) { // button on RA0 pressed
Delay_ms(40);
current_duty++; // increment current_duty

www.raguvaran.puzl.com
PWM1_Set_Duty(current_duty);
}

if (RA1_bit) { // button on RA1 pressed


Delay_ms(40);
current_duty--; // decrement current_duty
PWM1_Set_Duty(current_duty);
}

if (RA2_bit) { // button on RA2 pressed


Delay_ms(40);
current_duty1++; // increment current_duty1
PWM2_Set_Duty(current_duty1);
}

if (RA3_bit) { // button on RA3 pressed


Delay_ms(40);
current_duty1--; // decrement current_duty1
PWM2_Set_Duty(current_duty1);
}

Delay_ms(5); // slow down change pace a little


}
}

HW Connection

PWM demonstration

www.raguvaran.puzl.com
RS-485 Library
RS-485 is a multipoint communication which allows multiple devices to be connected to a single bus. The
mikroC PRO for PIC provides a set of library routines for comfortable work with RS485 system using
Master/Slave architecture. Master and Slave devices interchange packets of information. Each of these
packets contains synchronization bytes, CRC byte, address byte and the data. Each Slave has unique
address and receives only packets addressed to it. The Slave can never initiate communication.

It is the user’s responsibility to ensure that only one device transmits via 485 bus at a time.

The RS-485 routines require the UART module. Pins of UART need to be attached to RS-485 interface
transceiver, such as LTC485 or similar (see schematic at the bottom of this page).
Library constants:
 START byte value = 150
 STOP byte value = 169
 Address 50 is the broadcast address for all Slaves (packets containing address 50 will be
received by all Slaves except the Slaves with addresses 150 and 169).

Important :
 The library uses the UART module for communication. The user must initialize the
appropriate UART module before using the RS-485 Library.
 For MCUs with multiple UART modules it is possible to initialize them and then switch by
using the UART_Set_Active routine.

Library Dependency Tree

External dependencies of RS-485 Library


The following variable must be
defined in all projects using RS-485 Description : Example :
Library:
Control RS-485
extern sfr
Transmit/Receive sbit RS485_rxtx_pin at RC2_bit;
sbit RS485_rxtx_pin;
operation mode
Direction of the
extern sfr RS-485 sbit RS485_rxtx_pin_direction atTRISC2_bit;
sbit RS485_rxtx_pin_direction; Transmit/Receive
pin

Library Routines
 RS485Master_Init
 RS485Master_Receive
 RS485Master_Send
 RS485Slave_Init
 RS485Slave_Receive
 RS485Slave_Send

www.raguvaran.puzl.com
RS485Master_Init

Prototype void RS485Master_Init();

Returns Nothing.

Description Initializes MCU as a Master for RS-485 communication.

Requires Global variables :


 RS485_rxtx_pin - this pin is connected to RE/DE input of RS-485 transceiver(see schematic at
the bottom of this page). RE/DE signal controls RS-485 transceiver operation mode.
 RS485_rxtx_pin_direction - direction of the RS-485 Transmit/Receive pin.
must be defined before using this function.

UART HW module needs to be initialized. See UARTx_Init.

Example // RS485 module pinout


sbit RS485_rxtx_pin at RC2_bit; // transmit/receive control set to PORTC.B2

// Pin direction
sbit RS485_rxtx_pin_direction at TRISC2_bit; // RxTx pin direction set as output
...
UART1_Init(9600); // initialize UART1 module
RS485Master_Init(); // intialize MCU as a Master for RS-485
communication

RS485Master_Receive

Prototype void RS485Master_Receive(char *data_buffer);

Returns Nothing.

Description Receives messages from Slaves. Messages are multi-byte, so this routine must be called for each byte received.

Parameters :

 data_buffer: 7 byte buffer for storing received data, in the following manner:

 data[0..2]: message content


 data_buffer[3]: number of message bytes received, 1–3
 data_buffer[4]: is set to 255 when message is received
 data_buffer[5]: is set to 255 if error has occurred
 data_buffer[6]: address of the Slave which sent the message
The function automatically adjusts data[4] and data[5] upon every received message. These flags need to be
cleared by software.

Requires MCU must be initialized as a Master for RS-485 communication. See RS485Master_Init.

Example char msg[8];


...
RS485Master_Receive(msg);

www.raguvaran.puzl.com
RS485Master_Send

Prototype void RS485Master_Send(char *data_buffer, char datalen, char Slave_address);

Returns Nothing.

Description Sends message to Slave(s). Message format can be found at the bottom of this page.

Parameters :

 data_buffer: data to be sent


 datalen: number of bytes for transmition. Valid values: 0...3.
 Slave_address: Slave(s) address

Requires MCU must be initialized as a Master for RS-485 communication. See RS485Master_Init.
It is the user’s responsibility to ensure (by protocol) that only one device sends data via 485 bus at a time.

Example char msg[8];


...
// send 3 bytes of data to Slave with address 0x12
RS485Master_Send(msg, 3, 0x12);

RS485Slave_Init

Prototype void RS485Slave_Init(char Slave_address);

Returns Nothing.

Description Initializes MCU as a Slave for RS-485 communication.

Parameters :

 Slave_address: Slave address

Requires Global variables :


 RS485_rxtx_pin - this pin is connected to RE/DE input of RS-485 transceiver(see schematic at
the bottom of this page). RE/DE signal controls RS-485 transceiver operation mode. Valid
values: 1 (for transmitting) and 0 (for receiving
 RS485_rxtx_pin_direction - direction of the RS-485 Transmit/Receive pin.
must be defined before using this function.

UART HW module needs to be initialized. See UARTx_Init.

Example Initialize MCU as a Slave with address 160:

// RS485 module pinout


sbit RS485_rxtx_pin at RC2_bit; // transmit/receive control set to PORTC.B2

// Pin direction
sbit RS485_rxtx_pin_direction at TRISC2_bit; // RxTx pin direction set as output

www.raguvaran.puzl.com
...
UART1_Init(9600); // initialize UART1 module
RS485Slave_Init(160); // intialize MCU as a Slave for RS-485
communication with address 160

RS485Slave_Receive

Prototype void RS485Slave_Receive(char *data_buffer);

Returns Nothing.

Description Receives messages from Master. If Slave address and Message address field don't match then the message will be
discarded. Messages are multi-byte, so this routine must be called for each byte received.

Parameters :

 data_buffer: 6 byte buffer for storing received data, in the following manner:

 data[0..2]: message content


 data[3]: number of message bytes received, 1–3
 data[4]: is set to 255 when message is received
 data[5]: is set to 255 if error has occurred
The function automatically adjusts data[4] and data[5] upon every received message. These flags need to be
cleared by software.

Requires MCU must be initialized as a Slave for RS-485 communication. See RS485Slave_Init.

Example char msg[8];


...
RS485Slave_Read(msg);

RS485Slave_Send

Prototype void RS485Slave_Send(char *data_buffer, char datalen);

Returns Nothing.

Description Sends message to Master. Message format can be found at the bottom of this page.

Parameters :

 data_buffer: data to be sent


 datalen: number of bytes for transmition. Valid values: 0...3.

Requires MCU must be initialized as a Slave for RS-485 communication. See RS485Slave_Init. It is the user’s
responsibility to ensure (by protocol) that only one device sends data via 485 bus at a time.

Example char msg[8];


...
// send 2 bytes of data to the Master

www.raguvaran.puzl.com
RS485Slave_Send(msg, 2);

Library Example
This is a simple demonstration of RS485 Library routines usage.

Master sends message to Slave with address 160 and waits for a response. The Slave accepts data,
increments it and sends it back to the Master. Master then does the same and sends incremented data
back to Slave, etc.

Master displays received data on PORTB, while error on receive (0xAA) and number of consecutive
unsuccessful retries are displayed on PORTD. Slave displays received data on PORTB, while error on
receive (0xAA) is displayed on PORTD. Hardware configurations in this example are made for the
EasyPIC6 board and 16F887.

RS485 Master code:

Copy Code To Clipboard

char dat[10]; // buffer for receving/sending messages


char i,j;

sbit rs485_rxtx_pin at RC2_bit; // set transcieve pin


sbit rs485_rxtx_pin_direction at TRISC2_bit; // set transcieve pin direction

// Interrupt routine
void interrupt() {
RS485Master_Receive(dat);
}

void main(){
long cnt = 0;

ANSEL = 0; // Configure AN pins as digital I/O


ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;

PORTB = 0;
PORTD = 0;
TRISB = 0;
TRISD = 0;

UART1_Init(9600); // initialize UART1 module


Delay_ms(100);

RS485Master_Init(); // initialize MCU as Master


dat[0] = 0xAA;
dat[1] = 0xF0;
dat[2] = 0x0F;
dat[4] = 0; // ensure that message received flag is 0
dat[5] = 0; // ensure that error flag is 0
dat[6] = 0;

RS485Master_Send(dat,1,160);

RCIE_bit = 1; // enable interrupt on UART1 receive


TXIE_bit = 0; // disable interrupt on UART1 transmit
PEIE_bit = 1; // enable peripheral interrupts

www.raguvaran.puzl.com
GIE_bit = 1; // enable all interrupts

while (1){
// upon completed valid message receiving
// data[4] is set to 255
cnt++;
if (dat[5]) { // if an error detected, signal it
PORTD = 0xAA; // by setting portd to 0xAA
}
if (dat[4]) { // if message received successfully
cnt = 0;
dat[4] = 0; // clear message received flag
j = dat[3];
for (i = 1; i <= dat[3]; i++) { // show data on PORTB
PORTB = dat[i-1];
} // increment received dat[0]
dat[0] = dat[0]+1; // send back to master
Delay_ms(1);
RS485Master_Send(dat,1,160);

}
if (cnt > 100000) {
PORTD ++;
cnt = 0;
RS485Master_Send(dat,1,160);
if (PORTD > 10) // if sending failed 10 times
RS485Master_Send(dat,1,50); // send message on broadcast address
}
}

RS485 Slave code:

Copy Code To Clipboard

char dat[9]; // buffer for receving/sending messages


char i,j;

sbit rs485_rxtx_pin at RC2_bit; // set transcieve pin


sbit rs485_rxtx_pin_direction at TRISC2_bit; // set transcieve pin direction

// Interrupt routine
void interrupt() {
RS485Slave_Receive(dat);
}

void main() {
ANSEL = 0; // Configure AN pins as digital I/O
ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;

PORTB = 0;
PORTD = 0;
TRISB = 0;
TRISD = 0;

UART1_Init(9600); // initialize UART1 module


Delay_ms(100);
RS485Slave_Init(160); // Intialize MCU as slave, address 160

dat[4] = 0; // ensure that message received flag is 0


dat[5] = 0; // ensure that message received flag is 0

www.raguvaran.puzl.com
dat[6] = 0; // ensure that error flag is 0

RCIE_bit = 1; // enable interrupt on UART1 receive


TXIE_bit = 0; // disable interrupt on UART1 transmit
PEIE_bit = 1; // enable peripheral interrupts
GIE_bit = 1; // enable all interrupts

while (1) {
if (dat[5]) { // if an error detected, signal it by
PORTD = 0xAA; // setting portd to 0xAA
dat[5] = 0;
}
if (dat[4]) { // upon completed valid message receive
dat[4] = 0; // data[4] is set to 0xFF
j = dat[3];
for (i = 1; i <= dat[3];i++){
PORTB = dat[i-1];
}
dat[0] = dat[0]+1; // increment received dat[0]
Delay_ms(1);
RS485Slave_Send(dat,1); // and send it back to master
}
}
}

HW Connection

www.raguvaran.puzl.com
Example of interfacing PIC16F887 MCU to PIC16F887 MCU MCU via RS485 bus with LTC485 as RS-485 transceiver

www.raguvaran.puzl.com
Message format and CRC calculations
Q: How is CRC checksum calculated on RS485 Master side?
Copy Code To Clipboard

START_BYTE = 0x96; // 10010110


STOP_BYTE = 0xA9; // 10101001

PACKAGE:
--------
START_BYTE 0x96
ADDRESS
DATALEN
[DATA1] // if exists
[DATA2] // if exists
[DATA3] // if exists
CRC
STOP_BYTE 0xA9

DATALEN bits
------------
bit7 = 1 MASTER SENDS
0 SLAVE SENDS
bit6 = 1 ADDRESS WAS XORed with 1, IT WAS EQUAL TO START_BYTE or STOP_BYTE
0 ADDRESS UNCHANGED
bit5 = 0 FIXED
bit4 = 1 DATA3 (if exists) WAS XORed with 1, IT WAS EQUAL TO START_BYTE or STOP_BYTE
0 DATA3 (if exists) UNCHANGED
bit3 = 1 DATA2 (if exists) WAS XORed with 1, IT WAS EQUAL TO START_BYTE or STOP_BYTE
0 DATA2 (if exists) UNCHANGED
bit2 = 1 DATA1 (if exists) WAS XORed with 1, IT WAS EQUAL TO START_BYTE or STOP_BYTE
0 DATA1 (if exists) UNCHANGED
bit1bit0 = 0 to 3 NUMBER OF DATA BYTES SEND

CRC generation :
----------------
crc_send = datalen ^ address;
crc_send ^= data[0]; // if exists
crc_send ^= data[1]; // if exists
crc_send ^= data[2]; // if exists
crc_send = ~crc_send;
if ((crc_send == START_BYTE) || (crc_send == STOP_BYTE))
crc_send++;

NOTE: DATALEN<4..0> can not take the START_BYTE<4..0> or STOP_BYTE<4..0> values.

Software I²C Library

www.raguvaran.puzl.com
The mikroC PRO for PIC provides routines for implementing Software I²C communication. These routines
are hardware independent and can be used with any MCU. The Software I²C library enables you to use
MCU as Master in I²C communication. Multi-master mode is not supported.
Important :
 This library implements time-based activities, so interrupts need to be disabled when using
Software I²C.
 All I²C Library functions are blocking-call functions (they are waiting for I²C clock line to
become logical one).
 The pins used for the Software I²C communication should be connected to the pull-up
resistors. Turning off the LEDs connected to these pins may also be required.
 Every Software I²C library routine has its own counterpart in Hardware I²C library,
except I2C_Repeated_Start. Soft_I2C_Start is used instead of I2C_Repeated_Start.
 Working clock frequency of the Software I²C is 20kHz.

External dependencies of Software I²C Library


The following variables must be
Description
defined in all projects using Example :
:
Software I²C Library:

extern sbit Soft_I2C_Scl;


Soft I²C sbit Soft_I2C_Scl at RC3_bit;
Clock line.

extern sbit Soft_I2C_Sda;


Soft I²C sbit Soft_I2C_Sda at RC4_bit;
Data line.
Direction of
extern
the Soft I²C sbit Soft_I2C_Scl_Direction atTRISC3_bit;
sbit Soft_I2C_Scl_Direction;
Clock pin.
Direction of
extern
the Soft I²C sbit Soft_I2C_Sda_Direction atTRISC4_bit;
sbit Soft_I2C_Sda_Direction;
Data pin.

Library Routines
 Soft_I2C_Init
 Soft_I2C_Start
 Soft_I2C_Read
 Soft_I2C_Write
 Soft_I2C_Stop
 Soft_I2C_Break

Soft_I2C_Init

Prototype void Soft_I2C_Init();

Returns Nothing.

Description Configures the software I²C module.

Requires Global variables :


 Soft_I2C_Scl: Soft I²C clock line
 Soft_I2C_Sda: Soft I²C data line

www.raguvaran.puzl.com
 Soft_I2C_Scl_Pin_Direction: Direction of the Soft I²C clock pin
 Soft_I2C_Sda_Pin_Direction: Direction of the Soft I²C data pin
must be defined before using this function.

Example // Software I2C connections


sbit Soft_I2C_Scl at RC3_bit;
sbit Soft_I2C_Sda at RC4_bit;
sbit Soft_I2C_Scl_Direction at TRISC3_bit;
sbit Soft_I2C_Sda_Direction at TRISC4_bit;
// End Software I2C connections

...
Soft_I2C_Init();

Soft_I2C_Start

Prototype void Soft_I2C_Start(void);

Returns Nothing.

Description Determines if the I²C bus is free and issues START signal.

Requires Software I²C must be configured before using this function. See Soft_I2C_Init routine.

Example // Issue START signal


Soft_I2C_Start();

Soft_I2C_Read

Prototype unsigned short Soft_I2C_Read(unsigned int ack);

Returns One byte from the Slave.

Description Reads one byte from the slave.

Parameters :

 ack: acknowledge signal parameter. If the ack==0 not acknowledge signal will be sent after
reading, otherwise the acknowledge signal will be sent.

Requires Soft I²C must be configured before using this function. See Soft_I2C_Init routine.
Also, START signal needs to be issued in order to use this function. See Soft_I2C_Start routine.

Example unsigned short take;


...
// Read data and send the not_acknowledge signal
take = Soft_I2C_Read(0);

Soft_I2C_Write

www.raguvaran.puzl.com
Prototype unsigned short Soft_I2C_Write(unsigned short data_);

Returns  0 if there were no errors.


 1 if write collision was detected on the I²C bus.

Description Sends data byte via the I²C bus.


Parameters :

 data_: data to be sent

Requires Soft I²C must be configured before using this function. See Soft_I2C_Init routine.
Also, START signal needs to be issued in order to use this function. See Soft_I2C_Start routine.

Example unsigned short data_, error;


...
error = Soft_I2C_Write(data_);
error = Soft_I2C_Write(0xA3);

Soft_I2C_Stop

Prototype void Soft_I2C_Stop(void);

Returns Nothing.

Description Issues STOP signal.

Requires Soft I²C must be configured before using this function. See Soft_I2C_Init routine.

Example // Issue STOP signal


Soft_I2C_Stop();

Soft_I2C_Break

Prototype void Soft_I2C_Break(void);

Returns Nothing.

Description All Software I²C Library functions can block the program flow (see note at the top of this page). Calling this
routine from interrupt will unblock the program execution. This mechanism is similar to WDT.

Note : Interrupts should be disabled before using Software I²C routines again (see note at the top of this
page).

Requires Nothing.

Example
// Software I2C connections
sbit Soft_I2C_Scl at RC0_bit;
sbit Soft_I2C_Sda at RC1_bit;

www.raguvaran.puzl.com
sbit Soft_I2C_Scl_Direction at TRISC0_bit;
sbit Soft_I2C_Sda_Direction at TRISC1_bit;
// End Software I2C connections

char counter = 0;

void interrupt {

if (INTCON.T0IF) {
if (counter >= 20) {
Soft_I2C_Break();
counter = 0; // reset counter
}
else
counter++; // increment counter

INTCON.T0IF = 0; // Clear Timer0 overflow interrupt flag

}
}

void main() {

OPTION_REG = 0x04; // TMR0 prescaler set to 1:32

...

// try Soft_I2C_Init with blocking prevention mechanism


INTCON.GIE = 1; // Global interrupt enable
INTCON.T0IE = 1; // Enable Timer0 overflow interrupt
Soft_I2C_Init();
INTCON.GIE = 0; // Global interrupt disable

...
}

Library Example
The example demonstrates Software I²C Library routines usage. The PIC MCU is connected (SCL, SDA
pins) to PCF8583 RTC (real-time clock). Program reads date and time are read from the RTC and prints
it on Lcd.
Copy Code To Clipboard

// Software I2C connections


sbit Soft_I2C_Scl at RC3_bit;
sbit Soft_I2C_Sda at RC4_bit;
sbit Soft_I2C_Scl_Direction at TRISC3_bit;
sbit Soft_I2C_Sda_Direction at TRISC4_bit;
// End Software I2C connections

// LCD module connections


sbit LCD_RS at RB4_bit;
sbit LCD_EN at RB5_bit;
sbit LCD_D4 at RB0_bit;
sbit LCD_D5 at RB1_bit;
sbit LCD_D6 at RB2_bit;
sbit LCD_D7 at RB3_bit;

sbit LCD_RS_Direction at TRISB4_bit;


sbit LCD_EN_Direction at TRISB5_bit;
sbit LCD_D4_Direction at TRISB0_bit;
sbit LCD_D5_Direction at TRISB1_bit;
sbit LCD_D6_Direction at TRISB2_bit;
sbit LCD_D7_Direction at TRISB3_bit;

www.raguvaran.puzl.com
// End LCD module connections

char seconds, minutes, hours, day, month, year; // Global date/time variables

//--------------------- Reads time and date information from RTC (PCF8583)


void Read_Time() {

Soft_I2C_Start(); // Issue start signal


Soft_I2C_Write(0xA0); // Address PCF8583, see PCF8583 datasheet
Soft_I2C_Write(2); // Start from address 2
Soft_I2C_Start(); // Issue repeated start signal
Soft_I2C_Write(0xA1); // Address PCF8583 for reading R/W=1

seconds = Soft_I2C_Read(1); // Read seconds byte


minutes = Soft_I2C_Read(1); // Read minutes byte
hours = Soft_I2C_Read(1); // Read hours byte
day = Soft_I2C_Read(1); // Read year/day byte
month = Soft_I2C_Read(0); // Read weekday/month byte
Soft_I2C_Stop(); // Issue stop signal

//-------------------- Formats date and time


void Transform_Time() {
seconds = ((seconds & 0xF0) >> 4)*10 + (seconds & 0x0F); // Transform seconds
minutes = ((minutes & 0xF0) >> 4)*10 + (minutes & 0x0F); // Transform months
hours = ((hours & 0xF0) >> 4)*10 + (hours & 0x0F); // Transform hours
year = (day & 0xC0) >> 6; // Transform year
day = ((day & 0x30) >> 4)*10 + (day & 0x0F); // Transform day
month = ((month & 0x10) >> 4)*10 + (month & 0x0F); // Transform month
}

//-------------------- Output values to LCD


void Display_Time() {

Lcd_Chr(1, 6, (day / 10) + 48); // Print tens digit of day variable


Lcd_Chr(1, 7, (day % 10) + 48); // Print oness digit of day variable
Lcd_Chr(1, 9, (month / 10) + 48);
Lcd_Chr(1,10, (month % 10) + 48);
Lcd_Chr(1,15, year + 48); // Print year variable (start from year 2010)

Lcd_Chr(2, 6, (hours / 10) + 48);


Lcd_Chr(2, 7, (hours % 10) + 48);
Lcd_Chr(2, 9, (minutes / 10) + 48);
Lcd_Chr(2,10, (minutes % 10) + 48);
Lcd_Chr(2,12, (seconds / 10) + 48);
Lcd_Chr(2,13, (seconds % 10) + 48);
}

//------------------ Performs project-wide init


void Init_Main() {

TRISB = 0;
PORTB = 0xFF;
TRISB = 0xff;
ANSEL = 0; // Configure AN pins as digital I/O
ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;

Soft_I2C_Init(); // Initialize Soft I2C communication


Lcd_Init(); // Initialize LCD
Lcd_Cmd(_LCD_CLEAR); // Clear LCD display
Lcd_Cmd(_LCD_CURSOR_OFF); // Turn cursor off

www.raguvaran.puzl.com
Lcd_Out(1,1,"Date:"); // Prepare and output static text on LCD
Lcd_Chr(1,8,'.');
Lcd_Chr(1,11,'.');
Lcd_Chr(1,16,'.');
Lcd_Out(2,1,"Time:");
Lcd_Chr(2,8,':');
Lcd_Chr(2,11,':');
Lcd_Out(1,12,"201"); // start from year 2010
}

//----------------- Main procedure


void main() {
Delay_ms(500);

Init_Main(); // Perform initialization

while (1) { // Endless loop


Read_Time(); // Read time from RTC(PCF8583)
Transform_Time(); // Format date and time
Display_Time(); // Prepare and display on LCD
}
}

Software SPI Library

www.raguvaran.puzl.com
The mikroC PRO for PIC provides routines for implementing Software SPI communication. These routines
are hardware independent and can be used with any MCU. The Software SPI Library provides easy
communication with other devices via SPI: A/D converters, D/A converters, MAX7219, LTC1290, etc.
Library configuration:
 SPI to Master mode
 Clock value = 20 kHz.
 Data sampled at the middle of interval.
 Clock idle state low.
 Data sampled at the middle of interval.
 Data transmitted at low to high edge.

The library configures SPI to the master mode, clock = 20kHz, data sampled at the middle of interval,
clock idle state low and data transmitted at low to high edge.

Important : The Software SPI library implements time-based activities, so interrupts need to be
disabled when using it.

External dependencies of Software SPI Library


The following variables
must be defined in all Description
Example :
projects using Software :
SPI Library:
extern sfr
Data In line. sbit SoftSpi_SDI at RC4_bit;
sbit SoftSpi_SDI;

extern sfr Data Out sbit SoftSpi_SDO at RC5_bit;


sbit SoftSpi_SDO; line.
extern sfr
Clock line. sbit SoftSpi_CLK at RC3_bit;
sbit SoftSpi_CLK;

Direction of
extern sfr
the Data In sbit SoftSpi_SDI_Direction atTRISC4_bit;
sbit SoftSpi_SDI_Direction;
pin.

Direction of
extern sfr
the Data sbit SoftSpi_SDO_Direction atTRISC5_bit;
sbit SoftSpi_SDO_Direction;
Out pin

Direction of
extern sfr
the Clock sbit SoftSpi_CLK_Direction atTRISC3_bit;
sbit SoftSpi_CLK_Direction;
pin.

Library Routines
 Soft_SPI_Init
 Soft_SPI_Read
 Soft_SPI_Write

Soft_SPI_Init

www.raguvaran.puzl.com
Prototype void Soft_SPI_Init();

Returns Nothing.

Description Configures and initializes the software SPI module.

Requires Global variables:

 SoftSpi_SDI: Data in line


 SoftSpi_SDO: Data out line
 SoftSpi_CLK: Data clock line
 SoftSpi_SDI_Direction: Direction of the Data in pin
 SoftSpi_SDO_Direction: Direction of the Data out pin
 SoftSpi_CLK_Direction: Direction of the Data clock pin
must be defined before using this function.

Example // Software SPI module connections


sbit SoftSpi_SDI at RC4_bit;
sbit SoftSpi_SDO at RC5_bit;
sbit SoftSpi_CLK at RC3_bit;

sbit SoftSpi_SDI_Direction at TRISC4_bit;


sbit SoftSpi_SDO_Direction at TRISC5_bit;
sbit SoftSpi_CLK_Direction at TRISC3_bit;
// End Software SPI module connections
...
Soft_SPI_Init(); // Init Soft_SPI

Soft_SPI_Read

Prototype unsigned short Soft_SPI_Read(char sdata);

Returns Byte received via the SPI bus.

Description This routine performs 3 operations simultaneously. It provides clock for the
Software SPI bus, reads a byte and sends a byte.
Parameters :

 sdata: data to be sent.

Requires Soft SPI must be initialized before using this function. See Soft_SPI_Init routine.

Example unsigned short data_read;


char data_send;
...
// Read a byte and assign it to data_read variable
// (data_send byte will be sent via SPI during the Read operation)
data_read = Soft_SPI_Read(data_send);

Soft_SPI_Write

www.raguvaran.puzl.com
Prototype void Soft_SPI_Write(char sdata);

Returns Nothing.

Description This routine sends one byte via the Software SPI bus.
Parameters :

 sdata: data to be sent.

Requires Soft SPI must be initialized before using this function. See Soft_SPI_Init routine.

Example // Write a byte to the Soft SPI bus


Soft_SPI_Write(0xAA);

Library Example
This code demonstrates using library routines for Soft_SPI communication. Also, this example
demonstrates working with Microchip's MCP4921 12-bit D/A converter.

Copy Code To Clipboard

// DAC module connections


sbit Chip_Select at RC0_bit;
sbit SoftSpi_CLK at RC3_bit;
sbit SoftSpi_SDI at RC4_bit;
sbit SoftSpi_SDO at RC5_bit;

sbit Chip_Select_Direction at TRISC0_bit;


sbit SoftSpi_CLK_Direction at TRISC3_bit;
sbit SoftSpi_SDI_Direction at TRISC4_bit;
sbit SoftSpi_SDO_Direction at TRISC5_bit;
// End DAC module connections

unsigned int value;

void InitMain() {
TRISA0_bit = 1; // Set RA0 pin as input
TRISA1_bit = 1; // Set RA1 pin as input
Chip_Select = 1; // Deselect DAC
Chip_Select_Direction = 0; // Set CS# pin as Output
Soft_SPI_Init(); // Initialize Soft_SPI
}

// DAC increments (0..4095) --> output voltage (0..Vref)


void DAC_Output(unsigned int valueDAC) {
char temp;

Chip_Select = 0; // Select DAC chip

// Send High Byte


temp = (valueDAC >> 8) & 0x0F; // Store valueDAC[11..8] to temp[3..0]
temp |= 0x30; // Define DAC setting, see MCP4921 datasheet
Soft_SPI_Write(temp); // Send high byte via Soft SPI

// Send Low Byte


temp = valueDAC; // Store valueDAC[7..0] to temp[7..0]
Soft_SPI_Write(temp); // Send low byte via Soft SPI

Chip_Select = 1; // Deselect DAC chip

www.raguvaran.puzl.com
}

void main() {

ANSEL = 0; // Configure AN pins as digital


ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;

InitMain(); // Perform main initialization

value = 2048; // When program starts, DAC gives


// the output in the mid-range

while (1) { // Endless loop

if ((RA0_bit) && (value < 4095)) { // If RA0 button is pressed


value++; // increment value
}
else {
if ((RA1_bit) && (value > 0)) { // If RA1 button is pressed
value--; // decrement value
}
}

DAC_Output(value); // Send value to DAC chip


Delay_ms(1); // Slow down key repeat pace
}
}

www.raguvaran.puzl.com
Software UART Library
The mikroC PRO for PIC provides routines for implementing Software UART communication. These
routines are hardware independent and can be used with any MCU.
The Software UART Library provides easy communication with other devices via the RS232 protocol.

Important : The Software UART library implements time-based activities, so interrupts need to be
disabled when using it.

Library Routines
 Soft_UART_Init
 Soft_UART_Read
 Soft_UART_Write
 Soft_UART_Break

Soft_UART_Init

Prototype char Soft_UART_Init(char *port, char rx_pin, char tx_pin, unsigned


long baud_rate, char inverted);

Returns  2 - error, requested baud rate is too low


 1 - error, requested baud rate is too high
 0 - successful initialization

Description Configures and initializes the software UART module.


Parameters :

 port: port to be used.


 rx_pin: sets rx_pin to be used.
 tx_pin: sets tx_pin to be used.
 baud_rate: baud rate to be set. Maximum baud rate depends on the
MCU’s clock and working conditions.
 inverted: inverted output flag. When set to a non-zero value, inverted
logic on output is used.
Software UART routines use Delay_Cyc routine. If requested baud rate is too low then
calculated parameter for calling Delay_Cyc exceeds Delay_Cyc argument range.
If requested baud rate is too high then rounding error of Delay_Cyc argument corrupts
Software UART timings.

Requires Nothing.

Example This will initialize software UART and establish the communication at 14400 bps:
char error;
...
error = Soft_UART_Init(&PORTC, 7, 6, 14400, 0); // Initialize Soft UART at
14400 bps

Soft_UART_Read

www.raguvaran.puzl.com
Prototype char Soft_UART_Read(char * error);

Returns Byte received via UART.

Description The function receives a byte via software UART.


This is a blocking function call (waits for start bit). Programmer can unblock it by
calling Soft_UART_Break routine.
Parameters :

 error: Error flag. Error code is returned through this variable.


 0 - no error
 1 - stop bit error
 255 - user abort, Soft_UART_Break called

Requires Software UART must be initialized before using this function. See
the Soft_UART_Init routine.

Example char data_, error;


...
// wait until data is received
do
data = Soft_UART_Read(&error);
while (error);

// Now we can work with data:


if (data_) {...}

Soft_UART_Write

Prototype void Soft_UART_Write(char udata);

Returns Nothing.

Description This routine sends one byte via the Software UART bus.
Parameters :

 udata: data to be sent.

Requires Software UART must be initialized before using this function. See
the Soft_UART_Init routine.
Be aware that during transmission, software UART is incapable of receiving data – data
transfer protocol must be set in such a way to prevent loss of information.

Example char some_byte = 0x0A;


...
// Write a byte via Soft UART
Soft_UART_Write(some_byte);

www.raguvaran.puzl.com
Soft_UART_Break

Prototype void Soft_UART_Break();

Returns Nothing.

Description Soft_UART_Read is blocking routine and it can block the program flow. Calling this
routine from the interrupt will unblock the program execution. This mechanism is
similar toWDT.

Note : Interrupts should be disabled before using Software UART routines again
(see note at the top of this page).

Requires Nothing.

Example char data1, error, counter = 0;

void interrupt() {

if (INTCON.T0IF) {
if (counter >= 20) {
Soft_UART_Break();
counter = 0; // reset counter
}
else
counter++; // increment counter

INTCON.T0IF = 0; // Clear Timer0 overflow interrupt flag

}
}

void main() {

OPTION_REG = 0x04; // TMR0 prescaler set to 1:32

...

if (Soft_UART_Init(&PORTC, 7, 6, 9600, 0) == 0)
Soft_UART_Write(0x55);

...

// try Soft_UART_Read with blocking prevention mechanism


INTCON.GIE = 1; // Global interrupt enable
INTCON.T0IE = 1; // Enable Timer0 overflow interrupt
data1 = Soft_UART_Read(&error);
INTCON.GIE = 0; // Global interrupt disable

www.raguvaran.puzl.com
Library Example
This example demonstrates simple data exchange via software UART. If MCU is connected to the PC, you
can test the example from the mikroC PRO for PIC USART Terminal Tool.
Copy Code To Clipboard

char i, error, byte_read; // Auxiliary variables

void main(){

ANSEL = 0; // Configure AN pins as digital I/O


ANSELH = 0;

TRISB = 0x00; // Set PORTB as output (error signalization)


PORTB = 0; // No error

error = Soft_UART_Init(&PORTC, 7, 6, 14400, 0); // Initialize Soft UART at 14400 bps


if (error > 0) {
PORTB = error; // Signalize Init error
while(1) ; // Stop program
}
Delay_ms(100);

for (i = 'z'; i >= 'A'; i--) { // Send bytes from 'z' downto 'A'
Soft_UART_Write(i);
Delay_ms(100);
}

while(1) { // Endless loop


byte_read = Soft_UART_Read(&error); // Read byte, then test error flag
if (error) // If error was detected
PORTB = error; // signal it on PORTB
else
Soft_UART_Write(byte_read); // If error was not detected, return byte read
}
}

Sound Library

www.raguvaran.puzl.com
The mikroC PRO for PIC provides a Sound Library to supply users with routines necessary for sound
signalization in their applications. Sound generation needs additional hardware, such as piezo-speaker
(example of piezo-speaker interface is given on the schematic at the bottom of this page).

Library Routines
 Sound_Init
 Sound_Play

Sound_Init

Prototype void Sound_Init(char *snd_port, char snd_pin);

Returns Nothing.

Description Configures the appropriate MCU pin for sound generation.

Parameters :

 snd_port: sound output port address


 snd_pin: sound output pin

Requires Nothing.

Example // Initialize the pin RC3 for playing sound


Sound_Init(&PORTC, 3);

Sound_Play

Prototype void Sound_Play(unsigned freq_in_hz, unsigned duration_ms);

Returns Nothing.

Description Generates the square wave signal on the appropriate pin.

Parameters :

 freq_in_hz: signal frequency in Hertz (Hz)


 duration_ms: signal duration in miliseconds (ms)

Note : Frequency range is limited by Delay_Cyc parameter. Maximum frequency


that can be produced by this function is Freq_max = Fosc/(80*3). Minimum frequency
isFreq_min = Fosc/(80*255). Generated frequency may differ from
the freq_in_hz parameter due to integer arithmetics.

Requires In order to hear the sound, you need a piezo speaker (or other hardware) on

www.raguvaran.puzl.com
designated port. Also, you must call Sound_Init to prepare hardware for output before
using this function.

Example // Play sound of 1KHz in duration of 100ms


Sound_Play(1000, 100);

Library Example
The example is a simple demonstration of how to use the Sound Library for playing tones on a piezo
speaker.

Copy Code To Clipboard

void Tone1() {
Sound_Play(659, 250); // Frequency = 659Hz, duration = 250ms
}

void Tone2() {
Sound_Play(698, 250); // Frequency = 698Hz, duration = 250ms
}

void Tone3() {
Sound_Play(784, 250); // Frequency = 784Hz, duration = 250ms
}

void Melody() { // Plays the melody "Yellow house"


Tone1(); Tone2(); Tone3(); Tone3();
Tone1(); Tone2(); Tone3(); Tone3();
Tone1(); Tone2(); Tone3();
Tone1(); Tone2(); Tone3(); Tone3();
Tone1(); Tone2(); Tone3();
Tone3(); Tone3(); Tone2(); Tone2(); Tone1();
}

void ToneA() {
Sound_Play( 880, 50);
}
void ToneC() {
Sound_Play(1046, 50);
}
void ToneE() {
Sound_Play(1318, 50);
}

void Melody2() {
unsigned short i;
for (i = 9; i > 0; i--) {
ToneA(); ToneC(); ToneE();
}
}

void main() {

ANSEL = 0; // Configure AN pins as digital


ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;

TRISB = 0xF8; // Configure RB7..RB3 as input

Sound_Init(&PORTC, 3);
Sound_Play(880, 1000); // Play sound at 880Hz for 1 second

www.raguvaran.puzl.com
while (1) {
if (Button(&PORTB,7,1,1)) // RB7 plays Tone1
Tone1();
while (RB7_bit) ; // Wait for button to be released

if (Button(&PORTB,6,1,1)) // RB6 plays Tone2


Tone2();
while (RB6_bit) ; // Wait for button to be released

if (Button(&PORTB,5,1,1)) // RB5 plays Tone3


Tone3();
while (RB5_bit) ; // Wait for button to be released

if (Button(&PORTB,4,1,1)) // RB4 plays Melody2


Melody2();
while (RB4_bit) ; // Wait for button to be released

if (Button(&PORTB,3,1,1)) // RB3 plays Melody


Melody();
while (RB3_bit) ; // Wait for button to be released
}
}

HW Connection

www.raguvaran.puzl.com
Example of Sound Library connection

www.raguvaran.puzl.com
SPI Library
The mikroC PRO for PIC provides a library for comfortable with SPI work in Master mode. The
PIC MCU can easily communicate with other devices via SPI: A/D converters, D/A converters, MAX7219,
LTC1290, etc.

Important :

 SPI routines require you to specify the module you want to use. To select the desired SPI,
simply change the letter x in the prototype for a number from 1 to 2.
Number of SPI modules per MCU differs from chip to chip. Please, read the appropriate
datasheet before utilizing this library.
 Some MCUs have multiple SPI modules. Switching between the SPI modules in
the SPI library is done by the SPI_Set_Active function (SPI module has to be previously
initialized).
 Some of the MCUs do not support SPIx_Init_Advanced routine. Please, refer to the
appropriate datasheet.
 Certain SPI lines on some PIC16 Enhanced Family MCUs can be routed through a
alternative pins. These pins are selected by configuring APFCON register and appropriate
TRIS register.

Library Routines
 SPIx_Init
 SPIx_Init_Advanced
 SPIx_Read
 SPIx_Write
 SPI_Set_Active

Generic Routines
 SPI_Read
 SPI_Write

SPIx_Init

Prototype void SPIx_Init();

Returns Nothing.

Description This routine configures and enables SPI module with the following settings:
 master mode
 clock Fosc/4
 clock idle state low
 data transimtted on low to high edge
 input data sampled at the middle of interval

Requires You need PIC MCU with hardware integrated SPI.

Example // Initialize the SPI1 module with default settings


SPI1_Init();

www.raguvaran.puzl.com
SPIx_Init_Advanced

Prototype void SPIx_Init_Advanced(unsigned short master_slav, unsigned


short data_sample, unsigned short clock_idle, unsigned
short transmit_edge);

Returns Nothing.

Description Configures and initializes SPI. SPIx_Init or SPIx_Init_Advanced needs to be called


before using other functions of SPI Library.
Parameters mode, data_sample and clock_idle configure the SPI module, and can have
the following values:
Description Predefined library const

SPI work mode:

Master clock = Fosc/4 _SPI_MASTER_OSC_DIV4

Master clock = Fosc/16 _SPI_MASTER_OSC_DIV16

Master clock = Fosc/64 _SPI_MASTER_OSC_DIV64

Master clock source TMR2 _SPI_MASTER_TMR2

Slave select enabled _SPI_SLAVE_SS_ENABLE

Slave select disabled _SPI_SLAVE_SS_DIS

Data sampling interval:

Input data sampled in middle of interval _SPI_DATA_SAMPLE_MIDDLE

Input data sampled at the end of interval _SPI_DATA_SAMPLE_END

SPI clock idle state:

Clock idle HIGH _SPI_CLK_IDLE_HIGH

www.raguvaran.puzl.com
Clock idle LOW _SPI_CLK_IDLE_LOW

Transmit edge:

Data transmit on low to high edge _SPI_LOW_2_HIGH

Data transmit on high to low edge _SPI_HIGH_2_LOW

Requires You need PIC MCU with hardware integrated SPI.

Example // Set SPI1 module to master mode, clock = Fosc/4, data sampled at the middle of
interval, clock idle state low and data transmitted at low to high edge:
SPI1_Init_Advanced(_SPI_MASTER_OSC_DIV4, _SPI_DATA_SAMPLE_MIDDLE,
_SPI_CLK_IDLE_LOW, _SPI_LOW_2_HIGH);

SPIx_Read

Prototype unsigned short SPIx_Read(unsigned short buffer);

Returns Returns the received data.

Description Reads one byte from the SPI bus.

Parameters :

 buffer: dummy data for clock generation (see device Datasheet for SPI
modules implementation details)

Requires You need PIC MCU with hardware integrated SPI.


SPI must be initialized and communication established before using this function.
See SPIx_Init_Advanced or SPIx_Init.

Example short take, buffer;


...
take = SPI1_Read(buffer);

SPIx_Write

Prototype void SPIx_Write(unsigned short data_);

Returns Nothing.

www.raguvaran.puzl.com
Description Writes byte via the SPI bus.

Parameters :

 wrdata: data to be sent

Requires You need PIC MCU with hardware integrated SPI.


SPI must be initialized and communication established before using this function.
See SPIx_Init_Advanced or SPIx_Init.

Example // write a byte to the SPI bus


char buffer;
...
SPI1_Write(buffer);

SPI_Set_Active

Prototype void SPI_Set_Active(char (*read_ptr)(char), void(*write_ptr)(char))

Returns Nothing.

Description Sets the active SPI module which will be used by the SPI routines.
Parameters :

 read_ptr: SPIx_Read handler


 write_ptr: SPIx_Write handler

Requires Routine is available only for MCUs with two SPI modules.

Used SPI module must be initialized before using this function. See
the SPIx_Init, SPIx_Init_Advanced

Example SPI_Set_Active(&SPI2_Read, &SPI2_Write); // Sets the SPI2 module active

SPI_Read

Prototype unsigned short SPI_Read(unsigned short buffer);

Returns Returns the received data.

Description Reads one byte from the SPI bus.

This is a generic routine which uses the active SPI module previously activated by
the SPI_Set_Active routine.

www.raguvaran.puzl.com
Parameters :

 buffer: dummy data for clock generation (see device Datasheet for SPI
modules implementation details)

Requires You need PIC MCU with hardware integrated SPI.


SPI must be initialized and communication established before using this function.
See SPIx_Init_Advanced or SPIx_Init.

Example short take, buffer;


...
take = SPI_Read(buffer);

SPI_Write

Prototype void SPI_Write(unsigned short data_);

Returns Nothing.

Description Writes byte via the SPI bus.

This is a generic routine which uses the active SPI module previously activated by
the SPI_Set_Active routine.
Parameters :

 wrdata: data to be sent

Requires You need PIC MCU with hardware integrated SPI.


SPI must be initialized and communication established before using this function.
See SPIx_Init_Advanced or SPIx_Init.

Example // write a byte to the SPI bus


char buffer;
...
SPI_Write(buffer);

Library Example
The code demonstrates how to use SPI library functions for communication between SPI module of the
MCU and Microchip's MCP4921 12-bit D/A converter
Copy Code To Clipboard

// DAC module connections


sbit Chip_Select at RC0_bit;
sbit Chip_Select_Direction at TRISC0_bit;
// End DAC module connections

unsigned int value;

void InitMain() {
TRISA0_bit = 1; // Set RA0 pin as input

www.raguvaran.puzl.com
TRISA1_bit = 1; // Set RA1 pin as input
Chip_Select = 1; // Deselect DAC
Chip_Select_Direction = 0; // Set CS# pin as Output
SPI1_Init(); // Initialize SPI module
}

// DAC increments (0..4095) --> output voltage (0..Vref)


void DAC_Output(unsigned int valueDAC) {
char temp;

Chip_Select = 0; // Select DAC chip

// Send High Byte


temp = (valueDAC >> 8) & 0x0F; // Store valueDAC[11..8] to temp[3..0]
temp |= 0x30; // Define DAC setting, see MCP4921 datasheet
SPI1_Write(temp); // Send high byte via SPI

// Send Low Byte


temp = valueDAC; // Store valueDAC[7..0] to temp[7..0]
SPI1_Write(temp); // Send low byte via SPI

Chip_Select = 1; // Deselect DAC chip


}

void main() {
ANSEL = 0;
ANSELH = 0;
InitMain(); // Perform main initialization

value = 2048; // When program starts, DAC gives


// the output in the mid-range

while (1) { // Endless loop

if ((RA0_bit) && (value < 4095)) { // If RA0 button is pressed


value++; // increment value
}
else {
if ((RA1_bit) && (value > 0)) { // If RA1 button is pressed
value--; // decrement value
}
}
DAC_Output(value); // Send value to DAC chip
Delay_ms(1); // Slow down key repeat pace
}
}

www.raguvaran.puzl.com
HW Connection

SPI HW connection

www.raguvaran.puzl.com
SPI Remappable Library
SPI Remappable module is available with these MCUs: 18F2xJ11, 18F4xJ11, 18F2xJ50 and 18F4xJ50.
mikroC PRO for PIC provides a library for initializing Slave mode and comfortable work with Master
mode. PIC can easily communicate with other devices via SPI: A/D converters, D/A converters,
MAX7219, LTC1290, etc.
Note : Before using this library, make sure that Peripheral Pin Select Library and SPI Library are
checked in the Library Manager, and that appropriate pins were mapped.

Library Dependency Tree

Library Routines
 SPI_Remappable_Init
 SPI_Remappable_Init_Advanced
 SPI_Remappable_Read
 SPI_Remappable_Write

SPI_Remappable_Init

Prototype void SPI_Remappable_Init();

Returns Nothing.

Description Configures and initializes SPI Remappable module with default


settings. SPI_Remappable_Init_Advanced or SPI_Remappable_Init_Init needs to be called
before using other functions from SPI Remappable Library.
Default settings are:

 master mode
 clock Fosc/4
 clock idle state low
 data transimtted on low to high edge
 input data sampled at the middle of interval

Note : Before using this library, make sure that Peripheral Pin Select Library is
checked in the Library Manager, and that appropriate pins were mapped.

Requires You'll need PIC MCU with hardware integrated SPI and remappable feature.

Example // Initialize the SPI Remappable module with default settings


SPI_Remappable_Init();

SPI_Remappable_Init_Advanced

Prototype void SPI_Remappable_Init_Advanced(b>unsigned short master_slav, unsigned


short data_sample, unsigned short clock_idle, unsigned
shorttransmit_edge);

www.raguvaran.puzl.com
Returns Nothing.

Description Configures and initializes SPI Remappable


module. SPI_Remappable_Init_Advanced or SPI_Remappable_Init needs to be called
before using other functions of SPI Library.

Note : Before using this library, make sure that Peripheral Pin Select Library is
checked in the Library Manager, and that appropriate pins were mapped.
Parameters mode, data_sample, clock_idle and transmit_edge configure the SPI module,
and can have the following values:
Description Predefined library const

SPI work mode:

Master clock = Fosc/4 _SPI_REMAPPABLE_MASTER_OSC_DIV4

Master clock = Fosc/16 _SPI_REMAPPABLE_MASTER_OSC_DIV16

Master clock = Fosc/64 _SPI_REMAPPABLE_MASTER_OSC_DIV64

Master clock source TMR2 _SPI_REMAPPABLE_MASTER_TMR2

Slave select enabled _SPI_REMAPPABLE_SLAVE_SS_ENABLE

Slave select disabled _SPI_REMAPPABLE_SLAVE_SS_DIS

Data sampling interval:

Input data sampled in middle of


_SPI_REMAPPABLE_DATA_SAMPLE_MIDDLE
interval

Input data sampled at the end of


_SPI_REMAPPABLE_DATA_SAMPLE_END
interval

SPI clock idle state:

Clock idle HIGH _SPI_REMAPPABLE_CLK_IDLE_HIGH

Clock idle LOW _SPI_REMAPPABLE_CLK_IDLE_LOW

Transmit edge:

Data transmit on low to high edge _SPI_REMAPPABLE_LOW_2_HIGH

Data transmit on high to low edge _SPI_REMAPPABLE_HIGH_2_LOW

Requires You need PIC MCU with hardware integrated SPI and remappable feature.

Example // Set SPI to master mode, clock = Fosc/4, data sampled at the middle of
interval, clock idle state low and data transmitted at low to high edge:
SPI_Remappable_Init_Advanced(_SPI_REMAPPABLE_MASTER_OSC_DIV4,
_SPI_REMAPPABLE_DATA_SAMPLE_MIDDLE, _SPI_REMAPPABLE_CLK_IDLE_LOW,

www.raguvaran.puzl.com
_SPI_REMAPPABLE_LOW_2_HIGH);

SPI_Remappable_Read

Prototype unsigned short SPI_Remappable_Read(unsigned short buffer);

Returns Returns the received data.

Description Reads one byte from the SPI bus.

Parameters :

 buffer: dummy data for clock generation (see device Datasheet for SPI
modules implementation details)

Requires You need PIC MCU with hardware integrated SPI and remappable feature.
SPI must be initialized and communication established before using this function.
See SPI_Remappable_Init_Advanced or SPI_Remappable_Init.

Example short take, buffer;


...
take = SPI_Remappable_Read(buffer);

SPI_Remappable_Write

Prototype void SPI_Remappable_Write(unsigned short data_);

Returns Nothing.

Description Writes byte data to SSPBUF, and immediately starts the transmission.

Requires You need PIC MCU with hardware integrated SPI and remappable feature.
SPI must be initialized and communication established before using this function.
See SPI_Remappable_Init_Advanced or SPI_Remappable_Init.

Example SPI_Remappable_Write(1);

www.raguvaran.puzl.com
SPI Ethernet ENC28J60 Library
The ENC28J60 is a stand-alone Ethernet controller with an industry standard Serial Peripheral Interface
(SPI). It is designed to serve as an Ethernet network interface for any controller equipped withSPI.
The ENC28J60 meets all of the IEEE 802.3 specifications. It incorporates a number of packet filtering
schemes to limit incoming packets. It also provides an internal DMA module for fast data throughput
and hardware assisted IP checksum calculations. Communication with the host controller is
implemented via two interrupt pins and the SPI, with data rates of up to 10 Mb/s. Two dedicated pins
are used for LED link and network activity indication.
This library is designed to simplify handling of the underlying hardware (ENC28J60). It works with any PIC
with integrated SPI and more than 4 Kb ROM memory. 38 to 40 MHz clock is recommended to get from
8 to 10 Mhz SPI clock, otherwise PIC should be clocked by ENC28J60 clock output due to its silicon bug
in SPI hardware. If you try lower PIC clock speed, there might be board hang or miss some requests.

SPI Ethernet ENC28J60 Library supports:

 IPv4 protocol.
 ARP requests.
 ICMP echo requests.
 UDP requests.
 TCP requests (no stack, no packet reconstruction).
 ARP client with cache.
 DNS client.
 UDP client.
 DHCP client.
 packet fragmentation is NOT supported.

Important :

 Due to PIC16 RAM/Flash limitations PIC16 library


does NOT have ARP, DNS, UDP and DHCP client support implemented.
 Global library variable SPI_Ethernet_userTimerSec is used to keep track of time for all client
implementations (ARP, DNS, UDP and DHCP). It is user responsibility to increment this
variable each second in it's code if any of the clients is used.
 For advanced users there are header files
("__EthEnc28j60.h" and "__EthEnc28j60Private.h") in Uses\P16 and Uses\P18 folders of the
compiler with description of all routines and global variables, relevant to the user,
implemented in the SPI Ethernet ENC28J60 Library.
 The appropriate hardware SPI module must be initialized before using any of the SPI
Ethernet ENC28J60 library routines. Refer to SPI Library.
 For MCUs with two SPI modules it is possible to initialize both of them and then switch by
using the SPI_Set_Active() routine.

Library Dependency Tree

www.raguvaran.puzl.com
External dependencies of SPI Ethernet ENC28J60 Library
The following variables must be defined
in all projects using SPI Ethernet Description: Examples :
ENC28J60 Library:

ENC28J60
extern sfr sbit SPI_Ethernet_CS; chip select sbit SPI_Ethernet_CS at RC1_bit;
pin.

extern sfr ENC28J60


sbit SPI_Ethernet_Rst at RC0_bit;
sbit SPI_Ethernet_RST; reset pin.

Direction of
the
extern sfr
ENC28J60 sbit SPI_Ethernet_CS_Direction atTRISC1_bit;
sbit SPI_Ethernet_CS_Direction;
chip select
pin.

Direction of
extern sfr the
sbit SPI_Ethernet_Rst_Direction atTRISC0_bit;
sbit SPI_Ethernet_RST_Direction; ENC28J60
reset pin.

The following routines must be defined in all


Description: Examples :
project using SPI Ethernet ENC28J60 Library:

unsigned Refer to the library


int SPI_Ethernet_UserTCP(unsigned
example at the
char*remoteHost, unsigned
int remotePort, unsigned
TCP request handler. bottom of this page
intlocalPort, unsigned for code
int reqLength, TEthPktFlags*flags); implementation.

unsigned Refer to the library


int SPI_Ethernet_UserUDP(unsigned
example at the
char*remoteHost, unsigned
int remotePort, unsigned
UDP request handler. bottom of this page
intlocalPort, unsigned for code
int reqLength, TEthPktFlags*flags); implementation.

Library Routines

PIC16 and PIC18:


 SPI_Ethernet_Init
 SPI_Ethernet_Enable
 SPI_Ethernet_Disable
 SPI_Ethernet_doPacket

www.raguvaran.puzl.com
 SPI_Ethernet_putByte
 SPI_Ethernet_putBytes
 SPI_Ethernet_putString
 SPI_Ethernet_putConstString
 SPI_Ethernet_putConstBytes
 SPI_Ethernet_getByte
 SPI_Ethernet_getBytes
 SPI_Ethernet_UserTCP
 SPI_Ethernet_UserUDP

PIC18 Only:
 SPI_Ethernet_getIpAddress
 SPI_Ethernet_getGwIpAddress
 SPI_Ethernet_getDnsIpAddress
 SPI_Ethernet_getIpMask
 SPI_Ethernet_confNetwork
 SPI_Ethernet_arpResolve
 SPI_Ethernet_sendUDP
 SPI_Ethernet_dnsResolve
 SPI_Ethernet_initDHCP
 SPI_Ethernet_doDHCPLeaseTime
 SPI_Ethernet_renewDHCP

SPI_Ethernet_Init

Prototype void SPI_Ethernet_Init(unsigned char *mac, unsigned char *ip, unsigned


char fullDuplex);

Returns Nothing.

Description This is MAC module routine. It initializes ENC28J60 controller. This function is internaly splited into 2 parts to
help linker when coming short of memory.
ENC28J60 controller settings (parameters not mentioned here are set to default):
 receive buffer start address : 0x0000.
 receive buffer end address : 0x19AD.
 transmit buffer start address: 0x19AE.
 transmit buffer end address : 0x1FFF.
 RAM buffer read/write pointers in auto-increment mode.
 receive filters set to default: CRC + MAC Unicast + MAC Broadcast in OR mode.
 flow control with TX and RX pause frames in full duplex mode.
 frames are padded to 60 bytes + CRC.
 maximum packet size is set to 1518.
 Back-to-Back Inter-Packet Gap: 0x15 in full duplex mode; 0x12 in half duplex mode.
 Non-Back-to-Back Inter-Packet Gap: 0x0012 in full duplex mode; 0x0C12 in half duplex mode.
 Collision window is set to 63 in half duplex mode to accomodate some ENC28J60 revisions
silicon bugs.
 CLKOUT output is disabled to reduce EMI generation.
 half duplex loopback disabled.
 LED configuration: default (LEDA-link status, LEDB-link activity).
Parameters:

 mac: RAM buffer containing valid MAC address.

www.raguvaran.puzl.com
 ip: RAM buffer containing valid IP address.
 fullDuplex: ethernet duplex mode switch. Valid values: 0 (half duplex mode) and 1 (full
duplex mode).

Requires Global variables :

 SPI_Ethernet_CS: Chip Select line


 SPI_Ethernet_CS_Direction: Direction of the Chip Select pin
 SPI_Ethernet_RST: Reset line
 SPI_Ethernet_RST_Direction: Direction of the Reset pin
must be defined before using this function.

The SPI module needs to be initialized. See the SPIx_Init and SPIx_Init_Advanced routines.

Example #define SPI_Ethernet_HALFDUPLEX 0


#define SPI_Ethernet_FULLDUPLEX 1

// mE ethernet NIC pinout


sfr sbit SPI_Ethernet_Rst at RC0_bit;
sfr sbit SPI_Ethernet_CS at RC1_bit;
sfr sbit SPI_Ethernet_Rst_Direction at TRISC0_bit;
sfr sbit SPI_Ethernet_CS_Direction at TRISC1_bit;
// end ethernet NIC definitions

unsigned char myMacAddr[6] = {0x00, 0x14, 0xA5, 0x76, 0x19, 0x3f}; // my MAC address
unsigned char myIpAddr = {192, 168, 1, 60 }; // my IP addr

SPI1_Init();
SPI_Ethernet_Init(myMacAddr, myIpAddr, SPI_Ethernet_FULLDUPLEX);

SPI_Ethernet_Enable

Prototype void SPI_Ethernet_Enable(unsigned char enFlt);

Returns Nothing.

Description This is MAC module routine. This routine enables appropriate network traffic on the ENC28J60 module by the
means of it's receive filters (unicast, multicast, broadcast, crc). Specific type of network traffic will be enabled if a
corresponding bit of this routine's input parameter is set. Therefore, more than one type of network traffic can be
enabled at the same time. For this purpose, predefined library constants (see the table below) can be ORed to form
appropriate input value.
Parameters:

 enFlt: network traffic/receive filter flags. Each bit corresponds to the appropriate network
traffic/receive filter:

Bit Mask Description Predefined library const

0 0x01 MAC Broadcast traffic/receive filter flag. _SPI_Ethernet_BROADCAST


When set, MAC broadcast traffic will be

www.raguvaran.puzl.com
enabled.

MAC Multicast traffic/receive filter flag.


1 0x02 When set, MAC multicast traffic will be _SPI_Ethernet_MULTICAST
enabled.

2 0x04 not used none

3 0x08 not used none

4 0x10 not used none

CRC check flag. When set, packets with


5 0x20 _SPI_Ethernet_CRC
invalid CRC field will be discarded.

6 0x40 not used none

MAC Unicast traffic/receive filter flag.


7 0x80 When set, MAC unicast traffic will be _SPI_Ethernet_UNICAST
enabled.

Note :

 Advanced filtering available in the ENC28J60 module such as Pattern


Match, Magic Packet and Hash Table can not be enabled by this routine.
Additionaly, all filters, except CRC, enabled with this routine will work in OR mode,
which means that packet will be received if any of the enabled filters accepts it.
 This routine will change receive filter configuration on-the-fly. It will not, in any
way, mess with enabling/disabling receive/transmit logic or any other part of
the ENC28J60 module. The ENC28J60 module should be properly cofigured by the
means of SPI_Ethernet_Init routine.

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.

Example SPI_Ethernet_Enable(_SPI_Ethernet_CRC | _SPI_Ethernet_UNICAST); // enable CRC


checking and Unicast traffic

SPI_Ethernet_Disable

Prototype void SPI_Ethernet_Disable(unsigned char disFlt);

www.raguvaran.puzl.com
Returns Nothing.

Description This is MAC module routine. This routine disables appropriate network traffic on the ENC28J60 module by the
means of it's receive filters (unicast, multicast, broadcast, crc). Specific type of network traffic will be disabled if a
corresponding bit of this routine's input parameter is set. Therefore, more than one type of network traffic can be
disabled at the same time. For this purpose, predefined library constants (see the table below) can be ORed to
form appropriate input value.
Parameters:

 disFlt: network traffic/receive filter flags. Each bit corresponds to the appropriate network
traffic/receive filter:

Bit Mask Description Predefined library const

MAC Broadcast traffic/receive filter flag.


0 0x01 When set, MAC broadcast traffic will be _SPI_Ethernet_BROADCAST
disabled.

MAC Multicast traffic/receive filter flag.


1 0x02 When set, MAC multicast traffic will be _SPI_Ethernet_MULTICAST
disabled.

2 0x04 not used none

3 0x08 not used none

4 0x10 not used none

CRC check flag. When set, CRC check will


5 0x20 be disabled and packets with _SPI_Ethernet_CRC
invalid CRC field will be accepted.

6 0x40 not used none

MAC Unicast traffic/receive filter flag.


7 0x80 When set, MAC unicast traffic will be _SPI_Ethernet_UNICAST
disabled.

Note :

 Advanced filtering available in the ENC28J60 module such as Pattern

www.raguvaran.puzl.com
Match, Magic Packet and Hash Table can not be disabled by this routine.
 This routine will change receive filter configuration on-the-fly. It will not, in any
way, mess with enabling/disabling receive/transmit logic or any other part of
the ENC28J60 module.
 The ENC28J60 module should be properly cofigured by the means
of SPI_Ethernet_Init routine.

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.

Example SPI_Ethernet_Disable(_SPI_Ethernet_CRC | _SPI_Ethernet_UNICAST); // disable CRC


checking and Unicast traffic

SPI_Ethernet_doPacket

Prototype unsigned char SPI_Ethernet_doPacket();

Returns  0 - upon successful packet processing (zero packets received or received packet processed
successfully).
 1 - upon reception error or receive buffer corruption. ENC28J60 controller needs to be
restarted.
 2 - received packet was not sent to us (not our IP, nor IP broadcast address).
 3 - received IP packet was not IPv4.
 4 - received packet was of type unknown to the library.

Description This is MAC module routine. It processes next received packet if such exists. Packets are processed in the
following manner:
 ARP & ICMP requests are replied automatically.
 upon TCP request the SPI_Ethernet_UserTCP function is called for further processing.
 upon UDP request the SPI_Ethernet_UserUDP function is called for further processing.

Note : SPI_Ethernet_doPacket must be called as often as possible in user's code.

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.

Example if (SPI_Ethernet_doPacket() == 0)(1) { // process received packets


...
}

SPI_Ethernet_putByte

Prototype void SPI_Ethernet_putByte(unsigned char v);

Returns Nothing.

www.raguvaran.puzl.com
Description This is MAC module routine. It stores one byte to address pointed by the current ENC28J60 write pointer
(EWRPT).
Parameters:

 v: value to store

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.

Example char data_;


...
SPI_Ethernet_putByte(data); // put an byte into ENC28J60 buffer

SPI_Ethernet_putBytes

Prototype void SPI_Ethernet_putBytes(unsigned char *ptr, unsigned int n);

Returns Nothing.

Description This is MAC module routine. It stores requested number of bytes into ENC28J60 RAM starting from
current ENC28J60 write pointer (EWRPT) location.
Parameters:

 ptr: RAM buffer containing bytes to be written into ENC28J60 RAM.


 n: number of bytes to be written.

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.

Example char *buffer = "mikroElektronika";


...
SPI_Ethernet_putBytes(buffer, 16); // put an RAM array into ENC28J60 buffer

SPI_Ethernet_putConstBytes

Prototype void SPI_Ethernet_putConstBytes(const unsigned char *ptr, unsigned int n);

Returns Nothing.

Description This is MAC module routine. It stores requested number of const bytes into ENC28J60 RAM starting from
current ENC28J60 write pointer (EWRPT) location.
Parameters:

 ptr: const buffer containing bytes to be written into ENC28J60 RAM.


 n: number of bytes to be written.

www.raguvaran.puzl.com
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.

Example const char *buffer = "mikroElektronika";


...
SPI_Ethernet_putConstBytes(buffer, 16); // put a const array into ENC28J60 buffer

SPI_Ethernet_putString

Prototype unsigned int SPI_Ethernet_putString(unsigned char *ptr);

Returns Number of bytes written into ENC28J60 RAM.

Description This is MAC module routine. It stores whole string (excluding null termination) into ENC28J60 RAM starting
from current ENC28J60 write pointer (EWRPT) location.
Parameters:

 ptr: string to be written into ENC28J60 RAM.

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.

Example char *buffer = "mikroElektronika";


...
SPI_Ethernet_putString(buffer); // put a RAM string into ENC28J60 buffer

SPI_Ethernet_putConstString

Prototype unsigned int SPI_Ethernet_putConstString(const unsigned char *ptr);

Returns Number of bytes written into ENC28J60 RAM.

Description This is MAC module routine. It stores whole const string (excluding null termination)
into ENC28J60 RAM starting from current ENC28J60 write pointer (EWRPT) location.
Parameters:

 ptr: const string to be written into ENC28J60 RAM.

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.

Example const char *buffer = "mikroElektronika";


...
SPI_Ethernet_putConstString(buffer); // put a const string into ENC28J60 buffer

www.raguvaran.puzl.com
SPI_Ethernet_getByte

Prototype unsigned char SPI_Ethernet_getByte();

Returns Byte read from ENC28J60 RAM.

Description This is MAC module routine. It fetches a byte from address pointed to by current ENC28J60 read pointer
(ERDPT).

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.

Example char buffer;


...
buffer = SPI_Ethernet_getByte(); // read a byte from ENC28J60 buffer

SPI_Ethernet_getBytes

Prototype void SPI_Ethernet_getBytes(unsigned char *ptr, unsigned int addr, unsigned


int n);

Returns Nothing.

Description This is MAC module routine. It fetches equested number of bytes from ENC28J60 RAM starting from given
address. If value of 0xFFFF is passed as the address parameter, the reading will start from current ENC28J60 read
pointer (ERDPT) location.
Parameters:

 ptr: buffer for storing bytes read from ENC28J60 RAM.


 addr: ENC28J60 RAM start address. Valid values: 0..8192.
 n: number of bytes to be read.

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.

Example char buffer[16];


...
SPI_Ethernet_getBytes(buffer, 0x100, 16); // read 16 bytes, starting from address
0x100

SPI_Ethernet_UserTCP

Prototype unsigned int SPI_Ethernet_UserTCP(unsigned char *remoteHost, unsigned


int remotePort, unsigned int localPort, unsigned
int reqLength, TEthPktFlags*flags);

Returns  0 - there should not be a reply to the request.


 Length of TCP/HTTP reply data field - otherwise.

www.raguvaran.puzl.com
Description This is TCP module routine. It is internally called by the library. The user accesses to the TCP/HTTP request
by using some of the SPI_Ethernet_get routines. The user puts data in the transmit buffer by using some of the
SPI_Ethernet_put routines. The function must return the length in bytes of the TCP/HTTP reply, or 0 if there is
nothing to transmit. If there is no need to reply to the TCP/HTTP requests, just define this function with
return(0) as a single statement.
Parameters:

 remoteHost: client's IP address.


 remotePort: client's TCP port.
 localPort: port to which the request is sent.
 reqLength: TCP/HTTP request data field length.
 flags: structure consisted of two bit fields :
Copy Code To Clipboard

typedef struct {
unsigned canCloseTCP: 1; // flag which closes socket
unsigned isBroadcast: 1; // flag which denotes that the IP package has
been received via subnet broadcast address (not used for PIC16 family)
} TEthPktFlags;

Note : The function source code is provided with appropriate example projects. The code should be
adjusted by the user to achieve desired reply.

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.

Example This function is internally called by the library and should not be called by the user's code.

SPI_Ethernet_UserUDP

Prototype unsigned int SPI_Ethernet_UserUDP(unsigned char *remoteHost, unsigned


int remotePort, unsigned int destPort, unsigned
int reqLength, TEthPktFlags*flags);

Returns  0 - there should not be a reply to the request.


 Length of UDP reply data field - otherwise.

Description This is UDP module routine. It is internally called by the library. The user accesses to the UDP request by using
some of the SPI_Ethernet_get routines. The user puts data in the transmit buffer by using some of the
SPI_Ethernet_put routines. The function must return the length in bytes of the UDP reply, or 0 if nothing to
transmit. If you don't need to reply to the UDP requests, just define this function with a return(0) as single
statement.
Parameters:

 remoteHost: client's IP address.


 remotePort: client's port.
 destPort: port to which the request is sent.
 flags: structure consisted of two bit fields :

www.raguvaran.puzl.com
Copy Code To Clipboard

typedef struct {
unsigned canCloseTCP: 1; // flag which closes TCP socket (not relevant
to UDP)
unsigned isBroadcast: 1; // flag which denotes that the IP package has
been received via subnet broadcast address (not used for PIC16 family)
} TEthPktFlags;

Note : The function source code is provided with appropriate example projects. The code
should be adjusted by the user to achieve desired reply.

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.

Example This function is internally called by the library and should not be called by the user's code.

SPI_Ethernet_getIpAddress

Prototype unsigned char * SPI_Ethernet_getIpAddress();

Returns Pointer to the global variable holding IP address.

Description This routine should be used when DHCP server is present on the network to fetch assigned IP address.

Note : User should always copy the IP address from the RAM location returned by this routine into it's
own IP address buffer. These locations should not be altered by the user in any case!

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.


Available for PIC18 family MCUs only.

Example unsigned char ipAddr[4]; // user IP address buffer


...
memcpy(ipAddr, SPI_Ethernet_getIpAddress(), 4); // fetch IP address

SPI_Ethernet_getGwIpAddress

Prototype unsigned char * SPI_Ethernet_getGwIpAddress();

Returns Pointer to the global variable holding gateway IP address.

Description This routine should be used when DHCP server is present on the network to fetch assigned gateway IP address.

www.raguvaran.puzl.com
Note : User should always copy the IP address from the RAM location returned by this routine into it's
own gateway IP address buffer. These locations should not be altered by the user in any case!

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.


Available for PIC18 family MCUs only.

Example unsigned char gwIpAddr[4]; // user gateway IP address buffer


...
memcpy(gwIpAddr, SPI_Ethernet_getGwIpAddress(), 4); // fetch gateway IP address

SPI_Ethernet_getDnsIpAddress

Prototype unsigned char * SPI_Ethernet_getDnsIpAddress()

Returns Pointer to the global variable holding DNS IP address.

Description his routine should be used when DHCP server is present on the network to fetch assigned DNS IP address.

Note : User should always copy the IP address from the RAM location returned by this routine into it's
own DNS IP address buffer. These locations should not be altered by the user in any case!

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.


Available for PIC18 family MCUs only.

Example unsigned char dnsIpAddr[4]; // user DNS IP address buffer


...
memcpy(dnsIpAddr, SPI_Ethernet_getDnsIpAddress(), 4); // fetch DNS server address

SPI_Ethernet_getIpMask

Prototype unsigned char * SPI_Ethernet_getIpMask()

Returns Pointer to the global variable holding IP subnet mask.

Description This routine should be used when DHCP server is present on the network to fetch assigned IP subnet mask.

Note : User should always copy the IP address from the RAM location returned by this routine into it's
own IP subnet mask buffer. These locations should not be altered by the user in any case!

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.


Available for PIC18 family MCUs only.

www.raguvaran.puzl.com
Example unsigned char IpMask[4]; // user IP subnet mask buffer
...
memcpy(IpMask, SPI_Ethernet_getIpMask(), 4); // fetch IP subnet mask

SPI_Ethernet_confNetwork

Prototype void SPI_Ethernet_confNetwork(char *ipMask, char *gwIpAddr, char *dnsIpAddr)


;

Returns Nothing.

Descriptio Configures network parameters (IP subnet mask, gateway IP address, DNS IP address) when DHCP is not
n used.
Parameters:

 ipMask: IP subnet mask.


 gwIpAddr gateway IP address.
 dnsIpAddr: DNS IP address.

Note : The above mentioned network parameters should be set by this routine only if DHCP module is not
used. Otherwise DHCP will override these settings.

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.


Available for PIC18 family MCUs only.

Example char ipMask[4] = {255, 255, 255, 0 }; // network mask (for example :
255.255.255.0)
char gwIpAddr[4] = {192, 168, 1, 1 }; // gateway (router) IP address
char dnsIpAddr[4] = {192, 168, 1, 1 }; // DNS server IP address
...
SPI_Ethernet_confNetwork(ipMask, gwIpAddr, dnsIpAddr); // set network configuration
parameters

SPI_Ethernet_arpResolve

Prototype unsigned char *SPI_Ethernet_arpResolve(unsigned char *ip, unsigned


char tmax);

Returns  MAC address behind the IP address - the requested IP address was resolved.
 0 - otherwise.

Description This is ARP module routine. It sends an ARP request for given IP address and waits for ARP reply. If the
requested IP address was resolved, an ARP cash entry is used for storing the configuration. ARP cash can store
up to 3 entries. For ARP cash structure refer to "eth_enc28j60LibDef.h" header file in the compiler's
Uses/P18 folder.
Parameters:

 ip: IP address to be resolved.


 tmax: time in seconds to wait for an reply.

www.raguvaran.puzl.com
Note : The Ethernet services are not stopped while this routine waits for ARP reply. The incoming packets
will be processed normaly during this time.

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.


Available for PIC18 family MCUs only.

Example unsigned char IpAddr[4] = {192, 168, 1, 1 }; // IP address


...
SPI_Ethernet_arpResolve(IpAddr, 5); // get MAC address behind the above IP address,
wait 5 secs for the response

SPI_Ethernet_sendUDP

Prototype unsigned char SPI_Ethernet_sendUDP(unsigned char *destIP, unsigned


int sourcePort, unsigned int destPort, unsigned char *pkt, unsigned
int pktLen);

Returns  1 - UDP packet was sent successfully.


 0 - otherwise.

Description This is UDP module routine. It sends an UDP packet on the network.
Parameters:

 destIP: remote host IP address.


 sourcePort: local UDP source port number.
 destPort: destination UDP port number.
 pkt: packet to transmit.
 pktLen: length in bytes of packet to transmit.

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.


Available for PIC18 family MCUs only.

Example unsigned char IpAddr[4] = {192, 168, 1, 1 }; // remote IP address


...
SPI_Ethernet_sendUDP(IpAddr, 10001, 10001, "Hello", 5); // send Hello message to the
above IP address, from UDP port 10001 to UDP port 10001

SPI_Ethernet_dnsResolve

Prototype unsigned char * SPI_Ethernet_dnsResolve(unsigned char *host, unsigned


char tmax);

Returns  pointer to the location holding the IP address - the requested host name was resolved.
 0 - otherwise.

Description This is DNS module routine. It sends an DNS request for given host name and waits for DNS reply. If the
requested host name was resolved, it's IP address is stored in library global variable and a pointer containing this
address is returned by the routine. UDP port 53 is used as DNS port.

www.raguvaran.puzl.com
Parameters:

 host: host name to be resolved.


 tmax: time in seconds to wait for an reply.

Note :

 The Ethernet services are not stopped while this routine waits for DNS reply. The incoming
packets will be processed normaly during this time.
 User should always copy the IP address from the RAM location returned by this routine into it's
own resolved host IP address buffer. These locations should not be altered by the user in any
case!

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.


Available for PIC18 family MCUs only.

Example unsigned char * remoteHostIpAddr[4]; // user host IP address buffer


...
// SNTP server:
// Zurich, Switzerland: Integrated Systems Lab, Swiss Fed. Inst. of Technology
// 129.132.2.21: swisstime.ethz.ch
// Service Area: Switzerland and Europe
memcpy(remoteHostIpAddr, SPI_Ethernet_dnsResolve("swisstime.ethz.ch", 5), 4);

SPI_Ethernet_initDHCP

Prototype unsigned char SPI_Ethernet_initDHCP(unsigned char tmax);

Returns  1 - network parameters were obtained successfully.


 0 - otherwise.

Description This is DHCP module routine. It sends an DHCP request for network parameters (IP, gateway, DNS addresses
and IP subnet mask) and waits for DHCP reply. If the requested parameters were obtained successfully, their
values are stored into the library global variables.
These parameters can be fetched by using appropriate library IP get routines:
 SPI_Ethernet_getIpAddress - fetch IP address.
 SPI_Ethernet_getGwIpAddress - fetch gateway IP address.
 SPI_Ethernet_getDnsIpAddress - fetch DNS IP address.
 SPI_Ethernet_getIpMask - fetch IP subnet mask.
UDP port 68 is used as DHCP client port and UDP port 67 is used as DHCP server port.
Parameters:

 tmax: time in seconds to wait for an reply.

Note :

 The Ethernet services are not stopped while this routine waits for DNS reply. The incoming
packets will be processed normaly during this time.
 When DHCP module is used, global library variable SPI_Ethernet_userTimerSec is used to
keep track of time. It is user responsibility to increment this variable each second in it's code.

www.raguvaran.puzl.com
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
Available for PIC18 family MCUs only.

Example ...
SPI_Ethernet_initDHCP(5); // get network configuration from DHCP server, wait 5 sec
for the response
...

SPI_Ethernet_doDHCPLeaseTime

Prototype unsigned char SPI_Ethernet_doDHCPLeaseTime();

Returns  0 - lease time has not expired yet.


 1 - lease time has expired, it's time to renew it.

Description This is DHCP module routine. It takes care of IP address lease time by decrementing the global lease time
library counter. When this time expires, it's time to contact DHCPserver and renew the lease.

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.


Available for PIC18 family MCUs only.

Example while(1) {
...
if(SPI_Ethernet_doDHCPLeaseTime())
... // it's time to renew the IP address lease
}

SPI_Ethernet_renewDHCP

Prototype unsigned char SPI_Ethernet_renewDHCP(unsigned char tmax);

Returns  1 - upon success (lease time was renewed).


 0 - otherwise (renewal request timed out).

Description This is DHCP module routine. It sends IP address lease time renewal request to DHCP server.
Parameters:

 tmax: time in seconds to wait for an reply.

Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.


Available for PIC18 family MCUs only.

Example while(1) {
...
if(SPI_Ethernet_doDHCPLeaseTime())
SPI_Ethernet_renewDHCP(5); // it's time to renew the IP address lease, with 5
secs for a reply
...
}

www.raguvaran.puzl.com
Library Example
This code shows how to use the Ethernet mini library :

 the board will reply to ARP & ICMP echo requests


 the board will reply to UDP requests on any port :
 returns the request in upper char with a header made of remote host IP & port
number
 the board will reply to HTTP requests on port 80, GET method with pathnames :
 / will return the HTML main page
 /s will return board status as text string
 /t0 ... /t7 will toggle RD0 to RD7 bit and return HTML main page
 all other requests return also HTML main page.
Copy Code To Clipboard

#include "__EthEnc28j60.h"

// duplex config flags


#define Spi_Ethernet_HALFDUPLEX 0x00 // half duplex
#define Spi_Ethernet_FULLDUPLEX 0x01 // full duplex
// mE ehternet NIC pinout
sfr sbit SPI_Ethernet_Rst at RC0_bit;
sfr sbit SPI_Ethernet_CS at RC1_bit;
sfr sbit SPI_Ethernet_Rst_Direction at TRISC0_bit;
sfr sbit SPI_Ethernet_CS_Direction at TRISC1_bit;
// end ethernet NIC definitions

/************************************************************
* ROM constant strings
*/
const unsigned char httpHeader[] = "HTTP/1.1 200 OKnContent-type: " ; // HTTP header
const unsigned char httpMimeTypeHTML[] = "text/htmlnn" ; // HTML MIME type
const unsigned char httpMimeTypeScript[] = "text/plainnn" ; // TEXT MIME type
unsigned char httpMethod[] = "GET /";
/*
* web page, splited into 2 parts :
* when coming short of ROM, fragmented data is handled more efficiently by linker
*
* this HTML page calls the boards to get its status, and builds itself with javascript
*/
const char *indexPage = // Change the IP address of the page to be refreshed
"<meta http-equiv="refresh" content="3;url=http://192.168.20.60">
<HTML><HEAD></HEAD><BODY>
<h1>PIC + ENC28J60 Mini Web Server</h1>
<a href=/>Reload</a>
<script src=/https/www.scribd.com/s></script>
<table><tr><td valign=top><table border=1 style="font-size:20px ;font-family: terminal ;">
<tr><th colspan=2>ADC</th></tr>
<tr><td>AN2</td><td><script>document.write(AN2)</script></td></tr>
<tr><td>AN3</td><td><script>document.write(AN3)</script></td></tr>
</table></td><td><table border=1 style="font-size:20px ;font-family: terminal ;">
<tr><th colspan=2>PORTB</th></tr>
<script>
var str,i;
str="";
for(i=0;i<8;i++)
{str+="<tr><td bgcolor=pink>BUTTON #"+i+"</td>";
if(PORTB&(1<<i)){str+="<td bgcolor=red>ON";}
else {str+="<td bgcolor=#cccccc>OFF";}

www.raguvaran.puzl.com
str+="</td></tr>";}
document.write(str) ;
</script>
" ;

const char *indexPage2 = "</table></td><td>


<table border=1 style="font-size:20px ;font-family: terminal ;">
<tr><th colspan=3>PORTD</th></tr>
<script>
var str,i;
str="";
for(i=0;i<8;i++)
{str+="<tr><td bgcolor=yellow>LED #"+i+"</td>";
if(PORTD&(1<<i)){str+="<td bgcolor=red>ON";}
else {str+="<td bgcolor=#cccccc>OFF";}
str+="</td><td><a href=/https/www.scribd.com/t"+i+">Toggle</a></td></tr>";}
document.write(str) ;
</script>
</table></td></tr></table>
This is HTTP request #<script>document.write(REQ)</script></BODY></HTML>
" ;

/***********************************
* RAM variables
*/
unsigned char myMacAddr[6] = {0x00, 0x14, 0xA5, 0x76, 0x19, 0x3f} ; // my MAC address
unsigned char myIpAddr[4] = {192, 168, 20, 60} ; // my IP address
unsigned char getRequest[15] ; // HTTP request buffer
unsigned char dyna[30] ; // buffer for dynamic
response
unsigned long httpCounter = 0 ; // counter of HTTP
requests

/*******************************************
* functions
*/

/*
* put the constant string pointed to by s to the ENC transmit buffer.
*/
/*unsigned int putConstString(const char *s)
{
unsigned int ctr = 0 ;

while(*s)
{
Spi_Ethernet_putByte(*s++) ;
ctr++ ;
}
return(ctr) ;
}*/
/*
* it will be much faster to use library Spi_Ethernet_putConstString routine
* instead of putConstString routine above. However, the code will be a little
* bit bigger. User should choose between size and speed and pick the implementation that
* suites him best. If you choose to go with the putConstString definition above
* the #define line below should be commented out.
*
*/
#define putConstString SPI_Ethernet_putConstString

/*
* put the string pointed to by s to the ENC transmit buffer
*/
/*unsigned int putString(char *s)
{
unsigned int ctr = 0 ;

www.raguvaran.puzl.com
while(*s)
{
Spi_Ethernet_putByte(*s++) ;

ctr++ ;
}
return(ctr) ;
}*/
/*
* it will be much faster to use library Spi_Ethernet_putString routine
* instead of putString routine above. However, the code will be a little
* bit bigger. User should choose between size and speed and pick the implementation that
* suites him best. If you choose to go with the putString definition above
* the #define line below should be commented out.
*
*/
#define putString SPI_Ethernet_putString

/*
* this function is called by the library
* the user accesses to the HTTP request by successive calls to Spi_Ethernet_getByte()
* the user puts data in the transmit buffer by successive calls to Spi_Ethernet_putByte()
* the function must return the length in bytes of the HTTP reply, or 0 if nothing to transmit
*
* if you don't need to reply to HTTP requests,
* just define this function with a return(0) as single statement
*
*/
unsigned int SPI_Ethernet_UserTCP(unsigned char *remoteHost, unsigned int remotePort, unsigned
int localPort, unsigned int reqLength, TEthPktFlags *flags)
{
unsigned int len = 0 ; // my reply length
unsigned int i ; // general purpose integer

// should we close tcp socket after response is sent?


// library closes tcp socket by default if canClose flag is not reset here
// flags->canClose = 0; // 0 - do not close socket
// otherwise - close socket

if(localPort != 80) // I listen only to web request on port 80


{
return(0) ;
}

// get 10 first bytes only of the request, the rest does not matter here
for(i = 0 ; i < 10 ; i++)
{
getRequest[i] = SPI_Ethernet_getByte() ;
}
getRequest[i] = 0 ;

if(memcmp(getRequest, httpMethod, 5)) // only GET method is supported here


{
return(0) ;
}

httpCounter++ ; // one more request done

if(getRequest[5] == 's') // if request path name starts with s, store


dynamic data in transmit buffer
{
// the text string replied by this request can be interpreted as javascript
statements
// by browsers

len = putConstString(httpHeader) ; // HTTP header

www.raguvaran.puzl.com
len += putConstString(httpMimeTypeScript) ; // with text MIME type

// add AN2 value to reply


IntToStr(ADC_Read(2), dyna) ;
len += putConstString("var AN2=") ;
len += putString(dyna) ;
len += putConstString(";") ;

// add AN3 value to reply


IntToStr(ADC_Read(3), dyna) ;
len += putConstString("var AN3=") ;
len += putString(dyna) ;
len += putConstString(";") ;

// add PORTB value (buttons) to reply


len += putConstString("var PORTB=") ;
IntToStr(PORTB, dyna) ;
len += putString(dyna) ;
len += putConstString(";") ;

// add PORTD value (LEDs) to reply


len += putConstString("var PORTD=") ;
IntToStr(PORTD, dyna) ;
len += putString(dyna) ;
len += putConstString(";") ;

// add HTTP requests counter to reply


IntToStr(httpCounter, dyna) ;
len += putConstString("var REQ=") ;
len += putString(dyna) ;
len += putConstString(";") ;
}
else if(getRequest[5] == 't') // if request path name starts
with t, toggle PORTD (LED) bit number that comes after
{
unsigned char bitMask = 0 ; // for bit mask

if(isdigit(getRequest[6])) // if 0 <= bit number <= 9, bits 8


& 9 does not exist but does not matter
{
bitMask = getRequest[6] - '0' ; // convert ASCII to integer
bitMask = 1 << bitMask ; // create bit mask
PORTD ^= bitMask ; // toggle PORTD with xor operator
}
}

if(len == 0) // what do to by default


{
len = putConstString(httpHeader) ; // HTTP header
len += putConstString(httpMimeTypeHTML) ; // with HTML MIME type
len += putConstString(indexPage) ; // HTML page first part
len += putConstString(indexPage2) ; // HTML page second part
}

return(len) ; // return to the library with the


number of bytes to transmit
}

/*
* this function is called by the library
* the user accesses to the UDP request by successive calls to Spi_Ethernet_getByte()
* the user puts data in the transmit buffer by successive calls to Spi_Ethernet_putByte()
* the function must return the length in bytes of the UDP reply, or 0 if nothing to transmit
*
* if you don't need to reply to UDP requests,
* just define this function with a return(0) as single statement
*

www.raguvaran.puzl.com
*/
unsigned int SPI_Ethernet_UserUDP(unsigned char *remoteHost, unsigned int remotePort, unsigned
int destPort, unsigned int reqLength, TEthPktFlags *flags)
{
unsigned int len ; // my reply length

// reply is made of the remote host IP address in human readable format


ByteToStr(remoteHost[0], dyna) ; // first IP address byte
dyna[3] = '.' ;
ByteToStr(remoteHost[1], dyna + 4) ; // second
dyna[7] = '.' ;
ByteToStr(remoteHost[2], dyna + 8) ; // third
dyna[11] = '.' ;
ByteToStr(remoteHost[3], dyna + 12) ; // fourth

dyna[15] = ':' ; // add separator

// then remote host port number


WordToStr(remotePort, dyna + 16) ;
dyna[21] = '[' ;
WordToStr(destPort, dyna + 22) ;
dyna[27] = ']' ;
dyna[28] = 0 ;

// the total length of the request is the length of the dynamic string plus the text of
the request
len = 28 + reqLength;

// puts the dynamic string into the transmit buffer


SPI_Ethernet_putBytes(dyna, 28) ;

// then puts the request string converted into upper char into the transmit buffer
while(reqLength--)
{
SPI_Ethernet_putByte(toupper(SPI_Ethernet_getByte())) ;
}

return(len) ; // back to the library with the length of the UDP reply
}

/*
* main entry
*/
void main()
{
ANSEL = 0x0C ; // AN2 and AN3 convertors will be used
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;
PORTA = 0 ;
TRISA = 0xff ; // set PORTA as input for ADC

ANSELH = 0; // Configure other AN pins as digital I/O


PORTB = 0 ;
TRISB = 0xff ; // set PORTB as input for buttons

PORTD = 0 ;
TRISD = 0 ; // set PORTD as output

/*
* starts ENC28J60 with :
* reset bit on RC0
* CS bit on RC1
* my MAC & IP address
* full duplex
*/
SPI1_Init();
SPI_Ethernet_Init(myMacAddr, myIpAddr, Spi_Ethernet_FULLDUPLEX) ;

www.raguvaran.puzl.com
while(1) // do forever
{
/*
* if necessary, test the return value to get error code
*/
SPI_Ethernet_doPacket() ; // process incoming Ethernet packets

/*
* add your stuff here if needed
* Spi_Ethernet_doPacket() must be called as often as possible
* otherwise packets could be lost
*/
}
}

HW Connection

SPI Ethernet ENC24J600 Library


The ENC24J600 is a stand-alone Ethernet controller with an industry standard Serial Peripheral Interface
(SPI). It is designed to serve as an Ethernet network interface for any controller equipped with SPI.
The ENC24J600 meets all of the IEEE 802.3 specifications applicable to 10Base-T and 100Base-TX
Ethernet. It incorporates a number of packet filtering schemes to limit incoming packets. It also provides
an internal, 16-bit wide DMA module for fast data throughput and hardware assisted IP checksum

www.raguvaran.puzl.com
calculations. Communication with the host controller is implemented via two interrupt pins and the SPI,
with data rates of 10/100 Mb/s. Two dedicated pins are used for LED link and network activity
indication.
This library is designed to simplify handling of the underlying hardware (ENC24J600). It works with any
PIC with integrated SPI and more than 4 Kb ROM memory. 38 to 40 MHz clock is recommended to get
from 8 to 10 Mhz SPI clock, otherwise PIC should be clocked by ENC24J600 clock output due to its silicon
bug in SPI hardware. If you try lower PIC clock speed, there might be board hang or miss some
requests.

SPI Ethernet ENC24J600 Library supports:

 ENC424J600 and ENC624J600 modules.


 IPv4 protocol.
 ARP requests.
 ICMP echo requests.
 UDP requests.
 TCP requests (no stack, no packet reconstruction).
 ARP client with cache.
 DNS client.
 UDP client.
 DHCP client.
 packet fragmentation is NOT supported.

Important :

 Due to PIC16 RAM/Flash limitations PIC16 library


does NOT have ARP, DNS, UDP and DHCP client support implemented.
 Global library variable SPI_Ethernet_24j600_userTimerSec is used to keep track of time for
all client implementations (ARP, DNS, UDP and DHCP). It is user responsibility to
increment this variable each second in it's code if any of the clients is used.
 For advanced users there are header files
("__EthEnc24j600.h" and "__EthEnc24j600Private.h") in Uses\P16 and Uses\P18 folders of
the compiler with description of all routines and global variables, relevant to the user,
implemented in the SPI Ethernet ENC24J600 Library.
 The appropriate hardware SPI module must be initialized before using any of the SPI
Ethernet ENC24J600 Library routines. Refer to SPI Library.
 For MCUs with two SPI modules it is possible to initialize both of them and then switch by
using the SPI_Set_Active() routine.

Library Dependency Tree

External dependencies of SPI Ethernet ENC24J600 Library


The following variables must be defined in all Description
Examples :
projects using SPI Ethernet ENC24J600 Library: :

sbit SPI_Ethernet_24j600_CS at RC1_bit;


extern sfr ENC24J600

www.raguvaran.puzl.com
sbit SPI_Ethernet_24j600_CS; chip select
pin.

Direction of
extern sfr the
sbit SPI_Ethernet_24j600_CS_Direction atTRISC1_b
sbit SPI_Ethernet_24j600_CS_Directio ENC24J600
it;
n; chip select
pin.

The following routines must be defined in all


Description: Examples :
project using SPI Ethernet ENC24J600 Library:

unsigned Refer to the library


int SPI_Ethernet_24j600_UserTCP(unsigned
example at the
char*remoteHost, unsigned TCP request
int remotePort, unsigned
bottom of this
handler.
intlocalPort, unsigned page for code
int reqLength, TEthj600PktFlags*flags); implementation.

unsigned Refer to the library


int SPI_Ethernet_24j600_UserUDP(unsigned
example at the
char*remoteHost, unsigned UDP request
int remotePort, unsigned
bottom of this
handler.
intlocalPort, unsigned page for code
int reqLength, TEthj600PktFlags*flags); implementation.

Library Routines

PIC16 and PIC18:


 SPI_Ethernet_24j600_Init
 SPI_Ethernet_24j600_Enable
 SPI_Ethernet_24j600_Disable
 SPI_Ethernet_24j600_doPacket
 SPI_Ethernet_24j600_putByte
 SPI_Ethernet_24j600_putBytes
 SPI_Ethernet_24j600_putString
 SPI_Ethernet_24j600_putConstString
 SPI_Ethernet_24j600_putConstBytes
 SPI_Ethernet_24j600_getByte
 SPI_Ethernet_24j600_getBytes
 SPI_Ethernet_24j600_UserTCP
 SPI_Ethernet_24j600_UserUDP

PIC18 Only:
 SPI_Ethernet_24j600_getIpAddress
 SPI_Ethernet_24j600_getGwIpAddress
 SPI_Ethernet_24j600_getDnsIpAddress
 SPI_Ethernet_24j600_getIpMask
 SPI_Ethernet_24j600_confNetwork
 SPI_Ethernet_24j600_arpResolve

www.raguvaran.puzl.com
 SPI_Ethernet_24j600_sendUDP
 SPI_Ethernet_24j600_dnsResolve
 SPI_Ethernet_24j600_initDHCP
 SPI_Ethernet_24j600_doDHCPLeaseTime
 SPI_Ethernet_24j600_renewDHCP

SPI_Ethernet_24j600_Init

Prototype void SPI_Ethernet_24j600_Init(unsigned char *mac, unsigned


char *ip, unsigned char configuration);

Returns Nothing.

Description This is MAC module routine. It initializes ENC24J600 controller. This function is internaly splited into 2 parts to
help linker when coming short of memory.
ENC24J600 controller settings (parameters not mentioned here are set to default):

 receive buffer start address : 0x0000.


 receive buffer end address : 0x19AD.
 transmit buffer start address: 0x19AE.
 transmit buffer end address : 0x1FFF.
 RAM buffer read/write pointers in auto-increment mode.
 receive filters set to default: CRC + MAC Unicast + MAC Broadcast in OR mode.
 flow control with TX and RX pause frames in full duplex mode.
 frames are padded to 60 bytes + CRC.
 maximum packet size is set to 1518.
 Back-to-Back Inter-Packet Gap: 0x15 in full duplex mode; 0x12 in half duplex mode.
 Non-Back-to-Back Inter-Packet Gap: 0x0012 in full duplex mode; 0x0C12 in half duplex mode.
 Collision window is set to 63 in half duplex mode to accomodate some ENC24J600 revisions
silicon bugs.
 CLKOUT output is disabled to reduce EMI generation.
 half duplex loopback disabled.
 LED configuration: default (LEDA-link status, LEDB-link activity).
Parameters:

 mac: RAM buffer containing valid MAC address.


 ip: RAM buffer containing valid IP address.
 configuration: ethernet negotiation, duplex and speed mode settings. For this purpose,
predefined library constants (see the list below) can be combined using logical AND to form
appropriate value :

Description Predefined library const

Set Auto-negotiation SPI_Ethernet_24j600_AUTO_NEGOTIATION

Set manual negotiation. SPI_Ethernet_24j600_MANUAL_NEGOTIATION

Set Half duplex Mode SPI_Ethernet_24j600_HALFDUPLEX

www.raguvaran.puzl.com
Set Full duplex Mode SPI_Ethernet_24j600_FULLDUPLEX

Set transmission speed of 10Mbps SPI_Ethernet_24j600_SPD10

Set transmission speed of 100Mbps SPI_Ethernet_24j600_SPD100

Note :

 It is advisable to use only the Auto-negotiation setting. If manual negotiation is used, then
duplex and speed mode setting must be set also.
 Duplex and speed mode may be set only when using manual negotiation.

Requires Global variables :

 SPI_Ethernet_24j600_CS: Chip Select line


 SPI_Ethernet_24j600_CS_Direction: Direction of the Chip Select pin
must be defined before using this function.

The SPI module needs to be initialized. See the SPIx_Init and SPIx_Init_Advanced routines.

Example #include "__EthEnc24J600.h"

// mE ethernet NIC pinout


sfr sbit SPI_Ethernet_24j600_CS at RC0_bit;
sfr sbit SPI_Ethernet_24j600_CS_Direction at RC1_bit;
// end ethernet NIC definitions

unsigned char myMacAddr[6] = {0x00, 0x14, 0xA5, 0x76, 0x19, 0x3f}; // my MAC address
unsigned char myIpAddr = {192, 168, 1, 60 }; // my IP addr

SPI1_Init();
SPI_Ethernet_24j600_Init(myMacAddr, myIpAddr, SPI_Ethernet_24j600_MANUAL_NEGOTIATION
& SPI_Ethernet_24j600_FULLDUPLEX & SPI_Ethernet_24j600_SPD100);

SPI_Ethernet_24j600_Enable

Prototype void SPI_Ethernet_24j600_Enable(unsigned int enFlt);

Returns Nothing.

www.raguvaran.puzl.com
Description This is MAC module routine. This routine enables appropriate network traffic on the ENC24J600 module by the
means of it's receive filters (unicast, multicast, broadcast, crc). Specific type of network traffic will be enabled if a
corresponding bit of this routine's input parameter is set. Therefore, more than one type of network traffic can be
enabled at the same time. For this purpose, predefined library constants (see the table below) can be ORed to form
appropriate input value.
Parameters:

 enFlt: network traffic/receive filter flags. Each bit corresponds to the appropriate network
traffic/receive filter:

Bit Mask Description Predefined library const

MAC Broadcast traffic/receive


filter flag. When
0 0x01 _SPI_Ethernet_24j600_BROADCAST
set, MAC broadcast traffic will
be enabled.

MAC Multicast traffic/receive


filter flag. When
1 0x02 _SPI_Ethernet_24j600_MULTICAST
set, MAC multicast traffic will be
enabled.

2 0x04 not used none

3 0x08 not used none

4 0x10 not used none

CRC check flag. When set,


5 0x20 packets with invalid CRC field _SPI_Ethernet_24j600_CRC
will be discarded.

6 0x40 not used none

MAC Unicast traffic/receive filter


7 0x80 flag. When set, MAC unicast _SPI_Ethernet_24j600_UNICAST
traffic will be enabled.

Note :

 Advanced filtering available in the ENC24J600 module such as Pattern


Match, Magic Packet and Hash Table can not be enabled by this routine.

www.raguvaran.puzl.com
Additionaly, all filters, except CRC, enabled with this routine will work in OR mode,
which means that packet will be received if any of the enabled filters accepts it.
 This routine will change receive filter configuration on-the-fly. It will not, in any
way, mess with enabling/disabling receive/transmit logic or any other part of
the ENC24J600 module. The ENC24J600 module should be properly cofigured by
the means of SPI_Ethernet_24j600_Init routine.

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.

Example SPI_Ethernet_24j600_Enable(_SPI_Ethernet_24j600_CRC | _SPI_Ethernet_24j600_UNICAST);


// enable CRC checking and Unicast traffic

SPI_Ethernet_24j600_Disable

Prototype void SPI_Ethernet_24j600_Disable(unsigned int disFlt);

Returns Nothing.

Description This is MAC module routine. This routine disables appropriate network traffic on the ENC24J600 module by the
means of it's receive filters (unicast, multicast, broadcast, crc). Specific type of network traffic will be disabled if a
corresponding bit of this routine's input parameter is set. Therefore, more than one type of network traffic can be
disabled at the same time. For this purpose, predefined library constants (see the table below) can be ORed to
form appropriate input value.
Parameters:

 disFlt: network traffic/receive filter flags. Each bit corresponds to the appropriate network
traffic/receive filter:

Bit Mask Description Predefined library const

MAC Broadcast traffic/receive


filter flag. When
0 0x01 _SPI_Ethernet_24j600_BROADCAST
set, MAC broadcast traffic will
be disabled.

MAC Multicast traffic/receive


filter flag. When
1 0x02 _SPI_Ethernet_24j600_MULTICAST
set, MAC multicast traffic will be
disabled.

2 0x04 not used none

www.raguvaran.puzl.com
3 0x08 not used none

4 0x10 not used none

CRC check flag. When


set, CRC check will be disabled
5 0x20 and packets with _SPI_Ethernet_24j600_CRC
invalid CRC field will be
accepted.

6 0x40 not used none

MAC Unicast traffic/receive filter


7 0x80 flag. When set, MAC unicast _SPI_Ethernet_24j600_UNICAST
traffic will be disabled.

Note :

 Advanced filtering available in the ENC24J600 module such as Pattern


Match, Magic Packet and Hash Table can not be disabled by this routine.
 This routine will change receive filter configuration on-the-fly. It will not, in any
way, mess with enabling/disabling receive/transmit logic or any other part of
the ENC24J600 module.
 The ENC24J600 module should be properly cofigured by the means
of SPI_Ethernet_24j600_Init routine.

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.

Example SPI_Ethernet_24j600_Disable(_SPI_Ethernet_24j600_CRC | _SPI_Ethernet_24j600_UNICAST);


// disable CRC checking and Unicast traffic

SPI_Ethernet_24j600_doPacket

Prototype unsigned char SPI_Ethernet_24j600_doPacket();

Returns  0 - upon successful packet processing (zero packets received or received packet processed
successfully).
 1 - upon reception error or receive buffer corruption. ENC24J600 controller needs to be

www.raguvaran.puzl.com
restarted.
 2 - received packet was not sent to us (not our IP, nor IP broadcast address).
 3 - received IP packet was not IPv4.
 4 - received packet was of type unknown to the library.

Description This is MAC module routine. It processes next received packet if such exists. Packets are processed in the
following manner:
 ARP & ICMP requests are replied automatically.
 upon TCP request the SPI_Ethernet_24j600_UserTCP function is called for further processing.
 upon UDP request the SPI_Ethernet_24j600_UserUDP function is called for further processing.

Note : SPI_Ethernet_24j600_doPacket must be called as often as possible in user's code.

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.

Example if (SPI_Ethernet_24j600_doPacket() == 0)(1) { // process received packets


...
}

SPI_Ethernet_24j600_putByte

Prototype void SPI_Ethernet_24j600_putByte(unsigned char v);

Returns Nothing.

Description This is MAC module routine. It stores one byte to address pointed by the current ENC24J600 write pointer
(EWRPT).
Parameters:

 v: value to store

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.

Example char data_;


...
SPI_Ethernet_24j600_putByte(data); // put an byte into ENC24J600 buffer

SPI_Ethernet_24j600_putBytes

Prototype void SPI_Ethernet_24j600_putBytes(unsigned char *ptr, unsigned int n);

www.raguvaran.puzl.com
Returns Nothing.

Description This is MAC module routine. It stores requested number of bytes into ENC24J600 RAM starting from
current ENC24J600 write pointer (EWRPT) location.
Parameters:

 ptr: RAM buffer containing bytes to be written into ENC24J600 RAM.


 n: number of bytes to be written.

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.

Example char *buffer = "mikroElektronika";


...
SPI_Ethernet_24j600_putBytes(buffer, 16); // put an RAM array into ENC24J600 buffer

SPI_Ethernet_24j600_putConstBytes

Prototype void SPI_Ethernet_24j600_putConstBytes(const unsigned char *ptr, unsigned


int n);

Returns Nothing.

Description This is MAC module routine. It stores requested number of const bytes into ENC24J600 RAM starting from
current ENC24J600 write pointer (EWRPT) location.
Parameters:

 ptr: const buffer containing bytes to be written into ENC24J600 RAM.


 n: number of bytes to be written.

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.

Example const char *buffer = "mikroElektronika";


...
SPI_Ethernet_24j600_putConstBytes(buffer, 16); // put a const array into ENC24J600
buffer

SPI_Ethernet_24j600_putString

www.raguvaran.puzl.com
Prototype unsigned int SPI_Ethernet_24j600_putString(unsigned char *ptr);

Returns Number of bytes written into ENC24J600 RAM.

Description This is MAC module routine. It stores whole string (excluding null termination) into ENC24J600 RAM starting
from current ENC24J600 write pointer (EWRPT) location.
Parameters:

 ptr: string to be written into ENC24J600 RAM.

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.

Example char *buffer = "mikroElektronika";


...
SPI_Ethernet_24j600_putString(buffer); // put a RAM string into ENC24J600 buffer

SPI_Ethernet_24j600_putConstString

Prototype unsigned int SPI_Ethernet_24j600_putConstString(const unsigned char *ptr);

Returns Number of bytes written into ENC24J600 RAM.

Description This is MAC module routine. It stores whole const string (excluding null termination)
into ENC24J600 RAM starting from current ENC24J600 write pointer (EWRPT) location.
Parameters:

 ptr: const string to be written into ENC24J600 RAM.

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.

Example const char *buffer = "mikroElektronika";


...
SPI_Ethernet_24j600_putConstString(buffer); // put a const string into ENC24J600
buffer

SPI_Ethernet_24j600_getByte

Prototype unsigned char SPI_Ethernet_24j600_getByte();

Returns Byte read from ENC24J600 RAM.

Description This is MAC module routine. It fetches a byte from address pointed to by current ENC24J600 read pointer

www.raguvaran.puzl.com
(ERDPT).

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.

Example char buffer;


...
buffer = SPI_Ethernet_24j600_getByte(); // read a byte from ENC24J600 buffer

SPI_Ethernet_24j600_getBytes

Prototype void SPI_Ethernet_24j600_getBytes(unsigned char *ptr, unsigned


int addr, unsigned int n);

Returns Nothing.

Description This is MAC module routine. It fetches equested number of bytes from ENC24J600 RAM starting from given
address. If value of 0xFFFF is passed as the address parameter, the reading will start from
current ENC24J600 read pointer (ERDPT) location.
Parameters:

 ptr: buffer for storing bytes read from ENC24J600 RAM.


 addr: ENC24J600 RAM start address. Valid values: 0..8192.
 n: number of bytes to be read.

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.

Example char buffer[16];


...
SPI_Ethernet_24j600_getBytes(buffer, 0x100, 16); // read 16 bytes, starting from
address 0x100

SPI_Ethernet_24j600_UserTCP

Prototype unsigned int SPI_Ethernet_24j600_UserTCP(unsigned char *remoteHost, unsigned


int remotePort, unsigned int localPort, unsigned
int reqLength,TEthj600PktFlags *flags);

Returns  0 - there should not be a reply to the request.


 Length of TCP/HTTP reply data field - otherwise.

Description This is TCP module routine. It is internally called by the library. The user accesses to the TCP/HTTP request
by using some of the SPI_Ethernet_24j600_get routines. The user puts data in the transmit buffer by using some
of the SPI_Ethernet_24j600_put routines. The function must return the length in bytes of the TCP/HTTP reply,
or 0 if there is nothing to transmit. If there is no need to reply to the TCP/HTTP requests, just define this
function with return(0) as a single statement.
Parameters:

 remoteHost: client's IP address.

www.raguvaran.puzl.com
 remotePort: client's TCP port.
 localPort: port to which the request is sent.
 reqLength: TCP request data field length.
 flags: structure consisted of two bit fields :
Copy Code To Clipboard

typedef struct {
unsigned canCloseTCP: 1; // flag which closes socket
unsigned isBroadcast: 1; // flag which denotes that the IP package has
been received via subnet broadcast address (not used for PIC16 family)
} TEthj600PktFlags;

Note : The function source code is provided with appropriate example projects. The code should be
adjusted by the user to achieve desired reply.

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.

Example This function is internally called by the library and should not be called by the user's code.

SPI_Ethernet_24j600_UserUDP

Prototype unsigned int SPI_Ethernet_24j600_UserUDP(unsigned char *remoteHost, unsigned


int remotePort, unsigned int destPort, unsigned
int reqLength,TEthj600PktFlags *flags);

Returns  0 - there should not be a reply to the request.


 Length of UDP reply data field - otherwise.

Description This is UDP module routine. It is internally called by the library. The user accesses to the UDP request by using
some of the SPI_Ethernet_24j600_get routines. The user puts data in the transmit buffer by using some of the
SPI_Ethernet_24j600_put routines. The function must return the length in bytes of the UDP reply, or 0 if nothing
to transmit. If you don't need to reply to the UDP requests, just define this function with a return(0) as single
statement.
Parameters:

 remoteHost: client's IP address.


 remotePort: client's port.
 localPort: port to which the request is sent.
 reqLength: UDP request data field length.
 flags: structure consisted of two bit fields :
Copy Code To Clipboard

typedef struct {
unsigned canCloseTCP: 1; // flag which closes TCP socket (not relevant
to UDP)
unsigned isBroadcast: 1; // flag which denotes that the IP package has
been received via subnet broadcast address (not used for PIC16 family)

www.raguvaran.puzl.com
} TEthj600PktFlags;

Note : The function source code is provided with appropriate example projects. The code
should be adjusted by the user to achieve desired reply.

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.

Example This function is internally called by the library and should not be called by the user's code.

SPI_Ethernet_24j600_getIpAddress

Prototype unsigned char * SPI_Ethernet_24j600_getIpAddress();

Returns Pointer to the global variable holding IP address.

Description This routine should be used when DHCP server is present on the network to fetch assigned IP address.

Note : User should always copy the IP address from the RAM location returned by this routine into it's
own IP address buffer. These locations should not be altered by the user in any case!

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.


Available for PIC18 family MCUs only.

Example unsigned char ipAddr[4]; // user IP address buffer


...
memcpy(ipAddr, SPI_Ethernet_24j600_getIpAddress(), 4); // fetch IP address

SPI_Ethernet_24j600_getGwIpAddress

Prototype unsigned char * SPI_Ethernet_24j600_getGwIpAddress();

Returns Pointer to the global variable holding gateway IP address.

Description This routine should be used when DHCP server is present on the network to fetch assigned gateway IP address.

Note : User should always copy the IP address from the RAM location returned by this routine into it's
own gateway IP address buffer. These locations should not be altered by the user in any case!

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.


Available for PIC18 family MCUs only.

www.raguvaran.puzl.com
Example unsigned char gwIpAddr[4]; // user gateway IP address buffer
...
memcpy(gwIpAddr, SPI_Ethernet_24j600_getGwIpAddress(), 4); // fetch gateway IP
address

SPI_Ethernet_24j600_getDnsIpAddress

Prototype unsigned char * SPI_Ethernet_24j600_getDnsIpAddress()

Returns Pointer to the global variable holding DNS IP address.

Description his routine should be used when DHCP server is present on the network to fetch assigned DNS IP address.

Note : User should always copy the IP address from the RAM location returned by this routine into it's
own DNS IP address buffer. These locations should not be altered by the user in any case!

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.


Available for PIC18 family MCUs only.

Example unsigned char dnsIpAddr[4]; // user DNS IP address buffer


...
memcpy(dnsIpAddr, SPI_Ethernet_24j600_getDnsIpAddress(), 4); // fetch DNS server
address

SPI_Ethernet_24j600_getIpMask

Prototype unsigned char * SPI_Ethernet_24j600_getIpMask()

Returns Pointer to the global variable holding IP subnet mask.

Description This routine should be used when DHCP server is present on the network to fetch assigned IP subnet mask.

Note : User should always copy the IP address from the RAM location returned by this routine into it's
own IP subnet mask buffer. These locations should not be altered by the user in any case!

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.


Available for PIC18 family MCUs only.

Example unsigned char IpMask[4]; // user IP subnet mask buffer


...
memcpy(IpMask, SPI_Ethernet_24j600_getIpMask(), 4); // fetch IP subnet mask

www.raguvaran.puzl.com
SPI_Ethernet_24j600_confNetwork

Prototype void SPI_Ethernet_24j600_confNetwork(char *ipMask, char *gwIpAddr, char *dnsI


pAddr);

Returns Nothing.

Descriptio Configures network parameters (IP subnet mask, gateway IP address, DNS IP address) when DHCP is not used.
n Parameters:

 ipMask: IP subnet mask.


 gwIpAddr gateway IP address.
 dnsIpAddr: DNS IP address.

Note : The above mentioned network parameters should be set by this routine only if DHCP module is not
used. Otherwise DHCP will override these settings.

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.


Available for PIC18 family MCUs only.

Example char ipMask[4] = {255, 255, 255, 0 }; // network mask (for example :
255.255.255.0)
char gwIpAddr[4] = {192, 168, 1, 1 }; // gateway (router) IP address
char dnsIpAddr[4] = {192, 168, 1, 1 }; // DNS server IP address
...
SPI_Ethernet_24j600_confNetwork(ipMask, gwIpAddr, dnsIpAddr); // set network
configuration parameters

SPI_Ethernet_24j600_arpResolve

Prototype unsigned char *SPI_Ethernet_24j600_arpResolve(unsigned char *ip, unsigned


char tmax);

Returns  MAC address behind the IP address - the requested IP address was resolved.
 0 - otherwise.

Description This is ARP module routine. It sends an ARP request for given IP address and waits for ARP reply. If the
requested IP address was resolved, an ARP cash entry is used for storing the configuration. ARP cash can store
up to 3 entries. For ARP cash structure refer to "__EthEnc24j600.h" header file in the compiler's Uses/P18
folder.
Parameters:

 ip: IP address to be resolved.


 tmax: time in seconds to wait for an reply.

Note : The Ethernet services are not stopped while this routine waits for ARP reply. The incoming packets
will be processed normaly during this time.

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.


Available for PIC18 family MCUs only.

www.raguvaran.puzl.com
Example unsigned char IpAddr[4] = {192, 168, 1, 1 }; // IP address
...
SPI_Ethernet_24j600_arpResolve(IpAddr, 5); // get MAC address behind the above IP
address, wait 5 secs for the response

SPI_Ethernet_24j600_sendUDP

Prototype unsigned char SPI_Ethernet_24j600_sendUDP(unsigned char *destIP, unsigned


int sourcePort, unsigned int destPort, unsigned char *pkt, unsigned
intpktLen);

Returns  1 - UDP packet was sent successfully.


 0 - otherwise.

Description This is UDP module routine. It sends an UDP packet on the network.
Parameters:

 destIP: remote host IP address.


 sourcePort: local UDP source port number.
 destPort: destination UDP port number.
 pkt: packet to transmit.
 pktLen: length in bytes of packet to transmit.

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.


Available for PIC18 family MCUs only.

Example unsigned char IpAddr[4] = {192, 168, 1, 1 }; // remote IP address


...
SPI_Ethernet_24j600_sendUDP(IpAddr, 10001, 10001, "Hello", 5); // send Hello message
to the above IP address, from UDP port 10001 to UDP port 10001

SPI_Ethernet_24j600_dnsResolve

Prototype unsigned char * SPI_Ethernet_24j600_dnsResolve(unsigned char *host, unsigned


char tmax);

Returns  pointer to the location holding the IP address - the requested host name was resolved.
 0 - otherwise.

Description This is DNS module routine. It sends an DNS request for given host name and waits for DNS reply. If the
requested host name was resolved, it's IP address is stored in library global variable and a pointer containing this
address is returned by the routine. UDP port 53 is used as DNS port.
Parameters:

 host: host name to be resolved.


 tmax: time in seconds to wait for an reply.

Note :

 The Ethernet services are not stopped while this routine waits for DNS reply. The incoming
packets will be processed normaly during this time.

www.raguvaran.puzl.com
 User should always copy the IP address from the RAM location returned by this routine into it's
own resolved host IP address buffer. These locations should not be altered by the user in any
case!

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.


Available for PIC18 family MCUs only.

Example unsigned char * remoteHostIpAddr[4]; // user host IP address buffer


...
// SNTP server:
// Zurich, Switzerland: Integrated Systems Lab, Swiss Fed. Inst. of Technology
// 129.132.2.21: swisstime.ethz.ch
// Service Area: Switzerland and Europe
memcpy(remoteHostIpAddr, SPI_Ethernet_24j600_dnsResolve("swisstime.ethz.ch", 5), 4);

SPI_Ethernet_24j600_initDHCP

Prototype unsigned char SPI_Ethernet_24j600_initDHCP(unsigned char tmax);

Returns  1 - network parameters were obtained successfully.


 0 - otherwise.

Description This is DHCP module routine. It sends an DHCP request for network parameters (IP, gateway, DNS addresses
and IP subnet mask) and waits for DHCP reply. If the requested parameters were obtained successfully, their
values are stored into the library global variables.
These parameters can be fetched by using appropriate library IP get routines:
 SPI_Ethernet_24j600_getIpAddress - fetch IP address.
 SPI_Ethernet_24j600_getGwIpAddress - fetch gateway IP address.
 SPI_Ethernet_24j600_getDnsIpAddress - fetch DNS IP address.
 SPI_Ethernet_24j600_getIpMask - fetch IP subnet mask.
UDP port 68 is used as DHCP client port and UDP port 67 is used as DHCP server port.
Parameters:

 tmax: time in seconds to wait for an reply.

Note :

 The Ethernet services are not stopped while this routine waits for DNS reply. The incoming
packets will be processed normaly during this time.
 When DHCP module is used, global library variable SPI_Ethernet_24j600_userTimerSec is
used to keep track of time. It is user responsibility to increment this variable each second in it's
code.

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.


Available for PIC18 family MCUs only.

Example ...
SPI_Ethernet_24j600_initDHCP(5); // get network configuration from DHCP server, wait
5 sec for the response
...

www.raguvaran.puzl.com
SPI_Ethernet_24j600_doDHCPLeaseTime

Prototype unsigned char SPI_Ethernet_24j600_doDHCPLeaseTime();

Returns  0 - lease time has not expired yet.


 1 - lease time has expired, it's time to renew it.

Description This is DHCP module routine. It takes care of IP address lease time by decrementing the global lease time
library counter. When this time expires, it's time to contact DHCPserver and renew the lease.

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.


Available for PIC18 family MCUs only.

Example while(1) {
...
if(SPI_Ethernet_24j600_doDHCPLeaseTime())
... // it's time to renew the IP address lease
}

SPI_Ethernet_24j600_renewDHCP

Prototype unsigned char SPI_Ethernet_24j600_renewDHCP(unsigned char tmax);

Returns  1 - upon success (lease time was renewed).


 0 - otherwise (renewal request timed out).

Description This is DHCP module routine. It sends IP address lease time renewal request to DHCP server.
Parameters:

 tmax: time in seconds to wait for an reply.

Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.


Available for PIC18 family MCUs only.

Example while(1) {
...
if(SPI_Ethernet_24j600_doDHCPLeaseTime())
SPI_Ethernet_24j600_renewDHCP(5); // it's time to renew the IP address lease,
with 5 secs for a reply
...
}

Library Example
This code shows how to use the Ethernet mini library :

 the board will reply to ARP & ICMP echo requests


 the board will reply to UDP requests on any port :
 returns the request in upper char with a header made of remote host IP & port
number
 the board will reply to HTTP requests on port 80, GET method with pathnames :

www.raguvaran.puzl.com
 / will return the HTML main page
 /s will return board status as text string
 /t0 ... /t7 will toggle RD0 to RD7 bit and return HTML main page
 all other requests return also HTML main page.
Copy Code To Clipboard

#include "__EthEnc24j600.h"

// mE ehternet NIC pinout


sfr sbit SPI_Ethernet_24j600_CS at RC1_bit;
sfr sbit SPI_Ethernet_24j600_CS_Direction at TRISC1_bit;
// end ethernet NIC definitions

/************************************************************
* ROM constant strings
*/
const unsigned char httpHeader[] = "HTTP/1.1 200 OKnContent-type: " ; // HTTP header
const unsigned char httpMimeTypeHTML[] = "text/htmlnn" ; // HTML MIME type
const unsigned char httpMimeTypeScript[] = "text/plainnn" ; // TEXT MIME type
unsigned char httpMethod[] = "GET /";
/*
* web page, splited into 2 parts :
* when coming short of ROM, fragmented data is handled more efficiently by linker
*
* this HTML page calls the boards to get its status, and builds itself with javascript
*/
const char *indexPage = // Change the IP address of the page to be refreshed
"<meta http-equiv="refresh" content="3;url=http://192.168.20.60">
<HTML><HEAD></HEAD><BODY>
<h1>PIC + ENC24J600 Mini Web Server</h1>
<a href=/>Reload</a>
<script src=/https/www.scribd.com/s></script>
<table><tr><td valign=top><table border=1 style="font-size:20px ;font-family: terminal ;">
<tr><th colspan=2>ADC</th></tr>
<tr><td>AN2</td><td><script>document.write(AN2)</script></td></tr>
<tr><td>AN3</td><td><script>document.write(AN3)</script></td></tr>
</table></td><td><table border=1 style="font-size:20px ;font-family: terminal ;">
<tr><th colspan=2>PORTB</th></tr>
<script>
var str,i;
str="";
for(i=0;i<8;i++)
{str+="<tr><td bgcolor=pink>BUTTON #"+i+"</td>";
if(PORTB&(1<<i)){str+="<td bgcolor=red>ON";}
else {str+="<td bgcolor=#cccccc>OFF";}
str+="</td></tr>";}
document.write(str) ;
</script>
" ;

const char *indexPage2 = "</table></td><td>


<table border=1 style="font-size:20px ;font-family: terminal ;">
<tr><th colspan=3>PORTD</th></tr>
<script>
var str,i;
str="";
for(i=0;i<8;i++)
{str+="<tr><td bgcolor=yellow>LED #"+i+"</td>";
if(PORTD&(1<<i)){str+="<td bgcolor=red>ON";}
else {str+="<td bgcolor=#cccccc>OFF";}
str+="</td><td><a href=/https/www.scribd.com/t"+i+">Toggle</a></td></tr>";}

www.raguvaran.puzl.com
document.write(str) ;
</script>
</table></td></tr></table>
This is HTTP request #<script>document.write(REQ)</script></BODY></HTML>
" ;

/***********************************
* RAM variables
*/
unsigned char myMacAddr[6] = {0x00, 0x14, 0xA5, 0x76, 0x19, 0x3f} ; // my MAC address
unsigned char myIpAddr[4] = {192, 168, 20, 60} ; // my IP address
unsigned char getRequest[15] ; // HTTP request buffer
unsigned char dyna[30] ; // buffer for dynamic
response
unsigned long httpCounter = 0 ; // counter of HTTP
requests

/*******************************************
* functions
*/

/*
* put the constant string pointed to by s to the ENC transmit buffer.
*/
/*unsigned int putConstString(const char *s)
{
unsigned int ctr = 0 ;

while(*s)
{
SPI_Ethernet_24j600_putByte(*s++) ;
ctr++ ;
}
return(ctr) ;
}*/
/*
* it will be much faster to use library SPI_Ethernet_24j600_putConstString routine
* instead of putConstString routine above. However, the code will be a little
* bit bigger. User should choose between size and speed and pick the implementation that
* suites him best. If you choose to go with the putConstString definition above
* the #define line below should be commented out.
*
*/
#define putConstString SPI_Ethernet_24j600_putConstString

/*
* put the string pointed to by s to the ENC transmit buffer
*/
/*unsigned int putString(char *s)
{
unsigned int ctr = 0 ;

while(*s)
{
SPI_Ethernet_24j600_putByte(*s++) ;

ctr++ ;
}
return(ctr) ;
}*/
/*
* it will be much faster to use library SPI_Ethernet_24j600_putString routine
* instead of putString routine above. However, the code will be a little
* bit bigger. User should choose between size and speed and pick the implementation that
* suites him best. If you choose to go with the putString definition above
* the #define line below should be commented out.
*

www.raguvaran.puzl.com
*/
#define putString SPI_Ethernet_24j600_putString

/*
* this function is called by the library
* the user accesses to the HTTP request by successive calls to SPI_Ethernet_24j600_getByte()
* the user puts data in the transmit buffer by successive calls to SPI_Ethernet_24j600_putByte()
* the function must return the length in bytes of the HTTP reply, or 0 if nothing to transmit
*
* if you don't need to reply to HTTP requests,
* just define this function with a return(0) as single statement
*
*/
unsigned int SPI_Ethernet_24j600_UserTCP(unsigned char *remoteHost, unsigned int remotePort,
unsigned int localPort, unsigned int reqLength, TEthPktFlags *flags)
{
unsigned int len = 0 ; // my reply length
unsigned int i ; // general purpose integer

// should we close tcp socket after response is sent?


// library closes tcp socket by default if canClose flag is not reset here
// flags->canClose = 0; // 0 - do not close socket
// otherwise - close socket

if(localPort != 80) // I listen only to web request on port 80


{
return(0) ;
}

// get 10 first bytes only of the request, the rest does not matter here
for(i = 0 ; i < 10 ; i++)
{
getRequest[i] = SPI_Ethernet_24j600_getByte() ;
}
getRequest[i] = 0 ;

if(memcmp(getRequest, httpMethod, 5)) // only GET method is supported here


{
return(0) ;
}

httpCounter++ ; // one more request done

if(getRequest[5] == 's') // if request path name starts with s, store


dynamic data in transmit buffer
{
// the text string replied by this request can be interpreted as javascript
statements
// by browsers

len = putConstString(httpHeader) ; // HTTP header


len += putConstString(httpMimeTypeScript) ; // with text MIME type

// add AN2 value to reply


IntToStr(ADC_Read(2), dyna) ;
len += putConstString("var AN2=") ;
len += putString(dyna) ;
len += putConstString(";") ;

// add AN3 value to reply


IntToStr(ADC_Read(3), dyna) ;
len += putConstString("var AN3=") ;
len += putString(dyna) ;
len += putConstString(";") ;

// add PORTB value (buttons) to reply


len += putConstString("var PORTB=") ;

www.raguvaran.puzl.com
IntToStr(PORTB, dyna) ;
len += putString(dyna) ;
len += putConstString(";") ;

// add PORTD value (LEDs) to reply


len += putConstString("var PORTD=") ;
IntToStr(PORTD, dyna) ;
len += putString(dyna) ;
len += putConstString(";") ;

// add HTTP requests counter to reply


IntToStr(httpCounter, dyna) ;
len += putConstString("var REQ=") ;
len += putString(dyna) ;
len += putConstString(";") ;
}
else if(getRequest[5] == 't') // if request path name starts
with t, toggle PORTD (LED) bit number that comes after
{
unsigned char bitMask = 0 ; // for bit mask

if(isdigit(getRequest[6])) // if 0 <= bit number <= 9, bits 8


& 9 does not exist but does not matter
{
bitMask = getRequest[6] - '0' ; // convert ASCII to integer
bitMask = 1 << bitMask ; // create bit mask
PORTD ^= bitMask ; // toggle PORTD with xor operator
}
}

if(len == 0) // what do to by default


{
len = putConstString(httpHeader) ; // HTTP header
len += putConstString(httpMimeTypeHTML) ; // with HTML MIME type
len += putConstString(indexPage) ; // HTML page first part
len += putConstString(indexPage2) ; // HTML page second part
}

return(len) ; // return to the library with the


number of bytes to transmit
}

/*
* this function is called by the library
* the user accesses to the UDP request by successive calls to SPI_Ethernet_24j600_getByte()
* the user puts data in the transmit buffer by successive calls to SPI_Ethernet_24j600_putByte()
* the function must return the length in bytes of the UDP reply, or 0 if nothing to transmit
*
* if you don't need to reply to UDP requests,
* just define this function with a return(0) as single statement
*
*/
unsigned int SPI_Ethernet_24j600_UserUDP(unsigned char *remoteHost, unsigned int remotePort,
unsigned int destPort, unsigned int reqLength, TEthPktFlags *flags)
{
unsigned int len ; // my reply length

// reply is made of the remote host IP address in human readable format


ByteToStr(remoteHost[0], dyna) ; // first IP address byte
dyna[3] = '.' ;
ByteToStr(remoteHost[1], dyna + 4) ; // second
dyna[7] = '.' ;
ByteToStr(remoteHost[2], dyna + 8) ; // third
dyna[11] = '.' ;
ByteToStr(remoteHost[3], dyna + 12) ; // fourth

dyna[15] = ':' ; // add separator

www.raguvaran.puzl.com
// then remote host port number
WordToStr(remotePort, dyna + 16) ;
dyna[21] = '[' ;
WordToStr(destPort, dyna + 22) ;
dyna[27] = ']' ;
dyna[28] = 0 ;

// the total length of the request is the length of the dynamic string plus the text of
the request
len = 28 + reqLength;

// puts the dynamic string into the transmit buffer


SPI_Ethernet_24j600_putBytes(dyna, 28) ;

// then puts the request string converted into upper char into the transmit buffer
while(reqLength--)
{
SPI_Ethernet_24j600_putByte(toupper(SPI_Ethernet_24j600_getByte())) ;
}

return(len) ; // back to the library with the length of the UDP reply
}

/*
* main entry
*/
void main()
{
ANSEL = 0x0C ; // AN2 and AN3 convertors will be used
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;
PORTA = 0 ;
TRISA = 0xff ; // set PORTA as input for ADC

ANSELH = 0; // Configure other AN pins as digital I/O


PORTB = 0 ;
TRISB = 0xff ; // set PORTB as input for buttons

PORTD = 0 ;
TRISD = 0 ; // set PORTD as output

/*
* CS bit on RC1
* my MAC & IP address
* full duplex
*/
SPI1_Init();
SPI_Ethernet_24j600_Init(myMacAddr, myIpAddr, SPI_Ethernet_24j600_AUTO_NEGOTIATION) ;

while(1) // do forever
{
/*
* if necessary, test the return value to get error code
*/
SPI_Ethernet_24j600_doPacket() ; // process incoming Ethernet packets

/*
* add your stuff here if needed
* SPI_Ethernet_24j600_doPacket() must be called as often as possible
* otherwise packets could be lost
*/
}
}

www.raguvaran.puzl.com
SPI Graphic Lcd Library
mikroC PRO for PIC provides a library for operating Graphic Lcd 128x64 (with commonly used Samsung
KS108/KS107 controller) via SPI interface.
For creating a custom set of Glcd images use Glcd Bitmap Editor Tool.
Important :
 The library uses the SPI module for communication. User must initialize SPI module before
using the SPI Graphic Lcd Library.
 This Library is designed to work with the mikroElektronika's Serial Lcd/Glcd Adapter Board
pinout, see schematic at the bottom of this page for details.
 PIC16 family of MCUs does not support working with external resources.

Library Dependency Tree

External dependencies of SPI Lcd Library


The implementation of SPI Lcd Library routines is based on Port Expander Library routines.
External dependencies are the same as Port Expander Library external dependencies.

Library Routines
Basic routines:

 SPI_Glcd_Init
 SPI_Glcd_Set_Side
 SPI_Glcd_Set_Page
 SPI_Glcd_Set_X
 SPI_Glcd_Read_Data
 SPI_Glcd_Write_Data
 SPI_Glcd_Set_Ext_Buffer

Advanced routines:

 SPI_Glcd_Fill
 SPI_Glcd_Dot
 SPI_Glcd_Line
 SPI_Glcd_V_Line
 SPI_Glcd_H_Line
 SPI_Glcd_Rectangle
 SPI_Glcd_Rectangle_Round_Edges
 SPI_Glcd_Rectangle_Round_Edges_Fill
 SPI_Glcd_Box
 SPI_Glcd_Circle
 SPI_Glcd_Circle_Fill
 SPI_Glcd_Set_Font
 SPI_Glcd_Set_Font_Adv
 SPI_Glcd_Set_Ext_Font_Adv
 SPI_Glcd_Write_Char
 SPI_Glcd_Write_Char_Adv
 SPI_Glcd_Write_Text
 SPI_Glcd_Write_Text_Adv
 SPI_Glcd_Write_Const_Text_Adv
 SPI_Glcd_Image

www.raguvaran.puzl.com
 SPI_Glcd_Ext_Image
 SPI_Glcd_PartialImage
 SPI_Glcd_Ext_PartialImage

SPI_Glcd_Init

Prototype void SPI_Glcd_Init(char DeviceAddress);

Returns Nothing.

Description Initializes the Glcd module via SPI interface.


Parameters :

 DeviceAddress: SPI expander hardware address, see schematic at the bottom of this page

Requires Global variables :


 SPExpanderCS: Chip Select line
 SPExpanderRST: Reset line
 SPExpanderCS_Direction: Direction of the Chip Select pin
 SPExpanderRST_Direction: Direction of the Reset pin
must be defined before using this function.

The SPI module needs to be initialized. See SPIx_Init and SPIx_Init_Advanced routines.

Example // Port Expander module connections


sbit SPExpanderRST at RC0_bit;
sbit SPExpanderCS at RC1_bit;
sbit SPExpanderRST_Direction at TRISC0_bit;
sbit SPExpanderCS_Direction at TRISC1_bit;
// End Port Expander module connections

...

// If Port Expander Library uses SPI module :


SPI1_Init(); // Initialize SPI module used with PortExpander
SPI_Glcd_Init(0);

SPI_Glcd_Set_Side

Prototype void SPI_Glcd_Set_Side(char x_pos);

Returns Nothing.

Description Selects Glcd side. Refer to the Glcd datasheet for detail explanation.

Parameters :

 x_pos: position on x-axis. Valid values: 0..127


The parameter x_pos specifies the Glcd side: values from 0 to 63 specify the left side, values from 64 to 127
specify the right side.

Note : For side, x axis and page layout explanation see schematic at the bottom of this page.

www.raguvaran.puzl.com
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.

Example The following two lines are equivalent, and both of them select the left side of Glcd:

SPI_Glcd_Set_Side(0);
SPI_Glcd_Set_Side(10);

SPI_Glcd_Set_Page

Prototype void SPI_Glcd_Set_Page(char page);

Returns Nothing.

Description Selects page of Glcd.

Parameters :

 page: page number. Valid values: 0..7

Note : For side, x axis and page layout explanation see schematic at the bottom of this page.

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.

Example SPI_Glcd_Set_Page(5);

SPI_Glcd_Set_X

Prototype void SPI_Glcd_Set_X(char x_pos);

Returns Nothing.

Description Sets x-axis position to x_pos dots from the left border of Glcd within the selected side.
Parameters :

 x_pos: position on x-axis. Valid values: 0..63

Note : For side, x axis and page layout explanation see schematic at the bottom of this page.

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.

Example SPI_Glcd_Set_X(25);

SPI_Glcd_Read_Data

Prototype char SPI_Glcd_Read_Data();

www.raguvaran.puzl.com
Returns One byte from Glcd memory.

Description Reads data from the current location of Glcd memory and moves to the next location.

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.
Glcd side, x-axis position and page should be set first. See the functions SPI_Glcd_Set_Side, SPI_Glcd_Set_X,
and SPI_Glcd_Set_Page.

Example char data;


...
data = SPI_Glcd_Read_Data();

SPI_Glcd_Write_Data

Prototype void SPI_Glcd_Write_Data(char Ddata);

Returns Nothing.

Description Writes one byte to the current location in Glcd memory and moves to the next location.

Parameters :

 Ddata: data to be written

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.
Glcd side, x-axis position and page should be set first. See the functions SPI_Glcd_Set_Side, SPI_Glcd_Set_X,
and SPI_Glcd_Set_Page.

Example char data_;


...
SPI_Glcd_Write_Data(data_);

SPI_Glcd_Set_Ext_Buffer

Prototype void SPI_Glcd_Set_Ext_Buffer(char* (*getExtDataPtr)(unsigned


long offset, unsigned long count, unsigned long* num));

Returns Nothing.

Description Function sets pointer to the user function which manipulates the external resource.

Parameters :

 offset - offset from the beginning of the resource from where the data is requested.
 count - requested number of bytes.
 num - variable for holding the returned number ob byte (less or equal to the number of acqired
bytes).

www.raguvaran.puzl.com
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
Glcd side, x-axis position and page should be set first. See the functions SPI_Glcd_Set_Side, SPI_Glcd_Set_X,
and SPI_Glcd_Set_Page.

Example char* ReadExternalBuffer(unsigned long offset, unsigned int count, unsigned int
*num){
unsigned long start_sector;
unsigned int pos;

start_sector = Mmc_Get_File_Write_Sector() + offset/512;


pos = (unsigned long)offset%512;

if(start_sector == currentSector+1){
Mmc_Multi_Read_Buffer(EXT_BUFFER);
currentSector = start_sector;
}else
if(start_sector != currentSector){
Mmc_Multi_Read_Stop();
Mmc_Multi_Read_Start(start_sector);
Mmc_Multi_Read_Buffer(EXT_BUFFER);
currentSector = start_sector;
}

if(count>512-pos){
*num = 512-pos;
}
else
*num = count;

return EXT_BUFFER+pos;
}

SPI_Glcd_Set_Ext_Buffer(ReadExternalBuffer);

SPI_Glcd_Fill

Prototype void SPI_Glcd_Fill(char pattern);

Returns Nothing.

Description Fills Glcd memory with byte pattern.


Parameters :

 pattern: byte to fill Glcd memory with


To clear the Glcd screen, use SPI_Glcd_Fill(0).
To fill the screen completely, use SPI_Glcd_Fill(0xFF).

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.

Example // Clear screen


SPI_Glcd_Fill(0);

SPI_Glcd_Dot

Prototype void SPI_Glcd_Dot(char x_pos, char y_pos, char color);

www.raguvaran.puzl.com
Returns Nothing.

Description Draws a dot on Glcd at coordinates (x_pos, y_pos).


Parameters :

 x_pos: x position. Valid values: 0..127


 y_pos: y position. Valid values: 0..63
 color: color parameter. Valid values: 0..2
The parameter color determines the dot state: 0 clears dot, 1 puts a dot, and 2 inverts dot state.

Note : For side, x and y axis and page layout explanation see schematic at the bottom of this page.

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.

Example // Invert the dot in the upper left corner


SPI_Glcd_Dot(0, 0, 2);

SPI_Glcd_Line

Prototype void SPI_Glcd_Line(int x_start, int y_start, int x_end, int y_end, char colo
r);

Returns Nothing.

Descriptio Draws a line on Glcd.


n
Parameters :

 x_start: x coordinate of the line start. Valid values: 0..127


 y_start: y coordinate of the line start. Valid values: 0..63
 x_end: x coordinate of the line end. Valid values: 0..127
 y_end: y coordinate of the line end. Valid values: 0..63
 color: color parameter. Valid values: 0..2
Parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot.

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.

Example // Draw a line between dots (0,0) and (20,30)


SPI_Glcd_Line(0, 0, 20, 30, 1);

SPI_Glcd_V_Line

Prototype void SPI_Glcd_V_Line(char y_start, char y_end, char x_pos, char color);

Returns Nothing.

Description Draws a vertical line on Glcd.

www.raguvaran.puzl.com
Parameters :

 y_start: y coordinate of the line start. Valid values: 0..63


 y_end: y coordinate of the line end. Valid values: 0..63
 x_pos: x coordinate of vertical line. Valid values: 0..127
 color: color parameter. Valid values: 0..2
Parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot.

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.

Example // Draw a vertical line between dots (10,5) and (10,25)


SPI_Glcd_V_Line(5, 25, 10, 1);

SPI_Glcd_H_Line

Prototype void SPI_Glcd_H_Line(char x_start, char x_end, char y_pos, char color);

Returns Nothing.

Description Draws a horizontal line on Glcd.

Parameters :

 x_start: x coordinate of the line start. Valid values: 0..127


 x_end: x coordinate of the line end. Valid values: 0..127
 y_pos: y coordinate of horizontal line. Valid values: 0..63
 color: color parameter. Valid values: 0..2
The parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot.

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.

Example // Draw a horizontal line between dots (10,20) and (50,20)


SPI_Glcd_H_Line(10, 50, 20, 1);

SPI_Glcd_Rectangle

Prototy void SPI_Glcd_Rectangle(char x_upper_left, char y_upper_left, char x_bottom_ri


pe ght, char y_bottom_right, char color);

Return Nothing.
s

Descrip Draws a rectangle on Glcd.


tion
Parameters :

 x_upper_left: x coordinate of the upper left rectangle corner. Valid values: 0..127
 y_upper_left: y coordinate of the upper left rectangle corner. Valid values: 0..63
 x_bottom_right: x coordinate of the lower right rectangle corner. Valid values: 0..127
 y_bottom_right: y coordinate of the lower right rectangle corner. Valid values: 0..63

www.raguvaran.puzl.com
 color: color parameter. Valid values: 0..2
The parameter color determines the color of the rectangle border: 0 white, 1 black, and 2 inverts each dot.

Requir Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.
es

Exampl // Draw a rectangle between dots (5,5) and (40,40)


e SPI_Glcd_Rectangle(5, 5, 40, 40, 1);

SPI_Glcd_Rectangle_Round_Edges

Prototype void SPI_Glcd_Rectangle_Round_Edges(unsigned short x_upper_left, unsigned


short y_upper_left, unsigned short x_bottom_right, unsigned
shorty_bottom_right, unsigned short round_radius, unsigned short color);

Returns Nothing.

Description Draws a rounded edge rectangle on Glcd.

Parameters :

 x_upper_left: x coordinate of the upper left rectangle corner. Valid values: 0..127
 y_upper_left: y coordinate of the upper left rectangle corner. Valid values: 0..63
 x_bottom_right: x coordinate of the lower right rectangle corner. Valid values: 0..127
 y_bottom_right: y coordinate of the lower right rectangle corner. Valid values: 0..63
 round_radius: radius of the rounded edge.
 color: color parameter. Valid values: 0..2
The parameter color determines the color of the rectangle border: 0 white, 1 black, and 2 inverts each dot.

Requires Glcd needs to be initialized, see SPI_Glcd_Init routine.

Example // Draw a rounded edge rectangle between dots (5,5) and (40,40) with the radius of
12
SPI_Glcd_Rectangle_Round_Edges(5, 5, 40, 40, 12, 1);

SPI_Glcd_Rectangle_Round_Edges_Fill

Prototype void SPI_Glcd_Rectangle_Round_Edges_Fill(unsigned


short x_upper_left, unsigned short y_upper_left, unsigned
short x_bottom_right, unsigned shorty_bottom_right, unsigned
short round_radius, unsigned short color);

Returns Nothing.

Description Draws a filled rounded edge rectangle on Glcd with color.

Parameters :

 x_upper_left: x coordinate of the upper left rectangle corner. Valid values: 0..127

www.raguvaran.puzl.com
 y_upper_left: y coordinate of the upper left rectangle corner. Valid values: 0..63
 x_bottom_right: x coordinate of the lower right rectangle corner. Valid values: 0..127
 y_bottom_right: y coordinate of the lower right rectangle corner. Valid values: 0..63
 round_radius: radius of the rounded edge
 color: color parameter. Valid values: 0..2
The parameter color determines the color of the rectangle border: 0 white, 1 black, and 2 inverts each dot.

Requires Glcd needs to be initialized, see SPI_Glcd_Init routine.

Example // Draws a filled rounded edge rectangle between dots (5,5) and (40,40) with the
radius of 12
SPI_Glcd_Rectangle_Round_Edges_Fill(5, 5, 40, 40, 12, 1);

SPI_Glcd_Box

Prototy void SPI_Glcd_Box(char x_upper_left, char y_upper_left, char x_bottom_right, c


pe har y_bottom_right, char color);

Returns Nothing.

Descrip Draws a box on Glcd.


tion
Parameters :

 x_upper_left: x coordinate of the upper left box corner. Valid values: 0..127
 y_upper_left: y coordinate of the upper left box corner. Valid values: 0..63
 x_bottom_right: x coordinate of the lower right box corner. Valid values: 0..127
 y_bottom_right: y coordinate of the lower right box corner. Valid values: 0..63
 color: color parameter. Valid values: 0..2
The parameter color determines the color of the box fill: 0 white, 1 black, and 2 inverts each dot.

Require Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.
s

Exampl // Draw a box between dots (5,15) and (20,40)


e SPI_Glcd_Box(5, 15, 20, 40, 1);

SPI_Glcd_Circle

Prototype void SPI_Glcd_Circle(int x_center, int y_center, int radius, char color);

Returns Nothing.

Description Draws a circle on Glcd.

Parameters :

 x_center: x coordinate of the circle center. Valid values: 0..127


 y_center: y coordinate of the circle center. Valid values: 0..63

www.raguvaran.puzl.com
 radius: radius size
 color: color parameter. Valid values: 0..2
The parameter color determines the color of the circle line: 0 white, 1 black, and 2 inverts each dot.

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.

Example // Draw a circle with center in (50,50) and radius=10


SPI_Glcd_Circle(50, 50, 10, 1);

SPI_Glcd_Circle_FIll

Prototype void SPI_Glcd_Circle_Fill(int x_center, int y_center, int radius, char color
);

Returns Nothing.

Descriptio Draws a filled circle on Glcd.


n
Parameters :

 x_center: x coordinate of the circle center. Valid values: 0..127


 y_center: y coordinate of the circle center. Valid values: 0..63
 radius: radius size
 color: color parameter. Valid values: 0..2
The parameter color determines the color of the circle : 0 white, 1 black, and 2 inverts each dot.

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.

Example // Draw a circle with center in (50,50) and radius=10


SPI_Glcd_Circle_Fill(50, 50, 10, 1);

SPI_Glcd_Set_Font

Prototype void SPI_Glcd_Set_Font(const code


char *activeFont, char aFontWidth, char aFontHeight, unsigned
int aFontOffs);

Returns Nothing.

Description Sets font that will be used with SPI_Glcd_Write_Char and SPI_Glcd_Write_Text routines.
Parameters :

 activeFont: font to be set. Needs to be formatted as an array of char


 aFontWidth: width of the font characters in dots.
 aFontHeight: height of the font characters in dots.
 aFontOffs: number that represents difference between the mikroC PRO for PIC character set
and regular ASCII set (eg. if 'A' is 65 in ASCII character, and 'A' is 45 in the mikroC PRO
character set, aFontOffs is 20). Demo fonts supplied with the library have an offset of 32, which
means that they start with space.

www.raguvaran.puzl.com
The user can use fonts given in the file __Lib_GLCDFonts file located in the Uses folder or create his own fonts.
List of supported fonts:
 Font_Glcd_System3x5
 Font_Glcd_System5x7
 Font_Glcd_5x7
 Font_Glcd_Character8x7
For the sake of the backward compatibility, these fonts are supported also:

 System3x5 (equivalent to Font_Glcd_System3x5)


 FontSystem5x7_v2 (equivalent to Font_Glcd_System5x7)
 font5x7 (equivalent to Font_Glcd_5x7)
 Character8x7 (equivalent to Font_Glcd_Character8x7)

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.

Example // Use the custom 5x7 font "myfont" which starts with space (32):
SPI_Glcd_Set_Font(myfont, 5, 7, 32);

SPI_Glcd_Set_Font_Adv

Prototype void SPI_Glcd_Set_Font_Adv(const char *activeFont, unsigned


char font_color, char font_orientation);

Description Sets font that will be used with SPI_Glcd_Write_Char_Adv and SPI_Glcd_Write_Text_Adv routines. Font is
located in an external resource.

Parameters  activeFont: font to be set. Needs to be formatted as an array of char.


 font_color: sets font color.
 font_orientation: sets font orientation.

Returns Nothing.

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.

Example Glcd_Set_Font_Adv(&myfont, 0, 0);

Notes None.

SPI_Glcd_Set_Ext_Font_Adv

Prototype void SPI_Glcd_Set_Ext_Font_Adv(unsigned long activeFont, unsigned


short aFontWidth, unsigned short aFontHeight, unsigned int aFontOffs);

Description Sets font that will be used with SPI_Glcd_Write_Char_Adv and SPI_Glcd_Write_Text_Adv routines. Font is
located in an external resource.

Parameters  activeFont: font to be set. This parameter represents the address in the exteral resource from
where the font data begins.
 font_color: sets font color.

www.raguvaran.puzl.com
 font_orientation: sets font orientation.

Returns Nothing.

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.

Example SPI_Glcd_Set_Ext_Font_Adv(173296, 5, 7, 32);

Notes None.

SPI_Glcd_Write_Char

Prototype void SPI_Glcd_Write_Char(char chr1, char x_pos, char page_num, char color);

Returns Nothing.

Description Prints character on Glcd.

Parameters :

 chr1: character to be written


 x_pos: character starting position on x-axis. Valid values: 0..(127-FontWidth)
 page_num: the number of the page on which character will be written. Valid values: 0..7
 color: color parameter. Valid values: 0..2
The parameter color determines the color of the character: 0 white, 1 black, and 2 inverts each dot.

Note : For side, x axis and page layout explanation see schematic at the bottom of this page.

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.
Use the SPI_Glcd_Set_Font to specify the font for display; if no font is specified, then the
default Font_Glcd_System5x7 font supplied with the library will be used.

Example // Write character 'C' on the position 10 inside the page 2:


SPI_Glcd_Write_Char('C', 10, 2, 1);

SPI_Glcd_Write_Char_Adv

Prototype void SPI_Glcd_Write_Char_Adv(unsigned int c, unsigned int x, unsigned


int y);

Returns Nothing.

Description Writes a char on the glcd at coordinates (x, y).

 c: char to be written.
 x: char position on x-axis.

www.raguvaran.puzl.com
 y: char position on y-axis.

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.

Example SPI_Glcd_Write_Char_Adv('A',22,23,);

SPI_Glcd_Write_Text

Prototype void SPI_Glcd_Write_Text(char text[], char x_pos, char page_num, char color)
;

Returns Nothing.

Descriptio Prints text on Glcd.


n
Parameters :

 text: text to be written


 x_pos: text starting position on x-axis.
 page_num: the number of the page on which text will be written. Valid values: 0..7
 color: color parameter. Valid values: 0..2
The parameter color determines the color of the text: 0 white, 1 black, and 2 inverts each dot.

Note : For side, x axis and page layout explanation see schematic at the bottom of this page.

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.
Use the SPI_Glcd_Set_Font to specify the font for display; if no font is specified, then the
default Font_Glcd_System5x7 font supplied with the library will be used.

Example // Write text "Hello world!" on the position 10 inside the page 2:
SPI_Glcd_Write_Text("Hello world!", 10, 2, 1);

SPI_Glcd_Write_Text_Adv

Prototype void SPI_Glcd_Write_Text_Adv(unsigned char *text, unsigned int x, unsigned


int y);

Returns Nothing.

Description Writes text on the glcd at coordinates (x, y).

Parameters :

 text: text to be written.


 x: text position on x-axis.
 y: text position on y-axis.

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.

www.raguvaran.puzl.com
Example SPI_Glcd_Write_Text_Adv("GLCD LIBRARY DEMO, WELCOME !", 0, 0,);

SPI_Glcd_Write_Const_Text_Adv

Prototype void SPI_Glcd_Write_Const_Text_Adv(const far char *text, unsigned


int x, unsigned int y);

Returns Nothing.

Description Writes text located in the program memory on the glcd at coordinates (x, y).

Parameters :

 text: text to be written.


 x: text position on x-axis.
 y: text position on y-axis.

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.

Example const char ctext[] = "mikroElektronika";


...
SPI_Glcd_Write_Const_Text_Adv(ctext, 0, 0,);

SPI_Glcd_Image

Prototype void SPI_Glcd_Image(const code char *image);

Returns Nothing.

Description Displays bitmap on Glcd.

Parameters :

 image: image to be displayed. Bitmap array is located in code memory.


Use the integrated Glcd Bitmap Editor (menu option Tools › Glcd Bitmap Editor) to convert image to a constant
array suitable for displaying on Glcd.

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.

Example // Draw image my_image on Glcd


SPI_Glcd_Image(my_image);

SPI_Glcd_Ext_Image

Prototype void SPI_Glcd_Ext_Image(unsigned long image);

www.raguvaran.puzl.com
Description Displays a bitmap from an external resource on a desired address.

Parameters  image: image to be displayed. This parameter represents the address in the exteral resource from
where the image data begins.

Returns Nothing.

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.

Example SPI_Glcd_Ext_Image(153608);

Notes Use the mikroC PRO for AVR integrated Glcd Bitmap Editor, Tools > Glcd Bitmap Editor, to convert image to
a constant array suitable for displaying on Glcd.

SPI_Glcd_PartialImage

Prototype void SPI_Glcd_PartialImage(unsigned int x_left, unsigned int y_top, unsigned


int width, unsigned int height, unsigned int picture_width, unsigned
int picture_height, code const unsigned short * image);

Returns Nothing.

Description Displays a partial area of the image on a desired location.

Parameters :

 x_left: x coordinate of the desired location (upper left coordinate).


 y_top: y coordinate of the desired location (upper left coordinate).
 width: desired image width.
 height: desired image height.
 picture_width: width of the original image.
 picture_height: height of the original image.
 image: image to be displayed. Bitmap array is located in code memory.
Use the integrated Glcd Bitmap Editor (menu option Tools › Glcd Bitmap Editor) to convert image to a constant
array suitable for displaying on Glcd.

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.

Example // Draws a 10x15 part of the image starting from the upper left corner on the
coordinate (10,12). Original image size is 16x32.
SPI_Glcd_PartialImage(10, 12, 10, 15, 16, 32, image);

SPI_Glcd_Ext_PartialImage

Prototype void SPI_Glcd_Ext_PartialImage(unsigned int x_left, unsigned

www.raguvaran.puzl.com
int y_top, unsigned int width, unsigned int height, unsigned
int picture_width,unsigned int picture_height, unsigned long image);

Description Displays a partial area of the image, located on an external resource, on a desired location of the screen.

Parameters  x_left: x coordinate of the desired location (upper left coordinate).


 y_top: y coordinate of the desired location (upper left coordinate).
 width: desired image width.
 height: desired image height.
 picture_width: width of the original image.
 picture_height: height of the original image.
 image: image to be displayed. This parameter represents the address in the exteral resource from
where the image data begins.

Returns Nothing.

Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.

Example SPI_Glcd_Ext_PartialImage(10, 12, 10, 15, 16, 32, 0);

Notes Use the mikroC PRO for AVR integrated Glcd Bitmap Editor, Tools > Glcd Bitmap Editor, to convert image to
a constant array suitable for displaying on Glcd.

Library Example
The example demonstrates how to communicate to KS0108 Glcd via the SPI module, using serial to
parallel convertor MCP23S17.

Copy Code To Clipboard

const code char truck_bmp[1024];

// Port Expander module connections


sbit SPExpanderRST at RC0_bit;
sbit SPExpanderCS at RC1_bit;
sbit SPExpanderRST_Direction at TRISC0_bit;
sbit SPExpanderCS_Direction at TRISC1_bit;
// End Port Expander module connections

void Delay2s(){ // 2 seconds delay function


Delay_ms(2000);
}

void main() {
char counter;
char *someText;

#define COMPLETE_EXAMPLE
ANSEL = 0; // Configure AN pins as digital
ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;

// If Port Expander Library uses SPI1 module


SPI1_Init(); // Initialize SPI module used with
PortExpander

www.raguvaran.puzl.com
// // If Port Expander Library uses SPI2 module
// SPI2_Init(); // Initialize SPI module used with PortExpander

SPI_Glcd_Init(0); // Initialize Glcd via SPI


SPI_Glcd_Fill(0x00); // Clear Glcd

while(1) {
#ifdef COMPLETE_EXAMPLE
SPI_Glcd_Image(truck_bmp); // Draw image
Delay2s(); Delay2s();
#endif
SPI_Glcd_Fill(0x00); // Clear Glcd
Delay2s;

SPI_Glcd_Box(62,40,124,56,1); // Draw box


SPI_Glcd_Rectangle(5,5,84,35,1); // Draw rectangle
SPI_Glcd_Line(0, 63, 127, 0,1); // Draw line
Delay2s();

for(counter = 5; counter < 60; counter+=5 ) { // Draw horizontal and vertical line
Delay_ms(250);
SPI_Glcd_V_Line(2, 54, counter, 1);
SPI_Glcd_H_Line(2, 120, counter, 1);
}
Delay2s();

#ifdef COMPLETE_EXAMPLE
SPI_Glcd_Fill(0x00); // Clear Glcd
SPI_Glcd_Set_Font(Font_Glcd_Character8x7, 8, 8, 32); // Choose font, see __Lib_GLCDFonts.c
in Uses folder
SPI_Glcd_Write_Text("mikroE", 5, 7, 2); // Write string
#endif

for (counter = 1; counter <= 10; counter++) // Draw circles


SPI_Glcd_Circle(63,32, 3*counter, 1);
Delay2s();

#ifdef COMPLETE_EXAMPLE
SPI_Glcd_Box(12,20, 70,63, 2); // Draw box
Delay2s();

SPI_Glcd_Fill(0xFF); // Fill Glcd


SPI_Glcd_Set_Font(Font_Glcd_Character8x7, 8, 7, 32); // Change font
someText = "8x7 Font";
SPI_Glcd_Write_Text(someText, 5, 1, 2); // Write string
Delay2s();

SPI_Glcd_Set_Font(Font_Glcd_System3x5, 3, 5, 32); // Change font


someText = "3X5 CAPITALS ONLY";
SPI_Glcd_Write_Text(someText, 5, 3, 2); // Write string
Delay2s();

SPI_Glcd_Set_Font(Font_Glcd_System5x7, 5, 7, 32); // Change font


someText = "5x7 Font";
SPI_Glcd_Write_Text(someText, 5, 5, 2); // Write string
Delay2s();

SPI_Glcd_Set_Font(Font_Glcd_5x7, 5, 7, 32); // Change font


someText = "5x7 Font (v2)";
SPI_Glcd_Write_Text(someText, 5, 7, 2); // Write string
Delay2s();
#endif
}
}

www.raguvaran.puzl.com
HW Connection

SPI Glcd HW connection

SPI Lcd Library


The mikroC PRO for PIC provides a library for communication with Lcd (with HD44780 compliant
controllers) in 4-bit mode via SPI interface.
For creating a custom set of Lcd characters use Lcd Custom Character Tool.

Important :

www.raguvaran.puzl.com
 The library uses the SPI module for communication. The user must initialize the SPI module
before using the SPI Lcd Library.
 This Library is designed to work with the mikroElektronika's Serial Lcd Adapter Board
pinout. See schematic at the bottom of this page for details.

Library Dependency Tree

External dependencies of SPI Lcd Library


The implementation of SPI Lcd Library routines is based on Port Expander Library routines.
External dependencies are the same as Port Expander Library external dependencies.

Library Routines
 SPI_Lcd_Config
 SPI_Lcd_Out
 SPI_Lcd_Out_Cp
 SPI_Lcd_Chr
 SPI_Lcd_Chr_Cp
 SPI_Lcd_Cmd

SPI_Lcd_Config

Prototype void SPI_Lcd_Config(char DeviceAddress);

Returns Nothing.

Description Initializes the Lcd module via SPI interface.


Parameters :

 DeviceAddress: SPI expander hardware address, see schematic at the


bottom of this page

Requires Global variables :

 SPExpanderCS: Chip Select line


 SPExpanderRST: Reset line
 SPExpanderCS_Direction: Direction of the Chip Select pin
 SPExpanderRST_Direction: Direction of the Reset pin
must be defined before using this function.

The SPI module needs to be initialized.


See SPIx_Init and SPIx_Init_Advanced routines.

Example // Port Expander module connections


sbit SPExpanderRST at RC0_bit;
sbit SPExpanderCS at RC1_bit;

www.raguvaran.puzl.com
sbit SPExpanderRST_Direction at TRISC0_bit;
sbit SPExpanderCS_Direction at TRISC1_bit;
// End Port Expander module connections

void main() {

// If Port Expander Library uses SPI1 module


SPI1_Init(); // Initialize SPI module used with
PortExpander
SPI_Lcd_Config(0); // initialize Lcd over SPI interface

SPI_Lcd_Out

Prototype void SPI_Lcd_Out(char row, char column, char *text);

Returns Nothing.

Description Prints text on the Lcd starting from specified position. Both string variables and literals
can be passed as a text.

Parameters :

 row: starting position row number


 column: starting position column number
 text: text to be written

Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd_Config routines.

Example // Write text "Hello!" on Lcd starting from row 1, column 3:


SPI_Lcd_Out(1, 3, "Hello!");

SPI_Lcd_Out_Cp

Prototype void SPI_Lcd_Out_CP(char *text);

Returns Nothing.

Description Prints text on the Lcd at current cursor position. Both string variables and literals can
be passed as a text.

Parameters :

 text: text to be written

Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd_Config routines.

www.raguvaran.puzl.com
Example // Write text "Here!" at current cursor position:
SPI_Lcd_Out_CP("Here!");

SPI_Lcd_Chr

Prototype void SPI_Lcd_Chr(char Row, char Column, char Out_Char);

Returns Nothing.

Description Prints character on Lcd at specified position. Both variables and literals can be passed
as character.

Parameters :

 Row: writing position row number


 Column: writing position column number
 Out_Char: character to be written

Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd_Config routines.

Example // Write character "i" at row 2, column 3:


SPI_Lcd_Chr(2, 3, 'i');

SPI_Lcd_Chr_Cp

Prototype void SPI_Lcd_Chr_CP(char Out_Char);

Returns Nothing.

Description Prints character on Lcd at current cursor position. Both variables and literals can be
passed as character.

Parameters :

 Out_Char: character to be written

Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd_Config routines.

Example // Write character "e" at current cursor position:


SPI_Lcd_Chr_Cp('e');

SPI_Lcd_Cmd

www.raguvaran.puzl.com
Prototype void SPI_Lcd_Cmd(char out_char);

Returns Nothing.

Description Sends command to Lcd.

Parameters :

 out_char: command to be sent

Note : Predefined constants can be passed to the function, see Available SPI Lcd
Commands.

Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd_Config routines.

Example // Clear Lcd display:


SPI_Lcd_Cmd(_LCD_CLEAR);

Available SPI Lcd Commands

SPI Lcd Command Purpose

_LCD_FIRST_ROW Move cursor to the 1st row

_LCD_SECOND_ROW Move cursor to the 2nd row

_LCD_THIRD_ROW Move cursor to the 3rd row

_LCD_FOURTH_ROW Move cursor to the 4th row

_LCD_CLEAR Clear display

_LCD_RETURN_HOME Return cursor to home position, returns a shifted display to its original position. Display
data RAM is unaffected.

_LCD_CURSOR_OFF Turn off cursor

_LCD_UNDERLINE_ON Underline cursor on

_LCD_BLINK_CURSOR_ON Blink cursor on

_LCD_MOVE_CURSOR_LEFT Move cursor left without changing display data RAM

www.raguvaran.puzl.com
SPI Lcd Command Purpose

_LCD_MOVE_CURSOR_RIGHT Move cursor right without changing display data RAM

_LCD_TURN_ON Turn Lcd display on

_LCD_TURN_OFF Turn Lcd display off

_LCD_SHIFT_LEFT Shift display left without changing display data RAM

_LCD_SHIFT_RIGHT Shift display right without changing display data RAM

Library Example
This example demonstrates how to communicate Lcd via the SPI module, using serial to parallel
convertor MCP23S17.

Copy Code To Clipboard

char *text = "mikroElektronika";

// Port Expander module connections


sbit SPExpanderRST at RC0_bit;
sbit SPExpanderCS at RC1_bit;
sbit SPExpanderRST_Direction at TRISC0_bit;
sbit SPExpanderCS_Direction at TRISC1_bit;
// End Port Expander module connections

void main() {

ANSEL = 0; // Configure AN pins as digital


ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;

// If Port Expander Library uses SPI1 module


SPI1_Init(); // Initialize SPI module used with PortExpander

// // If Port Expander Library uses SPI2 module


// SPI2_Init(); // Initialize SPI module used with PortExpander

SPI_Lcd_Config(0); // Initialize Lcd over SPI interface


SPI_Lcd_Cmd(_LCD_CLEAR); // Clear display
SPI_Lcd_Cmd(_LCD_CURSOR_OFF); // Turn cursor off
SPI_Lcd_Out(1,6, "mikroE"); // Print text to Lcd, 1st row, 6th column
SPI_Lcd_Chr_CP('!'); // Append '!'
SPI_Lcd_Out(2,1, text); // Print text to Lcd, 2nd row, 1st column

// SPI_Lcd_Out(3,1,"mikroE"); // For Lcd with more than two rows


// SPI_Lcd_Out(4,15,"mikroE"); // For Lcd with more than two rows
}

HW Connection

www.raguvaran.puzl.com
SPI Lcd HW connection

SPI Lcd8 (8-bit interface) Library


The mikroC PRO for PIC provides a library for communication with Lcd (with HD44780 compliant
controllers) in 8-bit mode via SPI interface.
For creating a custom set of Lcd characters use Lcd Custom Character Tool.

Important :

 The library uses the SPI module for communication. The user must initialize the SPI module
before using the SPI Lcd8 Library.

www.raguvaran.puzl.com
 This Library is designed to work with the mikroElektronika's Serial Lcd/Glcd Adapter Board
pinout. See schematic at the bottom of this page for details.

Library Dependency Tree

External dependencies of SPI Lcd Library


The implementation of SPI Lcd Library routines is based on Port Expander Library routines.
External dependencies are the same as Port Expander Library external dependencies.

Library Routines
 SPI_Lcd8_Config
 SPI_Lcd8_Out
 SPI_Lcd8_Out_Cp
 SPI_Lcd8_Chr
 SPI_Lcd8_Chr_Cp
 SPI_Lcd8_Cmd

SPI_Lcd8_Config

Prototype void SPI_Lcd8_Config(char DeviceAddress);

Returns Nothing.

Description Initializes the Lcd module via SPI interface.


Parameters :

 DeviceAddress: SPI expander hardware address, see schematic at the


bottom of this page

Requires Global variables :

 SPExpanderCS: Chip Select line


 SPExpanderRST: Reset line
 SPExpanderCS_Direction: Direction of the Chip Select pin
 SPExpanderRST_Direction: Direction of the Reset pin
must be defined before using this function.

The SPI module needs to be initialized.


See SPIx_Init and SPIx_Init_Advanced routines.

Example // Port Expander module connections


sbit SPExpanderRST at RC0_bit;
sbit SPExpanderCS at RC1_bit;
sbit SPExpanderRST_Direction at TRISC0_bit;
sbit SPExpanderCS_Direction at TRISC1_bit;

www.raguvaran.puzl.com
// End Port Expander module connections

...

// If Port Expander Library uses SPI1 module


SPI1_Init(); // Initialize SPI module used with
PortExpander
SPI_Lcd8_Config(0); // intialize Lcd in 8bit mode via SPI

SPI_Lcd8_Out

Prototype void SPI_Lcd8_Out(unsigned short row, unsigned short column, char *text);

Returns Nothing.

Description Prints text on Lcd starting from specified position. Both string variables and literals can
be passed as a text.

Parameters :

 row: starting position row number


 column: starting position column number
 text: text to be written

Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd8_Config routine.

Example // Write text "Hello!" on Lcd starting from row 1, column 3:


SPI_Lcd8_Out(1, 3, "Hello!");

SPI_Lcd8_Out_Cp

Prototype void SPI_Lcd8_Out_CP(char *text);

Returns Nothing.

Description Prints text on Lcd at current cursor position. Both string variables and literals can be
passed as a text.

Parameters :

 text: text to be written

Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd8_Config routine.

www.raguvaran.puzl.com
Example // Write text "Here!" at current cursor position:
SPI_Lcd8_Out_Cp("Here!");

SPI_Lcd8_Chr

Prototype void SPI_Lcd8_Chr(unsigned short row, unsigned


short column, char out_char);

Returns Nothing.

Description Prints character on Lcd at specified position. Both variables and literals can be passed
as character.

Parameters :

 row: writing position row number


 column: writing position column number
 out_char: character to be written

Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd8_Config routine.

Example // Write character "i" at row 2, column 3:


SPI_Lcd8_Chr(2, 3, 'i');

SPI_Lcd8_Chr_Cp

Prototype void SPI_Lcd8_Chr_CP(char out_char);

Returns Nothing.

Description Prints character on Lcd at current cursor position. Both variables and literals can be
passed as character.

Parameters :

 out_char: character to be written

Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd8_Config routine.

Example Print “e” at current cursor position:

// Write character "e" at current cursor position:


SPI_Lcd8_Chr_Cp('e');

www.raguvaran.puzl.com
SPI_Lcd8_Cmd

Prototype void SPI_Lcd8_Cmd(char out_char);

Returns Nothing.

Description Sends command to Lcd.

Parameters :

 out_char: command to be sent

Note : Predefined constants can be passed to the function, see Available SPI
Lcd8 Commands.

Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd8_Config routine.

Example // Clear Lcd display:


SPI_Lcd8_Cmd(_LCD_CLEAR);

Available SPI Lcd8 Commands

SPI Lcd8 Command Purpose

_LCD_FIRST_ROW Move cursor to the 1st row

_LCD_SECOND_ROW Move cursor to the 2nd row

_LCD_THIRD_ROW Move cursor to the 3rd row

_LCD_FOURTH_ROW Move cursor to the 4th row

_LCD_CLEAR Clear display

_LCD_RETURN_HOME Return cursor to home position, returns a shifted display to its original position. Display
data RAM is unaffected.

_LCD_CURSOR_OFF Turn off cursor

_LCD_UNDERLINE_ON Underline cursor on

_LCD_BLINK_CURSOR_ON Blink cursor on

_LCD_MOVE_CURSOR_LEFT Move cursor left without changing display data RAM

www.raguvaran.puzl.com
SPI Lcd8 Command Purpose

_LCD_MOVE_CURSOR_RIGHT Move cursor right without changing display data RAM

_LCD_TURN_ON Turn Lcd display on

_LCD_TURN_OFF Turn Lcd display off

_LCD_SHIFT_LEFT Shift display left without changing display data RAM

_LCD_SHIFT_RIGHT Shift display right without changing display data RAM

Library Example
This example demonstrates how to communicate Lcd in 8-bit mode via the SPI module, using serial to
parallel convertor MCP23S17.

Copy Code To Clipboard

char *text = "mikroElektronika";

// Port Expander module connections


sbit SPExpanderRST at RC0_bit;
sbit SPExpanderCS at RC1_bit;
sbit SPExpanderRST_Direction at TRISC0_bit;
sbit SPExpanderCS_Direction at TRISC1_bit;
// End Port Expander module connections

void main() {

ANSEL = 0; // Configure AN pins as digital


ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;

// If Port Expander Library uses SPI1 module


SPI1_Init(); // Initialize SPI module used with PortExpander

// // If Port Expander Library uses SPI2 module


// SPI2_Init(); // Initialize SPI module used with PortExpander

SPI_Lcd8_Config(0); // Initialize Lcd over SPI interface


SPI_Lcd8_Cmd(_LCD_CLEAR); // Clear display
SPI_Lcd8_Cmd(_LCD_CURSOR_OFF); // Turn cursor off
SPI_Lcd8_Out(1,6, "mikroE"); // Print text to Lcd, 1st row, 6th column
SPI_Lcd8_Chr_CP('!'); // Append '!'
SPI_Lcd8_Out(2,1, text); // Print text to Lcd, 2nd row, 1st column

// SPI_Lcd8_Out(3,1,"mikroE"); // For Lcd with more than two rows


// SPI_Lcd8_Out(4,15,"mikroE"); // For Lcd with more than two rows
}

HW Connection

www.raguvaran.puzl.com
SPI Lcd8 HW connection

SPI T6963C Graphic Lcd Library


The mikroC PRO for PIC provides a library for working with Glcds based on TOSHIBA T6963C controller
via SPI interface. The Toshiba T6963C is a very popular Lcd controller for the use in small graphics
modules. It is capable of controlling displays with a resolution up to 240x128. Because of its low power
and small outline it is most suitable for mobile applications such as PDAs, MP3 players or mobile
measurement equipment. Although this controller is small, it has a capability of displaying and merging
text and graphics and it manages all interfacing signals to the displays Row and Column drivers.
For creating a custom set of Glcd images use Glcd Bitmap Editor Tool.

Important :
 The library uses the SPI module for communication.
 The user must initialize SPI module before using the SPI T6963C Glcd Library.
 This Library is designed to work with mikroElektronika's Serial Glcd 240x128 and 240x64
Adapter Boards pinout, see schematic at the bottom of this page for details.

www.raguvaran.puzl.com
 To use constants located in __Lib_SPIT6963C_Const.h file, user must include it the source
file : #include "__SPIT6963C.h".
 PIC16 family of MCUs does not support working with external resources.

Some mikroElektronika's adapter boards have pinout different from T6369C datasheets. Appropriate
relations between these labels are given in the table below:

Adapter Board T6369C datasheet

RS C/D

R/W /RD

E /WR

Library Dependency Tree

External dependencies of SPI T6963C Graphic Lcd Library


The implementation of SPI T6963C Graphic Lcd Library routines is based on Port Expander Library
routines.
External dependencies are the same as Port Expander Library external dependencies.

Library Routines
 SPI_T6963C_Config
 SPI_T6963C_writeData
 SPI_T6963C_writeCommand
 SPI_T6963C_setPtr
 SPI_T6963C_Set_Ext_Buffer
 SPI_T6963C_waitReady
 SPI_T6963C_fill
 SPI_T6963C_dot
 SPI_T6963C_Set_Font_Adv
 SPI_T6963C_Set_Font_Ext_Adv
 SPI_T6963C_write_char
 SPI_T6963C_Write_Char_Adv
 SPI_T6963C_write_text
 SPI_T6963C_Write_Text_Adv
 SPI_T6963C_Write_Const_Text_Adv
 SPI_T6963C_line
 SPI_T6963C_rectangle
 SPI_T6963C_rectangle_round_edges
 SPI_T6963C_rectangle_round_edges_fill
 SPI_T6963C_box
 SPI_T6963C_circle
 SPI_T6963C_circle_fill
 SPI_T6963C_image
 SPI_T6963C_Ext_Image
 SPI_T6963C_PartialImage
 SPI_T6963C_Ext_PartialImage
 SPI_T6963C_sprite
 SPI_T6963C_set_cursor

www.raguvaran.puzl.com
 SPI_T6963C_clearBit
 SPI_T6963C_setBit
 SPI_T6963C_negBit
The following low level library routines are implemented as macros. These macros can be found in
the __SPIT6963C.h header file which is located in the SPI T6963C example projects folders.
 SPI_T6963C_displayGrPanel
 SPI_T6963C_displayTxtPanel
 SPI_T6963C_setGrPanel
 SPI_T6963C_setTxtPanel
 SPI_T6963C_panelFill
 SPI_T6963C_grFill
 SPI_T6963C_txtFill
 SPI_T6963C_cursor_height
 SPI_T6963C_graphics
 SPI_T6963C_text
 SPI_T6963C_cursor
 SPI_T6963C_cursor_blink

SPI_T6963C_Config

Prototype void SPI_T6963C_Config(unsigned int width, unsigned char height, unsigned


char fntW, char DeviceAddress, unsigned char wr, unsigned
char rd,unsigned char cd, unsigned char rst);

Returns Nothing.

Description Initializes T6963C Graphic Lcd controller.

Parameters :

 width: width of the Glcd panel


 height: height of the Glcd panel
 fntW: font width
 DeviceAddress: SPI expander hardware address, see schematic at the
bottom of this page
 wr: write signal pin on Glcd control port
 rd: read signal pin on Glcd control port
 cd: command/data signal pin on Glcd control port
 rst: reset signal pin on Glcd control port
Display RAM organization:
The library cuts RAM into panels : a complete panel is one graphics panel followed by a
text panel (see schematic below).
schematic:
+---------------------+ /\
+ GRAPHICS PANEL #0 + |
+ + |
+ + |
+ + |
+---------------------+ | PANEL 0
+ TEXT PANEL #0 + |
+ + \/
+---------------------+ /\
+ GRAPHICS PANEL #1 + |
+ + |
+ + |

www.raguvaran.puzl.com
+ + |
+---------------------+ | PANEL 1
+ TEXT PANEL #1 + |
+ + |
+---------------------+ \/

Requires Global variables :


 SPExpanderCS: Chip Select line
 SPExpanderRST: Reset line
 SPExpanderCS_Direction: Direction of the Chip Select pin
 SPExpanderRST_Direction: Direction of the Reset pin
must be defined before using this function.

The SPI module needs to be initialized. See


the SPIx_Init and SPIx_Init_Advanced routines.

Example // Port Expander module connections


sbit SPExpanderRST at RC0_bit;
sbit SPExpanderCS at RC1_bit;
sbit SPExpanderRST_Direction at TRISC0_bit;
sbit SPExpanderCS_Direction at TRISC1_bit;
// End Port Expander module connections

...

// Initialize SPI module


SPI1_Init();
SPI_T6963C_Config(240, 64, 8, 0, 0, 1, 3, 4);

SPI_T6963C_writeData

Prototype void SPI_T6963C_writeData(unsigned char Ddata);

Returns Nothing.

Description Writes data to T6963C controller via SPI interface.


Parameters :

 Ddata: data to be written

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_writeData(AddrL);

SPI_T6963C_writeCommand

Prototype void SPI_T6963C_writeCommand(unsigned char Ddata);

Returns Nothing.

www.raguvaran.puzl.com
Description Writes command to T6963C controller via SPI interface.
Parameters :

 Ddata: command to be written

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_writeCommand(SPI_T6963C_CURSOR_POINTER_SET);

SPI_T6963C_setPtr

Prototype void SPI_T6963C_setPtr(unsigned int p, unsigned char c);

Returns Nothing.

Description Sets the memory pointer p for command c.

Parameters :

 p: address where command should be written


 c: command to be written

Requires SToshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_setPtr(SPI_T6963C_grHomeAddr + start, SPI_T6963C_ADDRESS_POINTER_SET);

SPI_T6963C_Set_Ext_Buffer

Prototype void SPI_T6963C_Set_Ext_Buffer(char* (*getExtDataPtr)(unsigned


long offset, unsigned int count, unsigned int *num));

Returns Nothing.

Description Function sets pointer to the user function which manipulates the external resource.

Parameters :

 offset - offset from the beginning of the resource from where the data is
requested.
 count - requested number of bytes.
 num - variable for holding the returned number ob byte (less or equal to
the number of acqired bytes).

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example char* ReadExternalBuffer(unsigned long offset, unsigned int count, unsigned int
*num){

www.raguvaran.puzl.com
unsigned long start_sector;
unsigned int pos;

start_sector = Mmc_Get_File_Write_Sector() + offset/512;


pos = (unsigned long)offset%512;

if(start_sector == currentSector+1){
Mmc_Multi_Read_Buffer(EXT_BUFFER);
currentSector = start_sector;
}else
if(start_sector != currentSector){
Mmc_Multi_Read_Stop();
Mmc_Multi_Read_Start(start_sector);
Mmc_Multi_Read_Buffer(EXT_BUFFER);
currentSector = start_sector;
}

if(count>512-pos){
*num = 512-pos;
}
else
*num = count;

return EXT_BUFFER+pos;
}

SPI_T6963C_Set_Ext_Buffer(ReadExternalBuffer);

SPI_T6963C_waitReady

Prototype void SPI_T6963C_waitReady(void);

Returns Nothing.

Description Pools the status byte, and loops until Toshiba Glcd module is ready.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_waitReady();

SPI_T6963C_fill

Prototype void SPI_T6963C_fill(unsigned char v, unsigned int start, unsigned


int len);

Returns Nothing.

Description Fills controller memory block with given byte.

Parameters :

 v: byte to be written

www.raguvaran.puzl.com
 start: starting address of the memory block
 len: length of the memory block in bytes

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_fill(0x33,0x00FF,0x000F);

SPI_T6963C_dot

Prototype void SPI_T6963C_dot(int x, int y, unsigned char color);

Returns Nothing.

Description Draws a dot in the current graphic panel of Glcd at coordinates (x, y).

Parameters :

 x: dot position on x-axis


 y: dot position on y-axis
 color: color parameter. Valid values: SPI_T6963C_BLACK and
SPI_T6963C_WHITE

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_dot(x0, y0, SPI_T6963C_WHITE);

SPI_T6963C_Set_Font_Adv

Prototype void SPI_T6963C_Set_Font_Adv(const far char *activeFont, unsigned


char font_color, char font_orientation);

Description Sets font that will be used


with SPI_T6963C_Write_Char_Adv and SPI_T6963C_Write_Text_Adv routines.

Parameters  activeFont: font to be set. Needs to be formatted as an array of char.


 font_color: sets font color.
 font_orientation: sets font orientation.

Returns Nothing.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_Set_Font_Adv(&myfont, 1, 0,);

Notes None.

www.raguvaran.puzl.com
SPI_T6963C_Set_Ext_Font_Adv

Prototype void SPI_T6963C_Set_Ext_Font_Adv(unsigned long activeFont, unsigned


char font_color, char font_orientation);

Description Sets font that will be used


with SPI_T6963C_Write_Char_Adv and SPI_T6963C_Write_Text_Adv routines. Font is
located in an external resource.

Parameters  activeFont: font to be set. This parameter represents the address in the
exteral resource from where the font data begins.
 font_color: sets font color.
 font_orientation: sets font orientation.

Returns Nothing.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_Set_Ext_Font_Adv(173296, 0, 0);

Notes None.

SPI_T6963C_write_char

Prototy void SPI_T6963C_write_char(unsigned char c, unsigned char x, unsigned


pe char y, unsigned char mode);

Returns Nothing.

Descript Writes a char in the current text panel of Glcd at coordinates (x, y).
ion
Parameters :

 c: char to be written
 x: char position on x-axis
 y: char position on y-axis
 mode: mode parameter. Valid
values: SPI_T6963C_ROM_MODE_OR, SPI_T6963C_ROM_MODE_XOR, SPI_T6963C_ROM_MOD
E_AND and SPI_T6963C_ROM_MODE_TEXT
Mode parameter explanation:

 SPI_T6963C_ROM_MODE_OR Mode: In the OR-Mode, text and graphics can be


displayed and the data is logically “OR-ed”. This is the most common way of
combining text and graphics for example labels on buttons.
 SPI_T6963C_ROM_MODE_XOR Mode: In this mode, the text and graphics data are
combined via the logical “exclusive OR”. This can be useful to display text in
negative mode, i.e. white text on black background.
 SPI_T6963C_ROM_MODE_AND Mode: The text and graphic data shown on display

www.raguvaran.puzl.com
are combined via the logical “AND function”.
 SPI_T6963C_ROM_MODE_TEXT Mode: This option is only available when displaying
just a text. The Text Attribute values are stored in the graphic area of display
memory.
For more details see the T6963C datasheet.

Require Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.


s

Exampl SPI_T6963C_write_char("A",22,23,SPI_T6963C_ROM_MODE_AND);
e

SPI_T6963C_write_char_adv

Prototype void SPI_T6963C_write_char_adv(unsigned char ch, unsigned int x, unsigned


int y);

Description Writes a char in the current text panel of Glcd at coordinates (x, y).

Parameters  c: char to be written


 x: char position on x-axis
 y: char position on y-axis

Returns Nothing.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_Write_Char_Adv('A',22,23);

Notes None.

SPI_T6963C_write_text

Prototy void SPI_T6963C_write_text(unsigned char *str, unsigned char x, unsigned


pe char y, unsigned char mode);

Returns Nothing.

Descript Writes text in the current text panel of Glcd at coordinates (x, y).
ion
Parameters :

 str: text to be written


 x: text position on x-axis
 y: text position on y-axis

www.raguvaran.puzl.com
 mode: mode parameter. Valid
values: SPI_T6963C_ROM_MODE_OR, SPI_T6963C_ROM_MODE_XOR, SPI_T6963C_ROM_MOD
E_AND and SPI_T6963C_ROM_MODE_TEXT
Mode parameter explanation:

 SPI_T6963C_ROM_MODE_OR Mode: In the OR-Mode, text and graphics can be


displayed and the data is logically “OR-ed”. This is the most common way of
combining text and graphics for example labels on buttons.
 SPI_T6963C_ROM_MODE_XOR Mode: In this mode, the text and graphics data are
combined via the logical “exclusive OR”. This can be useful to display text in
negative mode, i.e. white text on black background.
 SPI_T6963C_ROM_MODE_AND Mode: The text and graphic data shown on display
are combined via the logical “AND function”.
 SPI_T6963C_ROM_MODE_TEXT Mode: This option is only available when displaying
just a text. The Text Attribute values are stored in the graphic area of display
memory.
For more details see the T6963C datasheet.

Require Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.


s

Exampl SPI_T6963C_write_text("Glcd LIBRARY DEMO, WELCOME !", 0, 0, SPI_T6963C_ROM_MODE_XOR);


e

SPI_T6963C_Write_Text_Adv

Prototype void SPI_T6963C_Write_Text_Adv(unsigned char *text, unsigned


int x, unsigned int y);

Description Writes text in the current text panel of Glcd at coordinates (x, y).

Parameters  str: text to be written


 x: text position on x-axis
 y: text position on y-axis

Returns Nothing.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_Write_Text_Adv("Glcd LIBRARY DEMO, WELCOME !", 0, 0);

Notes None.

SPI_T6963C_Write_Const_Text_Adv

Prototype void SPI_T6963C_Write_Const_Text_Adv(const far char *text, unsigned


int x, unsigned int y);

www.raguvaran.puzl.com
Description Writes text located in the program memory on the glcd at coordinates (x, y).

Parameters  str: text to be written


 x: text position on x-axis
 y: text position on y-axis

Returns Nothing.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example const char ctext[] = "mikroElektronika";


...
SPI_T6963C_Write_Const_Text_Adv(ctext, 0, 0,);

Notes None.

SPI_T6963C_line

Prototype void SPI_T6963C_line(int x0, int y0, int x1, int y1, unsigned
char pcolor);

Returns Nothing.

Description Draws a line from (x0, y0) to (x1, y1).

Parameters :

 x0: x coordinate of the line start


 y0: y coordinate of the line end
 x1: x coordinate of the line start
 y1: y coordinate of the line end
 pcolor: color parameter. Valid
values: SPI_T6963C_BLACK and SPI_T6963C_WHITE

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_line(0, 0, 239, 127, SPI_T6963C_WHITE);

SPI_T6963C_rectangle

Prototype void SPI_T6963C_rectangle(int x0, int y0, int x1, int y1, unsigned
char pcolor);

Returns Nothing.

www.raguvaran.puzl.com
Description Draws a rectangle on Glcd.

Parameters :

 x0: x coordinate of the upper left rectangle corner


 y0: y coordinate of the upper left rectangle corner
 x1: x coordinate of the lower right rectangle corner
 y1: y coordinate of the lower right rectangle corner
 pcolor: color parameter. Valid
values: SPI_T6963C_BLACK and SPI_T6963C_WHITE

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_rectangle(20, 20, 219, 107, SPI_T6963C_WHITE);

SPI_T6963C_rectangle_round_edges

Prototyp void SPI_T6963C_rectangle_round_edges(int x0, int y0, int x1, int y1, int ro
e und_radius, unsigned char pcolor);

Returns Nothing.

Descripti Draws a rounded edge rectangle on Glcd.


on
Parameters :

 x0: x coordinate of the upper left rectangle corner


 y0: y coordinate of the upper left rectangle corner
 x1: x coordinate of the lower right rectangle corner
 y1: y coordinate of the lower right rectangle corner
 round_radius: radius of the rounded edge.
 pcolor: color parameter. Valid
values: SPI_T6963C_BLACK and SPI_T6963C_WHITE

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_rectangle_round_edges(20, 20, 219, 107, 12, SPI_T6963C_WHITE);

SPI_T6963C_rectangle_round_edges_fill

Prototy void SPI_T6963C_rectangle_round_edges_fill(int x0, int y0, int x1, int y1, i
pe nt round_radius, unsigned char pcolor);

Returns Nothing.

Descript Draws a filled rounded edge rectangle on Glcd.


ion

www.raguvaran.puzl.com
Parameters :

 x0: x coordinate of the upper left rectangle corner


 y0: y coordinate of the upper left rectangle corner
 x1: x coordinate of the lower right rectangle corner
 y1: y coordinate of the lower right rectangle corner
 round_radius: radius of the rounded edge
 pcolor: color parameter. Valid
values: SPI_T6963C_BLACK and SPI_T6963C_WHITE

Require Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.


s

Example SPI_T6963C_rectangle_round_edges_fill(20, 20, 219, 107, 12, SPI_T6963C_WHITE);

SPI_T6963C_box

Prototype void SPI_T6963C_box(int x0, int y0, int x1, int y1, unsigned
char pcolor);

Returns Nothing.

Description Draws a box on the Glcd

Parameters :

 x0: x coordinate of the upper left box corner


 y0: y coordinate of the upper left box corner
 x1: x coordinate of the lower right box corner
 y1: y coordinate of the lower right box corner
 pcolor: color parameter. Valid
values: SPI_T6963C_BLACK and SPI_T6963C_WHITE

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_box(0, 119, 239, 127, SPI_T6963C_WHITE);

SPI_T6963C_circle

Prototype void SPI_T6963C_circle(int x, int y, long r, unsigned char pcolor);

Returns Nothing.

Description Draws a circle on the Glcd.

Parameters :

www.raguvaran.puzl.com
 x: x coordinate of the circle center
 y: y coordinate of the circle center
 r: radius size
 pcolor: color parameter. Valid
values: SPI_T6963C_BLACK and SPI_T6963C_WHITE

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_circle(120, 64, 110, SPI_T6963C_WHITE);

SPI_T6963C_circle_fill

Prototype void SPI_T6963C_circle_fill(int x, int y, long r, unsigned char pcolor);

Returns Nothing.

Description Draws a filled circle on the Glcd.

Parameters :

 x: x coordinate of the circle center


 y: y coordinate of the circle center
 r: radius size
 pcolor: color parameter. Valid
values: SPI_T6963C_BLACK and SPI_T6963C_WHITE

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_circle_fill(120, 64, 110, SPI_T6963C_WHITE);

SPI_T6963C_image

Prototype void SPI_T6963C_image(const code char *pic);

Returns Nothing.

Description Displays bitmap on Glcd.

Parameters :

 image: image to be displayed. Bitmap array is located in code memory.


Use the integrated Glcd Bitmap Editor (menu option Tools › Glcd Bitmap Editor) to
convert image to a constant array suitable for displaying on Glcd.

Note : Image dimension must match the display dimension.

www.raguvaran.puzl.com
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_image(my_image);

SPI_T6963C_Ext_Image

Prototype void SPI_T6963C_Ext_Image(unsigned long image);

Description Displays a bitmap from an external resource.

Parameters  pic: image to be displayed. This parameter represents the address in the
exteral resource from where the image data begins.

Returns Nothing.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_Ext_image(153608);

Notes Image dimension must match the display dimension.

Use the integrated Glcd Bitmap Editor (menu option Tools › Glcd Bitmap Editor) to
convert image to a constant array suitable for displaying on Glcd.

SPI_T6963C_PartialImage

Prototype void SPI_T6963C_PartialImage(unsigned int x_left, unsigned


int y_top, unsigned int width, unsigned int height, unsigned
int picture_width, unsigned int picture_height, code const unsigned
short * image);

Returns Nothing.

Description Displays a partial area of the image on a desired location.

Parameters :

 x_left: x coordinate of the desired location (upper left coordinate).


 y_top: y coordinate of the desired location (upper left coordinate).
 width: desired image width.
 height: desired image height.
 picture_width: width of the original image.
 picture_height: height of the original image.
 image: image to be displayed. Bitmap array is located in code memory.
Use the integrated Glcd Bitmap Editor (menu option Tools › Glcd Bitmap Editor) to
convert image to a constant array suitable for displaying on Glcd.

www.raguvaran.puzl.com
Note : Image dimension must match the display dimension.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example // Draws a 10x15 part of the image starting from the upper left corner on the
coordinate (10,12). Original image size is 16x32.
SPI_T6963C_PartialImage(10, 12, 10, 15, 16, 32, image);

SPI_T6963C_Ext_PartialImage

Prototype void SPI_T6963C_Ext_PartialImage(unsigned int x_left, unsigned


int y_top, unsigned int width, unsigned int height, unsigned
int picture_width,unsigned int picture_height, unsigned long image);

Description Displays a partial area of the image on a desired location.

Parameters  x_left: x coordinate of the desired location (upper left coordinate).


 y_top: y coordinate of the desired location (upper left coordinate).
 width: desired image width.
 height: desired image height.
 picture_width: width of the original image.
 picture_height: height of the original image.
 image: image to be displayed. This parameter represents the address in
the exteral resource from where the image data begins.

Returns Nothing.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_Ext_PartialImage(10, 12, 10, 15, 16, 32, 0);

Notes Image dimension must match the display dimension.

Use the integrated Glcd Bitmap Editor (menu option Tools › Glcd Bitmap Editor) to
convert image to a constant array suitable for displaying on Glcd.

SPI_T6963C_sprite

Prototype void SPI_T6963C_sprite(unsigned char px, unsigned char py, const code
char *pic, unsigned char sx, unsigned char sy);

Returns Nothing.

Description Fills graphic rectangle area (px, py) to (px+sx, py+sy) with custom size picture.

www.raguvaran.puzl.com
Parameters :

 px: x coordinate of the upper left picture corner. Valid values: multiples of
the font width
 py: y coordinate of the upper left picture corner
 pic: picture to be displayed
 sx: picture width. Valid values: multiples of the font width
 sy: picture height

Note : If px and sx parameters are not multiples of the font width they will be
scaled to the nearest lower number that is a multiple of the font width.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_sprite(76, 4, einstein, 88, 119); // draw a sprite

SPI_T6963C_set_cursor

Prototype void SPI_T6963C_set_cursor(unsigned char x, unsigned char y);

Returns Nothing.

Description Sets cursor to row x and column y.

Parameters :

 x: cursor position row number


 y: cursor position column number

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_set_cursor(cposx, cposy);

SPI_T6963C_clearbit

Prototype void SPI_T6963C_clearBit(char b);

Returns Nothing.

Description Clears control port bit(s).

Parameters :

 b: bit mask. The function will clear bit x on control port if bit x in bit mask
is set to 1.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

www.raguvaran.puzl.com
Example // clear bits 0 and 1 on control port
SPI_T6963C_clearBit(0x03);

SPI_T6963C_setBit

Prototype void SPI_T6963C_setBit(char b);

Returns Nothing.

Description Sets control port bit(s).

Parameters :

 b: bit mask. The function will set bit x on control port if bit x in bit mask is
set to 1.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example // set bits 0 and 1 on control port


SPI_T6963C_setBit(0x03);

SPI_T6963C_negBit

Prototype void SPI_T6963C_negBit(char b);

Returns Nothing.

Description Negates control port bit(s).

Parameters :

 b: bit mask. The function will negate bit x on control port if bit x in bit
mask is set to 1.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example // negate bits 0 and 1 on control port


SPI_T6963C_negBit(0x03);

SPI_T6963C_DisplayGrPanel

Prototype void SPI_T6963C_displayGrPanel(char n);

Returns Nothing.

www.raguvaran.puzl.com
Description Display selected graphic panel.

Parameters :

 n: graphic panel number. Valid values: 0 and 1.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example // display graphic panel 1


SPI_T6963C_displayGrPanel(1);

SPI_T6963C_displayTxtPanel

Prototype void SPI_T6963C_displayTxtPanel(char n);

Returns Nothing.

Description Display selected text panel.

Parameters :

 n: text panel number. Valid values: 0 and 1.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example // display text panel 1


SPI_T6963C_displayTxtPanel(1);

SPI_T6963C_setGrPanel

Prototype void SPI_T6963C_setGrPanel(char n);

Returns Nothing.

Description Compute start address for selected graphic panel and set appropriate internal pointers.
All subsequent graphic operations will be preformed at this graphic panel.

Parameters :

 n: graphic panel number. Valid values: 0 and 1.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example // set graphic panel 1 as current graphic panel.


SPI_T6963C_setGrPanel(1);

SPI_T6963C_setTxtPanel

www.raguvaran.puzl.com
Prototype void SPI_T6963C_setTxtPanel(char n);

Returns Nothing.

Description Compute start address for selected text panel and set appropriate internal pointers. All
subsequent text operations will be preformed at this text panel.

Parameters :

 n: text panel number. Valid values: 0 and 1.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example // set text panel 1 as current text panel.


SPI_T6963C_setTxtPanel(1);

SPI_T6963C_panelFill

Prototype void SPI_T6963C_panelFill(unsigned char v);

Returns Nothing.

Description Fill current panel in full (graphic+text) with appropriate value (0 to clear).

Parameters :

 v: value to fill panel with.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example clear current panel


SPI_T6963C_panelFill(0);

SPI_T6963C_grFill

Prototype void SPI_T6963C_grFill(unsigned char v);

Returns Nothing.

Description Fill current graphic panel with appropriate value (0 to clear).

Parameters :

 v: value to fill graphic panel with.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

www.raguvaran.puzl.com
Example // clear current graphic panel
SPI_T6963C_grFill(0);

SPI_T6963C_txtFill

Prototype void SPI_T6963C_txtFill(unsigned char v);

Returns Nothing.

Description Fill current text panel with appropriate value (0 to clear).

Parameters :

 v: this value increased by 32 will be used to fill text panel.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example // clear current text panel


SPI_T6963C_txtFill(0);

SPI_T6963C_cursor_height

Prototype void SPI_T6963C_cursor_height(unsigned char n);

Returns Nothing.

Description Set cursor size.

Parameters :

 n: cursor height. Valid values: 0..7.

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example SPI_T6963C_cursor_height(7);

SPI_T6963C_graphics

Prototype void SPI_T6963C_graphics(char n);

Returns Nothing.

Description Enable/disable graphic displaying.

www.raguvaran.puzl.com
Parameters :

 n: graphic enable/disable parameter. Valid values: 0 (disable graphic


dispaying) and 1 (enable graphic displaying).

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example // enable graphic displaying


SPI_T6963C_graphics(1);

SPI_T6963C_text

Prototype void SPI_T6963C_text(char n);

Returns Nothing.

Description Enable/disable text displaying.

Parameters :

 n: text enable/disable parameter. Valid values: 0 (disable text dispaying)


and 1 (enable text displaying).

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example // enable text displaying


SPI_T6963C_text(1);

SPI_T6963C_cursor

Prototype void SPI_T6963C_cursor(char n);

Returns Nothing.

Description Set cursor on/off.

Parameters :

 n: on/off parameter. Valid values: 0 (set cursor off) and 1 (set cursor on).

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example // set cursor on


SPI_T6963C_cursor(1);

www.raguvaran.puzl.com
SPI_T6963C_cursor_blink

Prototype void SPI_T6963C_cursor_blink(char n);

Returns Nothing.

Description Enable/disable cursor blinking.

Parameters :

 n: cursor blinking enable/disable parameter. Valid values: 0 (disable


cursor blinking) and 1 (enable cursor blinking).

Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.

Example // enable cursor blinking


SPI_T6963C_cursor_blink(1);

Library Example
The following drawing demo tests advanced routines of the SPI T6963C Glcd library. Hardware
configurations in this example are made for the T6963C 240x128 display, EasyPIC6 board and 16F887.

Copy Code To Clipboard

#include "__SPIT6963C.h"

/*
* bitmap pictures stored in ROM
*/
const code char mikroE_240x64_bmp[]; // PIC16F887 can't store larger picture(240x128) in ROM
const code char einstein[];

// Port Expander module connections


sbit SPExpanderRST at RC0_bit;
sbit SPExpanderCS at RC1_bit;
sbit SPExpanderRST_Direction at TRISC0_bit;
sbit SPExpanderCS_Direction at TRISC1_bit;
// End Port Expander module connections

void main() {
char txt1[] = " EINSTEIN WOULD HAVE LIKED mE";
char txt[] = " GLCD LIBRARY DEMO, WELCOME !";

unsigned char panel; // Current panel


unsigned int i; // General purpose register
unsigned char curs; // Cursor visibility
unsigned int cposx, cposy; // Cursor x-y position

#define COMPLETE_EXAMPLE // comment this line to make simpler/smaller example


ANSEL = 0; // Configure AN pins as digital I/O
ANSELH = 0;
C1ON_bit = 0; // Disable comparators

www.raguvaran.puzl.com
C2ON_bit = 0;

TRISB0_bit = 1; // Set RB0 as input


TRISB1_bit = 1; // Set RB1 as input
TRISB2_bit = 1; // Set RB2 as input
TRISB3_bit = 1; // Set RB3 as input
TRISB4_bit = 1; // Set RB4 as input

// If Port Expander Library uses SPI1 module


SPI1_Init(); // Initialize SPI module used with PortExpander

// // If Port Expander Library uses SPI2 module


// SPI2_Init(); // Initialize SPI module used with PortExpander

/*
* init display for 240 pixel width and 128 pixel height
* 8 bits character width
* data bus on MCP23S17 portB
* control bus on MCP23S17 portA
* bit 2 is !WR
* bit 1 is !RD
* bit 0 is !CD
* bit 4 is RST
* chip enable, reverse on, 8x8 font internaly set in library
*/

SPI_T6963C_Config(240, 128, 8, 0, 2, 1, 0, 4);


Delay_ms(1000);

/*
* Enable both graphics and text display at the same time
*/
SPI_T6963C_graphics(1);
SPI_T6963C_text(1);

panel = 0;
i = 0;
curs = 0;
cposx = cposy = 0;
/*
* Text messages
*/
SPI_T6963C_write_text(txt, 0, 0, SPI_T6963C_ROM_MODE_XOR);
SPI_T6963C_write_text(txt1, 0, 15, SPI_T6963C_ROM_MODE_XOR);

/*
* Cursor
*/
SPI_T6963C_cursor_height(8); // 8 pixel height
SPI_T6963C_set_cursor(0, 0); // move cursor to top left
SPI_T6963C_cursor(0); // cursor off

/*
* Draw rectangles
*/
SPI_T6963C_rectangle(0, 0, 239, 127, SPI_T6963C_WHITE);
SPI_T6963C_rectangle(20, 20, 219, 107, SPI_T6963C_WHITE);
SPI_T6963C_rectangle(40, 40, 199, 87, SPI_T6963C_WHITE);
SPI_T6963C_rectangle(60, 60, 179, 67, SPI_T6963C_WHITE);

/*
* Draw a cross
*/
SPI_T6963C_line(0, 0, 239, 127, SPI_T6963C_WHITE);
SPI_T6963C_line(0, 127, 239, 0, SPI_T6963C_WHITE);

/*

www.raguvaran.puzl.com
* Draw solid boxes
*/
SPI_T6963C_box(0, 0, 239, 8, SPI_T6963C_WHITE);
SPI_T6963C_box(0, 119, 239, 127, SPI_T6963C_WHITE);

#ifdef COMPLETE_EXAMPLE
/*
* Draw circles
*/
SPI_T6963C_circle(120, 64, 10, SPI_T6963C_WHITE);
SPI_T6963C_circle(120, 64, 30, SPI_T6963C_WHITE);
SPI_T6963C_circle(120, 64, 50, SPI_T6963C_WHITE);
SPI_T6963C_circle(120, 64, 70, SPI_T6963C_WHITE);
SPI_T6963C_circle(120, 64, 90, SPI_T6963C_WHITE);
SPI_T6963C_circle(120, 64, 110, SPI_T6963C_WHITE);
SPI_T6963C_circle(120, 64, 130, SPI_T6963C_WHITE);

SPI_T6963C_sprite(76, 4, einstein, 88, 119); // Draw a sprite

SPI_T6963C_setGrPanel(1); // Select other graphic panel

SPI_T6963C_sprite(0, 0, mikroE_240x64_bmp, 240, 64);// 240x128 can't be stored in most of


PIC16 MCUs
SPI_T6963C_sprite(0, 64, mikroE_240x64_bmp, 240, 64);// it is replaced with smaller picture
240x64
// Smaller picture is drawn two times
#endif

for(;;) { // Endless loop


/*
* If RB0 is pressed, display only graphic panel
*/
if(RB0_bit) {
SPI_T6963C_graphics(1);
SPI_T6963C_text(0);
Delay_ms(300);
}
#ifdef COMPLETE_EXAMPLE
/*
* If RB1 is pressed, toggle the display between graphic panel 0 and graphic panel 1
*/
else if(RB1_bit) {
panel++;
panel &= 1;
SPI_T6963C_displayGrPanel(panel);
Delay_ms(300);
}
#endif
/*
* If RB2 is pressed, display only text panel
*/
else if(RB2_bit) {
SPI_T6963C_graphics(0);
SPI_T6963C_text(1);
Delay_ms(300);
}

/*
* If RB3 is pressed, display text and graphic panels
*/
else if(RB3_bit) {
SPI_T6963C_graphics(1);
SPI_T6963C_text(1);
Delay_ms(300);
}
/*
* If RB4 is pressed, change cursor

www.raguvaran.puzl.com
*/
else if(RB4_bit) {
curs++;
if(curs == 3) curs = 0;
switch(curs) {
case 0:
// no cursor
SPI_T6963C_cursor(0);
break;
case 1:
// blinking cursor
SPI_T6963C_cursor(1);
SPI_T6963C_cursor_blink(1);
break;
case 2:
// non blinking cursor
SPI_T6963C_cursor(1);
SPI_T6963C_cursor_blink(0);
break;
}
Delay_ms(300);
}

/*
* Move cursor, even if not visible
*/
cposx++;
if(cposx == SPI_T6963C_txtCols) {
cposx = 0;
cposy++;
if(cposy == SPI_T6963C_grHeight / SPI_T6963C_CHARACTER_HEIGHT) {
cposy = 0;
}
}
SPI_T6963C_set_cursor(cposx, cposy);

Delay_ms(100);
}
}

HW Connection

www.raguvaran.puzl.com
SPI T6963C Glcd HW connection

T6963C Graphic Lcd Library


The mikroC PRO for PIC provides a library for working with Glcds based on TOSHIBA T6963C controller.
The Toshiba T6963C is a very popular Lcd controller for the use in small graphics modules. It is capable
of controlling displays with a resolution up to 240x128. Because of its low power and small outline it is
most suitable for mobile applications such as PDAs, MP3 players or mobile measurement equipment.

www.raguvaran.puzl.com
Although small, this contoller has a capability of displaying and merging text and graphics and it
manages all the interfacing signals to the displays Row and Column drivers.

For creating a custom set of Glcd images use Glcd Bitmap Editor Tool.
Important :
 ChipEnable(CE), FontSelect(FS) and Reverse(MD) have to be set to appropriate levels by
the user outside of the T6963C_Init() function. See the Library Example code at the bottom
of this page.
 Glcd size based initialization routines can be found in setup library files located in the Uses
folder.
 The user must make sure that used MCU has appropriate ports and pins. If this is not the
case the user should adjust initialization routines.
 PIC16 family of MCUs does not support working with external resources.

Some mikroElektronika's adapter boards have pinout different from T6369C datasheets. Appropriate
relations between these labels are given in the table below :
Adapter Board T6369C datasheet
RS C/D
R/W /RD
E /WR

Library Dependency Tree

External dependencies of T6963C Graphic Lcd Library


The following variables must be
defined in all projects using T6963C Description : Example :
Graphic Lcd library:
extern sfr T6963C Data char T6963C_dataPort at PORTD;
char T6963C_dataPort; Port.
extern sfr sbit T6963C_ctrlwr; Write signal. sbit T6963C_ctrlwr at RC2_bit;

extern sfr sbit T6963C_ctrlrd; Read signal. sbit T6963C_ctrlrd at RC1_bit;

extern sfr sbit T6963C_ctrlcd;


Command/Data sbit T6963C_ctrlcd at RC0_bit;
signal.
extern sfr
Reset signal. sbit T6963C_ctrlrst at RC4_bit;
sbit T6963C_ctrlrst;

extern sfr Direction of the sbit T6963C_ctrlwr_Direction atTRISC2_bit;


sbit T6963C_ctrlwr_Direction; Write pin.
extern sfr Direction of the sbit T6963C_ctrlrd_Direction atTRISC1_bit;
sbit T6963C_ctrlrd_Direction; Read pin.
Direction of the
extern sfr
Command/Data sbit T6963C_ctrlcd_Direction atTRISC0_bit;
sbit T6963C_ctrlcd_Direction;
pin.
extern sfr Direction of the sbit T6963C_ctrlrst_Direction atTRISC4_bit;
sbit T6963C_ctrlrst_Direction; Reset pin.

www.raguvaran.puzl.com
Library Routines
 T6963C_init
 T6963C_writeData
 T6963C_writeCommand
 T6963C_setPtr
 T6963C_Set_Ext_Buffer
 T6963C_waitReady
 T6963C_fill
 T6963C_dot
 T6963C_Set_Font_Adv
 T6963C_Set_Font_Ext_Adv
 T6963C_write_char
 T6963C_Write_Char_Adv
 T6963C_write_text
 T6963C_Write_Text_Adv
 T6963C_Write_Const_Text_Adv
 T6963C_line
 T6963C_rectangle
 T6963C_rectangle_round_edges
 T6963C_rectangle_round_edges_fill
 T6963C_box
 T6963C_circle
 T6963C_circle_fill
 T6963C_image
 T6963C_Ext_Image
 T6963C_PartialImage
 T6963C_Ext_PartialImage
 T6963C_sprite
 T6963C_set_cursor
The following low level library routines are implemented as macros. These macros can be found in
the __T6963C.h header file which is located in the T6963C example projects folders.
 T6963C_clearBit
 T6963C_setBit
 T6963C_negBit
 T6963C_displayGrPanel
 T6963C_displayTxtPanel
 T6963C_setGrPanel
 T6963C_setTxtPanel
 T6963C_panelFill
 T6963C_grFill
 T6963C_txtFill
 T6963C_cursor_height
 T6963C_graphics
 T6963C_text
 T6963C_cursor
 T6963C_cursor_blink

T6963C_init

Prototype void T6963C_init(unsigned int width, unsigned char height, unsigned


char fntW);

www.raguvaran.puzl.com
Returns Nothing.

Description Initializes T6963C Graphic Lcd controller.

Parameters :

 width: width of the Glcd panel


 height: height of the Glcd panel
 fntW: font width
Display RAM organization:
The library cuts the RAM into panels : a complete panel is one graphics panel followed by a text panel (see
schematic below).
schematic:
+---------------------+ /\
+ GRAPHICS PANEL #0 + |
+ + |
+ + |
+ + |
+---------------------+ | PANEL 0
+ TEXT PANEL #0 + |
+ + \/
+---------------------+ /\
+ GRAPHICS PANEL #1 + |
+ + |
+ + |
+ + |
+---------------------+ | PANEL 1
+ TEXT PANEL #1 + |
+ + |
+---------------------+ \/

Requires Global variables :

 T6963C_dataPort: Data Port


 T6963C_ctrlwr: Write signal pin
 T6963C_ctrlrd: Read signal pin
 T6963C_ctrlcd: Command/Data signal pin
 T6963C_ctrlrst: Reset signal pin

 T6963C_ctrlwr_Direction: Direction of Write signal pin


 T6963C_ctrlrd_Direction: Direction of Read signal pin
 T6963C_ctrlcd_Direction: Direction of Command/Data signal pin
 T6963C_ctrlrst_Direction: Direction of Reset signal pin
must be defined before using this function.

Example // T6963C module connections


char T6963C_dataPort at PORTD;
sbit T6963C_ctrlwr at RC2_bit;
sbit T6963C_ctrlrd at RC1_bit;
sbit T6963C_ctrlcd at RC0_bit;
sbit T6963C_ctrlrst at RC4_bit;
sbit T6963C_ctrlwr_Direction at TRISC2_bit;
sbit T6963C_ctrlrd_Direction at TRISC1_bit;
sbit T6963C_ctrlcd_Direction at TRISC0_bit;
sbit T6963C_ctrlrst_Direction at TRISC4_bit;
// End of T6963C module connections

// Signals not used by library, they are set in main function

www.raguvaran.puzl.com
sbit T6963C_ctrlce at RC3_bit; // CE signal
sbit T6963C_ctrlfs at RC6_bit; // FS signal
sbit T6963C_ctrlmd at RC5_bit; // MD signal
sbit T6963C_ctrlce_Direction at TRISC3_bit; // CE signal direction
sbit T6963C_ctrlfs_Direction at TRISC6_bit; // FS signal direction
sbit T6963C_ctrlmd_Direction at TRISC5_bit; // MD signal direction
// End T6963C module connections

...
// init display for 240 pixel width, 128 pixel height and 8 bits character width
T6963C_init(240, 128, 8);

T6963C_writeData

Prototype void T6963C_writeData(unsigned char mydata);

Returns Nothing.

Description Writes data to T6963C controller.

Parameters :

 mydata: data to be written

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_writeData(AddrL);

T6963C_writeCommand

Prototype void T6963C_writeCommand(unsigned char mydata);

Returns Nothing.

Description Writes command to T6963C controller.

Parameters :

 mydata: command to be written

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_writeCommand(T6963C_CURSOR_POINTER_SET);

T6963C_setPtr

Prototype void T6963C_setPtr(unsigned int p, unsigned char c);

www.raguvaran.puzl.com
Returns Nothing.

Description Sets the memory pointer p for command c.

Parameters :

 p: address where command should be written


 c: command to be written

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_setPtr(T6963C_grHomeAddr + start, T6963C_ADDRESS_POINTER_SET);

T6963C_Set_Ext_Buffer

Prototype void T6963C_Set_Ext_Buffer(char* (*getExtDataPtr)(unsigned


long offset, unsigned int count, unsigned int *num));

Returns Nothing.

Description Function sets pointer to the user function which manipulates the external resource.

Parameters :

 offset - offset from the beginning of the resource from where the data is requested.
 count - requested number of bytes.
 num - variable for holding the returned number ob byte (less or equal to the number of acqired
bytes).

Requires Glcd module needs to be initialized. See the T6963C_Init routine.

Example char* ReadExternalBuffer(unsigned long offset, unsigned int count, unsigned int
*num){
unsigned long start_sector;
unsigned int pos;

start_sector = Mmc_Get_File_Write_Sector() + offset/512;


pos = (unsigned long)offset%512;

if(start_sector == currentSector+1){
Mmc_Multi_Read_Buffer(EXT_BUFFER);
currentSector = start_sector;
}else
if(start_sector != currentSector){
Mmc_Multi_Read_Stop();
Mmc_Multi_Read_Start(start_sector);
Mmc_Multi_Read_Buffer(EXT_BUFFER);
currentSector = start_sector;
}

if(count>512-pos){
*num = 512-pos;
}
else

www.raguvaran.puzl.com
*num = count;

return EXT_BUFFER+pos;
}

T6963C_Set_Ext_Buffer(ReadExternalBuffer);

T6963C_waitReady

Prototype void T6963C_waitReady(void);

Returns Nothing.

Description Pools the status byte, and loops until Toshiba Glcd module is ready.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_waitReady();

T6963C_fill

Prototype void T6963C_fill(unsigned char v, unsigned int start, unsigned int len);

Returns Nothing.

Description Fills controller memory block with given byte.

Parameters :

 v: byte to be written
 start: starting address of the memory block
 len: length of the memory block in bytes

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_fill(0x33,0x00FF,0x000F);

T6963C_dot

Prototype void T6963C_dot(int x, int y, unsigned char color);

Returns Nothing.

Description Draws a dot in the current graphic panel of Glcd at coordinates (x, y).

www.raguvaran.puzl.com
Parameters :

 x: dot position on x-axis


 y: dot position on y-axis
 color: color parameter. Valid values: T6963C_BLACK and T6963C_WHITE

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_dot(x0, y0, T6963C_WHITE);

T6963C_Set_Font_Adv

Prototype void T6963C_Set_Font_Adv(const far char *activeFont, unsigned


char font_color, char font_orientation);

Description Sets font that will be used with T6963C_Write_Char_Adv and T6963C_Write_Text_Adv routines.

Parameters  activeFont: font to be set. Needs to be formatted as an array of char.


 font_color: sets font color.
 font_orientation: sets font orientation.

Returns Nothing.

Requires Glcd needs to be initialized, see T6963C_Init routine.

Example T6963C_Set_Font_Adv(&myfont, 1, 0,);

Notes None.

T6963C_Set_Ext_Font_Adv

Prototype void T6963C_Set_Ext_Font_Adv(unsigned long activeFont, unsigned


int font_color, char font_orientation);

Description Sets font that will be used with T6963C_Write_Char_Adv and T6963C_Write_Text_Adv routines. Font is
located in an external resource.

Parameters  activeFont: font to be set. This parameter represents the address in the exteral resource from
where the font data begins.
 font_color: sets font color.
 font_orientation: sets font orientation.

Returns Nothing.

Requires Glcd needs to be initialized, see T6963C_Init routine.

Example T6963C_Set_Ext_Font_Adv(173296, 5, 7, 32);

www.raguvaran.puzl.com
Notes None.

T6963C_write_char

Prototype void T6963C_write_char(unsigned char c, unsigned char x, unsigned


char y, unsigned char mode);

Returns Nothing.

Descriptio Writes a char in the current text panel of Glcd at coordinates (x, y).
n
Parameters :

 c: char to be written
 x: char position on x-axis
 y: char position on y-axis
 mode: mode parameter. Valid
values: T6963C_ROM_MODE_OR, T6963C_ROM_MODE_XOR, T6963C_ROM_MODE_AND and T6963C_
ROM_MODE_TEXT
Mode parameter explanation:

 T6963C_ROM_MODE_OR Mode: In the OR-Mode, text and graphics can be displayed and the data
is logically "OR-ed". This is the most common way of combining text and graphics for example
labels on buttons.
 T6963C_ROM_MODE_XOR Mode: In this mode, the text and graphics data are combined via the
logical "exclusive OR". This can be useful to display text in the negative mode, i.e. white text on
black background.
 T6963C_ROM_MODE_AND Mode: The text and graphic data shown on display are combined via the
logical "AND function".
 T6963C_ROM_MODE_TEXT Mode: This option is only available when displaying just a text. The
Text Attribute values are stored in the graphic area of display memory.
For more details see the T6963C datasheet.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_write_char('A',22,23,T6963C_ROM_MODE_AND);

T6963C_write_char_adv

Prototype void T6963C_write_char_adv(unsigned char c, unsigned char x, unsigned


char y);

Description Writes a char in the current text panel of Glcd at coordinates (x, y).

Parameters  c: char to be written


 x: char position on x-axis
 y: char position on y-axis

www.raguvaran.puzl.com
Returns Nothing.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_write_char_adv('A',22,23);

Notes None.

T6963C_write_text

Prototype void T6963C_write_text(unsigned char *str, unsigned char x, unsigned


char y, unsigned char mode);

Returns Nothing.

Descriptio Writes text in the current text panel of Glcd at coordinates (x, y).
n
Parameters :

 str: text to be written


 x: text position on x-axis
 y: text position on y-axis
 mode: mode parameter. Valid
values: T6963C_ROM_MODE_OR, T6963C_ROM_MODE_XOR, T6963C_ROM_MODE_AND and T6963C_
ROM_MODE_TEXT
Mode parameter explanation:

 T6963C_ROM_MODE_OR Mode: In the OR-Mode, text and graphics can be displayed and the data
is logically "OR-ed". This is the most common way of combining text and graphics for example
labels on buttons.
 T6963C_ROM_MODE_XOR Mode: In this mode, the text and graphics data are combined via the
logical "exclusive OR". This can be useful to display text in the negative mode, i.e. white text on
black background.
 T6963C_ROM_MODE_AND Mode: The text and graphic data shown on display are combined via the
logical "AND function".
 T6963C_ROM_MODE_TEXT Mode: This option is only available when displaying just a text. The
Text Attribute values are stored in the graphic area of display memory.
For more details see the T6963C datasheet.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_write_text(" Glcd LIBRARY DEMO, WELCOME !", 0, 0, T6963C_ROM_MODE_XOR);

T6963C_Write_Text_Adv

Prototype void T6963C_Write_Text_Adv(unsigned char *text, unsigned char x, unsigned


char y);

www.raguvaran.puzl.com
Description Writes text in the current text panel of Glcd at coordinates (x, y).

Parameters  str: text to be written


 x: text position on x-axis
 y: text position on y-axis

Returns Nothing.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_Write_Text_Adv("Glcd LIBRARY DEMO, WELCOME !", 0, 0);

Notes None.

T6963C_Write_Text_Const_Adv

Prototype void T6963C_Write_Text_Const_Adv(unsigned char *text, unsigned


char x, unsigned char y);

Description Writes text located in the program memory on the glcd at coordinates (x, y).

Parameters  str: text to be written


 x: text position on x-axis
 y: text position on y-axis

Returns Nothing.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example const char ctext[] = "mikroElektronika";


...
T6963C_Write_Const_Text_Adv(ctext, 0, 0,);

Notes None.

T6963C_line

Prototype void T6963C_line(int x0, int y0, int x1, int y1, unsigned char pcolor);

Returns Nothing.

www.raguvaran.puzl.com
Description Draws a line from (x0, y0) to (x1, y1).

Parameters :

 x0: x coordinate of the line start


 y0: y coordinate of the line end
 x1: x coordinate of the line start
 y1: y coordinate of the line end
 pcolor: color parameter. Valid values: T6963C_BLACK and T6963C_WHITE

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_line(0, 0, 239, 127, T6963C_WHITE);

T6963C_rectangle

Prototype void T6963C_rectangle(int x0, int y0, int x1, int y1, unsigned char pcolor);

Returns Nothing.

Description Draws a rectangle on Glcd.

Parameters :

 x0: x coordinate of the upper left rectangle corner


 y0: y coordinate of the upper left rectangle corner
 x1: x coordinate of the lower right rectangle corner
 y1: y coordinate of the lower right rectangle corner
 pcolor: color parameter. Valid values: T6963C_BLACK and T6963C_WHITE

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_rectangle(20, 20, 219, 107, T6963C_WHITE);

T6963C_rectangle_round_edges

Prototyp void T6963C_rectangle_round_edges(int x0, int y0, int x1, int y1, int round_r
e adius, unsigned char pcolor);

Returns Nothing.

Descripti Draws a rounded edge rectangle on Glcd.


on
Parameters :

 x0: x coordinate of the upper left rectangle corner


 y0: y coordinate of the upper left rectangle corner
 x1: x coordinate of the lower right rectangle corner

www.raguvaran.puzl.com
 y1: y coordinate of the lower right rectangle corner
 round_radius: radius of the rounded edge.
 pcolor: color parameter. Valid values: T6963C_BLACK and T6963C_WHITE

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_rectangle_round_edges(20, 20, 219, 107, 12, T6963C_WHITE);

T6963C_rectangle_round_edges_fill

Prototyp void T6963C_rectangle_round_edges_fill(int x0, int y0, int x1, int y1, int ro
e und_radius, unsigned char pcolor);

Returns Nothing.

Descripti Draws a filled rounded edge rectangle on Glcd.


on
Parameters :

 x0: x coordinate of the upper left rectangle corner


 y0: y coordinate of the upper left rectangle corner
 x1: x coordinate of the lower right rectangle corner
 y1: y coordinate of the lower right rectangle corner
 round_radius: radius of the rounded edge
 pcolor: color parameter. Valid values: T6963C_BLACK and T6963C_WHITE

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_rectangle_round_edges_fill(20, 20, 219, 107, 12, T6963C_WHITE);

T6963C_box

Prototype void T6963C_box(int x0, int y0, int x1, int y1, unsigned char pcolor);

Returns Nothing.

Description Draws a box on Glcd

Parameters :

 x0: x coordinate of the upper left box corner


 y0: y coordinate of the upper left box corner
 x1: x coordinate of the lower right box corner
 y1: y coordinate of the lower right box corner
 pcolor: color parameter. Valid values: T6963C_BLACK and T6963C_WHITE

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

www.raguvaran.puzl.com
Example T6963C_box(0, 119, 239, 127, T6963C_WHITE);

T6963C_circle

Prototype void T6963C_circle(int x, int y, long r, unsigned char pcolor);

Returns Nothing.

Description Draws a circle on Glcd.

Parameters :

 x: x coordinate of the circle center


 y: y coordinate of the circle center
 r: radius size
 pcolor: color parameter. Valid values: T6963C_BLACK and T6963C_WHITE

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_circle(120, 64, 110, T6963C_WHITE);

T6963C_circle_fill

Prototype void T6963C_circle_fill(int x, int y, long r, unsigned char pcolor);

Returns Nothing.

Description Draws a filled circle on Glcd.

Parameters :

 x: x coordinate of the circle center


 y: y coordinate of the circle center
 r: radius size
 pcolor: color parameter. Valid values: T6963C_BLACK and T6963C_WHITE

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_circle_fill(120, 64, 110, T6963C_WHITE);

T6963C_image

Prototype void T6963C_image(const code char *pic);

Returns Nothing.

www.raguvaran.puzl.com
Description Displays bitmap on Glcd.

Parameters :

 image: image to be displayed. Bitmap array is located in code memory.


Use the integrated Glcd Bitmap Editor (menu option Tools › Glcd Bitmap Editor) to convert image to a constant
array suitable for displaying on Glcd.

Note : Image dimension must match the display dimension.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_image(mc);

T6963C_Ext_Image

Prototype void T6963C_Ext_Image(unsigned long image);

Description Displays a bitmap from an external resource.

Parameters  pic: image to be displayed. This parameter represents the address in the exteral resource from
where the image data begins.

Returns Nothing.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_Ext_image(153608);

Notes Image dimension must match the display dimension.

Use the integrated Glcd Bitmap Editor (menu option Tools › Glcd Bitmap Editor) to convert image to a constant
array suitable for displaying on Glcd.

T6963C_PartialImage

Prototype void T6963C_PartialImage(unsigned int x_left, unsigned int y_top, unsigned


int width, unsigned int height, unsigned int picture_width, unsigned
intpicture_height, code const unsigned short * image);

Returns Nothing.

Description Displays a partial area of the image on a desired location.

Parameters :

 x_left: x coordinate of the desired location (upper left coordinate).

www.raguvaran.puzl.com
 y_top: y coordinate of the desired location (upper left coordinate).
 width: desired image width.
 height: desired image height.
 picture_width: width of the original image.
 picture_height: height of the original image.
 image: image to be displayed. Bitmap array is located in code memory.
Use the integrated Glcd Bitmap Editor (menu option Tools › Glcd Bitmap Editor) to convert image to a constant
array suitable for displaying on Glcd.

Note : Image dimension must match the display dimension.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example // Draws a 10x15 part of the image starting from the upper left corner on the
coordinate (10,12). Original image size is 16x32.
T6963C_PartialImage(10, 12, 10, 15, 16, 32, image);

T6963C_Ext_PartialImage

Prototype void T6963C_Ext_PartialImage(unsigned int x_left, unsigned


int y_top, unsigned int width, unsigned int height, unsigned
int picture_width, unsigned int picture_height, unsigned long image);

Description Displays a partial area of the image on a desired location.

Parameters  x_left: x coordinate of the desired location (upper left coordinate).


 y_top: y coordinate of the desired location (upper left coordinate).
 width: desired image width.
 height: desired image height.
 picture_width: width of the original image.
 picture_height: height of the original image.
 image: image to be displayed. This parameter represents the address in the exteral resource from
where the image data begins.

Returns Nothing.

Requires Toshiba Glcd module needs to be initialized. See T6963C_init routine.

Example T6963C_Ext_PartialImage(10, 12, 10, 15, 16, 32, 0);

Notes Image dimension must match the display dimension.

Use the integrated Glcd Bitmap Editor (menu option Tools › Glcd Bitmap Editor) to convert image to a constant
array suitable for displaying on Glcd.

T6963C_sprite

www.raguvaran.puzl.com
Prototype void T6963C_sprite(unsigned char px, unsigned char py, const code
char *pic, unsigned char sx, unsigned char sy);

Returns Nothing.

Description Fills graphic rectangle area (px, py) to (px+sx, py+sy) with custom size picture.

Parameters :

 px: x coordinate of the upper left picture corner. Valid values: multiples of the font width
 py: y coordinate of the upper left picture corner
 pic: picture to be displayed
 sx: picture width. Valid values: multiples of the font width
 sy: picture height

Note : If px and sx parameters are not multiples of the font width they will be scaled to the nearest lower
number that is a multiple of the font width.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_sprite(76, 4, einstein, 88, 119); // draw a sprite

T6963C_set_cursor

Prototype void T6963C_set_cursor(unsigned char x, unsigned char y);

Returns Nothing.

Description Sets cursor to row x and column y.

Parameters :

 x: cursor position row number


 y: cursor position column number

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_set_cursor(cposx, cposy);

T6963C_clearBit

Prototype void T6963C_clearBit(char b);

Returns Nothing.

Description Clears control port bit(s).

www.raguvaran.puzl.com
Parameters :

 b: bit mask. The function will clear bit x on control port if bit x in bit mask is set to 1.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example // clear bits 0 and 1 on control port


T6963C_clearBit(0x03);

T6963C_setBit

Prototype void T6963C_setBit(char b);

Returns Nothing.

Description Sets control port bit(s).

Parameters :

 b: bit mask. The function will set bit x on control port if bit x in bit mask is set to 1.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example // set bits 0 and 1 on control port


T6963C_setBit(0x03);

T6963C_negBit

Prototype void T6963C_negBit(char b);

Returns Nothing.

Description Negates control port bit(s).

Parameters :

 b: bit mask. The function will negate bit x on control port if bit x in bit mask is set to 1.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example // negate bits 0 and 1 on control port


T6963C_negBit(0x03);

T6963C_displayGrPanel

www.raguvaran.puzl.com
Prototype void T6963C_displayGrPanel(char n);

Returns Nothing.

Description Display selected graphic panel.

Parameters :

 n: graphic panel number. Valid values: 0 and 1.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example // display graphic panel 1


T6963C_displayGrPanel(1);

T6963C_displayTxtPanel

Prototype void T6963C_displayTxtPanel(char n);

Returns Nothing.

Description Display selected text panel.

Parameters :

 n: text panel number. Valid values: 0 and 1.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example // display text panel 1


T6963C_displayTxtPanel(1);

T6963C_setGrPanel

Prototype void T6963C_setGrPanel(char n);

Returns Nothing.

Description Computes start address for selected graphic panel and set appropriate internal pointers. All subsequent graphic
operations will be preformed at this graphic panel.

Parameters :

 n: graphic panel number. Valid values: 0 and 1.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

www.raguvaran.puzl.com
Example // set graphic panel 1 as current graphic panel.
T6963C_setGrPanel(1);

T6963C_setTxtPanel

Prototype void T6963C_setTxtPanel(char n);

Returns Nothing.

Description Computes start address for selected text panel and set appropriate internal pointers. All subsequent text operations
will be preformed at this text panel.

Parameters :

 n: text panel number. Valid values: 0 and 1.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example // set text panel 1 as current text panel.


T6963C_setTxtPanel(1);

T6963C_panelFill

Prototype void T6963C_panelFill(unsigned char v);

Returns Nothing.

Description Fill current panel in full (graphic+text) with appropriate value (0 to clear).

Parameters :

 v: value to fill panel with.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example clear current panel


T6963C_panelFill(0);

T6963C_grFill

Prototype void T6963C_grFill(unsigned char v);

Returns Nothing.

Description Fill current graphic panel with appropriate value (0 to clear).

www.raguvaran.puzl.com
Parameters :

 v: value to fill graphic panel with.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example // clear current graphic panel


T6963C_grFill(0);

T6963C_txtFill

Prototype void T6963C_txtFill(unsigned char v);

Returns Nothing.

Description Fill current text panel with appropriate value (0 to clear).

Parameters :

 v: this value increased by 32 will be used to fill text panel.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example // clear current text panel


T6963C_txtFill(0);

T6963C_cursor_height

Prototype void T6963C_cursor_height(unsigned char n);

Returns Nothing.

Description Set cursor size.

Parameters :

 n: cursor height. Valid values: 0..7.

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example T6963C_cursor_height(7);

T6963C_graphics

Prototype void T6963C_graphics(char n);

www.raguvaran.puzl.com
Returns Nothing.

Description Enable/disable graphic displaying.

Parameters :

 n: on/off parameter. Valid values: 0 (disable graphic displaying) and 1 (enable graphic
displaying).

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example // enable graphic displaying


T6963C_graphics(1);

T6963C_text

Prototype void T6963C_text(char n);

Returns Nothing.

Description Enable/disable text displaying.

Parameters :

 n: on/off parameter. Valid values: 0 (disable text displaying) and 1 (enable text displaying).

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example // enable text displaying


T6963C_text(1);

T6963C_cursor

Prototype void T6963C_cursor(char n);

Returns Nothing.

Description Set cursor on/off.

Parameters :

 n: on/off parameter. Valid values: 0 (set cursor off) and 1 (set cursor on).

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example // set cursor on


T6963C_cursor(1);

www.raguvaran.puzl.com
T6963C_cursor_blink

Prototype void T6963C_cursor_blink(char n);

Returns Nothing.

Description Enable/disable cursor blinking.

Parameters :

 n: on/off parameter. Valid values: 0 (disable cursor blinking) and 1 (enable cursor blinking).

Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.

Example // enable cursor blinking


T6963C_cursor_blink(1);

Library Example
The following drawing demo tests advanced routines of the T6963C Glcd library. Hardware
configurations in this example are made for the T6963C 240x128 display, EasyPIC6 board and 16F887.

Copy Code To Clipboard

#include "__T6963C.h"

// T6963C module connections


char T6963C_dataPort at PORTD; // DATA port

sbit T6963C_ctrlwr at RC2_bit; // WR write signal


sbit T6963C_ctrlrd at RC1_bit; // RD read signal
sbit T6963C_ctrlcd at RC0_bit; // CD command/data signal
sbit T6963C_ctrlrst at RC4_bit; // RST reset signal
sbit T6963C_ctrlwr_Direction at TRISC2_bit; // WR write signal
sbit T6963C_ctrlrd_Direction at TRISC1_bit; // RD read signal
sbit T6963C_ctrlcd_Direction at TRISC0_bit; // CD command/data signal
sbit T6963C_ctrlrst_Direction at TRISC4_bit; // RST reset signal

// Signals not used by library, they are set in main function


sbit T6963C_ctrlce at RC3_bit; // CE signal
sbit T6963C_ctrlfs at RC6_bit; // FS signal
sbit T6963C_ctrlmd at RC5_bit; // MD signal
sbit T6963C_ctrlce_Direction at TRISC3_bit; // CE signal direction
sbit T6963C_ctrlfs_Direction at TRISC6_bit; // FS signal direction
sbit T6963C_ctrlmd_Direction at TRISC5_bit; // MD signal direction

// End T6963C module connections

/*
* bitmap pictures stored in ROM
*/
const code char mikroE_240x64_bmp[]; // PIC16F887 can't store larger picture(240x128) in ROM
const code char einstein[];

www.raguvaran.puzl.com
void main() {
char txt1[] = " EINSTEIN WOULD HAVE LIKED mE";
char txt[] = " GLCD LIBRARY DEMO, WELCOME !";

unsigned char panel; // Current panel


unsigned int i; // General purpose register
unsigned char curs; // Cursor visibility
unsigned int cposx, cposy; // Cursor x-y position

#define COMPLETE_EXAMPLE // comment this line to make simpler/smaller example


ANSEL = 0; // Configure AN pins as digital I/O
ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;

TRISB0_bit = 1; // Set RB0 as input


TRISB1_bit = 1; // Set RB1 as input
TRISB2_bit = 1; // Set RB2 as input
TRISB3_bit = 1; // Set RB3 as input
TRISB4_bit = 1; // Set RB4 as input

T6963C_ctrlce_Direction = 0;
T6963C_ctrlce = 0; // Enable T6963C
T6963C_ctrlfs_Direction = 0;
T6963C_ctrlfs = 0; // Font Select 8x8
T6963C_ctrlmd_Direction = 0;
T6963C_ctrlmd = 0; // Column number select

// Initialize T6963C
T6963C_init(240, 128, 8);

/*
* Enable both graphics and text display at the same time
*/
T6963C_graphics(1);
T6963C_text(1);

panel = 0;
i = 0;
curs = 0;
cposx = cposy = 0;
/*
* Text messages
*/
T6963C_write_text(txt, 0, 0, T6963C_ROM_MODE_XOR);
T6963C_write_text(txt1, 0, 15, T6963C_ROM_MODE_XOR);

/*
* Cursor
*/
T6963C_cursor_height(8); // 8 pixel height
T6963C_set_cursor(0, 0); // Move cursor to top left
T6963C_cursor(0); // Cursor off

/*
* Draw rectangles
*/
T6963C_rectangle(0, 0, 239, 127, T6963C_WHITE);
T6963C_rectangle(20, 20, 219, 107, T6963C_WHITE);
T6963C_rectangle(40, 40, 199, 87, T6963C_WHITE);
T6963C_rectangle(60, 60, 179, 67, T6963C_WHITE);

/*
* Draw a cross
*/

www.raguvaran.puzl.com
T6963C_line(0, 0, 239, 127, T6963C_WHITE);
T6963C_line(0, 127, 239, 0, T6963C_WHITE);

/*
* Draw solid boxes
*/
T6963C_box(0, 0, 239, 8, T6963C_WHITE);
T6963C_box(0, 119, 239, 127, T6963C_WHITE);

#ifdef COMPLETE_EXAMPLE
/*
* Draw circles
*/
T6963C_circle(120, 64, 10, T6963C_WHITE);
T6963C_circle(120, 64, 30, T6963C_WHITE);
T6963C_circle(120, 64, 50, T6963C_WHITE);
T6963C_circle(120, 64, 70, T6963C_WHITE);
T6963C_circle(120, 64, 90, T6963C_WHITE);
T6963C_circle(120, 64, 110, T6963C_WHITE);
T6963C_circle(120, 64, 130, T6963C_WHITE);

T6963C_sprite(76, 4, einstein, 88, 119); // Draw a sprite

T6963C_setGrPanel(1); // Select other graphic panel

T6963C_sprite(0, 0, mikroE_240x64_bmp, 240, 64);// 240x128 can't be stored in most of PIC16


MCUs
T6963C_sprite(0, 64, mikroE_240x64_bmp, 240, 64);// it is replaced with smaller picture
240x64
// Smaller picture is drawn two times
#endif

for(;;) { // Endless loop


/*
* If RB0 is pressed, display only graphic panel
*/
if(RB0_bit) {
T6963C_graphics(1);
T6963C_text(0);
Delay_ms(300);
}
#ifdef COMPLETE_EXAMPLE
/*
* If RB1 is pressed, toggle the display between graphic panel 0 and graphic panel 1
*/
else if(RB1_bit) {
panel++;
panel &= 1;
T6963C_displayGrPanel(panel);
Delay_ms(300);
}
#endif
/*
* If RB2 is pressed, display only text panel
*/
else if(RB2_bit) {
T6963C_graphics(0);
T6963C_text(1);
Delay_ms(300);
}

/*
* If RB3 is pressed, display text and graphic panels
*/
else if(RB3_bit) {
T6963C_graphics(1);
T6963C_text(1);

www.raguvaran.puzl.com
Delay_ms(300);
}
/*
* If RB4 is pressed, change cursor
*/
else if(RB4_bit) {
curs++;
if(curs == 3) curs = 0;
switch(curs) {
case 0:
// no cursor
T6963C_cursor(0);
break;
case 1:
// blinking cursor
T6963C_cursor(1);
T6963C_cursor_blink(1);
break;
case 2:
// non blinking cursor
T6963C_cursor(1);
T6963C_cursor_blink(0);
break;
}
Delay_ms(300);
}

/*
* Move cursor, even if not visible
*/
cposx++;
if(cposx == T6963C_txtCols) {
cposx = 0;
cposy++;
if(cposy == T6963C_grHeight / T6963C_CHARACTER_HEIGHT) {
cposy = 0;
}
}
T6963C_set_cursor(cposx, cposy);

Delay_ms(100);
}
}

HW Connection

www.raguvaran.puzl.com
T6963C Glcd HW connection

TFT Library

www.raguvaran.puzl.com
Thin film transistor liquid crystal display (TFT-LCD) is a variant of liquid crystal display (LCD) which uses
thin-film transistor (TFT) technology to improve image quality (e.g., addressability, contrast).
TFT LCD is one type of active matrix LCD, though all LCD-screens are based on TFT active matrix
addressing.
TFT LCDs are used in television sets, computer monitors, mobile phones, handheld video game systems,
personal digital assistants, navigation systems, projectors, etc.

The mikroC PRO for PIC provides a library for working with the following display controllers :

 Himax HX8347G,
 Solomon Systech SSD1963,
 Renesas SP R61526,
 Sitronix SST7715R.

Note :
 When connecting the TFT display to the MCU use voltage translators from 5V to 3.3V (if
MCU is a 5V device). In any other case you can damage the TFT!
 Library works with PIC18 family only.
 All display controllers are initialized with 65,536 colors (R(5),G(6),B(5)).

External dependencies of TFT Library


The following variables must be
defined in all projects using TFT Description : Example :
library:
extern sfr
TFT Data Port. char TFT_DataPort at LATD;
char TFT_DataPort;

extern sfr Direction of the char TFT_DataPort_Direction at TRISD;


char TFT_DataPort_Direction; TFT Data Port.
extern sfr sbit TFT_WR; Write signal. sbit TFT_WR at LATE1_bit;

extern sfr sbit TFT_RD; Read signal. sbit TFT_RD at LATE0_bit;

extern sfr sbit TFT_CS; Chip Select signal. sbit TFT_CS at LATG3_bit;

extern sfr sbit TFT_RS;


Command/Register sbit TFT_RS at LATH6_bit;
Select signal.
extern sfr sbit TFT_RST; Reset signal. sbit TFT_RST at LATH4_bit;

extern sfr Direction of the sbit TFT_WR_Direction at TRISE1_bit;


sbit TFT_WR_Direction; Write pin.
extern sfr Direction of the sbit TFT_WR_Direction at TRISE0_bit;
sbit TFT_RD_Direction; Read pin.
extern sfr Direction of the sbit TFT_CS_Direction at TRISG3_bit;
sbit TFT_CS_Direction; Chip Select pin.
Direction of the
extern sfr
Register Select sbit TFT_RS_Direction at TRISH6_bit;
sbit TFT_RS_Direction;
pin.
extern sfr Direction of the sbit TFT_RST_Direction at TRISH4_bit;
sbit TFT_RST_Direction; Reset pin.

Library Routines

www.raguvaran.puzl.com
 TFT_Init
 TFT_Init_HX8347G
 TFT_Init_SSD1963_8bit
 TFT_Init_R61526
 TFT_Init_SST7715R

 TFT_Set_Index
 TFT_Write_Command
 TFT_Write_Data
 TFT_Set_Reg
 TFT_Set_Ext_Buffer
 TFT_Set_Active
 TFT_Set_Default_Mode
 TFT_Set_Font
 TFT_Set_Ext_Font
 TFT_Write_Char
 TFT_Write_Text
 TFT_Write_Const_Text
 TFT_Fill_Screen
 TFT_Set_Pen
 TFT_Set_Brush
 TFT_Dot
 TFT_Line
 TFT_H_Line
 TFT_V_Line
 TFT_Rectangle
 TFT_Rectangle_Round_Edges
 TFT_Circle
 TFT_Image
 TFT_Ext_Image
 TFT_Partial_Image
 TFT_Ext_Partial_Image
 TFT_Image_Jpeg
 TFT_RGBToColor16bit
 TFT_Color16bitToRGB
 TFT_Rotate_180

TFT_Init

Prototype void TFT_Init(unsigned int display_width, unsigned char display_height);

Returns Nothing.

Description Initializes HX8347-D display controller display in the 8-bit working mode.

Parameters :

 width: width of the TFT panel


 height: height of the TFT panel

Requires Global variables :

 TFT_DataPort: Data Port

www.raguvaran.puzl.com
 TFT_WR: Write signal pin
 TFT_RD: Read signal pin
 TFT_CS: Chip Select signal pin
 TFT_RS: Register Select signal pin
 TFT_RST: Reset signal pin

 TFT_DataPort_Direction: Direction of Data Port


 TFT_WR_Direction: Direction of Write signal pin
 TFT_RD_Direction: Direction of Read signal pin
 TFT_CS_Direction: Direction of Chip Select signal pin
 TFT_RS_Direction: Direction of Register Select signal pin
 TFT_RST_Direction: Direction of Reset signal pin
must be defined before using this function.

Example // TFT display connections


char TFT_DataPort at LATD;
sbit TFT_WR at LATE1_bit;
sbit TFT_RD at LATE0_bit;
sbit TFT_CS at LATG3_bit;
sbit TFT_RS at LATH6_bit;
sbit TFT_RST at LATH4_bit;

char TFT_DataPort_Direction at TRISD;


sbit TFT_WR_Direction : at TRISE1_bit;
sbit TFT_RD_Direction at TRISE0_bit;
sbit TFT_CS_Direction at TRISG3_bit;
sbit TFT_RS_Direction at TRISH6_bit;
sbit TFT_RST_Direction at TRISH4_bit;
// End of TFT display connections

// Initialize 240x320 TFT display


TFT_Init(240, 320);

TFT_Init_HX8347G

Prototype void TFT_Init_HX8347G(unsigned int display_width, unsigned


char display_height);

Returns Nothing.

Description Initializes HX8347-G display controller display in the 8-bit working mode.

Parameters :

 width: width of the TFT panel


 height: height of the TFT panel

Requires Global variables :

 TFT_DataPort: Data Port


 TFT_WR: Write signal pin
 TFT_RD: Read signal pin
 TFT_CS: Chip Select signal pin
 TFT_RS: Register Select signal pin
 TFT_RST: Reset signal pin

www.raguvaran.puzl.com
 TFT_DataPort_Direction: Direction of Data Port
 TFT_WR_Direction: Direction of Write signal pin
 TFT_RD_Direction: Direction of Read signal pin
 TFT_CS_Direction: Direction of Chip Select signal pin
 TFT_RS_Direction: Direction of Register Select signal pin
 TFT_RST_Direction: Direction of Reset signal pin
must be defined before using this function.

Example // TFT display connections


char TFT_DataPort at LATD;
sbit TFT_WR at LATE1_bit;
sbit TFT_RD at LATE0_bit;
sbit TFT_CS at LATG3_bit;
sbit TFT_RS at LATH6_bit;
sbit TFT_RST at LATH4_bit;

char TFT_DataPort_Direction at TRISD;


sbit TFT_WR_Direction : at TRISE1_bit;
sbit TFT_RD_Direction at TRISE0_bit;
sbit TFT_CS_Direction at TRISG3_bit;
sbit TFT_RS_Direction at TRISH6_bit;
sbit TFT_RST_Direction at TRISH4_bit;
// End of TFT display connections

// Initialize 240x320 TFT display


TFT_Init_HX8347G(240, 320);

TFT_Init_SSD1963_8bit

Prototype void TFT_Init_SSD1963_8bit(unsigned int display_width, unsigned


char display_height);

Returns Nothing.

Description Initializes SSD1963 display controller display in the 8-bit working mode.

Parameters :

 width: width of the TFT panel


 height: height of the TFT panel

Requires Global variables :

 TFT_DataPort: Data Port


 TFT_WR: Write signal pin
 TFT_RD: Read signal pin
 TFT_CS: Chip Select signal pin
 TFT_RS: Register Select signal pin
 TFT_RST: Reset signal pin

 TFT_DataPort_Direction: Direction of Data Port


 TFT_WR_Direction: Direction of Write signal pin
 TFT_RD_Direction: Direction of Read signal pin
 TFT_CS_Direction: Direction of Chip Select signal pin

www.raguvaran.puzl.com
 TFT_RS_Direction: Direction of Register Select signal pin
 TFT_RST_Direction: Direction of Reset signal pin
must be defined before using this function.

Example // TFT display connections


char TFT_DataPort at LATD;
sbit TFT_WR at LATE1_bit;
sbit TFT_RD at LATE0_bit;
sbit TFT_CS at LATG3_bit;
sbit TFT_RS at LATH6_bit;
sbit TFT_RST at LATH4_bit;

char TFT_DataPort_Direction at TRISD;


sbit TFT_WR_Direction : at TRISE1_bit;
sbit TFT_RD_Direction at TRISE0_bit;
sbit TFT_CS_Direction at TRISG3_bit;
sbit TFT_RS_Direction at TRISH6_bit;
sbit TFT_RST_Direction at TRISH4_bit;
// End of TFT display connections

// Initialize 240x320 TFT display


TFT_Init_SSD1963_8bit(240, 320);

TFT_Init_R61526

Prototype void TFT_Init_R61526(unsigned int display_width, unsigned


char display_height);

Returns Nothing.

Description Initializes R61526 display controller display in the 8-bit working mode.

Parameters :

 width: width of the TFT panel


 height: height of the TFT panel

Requires Global variables :

 TFT_DataPort: Data Port


 TFT_WR: Write signal pin
 TFT_RD: Read signal pin
 TFT_CS: Chip Select signal pin
 TFT_RS: Register Select signal pin
 TFT_RST: Reset signal pin

 TFT_DataPort_Direction: Direction of Data Port


 TFT_WR_Direction: Direction of Write signal pin
 TFT_RD_Direction: Direction of Read signal pin
 TFT_CS_Direction: Direction of Chip Select signal pin
 TFT_RS_Direction: Direction of Register Select signal pin
 TFT_RST_Direction: Direction of Reset signal pin
must be defined before using this function.

Example // TFT display connections

www.raguvaran.puzl.com
char TFT_DataPort at LATD;
sbit TFT_WR at LATE1_bit;
sbit TFT_RD at LATE0_bit;
sbit TFT_CS at LATG3_bit;
sbit TFT_RS at LATH6_bit;
sbit TFT_RST at LATH4_bit;

char TFT_DataPort_Direction at TRISD;


sbit TFT_WR_Direction : at TRISE1_bit;
sbit TFT_RD_Direction at TRISE0_bit;
sbit TFT_CS_Direction at TRISG3_bit;
sbit TFT_RS_Direction at TRISH6_bit;
sbit TFT_RST_Direction at TRISH4_bit;
// End of TFT display connections

// Initialize 240x320 TFT display


TFT_Init_R61526(240, 320);

TFT_Init_SST7715R

Prototype void TFT_Init_SST7715R(unsigned int display_width, unsigned


char display_height);

Returns Nothing.

Description Initializes SST7715R display controller display in the 8-bit working mode.

Parameters :

 width: width of the TFT panel


 height: height of the TFT panel

Requires Global variables :

 TFT_DataPort: Data Port


 TFT_WR: Write signal pin
 TFT_RD: Read signal pin
 TFT_CS: Chip Select signal pin
 TFT_RS: Register Select signal pin
 TFT_RST: Reset signal pin

 TFT_DataPort_Direction: Direction of Data Port


 TFT_WR_Direction: Direction of Write signal pin
 TFT_RD_Direction: Direction of Read signal pin
 TFT_CS_Direction: Direction of Chip Select signal pin
 TFT_RS_Direction: Direction of Register Select signal pin
 TFT_RST_Direction: Direction of Reset signal pin
must be defined before using this function.

Example // TFT display connections


char TFT_DataPort at LATD;
sbit TFT_WR at LATE1_bit;
sbit TFT_RD at LATE0_bit;
sbit TFT_CS at LATG3_bit;
sbit TFT_RS at LATH6_bit;
sbit TFT_RST at LATH4_bit;

www.raguvaran.puzl.com
char TFT_DataPort_Direction at TRISD;
sbit TFT_WR_Direction : at TRISE1_bit;
sbit TFT_RD_Direction at TRISE0_bit;
sbit TFT_CS_Direction at TRISG3_bit;
sbit TFT_RS_Direction at TRISH6_bit;
sbit TFT_RST_Direction at TRISH4_bit;
// End of TFT display connections

// Initialize 240x320 TFT display


TFT_Init_SST7715R(240, 320);

TFT_Set_Index

Prototype void TFT_Set_Index(unsigned short index);

Returns Nothing.

Description Accesses register space of the controller and sets the desired register.

Parameters :

 index: desired register number.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example // Access register at the location 0x02


TFT_Set_Index(0x02);

TFT_Write_Command

Prototype void TFT_Write_Command(unsigned short cmd);

Returns Nothing.

Description Accesses data space and writes a command.

Parameters :

 cmd: command to be written.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example // Write a command


TFT_Write_Command(0x02);

TFT_Write_Data

www.raguvaran.puzl.com
Prototype void TFT_Write_Data(unsigned int _data);

Returns Nothing.

Description Writes date into display memory.

Parameters :

 _data:data to be written.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example // Send data


TFT_Write_Data(0x02);

TFT_Set_Reg

Prototype void TFT_Set_Reg(unsigned short index, unsigned short value);

Returns Nothing.

Description Accesses register space of the controller and writes a value in the desired register.

Parameters :

 index: desired register.


 value: value to be written.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example // 65K Color Selection


TFT_Set_Reg(0x17, 0x05);

TFT_Set_Ext_Buffer

Prototype void TFT_Set_Ext_Buffer(char* (*getExtDataPtr)(unsigned


long offset, unsigned long count, unsigned long* num));

Returns Nothing.

Description Function sets pointer to the user function which manipulates the external resource.

Parameters :

 offset - offset from the beginning of the resource from where the data is requested.
 count - requested number of bytes.
 num - variable for holding the returned number of bytes (less or equal to the number of acquired

www.raguvaran.puzl.com
bytes).

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example char* ReadExternalBuffer(unsigned long offset, unsigned int count, unsigned int
*num){
unsigned long start_sector;
unsigned int pos;

start_sector = Mmc_Get_File_Write_Sector() + offset/512;


pos = (unsigned long)offset%512;

if(start_sector == currentSector+1){
Mmc_Multi_Read_Buffer(EXT_BUFFER);
currentSector = start_sector;
}else
if(start_sector != currentSector){
Mmc_Multi_Read_Stop();
Mmc_Multi_Read_Start(start_sector);
Mmc_Multi_Read_Buffer(EXT_BUFFER);
currentSector = start_sector;
}

if(count>512-pos){
*num = 512-pos;
}
else
*num = count;

return EXT_BUFFER+pos;
}

TFT_Set_Ext_Buffer(ReadExternalBuffer);

TFT_Set_Active

Prototype void TFT_Set_Active(void (*Set_Index_Ptr)(unsigned


short), void (*Write_Command_Ptr)(unsigned
short), void (*Write_Data_Ptr)(unsigned int));

Returns Nothing.

Description This function sets appropriate pointers to a user-defined basic routines in order to enable multiple working modes.

Parameters :

 Set_Index_Ptr: Set_Index handler.


 Write_Command_Ptr: _Write_Command handler.
 Write_Data_Ptr: Write_Data handler.

Requires None.

Example // Example of establishing 16-bit communication between TFT display and PORTD, PORTE
of MCU :

void Set_Index(unsigned short index) {

www.raguvaran.puzl.com
TFT_RS = 0;
Lo(LATD) = index;
TFT_WR = 0;
TFT_WR = 1;
}

void Write_Command(unsigned short cmd) {


TFT_RS = 1;
Lo(LATD) = cmd;
TFT_WR = 0;
TFT_WR = 1;
}

void Write_Data(unsigned int _data) {


TFT_RS = 1;
Lo(LATE) = Hi(_data);
Lo(LATD) = Lo(_data);
TFT_WR = 0;
TFT_WR = 1;
}

void main(){
TRISE = 0;
TRISD = 0;

TFT_Set_Active(Set_Index,Write_Command,Write_Data);
TFT_Init(320, 240);

.....
}

TFT_Set_Default_Mode

Prototype void TFT_Set_Default_Mode();

Returns Nothing.

Description This function sets TFT in default working mode.

Parameters :

 None.

Requires None.

Example TFT_Set_Default_Mode();
TFT_Init(320, 240);

TFT_Set_Font

Prototype void TFT_Set_Font(const char far *activeFont, unsigned


int font_color, char font_orientation);

www.raguvaran.puzl.com
Returns Nothing.

Description Sets font, its color and font orientation.

Parameters :

 activeFont: desired font. Currently, only TFT_defaultFont (Tahoma14x16) is supported.


 font_color: sets font color :

Value Description

CL_AQUA Aqua color

CL_BLACK Black color

CL_BLUE Blue color

CL_FUCHSIA Fuchsia color

CL_GRAY Gray color

CL_GREEN Green color

CL_LIME Lime color

CL_MAROON Maroon color

CL_NAVY Navy color

CL_OLIVE Olive color

CL_PURPLE Purple color

CL_RED Red color

CL_SILVER Silver color

CL_TEAL Teal color

CL_WHITE White color

CL_YELLOW Yellow color

 font_orientation: sets font orientation :

Value Description

FO_HORIZONTAL Horizontal orientation

FO_VERTICAL Vertical orientation

www.raguvaran.puzl.com
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_Set_Font(TFT_defaultFont, CL_BLACK, FO_HORIZONTAL);

TFT_Set_Ext_Font

Prototype void TFT_Set_Ext_Font(unsigned long *activeFont, unsigned


int font_color, char font_orientation);

Returns Nothing.

Description Sets font, its color and font orientation. Font is located in an external resource

Parameters :

 activeFont: desired font. This parameter represents the address in the exteral resource from
where the font data begins.
 font_color: sets font color :

Value Description

CL_AQUA Aqua color

CL_BLACK Black color

CL_BLUE Blue color

CL_FUCHSIA Fuchsia color

CL_GRAY Gray color

CL_GREEN Green color

CL_LIME Lime color

CL_MAROON Maroon color

CL_NAVY Navy color

CL_OLIVE Olive color

CL_PURPLE Purple color

CL_RED Red color

CL_SILVER Silver color

CL_TEAL Teal color

www.raguvaran.puzl.com
CL_WHITE White color

CL_YELLOW Yellow color

 font_orientation: sets font orientation :

Value Description

FO_HORIZONTAL Horizontal orientation

FO_VERTICAL Vertical orientation

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_Set_Ext_Font(173296,CL_BLACK,FO_HORIZONTAL);

TFT_Write_Char

Prototype void TFT_Write_Char(unsigned int c, unsigned int x, unsigned int y);

Returns Nothing.

Description Writes a char on the TFT at coordinates (x, y).

 c: char to be written.
 x: char position on x-axis.
 y: char position on y-axis.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_Write_Char('A',22,23,);

TFT_Write_Text

Prototype void TFT_Write_Text(unsigned char *text, unsigned int x, unsigned int y);

Returns Nothing.

Description Writes text on the TFT at coordinates (x, y).

Parameters :

 text: text to be written.


 x: text position on x-axis.
 y: text position on y-axis.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

www.raguvaran.puzl.com
Example TFT_Write_Text("TFT LIBRARY DEMO, WELCOME !", 0, 0,);

TFT_Write_Const_Text

Prototype void TFT_Write_Const_Text(const far char *text, unsigned int x, unsigned


int y);

Returns Nothing.

Description Writes text located in the program memory on the TFT at coordinates (x, y).

Parameters :

 text: text to be written.


 x: text position on x-axis.
 y: text position on y-axis.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example const char ctext[] = "mikroElektronika";


...
TFT_Write_Const_Text(ctext, 0, 0,);

TFT_Fill_Screen

Prototype void TFT_Fill_Screen(unsigned int color);

Returns Nothing.

Description Fills screen memory block with given color.

Parameters :

 color: color to be filled :

Value Description

CL_AQUA Aqua color

CL_BLACK Black color

CL_BLUE Blue color

CL_FUCHSIA Fuchsia color

CL_GRAY Gray color

CL_GREEN Green color

www.raguvaran.puzl.com
CL_LIME Lime color

CL_MAROON Maroon color

CL_NAVY Navy color

CL_OLIVE Olive color

CL_PURPLE Purple color

CL_RED Red color

CL_SILVER Silver color

CL_TEAL Teal color

CL_WHITE White color

CL_YELLOW Yellow color

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_Fill_Screen(CL_BLACK);

TFT_Dot

Prototype void TFT_Dot(int x, int y, unsigned int color);

Returns Nothing.

Description Draws a dot on the TFT at coordinates (x, y).

Parameters :

 x: dot position on x-axis.


 y: dot position on y-axis.
 color: color parameter. Valid values :

Value Description

CL_AQUA Aqua color

CL_BLACK Black color

CL_BLUE Blue color

CL_FUCHSIA Fuchsia color

www.raguvaran.puzl.com
CL_GRAY Gray color

CL_GREEN Green color

CL_LIME Lime color

CL_MAROON Maroon color

CL_NAVY Navy color

CL_OLIVE Olive color

CL_PURPLE Purple color

CL_RED Red color

CL_SILVER Silver color

CL_TEAL Teal color

CL_WHITE White color

CL_YELLOW Yellow color

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_Dot(50, 50, CL_BLACK);

TFT_Set_Pen

Prototype void TFT_Set_Pen(unsigned int pen_color, char pen_width);

Returns Nothing.

Description Sets color and thickness parameter for drawing line, circle and rectangle elements.

Parameters :

 pen_color: Sets color.

Value Description

CL_AQUA Aqua color

CL_BLACK Black color

CL_BLUE Blue color

www.raguvaran.puzl.com
CL_FUCHSIA Fuchsia color

CL_GRAY Gray color

CL_GREEN Green color

CL_LIME Lime color

CL_MAROON Maroon color

CL_NAVY Navy color

CL_OLIVE Olive color

CL_PURPLE Purple color

CL_RED Red color

CL_SILVER Silver color

CL_TEAL Teal color

CL_WHITE White color

CL_YELLOW Yellow color

 pen_width: sets thickness.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_Set_Pen(CL_BLACK, 10);

TFT_Set_Brush

Prototype void TFT_Set_Brush(char brush_enabled, unsigned


int brush_color, char gradient_enabled, char gradient_orientation, unsigned
intgradient_color_from, unsigned int gradient_color_to);

Returns Nothing.

Description Sets color and gradient which will be used to fill circles or rectangles.

Parameters :

 brush_enabled: enable brush fill.

Value Description

1 Enable brush fill.

www.raguvaran.puzl.com
0 Disable brush fill.

 brush_color: set brush fill color.

Value Description

CL_AQUA Aqua color

CL_BLACK Black color

CL_BLUE Blue color

CL_FUCHSIA Fuchsia color

CL_GRAY Gray color

CL_GREEN Green color

CL_LIME Lime color

CL_MAROON Maroon color

CL_NAVY Navy color

CL_OLIVE Olive color

CL_PURPLE Purple color

CL_RED Red color

CL_SILVER Silver color

CL_TEAL Teal color

CL_WHITE White color

CL_YELLOW Yellow color

 gradient_enabled: enable gradient

Value Description

1 Enable gradient.

0 Disable gradient.

 gradient_orientation: sets gradient orientation :

Value Description

LEFT_TO_RIGHT Left to right gradient orientation

TOP_TO_BOTTOM Top to bottom gradient orientation

 gradient_color_from: sets the starting gradient color.

www.raguvaran.puzl.com
Value Description

CL_AQUA Aqua color

CL_BLACK Black color

CL_BLUE Blue color

CL_FUCHSIA Fuchsia color

CL_GRAY Gray color

CL_GREEN Green color

CL_LIME Lime color

CL_MAROON Maroon color

CL_NAVY Navy color

CL_OLIVE Olive color

CL_PURPLE Purple color

CL_RED Red color

CL_SILVER Silver color

CL_TEAL Teal color

CL_WHITE White color

CL_YELLOW Yellow color

 gradient_color_to: sets the ending gradient color.

Value Description

CL_AQUA Aqua color

CL_BLACK Black color

CL_BLUE Blue color

CL_FUCHSIA Fuchsia color

CL_GRAY Gray color

CL_GREEN Green color

CL_LIME Lime color

www.raguvaran.puzl.com
CL_MAROON Maroon color

CL_NAVY Navy color

CL_OLIVE Olive color

CL_PURPLE Purple color

CL_RED Red color

CL_SILVER Silver color

CL_TEAL Teal color

CL_WHITE White color

CL_YELLOW Yellow color

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example // Enable gradient from black to white color, left-right orientation


TFT_Set_Brush(0, 0, 1, LEFT_TO_RIGHT, CL_BLACK, CL_WHITE);

TFT_Line

Prototype void TFT_Line(int x1, int y1, int x2, int y2);

Returns Nothing.

Description Draws a line from (x1, y1) to (x2, y2).

Parameters :

 x1: x coordinate of the line start.


 y1: y coordinate of the line end.
 x2: x coordinate of the line start.
 y2: y coordinate of the line end.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_Line(0, 0, 239, 127);

www.raguvaran.puzl.com
TFT_H_Line

Prototype void TFT_H_Line(int x_start, int x_end, int y_pos);

Returns Nothing.

Description Draws a horizontal line on TFT.

Parameters :

 x_start: x coordinate of the line start.


 x_end: x coordinate of the line end.
 y_pos: y coordinate of horizontal line.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example // Draw a horizontal line between dots (10,20) and (50,20)


TFT_H_Line(10, 50, 20);

TFT_V_Line

Prototype void TFT_V_Line(int y_start, int y_end, int x_pos);

Returns Nothing.

Description Draws a vertical line on TFT.

Parameters :

 y_start: y coordinate of the line start.


 y_end: y coordinate of the line end.
 x_pos: x coordinate of vertical line.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example // Draw a vertical line between dots (10,5) and (10,25)


TFT_V_Line(5, 25, 10);

TFT_Rectangle

Prototyp void TFT_Rectangle(int x_upper_left, int y_upper_left, int x_bottom_right, in


e t y_bottom_right);

Returns Nothing.

Descripti Draws a rectangle on TFT.


on

www.raguvaran.puzl.com
Parameters :

 x_upper_left: x coordinate of the upper left rectangle corner.


 y_upper_left: y coordinate of the upper left rectangle corner.
 x_bottom_right: x coordinate of the lower right rectangle corner.
 y_bottom_right: y coordinate of the lower right rectangle corner.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_Rectangle(20, 20, 219, 107);

TFT_Rectangle_Round_Edges

Prototype void TFT_Rectangle_Round_Edges(unsigned int x_upper_left, unsigned


int y_upper_left, unsigned int x_bottom_right, unsigned
int y_bottom_right,unsigned int round_radius);

Returns Nothing.

Description Draws a rounded edge rectangle on TFT.

Parameters :

 x_upper_left: x coordinate of the upper left rectangle corner.


 y_upper_left: y coordinate of the upper left rectangle corner.
 x_bottom_right: x coordinate of the lower right rectangle corner.
 y_bottom_right: y coordinate of the lower right rectangle corner.
 round_radius: radius of the rounded edge.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_Rectangle_Round_Edges(20, 20, 219, 107, 12);

TFT_Circle

Prototype void TFT_Circle(int x_center, int y_center, int radius);

Returns Nothing.

Description Draws a circle on TFT.

Parameters :

 x: x coordinate of the circle center.


 y: y coordinate of the circle center.
 r: radius size.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

www.raguvaran.puzl.com
Example TFT_Circle(120, 64, 110);

TFT_Image

Prototype void TFT_Image(unsigned int left, unsigned int top, code const far unsigned
short * image, unsigned short stretch);

Returns Nothing.

Description Displays an image on a desired location.

Parameters :

 left: position of the image's left edge.


 top:position of the image's top edge.
 image: image to be displayed. Bitmap array is located in code memory.
 stretch: stretches image by a given factor (if 2, it will double the image.).

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_Image(0, 0, image, 1);

TFT_Ext_Image

Prototype void TFT_Ext_Image(unsigned int left, unsigned int top, unsigned


long image, unsigned short stretch);

Returns Nothing.

Description Displays an image from an external resource on a desired address.

Parameters :

 left: position of the image's left edge.


 top:position of the image's top edge.
 image: image to be displayed. This parameter represents the address in the exteral resource from
where the image data begins.
 stretch: stretches image by a given factor (if 2, it will double the image.).

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_Image(0, 0, 153608, 1);

TFT_Partial_Image

Prototype void TFT_Partial_Image(unsigned int left, unsigned int top, unsigned


int width, unsigned int height, code const far unsigned short *

www.raguvaran.puzl.com
image,unsigned short stretch);

Returns Nothing.

Description Displays a partial area of the image on a desired location.

Parameters :

 left: left coordinate of the image.


 top: top coordinate of the image.
 width: desired image width.
 height: desired image height.
 image: image to be displayed. Bitmap array is located in code memory.
 stretch: stretches image by a given factor (if 2, it will double the image.).

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example // Draws a 10x15 part of the image starting from the upper left corner on the
coordinate (10,12)
TFT_Partial_Image(10, 12, 10, 15, image, 1);

TFT_Ext_Partial_Image

Prototype void TFT_Ext_Partial_Image(unsigned int left, unsigned int top, unsigned


int width, unsigned int height, unsigned long image, unsigned shortstretch);

Returns Nothing.

Description Displays a partial area of the image, located on an external resource, on a desired location of the screen.

Parameters :

 left: left coordinate of the image.


 top: top coordinate of the image.
 width: desired image width.
 height: desired image height.
 image: image to be displayed. This parameter represents the address in the exteral resource from
where the image data begins.
 stretch: stretches image by a given factor (if 2, it will double the image.).

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_Ext_Partial_Image(159,0,160,120,0,1);

TFT_Image_Jpeg

Prototype char TFT_Image_Jpeg(unsigned int left, unsigned int top, code const far
unsigned short *image);

www.raguvaran.puzl.com
Returns  0 - if image is loaded and displayed successfully.
 1 - if error occured.

Description Displays a JPEG image on a desired location.

Parameters :

 left: left coordinate of the image.


 top: top coordinate of the image.
 image: image to be displayed. Bitmap array is located in code memory.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_Image_Jpeg(0, 0, image);

TFT_RGBToColor16bit

Prototype unsigned
int TFT_RGBToColor16bit(char rgb_red, char rgb_green, char rgb_blue);

Returns Returns a color value in the following bit-order : 5 bits red, 6 bits green and 5 bits blue color.

Description Converts 5:6:5 RGB format into true color format.

Parameters :

 rgb_red: red component of the image.


 rgb_green: green component of the image.
 rgb_blue: blue component of the image.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example color16 = TFT_RGBToColor16bit(150, 193, 65);

TFT_Color16bitToRGB

Prototype void TFT_Color16bitToRGB(unsigned


int color, char *rgb_red, char *rgb_green, char *rgb_blue);

Returns Nothing.

Description Converts true color into 5:6:5 RGB format.

Parameters :

 color: true color to be converted.


 rgb_red: red component of the input color.
 rgb_green: green component of the input color.

www.raguvaran.puzl.com
 rgb_blue: blue component of the input color.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_Color16bitToRGB(start_color, &red_start, &green_start, &blue_start);

TFT_Rotate_180

Prototype void TFT_Rotate_180(char rotate);

Returns Nothing.

Description Rotates the TFT display.

Parameters :

 rotate: parameter for rotating display. Valid values :


 0 - display will not be rotated.
 1 - display will be rotated for 180 degrees.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example // Rotate TFT display for 180 degrees


TFT_Rotate_180(1);

// Initialize TFT display


TFT_Init(240, 320);

www.raguvaran.puzl.com
HW Connection

TFT HW connection

www.raguvaran.puzl.com
TFT 16-bit Library
Thin film transistor liquid crystal display (TFT-LCD) is a variant of liquid crystal display (LCD) which uses
thin-film transistor (TFT) technology to improve image quality (e.g., addressability, contrast).
TFT LCD is one type of active matrix LCD, though all LCD-screens are based on TFT active matrix
addressing.
TFT LCDs are used in television sets, computer monitors, mobile phones, handheld video game systems,
personal digital assistants, navigation systems, projectors, etc.

The mikroC PRO for PIC provides a library for working with the following display controllers :

 Himax HX8352A,
 Solomon Systech SSD1963,
 Ilitek ILI9340, ILI9342 and ILI9481.

Note :
 When connecting the TFT display to the MCU use voltage translators from 5V to 3.3V (if
MCU is a 5V device). In any other case you can damage the TFT!
 Library works with PIC18 family only.
 All display controllers are initialized with 65,536 colors (R(5),G(6),B(5)) and require two full
ports for operation (due to the 16-bit interface).

External dependencies of TFT 16-bit Library


The following variables must be defined in all
Description : Example :
projects using TFT 16-bit Library:
extern sfr TFT Data Port char TFT_16bit_DataPort_Lo at LATB;
char TFT_16bit_DataPort_Lo; Low.
extern sfr TFT Data Port char TFT_16bit_DataPort_Hi at LATC;
char TFT_16bit_DataPort_Hi; High.
extern sfr Direction of the
char TFT_16bit_DataPort_Hi_Direction atTRIS
char TFT_16bit_DataPort_Hi_Direction TFT Data Port B;
; Low.
extern sfr Direction of the
char TFT_16bit_DataPort_Lo_Direction atTRIS
char TFT_16bit_DataPort_Lo_Direction TFT Data Port C;
; High .
extern sfr sbit TFT_16bit_WR; Write signal. sbit TFT_16bit_WR at LATE1_bit;

extern sfr sbit TFT_16bit_RD; Read signal. sbit TFT_16bit_RD at LATE0_bit;

extern sfr sbit TFT_16bit_CS; Chip Select signal. sbit TFT_16bit_CS at LATG3_bit;

extern sfr sbit TFT_16bit_RS;


Command/Registe sbit TFT_16bit_RS at LATH6_bit;
r Select signal.
extern sfr sbit TFT_16bit_RST; Reset signal. sbit TFT_16bit_RST at LATH4_bit;

extern sfr Direction of the sbit TFT_16bit_WR_Direction atTRISE1_bit;


sbit TFT_16bit_WR_Direction; Write pin.
extern sfr Direction of the sbit TFT_16bit_WR_Direction atTRISE0_bit;
sbit TFT_16bit_RD_Direction; Read pin.
extern sfr Direction of the sbit TFT_16bit_CS_Direction atTRISG3_bit;
sbit TFT_16bit_CS_Direction; Chip Select pin.

www.raguvaran.puzl.com
Direction of the
extern sfr
Register Select sbit TFT_16bit_RS_Direction atTRISH6_bit;
sbit TFT_16bit_RS_Direction;
pin.
extern sfr Direction of the sbit TFT_16bit_RST_Direction atTRISH4_bit;
sbit TFT_16bit_RST_Direction; Reset pin.

Library Routines
 TFT_Init_HX8352A
 TFT_Init_SSD1963
 TFT_Init_ILI9340
 TFT_Init_ILI9342
 TFT_Init_ILI9481

 TFT_16bit_Set_Index
 TFT_16bit_Write_Command
 TFT_16bit_Write_Data
 TFT_16bit_Set_Reg
 TFT_16bit_Set_Ext_Buffer
 TFT_16bit_Set_Active
 TFT_16bit_Set_Default_Mode
 TFT_16bit_Set_Font
 TFT_16bit_Set_Ext_Font
 TFT_16bit_Write_Char
 TFT_16bit_Write_Text
 TFT_16bit_Write_Const_Text
 TFT_16bit_Fill_Screen
 TFT_16bit_Set_Pen
 TFT_16bit_Set_Brush
 TFT_16bit_Dot
 TFT_16bit_Line
 TFT_16bit_H_Line
 TFT_16bit_V_Line
 TFT_16bit_Rectangle
 TFT_16bit_Rectangle_Round_Edges
 TFT_16bit_Circle
 TFT_16bit_Image
 TFT_16bit_Ext_Image
 TFT_16bit_Partial_Image
 TFT_16bit_Ext_Partial_Image
 TFT_16bit_Image_Jpeg
 TFT_16bit_RGBToColor16bit
 TFT_16bit_Color16bitToRGB
 TFT_16bit_Rotate_180

TFT_Init_HX8352A

Prototype void TFT_Init_HX8352A(unsigned int display_width, unsigned


char display_height);

Returns Nothing.

www.raguvaran.puzl.com
Description Initializes HX8352A display controller in 16-bit working mode.

Parameters :

 width: width of the TFT display.


 height: height of the TFT display.

Requires Global variables :

 TFT_16bit_DataPort_Lo: Data Port Low


 TFT_16bit_DataPort_Hi: Data Port High
 TFT_16bit_WR: Write signal pin
 TFT_16bit_RD: Read signal pin
 TFT_16bit_CS: Chip Select signal pin
 TFT_16bit_RS: Register Select signal pin
 TFT_16bit_RST: Reset signal pin

 TFT_16bit_DataPort_Direction_Lo: Direction of Data Port Low


 TFT_16bit_DataPort_Direction_Hi: Direction of Data Port High
 TFT_16bit_WR_Direction: Direction of Write signal pin
 TFT_16bit_RD_Direction: Direction of Read signal pin
 TFT_16bit_CS_Direction: Direction of Chip Select signal pin
 TFT_16bit_RS_Direction: Direction of Register Select signal pin
 TFT_16bit_RST_Direction: Direction of Reset signal pin
must be defined before using this function.

Example // TFT display connections


char TFT_16bit_DataPort_Lo at LATB;
char TFT_16bit_DataPort_Hi at LATC;
sbit TFT_16bit_WR at LATE1_bit;
sbit TFT_16bit_RD at LATE0_bit;
sbit TFT_16bit_CS at LATG3_bit;
sbit TFT_16bit_RS at LATH6_bit;
sbit TFT_16bit_RST at LATH4_bit;

char TFT_16bit_DataPort_Lo_Direction at TRISB;


char TFT_16bit_DataPort_Hi_Direction at TRISC;
sbit TFT_16bit_WR_Direction : at TRISE1_bit;
sbit TFT_16bit_RD_Direction at TRISE0_bit;
sbit TFT_16bit_CS_Direction at TRISG3_bit;
sbit TFT_16bit_RS_Direction at TRISH6_bit;
sbit TFT_16bit_RST_Direction at TRISH4_bit;
// End of TFT display connections

// Initialize 240x320 TFT display


TFT_Init_HX8352A(240, 320);

TFT_Init_SSD1963

Prototype void TFT_Init_SSD1963(unsigned int display_width, unsigned


char display_height);

Returns Nothing.

www.raguvaran.puzl.com
Description Initializes SSD1963 display controller in 16-bit working mode.

Parameters :

 width: width of the TFT display.


 height: height of the TFT display.

Requires Global variables :

 TFT_16bit_DataPort_Lo: Data Port Low


 TFT_16bit_DataPort_Hi: Data Port High
 TFT_16bit_WR: Write signal pin
 TFT_16bit_RD: Read signal pin
 TFT_16bit_CS: Chip Select signal pin
 TFT_16bit_RS: Register Select signal pin
 TFT_16bit_RST: Reset signal pin

 TFT_16bit_DataPort_Direction_Lo: Direction of Data Port Low


 TFT_16bit_DataPort_Direction_Hi: Direction of Data Port High
 TFT_16bit_WR_Direction: Direction of Write signal pin
 TFT_16bit_RD_Direction: Direction of Read signal pin
 TFT_16bit_CS_Direction: Direction of Chip Select signal pin
 TFT_16bit_RS_Direction: Direction of Register Select signal pin
 TFT_16bit_RST_Direction: Direction of Reset signal pin
must be defined before using this function.

Example // TFT display connections


char TFT_16bit_DataPort_Lo at LATB;
char TFT_16bit_DataPort_Hi at LATC;
sbit TFT_16bit_WR at LATE1_bit;
sbit TFT_16bit_RD at LATE0_bit;
sbit TFT_16bit_CS at LATG3_bit;
sbit TFT_16bit_RS at LATH6_bit;
sbit TFT_16bit_RST at LATH4_bit;

char TFT_16bit_DataPort_Lo_Direction at TRISB;


char TFT_16bit_DataPort_Hi_Direction at TRISC;
sbit TFT_16bit_WR_Direction : at TRISE1_bit;
sbit TFT_16bit_RD_Direction at TRISE0_bit;
sbit TFT_16bit_CS_Direction at TRISG3_bit;
sbit TFT_16bit_RS_Direction at TRISH6_bit;
sbit TFT_16bit_RST_Direction at TRISH4_bit;
// End of TFT display connections

// Initialize 240x320 TFT display


TFT_Init_SSD1963(240, 320);

TFT_Init_ILI9340

Prototype void TFT_Init_ILI9340(unsigned int display_width, unsigned


char display_height);

Returns Nothing.

www.raguvaran.puzl.com
Description Initializes ILI9340 display controller in 16-bit working mode.

Parameters :

 width: width of the TFT display.


 height: height of the TFT display.

Requires Global variables :

 TFT_16bit_DataPort_Lo: Data Port Low


 TFT_16bit_DataPort_Hi: Data Port High
 TFT_16bit_WR: Write signal pin
 TFT_16bit_RD: Read signal pin
 TFT_16bit_CS: Chip Select signal pin
 TFT_16bit_RS: Register Select signal pin
 TFT_16bit_RST: Reset signal pin

 TFT_16bit_DataPort_Direction_Lo: Direction of Data Port Low


 TFT_16bit_DataPort_Direction_Hi: Direction of Data Port High
 TFT_16bit_WR_Direction: Direction of Write signal pin
 TFT_16bit_RD_Direction: Direction of Read signal pin
 TFT_16bit_CS_Direction: Direction of Chip Select signal pin
 TFT_16bit_RS_Direction: Direction of Register Select signal pin
 TFT_16bit_RST_Direction: Direction of Reset signal pin
must be defined before using this function.

Example // TFT display connections


char TFT_16bit_DataPort_Lo at LATB;
char TFT_16bit_DataPort_Hi at LATC;
sbit TFT_16bit_WR at LATE1_bit;
sbit TFT_16bit_RD at LATE0_bit;
sbit TFT_16bit_CS at LATG3_bit;
sbit TFT_16bit_RS at LATH6_bit;
sbit TFT_16bit_RST at LATH4_bit;

char TFT_16bit_DataPort_Lo_Direction at TRISB;


char TFT_16bit_DataPort_Hi_Direction at TRISC;
sbit TFT_16bit_WR_Direction : at TRISE1_bit;
sbit TFT_16bit_RD_Direction at TRISE0_bit;
sbit TFT_16bit_CS_Direction at TRISG3_bit;
sbit TFT_16bit_RS_Direction at TRISH6_bit;
sbit TFT_16bit_RST_Direction at TRISH4_bit;
// End of TFT display connections

// Initialize 240x320 TFT display


TFT_Init_ILI9340(240, 320);

TFT_Init_ILI9342

Prototype void TFT_Init_ILI9342(unsigned int display_width, unsigned


char display_height);

Returns Nothing.

www.raguvaran.puzl.com
Description Initializes ILI9342 display controller in 16-bit working mode.

Parameters :

 width: width of the TFT display.


 height: height of the TFT display.

Requires Global variables :

 TFT_16bit_DataPort_Lo: Data Port Low


 TFT_16bit_DataPort_Hi: Data Port High
 TFT_16bit_WR: Write signal pin
 TFT_16bit_RD: Read signal pin
 TFT_16bit_CS: Chip Select signal pin
 TFT_16bit_RS: Register Select signal pin
 TFT_16bit_RST: Reset signal pin

 TFT_16bit_DataPort_Direction_Lo: Direction of Data Port Low


 TFT_16bit_DataPort_Direction_Hi: Direction of Data Port High
 TFT_16bit_WR_Direction: Direction of Write signal pin
 TFT_16bit_RD_Direction: Direction of Read signal pin
 TFT_16bit_CS_Direction: Direction of Chip Select signal pin
 TFT_16bit_RS_Direction: Direction of Register Select signal pin
 TFT_16bit_RST_Direction: Direction of Reset signal pin
must be defined before using this function.

Example // TFT display connections


char TFT_16bit_DataPort_Lo at LATB;
char TFT_16bit_DataPort_Hi at LATC;
sbit TFT_16bit_WR at LATE1_bit;
sbit TFT_16bit_RD at LATE0_bit;
sbit TFT_16bit_CS at LATG3_bit;
sbit TFT_16bit_RS at LATH6_bit;
sbit TFT_16bit_RST at LATH4_bit;

char TFT_16bit_DataPort_Lo_Direction at TRISB;


char TFT_16bit_DataPort_Hi_Direction at TRISC;
sbit TFT_16bit_WR_Direction : at TRISE1_bit;
sbit TFT_16bit_RD_Direction at TRISE0_bit;
sbit TFT_16bit_CS_Direction at TRISG3_bit;
sbit TFT_16bit_RS_Direction at TRISH6_bit;
sbit TFT_16bit_RST_Direction at TRISH4_bit;
// End of TFT display connections

// Initialize 240x320 TFT display


TFT_Init_ILI9342(240, 320);

TFT_Init_ILI9481

Prototype void TFT_Init_ILI9481(unsigned int display_width, unsigned


char display_height);

Returns Nothing.

www.raguvaran.puzl.com
Description Initializes ILI9481 display controller in 16-bit working mode.

Parameters :

 width: width of the TFT display.


 height: height of the TFT display.

Requires Global variables :

 TFT_16bit_DataPort_Lo: Data Port Low


 TFT_16bit_DataPort_Hi: Data Port High
 TFT_16bit_WR: Write signal pin
 TFT_16bit_RD: Read signal pin
 TFT_16bit_CS: Chip Select signal pin
 TFT_16bit_RS: Register Select signal pin
 TFT_16bit_RST: Reset signal pin

 TFT_16bit_DataPort_Direction_Lo: Direction of Data Port Low


 TFT_16bit_DataPort_Direction_Hi: Direction of Data Port High
 TFT_16bit_WR_Direction: Direction of Write signal pin
 TFT_16bit_RD_Direction: Direction of Read signal pin
 TFT_16bit_CS_Direction: Direction of Chip Select signal pin
 TFT_16bit_RS_Direction: Direction of Register Select signal pin
 TFT_16bit_RST_Direction: Direction of Reset signal pin
must be defined before using this function.

Example // TFT display connections


char TFT_16bit_DataPort_Lo at LATB;
char TFT_16bit_DataPort_Hi at LATC;
sbit TFT_16bit_WR at LATE1_bit;
sbit TFT_16bit_RD at LATE0_bit;
sbit TFT_16bit_CS at LATG3_bit;
sbit TFT_16bit_RS at LATH6_bit;
sbit TFT_16bit_RST at LATH4_bit;

char TFT_16bit_DataPort_Lo_Direction at TRISB;


char TFT_16bit_DataPort_Hi_Direction at TRISC;
sbit TFT_16bit_WR_Direction : at TRISE1_bit;
sbit TFT_16bit_RD_Direction at TRISE0_bit;
sbit TFT_16bit_CS_Direction at TRISG3_bit;
sbit TFT_16bit_RS_Direction at TRISH6_bit;
sbit TFT_16bit_RST_Direction at TRISH4_bit;
// End of TFT display connections

// Initialize 240x320 TFT display


TFT_Init_ILI9481(240, 320);

TFT_16bit_Set_Index

Prototype void TFT_16bit_Set_Index(unsigned short index);

Returns Nothing.

Description Accesses register space of the controller and sets the desired register.

www.raguvaran.puzl.com
Parameters :

 index: desired register number.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example // Access register at the location 0x02


TFT_16bit_Set_Index(0x02);

TFT_16bit_Write_Command

Prototype void TFT_16bit_Write_Command(unsigned short cmd);

Returns Nothing.

Description Accesses data space and writes a command.

Parameters :

 cmd: command to be written.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example // Write a command


TFT_16bit_Write_Command(0x02);

TFT_16bit_Write_Data

Prototype void TFT_16bit_Write_Data(unsigned int _data);

Returns Nothing.

Description Writes date into display memory.

Parameters :

 _data:data to be written.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example // Send data


TFT_16bit_Write_Data(0x02);

TFT_16bit_Set_Reg

Prototype void TFT_16bit_Set_Reg(unsigned short index, unsigned short value);

www.raguvaran.puzl.com
Returns Nothing.

Description Accesses register space of the controller and writes a value in the desired register.

Parameters :

 index: desired register.


 value: value to be written.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example // 65K Color Selection


TFT_16bit_Set_Reg(0x17, 0x05);

TFT_16bit_Set_Ext_Buffer

Prototype void TFT_16bit_Set_Ext_Buffer(char* (*getExtDataPtr)(unsigned


long offset, unsigned long count, unsigned long* num));

Returns Nothing.

Description Function sets pointer to the user function which manipulates the external resource.

Parameters :

 offset - offset from the beginning of the resource from where the data is requested.
 count - requested number of bytes.
 num - variable for holding the returned number of bytes (less or equal to the number of acquired
bytes).

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example char* ReadExternalBuffer(unsigned long offset, unsigned int count, unsigned int
*num){
unsigned long start_sector;
unsigned int pos;

start_sector = Mmc_Get_File_Write_Sector() + offset/512;


pos = (unsigned long)offset%512;

if(start_sector == currentSector+1){
Mmc_Multi_Read_Buffer(EXT_BUFFER);
currentSector = start_sector;
}else
if(start_sector != currentSector){
Mmc_Multi_Read_Stop();
Mmc_Multi_Read_Start(start_sector);
Mmc_Multi_Read_Buffer(EXT_BUFFER);
currentSector = start_sector;
}

if(count>512-pos){
*num = 512-pos;
}

www.raguvaran.puzl.com
else
*num = count;

return EXT_BUFFER+pos;
}

TFT_16bit_Set_Ext_Buffer(ReadExternalBuffer);

TFT_16bit_Set_Active

Prototype void TFT_16bit_Set_Active(void (*Set_Index_Ptr)(unsigned


short), void (*Write_Command_Ptr)(unsigned
short), void (*Write_Data_Ptr)(unsigned int));

Returns Nothing.

Description This function sets appropriate pointers to a user-defined basic routines in order to enable multiple working modes.

Parameters :

 Set_Index_Ptr: Set_Index handler.


 Write_Command_Ptr: _Write_Command handler.
 Write_Data_Ptr: Write_Data handler.

Requires None.

Example Please see controller's datasheet for working mode descriptions.

void Set_Index(unsigned short index) {


// Set Index
}

void Write_Command(unsigned short cmd) {


// Write Command
}

void Write_Data(unsigned int _data) {


// Write Data
}

void main(){
...
TFT_Set_Active(Set_Index,Write_Command,Write_Data);
TFT_Init_HX8352A (320, 240);
...
}

TFT_16bit_Set_Default_Mode

Prototype void TFT_16bit_Set_Default_Mode();

Returns Nothing.

www.raguvaran.puzl.com
Description This function sets TFT in default working mode.

Parameters :

 None.

Requires None.

Example TFT_16bit_Set_Default_Mode();
TFT_Init_HX8352A(320, 240);

TFT_16bit_Set_Font

Prototype void TFT_16bit_Set_Font(const char far *activeFont, unsigned


int font_color, char font_orientation);

Returns Nothing.

Description Sets font, its color and font orientation.

Parameters :

 activeFont: desired font. Currently, only TFT_16bit_defaultFont (Tahoma14x16) is


supported.
 font_color: sets font color :

Value Description

CL_AQUA_16bit Aqua color

CL_BLACK_16bit Black color

CL_BLUE_16bit Blue color

CL_FUCHSIA_16bit Fuchsia color

CL_GRAY_16bit Gray color

CL_GREEN_16bit Green color

CL_LIME_16bit Lime color

CL_MAROON_16bit Maroon color

CL_NAVY_16bit Navy color

CL_OLIVE_16bit Olive color

CL_PURPLE_16bit Purple color

www.raguvaran.puzl.com
CL_RED_16bit Red color

CL_SILVER_16bit Silver color

CL_TEAL_16bit Teal color

CL_WHITE_16bit White color

CL_YELLOW_16bit Yellow color

 font_orientation: sets font orientation :

Value Description

FO_HORIZONTAL_16bit Horizontal orientation

FO_VERTICAL_16bit Vertical orientation

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_16bit_Set_Font(TFT_16bit_defaultFont, CL_BLACK_16bit, FO_HORIZONTAL_16bit);

TFT_16bit_Set_Ext_Font

Prototype void TFT_16bit_Set_Ext_Font(unsigned long *activeFont, unsigned


int font_color, char font_orientation);

Returns Nothing.

Description Sets font, its color and font orientation. Font is located in an external resource

Parameters :

 activeFont: desired font. This parameter represents the address in the exteral resource from
where the font data begins.
 font_color: sets font color :

Value Description

CL_AQUA_16bit Aqua color

CL_BLACK_16bit Black color

CL_BLUE_16bit Blue color

CL_FUCHSIA_16bit Fuchsia color

CL_GRAY_16bit Gray color

www.raguvaran.puzl.com
CL_GREEN_16bit Green color

CL_LIME_16bit Lime color

CL_MAROON_16bit Maroon color

CL_NAVY_16bit Navy color

CL_OLIVE_16bit Olive color

CL_PURPLE_16bit Purple color

CL_RED_16bit Red color

CL_SILVER_16bit Silver color

CL_TEAL_16bit Teal color

CL_WHITE_16bit/td> White color

CL_YELLOW_16bit Yellow color

 font_orientation: sets font orientation :

Value Description

FO_HORIZONTAL_16bit Horizontal orientation

FO_VERTICAL_16bit Vertical orientation

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_16bit_Set_Ext_Font(173296, CL_BLACK_16bit, FO_HORIZONTAL_16bit);

TFT_16bit_Write_Char

Prototype void TFT_16bit_Write_Char(unsigned int c, unsigned int x, unsigned int y);

Returns Nothing.

Description Writes a char on the TFT at coordinates (x, y).

 c: char to be written.
 x: char position on x-axis.
 y: char position on y-axis.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_16bit_Write_Char('A',22,23,);

www.raguvaran.puzl.com
TFT_16bit_Write_Text

Prototype void TFT_16bit_Write_Text(unsigned char *text, unsigned int x, unsigned


int y);

Returns Nothing.

Description Writes text on the TFT at coordinates (x, y).

Parameters :

 text: text to be written.


 x: text position on x-axis.
 y: text position on y-axis.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_16bit_Write_Text("TFT 16-bit Library DEMO, WELCOME !", 0, 0,);

TFT_16bit_Write_Const_Text

Prototype void TFT_16bit_Write_Const_Text(const far char *text, unsigned


int x, unsigned int y);

Returns Nothing.

Description Writes text located in the program memory on the TFT at coordinates (x, y).

Parameters :

 text: text to be written.


 x: text position on x-axis.
 y: text position on y-axis.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example const char ctext[] = "mikroElektronika";


...
TFT_16bit_Write_Const_Text(ctext, 0, 0,);

TFT_16bit_Fill_Screen

Prototype void TFT_16bit_Fill_Screen(unsigned int color);

Returns Nothing.

Description Fills screen memory block with given color.

www.raguvaran.puzl.com
Parameters :

 color: color to be filled :

Value Description

CL_AQUA_16bit Aqua color

CL_BLACK_16bit Black color

CL_BLUE_16bit Blue color

CL_FUCHSIA_16bit Fuchsia color

CL_GRAY_16bit Gray color

CL_GREEN_16bit Green color

CL_LIME_16bit Lime color

CL_MAROON_16bit Maroon color

CL_NAVY_16bit Navy color

CL_OLIVE_16bit Olive color

CL_PURPLE_16bit Purple color

CL_RED_16bit Red color

CL_SILVER_16bit Silver color

CL_TEAL_16bit Teal color

CL_WHITE_16bit White color

CL_YELLOW_16bit Yellow color

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_16bit_Fill_Screen(CL_BLACK_16bit);

TFT_16bit_Dot

Prototype void TFT_16bit_Dot(int x, int y, unsigned int color);

Returns Nothing.

Description Draws a dot on the TFT at coordinates (x, y).

www.raguvaran.puzl.com
Parameters :

 x: dot position on x-axis.


 y: dot position on y-axis.
 color: color parameter. Valid values :

Value Description

CL_AQUA_16bit Aqua color

CL_BLACK_16bit Black color

CL_BLUE_16bit Blue color

CL_FUCHSIA_16bit Fuchsia color

CL_GRAY_16bit Gray color

CL_GREEN_16bit Green color

CL_LIME_16bit Lime color

CL_MAROON_16bit Maroon color

CL_NAVY_16bit Navy color

CL_OLIVE_16bit Olive color

CL_PURPLE_16bit Purple color

CL_RED_16bit Red color

CL_SILVER_16bit Silver color

CL_TEAL_16bit Teal color

CL_WHITE_16bit White color

CL_YELLOW_16bit Yellow color

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_16bit_Dot(50, 50, CL_BLACK_16bit);

TFT_16bit_Set_Pen

Prototype void TFT_16bit_Set_Pen(unsigned int pen_color, char pen_width);

Returns Nothing.

www.raguvaran.puzl.com
Description Sets color and thickness parameter for drawing line, circle and rectangle elements.

Parameters :

 pen_color: Sets color.

Value Description

CL_AQUA_16bit Aqua color

CL_BLACK_16bit Black color

CL_BLUE_16bit Blue color

CL_FUCHSIA_16bit Fuchsia color

CL_GRAY_16bit Gray color

CL_GREEN_16bit Green color

CL_LIME_16bit Lime color

CL_MAROON_16bit Maroon color

CL_NAVY_16bit Navy color

CL_OLIVE_16bit Olive color

CL_PURPLE_16bit Purple color

CL_RED_16bit Red color

CL_SILVER_16bit Silver color

CL_TEAL_16bit Teal color

CL_WHITE_16bit White color

CL_YELLOW_16bit Yellow color

 pen_width: sets thickness.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_16bit_Set_Pen(CL_BLACK_16bit, 10);

TFT_16bit_Set_Brush

Prototype void TFT_16bit_Set_Brush(char brush_enabled, unsigned

www.raguvaran.puzl.com
int brush_color, char gradient_enabled, char gradient_orientation, unsigned
intgradient_color_from, unsigned int gradient_color_to);

Returns Nothing.

Description Sets color and gradient which will be used to fill circles or rectangles.

Parameters :

 brush_enabled: enable brush fill.

Value Description

1 Enable brush fill.

0 Disable brush fill.

 brush_color: set brush fill color.

Value Description

CL_AQUA_16bit Aqua color

CL_BLACK_16bit Black color

CL_BLUE_16bit Blue color

CL_FUCHSIA_16bit Fuchsia color

CL_GRAY_16bit Gray color

CL_GREEN_16bit Green color

CL_LIME_16bit Lime color

CL_MAROON_16bit Maroon color

CL_NAVY_16bit Navy color

CL_OLIVE_16bit Olive color

CL_PURPLE_16bit Purple color

CL_RED_16bit Red color

CL_SILVER_16bit Silver color

CL_TEAL_16bit Teal color

CL_WHITE_16bit White color

www.raguvaran.puzl.com
CL_YELLOW_16bit Yellow color

 gradient_enabled: enable gradient

Value Description

1 Enable gradient.

0 Disable gradient.

 gradient_orientation: sets gradient orientation :

Value Description

LEFT_TO_RIGHT_16bit Left to right gradient orientation

TOP_TO_BOTTOM<_16bit/td> Top to bottom gradient orientation

 gradient_color_from: sets the starting gradient color.

Value Description

CL_AQUA_16bit Aqua color

CL_BLACK_16bit Black color

CL_BLUE_16bit Blue color

CL_FUCHSIA_16bit Fuchsia color

CL_GRAY_16bit Gray color

CL_GREEN_16bit Green color

CL_LIME_16bit Lime color

CL_MAROON_16bit Maroon color

CL_NAVY_16bit Navy color

CL_OLIVE_16bit Olive color

CL_PURPLE_16bit Purple color

CL_RED_16bit Red color

CL_SILVER_16bit Silver color

CL_TEAL_16bit Teal color

CL_WHITE_16bit White color

CL_YELLOW_16bit Yellow color

 gradient_color_to: sets the ending gradient color.

www.raguvaran.puzl.com
Value Description

CL_AQUA_16bit Aqua color

CL_BLACK_16bit Black color

CL_BLUE_16bit Blue color

CL_FUCHSIA_16bit Fuchsia color

CL_GRAY_16bit Gray color

CL_GREEN_16bit Green color

CL_LIME_16bit Lime color

CL_MAROON_16bit Maroon color

CL_NAVY_16bit Navy color

CL_OLIVE_16bit Olive color

CL_PURPLE_16bit Purple color

CL_RED_16bit Red color

CL_SILVER_16bit Silver color

CL_TEAL_16bit Teal color

CL_WHITE_16bit White color

CL_YELLOW_16bit Yellow color

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example // Enable gradient from black to white color, left-right orientation


TFT_16bit_Set_Brush(0, 0, 1, LEFT_TO_RIGHT_16bit, CL_BLACK_16bit, CL_WHITE_16bit);

TFT_16bit_Line

Prototype void TFT_16bit_Line(int x1, int y1, int x2, int y2);

Returns Nothing.

Description Draws a line from (x1, y1) to (x2, y2).

www.raguvaran.puzl.com
Parameters :

 x1: x coordinate of the line start.


 y1: y coordinate of the line end.
 x2: x coordinate of the line start.
 y2: y coordinate of the line end.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_16bit_Line(0, 0, 239, 127);

TFT_16bit_H_Line

Prototype void TFT_16bit_H_Line(int x_start, int x_end, int y_pos);

Returns Nothing.

Description Draws a horizontal line on TFT.

Parameters :

 x_start: x coordinate of the line start.


 x_end: x coordinate of the line end.
 y_pos: y coordinate of horizontal line.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example // Draw a horizontal line between dots (10,20) and (50,20)


TFT_16bit_H_Line(10, 50, 20);

TFT_16bit_V_Line

Prototype void TFT_16bit_V_Line(int y_start, int y_end, int x_pos);

Returns Nothing.

Description Draws a vertical line on TFT.

Parameters :

 y_start: y coordinate of the line start.


 y_end: y coordinate of the line end.
 x_pos: x coordinate of vertical line.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example // Draw a vertical line between dots (10,5) and (10,25)


TFT_16bit_V_Line(5, 25, 10);

www.raguvaran.puzl.com
TFT_16bit_Rectangle

Prototyp void TFT_16bit_Rectangle(int x_upper_left, int y_upper_left, int x_bottom_righ


e t, int y_bottom_right);

Returns Nothing.

Descript Draws a rectangle on TFT.


ion
Parameters :

 x_upper_left: x coordinate of the upper left rectangle corner.


 y_upper_left: y coordinate of the upper left rectangle corner.
 x_bottom_right: x coordinate of the lower right rectangle corner.
 y_bottom_right: y coordinate of the lower right rectangle corner.

Require TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
s

Example TFT_16bit_Rectangle(20, 20, 219, 107);

TFT_16bit_Rectangle_Round_Edges

Prototype void TFT_16bit_Rectangle_Round_Edges(unsigned int x_upper_left, unsigned


int y_upper_left, unsigned int x_bottom_right, unsigned
inty_bottom_right, unsigned int round_radius);

Returns Nothing.

Description Draws a rounded edge rectangle on TFT.

Parameters :

 x_upper_left: x coordinate of the upper left rectangle corner.


 y_upper_left: y coordinate of the upper left rectangle corner.
 x_bottom_right: x coordinate of the lower right rectangle corner.
 y_bottom_right: y coordinate of the lower right rectangle corner.
 round_radius: radius of the rounded edge.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_16bit_Rectangle_Round_Edges(20, 20, 219, 107, 12);

TFT_16bit_Circle

Prototype void TFT_16bit_Circle(int x_center, int y_center, int radius);

www.raguvaran.puzl.com
Returns Nothing.

Description Draws a circle on TFT.

Parameters :

 x: x coordinate of the circle center.


 y: y coordinate of the circle center.
 r: radius size.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_16bit_Circle(120, 64, 110);

TFT_16bit_Image

Prototype void TFT_16bit_Image(unsigned int left, unsigned int top, code const far
unsigned short * image, unsigned short stretch);

Returns Nothing.

Description Displays an image on a desired location.

Parameters :

 left: position of the image's left edge.


 top:position of the image's top edge.
 image: image to be displayed. Bitmap array is located in code memory.
 stretch: stretches image by a given factor (if 2, it will double the image.).

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_16bit_Image(0, 0, image, 1);

TFT_16bit_Ext_Image

Prototype void TFT_16bit_Ext_Image(unsigned int left, unsigned int top, unsigned


long image, unsigned short stretch);

Returns Nothing.

Description Displays an image from an external resource on a desired address.

Parameters :

 left: position of the image's left edge.


 top:position of the image's top edge.

www.raguvaran.puzl.com
 image: image to be displayed. This parameter represents the address in the exteral resource from
where the image data begins.
 stretch: stretches image by a given factor (if 2, it will double the image.).

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_16bit_Image(0, 0, 153608, 1);

TFT_16bit_Partial_Image

Prototype void TFT_16bit_Partial_Image(unsigned int left, unsigned int top, unsigned


int width, unsigned int height, code const far unsigned short *
image,unsigned short stretch);

Returns Nothing.

Description Displays a partial area of the image on a desired location.

Parameters :

 left: left coordinate of the image.


 top: top coordinate of the image.
 width: desired image width.
 height: desired image height.
 image: image to be displayed. Bitmap array is located in code memory.
 stretch: stretches image by a given factor (if 2, it will double the image.).

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example // Draws a 10x15 part of the image starting from the upper left corner on the
coordinate (10,12)
TFT_16bit_Partial_Image(10, 12, 10, 15, image, 1);

TFT_16bit_Ext_Partial_Image

Prototype void TFT_16bit_Ext_Partial_Image(unsigned int left, unsigned


int top, unsigned int width, unsigned int height, unsigned
long image, unsigned shortstretch);

Returns Nothing.

Description Displays a partial area of the image, located on an external resource, on a desired location of the screen.

Parameters :

 left: left coordinate of the image.


 top: top coordinate of the image.
 width: desired image width.
 height: desired image height.

www.raguvaran.puzl.com
 image: image to be displayed. This parameter represents the address in the exteral resource from
where the image data begins.
 stretch: stretches image by a given factor (if 2, it will double the image.).

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_16bit_Ext_Partial_Image(159,0,160,120,0,1);

TFT_16bit_Image_Jpeg

Prototype char TFT_16bit_Image_Jpeg(unsigned int left, unsigned int top, code const
far unsigned short *image);

Returns  0 - if image is loaded and displayed successfully.


 1 - if error occured.

Description Displays a JPEG image on a desired location.

Parameters :

 left: left coordinate of the image.


 top: top coordinate of the image.
 image: image to be displayed. Bitmap array is located in code memory.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_16bit_Image_Jpeg(0, 0, image);

TFT_16bit_RGBToColor16bit

Prototype unsigned
int TFT_16bit_RGBToColor16bit(char rgb_red, char rgb_green, char rgb_blue);

Returns Returns a color value in the following bit-order : 5 bits red, 6 bits green and 5 bits blue color.

Description Converts 5:6:5 RGB format into true color format.

Parameters :

 rgb_red: red component of the image.


 rgb_green: green component of the image.
 rgb_blue: blue component of the image.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example color16 = TFT_16bit_RGBToColor16bit(150, 193, 65);

TFT_16bit_Color16bitToRGB

www.raguvaran.puzl.com
Prototype void TFT_16bit_Color16bitToRGB(unsigned
int color, char *rgb_red, char *rgb_green, char *rgb_blue);

Returns Nothing.

Description Converts true color into 5:6:5 RGB format.

Parameters :

 color: true color to be converted.


 rgb_red: red component of the input color.
 rgb_green: green component of the input color.
 rgb_blue: blue component of the input color.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example TFT_16bit_Color16bitToRGB(start_color, &red_start, &green_start, &blue_start);

TFT_16bit_Rotate_180

Prototype void TFT_16bit_Rotate_180(char rotate);

Returns Nothing.

Description Rotates the TFT display.

Parameters :

 rotate: parameter for rotating display. Valid values :


 0 - display will not be rotated.
 1 - display will be rotated for 180 degrees.

Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.

Example // Rotate TFT display for 180 degrees


TFT_16bit_Rotate_180(1);

// Initialize TFT display


TFT_Init_HX8352A(240, 320);

Touch Panel Library


The mikroC PRO for PIC provides a library for working with Touch Panel.

www.raguvaran.puzl.com
Library Dependency Tree

External dependencies of Touch Panel Library


The following
variables must be
Description
defined in all Example :
:
projects using Touch
Panel Library:
extern sfr
DriveA line. sbit DriveA at RC0_bit;
sbit DriveA;

extern sfr
DriveB line. sbit DriveB at RC1_bit;
sbit DriveB;

Direction of
extern sfr
the DriveA sbit DriveA_Direction at TRISC0_bit;
sbit DriveA_Direction;
pin.

Direction of
extern sfr
the DriveB sbit DriveB_Direction at TRISC1_bit;
sbit DriveB_Direction;
pin.

Library Routines
 TP_Init
 TP_Set_ADC_Threshold
 TP_Press_Detect
 TP_Get_Coordinates
 TP_Calibrate_Bottom_Left
 TP_Calibrate_Upper_Right
 TP_Get_Calibration_Consts
 TP_Set_Calibration_Consts

TP_Init

Prototype void TP_Init(unsigned int display_width, unsigned


int display_height, char readX_ChNo, char readY_ChNo);

Description Initialize touch panel display. Default touch panel ADC threshold value is set to 3900.

Parameters  display_width: set display width.


 display_height: set display height.
 readX_ChNo: read X coordinate from desired ADC channel.
 readY_ChNo: read Y coordinate from desired ADC channel.

Returns Nothing.

Requires Before calling this function initialize ADC module.

Example ADC_Init(); // Initalize ADC module

www.raguvaran.puzl.com
TP_Init(128, 64, 6, 7); // Initialize touch panel, dimensions 128x64

TP_Set_ADC_Threshold

Prototype void TP_Set_ADC_Threshold(unsigned int threshold);

Description Set custom ADC threshold value, call this function after TP_Init.

Parameters  threshold: custom ADC threshold value.

Returns Nothing.

Requires TP_Init has to be called before using this routine.

Example TP_Set_ADC_Threshold(3900); // Set touch panel ADC threshold

TP_Press_Detect

Prototype char TP_Press_Detect();

Description Detects if the touch panel has been pressed.

Parameters None.

Returns  1 - if touch panel is pressed.


 0 - otherwise.

Requires Global variables :

 DriveA: DriveA.
 DriveB: DriveB.
 DriveA_Direction: Direction of DriveA pin.
 DriveB_Direction: Direction of DriveB pin.
must be defined before using this function.

Example // Touch Panel module connections


sbit DriveA at RC0_bit;
sbit DriveB at RC1_bit;
sbit DriveA_Direction at TRISC0_bit;
sbit DriveB_Direction at TRISC1_bit;
// End Touch Panel module connections

if (TP_Press_Detect()) {
...
}

TP_Get_Coordinates

www.raguvaran.puzl.com
Prototype char TP_Get_Coordinates(unsigned int *x_coordinate, unsigned
int *y_coordinate);

Description Get touch panel coordinates and store them


in x_coordinate and y_coordinate parameters.

Parameters  x_coordinate: x coordinate of the place of touch.


 y_coordinate: y coordinate of the place of touch.

Returns  0 - if reading is within display dimension range.


 1 - if reading is out of display dimension range.

Requires Nothing.

Example if (TP_Get_Coordinates(&x_coord, &y_coord) == 0) {


...
}

TP_Calibrate_Bottom_Left

Prototype void TP_Calibrate_Bottom_Left();

Description Calibrate bottom left corner of the touch Panel.

Parameters None.

Returns Nothing.

Requires Nothing.

Example TP_Calibrate_Bottom_Left(); // Calibration of bottom left corner

TP_Calibrate_Upper_Right

Prototype void TP_Calibrate_Upper_Right();

Description Calibrate upper right corner of the touch panel.

Parameters None.

www.raguvaran.puzl.com
Returns Nothing.

Requires Nothing.

Example TP_Calibrate_Upper_Right(); // Calibration of upper right corner

TP_Get_Calibration_Consts

Prototype void TP_Get_Calibration_Consts(unsigned int *x_min, unsigned


int *x_max, unsigned int *y_min, unsigned int *y_max);

Description Gets calibration constants after calibration is done and stores them
in x_min, x_max, y_min and y_max parameters.

Parameters  x_min: x coordinate of the bottom left corner of the working area.
 x_max: x coordinate of the upper right corner of the working area.
 y_min: y coordinate of the bottom left corner of the working area.
 y_max: y coordinate of the upper right corner of the working area.

Returns Nothing.

Requires Nothing.

Example TP_Get_Calibration_Consts(&x_min, &y_min, &x_max, &y_max); // Get calibration


constants

TP_Set_Calibration_Consts

Prototype void TP_Set_Calibration_Consts(unsigned int x_min, unsigned


int x_max, unsigned int y_min, unsigned int y_max);

Description Sets calibration constants.

Parameters  x_min: x coordinate of the bottom left corner of the working area.
 x_max: x coordinate of the upper right corner of the working area.
 y_min: y coordinate of the bottom left corner of the working area.
 y_max: y coordinate of the upper right corner of the working area.

Returns Nothing.

Requires Nothing.

www.raguvaran.puzl.com
Example TP_Set_Calibration_Consts(148, 3590, 519, 3370); // Set calibration constants

Library Example
The following drawing demo tests routines of the Touch Panel library :

Copy Code To Clipboard

// Glcd module connections


char GLCD_DataPort at PORTD;

sbit GLCD_CS1 at RB0_bit;


sbit GLCD_CS2 at RB1_bit;
sbit GLCD_RS at RB2_bit;
sbit GLCD_RW at RB3_bit;
sbit GLCD_EN at RB4_bit;
sbit GLCD_RST at RB5_bit;

sbit GLCD_CS1_Direction at TRISB0_bit;


sbit GLCD_CS2_Direction at TRISB1_bit;
sbit GLCD_RS_Direction at TRISB2_bit;
sbit GLCD_RW_Direction at TRISB3_bit;
sbit GLCD_EN_Direction at TRISB4_bit;
sbit GLCD_RST_Direction at TRISB5_bit;
// End Glcd module connections

// Touch Panel module connections


sbit DriveA at RC0_bit;
sbit DriveB at RC1_bit;
sbit DriveA_Direction at TRISC0_bit;
sbit DriveB_Direction at TRISC1_bit;
// End Touch Panel module connections

bit write_erase;
char pen_size;
char write_msg[] = "WRITE"; // GLCD menu messages
char clear_msg[] = "CLEAR";
char erase_msg[] = "ERASE";
unsigned int x_coord, y_coord;

void Initialize() {
DriveA_Direction = 0; // Set DriveA pin as output
DriveB_Direction = 0; // Set DriveB pin as output
ANSEL = 3; // Configure AN0 and AN1 pins as analog
inputs
ANSELH = 0; // and other AN pins as digital I/O
TRISA = 3;

C1ON_bit = 0; // Disable comparators


C2ON_bit = 0;

Glcd_Init(); // Initialize GLCD


Glcd_Fill(0); // Clear GLCD

ADC_Init(); // Initialize ADC


TP_Init(128, 64, 0, 1); // Initialize touch panel
TP_Set_ADC_Threshold(900); // Set touch panel ADC threshold
}

void Calibrate() {

Glcd_Dot(0,63,1); // Draw bottom left dot


Glcd_Write_Text("TOUCH BOTTOM LEFT",12,3,1);
TP_Calibrate_Bottom_Left(); // Calibration of bottom left corner

www.raguvaran.puzl.com
Delay_ms(1000);

Glcd_Dot(0,63,0); // Clear bottom left dot


Glcd_Dot(127,0,1); // Draw upper right dot
Glcd_Write_Text(" ",12,3,1);
Glcd_Write_Text("TOUCH UPPER RIGHT",12,4,1);
TP_Calibrate_Upper_Right(); // Calibration of upper right corner

Delay_ms(1000);
}

void main() {

Initialize();

Glcd_Write_Text("CALIBRATION",32,3,1);
Delay_ms(1000);
Glcd_Fill(0); // Clear GLCD
Calibrate();

Glcd_Fill(0);
Glcd_Write_Text("WRITE ON SCREEN", 20, 5, 1) ;
Delay_ms(1000);

Glcd_Fill(0); // Clear GLCD


Glcd_V_Line(0,7,0,1);
Glcd_Write_Text(clear_msg,1,0,0);
Glcd_V_Line(0,7,97,1);
Glcd_Write_Text(erase_msg,98,0,0);

// Pen Menu:
Glcd_Rectangle(41,0,52,9,1);
Glcd_Box(45,3,48,6,1);
Glcd_Rectangle(63,0,70,7,1);
Glcd_Box(66,3,67,4,1);
Glcd_Rectangle(80,0,86,6,1);
Glcd_Dot(83,3,1);

write_erase = 1;
pen_size = 1;
while (1) {

if (TP_Press_Detect()) {
// After a PRESS is detected read X-Y and convert it to 128x64 space
if (TP_Get_Coordinates(&x_coord, &y_coord) == 0) {

if ((x_coord < 31) && (y_coord < 8)) {

Glcd_Fill(0);

// Pen Menu:
Glcd_Rectangle(41,0,52,9,1);
Glcd_Box(45,3,48,6,1);
Glcd_Rectangle(63,0,70,7,1);
Glcd_Box(66,3,67,4,1);
Glcd_Rectangle(80,0,86,6,1);
Glcd_Dot(83,3,1);

Glcd_V_Line(0,7,0,1);
Glcd_Write_Text(clear_msg,1,0,0);
Glcd_V_Line(0,7,97,1);
if (write_erase)
Glcd_Write_Text(erase_msg,98,0,0);
else
Glcd_Write_Text(write_msg,98,0,0);
}

www.raguvaran.puzl.com
// If write/erase is pressed
if ((x_coord > 96) && (y_coord < 8)) {
if (write_erase) {
write_erase = 0;
Glcd_Write_Text(write_msg,98,0,0);
Delay_ms(500);
}
else {
write_erase = 1;
Glcd_Write_Text(erase_msg,98,0,0);
Delay_ms(500);
}
}

// If pen size is selected


if ((x_coord >= 41) && (x_coord <= 52) && (y_coord <= 9))
pen_size = 3;

if ((x_coord >= 63) && (x_coord <= 70) && (y_coord <= 7))
pen_size = 2;

if ((x_coord >= 80) && (x_coord <= 86) && (y_coord <= 6))
pen_size = 1;

if (y_coord < 11)


continue;

switch (pen_size) {
case 1 : {
if ( (x_coord >= 0) && (y_coord >= 0) && (x_coord <= 127) && (y_coord <= 63)
)
Glcd_Dot(x_coord, y_coord, write_erase);
break;
}
case 2 : {
if ( (x_coord >= 0) && (y_coord >= 0) && (x_coord <= 127-1) && (y_coord <=
63-1) )
Glcd_Box(x_coord, y_coord, x_coord + 1, y_coord + 1, write_erase);
break;
}
case 3 : {
if ( (x_coord >= 1) && (y_coord >= 1) && (x_coord <= 127-2) && (y_coord <=
63-2) )
Glcd_Box(x_coord-1, y_coord-1, x_coord + 2, y_coord + 2, write_erase);
break;
}
}
}
}
}
}

UART Library
The UART hardware module is available with a number of PIC compliant MCUs. The mikroC PRO for
PIC UART Library provides comfortable work with the Asynchronous (full duplex) mode.

You can easily communicate with other devices via RS-232 protocol (for example with PC, see the figure
at the end of the topic – RS-232 HW connection). You need a PIC MCU with hardware integrated UART,
for example 16F887. Then, simply use the functions listed below.

www.raguvaran.puzl.com
Important :

 UART library routines require you to specify the module you want to use. To select the
desired UART module, simply change the letter x in the routine prototype for a number
from 1 to2.
 Switching between the UART modules in the UART library is done by
the UART_Set_Active function (UART modules have to be previously initialized).
 Number of UART modules per MCU differs from chip to chip. Please, read the appropriate
datasheet before utilizing this library.

Library Routines
 UARTx_Init
 UARTx_Data_Ready
 UARTx_Tx_Idle
 UARTx_Read
 UARTx_Read_Text
 UARTx_Write
 UARTx_Write_Text
 UART_Set_Active

Generic Routines
 UART_Data_Ready
 UART_Tx_Idle
 UART_Read
 UART_Read_Text
 UART_Write
 UART_Write_Text

UARTx_Init

Prototype void UARTx_Init(const unsigned long baud_rate);

Returns Nothing.

Description Initializes desired hardware UART module with the desired baud rate. Refer to the
device data sheet for baud rates allowed for specific Fosc. If you specify the
unsupported baud rate, compiler will report an error.

Requires You need PIC MCU with hardware UART.


UARTx_Init needs to be called before using other functions from UART Library.
Parameters :

 baud_rate: requested baud rate


Refer to the device data sheet for baud rates allowed for specific Fosc.

Note : Calculation of the UART baud rate value is carried out by the compiler, as
it would produce a relatively large code if performed on the library level.
Therefore, compiler needs to know the value of the parameter in the compile time.

www.raguvaran.puzl.com
That is why this parameter needs to be a constant, and not a variable.

Example // Initialize hardware UART1 and establish communication at 9600 bps


UART1_Init(9600);

UARTx_Data_Ready

Prototype char UARTx_Data_Ready();

Returns  1 if data is ready for reading


 0 if there is no data in the receive register

Description Use the function to test if data in receive buffer is ready for reading.

Requires UART HW module must be initialized and communication established before using this
function. See UARTx_Init.

Example // If data is ready, read it:


if (UART1_Data_Ready() == 1) {
receive = UART1_Read();
}

UARTx_Tx_Idle

Prototype char UARTx_Tx_Idle();

Returns  1 if the data has been transmitted


 0 otherwise

Description Use the function to test if the transmit shift register is empty or not.

Requires UART HW module must be initialized and communication established before using this
function. See UARTx_Init.

Example // If the previous data has been shifted out, send next data:
if (UART1_Tx_Idle() == 1) {
UART1_Write(_data);
}

UARTx_Read

Prototype char UARTx_Read();

www.raguvaran.puzl.com
Returns Returns the received byte.

Description Function receives a byte via UART. Use the function UARTx_Data_Ready to test if data
is ready first.

Requires UART HW module must be initialized and communication established before using this
function. See UARTx_Init.

Example // If data is ready, read it:


if (UART1_Data_Ready() == 1) {
receive = UART1_Read();
}

UARTx_Read_Text

Prototype void UARTx_Read_Text(char *Output, char *Delimiter, char Attempts);

Returns Nothing.

Description Reads characters received via UART until the delimiter sequence is detected. The read
sequence is stored in the parameter output; delimiter sequence is stored in the
parameterdelimiter.
This is a blocking call: the delimiter sequence is expected, otherwise the procedure
exits (if the delimiter is not found).

Parameters :

 Output: received text


 Delimiter: sequence of characters that identifies the end of a received
string
 Attempts: defines number of received characters in
which Delimiter sequence is expected. If Attempts is set to 255, this
routine will continuously try to detect theDelimiter sequence.

Requires UART HW module must be initialized and communication established before using this
function. See UARTx_Init.

Example Read text until the sequence “OK” is received, and send back what’s been received:

UART1_Init(4800); // initialize UART1 module


Delay_ms(100);

while (1) {
if (UART1_Data_Ready() == 1) { // if data is received
UART1_Read_Text(output, "OK", 10); // reads text until 'OK' is found
UART1_Write_Text(output); // sends back text
}
}

UARTx_Write

www.raguvaran.puzl.com
Prototype void UARTx_Write(char data_);

Returns Nothing.

Description The function transmits a byte via the UART module.


Parameters :

 _data: data to be sent

Requires UART HW module must be initialized and communication established before using this
function. See UARTx_Init.

Example unsigned char _data = 0x1E;


...
UART1_Write(_data);

UARTx_Write_Text

Prototype void UARTx_Write_Text(char * UART_text);

Returns Nothing.

Description Sends text via UART. Text should be zero terminated.


Parameters :

 UART_text: text to be sent

Requires UART HW module must be initialized and communication established before using this
function. See UARTx_Init.

Example Read text until the sequence “OK” is received, and send back what’s been received:

UART1_Init(4800); // initialize UART1 module


Delay_ms(100);

while (1) {
if (UART1_Data_Ready() == 1) { // if data is received
UART1_Read_Text(output, "OK", 10); // reads text until 'OK' is found
UART1_Write_Text(output); // sends back text
}
}

UART_Set_Active

Prototype void UART_Set_Active(char (*read_ptr)(), void (*write_ptr)(unsigned


char data_), char (*ready_ptr)(), char (*tx_idle_ptr)())

www.raguvaran.puzl.com
Returns Nothing.

Description Sets active UART module which will be used by the UART library routines.
Parameters :

 read_ptr: UARTx_Read handler


 write_ptr: UARTx_Write handler
 ready_ptr: UARTx_Data_Ready handler
 tx_idle_ptr: UARTx_Tx_Idle handler

Requires Routine is available only for MCUs with two UART modules.
Used UART module must be initialized before using this routine.
See UARTx_Init routine

Example UART1_Init(9600); // initialize UART1 module


UART2_Init(9600); // initialize UART2 module

RS485Master_Init(); // initialize MCU as Master

UART_Set_Active(&UART1_Read, &UART1_Write, &UART1_Data_Ready, &UART1_Tx_Idle); //


set UART1 active
RS485Master_Send(dat,1,160); // send message through UART1

UART_Set_Active(&UART2_Read, &UART2_Write, &UART2_Data_Ready, &UART2_Tx_Idle); //


set UART2 active
RS485Master_Send(dat,1,160); // send through UART2

UART_Data_Ready

Prototype char UART_Data_Ready();

Returns  1 if data is ready for reading


 0 if there is no data in the receive register

Description Use the function to test if data in receive buffer is ready for reading.

This is a generic routine which uses the active UART module previously activated by
the UART_Set_Active routine.

Requires UART HW module must be initialized and communication established before using this
function. See UARTx_Init.

Example // If data is ready, read it:


if (UART_Data_Ready() == 1) {
receive = UART_Read();
}

UART_Tx_Idle

Prototype char UART_Tx_Idle();

www.raguvaran.puzl.com
Returns  1 if the data has been transmitted
 0 otherwise

Description Use the function to test if the transmit shift register is empty or not.

This is a generic routine which uses the active UART module previously activated by
the UART_Set_Active routine.

Requires UART HW module must be initialized and communication established before using this
function. See UARTx_Init.

Example // If the previous data has been shifted out, send next data:
if (UART_Tx_Idle() == 1) {
UART_Write(_data);
}

UART_Read

Prototype char UART_Read();

Returns Returns the received byte.

Description Function receives a byte via UART. Use the function UART_Data_Ready to test if data is
ready first.
This is a generic routine which uses the active UART module previously activated by
the UART_Set_Active routine.

Requires UART HW module must be initialized and communication established before using this
function. See UARTx_Init.

Example // If data is ready, read it:


if (UART_Data_Ready() == 1) {
receive = UART_Read();
}

UART_Read_Text

Prototype void UART_Read_Text(char *Output, char *Delimiter, char Attempts);

Returns Nothing.

Description Reads characters received via UART until the delimiter sequence is detected. The read
sequence is stored in the parameter output; delimiter sequence is stored in the
parameterdelimiter.
This is a blocking call: the delimiter sequence is expected, otherwise the procedure
exits (if the delimiter is not found).

www.raguvaran.puzl.com
This is a generic routine which uses the active UART module previously activated by
the UART_Set_Active routine.
Parameters :

 Output: received text


 Delimiter: sequence of characters that identifies the end of a received
string
 Attempts: defines number of received characters in
which Delimiter sequence is expected. If Attempts is set to 255, this
routine will continuously try to detect theDelimiter sequence.

Requires UART HW module must be initialized and communication established before using this
function. See UARTx_Init.

Example Read text until the sequence “OK” is received, and send back what’s been received:

UART1_Init(4800); // initialize UART1 module


Delay_ms(100);

while (1) {
if (UART_Data_Ready() == 1) { // if data is received
UART_Read_Text(output, "OK", 10); // reads text until 'OK' is found
UART_Write_Text(output); // sends back text
}
}

UART_Write

Prototype void UART_Write(char data_);

Returns Nothing.

Description The function transmits a byte via the UART module.


This is a generic routine which uses the active UART module previously activated by
the UART_Set_Active routine.
Parameters :

 _data: data to be sent

Requires UART HW module must be initialized and communication established before using this
function. See UARTx_Init.

Example unsigned char _data = 0x1E;


...
UART_Write(_data);

UART_Write_Text

Prototype void UART_Write_Text(char * UART_text);

www.raguvaran.puzl.com
Returns Nothing.

Description Sends text via UART. Text should be zero terminated.


This is a generic routine which uses the active UART module previously activated by
the UART_Set_Active routine.
Parameters :

 UART_text: text to be sent

Requires UART HW module must be initialized and communication established before using this
function. See UARTx_Init.

Example Read text until the sequence “OK” is received, and send back what’s been received:

UART1_Init(4800); // initialize UART1 module


Delay_ms(100);

while (1) {
if (UART_Data_Ready() == 1) { // if data is received
UART_Read_Text(output, "OK", 10); // reads text until 'OK' is found
UART_Write_Text(output); // sends back text
}
}

Library Example
The example demonstrates a simple data exchange via UART. When PIC MCU receives data, it
immediately sends it back. If PIC is connected to the PC (see the figure below), you can test the
example from the mikroC PRO for PIC terminal for RS-232 communication, menu
choice Tools › Terminal.
Copy Code To Clipboard

char uart_rd;

void main() {
ANSEL = 0; // Configure AN pins as digital
ANSELH = 0;

UART1_Init(9600); // Initialize UART module at 9600 bps


Delay_ms(100); // Wait for UART module to stabilize

UART1_Write_Text("Start");
UART1_Write(10);
UART1_Write(13);

while (1) { // Endless loop


if (UART1_Data_Ready()) { // If data is received,
uart_rd = UART1_Read(); // read the received data,
UART1_Write(uart_rd); // and send data via UART
}
}
}

HW Connection

www.raguvaran.puzl.com
RS-232 HW connection

UART Remappable Library


UART Remappable hardware module is available with these MCUs: 18F2xJ11, 18F4xJ11, 18F2xJ50 and
18F4xJ50. mikroC PRO for PIC UART Remappable Library provides comfortable work with the
Asynchronous (full duplex) mode.

You can easily communicate with other devices via RS-232 protocol (for example with PC, see the figure
at the end of the topic – RS-232 HW connection). Then, simply use the functions listed below.

Important : Before using this library, make sure that Peripheral Pin Select Library and Uart
Library are checked in the Library Manager, and that appropriate pins were mapped.

www.raguvaran.puzl.com
Library Dependency Tree

Library Routines
 UART_Remappable_Init
 UART_Remappable_Data_Ready
 UART_Remappable_Tx_Idle
 UART_Remappable_Read
 UART_Remappable_Read_Text
 UART_Remappable_Write
 UART_Remappable_Write_Text

UART_Remappable_Init

Prototype void UART_Remappable_Init(const unsigned long baud_rate);

Returns Nothing.

Description Initializes hardware UART Remappable module with the desired baud rate. Refer to the
device data sheet for baud rates allowed for specific Fosc. If you specify the
unsupported baud rate, compiler will report an error.
Parameters :

 baud_rate: requested baud rate

Note : Before using this library, make sure that Peripheral Pin Select Library is
checked in the Library Manager, and that appropriate pins were mapped.
Refer to the device data sheet for baud rates allowed for specific Fosc.

Requires You'll need PIC MCU with hardware UART module and remappable feature.
UART_Remappable_Init needs to be called before using other functions
from UART Remappable Library.

Note : Calculation of the UART baud rate value is carried out by the compiler, as
it would produce a relatively large code if performed on the library level.
Therefore, compiler needs to know the value of the parameter in the compile time.
That is why this parameter needs to be a constant, and not a variable.

Example This will initialize hardware UART module and establish the communication at
2400 bps:
UART_Remappable_Init(2400);

UART_Remappable_Data_Ready

Prototype unsigned short UART_Remappable_Data_Ready();

Returns Function returns 1 if data is ready or 0 if there is no data.

www.raguvaran.puzl.com
Description The function tests if data in receive buffer is ready for reading.

Requires MCU with the UART module and remappable feature.


The UART module must be initialized before using this routine. See
the UART_Remappable_Init routine.

Example // If data is ready, read it:


if (UART_Remappable_Data_Ready() == 1) {
receive = UART_Remappable_Read();
}

UART_Remappable_Tx_Idle

Prototype char UART_Remappable_Tx_Idle();

Returns  1 if the data has been transmitted


 0 otherwise

Description Use the function to test if the transmit shift register is empty or not.

Requires UART HW module must be initialized and communication established before using this
function. See UART_Remappable_Init.

Example // If the previous data has been shifted out, send next data:
if (UART_Remappable_Tx_Idle() == 1) {
UART_Remappable_Write(_data);
}

UART_Remappable_Read

Prototype unsigned short UART_Remappable_Read();

Returns Received byte.

Description The function receives a byte via UART. Use


the UART_Remappable_Data_Ready function to test if data is ready first.

Requires MCU with the UART module and remappable feature.


The UART module must be initialized before using this routine.
See UART_Remappable_Init routine.

Example // If data is ready, read it:


if (UART_Remappable_Data_Ready() == 1) {
receive = UART_Remappable_Read();
}

UART_Remappable_Read_Text

www.raguvaran.puzl.com
Prototype void UART_Remappable_Read_Text(char *Output, char *Delimiter, char Attempt
s);

Returns Nothing.

Descriptio Reads characters received via UART until the delimiter sequence is detected. The read
n sequence is stored in the parameter output; delimiter sequence is stored in the
parameterdelimiter.
This is a blocking call: the delimiter sequence is expected, otherwise the procedure
exits( if the delimiter is not found). Parameter Attempts defines number of received
characters in which Delimiter sequence is expected. If Attempts is set to 255, this
routine will continuously try to detect the Delimiter sequence.

Requires UART HW module must be initialized and communication established before using this
function. See UART_Remappable_Init.

Example Read text until the sequence “OK” is received, and send back what’s been received:

UART_Remappable_Init(4800); // initialize UART module


Delay_ms(100);

while (1) {
if (UART_Remappable_Data_Ready() == 1) { // if data is received
UART_Remappable_Read_Text(output, "OK", 10); // reads text until 'OK' is
found
UART_Remappable_Write(output); // sends back text
}
}

UART_Remappable_Write

Prototype void UART_Remappable_Write(unsigned short data_);

Returns Nothing.

Description The function transmits a byte via the UART module.


Parameters :

 TxData: data to be sent

Requires MCU with the UART module and remappable feature.


The UART module must be initialized before using this routine.
See UART_Remappable_Init routine.

Example unsigned char _data = 0x1E;


...
UART_Remappable_Write(_data);

UART_Remappable_Write_Text

www.raguvaran.puzl.com
Prototype void UART_Remappable_Write_Text (char *uart_text);

Returns Nothing.

Description Sends text (parameter uart_text) via UART. Text should be zero terminated.

Requires UART HW module must be initialized and communication established before using this
function. See UART_Remappable_Init.

Example Read text until the sequence “OK” is received, and send back what’s been received:

UART_Remappable_Init(4800); // initialize UART module


Delay_ms(100);

while (1) {
if (UART_Remappable_Data_Ready() == 1) { // if data is received
UART_Remappable_Read_Text(output, "OK", 10); // reads text until 'OK' is
found
UART_Remappable_Write(output); // sends back text
}
}

USB Library
Universal Serial Bus (USB) provides a serial bus standard for connecting a wide variety of devices,
including computers, cell phones, game consoles, PDA’s, etc.
USB Library contains HID routines that support HID class devices, and also the generic routines that can
be used with vendor specified drivers.
USB HID Class
The HID class consists primarily of devices that are used by humans to control the operation of
computer systems. Typical examples of HID class devices include :
 Keyboards and pointing devices, for example: standard mouse devices, trackballs, and
joysticks.
 Front-panel controls, for example: knobs, switches, buttons, and sliders.
 Controls that might be found on devices such as telephones, VCR remote controls, games
or simulation devices, for example: data gloves, throttles, steering wheels, and rudder
pedals.

www.raguvaran.puzl.com
 Devices that may not require human interaction but provide data in a similar format
to HID class devices, for example, bar-code readers, thermometers, or voltmeters.
Many typical HID class devices include indicators, specialized displays, audio feedback, and force or
tactile feedback. Therefore, the HID class definition includes support for various types of output directed
to the end user.

Descriptor File
Each project based on the USB library should include a descriptor source file which contains vendor id
and name, product id and name, report length, and other relevant information. To create a descriptor
file, use the integrated USB HID terminal of mikroC PRO for PIC (Tools › USB HID Terminal). The
default name for descriptor file is USBdsc.c, but you may rename it.

Important :

 The USB library routines have been changed. Please, have this in mind when migrating
projects from previous versions of the compiler.
 Also, this relates to the descriptor source file, so it is necessary to create a new descriptor
file in order to make your project work.

Library Routines
 HID_Enable
 HID_Read
 HID_Write
 HID_Disable
 USB_Interrupt_Proc
 USB_Polling_Proc
 Gen_Enable
 Gen_Read
 Gen_Write

HID_Enable

Prototype void HID_Enable(char *readbuff, char *writebuff);

Description Enables USB HID communication.

Parameters  readbuff: Read Buffer.


 writebuff: Write Buffer.
These parameters are used for HID communication.

Returns Nothing.

Requires Nothing.

Example HID_Enable(&readbuff,&writebuff);

www.raguvaran.puzl.com
Notes This function needs to be called before using other routines of USB HID Library.

HID_Read

Prototype char HID_Read(void);

Description Receives message from host and stores it in the Read Buffer.

Parameters None.

Returns If the data reading has failed, the function returns 0. Otherwise, it returns number of
characters received from the host.

Requires USB HID needs to be enabled before using this function. See HID_Enable.

Example // retry until success


while(!HID_Read())
;

Notes None.

HID_Write

Prototype char HID_Write(char *writebuff, char len);

Description Function sends data from Write Buffer writebuff to host.

Parameters  writebuff: Write Buffer, same parameter as used in initialization;


see HID_Enable.
 len: specifies a length of the data to be transmitted.

Returns If the data transmitting has failed, the function returns 0. Otherwise, it returns number
of transmitted bytes.

Requires USB HID needs to be enabled before using this function. See HID_Enable.

Example // retry until success


while(!HID_Write(&writebuff,64))
;

www.raguvaran.puzl.com
Notes Function call needs to be repeated as long as data is not successfuly sent.

HID_Disable

Prototype void HID_Disable(void);

Description Disables USB HID communication.

Parameters None.

Returns Nothing.

Requires USB HID needs to be enabled before using this function. See HID_Enable.

Example HID_Disable();

Notes None.

USB_Interrupt_Proc

Prototype void USB_Interrupt_Proc(void);

Description This routine is used for servicing various USB bus events. Should be called inside USB
interrupt routine.

Parameters None.

Returns Nothing.

Requires Nothing.

Example void interrupt() {


USB_Interrupt_Proc();
}

www.raguvaran.puzl.com
Notes Do not use this function with USB_Polling_Proc, only one should be used. To enable
servicing through interrupt, USB_INTERRUPT constant should be set (it is set by default in
descriptor file).

USB_Polling_Proc

Prototype void USB_Polling_Proc(void);

Description This routine is used for servicing various USB bus events. It should be periodically,
preferably every 100 microseconds.

Parameters None.

Returns Nothing.

Requires Nothing.

Example while(1) {
USB_Polling_Proc();
kk = HID_Read();
if (kk != 0) {
for(cnt=0; cnt < 64; cnt++)
writebuff[cnt]=readbuff[cnt];
HID_Write(&writebuff,64);
}
}

Notes Do not use this functions with USB_Interrupt_Proc. To enable servicing by


polling, USB_INTERRUPT constant should be set to 0 (it is located in descriptor file).

Gen_Enable

Prototype void Gen_Enable(char* readbuff, char* writebuff);

Description Initialize the USB module of the MCU.

Parameters  readbuff: Read Buffer.


 writebuff: Write Buffer.

www.raguvaran.puzl.com
Returns Nothing.

Requires USB needs to be enabled before using this function. See Gen_Enable.

Example Gen_Enable(&readbuff,&writebuff);

Notes None.

Gen_Read

Prototype char Gen_Read(char *readbuff, char length, char ep);

Description Generic routine that receives the specified data from the specified endpoint.

Parameters  readbuff: Received data.


 length: The length of the data that you wish to receive.
 ep: Endpoint number you want to receive the data into.

Returns Returns the number of received bytes, otherwise 0.

Requires USB needs to be enabled before using this function. See Gen_Enable.

Example while(Gen_Read(readbuff,64,1)==0)
;

Notes None.

Gen_Write

Prototype char Gen_Write(char* writebuff, char length, char ep);

Description Sends the specified data to the specified endpoint.

Parameters  writebuff: The data that you want to send.


 length: the length of the data that you wish to send.

www.raguvaran.puzl.com
 ep: Endpoint number you want to send the data into.

Returns Returns the number of transmitted bytes, otherwise 0.

Requires USB needs to be enabled before using this function. See Gen_Enable.

Example while(Gen_Write(writebuff,64,1)==0)
;

Notes None.

Library Example
This example establishes connection with the HID terminal that is active on the PC. Upon connection
establishment, the HID Device Name will appear in the respective window. After that software will wait
for data and it will return received data back. Examples uses USBdsc.c descriptor file, which is in the
same folder, and can be created by the HID Terminal.
Copy Code To Clipboard

unsigned char readbuff[64] absolute 0x500; // Buffers should be in USB RAM, please consult
datasheet
unsigned char writebuff[64] absolute 0x540;

char cnt;
char kk;

void interrupt(){
USB_Interrupt_Proc(); // USB servicing is done inside the interrupt
}

void main(void){
ADCON1 |= 0x0F; // Configure all ports with analog function as digital
CMCON |= 7; // Disable comparators

HID_Enable(&readbuff,&writebuff); // Enable HID communication

while(1){
while(!HID_Read())
;

for(cnt=0;cnt<64;cnt++)
writebuff[cnt]=readbuff[cnt];

while(!HID_Write(&writebuff,64))
;
}
}

HW Connection

www.raguvaran.puzl.com
USB connection scheme

Miscellaneous Libraries

Button Library
The Button Library provides routines for detecting button presses and debouncing (eliminating the
influence of contact flickering upon pressing a button).

www.raguvaran.puzl.com
Library Routines
 Button

Button

Prototype unsigned short Button(unsigned short *port, unsigned short pin, unsigned
short time, unsigned short active_state);

Returns  255 if the pin was in the active state for given period.
 0 otherwise

Description Function eliminates the influence of contact flickering upon pressing a button
(debouncing).

Parameter port specifies the location of the button; parameter pin is the pin number
on designated port and goes from 0..7; parameter time is a debounce period in
milliseconds; parameter active_state can be either 0 or 1, and it determines if the
button is active upon logical zero or logical one.

Requires Button pin must be configured as input.

Example Example reads RB0, to which the button is connected; on transition from 1 to 0
(release of button), PORTD is inverted:

bit oldstate; // Old state flag

void main() {

ANSEL = 0; // Configure AN pins as digital


I/O
ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;

TRISB0_bit = 1; // set RB0 pin as input

TRISC = 0x00; // Configure PORTC as output


PORTC = 0xAA; // Initial PORTC value
oldstate = 0;

do {
if (Button(&PORTB, 0, 1, 1)) { // Detect logical one
oldstate = 1; // Update flag
}
if (oldstate && Button(&PORTB, 0, 1, 0)) { // Detect one-to-zero transition
PORTC = ~PORTC; // Invert PORTC
oldstate = 0; // Update flag
}
} while(1); // Endless loop
}

www.raguvaran.puzl.com
Conversions Library
The mikroC PRO for PIC Conversions Library provides routines for numerals to strings and BCD/decimal
conversions.

Library Dependency Tree

www.raguvaran.puzl.com
Library Routines
You can get text representation of numerical value by passing it to one of the following routines:

 ByteToStr
 ShortToStr
 WordToStr
 IntToStr
 LongToStr
 LongWordToStr
 FloatToStr
 WordToStrWithZeros
 IntToStrWithZeros
 LongWordToStrWithZeros
 LongIntToStrWithZeros
 ByteToHex
 ShortToHex
 WordToHex
 IntToHex
 LongWordToHex
 LongIntToHex
 Rtrim
 Ltrim
The following functions convert decimal values to BCD and vice versa:
 Dec2Bcd
 Bcd2Dec
 Dec2Bcd16
 Bcd2Dec16

ByteToStr

Prototype void ByteToStr(unsigned short input, char *output);

Returns Nothing.

Description Converts input byte to a string. The output string has fixed width of 4 characters
including null character at the end (string termination). The output string is right
justified and remaining positions on the left (if any) are filled with blanks.

Parameters :

 input: byte to be converted


 output: destination string

Requires Destination string should be at least 4 characters in length.

Example unsigned short t = 24;


char txt[4];
...
ByteToStr(t, txt); // txt is " 24" (one blank here)

www.raguvaran.puzl.com
ShortToStr

Prototype void ShortToStr(short input, char *output);

Returns Nothing.

Description Converts input signed short number to a string. The output string has fixed width of 5
characters including null character at the end (string termination). The output string is
right justified and remaining positions on the left (if any) are filled with blanks.

Parameters :

 input: signed short number to be converted


 output: destination string

Requires Destination string should be at least 5 characters in length.

Example short t = -24;


char txt[5];
...
ShortToStr(t, txt); // txt is " -24" (one blank here)

WordToStr

Prototype void WordToStr(unsigned input, char *output);

Returns Nothing.

Description Converts input word to a string. The output string has fixed width of 6 characters
including null character at the end (string termination). The output string is right
justified and the remaining positions on the left (if any) are filled with blanks.

Parameters :

 input: word to be converted


 output: destination string

Requires Destination string should be at least 6 characters in length.

Example unsigned t = 437;


char txt[6];
...
WordToStr(t, txt); // txt is " 437" (two blanks here)

IntToStr

Prototype void IntToStr(int input, char *output);

www.raguvaran.puzl.com
Returns Nothing.

Description Converts input signed integer number to a string. The output string has fixed width of
7 characters including null character at the end (string termination). The output string
is right justified and the remaining positions on the left (if any) are filled with blanks.

Parameters :

 input: signed integer number to be converted


 output: destination string

Requires Destination string should be at least 7 characters in length.

Example int j = -4220;


char txt[7];
...
IntToStr(j, txt); // txt is " -4220" (one blank here)

LongToStr

Prototype void LongToStr(long input, char *output);

Returns Nothing.

Description Converts input signed long integer number to a string. The output string has fixed
width of 12 characters including null character at the end (string termination). The
output string is right justified and the remaining positions on the left (if any) are filled
with blanks.

Parameters :

 input: signed long integer number to be converted


 output: destination string

Requires Destination string should be at least 12 characters in length.

Example long jj = -3700000;


char txt[12];
...
LongToStr(jj, txt);
// txt is " -3700000" (three blanks here)

LongWordToStr

Prototype void LongWordToStr(unsigned long input, char *output);

www.raguvaran.puzl.com
Returns Nothing.

Description Converts input unsigned long integer number to a string. The output string has fixed
width of 11 characters including null character at the end (string termination). The
output string is right justified and the remaining positions on the left (if any) are filled
with blanks.

Parameters :

 input: unsigned long integer number to be converted


 output: destination string

Requires Destination string should be at least 11 characters in length.

Example unsigned long jj = 3700000;


char txt[11];
...
LongWordToStr(jj, txt);
// txt is " 3700000" (three blanks here)

FloatToStr

Prototype unsigned char FloatToStr(float fnum, unsigned char *str);

Returns  3 if input number is NaN


 2 if input number is -INF
 1 if input number is +INF
 0 if conversion was successful

Description Converts a floating point number to a string.

Parameters :

 fnum: floating point number to be converted


 str: destination string
The output string is left justified and null terminated after the last digit.

Note : Given floating point number will be truncated to 7 most significant digits
before conversion.

Requires Destination string should be at least 14 characters in length.

Example float ff1 = -374.2;


float ff2 = 123.456789;
float ff3 = 0.000001234;
char txt[15];
...
FloatToStr(ff1, txt); // txt is "-374.2"
FloatToStr(ff2, txt); // txt is "123.4567"

www.raguvaran.puzl.com
FloatToStr(ff3, txt); // txt is "1.234e-6"

WordToStrWithZeros

Prototype void WordToStrWithZeros(unsigned int input, char *output);

Returns Nothing.

Description Converts input word to a string. The output string has fixed width of 6 characters
including null character at the end (string termination). The output string is right
justified and remaining positions on the left (if any) are filled with zeros.

Parameters :

 input: unsigned integer to be converted


 output: destination string

Requires Destination string should be at least 6 characters in length.

Example unsigned short t = 437;


char txt[6];
...
WordToStrWithZeros(t, txt); // txt is "0437" (one zero here)

IntToStrWithZeros

Prototype void IntToStrWithZeros(int input, char *output);

Returns Nothing.

Description Converts input integer to a string. The output string has fixed width of 7 characters
including null character at the end (string termination). The output string is right
justified and remaining positions on the left (if any) are filled with zeros.

Parameters :

 input: integer number to be converted


 output: destination string

Requires Destination string should be at least 7 characters in length.

Example short t = -3276;


char txt[7];
...
IntToStrWithZeros(t, txt); // txt is "-03276" (one zero here)

www.raguvaran.puzl.com
LongWordToStrWithZeros

Prototype void LongWordToStrWithZeros(unsigned long input, char *output);

Returns Nothing.

Description Converts input longword to a string. The output string has fixed width of 11 characters
including null character at the end (string termination). The output string is right
justified and the remaining positions on the left (if any) are filled with zeros.

Parameters :

 input: unsigned long number to be converted


 output: destination string

Requires Destination string should be at least 11 characters in length.

Example unsigned t = 12345678;


char txt[11];
...
LongWordToStrWithZeros(t, txt); // txt is "0012345678" (two zeros)

LongIntToStrWithZeros

Prototype void LongIntToStrWithZeros(long input, char *output);

Returns Nothing.

Description Converts input signed long integer number to a string. The output string has fixed
width of 12 characters including null character at the end (string termination). The
output string is right justified and the remaining positions on the left (if any) are filled
with zaeros.

Parameters :

 input: signed long number to be converted


 output: destination string

Requires Destination string should be at least 12 characters in length.

Example int j = -12345678;


char txt[12];
...
LongIntToStrWithZeros(j, txt); // txt is "-0012345678" (one zero here)

ByteToHex

www.raguvaran.puzl.com
Prototype void ByteToHex(char input, char *output);

Returns Nothing.

Description Converts input number to a string containing the number's hexadecimal


representation. The output string has fixed width of 3 characters including null
character at the end (string termination).

Parameters :

 input: byte to be converted


 output: destination string

Requires Destination string should be at least 3 characters in length.

Example unsigned short t = 2;


char txt[3];
...
ByteToHex(t, txt); // txt is "02"

ShortToHex

Prototype void ShortToHex(unsigned short input, char *output);

Returns Nothing.

Description Converts input number to a string containing the number's hexadecimal


representation. The output string has fixed width of 3 characters including null
character at the end (string termination).

Parameters :

 input: signed short number to be converted


 output: destination string

Requires Destination string should be at least 3 characters in length.

Example short t = -100;


char txt[3];
...
ShortToHex(t, txt); // txt is "9C"

WordToHex

Prototype void WordToHex(unsigned input, char *output);

www.raguvaran.puzl.com
Returns Nothing.

Description Converts input number to a string containing the number's hexadecimal


representation. The output string has fixed width of 5 characters including null
character at the end (string termination).

Parameters :

 input: unsigned integer to be converted


 output: destination string

Requires Destination string should be at least 5 characters in length.

Example unsigned t = 1111;


char txt[5];
...
WordToHex(t, txt); // txt is "0457"

IntToHex

Prototype void IntToHex(int input, char *output);

Returns Nothing.

Description Converts input number to a string containing the number's hexadecimal


representation. The output string has fixed width of 5 characters including null
character at the end (string termination).

Parameters :

 input: signed integer number to be converted


 output: destination string

Requires Destination string should be at least 5 characters in length.

Example int j = -32768;


char txt[5];
...
IntToHex(j, txt); // txt is "8000"

LongWordToHex

Prototype void LongWordToHex(unsigned long input, char *output);

Returns Nothing.

www.raguvaran.puzl.com
Description Converts input number to a string containing the number's hexadecimal
representation. The output string has fixed width of 9 characters including null
character at the end (string termination).

Parameters :

 input: unsigned long integer number to be converted


 output: destination string

Requires Destination string should be at least 9 characters in length.

Example unsigned long jj = 65535;


char txt[9];
...
LongWordToHex(jj, txt); // txt is "0000FFFF"

LongIntToHex

Prototype void LongIntToHex(long int input, char *output);

Returns Nothing.

Description Converts input number to a string containing the number's hexadecimal


representation. The output string has fixed width of 9 characters including null
character at the end (string termination).

Parameters :

 input: signed long integer number to be converted


 output: destination string

Requires Destination string should be at least 9 characters in length.

Example long int jj = -2147483648;


char txt[9];
...
LongIntToHex(jj, txt); // txt is "80000000"

Dec2Bcd

Prototype unsigned short Dec2Bcd(unsigned short decnum);

Returns Converted BCD value.

Description Converts input unsigned short integer number to its appropriate BCD representation.
Parameters :

www.raguvaran.puzl.com
 decnum: unsigned short integer number to be converted

Requires Nothing.

Example unsigned short a, b;


...
a = 22;
b = Dec2Bcd(a); // b equals 34

Bcd2Dec

Prototype unsigned short Bcd2Dec(unsigned short decnum);

Returns Converted decimal value.

Description Converts 8-bit BCD numeral to its decimal equivalent.


Parameters :

 bcdnum: 8-bit BCD numeral to be converted

Requires Nothing.

Example unsigned short a, b;


...
a = 0x34; // a equals 0x34
b = Bcd2Dec(a); // b equals 22

Dec2Bcd16

Prototype unsigned Dec2Bcd16(unsigned decnum);

Returns Converted BCD value.

Description Converts unsigned 16-bit decimal value to its BCD equivalent.


Parameters :

 decnum unsigned 16-bit decimal number to be converted

Requires Nothing.

Example unsigned a, b;
...
a = 2345;
b = Dec2Bcd16(a); // b equals 9029

Bcd2Dec16

www.raguvaran.puzl.com
Prototype unsigned Bcd2Dec16(unsigned bcdnum);

Returns Converted decimal value.

Description Converts 16-bit BCD numeral to its decimal equivalent.


Parameters :

 bcdnum: 16-bit BCD numeral to be converted

Requires Nothing.

Example unsigned a, b;
...
a = 0x1234; // a equals 4660
b = Bcd2Dec16(a); // b equals 1234

Rtrim

Prototype char *Rtrim(char *string);

Returns The function returns pointer to the array without trailing spaces.

Description Trims the trailing spaces from array given with *string
Parameters :

 string: array to be trimmed.

Requires Nothing.

Example char *res;

res = Rtrim("mikroe "); // trims the trailing spaces and returns the address of
the first non-space character

Ltrim

Prototype char *Ltrim(char *string);

Returns The function returns pointer to the array without leading spaces.

Description Trims the leading spaces from array given with *string

www.raguvaran.puzl.com
Parameters :

 string: array to be trimmed.

Requires Nothing.

Example char *res;

res = Ltrim(" mikroe"); // trims the leading spaces and returns the address
of the first non-space character

PrintOut Library
The mikroC PRO for PIC provides the PrintOut routine for easy data formatting and printing.

Important : Library works with PIC18 family only.

www.raguvaran.puzl.com
Library Dependency Tree

Library Routines
 PrintOut

PrintOut

Prototype void PrintOut(void (*prntoutfunc)(char ch), const char *f,...);

Returns Nothing.

Description PrintOut is used to format data and print them in a way defined by the user through a
print handler function.
Parameters :

 prntoutfunc: print handler function


 f: format string
The f argument is a format string and may be composed of characters, escape
sequences, and format specifications. Ordinary characters and escape sequences are
copied to the print handler in order in which they are interpreted. Format specifications
always begin with a percent sign (%) and require additional arguments to be included in
the function call.
The format string is read from left to right. The first format specification encountered
refers to the first argument after the f parameter and then converts and outputs it
using the format specification. The second format specification accesses the second
argument after f, and so on. If there are more arguments than format specifications,
the extra arguments are ignored. Results are unpredictable if there are not enough
arguments for the format specifications. The format specifications have the following
format:
% [flags] [width] [.precision] [{ l | L }] conversion_type
Each field in the format specification can be a single character or a number which
specifies a particular format option. The conversion_type field is where a single
character specifies that an argument is interpreted as a character, string, number, or
pointer, as shown in the following table:
conversion_type Argument Type Output Format

d int Signed decimal number

u unsigned int Unsigned decimal number

o unsigned int Unsigned octal number

x unsigned int Unsigned hexadecimal number using 0123456789abcdef

X unsigned int Unsigned hexadecimal number using 0123456789ABCEDF

f double Floating-point number using the format [-]dddd.dddd

www.raguvaran.puzl.com
e double Floating-point number using the format [-]d.dddde[-]dd

E double Floating-point number using the format [-]d.ddddE[-]dd

Floating-point number using either e or f format, whichever


g double is more compact for the specified value and precision

c int int is converted to an unsigned char, and the


resulting character is written

s char * String with a terminating null character

p void * Pointer value, the X format is used

A % is written. No argument is converted. The complete


% <none> conversion specification shall be %%.

The flags field is where a single character is used to justify the output and to print +/-
signs and blanks, decimal points, and octal and hexadecimal prefixes, as shown in the
following table.
flags Meaning

- Left justify the output in the specified field width.

+ Prefix the output value with + or - sign if the output is a signed type.

Prefix the output value with a blank if it is a signed positive value. Otherwise, no blank is
space (' ') prefixed.

Prefix a non-zero output value with 0, 0x, or 0X when used with o, x, and X field
# types, respectively. When used with the e, E, f, g, and G field types, the # flag forces
the output value to include a decimal point. In any other case the # flag is ignored.

* Ignore format specifier.

The width field is a non-negative number that specifies a minimum number of printed
characters. If a number of characters in the output value is less than width, blanks are
added on the left or right (when the - flag is specified) in order to pad to the minimum
width. If the width is prefixed with 0, then zeros are padded instead of blanks.
The widthfield never truncates a field. If the length of the output value exceeds the
specified width, all characters are output.
The precision field is a non-negative number that specifies the number of characters
to print, number of significant digits, or number of decimal places. The precision field
can cause truncation or rounding of the output value in the case of a floating-point
number as specified in the following table.
flags Meaning of the precision field

The precision field is where you specify the minimum number of digits that will be
included in the output value. Digits are not truncated if the number of digits in an
d, u, o, x, X argument exceeds that defined in the precision field. If the number of digits in the
argument is less than the precision field, the output value is padded on the left with zeros.

The precision field is where you specify the number of digits to the right of the decimal
f point. The last digit is rounded.

www.raguvaran.puzl.com
The precision field is where you specify the number of digits to the right of the decimal
e, E point. The last digit is rounded.

The precision field is where you specify the maximum number of significant digits in the
g output value.

c, C The precision field has no effect on these field types.

The precision field is where you specify the maximum number of characters in the output
s value. Excess characters are not output.

The optional characters l or L may immediately precede conversion_type to


respectively specify long versions of the integer types d, i, u, o, x, and X.
You must ensure that the argument type matches that of the format specification. You
can use type casts to ensure that the proper type is passed to printout.

Requires Nothing.

Example Print mikroElektronika example's header file to UART.

void PrintHandler(char c) {
UART1_Write(c);
}

void main() {
UART1_Init(9600);
Delay_ms(100);

PrintOut(PrintHandler, "/*rn"
" * Project name:rn"
" PrintOutExample (Sample usage of PrintOut()
function)rn"
" * Copyright:rn"
" (c) MikroElektronika, 2006.rn"
" * Revision History:rn"
" 20060710:rn"
" - Initial releasern"
" * Description:rn"
" Simple demonstration on usage of the PrintOut()
functionrn"
" * Test configuration:rn"
" MCU: PIC18F4520rn"
" Dev.Board: EasyPIC6rn"
" Oscillator: HS, %6.3fMHzrn"
" Ext. Modules: None.rn"
" SW: mikroC PRO for PICrn"
" * NOTES:rn"
" None.rn"
" */rn", Get_Fosc_kHz()/1000.);

Setjmp Library
This library contains functions and types definitions for bypassing the normal function call and return
discipline. The type declared is jmp_buf which is an array type suitable for holding the information
needed to restore a calling environment.

www.raguvaran.puzl.com
Type declaration is contained in sejmp16.h and setjmp18.h header files for PIC16 and PIC18 family
mcus respectively. These headers can be found in the include folder of the compiler. The implementation
of this library is different for PIC16 and PIC18 family mcus. For PIC16 family Setjmp and Longjmp are
implemented as macros defined in setjmp16.h header file and for PIC18 family as functions defined in
setjmp library file.
Note : Due to PIC16 family specific of not being able to read/write stack pointer, the program
execution after Longjmp ivocation occurs depends on the stack content. That is why, for PIC16 family
only, implementation of Setjmp and Longjmp functions is not ANSI C standard compliant.

Library Routines
 Setjmp
 Longjmp

Setjmp

Prototype int setjmp(jmp_buf env);

Returns if the return is from direct invocation it returns 0


if the return is from a call to the longjmp it returns nonzero value

Description This function saves calling position in jmp_buf for later use by longjmp. The
parameter env: array of type (jmp_buf) suitible for holding the information needed for
restoring calling environment.

Requires Nothing.

Example setjmp(buf);

Longjmp

Prototype void longjmp(jmp_buf env, int val);

Returns longjmp causes setjmp to return val, if val is 0 it will return 1.

Description Restores calling environment saved in jmp_buf by most recent invocation of setjmp
macro. If there has been no such invocation, or function conatinig the invocation of
setjmp has terminated in the interim, the behaviour is undefined.Parameter env: array
of type (jmp_buf) holding the information saved by corresponding setjmp
invocation, val: char value, that will return corresponding setjmp.

Requires Invocation of Longjmp must occur before return from the function in which Setjmp was
called encounters.

Example longjmp(buf, 2);

Library Example

www.raguvaran.puzl.com
Example demonstrates function cross calling using setjmp and longjmp functions. When called, Setjmp()
saves its calling environment in its jmp_buf argument for later use by the Longjmp(). Longjmp(), on the
other hand, restores the environment saved by the most recent invocation of the Setjmp() with the
corresponding jmp_buf argument. The given example is for P16.

Copy Code To Clipboard

#include <setjmp16.h>

jmp_buf buf; // Note: Program flow diagrams are indexed according


// to the sequence of execution

void func33(){ // 2<----------|


Delay_ms(1000); // |
// |
asm nop; // |
longjmp(buf, 2); // 3-------------->|
asm nop; // | |
// | |
} // | |
// | |
void func(){ // 1<------| | |
// | | |
PORTB = 3; // | | |
if (setjmp(buf) == 2) // 3<--------------|
PORTB = 1; // 4-->| | |
else // | | |
func33(); // 2---------->|
// | |
asm nop; // 4<--| |
} // 5-------|-------> depends on stack content
// |
void main() { // |
// |
PORTB = 0; // |
TRISB = 0; // |
// |
asm nop; // |
// |
func(); // 1------>|
//
asm nop; //
Delay_ms(1000);
PORTB = 0xFF;
}

Sprint Library
The mikroC PRO for PIC provides the standard ANSI C Sprintf function for easy data formatting.

www.raguvaran.puzl.com
Note : In addition to ANSI C standard, the Sprint Library also includes two limited versions of
the sprintf function (sprinti and sprintl)
These functions take less ROM and RAM and may be more convenient for use in some cases.

Library Dependency Tree

Functions
 sprintf
 sprintl
 sprinti

sprintf

Prototype void sprintf(char *wh, const code char *f,...);

Returns The function returns the number of characters actually written to destination string.

Description sprintf is used to format data and print them into destination string.
Parameters :

 wh: destination string


 f: format string
The f argument is a format string and may be composed of characters, escape
sequences, and format specifications. Ordinary characters and escape sequences are
copied to the destination string in the order in which they are interpreted. Format
specifications always begin with a percent sign (%) and require additional arguments to
be included in the function call.
The format string is read from left to right. The first format specification encountered
refers to the first argument after f and then converts and outputs it using the format
specification. The second format specification accesses the second argument after f,
and so on. If there are more arguments than format specifications, then these extra
arguments are ignored. Results are unpredictable if there are not enough arguments
for the format specifications. The format specifications have the following format:
% [flags] [width] [.precision] [{ l | L }] conversion_type
Each field in the format specification can be a single character or a number which
specifies a particular format option. The conversion_type field is where a single
character specifies that the argument is interpreted as a character, string, number, or
pointer, as shown in the following table:
conversion_type Argument Type Output Format

d int Signed decimal number

u unsigned int Unsigned decimal number

o unsigned int Unsigned octal number

x unsigned int Unsigned hexadecimal number using 0123456789abcdef

www.raguvaran.puzl.com
X unsigned int Unsigned hexadecimal number using 0123456789ABCEDF

f double Floating-point number using the format [-]dddd.dddd

e double Floating-point number using the format [-]d.dddde[-]dd

E double Floating-point number using the format [-]d.ddddE[-]dd

Floating-point number using either e or f format, whichever


g double is more compact for the specified value and precision

c int int is converted to unsigned char, and the


resulting character is written

s char * String with a terminating null character

p void * Pointer value, the X format is used

A % is written. No argument is converted. The complete


% <none> conversion specification shall be %%.

The flags field is where a single character is used to justify the output and to print +/-
signs and blanks, decimal points, and octal and hexadecimal prefixes, as shown in the
following table.
flags Meaning

- Left justify the output in the specified field width.

+ Prefix the output value with + or - sign if the output is a signed type.

Prefix the output value with a blank if it is a signed positive value. Otherwise, no blank is
space (' ') prefixed

Prefixes a non-zero output value with 0, 0x, or 0X when used with o, x, and X field
# types, respectively. When used with e, E, f, g, and G field types, the # flag forces the
output value to include a decimal point. The # flag is ignored in all other cases.

* Ignore format specifier.

The width field is a non-negative number that specifies the minimum number of printed
characters. If a number of characters in the output value is less than width, then
blanks are added on the left or right (when the - flag is specified) to pad to the
minimum width. If width is prefixed with 0, then zeros are padded instead of blanks.
The width field never truncates a field. If a length of the output value exceeds the
specified width, all characters are output.
The precision field is a non-negative number that specifies a number of characters to
print, number of significant digits or number of decimal places. The precision field can
cause truncation or rounding of the output value in the case of a floating-point number
as specified in the following table.
flags Meaning of the precision field

The precision field is where you specify a minimum number of digits that will be
d, u, o, x, X included in the output value. Digits are not truncated if the number of digits in the

www.raguvaran.puzl.com
argument exceeds that defined in the precision field. If a number of digits in the argument
is less than the precision field, the output value is padded on the left with zeros.

The precision field is where you specify a number of digits to the right of the decimal
f point. The last digit is rounded.

The precision field is where you specify a number of digits to the right of the decimal
e, E point. The last digit is rounded.

The precision field is where you specify a maximum number of significant digits in the
g output value.

c, C The precision field has no effect on these field types.

The precision field is where you specify a maximum number of characters in the output
s value. Excess characters are not output.

The optional characters l or L may immediately precede conversion_type to


respectively specify long versions of the integer types d, i, u, o, x, and X.
You must ensure that the argument type matches that of the format specification. You
can use type casts to ensure that the proper type is passed to sprintf.

sprintl

Prototype void sprintl(char *wh, const code char *f,...);

Returns The function returns the number of characters actually written to destination string.

Description The same as sprintf, except it doesn't support float-type numbers.

sprinti

Prototype void sprinti(char *wh, const code char *f,...);

Returns The function returns the number of characters actually written to destination string.

Description The same as sprintf, except it doesn't support long integers and float-type numbers.

Library Example
This is a demonstration of the standard C library sprintf routine usage. Three different representations of
the same floating poing number obtained by using the sprintf routine are sent via UART.

Copy Code To Clipboard

www.raguvaran.puzl.com
double ww = -1.2587538e+1;
char buffer[15];

void main(){

UART1_Init(4800); // Initialize UART module at 4800 bps


Delay_ms(10);

UART1_Write_Text("Floating point number representation"); // Write message on UART

sprintf(buffer, "%12e", ww); // Format ww and store it to buffer


UART1_Write_Text("rne format:"); // Write message on UART
UART1_Write_Text(buffer); // Write buffer on UART

sprintf(buffer, "%12f", ww); // Format ww and store it to buffer


UART1_Write_Text("rnf format:"); // Write message on UART
UART1_Write_Text(buffer); // Write buffer on UART

sprintf(buffer, "%12g", ww); // Format ww and store it to buffer


UART1_Write_Text("rng format:"); // Write message on UART
UART1_Write_Text(buffer); // Write buffer on UART
}

Time Library
The Time Library contains functions and type definitions for time calculations in the UNIX time format
which counts the number of seconds since the "epoch". This is very convenient for programs that work
with time intervals: the difference between two UNIX time values is a real-time difference measured in
seconds.

What is the epoch?


Originally it was defined as the beginning of 1970 GMT. (January 1, 1970 Julian day) GMT, Greenwich
Mean Time, is a traditional term for the time zone in England.

www.raguvaran.puzl.com
The TimeStruct type is a structure type suitable for time and date storage. Type declaration is
contained in __Time.h which can be found in the mikroC PRO for PIC Time Library Demo example folder.

Library Routines
 Time_dateToEpoch
 Time_epochToDate
 Time_dateDiff

Time_dateToEpoch

Prototype long Time_dateToEpoch(TimeStruct *ts);

Returns Number of seconds since January 1, 1970 0h00mn00s.

Description This function returns the UNIX time : number of seconds since January 1, 1970
0h00mn00s.

Parameters :

 ts: time and date value for calculating UNIX time.

Requires Nothing.

Example #include "timelib.h"


...
TimeStruct ts1;
long epoch;
...
/*
* what is the epoch of the date in ts ?
*/
epoch = Time_dateToEpoch(&ts1);

Time_epochToDate

Prototype void Time_epochToDate(long e, TimeStruct *ts);

Returns Nothing.

Description Converts the UNIX time to time and date.

Parameters :

 e: UNIX time (seconds since UNIX epoch)


 ts: time and date structure for storing conversion output

Requires Nothing.

www.raguvaran.puzl.com
Example #include "timelib.h"
...
TimeStruct ts2;
long epoch;
...
/*
* what date is epoch 1234567890 ?
*/
epoch = 1234567890;
Time_epochToDate(epoch, &ts2);

Time_dateDiff

Prototype long Time_dateDiff(TimeStruct *t1, TimeStruct *t2);

Returns Time difference in seconds as a signed long.

Description This function compares two dates and returns time difference in seconds as a signed
long. Result is positive if t1 is before t2, result is null if t1 is the same as t2 and result
is negative if t1 is after t2.
Parameters :

 t1: time and date structure (the first comparison parameter)


 t2: time and date structure (the second comparison parameter)

Note : This function is implemented as macro in the timelib.h header file which
can be found in the mikroC PRO for PIC Time Library Demo example folder.

Requires Nothing.

Example #include "timelib.h"


...
TimeStruct ts1, ts2;
long diff;
...
/*
* how many seconds between these two dates contained in ts1 and ts2 buffers?
*/
diff = Time_dateDiff(&ts1, &ts2);

Library Example
Demonstration of Time library routines usage for time calculations in UNIX time format.

Copy Code To Clipboard

#include "timelib.h"

www.raguvaran.puzl.com
TimeStruct ts1, ts2 ;

long epoch ;
long diff ;

void main() {

ts1.ss = 0 ;
ts1.mn = 7 ;
ts1.hh = 17 ;
ts1.md = 23 ;
ts1.mo = 5 ;
ts1.yy = 2006 ;

/*
* What is the epoch of the date in ts ?
*/
epoch = Time_dateToEpoch(&ts1) ; // 1148404020

/*
* What date is epoch 1234567890 ?
*/
epoch = 1234567890 ;
Time_epochToDate(epoch, &ts2) ; // {0x1E, 0x1F,0x17, 0x0D, 0x04, 0x02, 0x07D9}

/*
* How much seconds between this two dates ?
*/
diff = Time_dateDiff(&ts1, &ts2) ; // 86163870
}

Trigonometry Library
The mikroC PRO for PIC implements fundamental trigonometry functions. These functions are
implemented as look-up tables. Trigonometry functions are implemented in integer format in order to
save memory.

Library Routines
 sinE3
 cosE3

www.raguvaran.puzl.com
sinE3

Prototype int sinE3(unsigned angle_deg);

Returns The function returns the sine of input parameter.

Description The function calculates sine multiplied by 1000 and rounded to the nearest integer:

result = round(sin(angle_deg)*1000)
Parameters :

 angle_deg: input angle in degrees

Note : Return value range: -1000..1000

Requires Nothing.

Example int res;


...
res = sinE3(45); // result is 707

cosE3

Prototype int cosE3(unsigned angle_deg);

Returns The function returns the cosine of input parameter.

Description The function calculates cosine multiplied by 1000 and rounded to the nearest integer:

result = round(cos(angle_deg)*1000)
Parameters :

 angle_deg: input angle in degrees

Note : Return value range: -1000..1000.

Requires Nothing.

Example int res;


...
res = cosE3(196); // result is -961

www.raguvaran.puzl.com

You might also like