蓝牙与单片机通信_单片机与手机蓝牙通信蓝牙优先 - CSDN
精华内容
参与话题
  • 打算利用蓝牙芯片HC06实现手机和单片机之间的简单通信。工具包括淘宝上淘的stc单片机实验板一块,hc-06蓝牙模块一个,杜邦线,win7电脑一部,安卓手机一部,相关软件:单片机小精灵,串口通讯助手,keil以及单片机...

    打算利用蓝牙芯片HC06实现手机和单片机之间的简单通信。工具包括淘宝上淘的stc单片机实验板一块,hc-06蓝牙模块一个,杜邦线,win7电脑一部,安卓手机一部,相关软件:单片机小精灵,串口通讯助手,keil以及单片机烧录软件,蓝牙通讯软件APP。软件基本上都是免安装直接运行的。

    工作流程简单总结下为以下3步:
    1.利用单片机小精灵软件,做好烧录程序,确定波特率应该设置为2400
    2.hc-06蓝牙模块进入AT模式,串口通讯助手成功将蓝牙模块波特率设置为2400
    3.将烧录程序通过keil编译成功后烧录至单片机实验板上,手机上安装好APP,设置完成后运行,确定成功。

    步骤(2)见


    https://blog.csdn.net/dok12/article/details/80152239
    步骤(3)见
    https://blog.csdn.net/dok12/article/details/801730

    本篇先介绍步骤1。工具,单片机小精灵软件,免安装,直接运行。

    打开单片机小精灵软件,选择串口波特率选项。必须选择好晶振和波特率。其他选项,c语言还是汇编,是否串口中断,波特率加倍,允许接收都自己决定。
    因为淘宝买到的单片机实验板是12M晶振,蓝牙模块的默认波特率是9600。所以一开始输入这两项数据。
    结果发现误差太大,必须修改。晶振改不了,只好改波特率了。
    修改波特率为2400后误差控制在千分之一点六,效果不错,得到了一个C语言的串口通信基本框架了。

    根据这个框架做了个C语言程序,目标是对单片机实现蓝牙通讯,实现不同的单片机流水灯效果,并且得到回复数字8。
    #include <reg51.h>
    unsigned char k;
    void InitUART(void)
    {
        TMOD = 0x20;
        SCON = 0x50;
        TH1 = 0xF3;
        TL1 = 0xF3;
        PCON = 0x00;
        EA = 1;
        ES = 1;
        TR1 = 1;
    }
    /*******延时函数*************/
    void delay(unsigned int i)
    {
        unsigned char j;
        for(i; i > 0; i--)   
            for(j = 255; j > 0; j--);
    }
    void main(void)
    {	k=0;
        InitUART();
    	while  (1){
    	if(k==1)
    	{P1=0xff;delay(500);P1=0x00;delay(500);}
    	else if (k==2)
    	{P1=0x01;delay(500);P1=0xfe;delay(500);}
    	else 
    	{P1=0x02;delay(500);P1=0xfd;delay(500);}
    	}
    }
    void SendOneByte(unsigned char c)
    {
        SBUF = c;
        while(!TI);
        TI = 0;
    }
    
    void UARTInterrupt(void) interrupt 4
    {
        if(RI)
        {
            RI = 0;
            //add your code here!
    		k++;
    		if(k>2)k=0;
    		SendOneByte(8);
        }
        else
            TI = 0;
    }
    
    
    




    展开全文
  • 手机与单片机通过蓝牙通信----手机控制灯

    万次阅读 热门讨论 2018-12-11 22:07:32
    ... QQ技术交流群:129518033     ...环境 1、普中科技HC6800-EM3 v2.2 单片机开发实验仪(芯片STC90C516RD+)  2、无线蓝牙串口透传模块 HC-06从机  3、windows xp操作系统  4、Androi...

     

    如需转载请标明出处:http://blog.csdn.net/itas109 

    QQ技术交流群:129518033

     

     

     

    环境   1、普中科技HC6800-EM3 v2.2 单片机开发实验仪(芯片STC90C516RD+)
              2、无线蓝牙串口透传模块 HC-06从机
              3、windows xp操作系统
              4、Android手机(蓝牙串口通信助手软件)

    注意:蓝牙部分连线图与实物图不符。可以参照下图接蓝牙(2013年05月31日改)

              上拉电阻的阻值有人问我,我当时用的是1KΩ。



    蓝牙开发初级实例,用手机控制灯的亮灭。

     实物连线图:

     

    单片机代码

      /***********************************************************
    STC89C52与蓝牙连线:
     蓝牙  51
     RXD    TXD
     TXD    RXD
    其他连线:
     P2.0、P2.1、P2.3分别接一个指示灯
    手机采用蓝牙串口通信助手
    ***********************************************************/
    #include <reg52.h>
    #include <intrins.h>
    unsigned char tmp;
    sbit led1=P2^0;     //指示灯0
    sbit led2=P2^1;   //指示灯1
    sbit led3=P2^3;   //指示灯3
    void init();
    void delay(unsigned int i);
    void send(); //发送回馈信息,目前无效不知道什么原因
    void ctrl();
    void main()
    {
      init();
              while(1)
              {
              
                      if(RI==1)                     // 是否有数据到来
                      {
                       RI = 0;
                      tmp = SBUF;                   // 暂存接收到的数据
          ctrl();
          }          
              }
    }
     void init() //初始化
     {
      TMOD = 0x20;                        // 定时器1工作于8位自动重载模式, 用于产生波特率
              TH1=TL1=0xFD;                                // 波特率9600
              
              SCON = 0x50;                        // 设定串行口工作方式1 允许接收,相当于下面三句
            //SM0=0;
           //SM1=1;
            //REN=1;
                   PCON =0x00;                        // 波特率不倍增
              TR1 = 1;
        EA=1;
            ES=1;
              led1=0;                            //初始化设置3个指示灯全亮
        led2=0;
        led3=0;
     }
    void delay(unsigned int i)
    {
     unsigned char j;
     for(i; i > 0; i--)
      for(j = 200; j > 0; j--) ;
    }
    void send() //发送回馈信息,目前无效不知道什么原因
    {
     unsigned char a;
     a=tmp;
     TI=0;
     SBUF=a;
     while(TI==0);
     TI=0;
     led3=1;
     //delay(1000);
    }
    void ctrl()   //根据接受信息做出操作
    {
            switch(tmp)
          {
           case '1':
          led1=1;              //收到字符1,指示灯0灭
          send();
          break;     
         case '2':      //收到字符2,指示灯1灭
           led2=1; 
           send();
           break;
         case '3':        //收到字符3,指示灯0、1亮
           led1=0;
           led2=0;
           send();
           break;
         case '4':     //收到字符4,指示灯0、1灭
            led1=1;
            led2=1;
            send();
            break;
         case '5':     //收到字符5,指示灯3亮
          led3=0;
          break;
         default:                   //其他,灯全灭
            led1=1;
            led2=1;
            led3=1;
            send();
          }
    }
    
    


    手机通过蓝牙串口助手操作:

     

    觉得文章对你有帮助,可以扫描二维码捐赠给博主,谢谢!

    如需转载请标明出处:http://blog.csdn.net/itas109 

    QQ技术交流群:129518033


     

    展开全文
  • 首先将HC-06蓝牙通信模块和单片机串口通过杜邦线连接,接线如图所示:RX-P30 TX-P31tips:淘宝购买HC06模块的时候,卖家表示蓝牙模块的TX,RX端的丝印搞反了,所以如果你发现蓝牙模块无法和单片机通信的话,可以尝试...

    本篇介绍如何将蓝牙模块进入AT模式,调整波特率。

    工具:软件串口通讯助手,免安装,直接在win7电脑上运行。

    首先将HC-06蓝牙通信模块和单片机串口通过杜邦线连接,接线如图所示:
    RX-P30                TX-P31
    tips:淘宝购买HC06模块的时候,卖家表示蓝牙模块的TX,RX端的丝印搞反了,所以如果你发现蓝牙模块无法和单片机通信的话,可以尝试调换下TX,RX两端的杜邦线


    将单片机连上电脑,(电脑需要安装单片机的相关驱动,买单片机实验板时候卖家附送的驱动我发现在win10下没用,win7下正常运行),我的电脑——》计算机管理,端口显示端口4
    然后在打开串口调试助手软件。

    串口com4,波特率是9600,输入AT,得到OK就表明成功进入AT模式。

    之后在输入AT+BAUD2,将波特率改为2400.会显示OK2400.
    将串口助手波特率改为2400,输入AT显示OK,表明成功修改至2400



    展开全文
  • 通过蓝牙模块与单片机通讯

    千次阅读 2015-08-06 17:50:48
    ·简介:由于业务关系,需要开发一个向单片机发送数据的应用,不过由于需求很简单,只  需要发送数据即可,所以该dome的功能只有发送数据功能,并没有对输入的数据  做进一步的处理 这里有蓝牙开发的基本...
    ·简介:由于业务关系,需要开发一个向单片机发送数据的应用,不过由于需求很简单,只  需要发送数据即可,所以该dome的功能只有发送数据功能,并没有对输入的数据   做进一步的处理

    这里有蓝牙开发的基本资料,建议蓝牙基础欠缺的可以先悉知一下:http://pan.baidu.com/s/1ntrHntB

    这里是我的dome工程目录





    布局文件:
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
        android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
    
    
    
        <TextView
            android:id="@+id/textView1"
            android:text="@string/hello_world"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/textView2"
            android:layout_below="@id/textView1"
            android:text="@string/hello_world"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    
        <TextView
            android:id="@+id/textView3"
            android:layout_below="@id/textView2"
            android:text="@string/hello_world"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    
    
        <SeekBar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/seekBar1"
            android:layout_below="@+id/textView2"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="108dp" />
        <SeekBar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/seekBar2"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
    
    </RelativeLayout>

    总的来说,通讯过程是:
    1、得到本地蓝牙设备,
     void initOpenBluetooth() {
            //取得本地蓝牙设备
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    
            if (mBluetoothAdapter == null) {
                Toast.makeText(this, "蓝牙不可用", Toast.LENGTH_SHORT).show();
                finish();
                return;
            }
    
            //如果蓝牙没打开,提醒用户打开蓝牙
            if (!mBluetoothAdapter.isEnabled()) {
                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(intent, REQUEST_ENABLE_BT);
            }else {
                if(mBluetoothAdapter.isEnabled()){
                    initGetDevice();
                }
            }
    
        }

    2、得到远程设备,
    private void initGetDevice(){
            //获取远程BlueToothDevice
            device = mBluetoothAdapter.getRemoteDevice(address);
            textView3.setText(device.getAddress() + ":" + device.getName());
    
            if (mChatService == null) {
                mChatService = new BluetoothChatService(this);
                if (D) Log.v(TAG, "当前蓝牙状态:" + mChatService.getState());
    
                mChatService.connect(device);//启动了蓝牙连接线程,
                if (D) Log.v(TAG, "当前蓝牙状态:" + mChatService.getState());
            }
        }

    3、找到已配对的设备,连接,连接需要唯一的通讯信道UUID
     /*********************    连接线程   ****************/
        private class ConnectThread extends Thread {
            private final BluetoothSocket mmSocket;
            private final BluetoothDevice mmDevice;
    
            public ConnectThread(BluetoothDevice device) {
                mmDevice = device;
                BluetoothSocket tmp = null;
    
                // Get a BluetoothSocket for a connection with the
                // given BluetoothDevice
                try {
                    tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
                } catch (IOException e) {
                    Log.e(TAG, "create() failed", e);
                }
                mmSocket = tmp;
            }
    
            public void run() {
                Log.i(TAG, "BEGIN mConnectThread");
                setName("ConnectThread");
    
                // Always cancel discovery because it will slow down a connection
                mAdapter.cancelDiscovery();
    
                // Make a connection to the BluetoothSocket
                try {
                    // This is a blocking call and will only return on a
                    // successful connection or an exception
                    mmSocket.connect();
                } catch (IOException e) {
                    connectionFailed();
                    // Close the socket
                    try {
                        mmSocket.close();
                    } catch (IOException e2) {
                        Log.e(TAG, "unable to close() socket during connection failure", e2);
                    }
                    /*// Start the service over to restart listening mode
                    BluetoothChatService.this.start();*/
                    return;
                }
    
                // Reset the ConnectThread because we're done
                synchronized (BluetoothChatService.this) {
                    mConnectThread = null;
                }
    
                // Start the connected thread
                connected(mmSocket, mmDevice);
            }
    
            public void cancel() {
                try {
                    mmSocket.close();
                } catch (IOException e) {
                    Log.e(TAG, "close() of connect socket failed", e);
                }
            }
        }
    

    3、连接后的连接管理,通讯
     /*********************   连接管理,通讯线程   **********************/
        private class ConnectedThread extends Thread {
            private final BluetoothSocket mmSocket;
            private final InputStream mmInStream;
            private final OutputStream mmOutStream;
    
            public ConnectedThread(BluetoothSocket socket) {
                Log.d(TAG, "create ConnectedThread");
                mmSocket = socket;
                InputStream tmpIn = null;
                OutputStream tmpOut = null;
    
                // Get the BluetoothSocket input and output streams
                try {
                    tmpIn = socket.getInputStream();
                    tmpOut = socket.getOutputStream();
                } catch (IOException e) {
                    Log.e(TAG, "temp sockets not created", e);
                }
    
                mmInStream = tmpIn;
                mmOutStream = tmpOut;
            }
    
            public void run() {
                Log.i(TAG, "BEGIN mConnectedThread");
                byte[] buffer = new byte[1024];
                int bytes;
    
                // Keep listening to the InputStream while connected
                while (true) {
                    try {
                        // Read from the InputStream
                        bytes = mmInStream.read(buffer);
    
                    } catch (IOException e) {
                        Log.e(TAG, "disconnected", e);
                        connectionLost();
                        break;
                    }
                }
            }
    
            /**
             * Write to the connected OutStream.
             * @param buffer  The bytes to write
             */
            public void write(byte[] buffer) {
                try {
                    mmOutStream.write(buffer);
    
                } catch (IOException e) {
                    Log.e(TAG, "Exception during write", e);
                }
            }
    
            public void cancel() {
                try {
                    mmSocket.close();
                } catch (IOException e) {
                    Log.e(TAG, "close() of connect socket failed", e);
                }
            }
        }

    4、最后一步,修复一些小Bug,然后可以根据自己的业务需求来更改代码。
         本来还有一个等待连接线程的,但该次业务无此需求,故不列出来了。

    5:这里是整个dome的代码:
    MainActivity:
    public class MainActivity extends ActionBarActivity implements SeekBar.OnSeekBarChangeListener {
    
        // Debugging
        private static final String TAG = "MainActivity";
        private static final boolean D = true;
    
        //定义打开蓝牙的请求码
        private static final int REQUEST_ENABLE_BT = 2;
    
        // 本地蓝牙设备
        private BluetoothAdapter mBluetoothAdapter = null;
        // Member object for the chat services
        private BluetoothChatService mChatService = null;
    
        BluetoothDevice device;
        private static String address = "30:14:11:12:38:01";
    
        SeekBar seekBar1,seekBar2;
        TextView textView1,textView2,textView3;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            if(D) Log.v(TAG, "+++ ON CREATE +++");
            System.out.println("+++ ON CREATE +++");
    
            seekBar1 = (SeekBar) findViewById(R.id.seekBar1);
            seekBar2 = (SeekBar) findViewById(R.id.seekBar2);
            textView1 = (TextView) findViewById(R.id.textView1);
            textView2 = (TextView) findViewById(R.id.textView2);
            textView3 = (TextView) findViewById(R.id.textView3);
    
            //两种方式监听
            seekBar1.setOnSeekBarChangeListener(this);
            seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    textView2.setText("当前值:" + progress);
    
                    //  发送数据
                    String msg = String.valueOf(progress);
    
                    if (mChatService.getState() == BluetoothChatService.STATE_CONNECTED) {
    
                        mChatService.write(getHexBytes(msg));
    
                    }else {
                        System.out.println("没有连接好");
                    }
                }
    
                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
    
                }
    
                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
    
                }
            });
    
            initOpenBluetooth();
    
        }
    
        /***************  再按一次退出程序  ****************/
        private long _doubleClickedTime = 0;
        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                long clickedTime = System.currentTimeMillis();
                if (clickedTime - _doubleClickedTime <= 2000) {
                    // 两次点击退出
                    finish();
                } else {
                    Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    _doubleClickedTime = clickedTime;
                }
                return true;
            }
            return super.onKeyDown(keyCode, event);
        }
    
    
        /***********  退出后,把蓝牙的连接注销   ***********/
        @Override
        protected void onDestroy() {
            super.onDestroy();
            mChatService.stop();
            finish();
        }
    
    
        /*************  当“打开蓝牙的dialog结束后,要回调的函数”    ************/
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
    
            if(requestCode == REQUEST_ENABLE_BT){
    
                initGetDevice();
    
            }
        }
    
    
        /*******************  initOpenBluetooth    *********************/
        void initOpenBluetooth() {
            //取得本地蓝牙设备
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    
            if (mBluetoothAdapter == null) {
                Toast.makeText(this, "蓝牙不可用", Toast.LENGTH_SHORT).show();
                finish();
                return;
            }
    
            //如果蓝牙没打开,提醒用户打开蓝牙
            if (!mBluetoothAdapter.isEnabled()) {
                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(intent, REQUEST_ENABLE_BT);
            }else {
                if(mBluetoothAdapter.isEnabled()){
                    initGetDevice();
                }
            }
    
        }
    
    
        /********************  intDetDevice  **********************/
        private void initGetDevice(){
            //获取远程BlueToothDevice
            device = mBluetoothAdapter.getRemoteDevice(address);
            textView3.setText(device.getAddress() + ":" + device.getName());
    
            if (mChatService == null) {
                mChatService = new BluetoothChatService(this);
                if (D) Log.v(TAG, "当前蓝牙状态:" + mChatService.getState());
    
                mChatService.connect(device);//启动了蓝牙连接线程,
                if (D) Log.v(TAG, "当前蓝牙状态:" + mChatService.getState());
            }
        }
    
    
        /******************** 字符串转换为16进制  **********************/
        private byte[] getHexBytes(String message) {
            int len = message.length() / 2;
            char[] chars = message.toCharArray();
            String[] hexStr = new String[len];
            byte[] bytes = new byte[len];
            for (int i = 0, j = 0; j < len; i += 2, j++) {
                hexStr[j] = "" + chars[i] + chars[i + 1];
                bytes[j] = (byte) Integer.parseInt(hexStr[j], 16);
            }
            return bytes;
        }
    
    
        /********************************  拖动发送数据   ********************************/
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    
            textView1.setText("当前值:" + progress);
            //  发送数据
            String msg = String.valueOf(progress);
    
            if (mChatService.getState() == BluetoothChatService.STATE_CONNECTED) {
    
                mChatService.write(getHexBytes(msg));
    
            }else {
                System.out.println("没有连接好");
            }
        }
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
    
        }
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
    
        }
    
    /******************************   标题栏  ************************************/
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
    
            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }
    
            return super.onOptionsItemSelected(item);
        }
    }

    工具类:BluetoothChatService:
    public class BluetoothChatService {
        // Debugging
        private static final String TAG = "BluetoothChatService";
        private static final boolean D = true;
    
        // Name for the SDP record when creating server socket
        private static final String NAME = "BluetoothChat";
    
        // Unique UUID for this application
    
        private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    
        // Member fields
        private final BluetoothAdapter mAdapter;
    
        private AcceptThread mAcceptThread;
        private ConnectThread mConnectThread;
        private ConnectedThread mConnectedThread;
        private int mState;
    
        // Constants that indicate the current connection state
        public static final int STATE_NONE = 0;       // we're doing nothing
        public static final int STATE_LISTEN = 1;     // now listening for incoming connections
        public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
        public static final int STATE_CONNECTED = 3;  // now connected to a remote device
    
    
        public BluetoothChatService(Context context) {
            mAdapter = BluetoothAdapter.getDefaultAdapter();
            mState = STATE_NONE;
        }
    
    
        private synchronized void setState(int state) {
            if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
            mState = state;
    
    
        }
    
        public synchronized int getState() {
            return mState;
        }
    
        /***************  本来还有个监听线程入口 和 监听线程。此应用没用到  ***********/
    
        /**********************   启动连接线程  ************************/
        public synchronized void connect(BluetoothDevice device) {
            if (D) Log.d(TAG, "connect to: " + device);
    
            // Cancel any thread attempting to make a connection
          /*  if (mState == STATE_CONNECTING) {
                if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
            }
    */
            if (mState == STATE_NONE) {
                if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
            }
    
            // Cancel any thread currently running a connection
            if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
    
            // Start the thread to connect with the given device
            mConnectThread = new ConnectThread(device);
            mConnectThread.start();
            setState(STATE_CONNECTING);
        }
    
    
        /*******************  启动连接管理,通讯线程的入口 **************************/
        public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
            if (D) Log.d(TAG, "connected");
    
            // Cancel the thread that completed the connection
            if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
    
            // Cancel any thread currently running a connection
            if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
    
            // Cancel the accept thread because we only want to connect to one device
            if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}
    
            // Start the thread to manage the connection and perform transmissions
            mConnectedThread = new ConnectedThread(socket);
            mConnectedThread.start();
            setState(STATE_CONNECTED);
        }
    
        /******************   注销掉所有  *****************/
        public synchronized void stop() {
            if (D) Log.d(TAG, "stop");
            if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
            if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
            if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}
            setState(STATE_NONE);
        }
    
        /***************  写出给通许线程,由线程来发送数据  ***********/
        public void write(byte[] out) {
            // Create temporary object
            ConnectedThread r;
            // Synchronize a copy of the ConnectedThread
            synchronized (this) {
                if (mState != STATE_CONNECTED) return;
                r = mConnectedThread;
            }
            // Perform the write unsynchronized
            r.write(out);
        }
    
    
        private void connectionFailed() {
            setState(STATE_LISTEN);
        }
    
        private void connectionLost() {
            setState(STATE_LISTEN);
        }
    
    
       /*********************  等待监听线程,此应用没用到  ****************/
        private class AcceptThread extends Thread {
            // The local server socket
            private final BluetoothServerSocket mmServerSocket;
    
            public AcceptThread() {
                BluetoothServerSocket tmp = null;
    
                // Create a new listening server socket
                try {
                    tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
                } catch (IOException e) {
                    Log.e(TAG, "listen() failed", e);
                }
                mmServerSocket = tmp;
            }
    
            public void run() {
                if (D) Log.d(TAG, "BEGIN mAcceptThread" + this);
                setName("AcceptThread");
                BluetoothSocket socket = null;
    
                // Listen to the server socket if we're not connected
                while (mState != STATE_CONNECTED) {
                    try {
                        // This is a blocking call and will only return on a
                        // successful connection or an exception
                        socket = mmServerSocket.accept();
                    } catch (IOException e) {
                        Log.e(TAG, "accept() failed", e);
                        break;
                    }
    
                    // If a connection was accepted
                    if (socket != null) {
                        synchronized (BluetoothChatService.this) {
                            switch (mState) {
                                case STATE_LISTEN:
                                case STATE_CONNECTING:
                                    // Situation normal. Start the connected thread.
                                    connected(socket, socket.getRemoteDevice());
                                    break;
                                case STATE_NONE:
                                case STATE_CONNECTED:
                                    // Either not ready or already connected. Terminate new socket.
                                    try {
                                        socket.close();
                                    } catch (IOException e) {
                                        Log.e(TAG, "Could not close unwanted socket", e);
                                    }
                                    break;
                            }
                        }
                    }
                }
                if (D) Log.i(TAG, "END mAcceptThread");
            }
    
            public void cancel() {
                if (D) Log.d(TAG, "cancel " + this);
                try {
                    mmServerSocket.close();
                } catch (IOException e) {
                    Log.e(TAG, "close() of server failed", e);
                }
            }
        }
    
    
       /*********************    连接线程   ****************/
        private class ConnectThread extends Thread {
            private final BluetoothSocket mmSocket;
            private final BluetoothDevice mmDevice;
    
            public ConnectThread(BluetoothDevice device) {
                mmDevice = device;
                BluetoothSocket tmp = null;
    
                // Get a BluetoothSocket for a connection with the
                // given BluetoothDevice
                try {
                    tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
                } catch (IOException e) {
                    Log.e(TAG, "create() failed", e);
                }
                mmSocket = tmp;
            }
    
            public void run() {
                Log.i(TAG, "BEGIN mConnectThread");
                setName("ConnectThread");
    
                // Always cancel discovery because it will slow down a connection
                mAdapter.cancelDiscovery();
    
                // Make a connection to the BluetoothSocket
                try {
                    // This is a blocking call and will only return on a
                    // successful connection or an exception
                    mmSocket.connect();
                } catch (IOException e) {
                    connectionFailed();
                    // Close the socket
                    try {
                        mmSocket.close();
                    } catch (IOException e2) {
                        Log.e(TAG, "unable to close() socket during connection failure", e2);
                    }
                    /*// Start the service over to restart listening mode
                    BluetoothChatService.this.start();*/
                    return;
                }
    
                // Reset the ConnectThread because we're done
                synchronized (BluetoothChatService.this) {
                    mConnectThread = null;
                }
    
                // Start the connected thread
                connected(mmSocket, mmDevice);
            }
    
            public void cancel() {
                try {
                    mmSocket.close();
                } catch (IOException e) {
                    Log.e(TAG, "close() of connect socket failed", e);
                }
            }
        }
    
      /*********************   连接管理,通讯线程   **********************/
        private class ConnectedThread extends Thread {
            private final BluetoothSocket mmSocket;
            private final InputStream mmInStream;
            private final OutputStream mmOutStream;
    
            public ConnectedThread(BluetoothSocket socket) {
                Log.d(TAG, "create ConnectedThread");
                mmSocket = socket;
                InputStream tmpIn = null;
                OutputStream tmpOut = null;
    
                // Get the BluetoothSocket input and output streams
                try {
                    tmpIn = socket.getInputStream();
                    tmpOut = socket.getOutputStream();
                } catch (IOException e) {
                    Log.e(TAG, "temp sockets not created", e);
                }
    
                mmInStream = tmpIn;
                mmOutStream = tmpOut;
            }
    
            public void run() {
                Log.i(TAG, "BEGIN mConnectedThread");
                byte[] buffer = new byte[1024];
                int bytes;
    
                // Keep listening to the InputStream while connected
                while (true) {
                    try {
                        // Read from the InputStream
                        bytes = mmInStream.read(buffer);
    
                    } catch (IOException e) {
                        Log.e(TAG, "disconnected", e);
                        connectionLost();
                        break;
                    }
                }
            }
    
            /**
             * Write to the connected OutStream.
             * @param buffer  The bytes to write
             */
            public void write(byte[] buffer) {
                try {
                    mmOutStream.write(buffer);
    
                } catch (IOException e) {
                    Log.e(TAG, "Exception during write", e);
                }
            }
    
            public void cancel() {
                try {
                    mmSocket.close();
                } catch (IOException e) {
                    Log.e(TAG, "close() of connect socket failed", e);
                }
            }
        }
    }
    


    希望这边文章可以帮到阅读者

    顺便一提:参考的出处的时候太久远了,忘了出处,在这里给他(他)说声:不好意思。。。


    展开全文
  • 安卓手机通过蓝牙与单片机通信

    千次阅读 热门讨论 2014-04-10 16:01:24
     手机端打开编写的蓝牙通信软件,与单片机蓝牙串口模块连接,而后,手机通过蓝牙发送读数据命令到单片机单片机开始读取传感器信息,将采集到得传感器信息通过蓝牙发送到手机端,手机端软件接收到后,显示。...
  • 该程序实现了51单片机与蓝牙通信程序,并在适当地方做了注释
  • android开发之手机与单片机蓝牙模块通信

    万次阅读 多人点赞 2014-01-07 10:08:35
    之前两篇都是在说手机的连接,连接方法,和主动配对连接,都是手机手机的操作,做起来还是没问题的,但是最终的目的是与单片机蓝牙模块的通信。   下面是到目前为止尝试的与单片机通信方法,没有成功,但是...
  • android手机接收并波形图显示单片机通过蓝牙传输的传感器数据
  • 最近辛辛苦苦的终于把落下了七八个月的Android蓝牙开发搞完了,其中的痛苦不堪回首啊。感谢那些帮了大忙的老师和同学们!辛苦归辛苦,收获总是有的,...而单片机上的蓝牙模块手机蓝牙连接有点不同,它的UUID号需要
  • android物联网初步,利用手机蓝牙与单片机通信,实现led灯开关和定时
  • 1.单片机发的是ASCII码,手机这边收的是
  • 系列博文: (1)安卓手机与蓝牙模块联合调试(一)——蓝牙模块的串口...本教程的项目地址:1989Jiangtao/BluetoothSCM: 安卓手机通过蓝牙与单片机通信-发送指令/接收数据​​​​​​​ 继续承接上两篇文章,这...
  • 首先运行sudo apt-get install bluez看看bluez是不是最新的...再使用bluetoothctl工具打开蓝牙,并查询蓝牙的地址,同时可以尝试进行连接。最后别忘了要断开连接,不然用其他工具就无法再次连接蓝牙了。 bluetoothct...
  • 单片机或者在其他领域中,蓝牙的传输是比较重要的,虽然理论只有10米的范围可以传输数据,但是被许多开发者所需求,个人在开发中也是需要蓝牙传输,浏览了许多谷歌的APi文档和博客之后,决定好好写一篇关于蓝牙...
  • 系列博文: (1)安卓手机与蓝牙模块联合调试(一)——蓝牙模块的串口...本教程的项目地址:1989Jiangtao/BluetoothSCM: 安卓手机通过蓝牙与单片机通信-发送指令/接收数据​​​​​​​ 忙里偷闲,承接上一篇文...
  • 3、单片机TxD RxD+蓝牙模块RxD TxD手机蓝牙 只能收不能发 电路查了又查,单片机和app的程序改了又改,在第三点里连最简单的一个字符都收不到,前面两点进行长字符串传输毫无问题。现在求大神给个思路。 补充一下...
  • 系列博文: (1)安卓手机与蓝牙模块联合调试(一)——蓝牙模块的串口...本教程的项目地址:1989Jiangtao/BluetoothSCM: 安卓手机通过蓝牙与单片机通信-发送指令/接收数据 最近项目有需求要蓝牙,在有了一些仪器...
  • 手机是安卓系统的,蓝牙模块采用hc-06,单片机用msp430f149.具体要求是手机发数据能通过蓝牙模块传给单片机然后做出相应的反应(如控制LED的亮灭等)。
  • android 手机与单片机之间的蓝牙通信

    热门讨论 2020-07-30 23:30:25
    刚好碰到这蓝牙通信方面的项目,上网也看过其他人在蓝牙这方面写的博客,但大多都不全,给一些初触蓝牙的开发者造成一定的麻烦,自己当初也费了不少劲。所以把自己参考网上的一些资料用Android studio写的代码完全放...
  • 51单片机与蓝牙模块连接

    万次阅读 多人点赞 2018-02-22 12:17:38
    不久前开始学习使用蓝牙模块,在模块51单片机连接的过程中出现了非常多的问题,我想应该也是很多新手和我一样会遇到这样的问题,因此特地写这篇文章,想分享下在学习过程中遇到的问题以及解决方法。此次学习用到...
1 2 3 4 5 ... 20
收藏数 2,622
精华内容 1,048
关键字:

蓝牙与单片机通信