蓝牙控制单片机LED 灯的亮灭

编程入门 行业动态 更新时间:2024-10-11 15:18:44

<a href=https://www.elefans.com/category/jswz/34/1768306.html style=蓝牙控制单片机LED 灯的亮灭"/>

蓝牙控制单片机LED 灯的亮灭

文章目录

        • 1.简介
        • 2.蓝牙模块 硬件连接
        • 3、手机端apk 功能实现
        • 4. 单片机端 程序

1.简介

通过蓝牙通讯 使用手机来控制 单片机 上 LED 灯的亮灭。

1)硬件使用 89c52 单片机
2)BT06 蓝牙模块
3) Android 手机一部

手机 —(蓝牙连接)—> BT06 ----(串口通信)–> 单片机 -----> LED

2.蓝牙模块 硬件连接

蓝牙模块与 51 开发板接线主要有 4 根线需要接,分别为 VCC、GND、TXD、RXD,蓝牙模块上的 VCC 接 到开发板上的 VCC 针脚,蓝牙模块的 GND 接到开发板上的 GND 针脚,蓝牙模块的 TXD 接到开发板上的 P30 针脚,蓝牙模块的 TXD 接到开发板上的 P31 针脚。

单片机上电之后,手机会搜索到 一个蓝牙名称为 “BT04-A” 的蓝牙信号,就是这个蓝牙模块。

3、手机端apk 功能实现

手机端主要是通过蓝牙连接,发送信号给单片机蓝牙模块

  1. 代码结构

    2)AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""package="myapplication.lum.ledcontrol"><uses-permission android:name="android.permission.BLUETOOTH"/><uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>
  1. activity_mani.xml 布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""xmlns:app=""xmlns:tools=""android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity"><Buttonandroid:layout_width="180dp"android:layout_height="60dp"android:id="@+id/connect_id"android:textSize="30dp"android:text="连接蓝牙"/><Buttonandroid:layout_width="180dp"android:layout_height="60dp"android:id="@+id/led_id"android:textSize="30dp"android:text="开灯"/></LinearLayout>

4) mainActivity.java 功能文件

这里 我知道自己买的蓝牙模块的物理地址 44:44:1B:0F:0D:B8 ,就可以直接手动连接 蓝牙,然后通过 蓝牙物理地址 找到 连接的设备,进而连接socket 等,

package myapplication.lum.ledcontrol;import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
import java.util.UUID;import static android.bluetooth.BluetoothProfile.GATT_SERVER;public class MainActivity extends AppCompatActivity implements View.OnClickListener {private String TAG = "LUM: ";private Button buttonConnect, buttonLed;private BluetoothAdapter mbluetoothAdapter;private String bluetoothDeviceMacAddress = "44:44:1B:0F:0D:B8"; //Bluetooth module physical address  private BluetoothDevice bluetoothDevice = null; // Connected Bluetooth deviceprivate BluetoothSocket btSocket = null; // Bluetooth communication socketprivate final static String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB"; // SPP service UUID numberprivate final static int RESULT_CODE = 100;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();}private void initView() {mbluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //get the default bluetooth adapterbuttonConnect = (Button) findViewById(R.id.connect_id);buttonLed = (Button) findViewById(R.id.led_id);buttonConnect.setOnClickListener(this);buttonLed.setOnClickListener(this);IntentFilter filter = new IntentFilter();filter.addAction(BluetoothDevice.ACTION_FOUND);  //Bluetooth searchfilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);registerReceiver(mReceiver, filter);}@Overridepublic void onClick(View view) {switch (view.getId()) {case R.id.connect_id:Log.i(TAG, "check link");//Jump directly to the Bluetooth settings interfaceif ("连接蓝牙".equals(buttonConnect.getText().toString())) {if (!mbluetoothAdapter.isEnabled()){startActivityForResult(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS), RESULT_CODE);} else {connectBtSocket();}} else {disconnect();}break;case R.id.led_id:Log.i(TAG, "led control");if (btSocket != null && btSocket.isConnected()) {if ("开灯".equals(buttonLed.getText().toString())) {send(1);buttonLed.setText("关灯");} else {send(2);buttonLed.setText("开灯");}}}}public void send(int command) {try {if (btSocket != null) {OutputStream os = btSocket.getOutputStream();   //Bluetooth connection output streamos.write(command);} else {Toast.makeText(this, "请先连接蓝牙", Toast.LENGTH_SHORT).show();}} catch (IOException e) {}}public void onActivityResult(int requestCode, int resultCode, Intent data) {if (requestCode == RESULT_CODE) {connectBtSocket();}}private void connectBtSocket() {// Get the handle of the Bluetooth devicebluetoothDevice = mbluetoothAdapter.getRemoteDevice(bluetoothDeviceMacAddress);//Turn off scanning before pairingif (mbluetoothAdapter.isDiscovering()) {mbluetoothAdapter.cancelDiscovery();}// Get the connected sockettry {btSocket = bluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));btSocket.connect();  //Connection socket} catch (IOException e) {Toast.makeText(this, "Connection failed, can't get Socket!" + e, Toast.LENGTH_SHORT).show();e.printStackTrace();}if (btSocket.isConnected()) {Log.i(TAG, "socket connected");Toast.makeText(this, "connect success", Toast.LENGTH_SHORT).show();buttonConnect.setText("蓝牙已连接");} else {Log.i(TAG, "socket didn't connected");Toast.makeText(this, "connect failed", Toast.LENGTH_SHORT).show();}}private void disconnect() {try {if (btSocket != null) {btSocket.close();}} catch (IOException e) {}buttonConnect.setText("连接蓝牙");}// Help us find the physical address of the Bluetooth module that needs to be connectedprivate final BroadcastReceiver mReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();if (BluetoothDevice.ACTION_FOUND.equals(action)) {BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);Log.i(TAG, "Searched Bluetooth device;  device name: " + device.getName() + "  device address: " + device.getAddress());}if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {Log.i(TAG, "ACTION_ACL_CONNECTED");if (btSocket.isConnected()) {buttonConnect.setText("蓝牙已连接");}}if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {Log.i(TAG, "ACTION_ACL_CONNECTED");if (btSocket.isConnected()) {buttonConnect.setText("连接蓝牙");}}}};public void onDestroy() {super.onDestroy();unregisterReceiver(mReceiver);Log.i(TAG, "Unregister");}
}
4. 单片机端 程序

#include <reg52.h> //51头文件sbit LED1 = P1^0; //位定义 LED1硬件接口
void delay(unsigned int z)//毫秒级延时
{unsigned int x,y;for(x = z; x > 0; x--)for(y = 114; y > 0 ; y--);
}	/******************************************************************/
/* 串口中断程序*/
/******************************************************************/
void UART_SER () interrupt 4
{unsigned int n; 	//定义临时变量if(RI) 		//判断是接收中断产生{RI=0; 	//标志位清零n=SBUF; //读入缓冲区的值switch(n){case 1:	LED1 = 0;	break;	//亮灯case 2:	LED1 = 1;	break;	//灭灯}}}//蓝牙初始化
void boothint(void)
{SCON = 0x50; 	// SCON: 模式1, 8-bit UART, 使能接收 TMOD |= 0x20;TH1=0xfd; 		//波特率9600 初值TL1=0xfd;TR1= 1;EA = 1;	    //开总中断ES= 1; 		//打开串口中断}
void main()
{boothint();while(1){}
}

文件参考:
安卓手机与蓝牙模块联合调试(三)—— 单片机蓝牙控制LED灯亮灭(下)

更多推荐

蓝牙控制单片机LED 灯的亮灭

本文发布于:2024-03-14 01:06:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1735289.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:蓝牙   单片机   LED

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!