我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用RPi.GPIO.PWM。
def setup_output(self, name, pwm=False, initial=False): """ Set pin as output. :param name: Numer of the pin. :type name: int :param pwm: If value if PWM. :type pwm: bool :param initial: Initial value to set. :type initial: bool """ self._pins[name] = {"name": name, "type": "out", "pwm": None} GPIO.setup(name, GPIO.OUT) if pwm: pwm = GPIO.PWM(name, 200) pwm.start(initial * 100.0) self._pins[name]["pwm"] = pwm else: self[name] = initial
def __init__(self): GPIO.setmode(GPIO.BCM) GPIO.setup(self.dir_pin, GPIO.OUT) GPIO.setup(self.pulse_pin, GPIO.OUT) GPIO.setup(self.ms1_pin, GPIO.OUT) GPIO.setup(self.ms2_pin, GPIO.OUT) GPIO.setup(self.sleep_pin, GPIO.OUT) GPIO.setup(self.reset_pin, GPIO.OUT) dir=False GPIO.output(self.dir_pin, dir) GPIO.output(self.pulse_pin, False) GPIO.output(self.ms1_pin, True) GPIO.output(self.ms2_pin, False) GPIO.output(self.sleep_pin, False) GPIO.output(self.reset_pin, True) self.p1 = GPIO.PWM(self.pulse_pin, self.pulse_freq)
def main(): import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(12, GPIO.OUT) p = GPIO.PWM(12, 50) try: p.start(0) for dc in range(0, 101, 5): p.ChangeDutyCycle(dc) time.sleep(0.1) for dc in range(100, -1, -5): p.ChangeDutyCycle(dc) time.sleep(0.1) finally: p.stop() GPIO.cleanup()
def motor(mag): # Run Motor pulse = 1 speed = int(mag * 3 + 20) # Min 20 max 50 duration = int(10 - mag) # 2 sec to 20 sec sec = 0.1 p = GPIO.PWM(MOTORPIN, 50) # channel=MOTORPIN frequency=50Hz p.start(0) p.ChangeDutyCycle(speed) time.sleep(0.1) for dc in range(speed, 10, -(duration)): p.ChangeDutyCycle(dc) time.sleep(pulse) pulse = pulse + sec p.stop() return
def turn_on(gpio_num, freq, dc): global g_led_pwm # print('turn_on: %d, %d, %d' % (gpio_num, freq, dc)) if not g_led_pwm.has_key(gpio_num): g_led_pwm[gpio_num] = {} GPIO.setup(gpio_num, GPIO.OUT) g_led_pwm[gpio_num]['obj'] = GPIO.PWM(gpio_num, freq) g_led_pwm[gpio_num]['obj'].start(0) g_led_pwm[gpio_num]['obj'].ChangeFrequency(freq) g_led_pwm[gpio_num]['obj'].ChangeDutyCycle(dc) g_led_pwm[gpio_num]['freq'] = freq g_led_pwm[gpio_num]['dc'] = dc g_led_pwm[gpio_num]['status'] = 'on' status_notify()
def _setup_pin(self, pin): self._logger.debug(u"_setup_pin(%s)" % (pin,)) if pin: p = None if self._pigpiod is None: self._pigpiod = pigpio.pi() if self._settings.get_boolean(['pigpiod']): if not self._pigpiod.connected: self._logger.error(u"Unable to communicate with PiGPIOd") else: p = PiGPIOpin(self._pigpiod, pin, self._logger) else: GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, GPIO.HIGH) p = GPIO.PWM(pin, 100) p.start(100) return p
def __init__(self, direction_channel, pwm=None, offset=True): '''Init a motor on giving dir. channel and PWM channel.''' if self._DEBUG: print self._DEBUG_INFO, "Debug on" self.direction_channel = direction_channel self._pwm = pwm self._offset = offset self.forward_offset = self._offset self.backward_offset = not self.forward_offset self._speed = 0 GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) if self._DEBUG: print self._DEBUG_INFO, 'setup motor direction channel at', direction_channel print self._DEBUG_INFO, 'setup motor pwm channel as', self._pwm.__name__ GPIO.setup(self.direction_channel, GPIO.OUT)
def screen_on(retPage, backlightControl): if os.environ["KPPIN"] != "1": launch_bg=os.environ["MENUDIR"] + "launch-bg.sh" process = subprocess.call(launch_bg, shell=True) pygame.quit() if backlightControl == "3.5r": process = subprocess.call("echo '1' > /sys/class/backlight/soc\:backlight/brightness", shell=True) elif backlightControl == "4dpi-24": process = subprocess.call("echo '80' > /sys/class/backlight/24-hat-pwm/brightness", shell=True) else: backlight = GPIO.PWM(18, 1023) backlight.start(100) GPIO.cleanup() if os.environ["KPPIN"] == "1": page=os.environ["MENUDIR"] + "menu-pin.py" args = [page, retPage] else: page=os.environ["MENUDIR"] + retPage args = [page] os.execvp("python", ["python"] + args) # Turn screen off
def screen_off(backlightControl): screen.canvas.fill(black) pygame.display.update() if backlightControl == "3.5r": process = subprocess.call("echo '0' > /sys/class/backlight/soc\:backlight/brightness", shell=True) elif backlightControl == "4dpi-24": process = subprocess.call("echo '0' > /sys/class/backlight/24-hat-pwm/brightness", shell=True) else: backlight = GPIO.PWM(18, 0.1) backlight.start(0) process = subprocess.call("setterm -term linux -back black -fore white -clear all", shell=True) return() # Input loop for touch event
def __init__(self, left_pin1, left_pin2, right_pin1, right_pin2, leftpwm_pin, rightpwm_pin): io.setmode(io.BCM) # Constant values self.PWM_MAX = 100 # Here we configure the GPIO settings for the left and right motors spinning direction. # It defines the four GPIO pins used as input on the L298 H-Bridge to set the motor mode (forward, reverse and stopp). self.leftmotor_in1_pin = left_pin1 self.leftmotor_in2_pin = left_pin2 self.rightmotor_in1_pin = right_pin1 self.rightmotor_in2_pin = right_pin2 self.leftmotorpwm_pin = leftpwm_pin self.rightmotorpwm_pin = rightpwm_pin self.SetupGPIO() self.leftmotorpwm = io.PWM(self.leftmotorpwm_pin,100) self.rightmotorpwm = io.PWM(self.rightmotorpwm_pin,100) self.InitPWM() # Disable warning from GPIO io.setwarnings(False)
def __init__(self): self.led_gpio_red = 17 # red self.led_gpio_green = 27 # green self.led_gpio_blue = 22 # blue self.r = 0.0 self.g = 0.0 self.b = 0.0 GPIO.setmode(GPIO.BCM) GPIO.setup(self.led_gpio_red, GPIO.OUT) GPIO.setup(self.led_gpio_green, GPIO.OUT) GPIO.setup(self.led_gpio_blue, GPIO.OUT) GPIO.output(self.led_gpio_red, True) GPIO.output(self.led_gpio_green, True) GPIO.output(self.led_gpio_blue, True) self.pwm_red = GPIO.PWM(self.led_gpio_red, 100) self.pwm_green = GPIO.PWM(self.led_gpio_green, 100) self.pwm_blue = GPIO.PWM(self.led_gpio_blue, 100) self.pwm_red.start(0) self.pwm_green.start(0) self.pwm_blue.start(0)
def __init__(self): GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(self.MotorFront1, GPIO.OUT) GPIO.setup(self.MotorFront2, GPIO.OUT) GPIO.setup(self.MotorFront, GPIO.OUT) GPIO.output(self.MotorFront, 0) GPIO.setup(self.MotorBack1, GPIO.OUT) GPIO.setup(self.MotorBack2, GPIO.OUT) GPIO.setup(self.MotorBack, GPIO.OUT) GPIO.output(self.MotorBack, 0) self.BackPWM = GPIO.PWM(self.MotorBack,100) self.BackPWM.start(0) self.BackPWM.ChangeDutyCycle(0) self.direction = 0
def rotate_motor(duration,sleeptime): import RPi.GPIO as GPIO #import time servoPIN = 17 GPIO.setmode(GPIO.BCM) GPIO.setup(servoPIN, GPIO.OUT) p = GPIO.PWM(servoPIN, 500) # GPIO 18 als PWM mit 50Hz p.start(2.5) # Initialisierung try: while duration > 0: p.ChangeDutyCycle(1) print 'motor running'+str(duration) time.sleep(sleeptime) duration -= 1 p.stop() GPIO.cleanup() except KeyboardInterrupt: p.stop() GPIO.cleanup()
def setup(self): """ setup GPIO pins and start GPIO PWM. """ from RPi import GPIO GPIO.setup(self.pin_red, GPIO.OUT) GPIO.setup(self.pin_green, GPIO.OUT) GPIO.setup(self.pin_blue, GPIO.OUT) freq = 100 # Hz self.red = GPIO.PWM(self.pin_red, freq) self.green = GPIO.PWM(self.pin_green, freq) self.blue = GPIO.PWM(self.pin_blue, freq) # Initial duty cycle is 100, that means 'off' self.green.start(100) self.red.start(100) self.blue.start(100)
def setup(): global p_R, p_G, p_B # Set the GPIO modes to BCM Numbering GPIO.setmode(GPIO.BCM) # Set all LedPin's mode to output, # and initial level to High(3.3v) for i in pins: GPIO.setup(pins[i], GPIO.OUT, initial=GPIO.HIGH) # Set all led as pwm channel, # and frequece to 2KHz p_R = GPIO.PWM(pins['Red'], 2000) p_G = GPIO.PWM(pins['Green'], 2000) p_B = GPIO.PWM(pins['Blue'], 2000) # Set all begin with value 0 p_R.start(0) p_G.start(0) p_B.start(0) # Define a MAP function for mapping values. # Like from 0~255 to 0~100
def __init__(self, forward_pin, backward_pin, enable_pin): """Constructor. Args: forward_pin (int): GPIO pin connected to motor's forward pin. backward_pin (int): GPIO pin connected to motor's backward pin. enable_pin (int): GPIO pin connected to motor's enable pin """ # store pins self.frwd_p = forward_pin self.bkwd_p = backward_pin self.enbl_p = enable_pin GPIO.setup( [self.frwd_p, self.bkwd_p, self.enbl_p], GPIO.OUT, initial=False) # frequency (Hz) second parameter self.pwm = GPIO.PWM(self.enbl_p, 100) self.pwm.start(0.0) # initial direction forward self.change_dir(True);
def __init__(self, left, right, enable_pin): """Constructor. Args: forward_pin (int): GPIO pin connected to motor's forward pin. backward_pin (int): GPIO pin connected to motor's backward pin. enable_pin (int): GPIO pin connected to motor's enable pin """ # store pins self.left_pin = left self.right_pin = right self.pwm_pin = enable_pin self.turn_direction = 0.0; # [-1, 1] GPIO.setup( [self.left_pin, self.right_pin, self.pwm_pin], GPIO.OUT, initial=False) # frequency (Hz) second parameter self.pwm = GPIO.PWM(self.pwm_pin, 100) self.pwm.start(0.0) # initial direction: 0.0 # self.change_dir(True);
def __init__(self, forward_pin, backward_pin, enable_pin): """Constructor. Args: forward_pin (int): GPIO pin connected to motor's forward pin. backward_pin (int): GPIO pin connected to motor's backward pin. enable_pin (int): GPIO pin connected to motor's enable pin """ # store pins self.left_pin = forward_pin self.right_pin = backward_pin self.pwm_pin = enable_pin GPIO.setup( [self.left_pin, self.right_pin, self.pwm_pin], GPIO.OUT, initial=False) # frequency (Hz) second parameter self.pwm = GPIO.PWM(self.pwm_pin, 100) self.pwm.start(0.0) # initial direction forward self.change_dir(True);
def blink(self, on=1, off=-1): """Blinks an LED by working out the correct PWM frequency/duty cycle @param self Object pointer. @param on Time the LED should stay at 100%/on @param off Time the LED should stay at 0%/off""" self.stop() if off == -1: off = on off = float(off) on = float(on) total = off + on duty_cycle = 100.0 * (on/total) # Use pure PWM blinking, because threads are ugly self.frequency(1.0/total) self.duty_cycle(duty_cycle) self.blinking = True return True
def startup(self): # funciton that starts th GPIO board and pin required GPIO.setmode(GPIO.BOARD) GPIO.setup(self.channel, GPIO.OUT) self.pwm = GPIO.PWM(self.channel, self.frequency) self.pwm.start(self.frequency)
def pwm(self, io_number, frequence, rapport_cyclique, nouveau_rapport_cyclique, nouvelle_frequence): if self.importlib is not None: p = GPIO.PWM(io_number, frequence) p.start(rapport_cyclique) # ici, rapport_cyclique vaut entre 0.0 et 100.0 p.ChangeFrequency(nouvelle_frequence) p.ChangeDutyCycle(nouveau_rapport_cyclique) p.stop()
def __init__(self, channel): self.animator = threading.Thread(target=self._animate) self.channel = channel self.iterator = None self.running = False self.state = None self.sleep = 0 GPIO.setmode(GPIO.BCM) GPIO.setup(channel, GPIO.OUT) self.pwm = GPIO.PWM(channel, 100) self.lock = threading.Lock()
def pwmtest(i): for freq in [200, 400, 800, 1600, 3200]: p1 = GPIO.PWM(pulse_pin, freq) logging.debug(freq) p1.start(10) logging.debug('started') time.sleep(i) logging.debug('stopping') p1.stop() logging.debug('stopped') time.sleep(2) #time.sleep(2) #pwmtest(4)
def __init__(self, fwdpin, revpin): GPIO.setmode(GPIO.BCM) GPIO.setup(dir_pin, GPIO.OUT) GPIO.setup(pulse_pin, GPIO.OUT) GPIO.setup(ms1_pin, GPIO.OUT) GPIO.setup(sleep_pin, GPIO.OUT) GPIO.setup(reset_pin, GPIO.OUT) GPIO.output(revpin, False) self.p1 = GPIO.PWM(fwdpin, self.pulse_freq) self.p2 = GPIO.PWM(revpin, self.pulse_freq)
def on(self, power=None): if power is not None: self.power = int(power) if self.frequency is None: self.frequency = 0.5 # 2 sec self.p = GPIO.PWM(int(self.gpio), float(self.frequency)) self.p.start(int(self.power))
def color_test(channel, frequency, speed, step): p = GPIO.PWM(channel, frequency) p.start(0) PulseWidthMods.append(p) 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 adjust_angle_for_perspective_of_current_led(angle, led): """ Take the current LED into account, and rotate the coordinate plane 360° to make PWM calculations easier :param angle: integer, between 0-359 indicating current angle of joystick position :param led: 'R', 'G', 'B', indicating the LED we're interested in :return: integer, between 0-359 indicating new angle relative to the current LED under consideration """ led_peak_angle = 90 if led == 'R' else (210 if led == 'B' else 330) return ((angle - led_peak_angle) + 360) % 360
def calculate_next_pwm_duty_cycle_for_led(angle, led): """ Calculate the next PWM duty cycle value for the current LED and joystick position (angle) :param angle: integer, between 0-359 indicating current angle of joystick position :param led: 'R', 'G', 'B', indicating the LED we're interested in :return: integer, between 0-100 indicating the next PWM duty cycle value for the LED """ angle = adjust_angle_for_perspective_of_current_led(angle, led) if 120 < angle < 240: return 0 elif angle <= 120: return 100 - (angle * (100 / 120.0)) else: return 100 - ((360 - angle) * (100 / 120.0))
def red_light(): p = GPIO.PWM(R, 300) p.start(100) pwms.append(p) while True: p.ChangeDutyCycle(min(random.randint(75, 100) * math.pow(intensity + 0.1, 0.75), 100) if intensity > 0 else 0) rand_flicker_sleep()
def motor2(mag): # If needed, use on/off motor instead of PWM GPIO.output(MOTORPIN, True) time.sleep(int(mag)) GPIO.output(MOTORPIN, False) return
def __init__(self, pin_fw, pin_bw): self._invert = False self.pin_fw = pin_fw self.pin_bw = pin_bw self._speed = 0 GPIO.setup(self.pin_fw, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(self.pin_bw, GPIO.OUT, initial=GPIO.LOW) self.pwm_fw = GPIO.PWM(self.pin_fw, 100) self.pwm_fw.start(0) self.pwm_bw = GPIO.PWM(self.pin_bw, 100) self.pwm_bw.start(0)
def init(): global p, q, a, b # Initialise the PWM device using the default address #use physical pin numbering GPIO.setmode(GPIO.BOARD) #print GPIO.RPI_REVISION #set up digital line detectors as inputs GPIO.setup(lineRight, GPIO.IN) # Right line sensor GPIO.setup(lineLeft, GPIO.IN) # Left line sensor #Set up IR obstacle sensors as inputs GPIO.setup(irFL, GPIO.IN) # Left obstacle sensor GPIO.setup(irFR, GPIO.IN) # Right obstacle sensor #use pwm on inputs so motors don't go too fast GPIO.setup(L1, GPIO.OUT) p = GPIO.PWM(L1, 20) p.start(0) GPIO.setup(L2, GPIO.OUT) q = GPIO.PWM(L2, 20) q.start(0) GPIO.setup(R1, GPIO.OUT) a = GPIO.PWM(R1, 20) a.start(0) GPIO.setup(R2, GPIO.OUT) b = GPIO.PWM(R2, 20) b.start(0) startServos() # cleanup(). Sets all motors off and sets GPIO to standard values
def setupPins(self): """ Set Raspberry Pi GPIO pins to the right mode. """ GPIO.setmode(GPIO.BCM) GPIO.setup(self.enapin, GPIO.OUT) GPIO.setup(self.enbpin, GPIO.OUT) GPIO.setup(self.inapin, GPIO.OUT) GPIO.setup(self.inbpin, GPIO.OUT) GPIO.setup(self.pwmpin, GPIO.OUT) GPIO.setup(self.fanpin, GPIO.OUT) GPIO.setup(self.diapin, GPIO.IN) GPIO.setup(self.dibpin, GPIO.IN) self.p = GPIO.PWM(self.pwmpin, self.freq)
def startPWM(self): """ Start the PWM output. """ GPIO.output(self.fanpin, True) GPIO.output(self.enapin, True) GPIO.output(self.enbpin, True) GPIO.output(self.inapin, True) GPIO.output(self.inbpin, False) # Setup PWM and DMA channel 0 self.p.start(0) self.dutycycle = 0
def stopPWM(self): """ Stop the PWM output. """ # Stop PWM self.p.stop() GPIO.output(self.enapin, False) GPIO.output(self.enbpin, False) GPIO.output(self.inapin, False) GPIO.output(self.inbpin, False) GPIO.output(self.fanpin, False)
def changeDutyCycle(self, duty): """ Set the PWM duty cycle in percent. @param float duty: PWM duty cycle 0 < duty < 100 """ self.dutycycle = 0 if duty >= 0: GPIO.output(self.inapin, True) GPIO.output(self.inbpin, False) else: GPIO.output(self.inapin, False) GPIO.output(self.inbpin, True) self.p.ChangeDutyCycle(abs(duty))
def __init__(self, gpio): GPIO.setmode(GPIO.BCM) GPIO.setup(gpio, GPIO.OUT) self.pwm = GPIO.PWM(gpio, 1)
def __init__(self, channel, init_state): import RPi.GPIO as GPIO GPIO.setup(channel, GPIO.OUT) self._pwm = GPIO.PWM(channel, init_state.get('Frequency')) self._pwm.start(init_state.get('DutyCycle'))
def InitPWM(self): # Here we configure the GPIO settings for the left and right motors spinning speed. # It defines the two GPIO pins used as input on the L298 H-Bridge to set the motor speed with a PWM signal. self.leftmotorpwm.start(0) self.leftmotorpwm.ChangeDutyCycle(0) self.rightmotorpwm.start(0) self.rightmotorpwm.ChangeDutyCycle(0)
def get_new_color(pin, frequency): GPIO.setup(pin, GPIO.OUT) return GPIO.PWM(pin, frequency)
def get_new_led(pin, frequency): GPIO.setup(pin, GPIO.OUT) return GPIO.PWM(pin, frequency)
def get_new_led(pin, frequency): GPIO.setup(pin, GPIO.OUT) return GPIO.PWM(pin, frequency) #execution
def __init__(self, motorPin): self.motorPin = motorPin # Setup GPIO # Broadcom SOCKET channel is used as standard GPIO.setmode(GPIO.BCM) GPIO.setup(self.motorPin, GPIO.OUT) # Setup PWM with 100KHz self.motor = GPIO.PWM(self.motorPin, 100) # Start PWM self.motor.start(0) # Start on speed zero self.setZero()
def __init__(self, servoPin): self.servoPin = servoPin # Setup GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(self.servoPin, GPIO.OUT) # Setup PWM with 100KHz self.servo = GPIO.PWM(self.servoPin, 100) # Start PWM with dutycycle of 0% self.servo.start(0) self.zeroPosition() # Set position to zero at start
def initGPIO(): global p, q, a, b #use physical pin numbering GPIO.setmode(GPIO.BOARD) #set up digital line detectors as inputs GPIO.setup(lineRight, GPIO.IN) # Right line sensor GPIO.setup(lineLeft, GPIO.IN) # Left line sensor #use pwm on inputs so motors don't go too fast GPIO.setup(L1, GPIO.OUT) p = GPIO.PWM(L1, 20) p.start(0) GPIO.setup(L2, GPIO.OUT) q = GPIO.PWM(L2, 20) q.start(0) GPIO.setup(R1, GPIO.OUT) a = GPIO.PWM(R1, 20) a.start(0) GPIO.setup(R2, GPIO.OUT) b = GPIO.PWM(R2, 20) b.start(0) threadC = threading.Thread(target=wheelCount) threadC.start() # spinLeft(speed): Sets motors to turn opposite directions at speed. 0 <= speed <= 100
def setAllLEDs (red, green, blue): for i in range(4): setLED(i, red, green, blue) # End of RGB LED Functions #====================================================================== #====================================================================== # White LED Functions # (Pi2Go-Lite only) # # LsetLED(LED, value): Sets the LED specified to OFF == 0 or ON == 1 # TODO: take value from 0 to 100 and use as percentage PWM value
def initOS(): global backlight os.environ['SDL_FBDEV'] = '/dev/fb1' os.environ['SDL_MOUSEDEV'] = '/dev/input/touchscreen' os.environ['SDL_MOUSEDRV'] = 'TSLIB' os.environ['SDL_VIDEODRIVER'] = 'fbcon' GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) backlight = GPIO.PWM(18, 1024) backlight.start(100)