# -*- coding: utf-8 -*- #通过声明可以在程序中书写中文 #输入通道与角度。即可选通并使该通道的舵机转动到相应的角度 from __future__ import division #导入 __future__ 文件的 division 功能函数(模块、变量名....) #新的板库函数 //= import time import Adafruit_PCA9685 #导入Adafruit_PCA9685模块 pwm = Adafruit_PCA9685.PCA9685() #把Adafruit_PCA9685.PCA9685()引用地址赋给PWM标签 def set_servo_speed(channel, speed): pulse_width = 1500 + 10 * speed #500-1500us的PWM是控制它正转,值越小,旋转速度越大;1500-2500us的PWM是它反转,值越大,旋转速度越大。 date = 4096 * pulse_width / 20000 #1500us的PWM是控制它停止。 pwm.set_pwm(channel, 0, date) # Set frequency to 50hz, good for servos. pwm.set_pwm_freq(50) if True: # Move servo on channel O between extremes. channel = 12 speed = -50 set_servo_speed(channel, speed) time.sleep(3) speed = 0 set_servo_speed(channel, speed)
# to the browser via Node-RED # import sys # allows for command line to be interpreted import json # enables creation of JSON strings import os # enables access to environment variables import math # import maths operations import random # import random numbers import time # enable sleep function sys.path.append('/home/pi/Adafruit_Python_PCA9685/Adafruit_PCA9685' ) # persistent directory for Adafruit driver print "Importing servo driver library..." import Adafruit_PCA9685 # enable control of devices ear servos via Adafruit library # Create and intialise servo driver pwm = Adafruit_PCA9685.PCA9685() pwm.set_pwm_freq(50) min_pwm = 140 mid_pwm = 370 max_pwm = 600 left_pwm_channel = 4 right_pwm_channel = 5 pwm.set_pwm(left_pwm_channel, 0, mid_pwm) pwm.set_pwm(right_pwm_channel, 0, mid_pwm) time.sleep(10) pwm.set_pwm(left_pwm_channel, 0, max_pwm) pwm.set_pwm(right_pwm_channel, 0, min_pwm)
def setup_output(self): import Adafruit_PCA9685 self.setup_output_variables(OUTPUT_INFORMATION) error = [] if self.pwm_hertz < 40: error.append("PWM Hertz must be a value between 40 and 1600") if error: for each_error in error: self.logger.error(each_error) return try: self.pwm_output = Adafruit_PCA9685.PCA9685( address=int(str(self.output.i2c_location), 16), busnum=self.output.i2c_bus) self.pwm_output.set_pwm_freq(self.pwm_hertz) self.output_setup = True self.logger.debug("Output setup on bus {} at {}".format( self.output.i2c_bus, self.output.i2c_location)) for i in range(16): if self.options_channels['state_startup'][i] == 0: self.logger.debug( "Startup state channel {ch}: off".format(ch=i)) self.output_switch('off', output_channel=i) elif self.options_channels['state_startup'][ i] == 'set_duty_cycle': self.logger.debug( "Startup state channel {ch}: on ({dc:.2f} %)".format( ch=i, dc=self.options_channels['startup_value'][i])) self.output_switch( 'on', output_channel=i, amount=self.options_channels['startup_value'][i]) elif self.options_channels['state_startup'][ i] == 'last_duty_cycle': self.logger.debug( "Startup state channel {ch}: last".format(ch=i)) device_measurement = db_retrieve_table_daemon( DeviceMeasurements).filter( and_( DeviceMeasurements.device_id == self.unique_id, DeviceMeasurements.channel == i)).first() last_measurement = None if device_measurement: channel, unit, measurement = return_measurement_info( device_measurement, None) last_measurement = read_last_influxdb( self.unique_id, unit, channel, measure=measurement, duration_sec=None) if last_measurement: self.logger.debug( "Setting channel {ch} startup duty cycle to last known value of {dc} %" .format(ch=i, dc=last_measurement[1])) self.output_switch('on', amount=last_measurement[1]) else: self.logger.error( "Output channel {} instructed at startup to be set to " "the last known duty cycle, but a last known " "duty cycle could not be found in the measurement " "database".format(i)) else: self.logger.debug( "Startup state channel {ch}: no change".format(ch=i)) except Exception as except_msg: self.logger.exception( "Output was unable to be setup: {err}".format(err=except_msg))
def __init__(self): self.pwm = Adafruit_PCA9685.PCA9685() self.pwm.set_pwm_freq(50)
W = 11 #-- Panel 3 --# if pwm_ch == 3: R = 12 G = 13 B = 14 W = 15 # Configure min and max LED pulse lengths led_min = 0 # Min pulse length out of 4095 led_max = 128 # Max pulse length out of 4095 #led_brightness = int((int(bright)/100) * led_max) # Apply brightness percentage to max pulse length #def initialize_gpio() pwm = PCA9685.PCA9685() def color_test(channel, frequency, speed, step): p = pwm(channel, 0, frequency) p.start(0) while True: for dutyCycle in range(0, 101, step): p.ChangeDutyCycle(dutyCycle) time.sleep(speed) for dutyCycle in range(100, -1, -step): p.ChangeDutyCycle(dutyCycle) time.sleep(speed) def color_test_thread():
def __init__(self): self.angleMin = 18 self.angleMax = 162 self.pwm = Adafruit_PCA9685.PCA9685() self.pwm.set_pwm_freq(50) # Set the cycle frequency of PWM
def __init__(self, threshold=1, show_windwos=False): #Servo config self.pwm = Adafruit_PCA9685.PCA9685() self.pwm.set_pwm_freq(60) self.pos_x = 300 self.pos_y = 300 self.point_y_max = 480 self.point_x_max = 640 self.servo_x_min = 100 self.servo_x_max = 500 self.servo_y_min = 475 self.servo_y_max = 575 #5v Relay for water solenoid config self.relay_gpio = 17 GPIO.setup(self.relay_gpio, GPIO.OUT) GPIO.output(self.relay_gpio, GPIO.LOW) self.is_squirting = False self.show = show_windwos # Either or not show the 2 windows self.frame = None #picamera self.camera = PiCamera() self.camera.resolution = (self.point_x_max, self.point_y_max) self.camera.framerate = 32 self.camera.vflip = True time.sleep(2) self.camera.saturation = 50 self.camera.brightness = 60 self.capture = PiRGBArray(self.camera, size=(self.point_x_max, self.point_y_max)) #background subtraction tool self.hist = 5000 self.thresh = 16 self.shadows = False self.fgbg = cv.createBackgroundSubtractorMOG2( history=self.hist, varThreshold=self.thresh, detectShadows=self.shadows) self.grmask = None self.gray_frame = np.zeros((self.point_y_max, self.point_x_max), dtype=np.uint8) self.average_frame = np.zeros((self.point_y_max, self.point_x_max, 3), np.float32) self.absdiff_frame = None self.previous_frame = None self.surface = self.point_x_max * self.point_y_max self.currentsurface = 0 self.currentcontours = None self.threshold = threshold if show_windwos: cv.namedWindow("Image") cv.createTrackbar("Detection treshold: ", "Image", self.threshold, 100, self.onChange) self.set_axis(0) self.set_axis(1)
import Adafruit_PCA9685 as ServoLib import sys pwm = ServoLib.PCA9685() pwm.set_pwm_freq(60) def left(): pwm.set_pwm(0, 0, 261) def right(): pwm.set_pwm(0, 0, 479) def reset(): pwm.set_pwm(0, 0, 370) if __name__ == '__main__': args = sys.argv if 'left' in args: left() elif 'right' in args: right() else: reset()
from __future__ import division import time import Adafruit_PCA9685 import math esc = Adafruit_PCA9685.PCA9685() esc.set_pwm_freq(50) esc.set_all_pwm(0, 320) def getPWMList(radianDirection, totalPWMSpeed): #motor 3 frontRight = cos(radianDirection - (math.pi / 4)) #motor 4 backRight = sin(radianDirection - (math.pi / 4)) #motor 5 backLeft = cos(radianDirection - (5 * math.pi / 4)) #motor 8 frontLeft = sin(radianDirection - (5 * math.pi / 4)) return [frontRight, backRight, backLeft, frontLeft] speedList = getPWMList(0, 340) print(speedList) #esc.set_pwm(0,0,speedList[0]) #esc.set_pwm(1,0,speedList[1]) #esc.set_pwm(2,0,speedList[2]) #esc.set_pwm(3,0,speedList[3]) #time.sleep(5) #esc.set_all_pwm(0,320)
def __init__(self): # Initialization at address 0x40 self.pwm = Adafruit_PCA9685.PCA9685()
#!/usr/bin/env python import paho.mqtt.client as mqtt from threading import Thread from time import sleep import Adafruit_PCA9685 from struct import * def dummySetPwm(pwmPort, minVal, maxVal): print(pwmPort, minVal, maxVal) try: pwm = Adafruit_PCA9685.PCA9685(busnum=1) pwm.set_pwm_freq(100) setPwm = pwm.set_pwm print("Started with real") except IOError as err: setPwm = dummySetPwm print("Error connecting: ", err) driveMin = 550 # Min pulse length out of 4096 driveMax = 750 # Max pulse length out of 4096 driveMid = 660 # driveMin + ((driveMax - driveMin) / 2) writes = {'val': 0} def setWheelsMid(): for i in range(5):
""" Created on Sun May 26 11:47:21 2019 @author: User """ import RPi.GPIO as gpio import time import Adafruit_PCA9685 import sys pwm_min = 5 pwm_min_rel = 150 pwm_max_rel = 600 servo = Adafruit_PCA9685.PCA9685() # PWM-Frequenz auf 50 Hz setzen servo.set_pwm_freq(50) # PWM starten, Servo auf 0 Grad servo.set_pwm(pwm_min) #2.5 # Umrechnung Grad in Tastverhaeltnis def setservo(winkel): if winkel < 0: winkel = 0 elif winkel > 180: winkel = 180 #pwm = winkel/36 + pwm_min
from __future__ import division import time import Adafruit_PCA9685 # from __future__ import printfunction # Initalisierung mit alternativer Adresse pwm = Adafruit_PCA9685.PCA9685(address=0x41) # Einstellen der Minimal- und Maximal-Pulslaengen servo_min = 150 # Minimale Pulslaenge servo_max = 600 # Maximale Pulslaenge motorpositions = [0, 0, 0, 0] def set_servo_pulse(channel, pulse): motorpositions[channel] = pulse pulse_length = 1000000 pulse_length /= 50 # print('{0}us per period'.format(pulse_length)) pulse_length /= 4096 # print('{0}us per bit'.format(pulse_length)) pulse *= 1000 # print(pulse_length) pulse /= pulse_length # print(pulse) pulse = round(pulse) # print(pulse) pulse = int(pulse) # print (pulse) pwm.set_pwm(channel, 0, pulse) print motorpositions
# Using Up and Down Arrow keys, one can settle on a speed limits suitable for the future task. # Modified from http://www.codehaven.co.uk/using-arrow-keys-with-inputs-python/ and # https://www.raspberrypi.org/forums/viewtopic.php?t=46732#p368096 # Author: Udayan Kumar from __future__ import division import curses import time # Import the PCA9685 module. import Adafruit_PCA9685 # Uncomment to enable debug output. # import logging # logging.basicConfig(level=logging.DEBUG) # Initialise the PCA9685 using the default address (0x40). pwm = Adafruit_PCA9685.PCA9685(address=0x40, busnum=1) # Configure min and max servo pulse lengths # TODO: adjust them for your car and motor turn_servo_right = 390 # Min pulse length out of 4096 turn_servo_left = 310 # Max pulse length out of 4096 move_esc_back = 350 # Min pulse length out of 4096 move_esc_fwd = 220 # Max pulse length out of 4096 pulse_freq = 50 # Set frequency to 50hz, good for esc. pwm.set_pwm_freq(pulse_freq) def getCenter():
from __future__ import division import time from smbus import SMBus import Adafruit_PCA9685 import subprocess import math from SherControl_Scripts_global import Inverse_Kinamatics as IK from SherControl_Scripts_global import Jacobian_Inv as JInv import numpy as np PI = math.pi #Global Variables pwm2 = Adafruit_PCA9685.PCA9685(address=0x41, busnum=1) pwm2.set_pwm_freq(50) bus = SMBus(1) pwm_hip = 330 pwm_knee = 400 flag = 1 ts = 5 filename = 'Black_dog_smooth_motion_st_' + str(ts) + '_ms.txt' fid = open(filename, 'w') fid.close() l_count = 0 while 1: l_count += 1