如何在python中为串行设备生成CRC?

2024-04-20 10:47:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须用python构建一个串行通信应用程序,旧的应用程序只在windowsxp上运行,而且是用C编写的。现在我不得不切换到linux,我没有一个可以工作的驱动程序。我开始自己编写代码。我从串行设备的生产公司得到了协议。 串行设备接收和发送由CRC结束的数据。我是python新手,我没有解决这个问题的方法,也许有人可以帮我。在

这是CRC alghoritm:

  ALGORITHM FOR CRC CALCULATION

The two CRC bytes are calculated according to the formula x^15 + 1. In the calculation are included all data bytes plus the byte for block end. Every byte passes through the calculation register from teh MSB to LSB.
Three working bytes are used - S1, S0 and TR
S1 - Most significant byte from the CRC ( it is transmitted immediatelly after END)
S0 - Least significant byte from the CRC ( It is transmitted after S1)
TR - the current transmitted byte in the block.

The CRC is calculated as follows:
1. S1 and S0 are zeroed
2. TR is loaded with the current transmitted byte. The byte is transmitted.
3. Points 3.1 and 3.2 are executed 8 times:
3.1. S1, S0 and TR are shifted one bit to the left.
3.2. If the carry bit from S1 is 1, the MSB of S1 and LSB of S0 are inverted.
Points 2 and 3 are executed for all bytes, included in the calculation of the CRC - from the first byte after BEG up to and including byte END.
4. TR is loaded with 0 and point 3 is executed
5. TR is loaded with 0 and point 3 is executed
6. Byte S1 is transmitted
7. Byte S0 is transmitted

ALGORITHM FOR CRC CHECK ON RECEIVING

Three working bytes are used S1, S0 and RC

S1 - Most significant byte from the CRC ( it is received immediately after END)
S0 - Least significant byte from the CRC ( transmitted after S1)
RC - the current received byte in the block ( beginning from the first byte after BEG and ending 2 bytes after END).

The CRC is obtained as follows:
1. S1 and S0 are zeroed
2. RC is loaded with the current received byte
3. Points 3.1 and 3.2 are executed 8 times:
3.1. S1, S0 and RC are shifted 8 times to the left
3.2. if the MSB of S1 is 1 then MSB of S1 and LSB of S0 are inverted. 
Points 2 and 3 are executed for all bytes, included in the calculation of the CRC - from the first byte after BEG up to and including 2 bytes after END.
S1 and S0 must be 0.

如果有人能教我怎么做,我会很高兴的非常感谢。谢谢你们所有人。在

编辑1:

我设法得到了同样的CRC程序,但它是用java编写的,我对java不太在行。也许你可以指导我用python转换它。代码如下:

^{pr2}$

Tags: andofthetofrombytesisbyte
1条回答
网友
1楼 · 发布于 2024-04-20 10:47:36
#!/usr/bin/python
import sys
crc = 0
while True:
    ch = sys.stdin.read(1)
    if not ch:
        break
    crc ^= ord(ch) << 8
    for _ in range(8):
        crc = crc << 1 if (crc & 0x8000) == 0 else (crc << 1) ^ 0x8001
    crc &= 0xffff
print(format(crc, '04x'))

相关问题 更多 >