蓝牙串口通信控制Arduino全彩呼吸灯 |
您所在的位置:网站首页 › arduino课程设计 › 蓝牙串口通信控制Arduino全彩呼吸灯 |
这是我期末的时候做的一个Arduino课程设计,可以通过手机APP来控制呼吸灯亮灭及颜色变化。 主要实验器材:Arduino UNO开发板共阳三色雾状LED灯面包板、普通LED灯、电阻、杜邦线若干HC-05蓝牙模块支持蓝牙功能的Android手机![]() HC-05 VCC ----- Arduino VIN HC-05 GND ----- Arduino GND HC-05 TXD ----- Arduino RXD HC-05 RXD ----- Arduino TXD Android蓝牙模块手机APP连接上HC-05后,在TextView中输入要发送的字符串,定义s、c、f、b分别为小LED灯开、关、和三色彩灯的开、关;通过蓝牙串口将字符串发送出去。 Android蓝牙通信程序关键代码打开蓝牙:// 获取蓝牙适配器 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //请求开启蓝牙 if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); }搜索设备:// 将已配对的设备添加到列表中 Set pairedDevices = mBluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { mDevicesArray.add(device.getName() + "\n" + device.getAddress()); deviceList.add(device); } } // 注册广播接收器,以获取蓝牙设备搜索结果 IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy // 搜索蓝牙设备 mBluetoothAdapter.startDiscovery(); // Create a BroadcastReceiver for ACTION_FOUND private final BroadcastReceiver mReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) { // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); deviceList.add(device); // Add the name and address to an array adapter to show in a ListView mDevicesArray.add(device.getName() + "\n" + device.getAddress()); // Notify ListView to update devicesListAdapter.notifyDataSetChanged(); } } };匹配并建立连接BluetoothSocket socket = null; try { // 蓝牙串口服务对应的UUID。如使用的是其它蓝牙服务,需更改下面的字符串 UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); socket = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (Exception e) { Log.d("log", "获取Socket失败"); return; } try { // Connect the device through the socket. This will block // until it succeeds or throws an exception socket.connect(); Log.d("log", "连接成功"); } catch (IOException connectException) { // Unable to connect; close the socket and get out Log.d("log", "连接失败"); try { socket.close(); } catch (IOException closeException) { } return; }收发数据mmInStream = socket.getInputStream(); mmOutStream = socket.getOutputStream(); //接收数据 byte[] buffer = new byte[1024]; try { bytes = mmInStream.read(buffer); } catch (IOException e) { break; } //发送数据 try { mmOutStream.write(bytes); } catch (IOException e) { }共阳三色雾状LED灯介绍![]() 顾名思义它可以产生三种颜色,分别是红、绿、蓝,也可以同时调整三种颜色的亮度,产生彩色呼吸灯的效果。 系统原理图:![]() ![]() |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |