본문 바로가기
프로젝트 모음/HRI ROS Project

[Robotics][Proj 12] 우분투 & 핸드폰 블루투스로 통신

by 하람 Haram 2023. 5. 11.
728x90

앞에 포스팅 

https://aisj.tistory.com/174

 

[Robotics] Collabot 현업(9) [라즈베리파이3에 ROS 설치 (Kinetic)]

사용하는 어플이 https://appinventor.mit.edu/ MIT App Inventor An Overview of the App Inventor Sources -- Components Read about how the App Inventor sources are structured in this series of blog posts. This week we discuss the App Inventor components

aisj.tistory.com

에서 말했듯이 아래의 사이트

https://appinventor.mit.edu/

 

MIT App Inventor

An Overview of the App Inventor Sources -- Components Read about how the App Inventor sources are structured in this series of blog posts. This week we discuss the App Inventor components module. More

appinventor.mit.edu

를 통해 만든 블루투스 어플을 이용하여서 통신을 해야하는데

 

컴퓨터 - 핸드폰 통신은 불가능하다고 하니

라즈베리파이 - 핸드폰 통신으로 대체하고자 한다

 

 

사용 스펙

라즈베리파이 : Rasberrypi 3

ROS : kinetic

 

라즈베리파이 3에 kinetic 설치는 위의 블로그를 참조하자

 

 

라즈베리파이 BT/BLE (Python)을 위한 세팅

 

1. 관련 라이브러리 다운로드 

sudo apt-get install bluez libbluetooth-dev pi-bluetooth

 

2. Python 설치 & 빌드

-> 어? 내 라즈베리파이는 python이 있는데 하겠지만

파이썬 관련 유틸리티가 설치된 상태에서 파이썬을 재빌드해서 설치해야 블루투스 모듈을 사용할 수 있다고 한다

 

다운로드 받을 폴더를 임시로 만들어 준다음 

mkdir temp
cd temp

Zip파일을 다운로드 받은 후 압축해제

wget https://www.python.org/ftp/python/3.6.5/Python-3.6.5.tgz
tar -xvf Python-3.6.5.tgz

빌드를 해주자

cd Python-3.6.5
./configure
sudo make && sudo make install

3. 시리얼 포트 등록

sudo sdptool add SP

 

4. bluetooth.service 수정

 

sudo nano /lib/systemd/system/bluetooth.service
ExecStart=/usr/libexec/bluetooth/bluetoothd   에서
ExecStart=/usr/libexec/bluetooth/bluetoothd -C 로 바꿔주기

설정 수정사항 저장

sudo systemctl daemon-reload

블루투스 서비스 재실행

sudo systemctl restart bluetooth

재부팅 시 서비스 자동 등록

sudo systemctl enable bluetooth
Synchronizing state of bluetooth.service with SysV service script with /lib/systemd/systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install enable bluetooth

 

5. 장치 내 블루투스를 Discoverable 상태로 변경

 

 

 

sudo hciconfig hci0 piscan

 

추가로 아래의 코드로 bluetooth가 연결되는지 확인할 수 있다

hciconfig

 

이렇게 하면 스마트 폰에서 다음과 같이 

raspberrypi가 블루투스 검색이 된다

 

 

6. pybluez 모듈 설치

sudo pip3 install pybluez pybleno

본인의 경우 다음과 같은 오류가 나왔는데

Could not find a version that satisfies the requirement pybluez

이거는 파이썬 버전하고 pip3 버전이 맞지 않아서 이다

python -V
>>Python 3.9.2

pip --version
>>pip 20.3.4 from /usr/lib/python3/dist-packages/pip (python 3.9)

pip3 --version
>>pip 9.0.3 from /usr/local/lib/python3.6/sites-packages (python 3.6)

그래서 버전과 맞는 pip로 다운로드 받았다

sudo pip install pybluez pybleno

그러면 위에서 왜 3.6을 다시 받은거지...

찝찝하지만 넘어가고

 

 

다음 명령어로 블루투스 쉘로 접속할 수 있다

sudo bluetoothctl

쉘 모드에서 관련 명령어 들은 

show
scan on
scan off
Discovery stopped
Discovery started
agent NoInputNoOutput  ->연결 잘 안될때 해보기
pair xx:xx:xx:xx:xx:xx
connect xx:xx:xx:xx:xx:xx
disconnect xx:xx:xx:xx:xx:xx
quit

 

밑에 블로그를 참고하자

https://webnautes.tistory.com/979

 

Arduino UNO와 Raspberry PI 3간 Bluetooth 통신 테스트

HC-05를 연결한 Arduino UNO와 Raspberry PI 3간 통신 테스트를 진행했습니다. 1. bluetoothctl 명령을 사용하여 페어링하는 방법 2. LED 제어 테스트 1. bluetoothctl 명령을 사용하여 페어링하는 방법라즈베리파

webnautes.tistory.com

페어링을 한후

trust <맥 주소>

혹시 모르니 Trust 해주고

다시 파이썬 코드

from bluetooth import *

#########################
## Scan
##########################

target_name = "Galaxy S8+" #target device name
target_address = "94:8B:C1:01:E2:71"
port = 6 #RFCOMM port

nearby_devices = discover_devices()

for bdaddr in nearby_devices:
    print(lookup_name(bdaddr))
    if target_name == lookup_name(bdaddr):
        target_address = bdaddr
        print("Update target address : ", target_address)
        break

if target_address is not None:
    print("Device found.")
else:
    print("Could not find target bluetooth device nearby")

####################
## Connect
####################

try:
    print("Try to connect Bluetooth socket")
    sock = BluetoothSocket(RFCOMM)
    print("RFCOMM : " ,RFCOMM)
    sock.connect((target_address,port))
    print("Success to connect target_address : ",target_address,"port : ", port)



    while True:
        try:
            recv_data = sock.recv(1024)


            #receive Data: bytes type so we need to Encode/Decode when using with string
            '''example
            example of Encoding : my_bytes = b"Hello world"
            example of Decoding : my_str = my_bytes.decode('utf-8')
                                  my_str = str(bytes, 'utf-8')
            '''
            print('bytes receive : ' ,recv_data)
            print('encode receive : ' ,recv_data.decode('utf-8'))


            #msg = recv_data.decode()[:-2]
            #print("Received : %s" % msg)
        
        except KeyboardInterrupt:
            print("disconnected")
            sock.close()
            print("all done")

except btcommon.BluetoothError as err :
    print("An error occured : %s" %err)
    sock.close()
    pass

하면

device found까지는 뜨는데

[Errno 111] Connection refused

가 나온다

 

나의 경우 Port 번호를 1로 했다가 생기는 오류였으므로 port 번호가 뭔지 확인 해본다

netstat -ntlp

이러면  tcp 6 막 이런식으로 나온다면 port 번호는 6 이다

 

 

 

참고 사이트

https://fishpoint.tistory.com/3430

 

라즈베리파이에서 파이썬 BT/BLE 프로그래밍

라즈베리파이에서 파이썬 BT/BLE 프로그래밍을 위한 라이브러리 설치와 동작확인하는 과정 정리 Bluetooth 기능을 내장한 라즈베리파이3 B 모델 – 블루투스 제어용 Python 라이브러리 사용법입니다.

fishpoint.tistory.com

 

728x90