CRC8


Recommended Posts

Hi,

Further to a long string to LCD, we add a CRC byte to the end as checksum. We copy and modify a C code from one of our working PIC project like this:

A sequence named as Func_CRC2 containing one function crc2( )

function crc2(private crc, private crc_data)

 private  i
   i = (crc_data ^ crc) & 0xff
   crc = 0
   if(i & 1)
	  crc ^= 0x5e
   endif
   if(i & 2)
	  crc ^= 0xbc
   endif   
   if(i & 4)
	  crc ^= 0x61
   endif   
   if(i & 8)
	  crc ^= 0xc2
   endif   
   if(i & 0x10)
	  crc ^= 0x9d
   endif   
   if(i & 0x20)
	  crc ^= 0x23
   endif   
   if(i & 0x40)
	  crc ^= 0x46
   endif   
   if(i & 0x80)
	  crc ^= 0x8c
   endif   
return(crc)

A Sequence named CRC8m:

crc8=0
   for (private i=0, i< getlength(vehicle), i++)
	 crc8 = crc2(crc8, vehicle[i])
   endfor

A Sequence named Write_Comm:

while(1)
   compose_vehicle()
   crc8m()
   vehicle = vehicle + crc8
   device.MO.write(vehicle)   //MO the serial device
   dv = vehicle

   delay(5)
endwhile

where crc8, vehicle and dv already declared global in a declaration sequence. dv is used with a variable text to observe the result.

After running, the crc8 is always returned as '0', anything going wrong in the above code?

Thank you,

ccf

Link to comment
Share on other sites

You can't index into a string like that:

NO:

private string x

x = "abcde"

if (x[1] == "a")

...

endif

x[1] is not the second character in x, but rather the second element in the array x, which of course only has one element at present so nothing is returned (NULL is returned). You'd have to use the mid() function to pull out a particular character. But truthfully, you don't want that either because your crc16 function is taking a number, not a character. DAQFactory isn't C (fortunately for you!). It treats strings as strings and numbers as numbers.

What I would do is use the asca() function to convert vehicle into an array of ASCII codes (numbers). Then the rest of your code remains largely the same:

crc8=0
private data = asca(vehicle)
for (private i=0, i< numrows(data), i++)
  crc8 = crc2(crc8, data[i])
endfor

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.