Example #1
0
def hug():
    WAVE_TIME = 4
    ANGLE1 = -180
    ANGLE2 = 180
    steps1 = abs(ANGLE1) / WAVE_TIME
    steps2 = abs(ANGLE2) / WAVE_TIME

    servo1 = pyb.Servo(4)
    servo2 = pyb.Servo(1)
    servo2.angle(0, 1)
    servo1.angle(0, 1)
    i = 1
    a1 = 1
    a2 = 1
    for i in range(WAVE_TIME + 1):
        print('i is: ', i)
        servo1.angle(a1, 1)
        servo2.angle(a2, 1)
        utime.sleep(1)
        a1 = i * steps1
        a2 = i * steps2
        if (ANGLE1 < 0):
            a1 = a1 * (-1)
        if (ANGLE2 < 0):
            a2 = a2 * (-1)
 def __init__( self, sensor, servonum = 3 ) :
   self._sensor = sensor
   self._servo = pyb.Servo(servonum)
   mn, mx, _, a, s = self._servo.calibration()
   self._servo.calibration(mn, mx, TreatThrower.servoCenter, a, s)
   self._servo.speed(0)
   self._led = pyb.LED(TreatThrower.ledNum)
Example #3
0
 def __init__(self, command_id, pin_num, start_pos=0):
     super().__init__(command_id, 'i8')
     self.start_pos = start_pos
     self.servo_ref = pyb.Servo(pin_num)
     if start_pos is not None:
         self.servo_ref.angle(start_pos)
     self.angle = start_pos
def main():
    a = pyb.Accel()
    pitches = [a.x, a.y]
    servos = [pyb.Servo(sn) for sn in servoNums]
    curangles = [-100, -100]

    #   mn, mx, _, a, s = s1.calibration()
    #   s1.calibration(mn, mx, servoCenter, a, s)
    #   s1.speed(0)

    l = pyb.LED(ledNum)
    sw = pyb.Switch()

    while (1):
        if sw():
            break
        for i in range(len(pitches)):
            p = pitches[i]()
            if curangles[i] != p:
                curangles[i] = p
                setservo(servos[i], p)
        pyb.delay(20)
Example #5
0
 def __init__(self, servoPin, offset = 0):
     self.servo = pyb.Servo(servoPin)
     self.offset = offset
     self.angle = 0
     return
Example #6
0
### Author: Dave Kimber <https://github.com/Kimbsy>
### Description: Control the MeArm robotic arm using the servo outputs on the badge.
### License: MIT
### Appname: MeArm Control

# pin 1 = bottom servo, rotation, left/right on joystick
# pin 2 = left servo, distance, up/down on joystick
# pin 3 = right servo, height, A/B buttons
# pin 4 = claw, toggle with center joystick

import pyb
import buttons
import ugfx

servos = [
    pyb.Servo(1),
    pyb.Servo(2),
    pyb.Servo(3),
    pyb.Servo(4),
]

boundaries = [
    [-90, 90],  # (right, left)
    [0, 65],  # (close, far)
    [-65, 20],  # (up,    down)
    [-80, 20],  # (open,  closed)
]

positions = [
    0,
    boundaries[1][0],
Example #7
0
def unhug():
    servo1 = pyb.Servo(4)
    servo2 = pyb.Servo(1)
    servo2.angle(0, 1)
    servo1.angle(0, 1)
Example #8
0
import pyb

servo = pyb.Servo(1)  # id can be 1-4 (corresponds to pins X1 - X4)

while True:
    # generates a random 30-bit number
    # dividing so we get a smaller number to work with roughly 0 - 200
    random_angle = pyb.rng() // 5500000

    # subtracting by 90 to bring range to roughly between -90 and 90
    # since many common servos have a range between -90 and 90 degrees
    random_angle -= 90

    #set servo's position immediately to random_angle
    servo.angle(random_angle)  # in degrees

    pyb.delay(500)  # wait half a second

    print(servo.angle())  # prints the servo's current position

    pyb.delay(500)
# DAC Setup

dac = pyb.DAC("P6") if analog_out_enable else None

if dac:
    dac.write(0)

# Servo Setup

min_s0_limit = min(s0_lower_limit, s0_upper_limit)
max_s0_limit = max(s0_lower_limit, s0_upper_limit)
min_s1_limit = min(s1_lower_limit, s1_upper_limit)
max_s1_limit = max(s1_lower_limit, s1_upper_limit)

s0_pan = pyb.Servo(1)  # P7
s1_tilt = pyb.Servo(2)  # P8

s0_pan.pulse_width(int((max_s0_limit - min_s0_limit) // 2))  # center
s1_tilt.pulse_width(int((max_s1_limit - min_s1_limit) // 2))  # center

s0_pan_conversion_factor = (max_s0_limit - min_s0_limit) / 1000
s1_tilt_conversion_factor = (max_s1_limit - min_s1_limit) / 1000


def s0_pan_position(value):
    s0_pan.pulse_width(
        round(s0_lower_limit +
              (max(min(value, 1000), 0) * s0_pan_conversion_factor)))

import pyb, time

from pyb import Pin, Timer

s1 = pyb.Servo(3)
s2 = pyb.Servo(2)

i = 0

while (1):

    s1.angle(30)  # move servo 1 to 45 degrees
    time.sleep(2000)

    s1.angle(0)  # move servo 1 to 45 degrees
    time.sleep(2000)

    s1.angle(-40)  # move servo 1 to 45 degrees
    time.sleep(2000)

    s1.angle(0)  # move servo 1 to 45 degrees
    time.sleep(5000)
# main.py -- Deployment Code

from pyb import UART
import pyb
import math
from machine import Pin
import time
from pyb import Pin, Timer

#Peripheral initialization
uart = UART(3, baudrate=9600)
accel = pyb.Accel()

#Servo Initialization
Sep_Servo = pyb.Servo(1)
Stabil_Servo = pyb.Servo(2)
orientServo = pyb.Servo(3)
Table_Servo = pyb.Servo(4)
p = Pin('X6')
tim = Timer(8, freq=50)
ArmDep_Servo = tim.channel(1, Timer.PWM, pin=p)

#Limit switch and LED initialization
Sep_SW = Pin('Y12', Pin.IN, Pin.PULL_UP)
Table_SW = Pin('Y11', Pin.IN, Pin.PULL_UP)
R_led = pyb.LED(1)
G_led = pyb.LED(2)
O_led = pyb.LED(3)
B_led = pyb.LED(4)

#Constants Definition for Orientation
# Hello World Example
#
# Welcome to the OpenMV IDE! Click on the green run arrow button below to run the script!


import pyb, time

s1 = pyb.Servo(3)   # create a servo object on position P7
i = -10;



while(1):

     s1.angle(i)        # move servo 1 to 45 degrees
     time.sleep(10)
     i=i+1
     if i > 2000 :
        i=0
     print('i = ',i)


#Mini Basketball Finite State Machine
#Made by Delroy Mangal
from pyb import Pin, ADC, Timer
import pyb

#Initializing servos
servo1 = pyb.Servo(1)
servo2 = pyb.Servo(2)
servo3 = pyb.Servo(3)
servo4 = pyb.Servo(4)

#Timer variables
period = 45000  #Length of game
servoInterval = 2000  #Time for hoop to move back and forth

#Servo variables
lastFlippedTime = 0
servoTracker = 0
startServos = 0

#Pin assignments
sw = pyb.Switch()
sw2 = pyb.Switch()
onButton = pyb.Pin('Y3', pyb.Pin.IN)
crashSensor = pyb.Pin('Y5', pyb.Pin.IN)

#Buzzer variables
buzzer1 = 550  #Frequency value
b1 = Pin('Y2')
tim = Timer(8, freq=2000)
ch = tim.channel(2, Timer.PWM, pin=b1)
'''
Implementing the orientation feature as a callable function.
'''
import pyb
import math
from pyb import UART
from machine import Pin
import time

#Peripheral(s) Initialization
uart = UART(3, baudrate=9600)  # create UART object
accel = pyb.Accel()  # create object to access Pyboard's built-in accelerometer
orientServo = pyb.Servo(
    1)  # Create a servo object 'orientServo' as a pin1 connection\

#Constants Definitions
CW = -90  # Value for Clockwise Servo Rotation
CCW = 90  # Value for Counterclockwise Servo Rotation
Stop = -10  # Value to Stop Servo Rotation
thresh_xacc = 22  # Value of the x-axis accelerometer reading once airframe is considered to be in the proper orientation.
keySet = 0  # Validation bit checking to see if message to initialize deployment has been received by the board


# Orientation Function. Accepts no arguments.
# Required Global Objects/Definitions: {uart, orientServo, accel, CW, CCW, Stop}
def orientation():
    completed = 0  #Validation bit to check if orientation is complete.
    uart.write('Setting servo speed(s) to 0')
    orientServo.speed(Stop)
    uart.write('Awaiting for Signal')
    while keySet == 0:
Example #15
0
 def __init__(self):
     self.s1 = pyb.Servo(3)   #defining the servo motor
     self.initial_angle = -70
     self.final_angle = 10
     self.s1.angle(self.initial_angle)   #setting the servo motor to start position
Example #16
0
import sensor, image, time, math, pyb
from pyb import Pin

p_out = Pin('P1', Pin.OUT)
p_out.low()
po = Pin('P2', Pin.OUT)
po.low()

s1 = pyb.Servo(1)
s2 = pyb.Servo(2)

sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time=2000)
sensor.set_auto_gain(False)
sensor.set_auto_whitebal(False)
clock = time.clock()

while (True):
    clock.tick()
    img = sensor.snapshot()
    img.lens_corr(1.8)

    matrices = img.find_datamatrices()
    for matrix in matrices:
        img.draw_rectangle(matrix.rect(), color=(255, 0, 0))
        print_args = (matrix.rows(), matrix.columns(), matrix.payload(),
                      (180 * matrix.rotation()) / math.pi, clock.fps())
        print("Matrix [%d:%d], Payload \"%s\", rotation %f (degrees), FPS %f" %
              print_args)
Example #17
0
File: main.py Project: HiloGoes/URA
from machine import Pin #utilização de pinos numerados da placa
import pyb #class de auxiliar de Servomotor da porta X1-X4
import time

"""#import umqtt "biblioteca de utilização mqtt"
qos(1) --> quality of service ao menos uma vez
#reference>>
https://github.com/micropython/micropython-lib/tree/master/umqtt.simple 
"""

#========= DEFNIÇÃO DE GLOBALS =========# 

sensor = machine.Pin(12, machine.Pin.IN, machine.Pin.PULL_UP)
estado_sensor=False

roda_esquerda = pyb.Servo(0,machine.Pin.OUT)
roda_direita = pyb.Servo(2,machine.Pin.OUT)

n_experimento = 1
volta = 0
tempo_volta

raio = []
angulo = []
vel_angular = []
vel_linear = []

#========= MANUPULAÇÃO DE DADOS =========#
def reset_dados():
	raio.clear()
	angulo.clear()
Example #18
0
#init
import pyb, gc

# 1.0 open, 0.0 closed
w_status = 1
#0 early, 1 late, 2 night, 3 manual
w_mode = 3

w_times = [[(19, 0), (8, 0)], [(19, 0), (10, 0)], [(7, 0), (14, 30)]]
#hardware
i2c = pyb.I2C(2, pyb.I2C.MASTER)
i2c.mem_write(4, 90, 0x5e)
touch = i2c.mem_read(1, 90, 0)[0]

s_up = pyb.Servo(1)
s_down = pyb.Servo(2)

lcd = pyb.LCD('Y')

rtc = pyb.RTC()

led_b = pyb.LED(1)
led_2 = pyb.LED(2)
#calibration
s_up.angle(-12)


def use_btn_w_servo(servo, duration=18000, inverse=False):
    if inverse:
        end_pos = -30
    else:
import machine
import framebuf
import time
import math
import pyb

SCREEN_WIDTH = 64
SCREEN_HEIGHT = 32

game_over = False  #player gameover-lose status
game_win = False  #player win status
score = 0  # game score
led_it = 0  # iterador de los leds
n_game = 0  #game counter
servo = pyb.Servo(1)  #servo motor
y12 = machine.Pin('Y12')  #red LED
y4 = machine.Pin('Y4')  #adc input pin
adc = pyb.ADC(y4)  #adc input object
i2c = machine.I2C('X')  #i2c screen
fbuf = framebuf.FrameBuffer(bytearray(64 * 32 // 8), 64, 32,
                            framebuf.MONO_HLSB)


def toggle_led():
    y12(0 if y12() else 1)


def toggle_leds(value):
    pyb.LED((value % 4) + 1).toggle()
    return (value + 1) % 4
Example #20
0
# Black Grayscale Line Following Example
#
# Making a line following robot requires a lot of effort. This example script
# shows how to do the machine vision part of the line following robot. You
# can use the output from this script to drive a differential drive robot to
# follow a line. This script just generates a single turn value that tells
# your robot to go left or right.
#
# For this script to work properly you should point the camera at a line at a
# 45 or so degree angle. Please make sure that only the line is within the
# camera's field of view.

import sensor, image, time, math, pyb

#BINARY_VIEW = True
servo = pyb.Servo(3)
moteur = pyb.Servo(2)
x_blob1 = 0
x_blob2 = 0
y_blob1 = 0
y_blob2 = 0
compteur = 0
angle = 0
# Tracks a black line. Use [(128, 255)] for a tracking a white line.
GRAYSCALE_THRESHOLD = [(150, 255)]

# Each roi is (x, y, w, h). The line detection algorithm will try to find the
# centroid of the largest blob in each roi. The x position of the centroids
# will then be averaged with different weights where the most weight is assigned
# to the roi near the bottom of the image and less to the next roi and so on.
ROIS = [  # [ROI, weight]   ROI : Regions of interest
Example #21
0
theta = 0.0

Kp = 0.3
Ki = 0.2
Kd = 0.01
# subject to change.

pid1 = PID.PID(Kp, Ki, Kd)
pid1.SetPoint = 0
pid1.setSampleTime(0.01)

pid2 = PID.PID(Kp, Ki, Kd)
pid2.SetPoint = 0
pid2.setSampleTime(0.01)

s1 = pyb.Servo(1)   # create a servo object on position P7
s1.angle(90) # neutral position
s2 = pyb.Servo(2)   # create a servo object on position P8
s2.angle(90) # nutral position


threshold_index = 0 # 0 for red, 1 for green, 2 for blue, see below

# Color Tracking Thresholds (L Min, L Max, A Min, A Max, B Min, B Max)
# The below thresholds track in general red/green/blue things. You may wish to tune them...
thresholds = [(30, 100, 15, 127, 15, 127), # generic_red_thresholds
              (30, 100, -64, -8, -32, 32), # generic_green_thresholds
              (0, 30, 0, 64, -128, 0)] # generic_blue_thresholds

pxtomm = None  # scale for conversion
sensor.set_contrast(1)
sensor.set_gainceiling(16)
# HQVGA and GRAYSCALE are the best for face tracking.
sensor.set_framesize(sensor.HQVGA)
sensor.set_pixformat(sensor.GRAYSCALE)

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

# FPS clock
clock = time.clock()

# Servo
left_ear = pyb.Servo(2)
right_ear = pyb.Servo(1)
arm = pyb.Servo(3)


# Servo functions
def move_ears():
    left_ear.angle(30)
    right_ear.angle(90)
    utime.sleep_ms(100)
    left_ear.angle(90)
    right_ear.angle(30)


def move_arms():
    arm.angle(-50)
Example #23
0
import pyb
import utime


def control_led(light):
    pyb.LED(light).on()
    utime.sleep(3)
    pyb.LED(light).off()


def move_servo(light, angle, speed):
    servo1.angle(angle, speed)
    control_led(light)


control_led(4)

servo1 = pyb.Servo(1)

move_servo(3, 90, 2000)

move_servo(2, -90, 2000)

control_led(4)
Example #24
0
# Untitled - By: yikealo - Sun Feb 4 2018

from pyb import Pin, Timer
import pyb

s = pyb.Servo(2)
INB = pyb.Pin("P3", pyb.Pin.OUT_PP)
INA = pyb.Pin("P4", pyb.Pin.OUT_PP)
INA.high()
INB.low()

p = Pin('P5')
Motor_Timer = Timer(2, freq=1000)
ch = Motor_Timer.channel(4, Timer.PWM, pin=p)
#ch.pulse_width_percent(50)
temp = 12
s.angle(0)
#pyb.delay(5000)
s.angle(40)
ch.pulse_width_percent(temp)
pyb.delay(5000)
ch.pulse_width_percent(0)
INA.low()
INB.high()
s.angle(-40)
ch.pulse_width_percent(temp)
pyb.delay(5000)
ch.pulse_width_percent(0)
Example #25
0
import machine
import pyb
import time

login_test=dict()
login_test["luiz"] = 0
login_test["micelli"] = 255
"""
Esse login_test, seria substituido por um querry de aprovados login = name e senha = user_id (ou quaisquer outra coisa)
existe o modelo de capitura dos logins e senhas no arquivo  'var/app_flask-instance/leitura de bd para porta', com o resutaldo um pickle exatamente do formato desejado
"""
y4 = machine.Pin('Y4')
adc = pyb.ADC(y4)
servo = pyb.Servo(1)
    
print("Enter name: ")
servo.angle(-90, 50)
while True:
    name=input()

    if name in login_test.keys() :

        if adc.read() == login_test[name]:
            print("Pode entrar")
            pyb.LED((1) + 1).on()
            servo.angle(90, 50)   
            time.sleep_ms(5000)
        else:
            print("'senha' invalida")
        
        print("Enter name: ")
        GREEN_LED.on()  

    start_trial = True


# Define the servo object. The numbering scheme differs between the pyboard and
# the pyboard LITE.
# 
# For the pyboard:
#  Servo 1 is connected to X1, Servo 2 to X2, Servo 3 to X3, and Servo 2 to X4
#
# For the pyboard LITE:
#  Servo 1 is connected to X3, Servo 2 to X4, Servo 3 to X1, and Servo 2 to X2

# Here, we'll use the first position on the pyboard
servo1 = pyb.Servo(1)
servo2 = pyb.Servo(2)


# This flag variable will be checked in the main part of the script, and 
# changed by an interrupt handler function attached to the track banana plugs
start_trial = False 

# Assign the start pin to variable start_pin
# We set it up as an input with a pulldown resistor and add an interrupt to 
# handle when it is pressed. This interrupt looks for rising edges, meaning 
# when the state changes from low to high
start_pin = pyb.ExtInt(pyb.Pin('X7'), 
                       pyb.ExtInt.IRQ_RISING, 
                       pyb.Pin.PULL_DOWN, 
                       handle_start_signal)
Example #27
0
'''
https://docs.micropython.org/en/latest/pyboard/tutorial/servo.html
     
connections: 
Ground (B) - GND 
Power  (R)   - 3V3 
NC
Signal -  pin X1
'''

import pyb

servo1 = pyb.Servo(1)  # pix X1

#set the angle
servo1.angle(45)

#read the angle
servo1.angle()

# move two servos at the same time with speed control
servo2 = pyb.Servo(2)
servo1.angle(-45, 2000)
servo2.angle(60, 2000)

# continuous rotation
servo1.speed()

# you can also change the calibration (see webpage)
Example #28
0
import sensor, image, time, pyb

sensor.reset()  # Reset and initialize the sensor.
sensor.set_pixformat(
    sensor.RGB565)  # Set pixel format to RGB565 (or GRAYSCALE)
sensor.set_framesize(sensor.QVGA)  # Set frame size to QVGA (320x240)
sensor.skip_frames(time=2000)  # Wait for settings take effect.
clock = time.clock()  # Create a clock object to track the FPS.

led_indicator = pyb.LED(
    1)  # Create a LED object which will indicate when camera on/off
# LED(1) turns on red
led_indicator.off()  # Set initial state to off

s_pan = pyb.Servo(1)  #Pan Servo connected to Pin P7
s_pan.angle(0)  #Set initial position to 0 degrees

s_tilt = pyb.Servo(2)  #Tilt Servo connected to Pin P8
s_tilt.angle(0)  #Set intitial position to 0 degrees

pan_angle = 0
tilt_angle = 0

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

#calculating bounds for movement
bound = 0.3
leftBound = (int)(320 * bound)
Example #29
0
##Example for sweeping a servo
##Connect Signal pin of the servo to pin D6


import pyb
import time

servo = pyb.Servo('D6')  #create a servo object attached at pin D6

while True:
    for pos in range(0, 180, 1): #pos changes from 0 to 179 degrees with step 1
        servo.angle(pos, 15) #moves servo to the value of pos in 15ms
#        print(pos)

    for pos in range(180, -1, -1): #pos changes from 180 to 0 degrees with step -1
        servo.angle(pos, 15) #moves servo to the value of pos in 15ms
#        print(pos)
Example #30
0
    print(mode)


ext = pyb.ExtInt(pins["Start Btn"], pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_NONE,
                 startMode)
ext = pyb.ExtInt(pins["Stop Btn"], pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_NONE,
                 stopMode)

batVoltageADC = pyb.ADC(pins["Battery Voltage"])
batVoltage = 0

# bluetooth = pyb.UART(2, 9600)
# bluetooth.init(9600, bits=8, parity=None, stop=1)

servoAngle = 45
servoHead = pyb.Servo(1)
servoSteer = pyb.Servo(2)

servoHead.angle(0)
servoSteer.angle(45)


def randInt(a, b):
    return int(pyb.rng() * ((b - a) / 1073741824) + a)


def read():
    #	print(positionTask.pos["x"], ", ", positionTask.pos["y"])
    #print(bno.read_euler())
    #print(bno.read_quaternion())
    pass