我想通过RS232将一些字节发送到一个控制机器人马达的DSPIC33F,DSPIC必须有序地接收9个字节,最后2个字节是CRC16的,我在C#中工作,所以我如何计算要发送的CRC字节。
计算CRC16的程序,我在互联网上找到了:
using System;
using System.Collections.Generic;
using System.Text;
namespace SerialPortTerminal
{
public enum InitialCrcValue { Zeros, NonZero1 = 0xffff, NonZero2 = 0x1D0F }
public class Crc16Ccitt
{
const ushort poly = 4129;
ushort[] table = new ushort[256];
ushort initialValue = 0;
public ushort ComputeChecksum(byte[] bytes)
{
ushort crc = this.initialValue;
for (int i = 0; i < bytes.Length; i++)
{
crc = (ushort)((crc << 8) ^ table[((crc >> 8) ^ (0xff & bytes[i]))]);
}
return crc;
}
public byte[] ComputeChecksumBytes(byte[] bytes)
{
ushort crc = ComputeChecksum(bytes);
return new byte[] { (byte)(crc >> 8), (byte)(crc & 0x00ff) };
}
public Crc16Ccitt(InitialCrcValue initialValue)
{
this.initialValue = (ushort)initialValue;
ushort temp, a;
for (int i = 0; i < table.Length; i++)
{
temp = 0;
a = (ushort)(i << 8);
for (int j = 0; j < 8; j++)
{
if (((temp ^ a) & 0x8000) != 0)
{
temp = (ushort)((temp << 1) ^ poly);
}
else
{
temp <<= 1;
}
a <<= 1;
}
table[i] = temp;
}
}
}
}发布于 2014-03-04 00:20:32
使用您提供的类,您将创建所需数据的缓冲区:
byte[] data = new byte[7];
data[0] = 1; // This example is just random numbers
data[1] = 12;
data[2] = 17;
data[3] = 9;
data[4] = 106;
data[5] = 12;
data[6] = 0;然后计算校验和字节:
Crc16Ccitt calculator = new Crc16Ccitt();
byte[] checksum = calculator.ComputeChecksumBytes(data);然后要么编写数据的两个部分
port.Write(data);
port.Write(checksum);或者构建要从这两个部分编写的数据包:
byte[] finalData = new byte[9];
Buffer.BlockCopy(data, 0, finalData, 0, 7);
Buffer.BlockCopy(data, 7, checksum, 0, 2);
port.Write(finalData);您发布的类可以稍加重写,以使其更高效、更容易/更干净地使用,但只要它以与您通信的设备相同的方式计算CRC 16,就足够了。如果这不起作用,那么您需要查阅设备的文档,或者向制造商询问所需的详细信息。
https://stackoverflow.com/questions/22156681
复制相似问题