BLE CRC24计算代码

BLE CRC24 计算详解

1. BLE 信道数据帧

1.1 LE Uncoded PHYs

请添加图片描述
The Preamble is transmitted first, followed by the Access Address, PDU, CRC, and Constant Tone Extension (if present) in that order. The entire packet is transmitted at the same symbol rate (either 1 Msym/s or 2 Msym/s modulation).
Packets (not including the Constant Tone Extension) take between 44 and
2120 µs to transmit.
When the Constant Tone Extension is present, the Constant Tone Extension
duration is between 16 and 160 µs.

请添加图片描述

1.2 LE Coded PHYs

请添加图片描述
请添加图片描述

请添加图片描述

2. CRC

多项式: 0x00065B // x24 + x10 + x9 + x6 + x4 + x3 + x + 1.
初始值:0x555555
REFIN:YES.
REFOUT: NO.

NOTE: CRC 传输与 PDU 相反(CRC is transmitted most significant bit first),解析时要注意。

//File: ble_crc24.cpp

#include "ble_crc24.h"

#define POLY        0x00065B   //POLY: x24 + x10 + x9 + x6 + x4 + x3 + x + 1
#define WIDTH       24
#define TOPBIT      (1 << (WIDTH - 1))
#define INIT_VAL    0x555555

static uint8_t reverse_bits(uint8_t byte) 
{
    uint8_t reversed = 0;
    for (int i = 0; i < 8; i++) 
    {
        reversed = (reversed << 1) | (byte & 1);
        byte >>= 1;
    }

    return reversed;
}

uint32_t calc_ble_crc24(uint8_t* data, uint32_t length) 
{
    uint32_t crc = INIT_VAL;  // The initial value is usually 0.

    for (size_t i = 0; i < length; i++) 
    {
        uint8_t reversed_byte = reverse_bits(data[i]);  // Invert input byte

        crc ^= (reversed_byte << 16);  // Move data into the high level of the CRC register.

        for (uint8_t bit = 0; bit < 8; bit++) 
        {
            if (crc & TOPBIT) 
            {
                crc = (crc << 1) ^ POLY;  // If the highest digit is 1, it is XOR with the POLY.
            }
            else 
            {
                crc <<= 1;  // Otherwise, just move left.
            }
        }
    }

    // Return the CRC value and ensure that only the lower 24 bits are valid.
    return crc & 0xFFFFFF;
}
//File: ble_crc24.h

#ifndef __BLE_CRC24_H__
#define __BLE_CRC24_H__

#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

uint32_t calc_ble_crc24(uint8_t* data, uint32_t length);

#ifdef __cplusplus
}
#endif
#endif
//File: app.cpp

#include <stdio.h>
#include "ble_crc24.h"

int main()
{
    uint8_t data[] = { 0x01, 0x1E, 0x1F, 0x21, 0x24, 0x28, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0x11, 0x22, 0x33, 0x44,
                       0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x11, 0x22, 0x33, 0x44,
    };  // 示例数据 "1234"

    size_t length = sizeof(data) / sizeof(data[0]);

    uint32_t crc = calc_ble_crc24(data, length);
    printf("CRC-24: 0x%08X\n", crc);

    return 0;
}

测试工程代码已上传,跳转下载

已验证通过,可放心食用。哈哈哈。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值