본문 바로가기

졸업프로젝트

아두이노 안드로이드 블루투스 통신 참고 블로그

더보기

접힌 글은 아두이노 회로 구성에 도움이 된 블로그들, 아두이노와 안드로이드의 블루투스 통신을 위해 참고하였으나 내가 제대로 적용하지 못한 블로그들 목록이다.

https://blog.naver.com/PostView.nhn?blogId=eduino&logNo=221121406317

 

[아두이노 강좌] 블루투스 모듈 HC-06 사용법 알아보기

 안녕하세요 에듀이노 입니다. 오늘은 블루투스 모듈 HC-06에 대해 알아보겠습니다. 1. 블루투스 H...

blog.naver.com

ㄴ 블루투스모듈

https://arduinosensors.tistory.com/entry/SEN0193-%ED%86%A0%EC%96%91-%EC%88%98%EB%B6%84%EC%84%BC%EC%84%9C-LCD1602-I2C

 

SEN0193 아두이노 토양 수분센서 (LCD16X2 I2C)

본 절은 [SEN0193] 아두이노 센서를 사용하기 위해 알아야 할 내용과 실습 방법에 대해 설명한다. 아두이노 센서의 특징, 동작원리, 사양, 연결 핀 배열, 출력 값, 주의사항을 알아본다. 아두이노와

arduinosensors.tistory.com

https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=zero_kjy&logNo=220808997014 

 

45. I2C LCD16X2 제어

I2C LCD16X2  제어 : 예전에 LCD 16X2를 제어할때는 많은 핀을 이용해서 제어했지만, ...

m.blog.naver.com

https://ddangeun.tistory.com/59

 

[안드로이드] 아두이노와 안드로이드 Bluetooth 통신하기

안드로이드 기기와 아두이노 보드간 블루투스 통신 코드를 소개하겠습니다. 아두이노는 블루투스 통신을 위해 HC-06을 사용하였습니다. 먼저 bluetooth 통신을 위해 connect 버튼을 누르면 버튼이벤

ddangeun.tistory.com

그리고 내가 적용에 성공한 깃헙이 바로

https://github.com/The-Frugal-Engineer/ArduinoBTExamplev3

 

GitHub - The-Frugal-Engineer/ArduinoBTExamplev3: ArduinoBTExamplev3

ArduinoBTExamplev3. Contribute to The-Frugal-Engineer/ArduinoBTExamplev3 development by creating an account on GitHub.

github.com

여기다. 

클래스 수가 많지 않아 따라하기 쉬울 것이다.

 

다만, 나는 Activity가 아니라 RecyclerViewAdapter에서 블루투스 통신을 해야 했기 때문에 따로 클래스를 만들었다.

메인 액티비티에 붙어있는 프라그먼트의 리사이클러뷰의 텍스트뷰 값을 바꿔줘야 해서 저렇게 됐다.

위의 깃헙주소의 MainActivity에 쓰이는 코드를 이 클래스에 넣어줬다.

위의 깃헙에는 없는 코드가 있는데 그건 위의 블로그들 중 하나에서 참고한 것이다.

깃헙주소 주인은 아두이노의 블루투스 모듈로 hc-05를 썼는데, 나는 hc-06을 썼다.

그래도 잘 돌아가는 것 같다.

↓ (BluetoothConnector 클래스)

더보기
import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat.getSystemService
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import oasis.team.econg.graduationproject.MainActivity
import java.util.*


class BluetoothConnector(context: Context, textView: TextView) {
    val TAG = "BLUETOOTH"
    var main = context as MainActivity
    val REQUEST_ALL_PERMISSION = 1
    var results: IntArray = IntArray(2)
    private val REQUEST_ENABLE_BT = 1
    private val ERROR_READ = 0
    val dataView = textView
    var arduinoBTModule : BluetoothDevice? = null
    var arduinoUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
    //val dataView = textView
    val permissions = arrayOf(Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_ADMIN)
    var bluetoothManager: BluetoothManager? = getSystemService(main, BluetoothManager::class.java)
    var bluetoothAdapter: BluetoothAdapter? = bluetoothManager?.adapter
    var handler = object: Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when(msg.what){
                ERROR_READ ->
                    dataView.text = msg.obj.toString()
            }
        }
    }

    val connectToBTObservable: Observable<String> = Observable.create { emitter ->
        Log.d(TAG, "Calling connectThread class")
        //Call the constructor of the ConnectThread class
        //Passing the Arguments: an Object that represents the BT device,
        // the UUID and then the handler to update the UI
        val connectThread = ConnectThread(arduinoBTModule!!, arduinoUUID, handler)
        connectThread.run()
        //Check if Socket connected
        if (connectThread.getMmSocket()!!.isConnected) {
            Log.d(TAG, "Calling ConnectedThread class")
            //The pass the Open socket as arguments to call the constructor of ConnectedThread
            val connectedThread =
                ConnectedThread(connectThread.getMmSocket()!!)
            connectedThread.run()
            if (connectedThread.getValueRead() != null) {
                // If we have read a value from the Arduino
                // we call the onNext() function
                //This value will be observed by the observer
                emitter.onNext(connectedThread.getValueRead()!!)
            }
            //We just want to stream 1 value, so we close the BT stream
            connectedThread.cancel()
        }
        // SystemClock.sleep(5000); // simulate delay
        //Then we close the socket connection
        connectThread.cancel()
        //We could Override the onComplete function
        emitter.onComplete()
    }

    fun hasPermissions(): Boolean {
        for (permission in permissions) {
            if (main.let { ActivityCompat.checkSelfPermission(it, permission) }
                != PackageManager.PERMISSION_GRANTED
            ) {
                return false
            }
        }
        return true
    }

    fun isBluetoothEnabled():Boolean{
        return if (!bluetoothAdapter!!.isEnabled) {
            Toast.makeText(main, "Bluetooth를 활성화 해 주세요.", Toast.LENGTH_SHORT).show()
            false
        }else{
            true
        }
    }

    @SuppressLint("MissingPermission")
    fun searchDevice(){
        if (bluetoothAdapter == null) {
            // Device doesn't support Bluetooth
            Log.d(TAG, "Device doesn't support Bluetooth")
        } else {
            Log.d(TAG, "Device support Bluetooth")
            //Check BT enabled. If disabled, we ask the user to enable BT
            if (!isBluetoothEnabled()) {
                Log.d(TAG, "Bluetooth is disabled")
                val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                if (!hasPermissions()) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    Log.d(TAG, "We don't BT Permissions")
                    ActivityCompat.requestPermissions(main, permissions, REQUEST_ENABLE_BT)
                    main.onRequestPermissionsResult(REQUEST_ENABLE_BT, permissions, results)
                    Log.d(TAG, "Bluetooth is enabled now")
                } else {
                    Log.d(TAG, "We have BT Permissions")
                    main.onRequestPermissionsResult(REQUEST_ENABLE_BT, permissions, results)
                    Log.d(TAG, "Bluetooth is enabled now")
                }

            } else {
                Log.d(TAG, "Bluetooth is enabled");
            }
            var btDevicesString=""
            val pairedDevices: MutableSet<BluetoothDevice>? = bluetoothAdapter?.bondedDevices

            if (pairedDevices!!.size > 0) {
                // There are paired devices. Get the name and address of each paired device.
                for (device: BluetoothDevice in pairedDevices) {
                    var deviceName = device.name;
                    var deviceHardwareAddress = device.address; // MAC address
                    Log.d(TAG, "deviceName:$deviceName");
                    Log.d(TAG, "deviceHardwareAddress:$deviceHardwareAddress");
                    //We append all devices to a String that we will display in the UI
                    //btDevicesString=btDevicesString+deviceName+" || "+deviceHardwareAddress+"\n";
                    //If we find the HC 05 device (the Arduino BT module)
                    //We assign the device value to the Global variable BluetoothDevice
                    //We enable the button "Connect to HC 05 device"
                    if (deviceName == " MySensor") {
                        Log.d(TAG, "MySensor found");
                        arduinoUUID = device.uuids[0].uuid
                        arduinoBTModule = device
                        connectToDevice()
                        break
                        //HC -05 Found, enabling the button to read results
                        //connectToDevice.setEnabled(true);
                    }
                    //dataView.text = btDevicesString;
                }
            }
        }
        Log.d(TAG, "Button Pressed");
    }

    @SuppressLint("CheckResult")
    fun connectToDevice(){
        if (arduinoBTModule != null) {
            //We subscribe to the observable until the onComplete() is called
            //We also define control the thread management with
            // subscribeOn:  the thread in which you want to execute the action
            // observeOn: the thread in which you want to get the response
            connectToBTObservable.observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io()).subscribe { valueRead: String? ->
                    //valueRead returned by the onNext() from the Observable
                    dataView.text = valueRead
                }
        }
    }