使用树莓派进行图像处理的时候,一般需要通过串口将数据传输给主控,但由于靠杜邦线连接容易出现断连,故有时可通过板载蓝牙的方式传输信息。由于树莓派的mini串口性能差,故一般只在蓝牙传输和串口传输之间选其一,将选择的方式配置到AMA0即可。
树莓派配置串口的教程网上很多,可以参考链接
这里主要存一下引脚和示例代码
import serial
import struct
from time import sleep
A = 1
B = 2
def serialConfig(port,baud):
ser = serial.Serial(
port,
baudrate=baud,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
) # Open port with baud rate
ser.flushInput()
return ser
if __name__ == "__main__":
ser = serialConfig("/dev/ttyAMA0",9600)
if ser.isOpen() is True:
try:
while True:
pack = struct.pack('BBBB', 0xaa, A, B, 0x55)
ser.write(pack) # transmit data serially
except KeyboardInterrupt:
ser.close()
else:
print("cannot open serial")
在使用蓝牙之前先要配置安装好相应的包
sudo apt-get install libbluetooth-dev
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple/ -U pybluez
接着将HC05模块用USB-TTL模块连接电脑,使其处于配对模式,在树莓派端蓝牙处 Add New Device ,并记录下蓝牙地址
可以看到蓝牙的地址是98:da:20:02:90:60
当然地址也可以用AT指令集获取,这个之后写代码会用到
在树莓派中创建文件bt_test.py,写入以下代码
import bluetooth
bt_addr = "98:da:20:02:90:60"
port = 1
def BlueToothInit():
global sock
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((bt_addr,port)
BlueToothInit()
sock.send('1')
sock.send('2')
sock.send('3')
sock.close()
执行文件
python3 bt_test.py
可以看到HC05端接收到的数据
将蓝牙移植到opencv找圆程序中测试
#import numpy as np
import cv2 as cv
# -*- coding:utf-8 -*-
import time
import bluetooth
bt_addr = "98:da:20:02:90:60"
port = 1
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((bt_addr,port))
# 串口配置
if __name__ == "__main__":
cap = cv.VideoCapture(0)
try:
while True:
ret, frame = cap.read()
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
circles = cv.HoughCircles(
gray, cv.HOUGH_GRADIENT, 2, 100, param1=100, param2=200, minRadius=10, maxRadius=500)
if circles is not None: # 如果识别出圆
for circle in circles[0]:
# 获取圆的坐标与半径
x = int(circle[0])
y = int(circle[1])
r = int(circle[2])
cv.circle(frame, (x, y), r, (0, 0, 255), 3) # 标记圆
cv.circle(frame, (x, y), 3, (255, 255, 0), -1) # 标记圆心
text = 'x: ' + str(x) + ' y: ' + str(y)
#cv2.putText(frame, text, (10, 30), font, 1, (0, 255, 0), 2) # 显示圆心位置
#print(text)
sock.send(text)
else:
#cv2.putText(frame, 'x: None y: None', (10, 30), font, 1, (0, 255, 0), 2)
sock.send("none")
cv.imshow('frame', gray)
k = cv.waitKey(5) & 0xFF
if k == 27:
break
except KeyboardInterrupt:
sock.close()
cap.release()
cv.destroyAllWindows()
以上就是树莓派配置蓝牙的具体步骤