使用树莓派+舵机+pca9685+usb摄像头制作二维云台,图像追踪
为什么使用pca9685驱动舵机,而不使用树莓派自带的引脚驱动舵机呢?
因为树莓派无法产生稳定的pwm波,容易造成舵机的抖动
我使用的是树莓派+ubuntu系统+pca9685
1.首先在ubuntu系统中安装相关依赖
sudo apt install whiptail parted lua5.1 alsa-utils psmisc
2.下载安装包
wget http://mirrors.ustc.edu.cn/archive.raspberrypi.org/debian/pool/main/r/raspi-config/raspi-config_20200601_all.deb
3.安装rasp-config
sudo dpkg -i raspi-config_20200601_all.deb
4.启用rasp-config
sudo raspi-config
5.打开IIC
6.安装PCA9685的库
下载依赖库
sudo apt-get install git build-essential python-dev
从github下载源码(这一步如果下载失败,可以直接复制链接到GitHub下载,然后移到工作空间下)
git clone https://github.com/adafruit/Adafruit_Python_PCA9685.git
安装库
cd Adafruit_Python_PCA9685
sudo python setup.py install
测试是否接好线
sudo apt-get install i2c-tools
sudo i2cdetect -y 1
测试舵机
python3 ~/Adafruit_Python_PCA9685/examples/simpletest.py
然后进行下面的图像追踪
import cv2
import time
import numpy as np
from threading import Thread
from pid import PID
import Adafruit_PCA9685
# 初始化PCA9685
pwm = Adafruit_PCA9685.PCA9685()
pwm.set_pwm_freq(60)
# 舵机的极限位置
servo_min = 150 # 最小脉冲长度
servo_max = 600 # 最大脉冲长度
# 初始化伺服电机
panChannel = 0
tiltChannel = 1
panAngle = 90 # 中心位置
tiltAngle = 90 # 中心位置
def set_servo_angle(channel, angle):
pulse = (servo_min + (servo_max - servo_min) * angle / 180)
pwm.set_pwm(channel, 0, int(pulse))
set_servo_angle(panChannel, panAngle)
set_servo_angle(tiltChannel, tiltAngle)
# 定义视频流类
class VideoStream:
def __init__(self, src=0):
self.stream = cv2.VideoCapture(src)
self.stream.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
self.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)
self.stream.set(cv2.CAP_PROP_FPS, 30)
self.grabbed, self.frame = self.stream.read()
self