手机端app:
1、首先需要给app授权蓝牙权限:
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.BLUETOOTH" />
2、获取手机配对蓝牙的MAC地址
ListView devicelist; private BluetoothAdapter myBluetooth = null; private Set<BluetoothDevice> pairedDevices; public static String EXTRA_ADDRESS = "device_address";
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if ( myBluetooth==null ) { // 设备不支持蓝牙 Toast.makeText(getApplicationContext(), "Bluetooth device not available", Toast.LENGTH_LONG).show(); finish(); } else if ( !myBluetooth.isEnabled() ) { Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(turnBTon,REQUEST_CONNECT_DEVICE); // 开启蓝牙 }
pairedDevices = myBluetooth.getBondedDevices(); // 返回已配对的蓝牙设备 ArrayList list = new ArrayList(); if ( pairedDevices.size() > 0 ) { // 存在可配对设备 for ( BluetoothDevice bt : pairedDevices ) { list.add(bt.getName().toString() + "\n" + bt.getAddress().toString()); } } else { Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show(); } final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list); devicelist.setAdapter(adapter); devicelist.setOnItemClickListener(myListClickListener); // list_View ***
private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String info = ((TextView) view).getText().toString(); String address = info.substring(info.length()-17); Intent i = new Intent(DeviceList.this, ledControl.class); // 传输要连接目标蓝牙的 MAC 地址 i.putExtra(EXTRA_ADDRESS, address); startActivity(i); } };
3、连接HC05
BluetoothAdapter myBluetooth = null; BluetoothSocket btSocket = null; private boolean isBtConnected = false; static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent newint = getIntent(); address = newint.getStringExtra(DeviceList.EXTRA_ADDRESS); setContentView(R.layout.activity_led_control); btn1 = (Button) findViewById(R.id.button2); btnDis = (Button) findViewById(R.id.button4); lumn = (TextView) findViewById(R.id.textView2); try { if ( btSocket==null || !isBtConnected ) { myBluetooth = BluetoothAdapter.getDefaultAdapter(); BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address); btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID); BluetoothAdapter.getDefaultAdapter().cancelDiscovery(); btSocket.connect(); msg("Connected Succesful"); } } catch (IOException e) { msg("Connected Failed. Try again."); } btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v) { msg("Click 1 "); sendSignal("1"); } }); btnDis.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v) { Disconnect(); } }); } private void sendSignal ( String number ) { if ( btSocket != null ) { try { btSocket.getOutputStream().write(number.toString().getBytes()); Log.i("sendSigal",number.toString()); } catch (IOException e) { Log.i("sendSigal",btSocket.toString()); msg("Error"); } }else{ Log.i("sendSigal","222222"); } } private void Disconnect () { if ( btSocket!=null ) { try { btSocket.close(); } catch(IOException e) { msg("Error"); } } finish(); } private void msg (String s) { Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show(); }
单片机(STM32)端 串口设置:
//串口1初始化配置void usart1_init(void)
{GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = 115200;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART1, &USART_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=1 ;//抢占优先级1
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //子优先级3
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道使能
NVIC_Init(&NVIC_InitStructure); //根据指定的参数初始化VIC寄存器
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//开启串口接受中断
USART_Cmd(USART1, ENABLE);
USART_ClearFlag(USART1, USART_FLAG_TC);
}
//串口1中断服务程序
void USART1_IRQHandler(void)
{
u8 Res;
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) //接收中断(接收到的数据必须是0x0d 0x0a结尾)
{
Res =USART_ReceiveData(USART1);//读取接收到的数据
USART1_RX_BUF[TX2_no++]=Res;
// 配置自己的接受判断逻辑
}else if(TX2_no == USART_RX_LEN) //接收缓冲区接收满,即接收完成
{
TX2_no = 0;
USART1_RX_STA = 1;
}
}
具体的代码,整理完毕后我会上传上来,如果大家需要也可以先私信我,共同学习!