BluetoothDemo蓝牙,根据蓝牙设备名进行连接

在.m文件中

#import "ViewController.h"
#import "NSString+SL_Extension.h"
#import <CoreBluetooth/CoreBluetooth.h>
@interface ViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate>
@property (nonatomic, strong) CBCentralManager *cMgr; /**< 中心管理设备 */
/** 连接到的外设 */
@property (nonatomic, strong) CBPeripheral *peripheral;
@property (strong ,nonatomic) CBCharacteristic        *writeCharacteristic;

@property (nonatomic,strong)CBCharacteristic * characteristic;
@end

@implementation ViewController
// 1.建立中心管理者
- (CBCentralManager *)cMgr
{
    if (!_cMgr) {
        NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
        /*
         设置主设备的代理,CBCentralManagerDelegate
         必须实现的:
         - (void)centralManagerDidUpdateState:(CBCentralManager *)central;//主设备状态改变调用,在初始化CBCentralManager的适合会打开设备,只有当设备正确打开后才能使用
         其他选择实现的委托中比较重要的:
         - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI; //找到外设
         - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//连接外设成功
         - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外设连接失败
         - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//断开外设
         */
        _cMgr = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()]; // 线程不传默认是主线程
    }
    return _cMgr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"大家好 我是山寨手环";
    self.view.backgroundColor = [UIColor orangeColor];

    // 初始化
    [self cMgr];
    // 不能在此处扫描,因为状态还没变为打开
    //[self.cMgr scanForPeripheralsWithServices:nil options:nil];
}

#pragma mark - CBCentralManagerDelegate
// 中心管理者状态改变, 在初始化CBCentralManager的时候会打开设备,只有当设备正确打开后才能使用
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
    switch (central.state) {
        case CBCentralManagerStateUnknown:
            NSLog(@">>>CBCentralManagerStateUnknown");
            break;
        case CBCentralManagerStateResetting:
            NSLog(@">>>CBCentralManagerStateResetting");
            break;
        case CBCentralManagerStateUnsupported:
            NSLog(@">>>CBCentralManagerStateUnsupported");
            break;
        case CBCentralManagerStateUnauthorized:
            NSLog(@">>>CBCentralManagerStateUnauthorized");
            break;
        case CBCentralManagerStatePoweredOff:
            NSLog(@">>>CBCentralManagerStatePoweredOff");
            break;
        case CBCentralManagerStatePoweredOn:
            NSLog(@">>>CBCentralManagerStatePoweredOn");
            // 2.开始扫描周围的外设
            /*
             第一个参数nil就是扫描周围所有的外设,扫描到外设后会进入
             - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;
             */
            [self.cMgr scanForPeripheralsWithServices:nil options:nil];

            break;
        default:
            break;
    }
}
// 扫描到设备会进入到此代理方法
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
{
    NSLog(@"%s, line = %d, per = %@, data = %@, rssi = %@", __FUNCTION__, __LINE__, peripheral, advertisementData, RSSI);
    // 接下来连接设备
    // 判断设备号是否扫描到
    if ([peripheral.name isEqualToString:@"iCre Band"]) {
        /*
         一个主设备最多能连7个外设,每个外设最多只能给一个主设备连接,连接成功,失败,断开会进入各自的委托
         - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//连接外设成功的委托
         - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外设连接失败的委托
         - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//断开外设的委托
         */
        // 保存外设,否则方法结束就销毁
        self.peripheral = peripheral;
        // 发现完之后就是进行连接
        [self.cMgr connectPeripheral:self.peripheral options:nil];
        NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
    }else
    {
        // 此处Alert提示未扫描到设备,重新扫描
#warning noCode
        NSLog(@"没扫描到 >>>>>>>>  %s, line = %d", __FUNCTION__, __LINE__);
    }
}

// 外设连接成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
    NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);
    //设置的peripheral代理CBPeripheralDelegate
    //@interface ViewController : UIViewController<CBCentralManagerDelegate,CBPeripheralDelegate>
    [peripheral setDelegate:self];

    //扫描外设Services,成功后会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    [peripheral discoverServices:nil];
    // 停止扫描
    [self.cMgr stopScan];
}
// 外设连接失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
}
// 断开连接(丢失连接)
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
}

#pragma mark - CBPeripheralDelegate
// 发现外设的service
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    if (error)
    {
        NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
        return;
    }
    for (CBService *service in peripheral.services) {
        NSLog(@"service.UUID = %@", service.UUID);
        //扫描每个service的Characteristics,扫描到后会进入方法: -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
        [peripheral discoverCharacteristics:nil forService:service];
    }
}


// 外设发现service的特征
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    if (error)
    {
        NSLog(@"error Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
        return;
    }
#warning noCodeFor 优化,分开写是为了让大家看注释清晰,并不符合编码规范
    //获取Characteristic的值,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
//    for (CBCharacteristic *characteristic in service.characteristics){
//        [peripheral readValueForCharacteristic:characteristic]; // 外设读取特征的值
//    }
//    //搜索Characteristic的Descriptors,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
//    for (CBCharacteristic *characteristic in service.characteristics){
//        [peripheral discoverDescriptorsForCharacteristic:characteristic]; // 外设发现特征的描述
//    }
    for (CBCharacteristic * characteristic in service.characteristics) {
        //        NSLog(@"查找到的服务(属性)%@",characteristic);
        //所对应的属性用于接收和发送数据
        NSLog(@"service:%@ 的 Characteristic: %@",service.UUID,characteristic.UUID);

        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"6E400003-B5A3-F393-E0A9-E50E24DCCA9E"]]) {
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];//监听这个服务发来的数据
            [peripheral readValueForCharacteristic:characteristic];//主动去读取这个服务发来的数据
        }

        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"6E400002-B5A3-F393-E0A9-E50E24DCCA9E"]]) {
            _writeCharacteristic = characteristic;
        }
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"6E400001-B5A3-F393-E0A9-E50E24DCCA9E"]]) {
//            [peripheral setNotifyValue:YES forCharacteristic:characteristic];//监听这个服务发来的数据
//            [peripheral readValueForCharacteristic:characteristic];//主动去读取这个服务发来的数据
        }


    }
}

// 获取characteristic的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
{

    NSData * data = characteristic.value;
    Byte * resultByte = (Byte *)[data bytes];

    for(int i=0;i<[data length];i++){
        printf("testByteFF02[%d] = %d\n",i,resultByte[i]);
}
    //打印出characteristic的UUID和值
    //!注意,value的类型是NSData,具体开发时,会根据外设协议制定的方式去解析数据
    if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"6E400003-B5A3-F393-E0A9-E50E24DCCA9E"]]) {
        Byte *databyte = (Byte *)[characteristic.value bytes];
        for (int i = 0; i<[characteristic.value length]; i++) {
            NSLog(@"收到3蓝牙发来的数据  %d",databyte[i]);
        }
//        NSString * string = [NSString hexadecimalString:characteristic.value];
        NSLog(@"----------%@",characteristic.value);
        //在这里解析收到的数据,一般是data类型的数据,这里要根据蓝牙厂商提供的协议进行解析并且配合LightBlue来查看数据结构,我当时收到的数据是十六进制的数据但是是data类型,所以我先讲data解析出来之后转为十进制来使用。具体方法后面我会贴出
        //还有一点收到数据后有的硬件是需要应答的,如果应答的话就是在这里再给蓝牙发一个指令(写数据):“我收到发的东西了,你那边要做什么操作可以做了”。
    }
    if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"6E400001-B5A3-F393-E0A9-E50E24DCCA9E"]]) {
        Byte *databyte = (Byte *)[characteristic.value bytes];
        for (int i = 0; i<[characteristic.value length]; i++) {
            NSLog(@"收到1蓝牙发来的数据  %d",databyte[i]);
        }
        NSString * string = [NSString hexadecimalString:characteristic.value];
        NSLog(@"----------%@",[NSString stringFromHexString:string]);
        //在这里解析收到的数据,一般是data类型的数据,这里要根据蓝牙厂商提供的协议进行解析并且配合LightBlue来查看数据结构,我当时收到的数据是十六进制的数据但是是data类型,所以我先讲data解析出来之后转为十进制来使用。具体方法后面我会贴出
        //还有一点收到数据后有的硬件是需要应答的,如果应答的话就是在这里再给蓝牙发一个指令(写数据):“我收到发的东西了,你那边要做什么操作可以做了”。
    }

    if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"6E400002-B5A3-F393-E0A9-E50E24DCCA9E"]]) {
        Byte *databyte = (Byte *)[characteristic.value bytes];
        for (int i = 0; i<[characteristic.value length]; i++) {
            NSLog(@"收到2蓝牙发来的数据  %d",databyte[i]);

        }

        //在这里解析收到的数据,一般是data类型的数据,这里要根据蓝牙厂商提供的协议进行解析并且配合LightBlue来查看数据结构,我当时收到的数据是十六进制的数据但是是data类型,所以我先讲data解析出来之后转为十进制来使用。具体方法后面我会贴出
        //还有一点收到数据后有的硬件是需要应答的,如果应答的话就是在这里再给蓝牙发一个指令(写数据):“我收到发的东西了,你那边要做什么操作可以做了”。
    }
    NSString *dataStr = [[NSString alloc]initWithData:characteristic.value encoding:NSUTF8StringEncoding];
    NSLog(@"%s, line = %d, characteristic.UUID:%@  value:%@", __FUNCTION__, __LINE__, characteristic.UUID, dataStr);
}
// 获取Characteristics的 descriptor的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(nonnull CBDescriptor *)descriptor error:(nullable NSError *)error
{
    //打印出DescriptorsUUID 和value
    //这个descriptor都是对于characteristic的描述,一般都是字符串,所以这里我们转换成字符串去解析
    NSString *dataStr = [[NSString alloc]initWithData:descriptor.value encoding:NSUTF8StringEncoding];
    NSLog(@"%s, line = %d, characteristic.UUID:%@  value:%@", __FUNCTION__, __LINE__, descriptor.UUID, dataStr);
}

// 发现特征Characteristics的描述Descriptor
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
    for (CBDescriptor *descriptor in characteristic.descriptors) {
        NSLog(@"descriptor.UUID:%@",descriptor.UUID);
    }
}

// 5.外设写数据到特征中

// 需要注意的是特征的属性是否支持写数据
- (void)sl_peripheral:(CBPeripheral *)peripheral didWriteData:(NSData *)data forCharacteristic:(nonnull CBCharacteristic *)characteristic
{
    /*
     typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {
     CBCharacteristicPropertyBroadcast                                              = 0x01,
     CBCharacteristicPropertyRead                                                   = 0x02,
     CBCharacteristicPropertyWriteWithoutResponse                                   = 0x04,
     CBCharacteristicPropertyWrite                                                  = 0x08,
     CBCharacteristicPropertyNotify                                                 = 0x10,
     CBCharacteristicPropertyIndicate                                               = 0x20,
     CBCharacteristicPropertyAuthenticatedSignedWrites                              = 0x40,
     CBCharacteristicPropertyExtendedProperties                                     = 0x80,
     CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0)        = 0x100,
     CBCharacteristicPropertyIndicateEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0)  = 0x200
     };
     打印出特征的权限(characteristic.properties),可以看到有很多种,这是一个NS_OPTIONS的枚举,可以是多个值
     常见的又read,write,noitfy,indicate.知道这几个基本够用了,前俩是读写权限,后俩都是通知,俩不同的通知方式
     */
    NSLog(@"%s, line = %d, char.pro = %d", __FUNCTION__, __LINE__, characteristic.properties);
    // 此时由于枚举属性是NS_OPTIONS,所以一个枚举可能对应多个类型,所以判断不能用 = ,而应该用包含&
    if (characteristic.properties & CBCharacteristicPropertyWrite) {
        // 核心代码在这里
        [peripheral writeValue:data // 写入的数据
             forCharacteristic:characteristic // 写给哪个特征
                          type:CBCharacteristicWriteWithResponse];// 通过此响应记录是否成功写入
    }
}
// 6.通知的订阅和取消订阅
// 实际核心代码是一个方法
// 一般这两个方法要根据产品需求来确定写在何处
- (void)sl_peripheral:(CBPeripheral *)peripheral regNotifyWithCharacteristic:(nonnull CBCharacteristic *)characteristic
{
    // 外设为特征订阅通知 数据会进入 peripheral:didUpdateValueForCharacteristic:error:方法
    [peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
- (void)sl_peripheral:(CBPeripheral *)peripheral CancleRegNotifyWithCharacteristic:(nonnull CBCharacteristic *)characteristic
{
    // 外设取消订阅通知 数据会进入 peripheral:didUpdateValueForCharacteristic:error:方法
    [peripheral setNotifyValue:NO forCharacteristic:characteristic];
}
// 7.断开连接
- (void)sl_dismissConentedWithPeripheral:(CBPeripheral *)peripheral
{
    // 停止扫描
    [self.cMgr stopScan];
    // 断开连接
    [self.cMgr cancelPeripheralConnection:peripheral];
}

- (IBAction)sendMessageToBan:(id)sender {
    //crc //
    unsigned char data0 [5]= {0};
    data0[0] = 0x6;
    *(data0+1) = 0x0;
    *(data0+2) = 0x10;
    *(data0+3) = 0x0;
    *(data0+4) = 0x0;

    uint16_t bb = bd_crc16(0,data0,sizeof(data0));
    NSLog(@"收到1蓝牙发来的数据%d",bb);
    unsigned char data [13]= {0};
    data[0] = 0xab;
    *(data+1) = 0x0;
    *(data+2) = 0x0;
    *(data+3) = 0x5;
    *(data+4) = 0xc5;
    *(data+5) = 0x89;
    *(data+6) = 0x0;
    *(data+7) = 0x1e;
    *(data+8) = 0x6;
    *(data+9) = 0x0;
    *(data+10) = 0x10;
    *(data+11) = 0x0;
    *(data+12) = 0x0;
//    *(data+5) = 0x0;

    NSData *data1 = [NSData dataWithBytes:data length:sizeof(data)];
    if (_peripheral.state == CBPeripheralStateConnected) {
        [_peripheral writeValue:data1 forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithResponse];
    }
}
//用于检测中心向外设写数据是否成功
-(void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    if (error) {
        NSLog(@"发送数据失败=======%@",error.userInfo);
    }else{
        //马达接口
        //ab  0  0  5  5 d8  0 50  6  0 11  0  0
        unsigned char data [13]= {0};
        //Magic byte,有 效值为 0XAB
        data[0] = 0xab;
        //Reserve 2 bits ERR flag Ack flag Version
        *(data+1) = 0x0;
        //Payload length
        *(data+2) = 0x0;
        //
        *(data+3) = 0x5;
        //CRC16
        *(data+4) = 0x1;
        //
        *(data+5) = 0x68;
        //Sequence id
        *(data+6) = 0x0;
        *(data+7) = 0x3c;
        //
        *(data+8) = 0x6;
        //
        *(data+9) = 0x0;
        //
        *(data+10) = 0x6;
        //
        *(data+11) = 0x0;
        //
        *(data+12) = 0x0;
        //    *(data+5) = 0x0;
        NSData *data1 = [NSData dataWithBytes:data length:sizeof(data)];
        if (_peripheral.state == CBPeripheralStateConnected) {

            [_peripheral writeValue:data1 forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithResponse];
        }
        NSLog(@"发送数据成功");
    }
    [peripheral readValueForCharacteristic:characteristic];
}

-(NSData *)hexString:(NSString *)hexString {
    int j=0;
    Byte bytes[20];
    ///3ds key的Byte 数组, 128位
    for(int i=0; i<[hexString length]; i++)
    {
        int int_ch;  /// 两位16进制数转化后的10进制数
        unichar hex_char1 = [hexString characterAtIndex:i]; 两位16进制数中的第一位(高位*16)
        int int_ch1;
        if(hex_char1 >= '0' && hex_char1 <='9')
            int_ch1 = (hex_char1-48)*16;    0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch1 = (hex_char1-55)*16;  A 的Ascll - 65
        else
            int_ch1 = (hex_char1-87)*16;  a 的Ascll - 97
        i++;
        unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
        int int_ch2;
        if(hex_char2 >= '0' && hex_char2 <='9')
            int_ch2 = (hex_char2-48);  0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch2 = hex_char2-55;  A 的Ascll - 65
        else
            int_ch2 = hex_char2-87;  a 的Ascll - 97

        int_ch = int_ch1+int_ch2;
        NSLog(@"int_ch=%d",int_ch);
        bytes[j] = int_ch;  ///将转化后的数放入Byte数组里
        j++;
    }

    NSData *newData = [[NSData alloc] initWithBytes:bytes length:20];

    return newData;
}

//停止手环振动
- (IBAction)stopShake:(id)sender {
    unsigned char data [13]= {0};
    data[0] = 0xab;
    *(data+1) = 0x0;
    *(data+2) = 0x0;
    *(data+3) = 0x5;
    *(data+4) = 0x5;
    *(data+5) = 0xd8;
    *(data+6) = 0x0;
    *(data+7) = 0x50;
    *(data+8) = 0x6;
    *(data+9) = 0x0;
    *(data+10) = 0x11;

    *(data+11) = 0x0;
    *(data+12) = 0x0;
    //    *(data+5) = 0x0;

    NSData *data1 = [NSData dataWithBytes:data length:sizeof(data)];
    if (_peripheral.state == CBPeripheralStateConnected) {
        [_peripheral writeValue:data1 forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithResponse];
    }
}

static inline uint16_t crc16_byte(uint16_t crc, const uint8_t data)
{
    return (crc >> 8) ^ crc16_table[(crc ^ data) & 0xff];
}

/** CRC table for the CRC-16. The poly is 0x8005 (x^16 + x^15 + x^2 + 1) */
uint16_t const crc16_table[256] =
{
    0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
    0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
    0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
    0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
    0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
    0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
    0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
    0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
    0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
    0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
    0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
    0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
    0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
    0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
    0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
    0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
    0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
    0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
    0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
    0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
    0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
    0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
    0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
    0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
    0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
    0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
    0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
    0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
    0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
    0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
    0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
    0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
};

/**
 * crc16 - compute the CRC-16 for the data buffer
 * @crc: previous CRC value 之前的crc值
 * @buffer: data pointer data指针
 * @len: number of bytes in the buffer 字节数
 *
 * Returns the updated CRC value.
 */
uint16_t bd_crc16(uint16_t crc, uint8_t const *buffer, uint16_t len)
{
    while (len--)
    crc = crc16_byte(crc, *buffer++);
    return crc;
}

@end
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在C#中从蓝牙设备获取数据,你需要使用.NET Framework提供的Bluetooth API。以下是一个简单的代码示例: ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO.Ports; using InTheHand.Net.Sockets; using InTheHand.Net.Bluetooth; namespace BluetoothDemo { class Program { static void Main(string[] args) { // 获取本机蓝牙设备列表 BluetoothClient client = new BluetoothClient(); BluetoothDeviceInfo[] devices = client.DiscoverDevices(); // 选择要连接设备 BluetoothDeviceInfo device = null; foreach (BluetoothDeviceInfo d in devices) { if (d.DeviceName == "MyDeviceName") { device = d; break; } } if (device != null) { // 连接设备 BluetoothClient client2 = new BluetoothClient(); BluetoothEndPoint ep = new BluetoothEndPoint(device.DeviceAddress, BluetoothService.SerialPort); BluetoothClient client3 = new BluetoothClient(); client3.Connect(ep); // 打开串口通信 SerialPort serialPort = new SerialPort(); serialPort.PortName = "COM1"; // 选择一个未使用的串口号 serialPort.BaudRate = 9600; serialPort.Parity = Parity.None; serialPort.DataBits = 8; serialPort.StopBits = StopBits.One; serialPort.Open(); // 从蓝牙设备读取数据并输出到控制台 while (true) { if (serialPort.BytesToRead > 0) { Console.Write((char)serialPort.ReadByte()); } } // 关闭串口通信 serialPort.Close(); } else { Console.WriteLine("Device not found."); } Console.ReadLine(); } } } ``` 注意,你需要在项目中引用`InTheHand.Net.Personal.dll`和`InTheHand.Net.Sockets.dll`。此外,你需要将`MyDeviceName`替换为你要连接蓝牙设备称。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值