Cobra_Phil
06-25-2010, 11:33 AM
I thought I would share with everyone a routine to calculate the ModBus CRC value. Snippets of code were pulled from this forum among other places. I don't really understand why this is needed, but it works in all the scenarios I have tested.
if crc < 0:
crc -= 256
I am brand new to programming in python. So, be kind. I'm open to suggestions if something can be done better or faster.
def CRC16(Output):
crc = 0xFFFF
l = len(Output)
i = 0
while i < l:
j = 0
crc = crc ^ ord(Output[i])
while j < 8:
if (crc & 0x1):
mask = 0xA001
else:
mask = 0x00
crc = ((crc >> 1) & 0x7FFF) ^ mask
j += 1
i += 1
if crc < 0:
crc -= 256
print Output + chr(crc % 256) + chr(crc / 256)
if crc < 0:
crc -= 256
I am brand new to programming in python. So, be kind. I'm open to suggestions if something can be done better or faster.
def CRC16(Output):
crc = 0xFFFF
l = len(Output)
i = 0
while i < l:
j = 0
crc = crc ^ ord(Output[i])
while j < 8:
if (crc & 0x1):
mask = 0xA001
else:
mask = 0x00
crc = ((crc >> 1) & 0x7FFF) ^ mask
j += 1
i += 1
if crc < 0:
crc -= 256
print Output + chr(crc % 256) + chr(crc / 256)