通过Android studio编写app,实现通过手机蓝牙控制arduino上的LED的亮灭

通过Android studio编写app,实现通过手机蓝牙控制arduino上的LED的亮灭

(一)Android studio代码部分
(1)MainActivity代码
package com.example.lx.lanya;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.UUID;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private BluetoothAdapter mBluetoothAdapter;
private OutputStream mOutputStream;
private ArrayList mDevices = new ArrayList<>();

private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            mDevices.add(device);
            mAdapter.notifyDataSetChanged();
            System.out.println("device name" + device.getName());
        } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
            Toast.makeText(getApplicationContext(), "开始扫描", Toast.LENGTH_SHORT).show();
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            Toast.makeText(getApplicationContext(), "扫描结束", Toast.LENGTH_SHORT).show();
        }
    }
};
private DeviceAdapter mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    ListView mListView;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mListView = findViewById(R.id.lv);
    mAdapter = new DeviceAdapter(getApplicationContext(), mDevices);
    mListView.setAdapter(mAdapter);
    mListView.setOnItemClickListener(this);
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(mBluetoothReceiver, filter);
}

public void clickBtn(View v) {
    switch (v.getId()) {
        case R.id.button1:

            if (!mBluetoothAdapter.isEnabled()) {

                mBluetoothAdapter.enable();
            }
            break;
        case R.id.button2:

            if (mBluetoothAdapter.isEnabled()) {
                mBluetoothAdapter.disable();
            }
            break;
        case R.id.button3:
            mDevices.clear();
            mAdapter.notifyDataSetChanged();
            mBluetoothAdapter.startDiscovery();
            break;
        case R.id.button4:
            mBluetoothAdapter.cancelDiscovery();
            break;
        case R.id.button5:
            sendCtrl(0);
            break;
        case R.id.button6:
            sendCtrl(1);
            break;

        default:
            break;
    }
}

private void sendCtrl(int i) {
    String str = "0xaaaaaa";
    String stc = "0xbbbbbb";
    try {
        byte[] bs;
        if (i == 0) {
            bs = hexString2Bytes(str);
        } else {
            bs = hexString2Bytes(stc);
        }
        mOutputStream.write(bs);
        System.out.print(bs);
    } catch (Exception e) {
        e.printStackTrace();
    }
}


@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(mBluetoothReceiver);
}

@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
    BluetoothDevice device = mDevices.get(position);
    conn(device);
}

private void conn(final BluetoothDevice device) {
    //建立蓝牙连接是耗时操作,类似TCP Socket,需要放在子线程里面
    new Thread() {
        public void run() {
            try {
                //获取BluetoothSocket,UUID需要和蓝牙服务端保持一致
                BluetoothSocket bluetoothSocket = device.createRfcommSocketToServiceRecord(UUID
                        .fromString("00001101-0000-1000-8000-00805F9B34FB"));
                // 和蓝牙服务端建立连接
                bluetoothSocket.connect();
                // 获取输出流,往蓝牙服务端写指令信息
                mOutputStream = bluetoothSocket.getOutputStream();
                // 提示用户
                runOnUiThread(new Runnable() {
                    public void run() {
                        System.out.println("连接成功");
                        Toast.makeText(getApplicationContext(), "连接成功", Toast.LENGTH_SHORT)
                                .show();
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.start();
}

public static byte[] hexString2Bytes(String hex) {

    if ((hex == null) || (hex.equals(""))) {
        return null;
    } else if (hex.length() % 2 != 0) {
        return null;
    } else {
        hex = hex.toUpperCase();
        //int len = hex.length()/2;
        byte[] b = new byte[]{};
        char[] hc = hex.toCharArray();
        b=getBytes(hc);
    }

}


    public static byte[] getBytes(char[] chars) {
        Charset cs = Charset.forName("UTF-8");
        CharBuffer cb = CharBuffer.allocate(chars.length);
        cb.put(chars);
        cb.flip();
        ByteBuffer bb = cs.encode(cb);
        return bb.array();
}

}
(2)DeviceAdapter部分
package com.example.lx.lanya;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;

public class DeviceAdapter extends BaseAdapter {
private ArrayList mDevices;
private Context mContext;

 DeviceAdapter(Context context, ArrayList devices) {
    mDevices = devices;
    mContext = context;
}

@Override
public int getCount() {
    return mDevices.size();
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if(convertView == null) {
        convertView = View.inflate(mContext, R.layout.item, null);
        holder = new ViewHolder();
        holder.mTvName = convertView.findViewById(R.id.tv_name);
        holder.mTvAddress =  convertView.findViewById(R.id.tv_address);
        convertView.setTag(holder);
    }else {
        holder = (ViewHolder) convertView.getTag();
    }
    BluetoothDevice device = mDevices.get(position);
    holder.mTvName.setText(device.getName());
    holder.mTvAddress.setText(device.getAddress());
    return convertView;
}

class ViewHolder {
    TextView mTvName;
    TextView mTvAddress;
}

}
(3)Activity_main部分

                                                                                                                                            

`
(4)item.xml部分

                                                                                                                                





(5)string.xml部分

蓝牙
打开蓝牙
关闭蓝牙
开始扫描
结束扫描
开灯
关灯

(6)AndroidMainfirst部分






    
        
            

            
        
    


(二)Arduino部分
使用hc05蓝牙模块,以及MEGA2560
(1)使用下载器与hc05连接设置蓝牙名字和密码,以及工作方式
参考连接https://blog.csdn.net/weixin_37272286/article/details/78016497?locationNum=10&fps=1
(2)arduino与蓝牙以及LED连接方法
RX接TX1
TX接RX1
VCC接5V
GAD接GND
13脚接LED正极
LE负极接GND
(3)arduino程序
byte val;
void setup() {
// put your setup code here, to run once:
Serial.begin(38400);
Serial1.begin(38400);
pinMode(13,OUTPUT);
}

void loop() {
// put your main code here, to run repeatedly:
while(Serial1.available()>0)
{
int i;
val=Serial1.read();
Serial.println(val);
if(val==65){
digitalWrite(13,HIGH);
Serial.println(val);
}
if(val==66){
digitalWrite(13,LOW);
Serial.println(val);
}
}
}
然后即可实现LED的亮灭

你可能感兴趣的:(Blutooth)