MikroC Library
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
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
www.raguvaran.puzl.com
Hi
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
Higher
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
Highest
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
LoWord
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.
Requires Nothing.
Example d = 0x12345678;
tmp = LoWord(d); // Equals 0x5678
Notes None.
HiWord
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.
www.raguvaran.puzl.com
Returns High word of number, bits 31..16.
Requires Nothing.
Example d = 0x12345678;
tmp = HiWord(d); // Equals 0x1234
Notes None.
Delay_us
Returns Nothing.
Requires Nothing.
Delay_ms
Returns Nothing.
Requires Nothing.
www.raguvaran.puzl.com
Example Delay_ms(1000); /* One second pause */
Vdelay_ms
Returns Nothing.
Requires Nothing.
VDelay_Advanced_ms
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.
Delay_Cyc
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.
Clock_kHz
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.
Clock_MHz
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.
www.raguvaran.puzl.com
Get_Fosc_kHz
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.
Swap
Requires Nothing.
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
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).
ADC_Get_Sample
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.
www.raguvaran.puzl.com
Example unsigned adc_value;
...
adc_value = ADC_Get_Sample(2); // read analog value from ADC module channel 2
ADC_Read
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.
Library Example
This example code reads analog value from channel 2 and displays it on PORTB and PORTC.
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;
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.
Important :
Library Routines
CANSetOperationMode
CANGetOperationMode
CANInitialize
CANSetBaudRate
CANSetMask
CANSetFilter
CANRead
www.raguvaran.puzl.com
CANWrite
CANSetOperationMode
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.
CANGetOperationMode
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.
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:
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.
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:
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.
CANSetMask
Returns Nothing.
Description Function sets mask for advanced filtering of messages. Given value is bit adjusted to
appropriate buffer mask registers.
Parameters:
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);
www.raguvaran.puzl.com
CANSetFilter
Returns Nothing.
Description Function sets message filter. Given value is bit adjusted to appropriate buffer mask
registers.
Parameters:
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.
CANRead
Prototype char CANRead(long *id, char *data, char *datalen, char *CAN_RX_MSG_FLAGS)
;
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)
// ...
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);
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:
// ...
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
_CAN_CONFIG_PHSEG2_PRG_ON &
_CAN_CONFIG_STD_MSG &
_CAN_CONFIG_DBL_BUFFER_ON &
_CAN_CONFIG_VALID_XTD_MSG &
_CAN_CONFIG_LINE_FILTER_OFF;
...
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
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
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.
void main() {
Can_Init_Flags = 0; //
Can_Send_Flags = 0; // clear flags
Can_Rcv_Flags = 0; //
www.raguvaran.puzl.com
Delay_ms(10);
CANWrite(ID_1st, RxTx_Data, 1, Can_Send_Flags); // send incremented
data back
}
}
}
void main() {
Can_Init_Flags = 0; //
Can_Send_Flags = 0; // clear flags
Can_Rcv_Flags = 0; //
www.raguvaran.puzl.com
HW Connection
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.
Important :
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
Returns Nothing.
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
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.
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.
// 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:
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.
www.raguvaran.puzl.com
CANSPISetMask
Returns Nothing.
Description Configures mask for advanced filtering of messages. The parameter value is bit-
adjusted to the appropriate mask registers.
Parameters:
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)
CANSPISetFilter
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.
CANSPIRead
Prototype char CANSPIRead(long *id, char *rd_data, char *data_len, char *CANSPI_RX_M
SG_FLAGS);
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:
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);
Descriptio If at least one empty Transmit Buffer is found, the function sends message in the queue
n for transmission.
Parameters:
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)
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
_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;
...
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
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,
You may use bitwise AND (&) to adjust the appropriate flags. For example:
Copy Code To Clipboard
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.
void main() {
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;
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;
Can_Init_Flags = 0; //
Can_Send_Flags = 0; // clear flags
Can_Rcv_Flags = 0; //
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
HW Connection
www.raguvaran.puzl.com
Example of interfacing CAN transceiver MCP2510 with MCU via SPI interface
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.
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.
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.
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
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
Cf_Issue_ID_Command
Cf_Init
Returns Nothing.
www.raguvaran.puzl.com
family)
sbit CF_A0 at LATB0_bit; // for writing to output pin always use latch (PIC18
family)
Cf_Detect
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.
Cf_Enable
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.
Cf_Disable
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.
Cf_Read_Init
Returns Nothing.
Parameters :
Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
Cf_Read_Byte
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.
www.raguvaran.puzl.com
data = Cf_Read_Byte();
Cf_Write_Init
Returns Nothing.
Parameters :
Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
Cf_Write_Byte
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 :
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.
Cf_Read_Sector
www.raguvaran.puzl.com
Returns Nothing.
Description Reads one sector (512 bytes). Read data is stored into buffer provided by
the buffer parameter.
Parameters :
Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
Cf_Write_Sector
Returns Nothing.
Description Writes 512 bytes of data provided by the buffer parameter to one CF sector.
Parameters :
Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
Cf_Fat_Init
Description Initializes CF card, reads CF FAT16 boot sector and extracts necessary data needed by
the library.
www.raguvaran.puzl.com
Requires Nothing.
Cf_Fat_QuickFormat
Parameters :
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.
Cf_Fat_Assign
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.
1 0x02 Hidden
2 0x04 System
4 0x10 Subdirectory
5 0x20 Archive
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.
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
www.raguvaran.puzl.com
Returns Nothing.
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.
Cf_Fat_Read
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.
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.
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.
Cf_Fat_Delete
Returns Nothing.
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.
Cf_Fat_Write
www.raguvaran.puzl.com
Returns Nothing.
Description Writes requested number of bytes to currently assigned file opened for writing.
Parameters :
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.
Cf_Fat_Set_File_Date
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 :
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.
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.
Cf_Fat_Get_File_Date_Modified
Returns Nothing.
Description Retrieves the last modification date/time of the currently assigned file.
Parameters :
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.
Cf_Fat_Get_File_Size
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.
Cf_Fat_Get_Swap_File
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
1 0x02 Hidden
2 0x04 System
4 0x10 Subdirectory
5 0x20 Archive
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:
// 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);
}
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
}
}
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
}
}
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);
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('.');
}
}
}
}
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
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
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.
EEPROM_Write
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.
www.raguvaran.puzl.com
Example EEPROM_Write(0x32, 19);
Library Example
The example demonstrates use of EEPROM Library.
Copy Code To Clipboard
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;
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.
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
Returns Nothing.
Parameters :
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_Write_Command
Returns Nothing.
Parameters :
Value Description
www.raguvaran.puzl.com
S1D13700_DISP_OFF Turn the display off.
S1D13700_Write_Parameter
Returns Nothing.
Parameters :
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
Returns Nothing.
S1D13700_Fill
Returns Nothing.
Parameters :
d: byte to be written.
start: starting address of the memory block.
len: length of the memory block in bytes.
Example // from the starting address of 0x3000, fill the memory block size of 0x7FFF with
0x20
S1D13700_Fill(0x20, 0x3000, 0x7FFF);
S1D13700_GrFill
Returns Nothing.
www.raguvaran.puzl.com
Parameters :
S1D13700_TxtFill
Returns Nothing.
Parameters :
S1D13700_Display_GrLayer
Returns Nothing.
Parameters :
Value Description
www.raguvaran.puzl.com
Requires Glcd module needs to be initialized. See the S1D13700_Init routine.
S1D13700_Display_TxtLayer
Returns Nothing.
Parameters :
Value Description
S1D13700_Set_Cursor
Returns Nothing.
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.
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
Returns Nothing.
Parameters :
Value Description
S1D13700_Write_Char
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".
Example S1D13700_Write_Char('A',22,23,S1D13700_OVERLAY_OR);
S1D13700_Write_Text
Returns Nothing.
Description Writes text in the current text panel of Glcd at coordinates (x, y).
Parameters :
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.
S1D13700_Dot
Returns Nothing.
Description Draws a dot in the current graphic panel of Glcd at coordinates (x, y).
Parameters :
Value Description
S1D13700_Line
Returns Nothing.
Parameters :
Value Description
www.raguvaran.puzl.com
S1D13700_BLACK Black color.
S1D13700_H_Line
Returns Nothing.
Parameters :
Value Description
S1D13700_V_Line
Returns Nothing.
Parameters :
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_Rectangle
Returns Nothing.
Parameters :
Value Description
S1D13700_Box
Returns Nothing.
www.raguvaran.puzl.com
Description Draws a box on Glcd.
Parameters :
Value Description
S1D13700_Rectangle_Round_Edges
Returns Nothing.
Parameters :
Value Description
www.raguvaran.puzl.com
S1D13700_Rectangle_Round_Edges_Fill
Returns Nothing.
Parameters :
Value Description
S1D13700_Circle
Returns Nothing.
Parameters :
Value Description
www.raguvaran.puzl.com
S1D13700_WHITE White color.
S1D13700_Circle_Fill
Returns Nothing.
Parameters :
Value Description
S1D13700_Image
Returns Nothing.
Parameters :
www.raguvaran.puzl.com
Requires Glcd module needs to be initialized. See the S1D13700_Init routine.
Example S1D13700_Image(image);
S1D13700_PartialImage
Returns Nothing.
Parameters :
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.
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
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):
Requires Nothing.
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
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:
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.
Ethernet_Disable
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:
www.raguvaran.puzl.com
4 0x10 not used none
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.
Ethernet_doPacket
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.
Ethernet_putByte
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
Ethernet_putBytes
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:
www.raguvaran.puzl.com
buffer
Ethernet_putConstBytes
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:
Ethernet_putString
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:
www.raguvaran.puzl.com
Ethernet_putConstString
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:
Ethernet_getByte
Description This is MAC module routine. It fetches a byte from address pointed to by current
Ethernet controller's read pointer (ERDPT).
Ethernet_getBytes
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.
Ethernet_UserTCP
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:
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;
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
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:
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;
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
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!
Ethernet_getGwIpAddress
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!
Ethernet_getDnsIpAddress();
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!
Ethernet_getIpMask
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!
Ethernet_confNetwork
Returns Nothing.
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.
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
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:
Note : The Ethernet services are not stopped while this routine waits
for ARP reply. The incoming packets will be processed normaly during this time.
Ethernet_sendUDP
Description This is UDP module routine. It sends an UDP packet on the network.
Parameters:
www.raguvaran.puzl.com
pkt: packet to transmit.
pktLen: length in bytes of packet to transmit.
Ethernet_dnsResolve
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:
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!
www.raguvaran.puzl.com
Ethernet_initDHCP
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:
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.
Example ...
Ethernet_initDHCP(5); // get network configuration from DHCP server, wait 5 sec
for the response
...
Ethernet_doDHCPLeaseTime
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.
www.raguvaran.puzl.com
Example while(1) {
...
if(Ethernet_doDHCPLeaseTime())
... // it's time to renew the IP address lease
}
Ethernet_renewDHCP
Description This is DHCP module routine. It sends IP address lease time renewal request
to DHCP server.
Parameters:
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 :
#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>
" ;
/***********************************
* 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
// 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 ;
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
/*
* 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
// 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;
// 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) ;
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
*/
}
}
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.
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).
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
Requires Nothing.
www.raguvaran.puzl.com
...
FLASH_Read_N_Bytes
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
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.
www.raguvaran.puzl.com
// write contents of the array to the address 0x0D00:
FLASH_Write_64(0x0D00, toWrite);
FLASH_Erase
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
Returns None.
Description Erase then write memory block starting from a given address.
Requires Nothing.
// 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.
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);
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);
}
}
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.
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
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
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>).
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.
Glcd_Set_Side
Returns Nothing.
Description Selects Glcd side. Refer to the Glcd datasheet for detailed explanation.
Parameters :
Note : For side, x axis and page layout explanation see schematic at the bottom of this page.
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
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 :
Note : For side, x axis and page layout explanation see schematic at the bottom of this page.
Example Glcd_Set_X(25);
Glcd_Set_Page
Returns Nothing.
Parameters :
Note : For side, x axis and page layout explanation see schematic at the bottom of this page.
Example Glcd_Set_Page(5);
Glcd_Read_Data
Description Reads data from from the current location of Glcd memory and moves to the next location.
www.raguvaran.puzl.com
Glcd_Write_Data
Returns Nothing.
Description Writes one byte to the current location in Glcd memory and moves to the next location.
Parameters :
Glcd_Set_Ext_Buffer
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).
Example char* ReadExternalBuffer(unsigned long offset, unsigned int count, unsigned int
*num){
unsigned long start_sector;
unsigned int pos;
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
Returns Nothing.
Glcd_Dot
Returns Nothing.
Note : For x and y axis layout explanation see schematic at the bottom of this page.
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.
Parameters :
Glcd_V_Line
Returns Nothing.
Parameters :
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.
Parameters :
Glcd_Rectangle
Returns Nothing.
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.
Glcd_Rectangle_Round_Edges
www.raguvaran.puzl.com
Returns Nothing.
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.
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
Returns Nothing.
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.
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
www.raguvaran.puzl.com
short y_bottom_right, unsigned short color);
Returns Nothing.
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.
Glcd_Circle
Returns Nothing.
Parameters :
Glcd_Circle_Fill
Returns Nothing.
www.raguvaran.puzl.com
Description Draws a filled circle on Glcd.
Parameters :
Glcd_Set_Font
Returns Nothing.
Description Sets font that will be used with Glcd_Write_Char and Glcd_Write_Text routines.
Parameters :
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
Description Sets font that will be used with Glcd_Write_Char_Adv and Glcd_Write_Text_Adv routines.
Returns Nothing.
Notes None.
Glcd_Set_Ext_Font_Adv
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.
Notes None.
Glcd_Write_Char
www.raguvaran.puzl.com
Returns Nothing.
Parameters :
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.
Glcd_Write_Char_Adv
Prototype void Glcd_Write_Char_Adv(unsigned char ch, unsigned int x, unsigned int y);
Returns Nothing.
Example Glcd_Write_Char_Adv('A',22,23,);
Glcd_Write_Text
Returns Nothing.
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
Returns Nothing.
Parameters :
Glcd_Write_Const_Text_Adv
Returns Nothing.
Description Writes text located in the program memory on the glcd at coordinates (x, y).
Parameters :
www.raguvaran.puzl.com
Example const ctext[] = "mikroElektronika"
...
Glcd_Write_Const_Text_Adv(ctext, 0, 0,)
Glcd_Image
Returns Nothing.
Parameters :
Glcd_Ext_Image
Parameters image: image to be displayed. This parameter represents the address in the exteral resource from
where the image data begins.
Returns Nothing.
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
www.raguvaran.puzl.com
Returns Nothing.
Parameters :
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
Description Displays a partial area of the image, located on an external resource, on a desired location of the screen.
Returns Nothing.
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.
//Declarations------------------------------------------------------------------
const code char truck_bmp[1024];
//--------------------------------------------------------------end-declarations
void main() {
unsigned short ii;
char *someText;
while(1) {
#ifdef COMPLETE_EXAMPLE
Glcd_Image(truck_bmp); // Draw image
delay2S(); delay2S();
#endif
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
#ifdef COMPLETE_EXAMPLE
Glcd_Fill(0xFF); // Fill GLCD
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
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.
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
Requires I²C must be configured before using this function. See I2C1_Init.
Example I2C1_Start();
I2C1_Repeated_Start
www.raguvaran.puzl.com
Returns Nothing.
Requires I²C must be configured before using this function. See I2C1_Init.
Example I2C1_Repeated_Start();
I2C1_Is_Idle
Requires I²C must be configured before using this function. See I2C1_Init.
I2C1_Rd
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.
I2C1_Wr
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
Returns Nothing.
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
Delay_100ms();
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.
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
Returns Nothing.
Keypad_Key_Press
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.
Keypad_Key_Click
www.raguvaran.puzl.com
Prototype char Keypad_Key_Click(void);
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.
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.
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
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.
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
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.
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 :
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 :
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 :
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 :
Lcd_Cmd
Prototype void Lcd_Cmd(char out_char);
Returns Nothing.
Parameters :
Note : Predefined constants can be passed to the function, see Available Lcd Commands.
www.raguvaran.puzl.com
Lcd Command Purpose
_LCD_RETURN_HOME Return cursor to home position, returns a shifted display to its original position. Display data
RAM is unaffected.
Library Example
The following code demonstrates usage of the Lcd Library routines:
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;
void main(){
ANSEL = 0; // Configure AN pins as digital I/O
ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;
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();
}
www.raguvaran.puzl.com
Move_Delay();
}
}
}
Lcd HW connection
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.
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
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.
Man_Receive
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.
www.raguvaran.puzl.com
Man_Send_Init
Returns Nothing.
Man_Send
Returns Nothing.
Parameters :
Requires To use this function, the user must prepare the MCU for sending. See Man_Send_Init.
Man_Synchro
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.
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.
void interrupt {
if (INTCON.T0IF) {
if (counter >= 20) {
Man_Break();
counter = 0; // reset counter
}
else
counter++; // increment counter
}
}
void main() {
...
Man_Receive_Init();
...
...
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:
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
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:
void main() {
Connection Example
www.raguvaran.puzl.com
Simple Transmitter connection
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
Parameters None.
Returns Nothing.
Requires Nothing.
Notes None.
Malloc
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..
Requires Nothing.
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
Returns Nothing.
Requires Nothing.
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
Description This function is used to determine largest available free memory block for the Heap.
Parameters None.
www.raguvaran.puzl.com
Requires Nothing.
void main() {
block = MM_LargestFreeMemBlock();
}
Notes None.
MM_TotalFreeMemSize
Parameters None.
Requires Nothing.
void main() {
block = MM_TotalFreeMemSize();
}
Notes None.
www.raguvaran.puzl.com
digital camcorders, handheld computers, media players, mobile phones, GPS receivers, video games
and PDAs.
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.
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
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
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.
Mmc_Read_Sector
Description The function reads one sector (512 bytes) from MMC card.
Parameters:
Mmc_Write_Sector
Description The function writes 512 bytes of data to one MMC card sector.
Parameters:
www.raguvaran.puzl.com
Requires MMC/SD card must be initialized. See Mmc_Init.
Mmc_Read_Cid
Parameters:
data_cid: buffer of minimum 16 bytes in length for storing CID register content.
Mmc_Read_Csd
Parameters:
data_csd: buffer of minimum 16 bytes in length for storing CSD register content.
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.
Notes None.
Mmc_Multi_Read_Sector
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.
Returns Nothing.
Notes None.
Mmc_Multi_Read_Stop
www.raguvaran.puzl.com
Description The function stops multi read mode sequence.
Parameters None.
Example Mmc_Multi_Read_Stop;
Notes None.
Mmc_Fat_Init
Description Initializes MMC/SD card, reads MMC/SD FAT16 boot sector and extracts necessary data needed by the library.
Mmc_Fat_QuickFormat
www.raguvaran.puzl.com
Prototype unsigned char Mmc_Fat_QuickFormat(char *mmc_fat_label);
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.
Example // Format and initialize MMC/SD card and MMC_FAT16 library globals
if (!Mmc_Fat_QuickFormat(&mmc_fat_label)) {
...
}
Mmc_Fat_Assign
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
1 0x02 Hidden
2 0x04 System
www.raguvaran.puzl.com
3 0x08 Volume Label
4 0x10 Subdirectory
5 0x20 Archive
File creation flag. If file does not exist and this flag is set, a new file with
7 0x80
specified name will be created.
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
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.
Mmc_Fat_Read
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.
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.
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.
www.raguvaran.puzl.com
Mmc_Fat_Delete
Returns Nothing.
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.
Mmc_Fat_Write
Returns Nothing.
Description Writes requested number of bytes to the currently assigned file opened for writing.
Parameters:
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
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.
Mmc_Fat_Get_File_Date
Returns Nothing.
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.
Mmc_Fat_Get_File_Date_Modified
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.
Mmc_Fat_Get_File_Size
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.
Mmc_Get_File_Write_Sector
www.raguvaran.puzl.com
Prototype unsigned long Mmc_Get_File_Write_Sector();
Parameters None.
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.
Notes None.
Mmc_Fat_Get_Swap_File
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:
1 0x02 Hidden
2 0x04 System
4 0x10 Subdirectory
5 0x20 Archive
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
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.
position = Mmc_Fat_Tell();
Notes None.
Mmc_Fat_Seek
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.
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.
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
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
Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
Notes None.
Mmc_Fat_RenameDir
Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
Notes None.
www.raguvaran.puzl.com
Mmc_Fat_RemoveDir
Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
Notes Recursive removing is not supported, i.e. the directory must be empty before it can be removed.
Mmc_Fat_ChangeDir
Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
// 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
Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
Notes None.
Mmc_Fat_Dir
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.
...
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.
// 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);
}
www.raguvaran.puzl.com
file_contents[1] = loop % 10 + 48;
Mmc_Fat_Write(file_contents, LINE_LEN-1); // write data to the assigned file
}
}
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
}
}
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);
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);
if (size) {
LongToStr((signed long)size, err_txt);
UART1_Write_Line(err_txt);
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.
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
www.raguvaran.puzl.com
Returns 0 if the device is present
1 if the device is not present
Parameters :
Ow_Reset(&PORTE, 2);
Ow_Read
Returns Data read from an external device over the OneWire bus.
Parameters :
Ow_Write
Prototype void Ow_Write(unsigned short *port, unsigned short pin, unsigned short par);
Returns Nothing.
Parameters :
www.raguvaran.puzl.com
port: OneWire bus port
pin: OneWire bus pin
par: data to be written
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.
// Extract temp_whole
temp_whole = temp2write >> RES_SHIFT ;
www.raguvaran.puzl.com
text[0] = temp_whole/100 + 48;
else
text[0] = '0';
void main() {
ANSEL = 0; // Configure AN pins as digital I/O
ANSELH = 0;
C1ON_bit = 0; // Disable comparators
C2ON_bit = 0;
Lcd_Chr(2,14,'C');
Ow_Reset(&PORTE, 2);
Ow_Write(&PORTE, 2, 0xCC); // Issue command SKIP_ROM
Ow_Write(&PORTE, 2, 0xBE); // Issue command READ_SCRATCHPAD
Delay_ms(500);
} while (1);
}
www.raguvaran.puzl.com
HW Connection
www.raguvaran.puzl.com
Example of DS1820 connection
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
Returns Nothing.
Requires Nothing.
Example Unlock_IOLOCK();
Lock_IOLOCK
Returns Nothing.
Requires Nothing.
Example Lock_IOLOCK();
www.raguvaran.puzl.com
PPS_Mapping
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
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()
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
_NULL The NULL function is assigned to all RPn outputs at device Reset and disables the RPn output function.
www.raguvaran.puzl.com
Function Name (Input) Description
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 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
Returns Nothing.
ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
...
Expander_Init_Advanced
Returns Nothing.
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
...
Expander_Read_Byte
Parameters :
ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
RegAddress: Port Expander's internal register address
www.raguvaran.puzl.com
Expander_Write_Byte
Returns Nothing.
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
Expander_Read_PortA
Parameters :
ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
Expander_Read_PortB
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
Expander_Read_PortAB
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
Expander_Write_PortA
Returns Nothing.
www.raguvaran.puzl.com
Parameters :
ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
Data_: data to be written
...
Expander_Set_DirectionPortA(0,0x00); // set expander's porta to be output
...
Expander_Write_PortA(0, 0xAA);
Expander_Write_PortB
Returns Nothing.
Parameters :
ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
Data_: data to be written
...
Expander_Set_DirectionPortB(0,0x00); // set expander's portb to be output
...
Expander_Write_PortB(0, 0x55);
Expander_Write_PortAB
Returns Nothing.
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
...
Expander_Set_DirectionPortAB(0,0x0000); // set expander's porta and portb to
be output
...
Expander_Write_PortAB(0, 0xAA55);
Expander_Set_DirectionPortA
Returns Nothing.
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.
Expander_Set_DirectionPortB
Returns Nothing.
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.
Expander_Set_DirectionPortAB
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.
Expander_Set_PullUpsPortA
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.
www.raguvaran.puzl.com
Expander_Set_PullUpsPortB
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.
Expander_Set_PullUpsPortAB
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.
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
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;
www.raguvaran.puzl.com
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.
PS/2 Data
extern sfr sbit PS2_Data; sbit PS2_Data at RC0_bit;
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
Returns Nothing.
Description Initializes the MCU for work with the PS/2 keyboard.
www.raguvaran.puzl.com
Requires Global variables :
Ps2_Key_Read
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.
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
void main() {
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
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
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.
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.
PWM1_Init(5000);
PWM1_Set_Duty
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.
PWM1_Set_Duty(192);
PWM1_Start
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
Returns Nothing.
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
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
www.raguvaran.puzl.com
PWM1_Set_Duty(current_duty);
}
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 Routines
RS485Master_Init
RS485Master_Receive
RS485Master_Send
RS485Slave_Init
RS485Slave_Receive
RS485Slave_Send
www.raguvaran.puzl.com
RS485Master_Init
Returns Nothing.
// 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
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:
Requires MCU must be initialized as a Master for RS-485 communication. See RS485Master_Init.
www.raguvaran.puzl.com
RS485Master_Send
Returns Nothing.
Description Sends message to Slave(s). Message format can be found at the bottom of this page.
Parameters :
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.
RS485Slave_Init
Returns Nothing.
Parameters :
// 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
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:
Requires MCU must be initialized as a Slave for RS-485 communication. See RS485Slave_Init.
RS485Slave_Send
Returns Nothing.
Description Sends message to Master. Message format can be found at the bottom of this page.
Parameters :
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.
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.
// Interrupt routine
void interrupt() {
RS485Master_Receive(dat);
}
void main(){
long cnt = 0;
PORTB = 0;
PORTD = 0;
TRISB = 0;
TRISD = 0;
RS485Master_Send(dat,1,160);
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
}
}
// 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;
www.raguvaran.puzl.com
dat[6] = 0; // ensure that error flag is 0
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
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++;
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.
Library Routines
Soft_I2C_Init
Soft_I2C_Start
Soft_I2C_Read
Soft_I2C_Write
Soft_I2C_Stop
Soft_I2C_Break
Soft_I2C_Init
Returns Nothing.
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.
...
Soft_I2C_Init();
Soft_I2C_Start
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.
Soft_I2C_Read
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.
Soft_I2C_Write
www.raguvaran.puzl.com
Prototype unsigned short Soft_I2C_Write(unsigned short data_);
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.
Soft_I2C_Stop
Returns Nothing.
Requires Soft I²C must be configured before using this function. See Soft_I2C_Init routine.
Soft_I2C_Break
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
}
}
void main() {
...
...
}
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
www.raguvaran.puzl.com
// End LCD module connections
char seconds, minutes, hours, day, month, year; // Global date/time variables
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;
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
}
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.
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.
Soft_SPI_Read
Description This routine performs 3 operations simultaneously. It provides clock for the
Software SPI bus, reads a byte and sends a byte.
Parameters :
Requires Soft SPI must be initialized before using this function. See Soft_SPI_Init routine.
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 :
Requires Soft SPI must be initialized before using this function. See Soft_SPI_Init routine.
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.
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
}
www.raguvaran.puzl.com
}
void main() {
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
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);
Requires Software UART must be initialized before using this function. See
the Soft_UART_Init routine.
Soft_UART_Write
Returns Nothing.
Description This routine sends one byte via the Software UART bus.
Parameters :
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.
www.raguvaran.puzl.com
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.
void interrupt() {
if (INTCON.T0IF) {
if (counter >= 20) {
Soft_UART_Break();
counter = 0; // reset counter
}
else
counter++; // increment counter
}
}
void main() {
...
if (Soft_UART_Init(&PORTC, 7, 6, 9600, 0) == 0)
Soft_UART_Write(0x55);
...
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
void main(){
for (i = 'z'; i >= 'A'; i--) { // Send bytes from 'z' downto 'A'
Soft_UART_Write(i);
Delay_ms(100);
}
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
Returns Nothing.
Parameters :
Requires Nothing.
Sound_Play
Returns Nothing.
Parameters :
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.
Library Example
The example is a simple demonstration of how to use the Sound Library for playing tones on a piezo
speaker.
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 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() {
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
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
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
www.raguvaran.puzl.com
SPIx_Init_Advanced
Returns Nothing.
www.raguvaran.puzl.com
Clock idle LOW _SPI_CLK_IDLE_LOW
Transmit edge:
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
Parameters :
buffer: dummy data for clock generation (see device Datasheet for SPI
modules implementation details)
SPIx_Write
Returns Nothing.
www.raguvaran.puzl.com
Description Writes byte via the SPI bus.
Parameters :
SPI_Set_Active
Returns Nothing.
Description Sets the active SPI module which will be used by the SPI routines.
Parameters :
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
SPI_Read
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)
SPI_Write
Returns Nothing.
This is a generic routine which uses the active SPI module previously activated by
the SPI_Set_Active routine.
Parameters :
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
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
}
void main() {
ANSEL = 0;
ANSELH = 0;
InitMain(); // Perform main initialization
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 Routines
SPI_Remappable_Init
SPI_Remappable_Init_Advanced
SPI_Remappable_Read
SPI_Remappable_Write
SPI_Remappable_Init
Returns Nothing.
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.
SPI_Remappable_Init_Advanced
www.raguvaran.puzl.com
Returns Nothing.
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
Transmit edge:
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
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.
SPI_Remappable_Write
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.
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 :
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.
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.
Library Routines
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
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:
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).
The SPI module needs to be initialized. See the SPIx_Init and SPIx_Init_Advanced routines.
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
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:
www.raguvaran.puzl.com
enabled.
Note :
SPI_Ethernet_Disable
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:
Note :
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.
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.
SPI_Ethernet_putByte
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
SPI_Ethernet_putBytes
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:
SPI_Ethernet_putConstBytes
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:
www.raguvaran.puzl.com
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
SPI_Ethernet_putString
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:
SPI_Ethernet_putConstString
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:
www.raguvaran.puzl.com
SPI_Ethernet_getByte
Description This is MAC module routine. It fetches a byte from address pointed to by current ENC28J60 read pointer
(ERDPT).
SPI_Ethernet_getBytes
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:
SPI_Ethernet_UserTCP
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:
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.
Example This function is internally called by the library and should not be called by the user's code.
SPI_Ethernet_UserUDP
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:
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.
Example This function is internally called by the library and should not be called by the user's code.
SPI_Ethernet_getIpAddress
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!
SPI_Ethernet_getGwIpAddress
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!
SPI_Ethernet_getDnsIpAddress
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!
SPI_Ethernet_getIpMask
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!
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
Returns Nothing.
Descriptio Configures network parameters (IP subnet mask, gateway IP address, DNS IP address) when DHCP is not
n used.
Parameters:
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.
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
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:
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.
SPI_Ethernet_sendUDP
Description This is UDP module routine. It sends an UDP packet on the network.
Parameters:
SPI_Ethernet_dnsResolve
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:
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!
SPI_Ethernet_initDHCP
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:
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
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.
Example while(1) {
...
if(SPI_Ethernet_doDHCPLeaseTime())
... // it's time to renew the IP address lease
}
SPI_Ethernet_renewDHCP
Description This is DHCP module routine. It sends IP address lease time renewal request to DHCP server.
Parameters:
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 :
#include "__EthEnc28j60.h"
/************************************************************
* 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>
" ;
/***********************************
* 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
// 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 ;
www.raguvaran.puzl.com
len += putConstString(httpMimeTypeScript) ; // with text MIME type
/*
* 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
// the total length of the request is the length of the dynamic string plus the text of
the request
len = 28 + reqLength;
// 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
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
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.
Important :
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.
Library Routines
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
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):
www.raguvaran.puzl.com
Set Full duplex Mode SPI_Ethernet_24j600_FULLDUPLEX
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.
The SPI module needs to be initialized. See the SPIx_Init and SPIx_Init_Advanced routines.
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
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:
Note :
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.
SPI_Ethernet_24j600_Disable
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:
www.raguvaran.puzl.com
3 0x08 not used none
Note :
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.
SPI_Ethernet_24j600_putByte
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
SPI_Ethernet_24j600_putBytes
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:
SPI_Ethernet_24j600_putConstBytes
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:
SPI_Ethernet_24j600_putString
www.raguvaran.puzl.com
Prototype unsigned int SPI_Ethernet_24j600_putString(unsigned char *ptr);
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:
SPI_Ethernet_24j600_putConstString
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:
SPI_Ethernet_24j600_getByte
Description This is MAC module routine. It fetches a byte from address pointed to by current ENC24J600 read pointer
www.raguvaran.puzl.com
(ERDPT).
SPI_Ethernet_24j600_getBytes
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:
SPI_Ethernet_24j600_UserTCP
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:
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.
Example This function is internally called by the library and should not be called by the user's code.
SPI_Ethernet_24j600_UserUDP
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:
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.
Example This function is internally called by the library and should not be called by the user's code.
SPI_Ethernet_24j600_getIpAddress
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!
SPI_Ethernet_24j600_getGwIpAddress
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!
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
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!
SPI_Ethernet_24j600_getIpMask
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!
www.raguvaran.puzl.com
SPI_Ethernet_24j600_confNetwork
Returns Nothing.
Descriptio Configures network parameters (IP subnet mask, gateway IP address, DNS IP address) when DHCP is not used.
n Parameters:
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.
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
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:
Note : The Ethernet services are not stopped while this routine waits for ARP reply. The incoming packets
will be processed normaly during this time.
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
Description This is UDP module routine. It sends an UDP packet on the network.
Parameters:
SPI_Ethernet_24j600_dnsResolve
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:
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!
SPI_Ethernet_24j600_initDHCP
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:
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.
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
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.
Example while(1) {
...
if(SPI_Ethernet_24j600_doDHCPLeaseTime())
... // it's time to renew the IP address lease
}
SPI_Ethernet_24j600_renewDHCP
Description This is DHCP module routine. It sends IP address lease time renewal request to DHCP server.
Parameters:
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 :
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"
/************************************************************
* 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>
" ;
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
// 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 ;
www.raguvaran.puzl.com
IntToStr(PORTB, dyna) ;
len += putString(dyna) ;
len += putConstString(";") ;
/*
* 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
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;
// 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
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 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
Returns Nothing.
DeviceAddress: SPI expander hardware address, see schematic at the bottom of this page
The SPI module needs to be initialized. See SPIx_Init and SPIx_Init_Advanced routines.
...
SPI_Glcd_Set_Side
Returns Nothing.
Description Selects Glcd side. Refer to the Glcd datasheet for detail explanation.
Parameters :
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
Returns Nothing.
Parameters :
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
Returns Nothing.
Description Sets x-axis position to x_pos dots from the left border of Glcd within the selected side.
Parameters :
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
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.
SPI_Glcd_Write_Data
Returns Nothing.
Description Writes one byte to the current location in Glcd memory and moves to the next location.
Parameters :
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.
SPI_Glcd_Set_Ext_Buffer
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;
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
Returns Nothing.
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.
SPI_Glcd_Dot
www.raguvaran.puzl.com
Returns Nothing.
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.
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.
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.
SPI_Glcd_V_Line
Prototype void SPI_Glcd_V_Line(char y_start, char y_end, char x_pos, char color);
Returns Nothing.
www.raguvaran.puzl.com
Parameters :
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.
SPI_Glcd_H_Line
Prototype void SPI_Glcd_H_Line(char x_start, char x_end, char y_pos, char color);
Returns Nothing.
Parameters :
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.
SPI_Glcd_Rectangle
Return Nothing.
s
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
SPI_Glcd_Rectangle_Round_Edges
Returns Nothing.
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.
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
Returns Nothing.
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.
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
Returns Nothing.
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
SPI_Glcd_Circle
Prototype void SPI_Glcd_Circle(int x_center, int y_center, int radius, char color);
Returns Nothing.
Parameters :
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.
SPI_Glcd_Circle_FIll
Prototype void SPI_Glcd_Circle_Fill(int x_center, int y_center, int radius, char color
);
Returns Nothing.
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
SPI_Glcd_Set_Font
Returns Nothing.
Description Sets font that will be used with SPI_Glcd_Write_Char and SPI_Glcd_Write_Text routines.
Parameters :
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:
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
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.
Returns Nothing.
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
Notes None.
SPI_Glcd_Set_Ext_Font_Adv
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.
Notes None.
SPI_Glcd_Write_Char
Prototype void SPI_Glcd_Write_Char(char chr1, char x_pos, char page_num, char color);
Returns Nothing.
Parameters :
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.
SPI_Glcd_Write_Char_Adv
Returns Nothing.
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.
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
Returns Nothing.
Parameters :
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
Returns Nothing.
Description Writes text located in the program memory on the glcd at coordinates (x, y).
Parameters :
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
SPI_Glcd_Image
Returns Nothing.
Parameters :
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.
SPI_Glcd_Ext_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
Returns Nothing.
Parameters :
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
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.
Returns Nothing.
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
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.
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;
www.raguvaran.puzl.com
// // If Port Expander Library uses SPI2 module
// SPI2_Init(); // Initialize SPI module used with PortExpander
while(1) {
#ifdef COMPLETE_EXAMPLE
SPI_Glcd_Image(truck_bmp); // Draw image
Delay2s(); Delay2s();
#endif
SPI_Glcd_Fill(0x00); // Clear Glcd
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
#ifdef COMPLETE_EXAMPLE
SPI_Glcd_Box(12,20, 70,63, 2); // Draw box
Delay2s();
www.raguvaran.puzl.com
HW Connection
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 Routines
SPI_Lcd_Config
SPI_Lcd_Out
SPI_Lcd_Out_Cp
SPI_Lcd_Chr
SPI_Lcd_Chr_Cp
SPI_Lcd_Cmd
SPI_Lcd_Config
Returns Nothing.
www.raguvaran.puzl.com
sbit SPExpanderRST_Direction at TRISC0_bit;
sbit SPExpanderCS_Direction at TRISC1_bit;
// End Port Expander module connections
void main() {
SPI_Lcd_Out
Returns Nothing.
Description Prints text on the Lcd starting from specified position. Both string variables and literals
can be passed as a text.
Parameters :
Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd_Config routines.
SPI_Lcd_Out_Cp
Returns Nothing.
Description Prints text on the Lcd at current cursor position. Both string variables and literals can
be passed as a text.
Parameters :
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
Returns Nothing.
Description Prints character on Lcd at specified position. Both variables and literals can be passed
as character.
Parameters :
Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd_Config routines.
SPI_Lcd_Chr_Cp
Returns Nothing.
Description Prints character on Lcd at current cursor position. Both variables and literals can be
passed as character.
Parameters :
Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd_Config routines.
SPI_Lcd_Cmd
www.raguvaran.puzl.com
Prototype void SPI_Lcd_Cmd(char out_char);
Returns Nothing.
Parameters :
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.
_LCD_RETURN_HOME Return cursor to home position, returns a shifted display to its original position. Display
data RAM is unaffected.
www.raguvaran.puzl.com
SPI Lcd Command Purpose
Library Example
This example demonstrates how to communicate Lcd via the SPI module, using serial to parallel
convertor MCP23S17.
void main() {
HW Connection
www.raguvaran.puzl.com
SPI Lcd HW connection
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 Routines
SPI_Lcd8_Config
SPI_Lcd8_Out
SPI_Lcd8_Out_Cp
SPI_Lcd8_Chr
SPI_Lcd8_Chr_Cp
SPI_Lcd8_Cmd
SPI_Lcd8_Config
Returns Nothing.
www.raguvaran.puzl.com
// End Port Expander module connections
...
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 :
Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd8_Config routine.
SPI_Lcd8_Out_Cp
Returns Nothing.
Description Prints text on Lcd at current cursor position. Both string variables and literals can be
passed as a text.
Parameters :
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
Returns Nothing.
Description Prints character on Lcd at specified position. Both variables and literals can be passed
as character.
Parameters :
Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd8_Config routine.
SPI_Lcd8_Chr_Cp
Returns Nothing.
Description Prints character on Lcd at current cursor position. Both variables and literals can be
passed as character.
Parameters :
Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd8_Config routine.
www.raguvaran.puzl.com
SPI_Lcd8_Cmd
Returns Nothing.
Parameters :
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.
_LCD_RETURN_HOME Return cursor to home position, returns a shifted display to its original position. Display
data RAM is unaffected.
www.raguvaran.puzl.com
SPI Lcd8 Command Purpose
Library Example
This example demonstrates how to communicate Lcd in 8-bit mode via the SPI module, using serial to
parallel convertor MCP23S17.
void main() {
HW Connection
www.raguvaran.puzl.com
SPI Lcd8 HW connection
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:
RS C/D
R/W /RD
E /WR
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
Returns Nothing.
Parameters :
www.raguvaran.puzl.com
+ + |
+---------------------+ | PANEL 1
+ TEXT PANEL #1 + |
+ + |
+---------------------+ \/
...
SPI_T6963C_writeData
Returns Nothing.
Example SPI_T6963C_writeData(AddrL);
SPI_T6963C_writeCommand
Returns Nothing.
www.raguvaran.puzl.com
Description Writes command to T6963C controller via SPI interface.
Parameters :
Example SPI_T6963C_writeCommand(SPI_T6963C_CURSOR_POINTER_SET);
SPI_T6963C_setPtr
Returns Nothing.
Parameters :
SPI_T6963C_Set_Ext_Buffer
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).
Example char* ReadExternalBuffer(unsigned long offset, unsigned int count, unsigned int
*num){
www.raguvaran.puzl.com
unsigned long start_sector;
unsigned int pos;
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
Returns Nothing.
Description Pools the status byte, and loops until Toshiba Glcd module is ready.
Example SPI_T6963C_waitReady();
SPI_T6963C_fill
Returns Nothing.
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
Example SPI_T6963C_fill(0x33,0x00FF,0x000F);
SPI_T6963C_dot
Returns Nothing.
Description Draws a dot in the current graphic panel of Glcd at coordinates (x, y).
Parameters :
SPI_T6963C_Set_Font_Adv
Returns Nothing.
Notes None.
www.raguvaran.puzl.com
SPI_T6963C_Set_Ext_Font_Adv
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.
Notes None.
SPI_T6963C_write_char
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:
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.
Exampl SPI_T6963C_write_char("A",22,23,SPI_T6963C_ROM_MODE_AND);
e
SPI_T6963C_write_char_adv
Description Writes a char in the current text panel of Glcd at coordinates (x, y).
Returns Nothing.
Example SPI_T6963C_Write_Char_Adv('A',22,23);
Notes None.
SPI_T6963C_write_text
Returns Nothing.
Descript Writes text in the current text panel of Glcd at coordinates (x, y).
ion
Parameters :
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_Write_Text_Adv
Description Writes text in the current text panel of Glcd at coordinates (x, y).
Returns Nothing.
Notes None.
SPI_T6963C_Write_Const_Text_Adv
www.raguvaran.puzl.com
Description Writes text located in the program memory on the glcd at coordinates (x, y).
Returns Nothing.
Notes None.
SPI_T6963C_line
Prototype void SPI_T6963C_line(int x0, int y0, int x1, int y1, unsigned
char pcolor);
Returns Nothing.
Parameters :
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 :
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.
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.
www.raguvaran.puzl.com
Parameters :
SPI_T6963C_box
Prototype void SPI_T6963C_box(int x0, int y0, int x1, int y1, unsigned
char pcolor);
Returns Nothing.
Parameters :
SPI_T6963C_circle
Returns Nothing.
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
SPI_T6963C_circle_fill
Returns Nothing.
Parameters :
SPI_T6963C_image
Returns Nothing.
Parameters :
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
Parameters pic: image to be displayed. This parameter represents the address in the
exteral resource from where the image data begins.
Returns Nothing.
Example SPI_T6963C_Ext_image(153608);
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
Returns Nothing.
Parameters :
www.raguvaran.puzl.com
Note : Image dimension must match the display dimension.
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
Returns Nothing.
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.
SPI_T6963C_set_cursor
Returns Nothing.
Parameters :
SPI_T6963C_clearbit
Returns Nothing.
Parameters :
b: bit mask. The function will clear bit x on control port if bit x in bit mask
is set to 1.
www.raguvaran.puzl.com
Example // clear bits 0 and 1 on control port
SPI_T6963C_clearBit(0x03);
SPI_T6963C_setBit
Returns Nothing.
Parameters :
b: bit mask. The function will set bit x on control port if bit x in bit mask is
set to 1.
SPI_T6963C_negBit
Returns Nothing.
Parameters :
b: bit mask. The function will negate bit x on control port if bit x in bit
mask is set to 1.
SPI_T6963C_DisplayGrPanel
Returns Nothing.
www.raguvaran.puzl.com
Description Display selected graphic panel.
Parameters :
SPI_T6963C_displayTxtPanel
Returns Nothing.
Parameters :
SPI_T6963C_setGrPanel
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 :
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 :
SPI_T6963C_panelFill
Returns Nothing.
Description Fill current panel in full (graphic+text) with appropriate value (0 to clear).
Parameters :
SPI_T6963C_grFill
Returns Nothing.
Parameters :
www.raguvaran.puzl.com
Example // clear current graphic panel
SPI_T6963C_grFill(0);
SPI_T6963C_txtFill
Returns Nothing.
Parameters :
SPI_T6963C_cursor_height
Returns Nothing.
Parameters :
Example SPI_T6963C_cursor_height(7);
SPI_T6963C_graphics
Returns Nothing.
www.raguvaran.puzl.com
Parameters :
SPI_T6963C_text
Returns Nothing.
Parameters :
SPI_T6963C_cursor
Returns Nothing.
Parameters :
n: on/off parameter. Valid values: 0 (set cursor off) and 1 (set cursor on).
www.raguvaran.puzl.com
SPI_T6963C_cursor_blink
Returns Nothing.
Parameters :
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.
#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[];
void main() {
char txt1[] = " EINSTEIN WOULD HAVE LIKED mE";
char txt[] = " GLCD LIBRARY DEMO, WELCOME !";
www.raguvaran.puzl.com
C2ON_bit = 0;
/*
* 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
*/
/*
* 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);
/*
* 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
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
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
www.raguvaran.puzl.com
Returns Nothing.
Parameters :
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
Returns Nothing.
Parameters :
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_writeData(AddrL);
T6963C_writeCommand
Returns Nothing.
Parameters :
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_writeCommand(T6963C_CURSOR_POINTER_SET);
T6963C_setPtr
www.raguvaran.puzl.com
Returns Nothing.
Parameters :
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
T6963C_Set_Ext_Buffer
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).
Example char* ReadExternalBuffer(unsigned long offset, unsigned int count, unsigned int
*num){
unsigned long start_sector;
unsigned int pos;
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
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.
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
Returns Nothing.
Description Draws a dot in the current graphic panel of Glcd at coordinates (x, y).
www.raguvaran.puzl.com
Parameters :
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
T6963C_Set_Font_Adv
Description Sets font that will be used with T6963C_Write_Char_Adv and T6963C_Write_Text_Adv routines.
Returns Nothing.
Notes None.
T6963C_Set_Ext_Font_Adv
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.
www.raguvaran.puzl.com
Notes None.
T6963C_write_char
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
Description Writes a char in the current text panel of Glcd at coordinates (x, y).
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
Returns Nothing.
Descriptio Writes text in the current text panel of Glcd at coordinates (x, y).
n
Parameters :
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.
T6963C_Write_Text_Adv
www.raguvaran.puzl.com
Description Writes text in the current text panel of Glcd at coordinates (x, y).
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Notes None.
T6963C_Write_Text_Const_Adv
Description Writes text located in the program memory on the glcd at coordinates (x, y).
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
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 :
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
T6963C_rectangle
Prototype void T6963C_rectangle(int x0, int y0, int x1, int y1, unsigned char pcolor);
Returns Nothing.
Parameters :
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
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.
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.
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.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
T6963C_box
Prototype void T6963C_box(int x0, int y0, int x1, int y1, unsigned char pcolor);
Returns Nothing.
Parameters :
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
Returns Nothing.
Parameters :
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
T6963C_circle_fill
Returns Nothing.
Parameters :
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
T6963C_image
Returns Nothing.
www.raguvaran.puzl.com
Description Displays bitmap on Glcd.
Parameters :
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_image(mc);
T6963C_Ext_Image
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);
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
Returns Nothing.
Parameters :
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.
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
Returns Nothing.
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.
T6963C_set_cursor
Returns Nothing.
Parameters :
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
T6963C_clearBit
Returns Nothing.
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.
T6963C_setBit
Returns Nothing.
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.
T6963C_negBit
Returns Nothing.
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.
T6963C_displayGrPanel
www.raguvaran.puzl.com
Prototype void T6963C_displayGrPanel(char n);
Returns Nothing.
Parameters :
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
T6963C_displayTxtPanel
Returns Nothing.
Parameters :
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
T6963C_setGrPanel
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 :
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
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 :
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
T6963C_panelFill
Returns Nothing.
Description Fill current panel in full (graphic+text) with appropriate value (0 to clear).
Parameters :
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
T6963C_grFill
Returns Nothing.
www.raguvaran.puzl.com
Parameters :
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
T6963C_txtFill
Returns Nothing.
Parameters :
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
T6963C_cursor_height
Returns Nothing.
Parameters :
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_cursor_height(7);
T6963C_graphics
www.raguvaran.puzl.com
Returns Nothing.
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.
T6963C_text
Returns Nothing.
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.
T6963C_cursor
Returns Nothing.
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.
www.raguvaran.puzl.com
T6963C_cursor_blink
Returns Nothing.
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.
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.
#include "__T6963C.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[];
www.raguvaran.puzl.com
void main() {
char txt1[] = " EINSTEIN WOULD HAVE LIKED mE";
char txt[] = " GLCD LIBRARY DEMO, WELCOME !";
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);
/*
* 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)).
extern sfr sbit TFT_CS; Chip Select signal. sbit TFT_CS at LATG3_bit;
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
Returns Nothing.
Description Initializes HX8347-D display controller display in the 8-bit working mode.
Parameters :
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_Init_HX8347G
Returns Nothing.
Description Initializes HX8347-G display controller display in the 8-bit working mode.
Parameters :
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.
TFT_Init_SSD1963_8bit
Returns Nothing.
Description Initializes SSD1963 display controller display in the 8-bit working mode.
Parameters :
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.
TFT_Init_R61526
Returns Nothing.
Description Initializes R61526 display controller display in the 8-bit working mode.
Parameters :
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;
TFT_Init_SST7715R
Returns Nothing.
Description Initializes SST7715R display controller display in the 8-bit working mode.
Parameters :
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
TFT_Set_Index
Returns Nothing.
Description Accesses register space of the controller and sets the desired register.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_Write_Command
Returns Nothing.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_Write_Data
www.raguvaran.puzl.com
Prototype void TFT_Write_Data(unsigned int _data);
Returns Nothing.
Parameters :
_data:data to be written.
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_Set_Reg
Returns Nothing.
Description Accesses register space of the controller and writes a value in the desired register.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_Set_Ext_Buffer
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;
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
Returns Nothing.
Description This function sets appropriate pointers to a user-defined basic routines in order to enable multiple working modes.
Parameters :
Requires None.
Example // Example of establishing 16-bit communication between TFT display and PORTD, PORTE
of MCU :
www.raguvaran.puzl.com
TFT_RS = 0;
Lo(LATD) = index;
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
Returns Nothing.
Parameters :
None.
Requires None.
Example TFT_Set_Default_Mode();
TFT_Init(320, 240);
TFT_Set_Font
www.raguvaran.puzl.com
Returns Nothing.
Parameters :
Value Description
Value Description
www.raguvaran.puzl.com
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_Set_Ext_Font
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
www.raguvaran.puzl.com
CL_WHITE White color
Value Description
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
Returns Nothing.
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.
Parameters :
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
Returns Nothing.
Description Writes text located in the program memory on the TFT at coordinates (x, y).
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_Fill_Screen
Returns Nothing.
Parameters :
Value Description
www.raguvaran.puzl.com
CL_LIME Lime color
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
Example TFT_Fill_Screen(CL_BLACK);
TFT_Dot
Returns Nothing.
Parameters :
Value Description
www.raguvaran.puzl.com
CL_GRAY Gray color
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_Set_Pen
Returns Nothing.
Description Sets color and thickness parameter for drawing line, circle and rectangle elements.
Parameters :
Value Description
www.raguvaran.puzl.com
CL_FUCHSIA Fuchsia color
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_Set_Brush
Returns Nothing.
Description Sets color and gradient which will be used to fill circles or rectangles.
Parameters :
Value Description
www.raguvaran.puzl.com
0 Disable brush fill.
Value Description
Value Description
1 Enable gradient.
0 Disable gradient.
Value Description
www.raguvaran.puzl.com
Value Description
Value Description
www.raguvaran.puzl.com
CL_MAROON Maroon color
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_Line
Prototype void TFT_Line(int x1, int y1, int x2, int y2);
Returns Nothing.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
www.raguvaran.puzl.com
TFT_H_Line
Returns Nothing.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_V_Line
Returns Nothing.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_Rectangle
Returns Nothing.
www.raguvaran.puzl.com
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_Rectangle_Round_Edges
Returns Nothing.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_Circle
Returns Nothing.
Parameters :
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.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_Ext_Image
Returns Nothing.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_Partial_Image
www.raguvaran.puzl.com
image,unsigned short stretch);
Returns Nothing.
Parameters :
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
Returns Nothing.
Description Displays a partial area of the image, located on an external resource, on a desired location of the screen.
Parameters :
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.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
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.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_Color16bitToRGB
Returns Nothing.
Parameters :
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.
TFT_Rotate_180
Returns Nothing.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
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).
extern sfr sbit TFT_16bit_CS; Chip Select signal. sbit TFT_16bit_CS at LATG3_bit;
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
Returns Nothing.
www.raguvaran.puzl.com
Description Initializes HX8352A display controller in 16-bit working mode.
Parameters :
TFT_Init_SSD1963
Returns Nothing.
www.raguvaran.puzl.com
Description Initializes SSD1963 display controller in 16-bit working mode.
Parameters :
TFT_Init_ILI9340
Returns Nothing.
www.raguvaran.puzl.com
Description Initializes ILI9340 display controller in 16-bit working mode.
Parameters :
TFT_Init_ILI9342
Returns Nothing.
www.raguvaran.puzl.com
Description Initializes ILI9342 display controller in 16-bit working mode.
Parameters :
TFT_Init_ILI9481
Returns Nothing.
www.raguvaran.puzl.com
Description Initializes ILI9481 display controller in 16-bit working mode.
Parameters :
TFT_16bit_Set_Index
Returns Nothing.
Description Accesses register space of the controller and sets the desired register.
www.raguvaran.puzl.com
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_16bit_Write_Command
Returns Nothing.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_16bit_Write_Data
Returns Nothing.
Parameters :
_data:data to be written.
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_16bit_Set_Reg
www.raguvaran.puzl.com
Returns Nothing.
Description Accesses register space of the controller and writes a value in the desired register.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_16bit_Set_Ext_Buffer
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;
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
Returns Nothing.
Description This function sets appropriate pointers to a user-defined basic routines in order to enable multiple working modes.
Parameters :
Requires None.
void main(){
...
TFT_Set_Active(Set_Index,Write_Command,Write_Data);
TFT_Init_HX8352A (320, 240);
...
}
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
Returns Nothing.
Parameters :
Value Description
www.raguvaran.puzl.com
CL_RED_16bit Red color
Value Description
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_16bit_Set_Ext_Font
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
www.raguvaran.puzl.com
CL_GREEN_16bit Green color
Value Description
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_16bit_Write_Char
Returns Nothing.
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
Returns Nothing.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_16bit_Write_Const_Text
Returns Nothing.
Description Writes text located in the program memory on the TFT at coordinates (x, y).
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_16bit_Fill_Screen
Returns Nothing.
www.raguvaran.puzl.com
Parameters :
Value Description
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
Example TFT_16bit_Fill_Screen(CL_BLACK_16bit);
TFT_16bit_Dot
Returns Nothing.
www.raguvaran.puzl.com
Parameters :
Value Description
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_16bit_Set_Pen
Returns Nothing.
www.raguvaran.puzl.com
Description Sets color and thickness parameter for drawing line, circle and rectangle elements.
Parameters :
Value Description
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_16bit_Set_Brush
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 :
Value Description
Value Description
www.raguvaran.puzl.com
CL_YELLOW_16bit Yellow color
Value Description
1 Enable gradient.
0 Disable gradient.
Value Description
Value Description
www.raguvaran.puzl.com
Value Description
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_16bit_Line
Prototype void TFT_16bit_Line(int x1, int y1, int x2, int y2);
Returns Nothing.
www.raguvaran.puzl.com
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_16bit_H_Line
Returns Nothing.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_16bit_V_Line
Returns Nothing.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
www.raguvaran.puzl.com
TFT_16bit_Rectangle
Returns Nothing.
Require TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
s
TFT_16bit_Rectangle_Round_Edges
Returns Nothing.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_16bit_Circle
www.raguvaran.puzl.com
Returns Nothing.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
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.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_16bit_Ext_Image
Returns Nothing.
Parameters :
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.
TFT_16bit_Partial_Image
Returns Nothing.
Parameters :
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
Returns Nothing.
Description Displays a partial area of the image, located on an external resource, on a desired location of the screen.
Parameters :
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);
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
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.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
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.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
TFT_16bit_Rotate_180
Returns Nothing.
Parameters :
Requires TFT module needs to be initialized. Please, see appropriate TFT initialization routine.
www.raguvaran.puzl.com
Library Dependency Tree
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
Description Initialize touch panel display. Default touch panel ADC threshold value is set to 3900.
Returns Nothing.
www.raguvaran.puzl.com
TP_Init(128, 64, 6, 7); // Initialize touch panel, dimensions 128x64
TP_Set_ADC_Threshold
Description Set custom ADC threshold value, call this function after TP_Init.
Returns Nothing.
TP_Press_Detect
Parameters None.
DriveA: DriveA.
DriveB: DriveB.
DriveA_Direction: Direction of DriveA pin.
DriveB_Direction: Direction of DriveB pin.
must be defined before using this function.
if (TP_Press_Detect()) {
...
}
TP_Get_Coordinates
www.raguvaran.puzl.com
Prototype char TP_Get_Coordinates(unsigned int *x_coordinate, unsigned
int *y_coordinate);
Requires Nothing.
TP_Calibrate_Bottom_Left
Parameters None.
Returns Nothing.
Requires Nothing.
TP_Calibrate_Upper_Right
Parameters None.
www.raguvaran.puzl.com
Returns Nothing.
Requires Nothing.
TP_Get_Calibration_Consts
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.
TP_Set_Calibration_Consts
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 :
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;
void Calibrate() {
www.raguvaran.puzl.com
Delay_ms(1000);
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);
// 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) {
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 ((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;
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
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.
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.
UARTx_Data_Ready
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.
UARTx_Tx_Idle
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
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.
UARTx_Read_Text
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 :
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:
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.
Requires UART HW module must be initialized and communication established before using this
function. See UARTx_Init.
UARTx_Write_Text
Returns Nothing.
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:
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
www.raguvaran.puzl.com
Returns Nothing.
Description Sets active UART module which will be used by the UART library routines.
Parameters :
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
UART_Data_Ready
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.
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
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.
UART_Read_Text
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 :
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:
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
Returns Nothing.
Requires UART HW module must be initialized and communication established before using this
function. See UARTx_Init.
UART_Write_Text
www.raguvaran.puzl.com
Returns Nothing.
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:
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_Write_Text("Start");
UART1_Write(10);
UART1_Write(13);
HW Connection
www.raguvaran.puzl.com
RS-232 HW connection
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
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 :
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
www.raguvaran.puzl.com
Description The function tests if data in receive buffer is ready for reading.
UART_Remappable_Tx_Idle
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
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:
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
Returns Nothing.
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:
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
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
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.
Notes None.
HID_Write
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.
www.raguvaran.puzl.com
Notes Function call needs to be repeated as long as data is not successfuly sent.
HID_Disable
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
Description This routine is used for servicing various USB bus events. Should be called inside USB
interrupt routine.
Parameters None.
Returns Nothing.
Requires Nothing.
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
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);
}
}
Gen_Enable
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
Description Generic routine that receives the specified data from the specified endpoint.
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
www.raguvaran.puzl.com
ep: Endpoint number you want to send the data into.
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
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.
Example Example reads RB0, to which the button is connected; on transition from 1 to 0
(release of button), PORTD is inverted:
void main() {
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.
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
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 :
www.raguvaran.puzl.com
ShortToStr
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 :
WordToStr
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 :
IntToStr
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 :
LongToStr
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 :
LongWordToStr
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 :
FloatToStr
Parameters :
Note : Given floating point number will be truncated to 7 most significant digits
before conversion.
www.raguvaran.puzl.com
FloatToStr(ff3, txt); // txt is "1.234e-6"
WordToStrWithZeros
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 :
IntToStrWithZeros
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 :
www.raguvaran.puzl.com
LongWordToStrWithZeros
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 :
LongIntToStrWithZeros
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 :
ByteToHex
www.raguvaran.puzl.com
Prototype void ByteToHex(char input, char *output);
Returns Nothing.
Parameters :
ShortToHex
Returns Nothing.
Parameters :
WordToHex
www.raguvaran.puzl.com
Returns Nothing.
Parameters :
IntToHex
Returns Nothing.
Parameters :
LongWordToHex
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 :
LongIntToHex
Returns Nothing.
Parameters :
Dec2Bcd
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.
Bcd2Dec
Requires Nothing.
Dec2Bcd16
Requires Nothing.
Example unsigned a, b;
...
a = 2345;
b = Dec2Bcd16(a); // b equals 9029
Bcd2Dec16
www.raguvaran.puzl.com
Prototype unsigned Bcd2Dec16(unsigned bcdnum);
Requires Nothing.
Example unsigned a, b;
...
a = 0x1234; // a equals 4660
b = Bcd2Dec16(a); // b equals 1234
Rtrim
Returns The function returns pointer to the array without trailing spaces.
Description Trims the trailing spaces from array given with *string
Parameters :
Requires Nothing.
res = Rtrim("mikroe "); // trims the trailing spaces and returns the address of
the first non-space character
Ltrim
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 :
Requires Nothing.
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.
www.raguvaran.puzl.com
Library Dependency Tree
Library Routines
PrintOut
PrintOut
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 :
www.raguvaran.puzl.com
e double Floating-point number using the format [-]d.dddde[-]dd
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
+ 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.
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.
The precision field is where you specify the maximum number of characters in the output
s value. Excess characters are not output.
Requires Nothing.
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
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
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.
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.
#include <setjmp16.h>
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.
Functions
sprintf
sprintl
sprinti
sprintf
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 :
www.raguvaran.puzl.com
X unsigned int Unsigned hexadecimal number using 0123456789ABCEDF
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
+ 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.
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.
The precision field is where you specify a maximum number of characters in the output
s value. Excess characters are not output.
sprintl
Returns The function returns the number of characters actually written to destination string.
sprinti
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.
www.raguvaran.puzl.com
double ww = -1.2587538e+1;
char buffer[15];
void main(){
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.
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
Description This function returns the UNIX time : number of seconds since January 1, 1970
0h00mn00s.
Parameters :
Requires Nothing.
Time_epochToDate
Returns Nothing.
Parameters :
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
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 :
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.
Library Example
Demonstration of Time library routines usage for time calculations in UNIX time format.
#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
Description The function calculates sine multiplied by 1000 and rounded to the nearest integer:
result = round(sin(angle_deg)*1000)
Parameters :
Requires Nothing.
cosE3
Description The function calculates cosine multiplied by 1000 and rounded to the nearest integer:
result = round(cos(angle_deg)*1000)
Parameters :
Requires Nothing.
www.raguvaran.puzl.com