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

本文介绍了作者在化工自动化控制项目中,为测试阀门精度问题,使用C语言编写的一个Modbus协议命令生成程序,包括CRC校验功能,以满足测试需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在和老师做一个化工厂里面的自动控制生产的工程,项目中有一个需要测试控制阀门的精度问题,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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nicehuai

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值