THRESHOLD = (10, 56, 7, 31, -64, 4) # Grayscale threshold for dark things...
#THRESHOLD = (0, 39, -15, 29, -18, 9)
import sensor, image, time
from pyb import LED
from pyb import Servo
from pid import PID
rho_pid = PID(p=0.8, i=0.001) # y=ax+b b截距
theta_pid = PID(p=1.5, i=0.01)# a斜率
LED(1).on()
LED(2).on()
LED(3).on()
pan_servo=Servo(1) # 控制转向舵机, 它在循环里面转动角度的值不能给-90到90
s2 = Servo(2)
s3 = Servo(3)
pan_servo.calibration(500,2500,500)
# pan_pid = PID(p=0.07, i=0, imax=90)
sensor.reset()
# 设置镜像
sensor.set_vflip(True) # 垂直翻转
sensor.set_hmirror(True) # 水平翻转
#
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QQQVGA) # 80x60 (4,800 pixels) - O(N^2) max = 2,3040,000.
#sensor.set_windowing([0,20,80,40])
sensor.skip_frames(time = 2000) # WARNING: If you use QQVGA it may take seconds
sensor.set_auto_gain(False)
sensor.set_auto_whitebal(False)
clock = time.clock() # to process a frame sometimes.
# 锁定云台的两个舵机的角度
s2.angle(-15)
s3.angle(75)
# 云台的舵机转动角度能正常给值-90到90,但控制转向的servo(3)只能给0到180度
while(1):
clock.tick()
print('舵机实际角度',pan_servo.angle())
img = sensor.snapshot().binary([THRESHOLD])
line = img.get_regression([(100,100)], robust = True)
if (line):
rho_err = abs(line.rho())-img.width()/2 #计算得到的直线与中央点的偏移
if line.theta()>90:
theta_err = line.theta()-180 # 角度的偏移-90 0 +90
else:
theta_err = line.theta()
img.draw_line(line.line(), color = 127)
# print(rho_err,line.magnitude(),rho_err)
# print('效果',line.magnitude())
if line.magnitude()>8: # magnitude值越大,线性回归效果越好
#if -40<b_err<40 and -30<t_err<30:
rho_output = rho_pid.get_pid(rho_err,1)
theta_output = theta_pid.get_pid(theta_err,1)
print('rho', rho_output)
print('theta', theta_output)
output = rho_output+theta_output
print('pid_out', output)
output = output + 90
if output > 140:
output = 140
elif output < 40:
output = 40
print('final_out', output)
pan_servo.angle(output)
else:
pan_servo.angle(90)
else:
pan_servo.angle(90)
pass
#print(clock.fps())
6
6vxd 发布的帖子
-
控制转向的servo(3)只能给0到180度,但把servo(3)拿出来不放在循环里面又正常能给到-90到90的转动角度