在网上看到的,你参考下吧:
主机为smartRF开发板,从机为两个cc2540设备,首先搜索设备,然后选择设备连接,一次选择一个进行连接,连接好了再同样操作连接下一个(能不能同时连接?)。连接好了之后给设备发命令,其实还是一个一个发数据的,还没找到同时发数据的方法。程序在SimpleBLECentral基础上改的。
主要修改的地方有:
回调函数中显示所有搜索到的从设备地址:
static void simpleBLECentralEventCB( gapCentralRoleEvent_t *pEvent )
{
switch ( pEvent->gap.opcode )
{
case GAP_DEVICE_INIT_DONE_EVENT: //设备初始化
{
LCD_WRITE_STRING( "BLE Central", HAL_LCD_LINE_1 );
LCD_WRITE_STRING( bdAddr2Str( pEvent->initDone.devAddr ), HAL_LCD_LINE_2 );
LCD_LINE_= 0x04;
simpleBLEConnHandle_num = 0;
}
break;
case GAP_DEVICE_INFO_EVENT:
{
// if filtering device discovery results based on service UUID
if ( DEFAULT_DEV_DISC_BY_SVC_UUID == TRUE )
{
if ( simpleBLEFindSvcUuid( SIMPLEPROFILE_SERV_UUID,
pEvent->deviceInfo.pEvtData,
pEvent->deviceInfo.dataLen ) )
{
simpleBLEAddDeviceInfo( pEvent->deviceInfo.addr, pEvent->deviceInfo.addrType );//向设备发现列表中添加一个设备
LCD_WRITE_STRING( "AdvDevice_Addr:", HAL_LCD_LINE_3 );
LCD_WRITE_STRING( bdAddr2Str( pEvent->deviceInfo.addr ), LCD_LINE_);//显示所有广告设备地址
LCD_LINE_++;//每增加一个设备屏幕换一行
}
}
}
break;
case GAP_DEVICE_DISCOVERY_EVENT://设备发现完成
{
// discovery complete
simpleBLEScanning = FALSE;
// if not filtering device discovery results based on service UUID
if ( DEFAULT_DEV_DISC_BY_SVC_UUID == FALSE )
{
// Copy results
simpleBLEScanRes = pEvent->discCmpl.numDevs;
osal_memcpy( simpleBLEDevList, pEvent->discCmpl.pDevList,
(sizeof( gapDevRec_t ) * pEvent->discCmpl.numDevs) );
}
LCD_WRITE_STRING_VALUE( "Devices Found", simpleBLEScanRes,
10, HAL_LCD_LINE_1 );
if ( simpleBLEScanRes > 0 )
{
LCD_WRITE_STRING( "<- To Select", HAL_LCD_LINE_2 );
}
// initialize scan index to last device
simpleBLEScanIdx = simpleBLEScanRes;
}
break;
case GAP_LINK_ESTABLISHED_EVENT://设备连接
{
if ( pEvent->gap.hdr.status == SUCCESS )
{
simpleBLEState = BLE_STATE_CONNECTED;
simpleBLEConnHandle= pEvent->linkCmpl.connectionHandle;
ConnHandle[simpleBLEConnHandle_num] =pEvent->linkCmpl.connectionHandle;//将handle存起来,供主机发送数据的时候使用
simpleBLEConnHandle_num++;//每连接一个设备增加一次
simpleBLEProcedureInProgress = TRUE;
发起连接请求:
if ( keys & HAL_KEY_CENTER )//建立连接
{
uint8 addrType;
uint8 *peerAddr;
// Connect or disconnect
// if ( simpleBLEState == BLE_STATE_IDLE )//屏蔽状态判断,任何时候都可以建立连接
// {
// if there is a scan result
if ( simpleBLEScanRes > 0 )
{
// connect to current device in scan result
peerAddr = simpleBLEDevList[simpleBLEScanIdx].addr;
addrType = simpleBLEDevList[simpleBLEScanIdx].addrType;
simpleBLEState = BLE_STATE_CONNECTING;
GAPCentralRole_EstablishLink( DEFAULT_LINK_HIGH_DUTY_CYCLE,
DEFAULT_LINK_WHITE_LIST,
addrType, peerAddr );//发起建立连接请求
LCD_WRITE_STRING( "Connecting", HAL_LCD_LINE_1 );
LCD_WRITE_STRING( bdAddr2Str( peerAddr ), HAL_LCD_LINE_2 );
}
发送数据的时候调用函数(算不上实际意义上的同时控制):
GATT_WriteCharValue( ConnHandle[0], &req, simpleBLETaskId );//发给设备1
GATT_WriteCharValue( ConnHandle[1], &req, simpleBLETaskId ); //发给设备2
………………
|