mikroC

making it simple...

Library Example

mikroC - C Compiler for Microchip PIC microcontrollers

The example demonstrates working with PIC as Slave nod in RS-485 communication. PIC receives only packets addressed to it (address 160 in our example), and general messsages with target address 50. The received data is forwarded to PORTB, and sent back to Master.

unsigned short dat[8]; // buffer for receiving/sending messages char i = 0, j = 0;

void interrupt() {

/* Every byte is received by RS485Slave_Read(dat); If message is received without errors, data[4] is set to 255 */

if (RCSTA.OERR) PORTD = 0x81; RS485Slave_Read(dat);

}//~

 

 

 

 

void main() {

 

 

 

TRISB = 0;

 

 

 

TRISD = 0;

 

 

 

Usart_Init(9600);

// Initialize usart module

RS485Slave_Init(160);

// Initialize MCU as Slave with address 160

PIE1.RCIE

= 1;

// Enable interrupt

INTCON.PEIE = 1;

//

on byte received

PIE2.TXIE

= 0;

//

via USART (RS485)

INTCON.GIE

= 1;

 

 

PORTB

= 0;

 

 

 

PORTD

= 0;

 

 

 

dat[4] = 0;

 

// Ensure that msg received flag is 0

dat[5] = 0;

 

// Ensure that error flag is 0

do {

 

 

 

 

if (dat[5]) PORTD = 0xAA;

// If there is error, set PORTD to $AA

if (dat[4]) {

// If

message received:

dat[4]

= 0;

//

Clear message received flag

j

= dat[3];

//

Number of data bytes received

for (i = 1; i < j; i++)

 

 

 

PORTB = dat[--i];

//

Output received data bytes

dat[0]++;

//

Increment received dat[0]

RS485Slave_Write(dat, 1);

//

Send it back to Master

}

 

 

 

 

}while (1); }//~!

 

 

page

 

MikroElektronika: Development tools - Books - Compilers

247