forked from microa/CRC
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModbus CRC.py
More file actions
44 lines (35 loc) · 1011 Bytes
/
Modbus CRC.py
File metadata and controls
44 lines (35 loc) · 1011 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def crc16(data: str, poly: hex = 0xA001) -> str:
'''
CRC-16 MODBUS HASHING ALGORITHM
'''
crc = 0xFFFF
for byte in data:
crc ^= byte
for _ in range(8):
crc = ((crc >> 1) ^ poly
if (crc & 0x0001)
else crc >> 1)
hv = hex(crc).upper()[2:]
blueprint = '0000'
return (blueprint if len(hv) == 0 else blueprint[:-len(hv)] + hv)
def makeBytes(DID,FID,RIDH,RIDL,RVH,RVL):
a = DID
b = FID
c = RIDH
d = RIDL
e = RVH
f = RVL
return bytes([a,b,c,d,e,f])
def CRC(DeviceID,FunctionID,RegIDH,RegIDL,RegValH,RegValL):
CMDBytes = makeBytes(DeviceID,FunctionID,RegIDH,RegIDL,RegValH,RegValL)
CRCResult = crc16(CMDBytes)
print("CRC:",CRCResult)
ts = int(CRCResult,16)
L = ts & 0x00FF # Low 8bit
H = (ts & 0xFF00) >>8
print (L)
print (H)
STR = bytearray(CMDBytes)
STR.append(L)
STR.append(H)
return STR