ajit_nayak87
Member level 5
Here I am trying to Interface PIC18F24k40 over modbus RTU. I am posting part of my code . The below code work with function 03 holding register . Now i i am trying same code to modified for function code 1 i. read coil register. I am getting improper modbus response error. can someone sugggest what change to be done make it work.
Below code will work on function 3
[/CODE]
Below code will work on function 3
Code:
[CODE]
unsigned int crc_fn(unsigned char *dpacket,unsigned int len) // CRC Function(Error calcualtion)
{
unsigned int crc = 0xffff,poly = 0xa001;
unsigned int i=0;
for(i=0;i<len;i++)
{
crc^= dpacket[i];
for(j=0;j<8;j++)
{
if(crc & 0x01)
{
crc >>= 1;
crc ^= poly;
}
else
crc >>= 1;
}
}
return (crc);
}
void ChecksumCal(char No_Bytes)
{
unsigned char highbyte,lowbyte;
unsigned short crc,thisbyte,i,shift,lastbit; /* 16 bit word values */
/* compute the CRC over the first 6 chars of the message*/
crc = 0xFFFF;
No_Bytes = No_Bytes -1;
for(i=0;i<=No_Bytes;i++)
{
thisbyte = rxbuf[i];
crc = crc^thisbyte;
for(shift=1;shift<=8;shift++)
{
lastbit = crc&0x0001;
crc = (crc>>1)&0x7fff;
if(lastbit==0x0001)
{
crc=crc^0xa001;
}
}
}
lowbyte = (crc>>8)&0xff;
highbyte = crc & 0xff;
crc_msb = highbyte;
crc_lsb = lowbyte;
}
void Serial_Request()
{
unsigned int address,crc1,crc2;
unsigned char length,i,j=0;
// Serial_1_Send_byte(rxbuf[0]);
crc2=crc_fn(&rxbuf[0],6); //crc function for received protocol from request
__delay_ms(10); // Changed on 20.01.2017
if((rxbuf[6]==(unsigned char)(crc2))&&(rxbuf[7]==((unsigned char)(crc2>>8))))
{
if(rxbuf[0]==device_ID)
{
//Serial_1_Send_byte(rxbuf[0]);
if(rxbuf[1]==READ_REG)
{
address=(((unsigned int)(rxbuf[2]<<8))+((unsigned int)(rxbuf[3])));
if(rxbuf[5]>=1)
{
// changes i made for function1, if i used i get an error.
length=(rxbuf[5]/8);// function code 1
address=0X01;// function code 1
[B] // original function 3 code, if i keep below code it works fine for function 3
// length=(rxbuf[5]*2);// function 3
// address=(address*2);// function 3
[/B]
ser_data[0]=device_ID;
ser_data[1]=rxbuf[1];
ser_data[2]=length;
crc_data[0]=device_ID;
crc_data[1]=rxbuf[1];
crc_data[2]=length;
j=3;
for(i=address;i<((address+length));i++)
{
crc_data[j++]=ser_data[i+3];
}
crc1 =crc_fn(&crc_data[0],(length+3)); //crc function for response protocol from the device
Serial_1_Send_byte(ser_data[0]);
Serial_1_Send_byte(rxbuf[1]);
Serial_1_Send_byte(ser_data[2]);
for(i=address;i<((address+length));i++)
{
Serial_1_Send_byte(ser_data[i+3]);
}
Serial_1_Send_byte((unsigned char)crc1);
Serial_1_Send_byte((unsigned char)(crc1>>8));
}
}
__delay_ms(5);
}
}
index=0;
rec_flag = 0;
}