生成系列命令的modbus命令(crc校验)

来源:互联网 发布:ubuntu 根目录不足 编辑:程序博客网 时间:2024/04/29 03:34

最近在和老师做一个化工厂里面的自动控制生产的工程,项目中有一个需要测试控制阀门的精度问题,modbus协议,测试中老师建议让我自己写一个生成测试命令的C程序,于是花了点时间自己吧,编了一个小程序。留着做纪念吧。

#include <stdio.h>unsigned int CRC_16(unsigned int puiCRCWord,unsigned char pucChechingChar) ; //crc16校验程序unsigned int CRC_16_command(unsigned int puiCRCWord) ; //crc16校验程序unsigned int swap(unsigned int puiCRCWord) ;  //高低字节转化unsigned char num[10] = {3,6,0,0} ;int main(){    //printf("%d",sizeof(int)) ;    int i ;    unsigned int n,end,inc = 10000 ;    printf("plese input begin nummber :") ;    scanf("%d",&n) ;    puts("") ;    printf("Plese input increace nummber :") ;    scanf("%d",&inc) ;    puts("") ;    printf("Plese input end nummber :") ;    scanf("%d",&end) ;    puts("") ;    while(n <= end)    {        printf("%d:",n) ;        CRC_16_command(n) ;  //命令: 03 06 00 00 XX XX (CRC) (CRC)        for(i = 0 ;i < 8 ;i++)        {            printf("%02x ",num[i]) ;        }        puts("") ;        n += inc ;    }    return 0 ;}unsigned int CRC_16_command(unsigned int x)  //crc16校验程序{    unsigned int puiCRCWord = 0xffff ;    unsigned char i ;    num[4] = (x >> 8) ;    num[5] = (x & 0xff) ;    for(i = 0 ;i < 6 ;i++)    {        puiCRCWord = CRC_16(puiCRCWord,num[i]) ;    }    puiCRCWord = swap(puiCRCWord) ;    num[6] = (puiCRCWord >> 8) ;    num[7] = (puiCRCWord & 0xff) ;    return puiCRCWord ;}unsigned int swap(unsigned int puiCRCWord){    unsigned int a ;    a = puiCRCWord & 0xff ;    puiCRCWord = puiCRCWord >>8 ;    puiCRCWord |= (a << 8) ;    return puiCRCWord ;}/************************************************************crc16校验程序:unsigned int CRC_16(unsigned int puiCRCWord,unsigned char pucChechingChar)功能:接收字节crc校验,返回校验值形参:pucChechingChar     需要校验数据       puiCRCWord          校验后的数据*************************************************************/unsigned int CRC_16(unsigned int puiCRCWord,unsigned char pucChechingChar){    unsigned char dataluc;    unsigned char luc ;    puiCRCWord ^= pucChechingChar;    for( luc = 8; luc > 0; luc--)    {        if( puiCRCWord & 0x0001)        {            puiCRCWord >>= 1 ;            puiCRCWord ^= 0xA001 ;        }        else        {            puiCRCWord >>= 1;        }    }    return puiCRCWord;}
0 0