I am trying to impilment modbus RTU with read coil register.
I have working code till receive data upto crc check & receive response from slave. My main problem is once data being received how can read coil register & pack data & send back for CRC check
I havent used the serial of arduino i have written in embedded c on atmega controller.
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 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)
{
length=(rxbuf[5]*2);
address=(address*2);
ser_data[0]=METER_ID;
ser_data[1]=rxbuf[1];
ser_data[2]=length;
ser_data[3]=00;// Put higher byte address Here
ser_data[4]=01;// Put Lower byte address Here
ser_data[5]=00;
ser_data[6]=04;
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));
/* line add for slow down*/
for(i=0;i<30;i++)
{
Serial_1_Send_byte(0);
}
}
}
__delay_ms(5);
}
}
index=0;
rec_flag = 0;
}
Its working code for function 3 , Now i would like modify for function 1 .as attached in link
request goes in 01 01 00 00 00 31 fd de
rxbuf[0]= 01 //device Id always
rxbuf[1]= 01 //Functional code
rxbuf[2]= 00 //higher byte of start address
rxbuf[3]= 00 //Lower byte of start address
rxbuf[4]= 00 //HI Number of Bits
rxbuf[5]= 31 //LO Number of Bits
rxbuf[6]= FD //CRC1
rxbuf[7]= DE //CRC2
Upto here coming properly.
I need to modify my address & length accordingly so accordingly i need to store digital status coil based on length & pack it send with crc check response. but i dont know can i store bits of my digital io pins.