int cm = 50;
int cnt;
int error = 0;
char dat[10]; // buffer for receving/sending messages
char i,j;
sbit rs485_rxtx_pin at LATC2_bit; // set transcieve pin
sbit rs485_rxtx_pin_direction at TRISC2_bit; // set transcieve pin direction
// Interrupt routine
void interrupt() {
RS485Slave_Receive(dat);
TRISA = 0b1111110; //1 eteint, 0 allumé ici RA0 allumé : rouge
RA0_bit=1;
RA1_bit=0;
}
void main() {
UART2_Init(9615);
Delay_ms(100);
//UART_Set_Active(&UART2_Read, &UART2_Write, &UART2_Data_Ready, &UART2_Tx_Idle);
ANSELA = 0;
ANSELB = 0; // Configure AN pins as digital I/O
ANSELC = 0;
ANSELD = 0;
LATB = 0;
LATD = 0;
TRISB = 0;
TRISD = 0;
TRISC = 0;
UART1_Init(9615); // initialize UART1 module
Delay_ms(100);
//UART_Set_Active(&UART1_Read, &UART1_Write, &UART1_Data_Ready, &UART1_Tx_Idle);
RS485Slave_Init(160);
dat[4] = 0; // ensure that message received flag is 0
dat[5] = 0; // ensure that message received flag is 0
dat[6] = 0; // ensure that error flag is 0
RCIE_bit = 1; // enable interrupt on UART1 receive
TXIE_bit = 0; // disable interrupt on UART1 transmit
PEIE_bit = 1; // enable peripheral interrupts
GIE_bit = 1;
while(1)
{
do{
//UART_Set_Active(&UART2_Read, &UART2_Write, &UART2_Data_Ready, &UART2_Tx_Idle);
Uart2_Write(0x00); // SFR02 Address (0x00 by default)
Uart2_Write(0x54); // Real Ranging Mode - Result in centimeters, automatically Tx range back to controller as soon as ranging is complete.
//delay_ms(80); // Wait >70 msec to get back the ranging
//Uart2_Write(0x5E);
//I NEED THIS TO READ RANGING DISTANCE FROM ULTRASOUND DETECTOR
/*
if(UART2_Data_Ready())
{
cm=Uart2_read();
}
*/
}while(cm==0);
delay_ms(500);
if (cm<50)
{
TRISA = 0b1111110; //1 eteint, 0 allumé ici RA0 allumé : rouge
RA0_bit=1;
RA1_bit=0;
dat[0] = 162;
}
if(cm>50)
{
TRISA = 0b1111101; // RA1 Allumé : vert
RA1_bit=1;
RA0_bit=0;
dat[0] = 161;
}
if (dat[5])
{ // if an error detected, signal it by
dat[5] = 0;
}
if (dat[4])
{
dat[4] = 0; // data[4] is set to 0xFF
j = dat[3];
Delay_ms(1);
//UART_Set_Active(&UART1_Read, &UART1_Write, &UART1_Data_Ready, &UART1_Tx_Idle);
RS485Slave_Send(dat,1); // and send it back to master
}
}
}