Beispiel #1
0
class Actuator:
    def __init__(self, actuator):
        self.servo = None
        self.stepper = None
        self.pin = actuator['pin']
        self.idle = 0
        self.active = 1
        self.speed = 0
        self.time = 0
        self.delay = 0
        self.actuator = None
        self.sensor = None
        self.trigger = 40000
        self.triggered = False

        if "idle_state" in actuator: self.idle = actuator['idle_state']
        if "active_state" in actuator: self.active = actuator['active_state']
        if "speed" in actuator: self.speed = actuator['speed']
        if "time" in actuator: self.time = actuator['time']
        if "delay" in actuator: self.delay = actuator['delay']
        if 'trigger' in actuator: self.trigger = actuator['trigger']
        if "sensor" in actuator: self.sensor = machine.ADC(actuator['sensor'])

        if not isinstance(self.pin, dict):
            if self.speed:  # Assume servo
                x = int(self.pin[1:]) + 1
                self.servo = Servo(x)

            else:
                self.actuator = machine.Pin(self.pin, machine.Pin.OUT)

        else:
            #TODO Handle Stepper motor
            pass

        self.current_state = self.idle

    def isActivated(self):
        return self.current_state == self.active

    def triggerActuator(self, value):
        try:
            if isinstance(self.pin, dict):
                print("TODO: triggerActuator handle stepper motors")
                pass

            else:
                if self.servo:
                    self.servo.angle(value, self.speed)

                else:
                    self.actuator.value(value)

        except Exception as e:
            sys.print_exception(e)

    def activate(self):
        print("Activating %s: %s" % (self.pin, self.active))
        self.triggerActuator(self.active)
        self.current_state = self.active

        if not isinstance(self.pin, dict) and not self.sensor:
            print("time: %i" % self.time)
            time.sleep_ms(self.time)

        if not self.sensor:
            self.deactivate()
            print("delay: %i" % self.delay)
            time.sleep_ms(self.delay)
        else:
            pass

    def deactivate(self):
        print("Deativating %s: %s" % (self.pin, self.idle))
        self.triggerActuator(self.idle)
        self.current_state = self.idle

    def readSensor(self):
        if self.isActivated():
            sensor_value = self.sensor.read_u16()
            self.triggered = sensor_value >= self.trigger
            print(self.sensor, self.triggered, sensor_value)

        return self.triggered
Beispiel #2
0
# Servo Control Example
# This example shows how to use your OpenMV Cam to control servos.
# Hardware : Servo, OpenMV
# connect:
#     Servo    OpenMV
#     VCC       5V
#     GND       GND
#     data1     P7
#     data2     P8

import time
from pyb import Servo, Pin

s1 = Servo(1)  # P7
s2 = Servo(2)  # P8

while (True):
    s1.angle(0)
    s2.angle(0)
    time.sleep(1000)
    s1.angle(90)
    s2.angle(90)
    time.sleep(1000)
    s1.angle(0)
    s2.angle(0)
    time.sleep(1000)
    s1.angle(-90)
    s2.angle(-90)
    time.sleep(1000)
Beispiel #3
0
f_x = (2.8 / 3.984) * 160 # 默认值
f_y = (2.8 / 2.952) * 120 # 默认值
c_x = 240 * 0.5 # 默认值(image.w * 0.5)
c_y = 160 * 0.5 # 默认值(image.h * 0.5)
def degrees(radians):
    return (180 * radians) / math.pi
while(True): #主循环
    clock.tick()
    img = sensor.snapshot() #获取图像
    #img.binary([(250, 255)], invert=False) #二值化
    #寻找AprilTag
    for tag in img.find_apriltags(fx=f_x, fy=f_y, cx=c_x, cy=c_y):
        img.draw_rectangle(tag.rect(), color = (255, 0, 0))
        img.draw_cross(tag.cx(), tag.cy(), color = (0, 255, 0))
        print_args = (tag.x_translation(), tag.y_translation(), tag.z_translation(), \
            degrees(tag.x_rotation()), degrees(tag.y_rotation()), degrees(tag.z_rotation()))
        #usb串口输出
        print("Tx: %f, Ty %f, Tz %f, Rx %f, Ry %f, Rz %f" % print_args)
        #USART3输出
        x=tag.x_translation()
        y=tag.y_translation()
        z=tag.z_translation()
        if(x>0) s1.angle(ss1+1)
        if(x<0) s1.angle(ss1-1)
        if(y>0) s2.angle(ss2+1)
        if(y<=) s2.angle(ss2-1)
        output_str="[%d,%d,%d]" % (tag.x_translation(), tag.y_translation(), tag.z_translation())
        print('you send:',output_str)
        uart.write(output_str+'\n')
    print(clock.fps())
Beispiel #4
0
# In this example we are going use Servo and Slider by reading using the ADC
# Make sure you have the Servo checkbox marked!
# Make sure you have the ADC checkbox marked!
# use the reset button to stop example

from machine import Pin
from pyb import ADC, Servo
from time import sleep_ms

# The slider is connected to pin Y4, try adjusting it
slider = ADC(Pin('Y4'))

# The pyboard has four simple servo connections
servo = Servo(1)

# calculate the basic step
STEP = 255 / 180
last = -1

print("Servo and Slider demo started..")

while True:
    pos = slider.read()

    if (pos != last):
        angle = int((pos / STEP) - 90)  # get the angle
        print("Slider position: ", pos, " Servo angle: ", angle)
        servo.angle(angle, 100)  # set servo angle
        last = pos

    sleep_ms(10)
Beispiel #5
0
from pyb import Accel, Servo
servo = Servo(1)
accel = Accel()
while 1:
    servo.angle(accel.x(), 100)
    pyb.delay(200)
Beispiel #6
0
        if blob[2] * blob[3] > max_size:
            max_blob = blob
            max_size = blob[2] * blob[3]
    return max_blob


def find_max_c(blobs):  #定义一个找最大圆的函数,输入一个圆对象列表,输出一个圆对象
    max_size = 0
    for blob in blobs:
        if blob[2] > max_size:
            max_blob = blob
            max_size = blob[2]
    return max_blob


s3.angle(s3_now)  #初始化舵机
s2.angle(s2_now)
shape = 0  #记录形状和颜色
color = 0
time.sleep(2000)
#下面是循环执行的部分
while (True):
    clock.tick()  # Track elapsed milliseconds between snapshots().
    img = sensor.snapshot().lens_corr(1.8)  #拍摄一张照片,并畸变矫正
    claps = img.find_blobs([red_threshold])  #寻找色块

    if claps:
        clap = find_max(claps)
        img.draw_cross(clap.x(),
                       clap.y(),
                       color=(0, 255, 0),
Beispiel #7
0
from pyb import Servo

servo = Servo(1)
print(servo)

servo.angle(0)
servo.angle(10, 100)

servo.speed(-10)
servo.speed(10, 100)

servo.pulse_width(1500)
print(servo.pulse_width())

servo.calibration(630, 2410, 1490, 2460, 2190)
print(servo.calibration())
Beispiel #8
0
class MyServo:

    _kp = _ki = _kd = _integrator = _imax = 0
    _last_error = _last_derivative = _last_t = 0
    _RC = 1 / (2 * pi * 20)

    def __init__(self, p=0, i=0, d=0, imax=0):
        self.pan = Servo(1)  # P7
        self.tilt = Servo(2)  # P8
        self._kp = float(p)
        self._ki = float(i)
        self._kd = float(d)
        self._imax = abs(imax)
        self._last_derivative = float('nan')
        self.corresponding_angle = 0.5  # per pixel
        self.scan_speed = 240

        self._mode_angle_map = {
            1: 0,
            2: 0,
        }

    def init(self, mode=1, tilt_angle=0):
        # self.pan.angle(self._mode_angle_map[mode])
        self.tilt.angle(tilt_angle)

    def get_pid(self, error, scaler):
        tnow = millis()
        dt = tnow - self._last_t
        output = 0
        if self._last_t == 0 or dt > 1000:
            dt = 0
            self.pid_clear()
        self._last_t = tnow
        delta_time = float(dt) / float(1000)
        output += error * self._kp
        if abs(self._kd) > 0 and dt > 0:
            if isnan(self._last_derivative):
                derivative = 0
                self._last_derivative = 0
            else:
                derivative = (error - self._last_error) / delta_time
            derivative = self._last_derivative + (
                (delta_time / (self._RC + delta_time)) *
                (derivative - self._last_derivative))
            self._last_error = error
            self._last_derivative = derivative
            output += self._kd * derivative
        output *= scaler
        if abs(self._ki) > 0 and dt > 0:
            self._integrator += (error * self._ki) * scaler * delta_time
            if self._integrator < -self._imax:
                self._integrator = -self._imax
            elif self._integrator > self._imax:
                self._integrator = self._imax
            output += self._integrator
        return output

    def pid_clear(self):
        self._integrator = 0
        self._last_derivative = float('nan')

    def rotate_steering_gear(self, delta_pixel):
        delta_pixel = -delta_pixel
        pan_output = self.get_pid(delta_pixel, 1) / 2
        self.pan.angle(self.pan.angle() + pan_output)
        return self.pan.angle()

    def scan(self, count):
        parity = 0
        if count % 2 == 0:
            if parity == 1:
                self.pid_clear()
            parity = 0
            self.rotate_steering_gear(self.scan_speed)
        elif count % 2 == 1:
            if parity == 0:
                self.pid_clear()
            parity = 1
            self.rotate_steering_gear(-self.scan_speed)
        return self.pan.angle()
Beispiel #9
0
from pyb import ADC, Pin, Servo
adc = ADC(Pin('X1'))
servo = Servo(2)
while 1:
    if adc.read() < 2840 and adc.read() > 2810:
        servo.angle(-90, 1000)
    if adc.read() > 2840 and adc.read() < 2860:
        servo.angle(0, 1000)
    if adc.read() > 2860:
        servo.angle(90, 1000)
Beispiel #10
0
    if blobs:
        max_blob = find_max(blobs)
        # pan_error = max_blob.cx()-img.width()/2
        #tilt_error = max_blob.cy()-img.height()/2
        pan_error = max_blob.cx() - 97
        tilt_error = max_blob.cy() - 97
        print("pan_error: ", pan_error)
        print("tilt_error: ", tilt_error)
        print(max_blob.cx(), max_blob.cy())
        img.draw_rectangle(max_blob.rect())  # rect
        img.draw_cross(max_blob.cx(), max_blob.cy())  # cx, cy
        img.draw_cross(97, 97)
        pan_output = pan_pid.get_pid(pan_error, 1)
        tilt_output = tilt_pid.get_pid(tilt_error, 1)
        print("pan_output", pan_output)
        #pan_servo.angle(-pan_output)
        #pan_servo.angle(pan_servo.angle()+pan_output)
        #tilt_servo.angle(tilt_servo.angle()-tilt_output)
        if pan_output < -40:
            pan_output = -40
        elif pan_output > 40:
            pan_output = 40

        if tilt_output < -40:
            tilt_output = -40
        if tilt_output > 40:
            tilt_output = 40

        pan_servo.angle(-pan_output - 1)
        tilt_servo.angle(-tilt_output - 3)
Beispiel #11
0
from pyb import Pin, Timer, ExtInt, UART, Servo, ADC
import time
import math
vd = ADC(Pin(Pin.cpu.A2))
servo = Servo(4)
servo.angle(45)
in11 = Pin(Pin.cpu.C4, Pin.OUT)
in12 = Pin(Pin.cpu.A4, Pin.OUT)
p1 = Pin(Pin.cpu.B3)
t2 = Timer(2, freq=1000)
t2c2 = t2.channel(2, Timer.PWM, pin=p1)
t2c2.pulse_width_percent(20)
in21 = Pin(Pin.cpu.B9, Pin.OUT)
in22 = Pin(Pin.cpu.B0, Pin.OUT)
p2 = Pin(Pin.cpu.B15)  # A1 has TIM5, CH1
t8 = Timer(8, freq=1000)
t8c3 = t8.channel(3, Timer.PWM, pin=p2)
t8c3.pulse_width_percent(20)
lv = 0
rv = 0
d = 20
f2b = 0
servo_center = servo_curr = 45

def back():
    global f2b
    in11.value(1)
    in12.value(0)
    in21.value(0)
    in22.value(1)
Beispiel #12
0
from pyb import Servo

s1 = Servo(1) 			# servo подключена к контакту X1
s1.angle(45) 			# повернуть servo на 45 градусов
s1.angle(-60, 1500) 	# поворачивать серво на -60 градусов в течении 1500 милисекунд
            if kpts1:
                img.draw_keypoints(kpts1)
                time.sleep(100)
                return kpts1


# FPS clock
clock = time.clock()

kpts1 = find_face()

while (True):
    clock.tick()
    img = sensor.snapshot()
    try:
        kpts2 = img.find_keypoints(threshold=32, normalized=False)
    except:
        continue

    if (kpts2 == None):
        continue

    c = img.match_keypoints(kpts1, kpts2, 70)
    if (c):
        l = 10
        img.draw_line((c[0] - l, c[1], c[0] + l, c[1]))
        img.draw_line((c[0], c[1] - l, c[0], c[1] + l))
        s1.angle(c[0], 500)
        time.sleep(20)
    print(clock.fps())
Beispiel #14
0
# main.py -- put your code here!
from pyb import Servo
while 1:
    s=Servo(1)
    s.angle(30,500)
    pyb.delay(1500)
    s.angle(-30,500)
    pyb.delay(1500)
    s.angle(60,500)
    pyb.delay(1500)
    s.angle(-60,500)
    pyb.delay(1500)
    s.angle(90,500)
    pyb.delay(1500)
    s.angle(-30,500)
    pyb.delay(1500)
    s.angle(135,500)
    pyb.delay(1500)
Beispiel #15
0
print("- (s)ervo")
print("- (m)otor")

servo = Servo(1)
motors = RCmotors(0)

motors.speed(0)

test_name = input("test to run: ")


if test_name == "s":
    while True:
        value = input("> ")
        if value == 'r':
            servo.angle(-12)
        elif value == 'l':
            servo.angle(14)
        elif value == 'f':
            servo.angle(2)
        else:
            try:
                servo.angle(int(value))
            except ValueError:
                pass
elif test_name == "m":
    while True:
        value = input("> ")
        if value == 'f':
            motors.speed(100)
        elif value == 'b':
Beispiel #16
0

ext = ExtInt(Pin('P9'), ExtInt.IRQ_FALLING, Pin.PULL_UP, key)  #下降沿触发,打开上拉电阻

##############################################
#  OLED初始显示
##############################################
oled.fill(0)  # 清屏显示黑色背景
oled.text('01Studio', 0, 0)  # 首行显示01Studio
oled.text('Servo-180', 0, 15)  # 次行显示实验名称
oled.text(str(angle[i]), 0, 35)  # 显示当前角度
oled.text('Pls Press USER', 0, 55)  #提示按按键
oled.show()

#X1指定角度,启动时i=0,默认-90°
s1.angle(angle[i])

while True:

    if key_node == 1:  #按键被按下
        i = i + 1
        if i == 5:
            i = 0
        key_node = 0  #清空按键标志位

        #X1指定角度
        s1.angle(angle[i])

        #显示当前频率
        oled.fill(0)  # 清屏显示黑色背景
        oled.text('01Studio', 0, 0)  # 首行显示01Studio
Beispiel #17
0
class car(object):
    def __init__(self):
        self.vd = ADC(Pin(Pin.cpu.A2))
        self.servo = Servo(4)
        self.curr_angle = self.center_angle = 48
        self.f2b = 0
        self.r1 = Pin(Pin.cpu.C4, Pin.OUT)
        self.r2 = Pin(Pin.cpu.A4, Pin.OUT)
        self.t2 = Timer(2, freq=1000)
        self.l = self.t2.channel(2, Timer.PWM, pin=Pin(Pin.cpu.B3))
        self.l1 = Pin(Pin.cpu.B9, Pin.OUT)
        self.l2 = Pin(Pin.cpu.B0, Pin.OUT)
        self.t8 = Timer(8, freq=1000)
        self.r = self.t8.channel(3, Timer.PWM_INVERTED, pin=Pin(Pin.cpu.B15))
        self.lv = 0
        self.rv = 0
        self.v = 25
        self.countR = self.countL = 0
        self.turn(self.center_angle)
        self.dinit_encoder()
        self.init_encoder()

    def turn(self, angle):
        if angle < 3:
            angle = 3
        if angle > 93:
            anlge = 93
        self.servo.angle(angle)
        self.curr_angle = angle
        self.run()

    def bak(self):
        self.r1.value(0), self.r2.value(1)
        self.l1.value(1), self.l2.value(0)
        self.f2b = 1
        self.run()

    def fwd(self):
        self.r1.value(1), self.r2.value(0)
        self.l1.value(0), self.l2.value(1)
        self.f2b = -1
        self.run()

    def stp(self):
        self.r1.value(1), self.r2.value(1)
        self.l1.value(1), self.l2.value(1)
        self.f2b = 0
        self.run()

    def run(self):
        self.turn_angle = self.curr_angle - self.center_angle
        if self.v > 68:
            self.v = 68
        if self.v < 38:
            self.v = 38
        self.lv = int(
            self.v *
            (1 - self.f2b *
             (140 / 2 / 152) * math.tan(math.pi * self.turn_angle / 180)))
        self.rv = int(
            self.v *
            (1 + self.f2b *
             (140 / 2 / 152) * math.tan(math.pi * self.turn_angle / 180)))
        self.r.pulse_width_percent(self.lv)
        self.l.pulse_width_percent(self.rv)

    def allvd(self):
        return self.vd.read() * 0.003316877506942302

    def callbackR(self, p):
        self.countR = self.countR + 1

    def callbackL(self, p):
        self.countL = self.countL + 1

    def add(self):
        self.v += 5
        if self.v > 95:
            self.v = 95

        self.run()

    def dec(self):
        self.v -= 5
        if self.v < 38:
            self.v = 38
        self.run()

    def init_encoder(self):
        ExtInt(Pin.cpu.A1,
               ExtInt.IRQ_RISING_FALLING,
               Pin.PULL_UP,
               callback=lambda t: self.callbackR(t))
        ExtInt(Pin.cpu.A0,
               ExtInt.IRQ_RISING_FALLING,
               Pin.PULL_UP,
               callback=lambda t: self.callbackR(t))
        ExtInt(Pin.cpu.B8,
               ExtInt.IRQ_RISING_FALLING,
               Pin.PULL_UP,
               callback=lambda t: self.callbackL(t))
        ExtInt(Pin.cpu.C7,
               ExtInt.IRQ_RISING_FALLING,
               Pin.PULL_UP,
               callback=lambda t: self.callbackL(t))

    def dinit_encoder(self):
        ExtInt(Pin.cpu.A1,
               ExtInt.IRQ_RISING_FALLING,
               Pin.PULL_UP,
               callback=None)
        ExtInt(Pin.cpu.A0,
               ExtInt.IRQ_RISING_FALLING,
               Pin.PULL_UP,
               callback=None)
        ExtInt(Pin.cpu.B8,
               ExtInt.IRQ_RISING_FALLING,
               Pin.PULL_UP,
               callback=None)
        ExtInt(Pin.cpu.C7,
               ExtInt.IRQ_RISING_FALLING,
               Pin.PULL_UP,
               callback=None)
Beispiel #18
0
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time=2000)
sensor.set_auto_gain(False)  # Must be turned off for color tracking
sensor.set_auto_whitebal(False)  # Must be turned off for color tracking
clock = time.clock()

# Only blobs that with more pixels than "pixel_threshold" and more area than "area_threshold" are
# returned by "find_blobs" below. Change "pixels_threshold" and "area_threshold" if you change the
# camera resolution. Don't set "merge=True" becuase that will merge blobs which we don't want here.

####################################################################
# Servo initialization and calibration here

pan = Servo(1)  # use PWM on P7, s2 on shield
pan.calibration(540, 2400, 540, 1400, 1500)
pan.angle(90)

tilt = Servo(2)  # use PWM on P8, s1 on shield
tilt.calibration(540, 2400, 1200, 1800, 1500)
tilt.angle(90)

delay(1000)  # delay to give servos time to get to 90 & 90
#####################################################################

#####################################################################
# DC Motor pin setup

LEFT_MOTOR1 = Pin('P0', Pin.OUT_PP, Pin.PULL_NONE)
LEFT_MOTOR2 = Pin('P1', Pin.OUT_PP, Pin.PULL_NONE)
LEFT_ENABLE = Pin('P2', Pin.OUT_PP, Pin.PULL_NONE)  # HI -> ON;  LOW -> OFF
Beispiel #19
0
     print("X: ", max_blob[0])
     print("Y: ", max_blob[1])
     pan_error = max_blob[0] - img.width() / 2
     tilt_error = max_blob[1] - img.height() / 2
     print("pan_error: ", pan_error)
     print("tilt_error: ", tilt_error)
     img.draw_circle(max_blob.x(),
                     max_blob.y(),
                     max_blob.r(),
                     color=(255, 0, 0))  #画出圆
     img.draw_cross(int(max_blob[0]), int(max_blob[1]))  #画出圆心
     pan_output = pan_pid.get_pid(pan_error, 1)
     tilt_output = tilt_pid.get_pid(tilt_error, 1)
     print("pan_output", pan_output)
     print("tilt_output", tilt_output)
     print("pan_output_angle", pan_servo.angle())
     print("tile_output_angle", tilt_servo.angle())
     print("r=", max_blob.r())
     if abs(pan_error) > 5 and abs(tilt_error) > 5:  #误差过小时停止调整
         pan_servo.angle(pan_servo.angle() - pan_output)
         tilt_servo.angle(tilt_servo.angle() + tilt_output)
     if abs(pan_error) <= 5 and abs(tilt_error) > 5:
         tilt_servo.angle(tilt_servo.angle() + tilt_output)
     if abs(pan_error) > 5 and abs(tilt_error) <= 5:
         pan_servo.angle(pan_servo.angle() - pan_output)
     if abs(pan_error) <= 5 and abs(tilt_error) <= 5:
         continue
 else:
     counter += 1
     if counter == 10:
         counter = 0
Beispiel #20
0
import sensor, image, time
from pyb import Pin
from pyb import Servo

tile_servo = Servo(1)  #上
pan_servo = Servo(2)  #下
pan_servo.angle(-2)
pan_servo.angle(0)
s = Pin('P5', Pin.IN, Pin.PULL_DOWN)
s_8 = Pin('P1', Pin.OUT_PP)
s_4 = Pin('P2', Pin.OUT_PP)
s_2 = Pin('P3', Pin.OUT_PP)
s_1 = Pin('P4', Pin.OUT_PP)

red_threshold = (18, 55, 23, 90, -3, 80)
k = 2479
list_num = []
data = 0
i = 0
fire = 0
num = 0
sensor.reset()  # Initialize the camera sensor.
sensor.set_pixformat(sensor.RGB565)  # use RGB565.
sensor.set_framesize(sensor.QQVGA)  # use QQVGA for speed.
sensor.skip_frames(10)  # Let new settings take affect.
sensor.set_auto_whitebal(False)  # turn this off.
clock = time.clock()  # Tracks FPS.

s.low()
s_8.low()
s_4.low()
Beispiel #21
0
from pyb import LED,Servo
import time
LED(1).on()
LED(2).on()
LED(3).on()
s1 = Servo(1) # servo on position 1 (P7)

s1.angle(0)
while(1):
    #s1.angle(360)
    #s1.speed(60)
    #pass
    #s1.angle(60)
    #s1.speed(50)
    #s1.angle(90)
    #s1.speed(50)
    #time.sleep(100)
    #s1.angle(45)
    #time.sleep(100)
    #s1.angle(90) # move to 45 degrees
    #time.sleep(50)
    #s1.angle(45) # move to 45 degrees
    #time.sleep(50)
    #s1.angle(90) # move to 45 degrees
    #time.sleep(50)
    #s1.angle(45) # move to 45 degrees
    #time.sleep(50)
    #s1.angle(0) # move to 45 degrees
    #time.sleep(500)
    #s1.angle(-60) # move to 45 degrees
    #time.sleep(500)
Beispiel #22
0
import time
from pyb import (USB_VCP, Servo)

SLEEP = 0.1

UP = -90
DOWN = 0
SPEED = 1000

servo = Servo(1)
servo.angle(30)

p = USB_VCP()

while True:
    if p.any():
        command = p.readline().strip()
        if command == b'up':
            servo.angle(UP, SPEED)
            p.write(b'up-ok\n')
        elif command == b'down':
            servo.angle(DOWN, SPEED)
            p.write(b'down-ok\n')
        else:
            p.write(command + b'\n')
            p.write(b'err\n')

    time.sleep(SLEEP)
Beispiel #23
0
import pyb
from pyb import Pin
from pyb import Servo
from pyb import LED

l1=LED(1)
l2=LED(2)
l3=LED(3)
l4=LED(4)
# creat servo projects.
s1 = Servo(1)
s2 = Servo(2) 
s3 = Servo(3)
#s4 = Servo(4)
# go to straight line
'''
s1.angle(0,2000)
pyb.delay(1000)  
s2.angle(0,2000)
pyb.delay(1000)
s3.angle(0,2000)
pyb.delay(1000)


# Movement 1
s1.angle(-50,2000)
pyb.delay(2000)
s2.angle(-50,2000)
pyb.delay(2000)
s3.angle(-50,2000)
pyb.delay(2000)
    max_size=0
    for blob in blobs:
        if blob[2]*blob[3] > max_size:
            max_blob=blob
            max_size = blob[2]*blob[3]
    return max_blob


while(True):
    clock.tick() # Track elapsed milliseconds between snapshots().
    img = sensor.snapshot() # Take a picture and return the image.

    faces = img.find_features(face_cascade, threshold=0.5, scale=1.25)
    if faces:
        face = find_max(faces)
        cx = int(face[0]+face[2]/2)
        cy = int(face[1]+face[3]/2)
        pan_error = cx-img.width()/2
        tilt_error = cy-img.height()/2

        print("pan_error: ", pan_error)

        img.draw_rectangle(face) # rect
        img.draw_cross(cx, cy) # cx, cy

        pan_output=pan_pid.get_pid(pan_error,1)
        tilt_output=tilt_pid.get_pid(tilt_error,1)
        print("pan_output",pan_output)
        pan_servo.angle(pan_servo.angle()+pan_output)
        tilt_servo.angle(tilt_servo.angle()+tilt_output)
Beispiel #25
0
                                threshold=0.75,
                                scale_factor=1.25)

    x_error = int((x - (img.width() / 2) + 40) / 2.3)
    y_error = int(y - (img.height() / 2))
    #print(y_error)

    #print(int(x_error))
    # Draw objects
    for r in objects:
        #print(r)
        x = r[0]
        y = r[1]
        img.draw_rectangle(r)
    if x_error == -34:
        xServo.angle(0)
        #print(0)

    else:
        if x_error == z:
            i = i + 1
            if i > 300:
                if x_error == z:
                    xServo.angle(0)
                    #print(0)
            else:
                if x_error > 30:
                    xServo.angle(int(30))
                elif x_error < -30:
                    xServo.angle(int(-30))
                #print(x_error)
Beispiel #26
0
p_in = Pin('X2', Pin.IN, Pin.PULL_UP)
p_in.value() # get value, 0 or 1

# pin PWM control
from pyb import Pin, Timer

p = Pin('X1') # X1 has TIM2, CH1
tim = Timer(2, freq=1000)
ch = tim.channel(1, Timer.PWM, pin=p)
ch.pulse_width_percent(50)

# servo control
from pyb import Servo

s1 = Servo(1) # servo on position 1 (X1, VIN, GND)
s1.angle(45) # move to 45 degrees
s1.angle(-60, 1500) # move to -60 degrees in 1500ms
s1.speed(50) # for continuous rotation servos

# ADC/DAC
from pyb import Pin, ADC

adc = ADC(Pin('X19'))
adc.read() # read value, 0-4095

from pyb import Pin, DAC

dac = DAC(Pin('X5'))
dac.write(120) # output between 0 and 255

# SPI
Beispiel #27
0
sensor.__write_reg(0x0C, sensor.__read_reg(0x0C) | (1 << 7))  #Flips Camera

s1 = Servo(1)  # servo on position 1 (PD12, VIN, GND)
s2 = Servo(2)  # servo on position 1 (PD13, VIN, GND)

# Load Haar Cascade
# By default this will use all stages, lower satges is faster but less accurate.
face_cascade = image.HaarCascade("frontalface", stages=15)

# Default Pan/Tilt for the camera in degrees.
# Camera range is from -90 to 90
cam_pan = 60
cam_tilt = 60

# Turn the camera to the default position
"""
s1.angle(0,0)
s2.angle(60-90,0)
"""


def remap(x, oMin, oMax, nMin, nMax):

    #range check
    if oMin == oMax:
        return None

    if nMin == nMax:
        return None

    #check reversed input range
# main.py -- put your code here!
import pyb  # importing the board
# move servo based on the movement of the board
from pyb import Servo
accel = pyb.Accel()  # assigning the sensor to act as movement detector…
ss = Servo(1)  # servo on position 1 (X1, VIN, GND)
while True:  # while loop
    if accel.x() > 5:
        ss.angle(90)
    elif accel.x() < -5:
        ss.angle(-90)
    elif accel.x() == 0:
        ss.angle(0)
Beispiel #29
0
from pyb import Servo

servo = Servo(1)
print(servo)

servo.angle(0)
servo.angle(10, 100)

servo.speed(-10)
servo.speed(10, 100)

servo.pulse_width(1500)
print(servo.pulse_width())

servo.calibration(630, 2410, 1490, 2460, 2190)
print(servo.calibration())
Beispiel #30
0
# Create a list of sevo for convenience
servo_list = [ servo1,servo2, servo3, servo4 ]

print( "All servos at -90" )
for servo in servo_list:
	servo.angle( -90 )
	sleep( 0.5 )

print( "All servos at +90" )
for servo in servo_list:
	servo.angle( +90 )
	sleep( 0.5 )

print( "All servos at 0 degree (at once)" )
for servo in servo_list:
	servo.angle( 0 )

print( "Wait 2 seconds")
sleep( 2 )

print( "coordinate servo movement" )
# Coordonate move to -90° for servo1 & servo2 during 2 seconds
# while coordinate move to +90° for servo3 & servo4 during the same 2 seconds.
servo1.angle( +90, 2000 ) # 2000 ms = 2 sec
servo2.angle( +90, 2000 ) # 2000 ms = 2 sec
servo3.angle( -90, 2000 ) # 2000 ms = 2 sec
servo4.angle( -90, 2000 ) # 2000 ms = 2 sec
sleep( 2 ) # wait end of movement

print( "That's all folks!")
# Servo Control Example
#
# This example shows how to use your OpenMV Cam to control servos.

import micropython, time
from pyb import Servo
micropython.alloc_emergency_exception_buf(100)

s1 = Servo(1)  # P7

#s1.calibration(1000, 1500, 1100)
s1.calibration(640, 2420, 1500)
s1.angle(0)

time.sleep(2000)

print(s1.pulse_width())
print(s1.calibration())

i = -45
while (i < 45):
    print(i)
    s1.angle(i)
    print(s1.pulse_width())
    time.sleep(100)
    i += 1

# Car seems to start at 1390 PW which is speed -14 on default scale

# PWM:
# at 200hz with pw%=10, pw = 2160