from machine import Pin, PWM, ADC from time import sleep servo = PWM(Pin(0)) freq = 50 servo.freq(freq) duty_cycles = [7000, 1000, 9000, 3000, 4500] while True: for duty in duty_cycles: servo.duty_u16(duty) # led.duty_u16(int(duty)) print(duty) sleep(2)
# This code controls one servos to move from 0 degree to 180 degree, # then back to 0 degree, and repeats forever. # --- # Connection: 1x Servo ports at GP12. Take note on the polarity. # --- # Hardware: # 1. Cytron Maker Pi RP2040 (www.cytron.io/p-MAKER-PI-RP2040) # - Any RP2040 boards should work too. # 2. TS90A Micro Servo 3-6V (www.cytron.io/p-analog-micro-servo-9g-3v-6v) # - Any servo motors within the rated voltage of 3.6-6V. # --- from machine import Pin, PWM import time # fine tune the duty cycle values to suit your servo motor MIN_DUTY = 1600 MAX_DUTY = 8400 pwm = PWM(Pin(12)) pwm.freq(50) while True: pwm.duty_u16(MIN_DUTY) time.sleep_ms(1000) pwm.duty_u16(MAX_DUTY) time.sleep_ms(1000)
# Programm reagiert auf eine äußere Eingabe (entprellter Taster) und treibt einen DC-Motor an. from machine import Pin, PWM Taster = Pin( 5, Pin.IN ) # Pin 5 an Pull-Down Widerstand (kann 10k sein), Tasterbetätigung führt zu logisch High pwm = PWM(Pin(1)) pwm.freq(1000) while True: if Taster.value() == 1: pwm.duty_u16(32768) else: pwm.duty_u16(0)
from machine import Pin, PWM from time import sleep pwm = PWM(Pin(11)) pwm.freq(1000) while True: for duty in range(65025): pwm.duty_u16(duty) sleep(0.0002) for duty in range(65025, 0, -1): pwm.duty_u16(duty) sleep(0.0002)
import time # led2 = Pin(25, Pin.OUT) #internal LED led = Pin(14, Pin.OUT) #GP14 led2 = Pin(11, Pin.OUT) btn = Pin(22, Pin.IN) led2.value(1) # switch on on program start # prepare servo servo = PWM(Pin(9)) servo.freq(50) pwmmiddle = 4000 dc = 0 servo.duty_u16(pwmmiddle) count = 0 while count < 2000: if btn.value(): led.value(1) dc = pwmmiddle else: led.value(0) dc = pwmmiddle + 1000 servo.duty_u16(dc) print("dc = " + str(dc)) count = count + 1 time.sleep(0.5) #switch all off
spi = SPI(0, sck=Pin(2), mosi=Pin(3), miso=Pin(4), baudrate=10000) cs = Pin(22, Pin.OUT) cs.value(1) # disable chip at start #in_0 = Pin(20, Pin.OUT) in_1 = Pin(21, Pin.OUT) chip = MCP3008(spi, cs) #https://docs.micropython.org/en/latest/esp8266/tutorial/pwm.html #https://github.com/raspberrypi/pico-micropython-examples pwm = PWM(Pin(20)) # GP20 pwm.freq(10) #https://github.com/micropython/micropython/blob/master/ports/rp2/machine_pwm.c #pwm.freq(1) -> ValueError: freq too small pwm.duty_u16(32768) # 50% pwm.duty_u16(16384) # 25% state = True last_0 = 0 last_1 = 0 nr = 0 while True: #in_0.value(state) #in_1.value(not state) #sleep(0.1) #state = not state actual_0 = chip.read(0)
from machine import Pin, PWM from utime import sleep led = PWM(Pin(25)) while True: brightness_str = input("brightness (0-65534):") brightness = int(brightness_str) led.duty_u16(brightness)
from machine import Pin, PWM, ADC import time print("setting servo") servo = PWM(Pin(1)) print("Setting up LED") led = PWM(Pin(25)) print("setting pot") potentiometer = ADC(26) print("setting servo frequency") freq = 50 servo.freq(freq) led.freq(1000) while True: # print("reading pot") pot = potentiometer.read_u16() duty = pot print('pot ', pot, ' duty:', duty, 'Freq:', freq) servo.duty_ns(int(duty)) led.duty_u16(int(duty)) time.sleep(0.001)
# This code Created by Inventing Phoenix # 1 FEB 2021 from machine import Pin, PWM, ADC # This will help you access these pins using the Pin class of the machine module # and PWM and ADC class of the machine module. ADC class will help us use analog pins import time pwm = PWM( Pin(15) ) # Pin number 15 has been assigned to our LED and it as also initated as PWM component adc = ADC( Pin(26) ) # Pin number 26 has been assigned to our potentiometer and its initated as analog component pwm.freq( 1000 ) # tells Raspberry Pi Pico how often to switch the power between on and off for the LED. while True: # runs the loop forever duty = adc.read_u16( ) # analog values read by the analog pin assigned to the potentiometer will be save in duty variable print(duty) # will print the analog value on the screen pwm.duty_u16( duty) # will pass one the analog value to the LED as a PWM input time.sleep(1) # delay for 1 second #Thank you for watching the video! Please subscribe to our youtube channel and click on the bell notification
# Pulse width measurement example using PWMCounter. # # Measures pulse width of PWM generated on GP0 # with counter configured on GP15. from machine import Pin, PWM from time import ticks_us, ticks_diff from PWMCounter import PWMCounter # Set PWM to output test signal pwm = PWM(Pin(0)) # Set duty cycle to 25% pwm.duty_u16(1 << 14) pwm.freq(1000) # We'll use counter pin for triggering, so set it up. in_pin = Pin(15, Pin.IN) # Configure counter to count rising edges on GP15 counter = PWMCounter(15, PWMCounter.LEVEL_HIGH) # Set divisor to 16 (helps avoid counter overflow) counter.set_div(16) # Start counter counter.start() last_state = 0 last_update = ticks_us() while True: start = ticks_us() if ~(x := in_pin.value()) & last_state: # Print pulse width in us - should show 250 with default setup print((counter.read_and_reset() * 16) / 125)
from machine import Pin, PWM from utime import sleep_ms pwm = PWM(Pin(20)) pwm.freq(1000) while True: pwm.duty_u16(32512) sleep_ms(1000) pwm.deinit() sleep_ms(2000)
'd': 294, 'e': 330, 'f': 349, 'g': 392, 'a': 440, 'b': 494, 'C': 523, ' ': 0, } beeper = PWM(Pin(16)) #, freq=440, duty=512) #beeper.duty(512) AttributeError: 'PWM' object has no attribute 'duty' while (True): beeper.freq(1000) beeper.duty_u16(512) melody = 'cdefgabC' rhythm = [8, 8, 8, 8, 8, 8, 8, 8] for tone, length in zip(melody, rhythm): beeper.freq(tones[tone]) time.sleep(tempo / length) beeper.deinit() time.sleep(0.5) beeper.freq(1000) beeper.duty_u16(512) melody = 'Cbagfedc' rhythm = [8, 8, 8, 8, 8, 8, 8, 8] for tone, length in zip(melody, rhythm): beeper.freq(tones[tone])
from machine import Pin from machine import PWM import utime m1ena = Pin(3, Pin.OUT) m1enb = Pin(4, Pin.OUT) m1pwm = PWM(Pin(5)) m1ena.value(0) m1enb.value(1) m1pwm.freq(500) for i in range(4): power = i * 4096 * 4 m1pwm.duty_u16(power) print("Step: ", i, " Power: ", power) utime.sleep(1) m1pwm.duty_u16(0)
forward = PWM(Pin(FORWARD_PIN)) reverse = PWM(Pin(REVERSE_PIN)) counter = 0 def main(): while True: global counter pot_val = pot.read_u16() if pot_val > HALF_POT: reverse.duty_u16(0) speed = (pot_val - HALF_POT)*2 forward.duty_u16(speed) print('forward', speed) else: forward.duty_u16(0) speed = (HALF_POT - pot_val)*2 reverse.duty_u16(speed) print('reverse', speed) counter += 1 sleep(.1) try: main() except KeyboardInterrupt: print('Got ctrl-c') finally: # Optional cleanup code print('Cleaning up') print('Powering down all motors now.') forward.duty_u16(0) reverse.duty_u16(0)
def main(self): # Overclock for faster calibration freq(250_000_000) ain = ADC(Pin(26, Pin.IN, Pin.PULL_DOWN)) cv1 = PWM(Pin(21)) usb = Pin(24, Pin.IN) def sample(): readings = [] for reading in range(256): readings.append(ain.read_u16()) return round(sum(readings) / 256) def wait_for_voltage(voltage): wait_for_b1(0) if voltage != 0: oled.centre_text(f'Plug in {voltage}V\n\nDone: Button 1') wait_for_b1(1) else: oled.centre_text(f'Unplug all\n\nDone: Button 1') wait_for_b1(1) oled.centre_text('Calibrating...') sleep(1.5) return sample() def text_wait(text, wait): oled.centre_text(text) sleep(wait) def fill_show(colour): oled.fill(colour) oled.show() def flash(flashes, period): for flash in range(flashes): fill_show(1) sleep(period / 2) fill_show(0) sleep(period / 2) def wait_for_b1(value): while b1.value() != value: sleep(0.05) # Calibration start if usb.value() == 1: oled.centre_text('Make sure rack\npower is on\nDone: Button 1') wait_for_b1(1) wait_for_b1(0) text_wait('Calibration\nMode', 3) oled.centre_text('Choose Process\n\n1 2') while True: if b1.value() == 1: chosen_process = 1 break elif b2.value() == 1: chosen_process = 2 break # Input calibration readings = [] if chosen_process == 1: readings.append(wait_for_voltage(0)) readings.append(wait_for_voltage(10)) else: for voltage in range(11): readings.append(wait_for_voltage(voltage)) with open(f'lib/calibration_values.py', 'w') as file: values = ", ".join(map(str, readings)) file.write(f"INPUT_CALIBRATION_VALUES=[{values}]") # Output Calibration oled.centre_text(f'Plug CV1 into\nanalogue in\nDone: Button 1') wait_for_b1(1) oled.centre_text('Calibrating...') if chosen_process == 1: new_readings = [readings[0]] m = (readings[1] - readings[0]) / 10 c = readings[0] for x in range(1, 10): new_readings.append(round((m * x) + c)) new_readings.append(readings[1]) readings = new_readings output_duties = [0] duty = 0 cv1.duty_u16(duty) reading = sample() for index, expected_reading in enumerate(readings[1:]): while abs(reading - expected_reading) > 0.002 and reading < expected_reading: cv1.duty_u16(duty) duty += 10 reading = sample() output_duties.append(duty) oled.centre_text(f'Calibrating...\n{index+1}V') with open(f'lib/calibration_values.py', 'a+') as file: values = ", ".join(map(str, output_duties)) file.write(f"\nOUTPUT_CALIBRATION_VALUES=[{values}]") oled.centre_text('Calibration\nComplete!')
sensor_1 = machine.ADC(26) sensor_2 = machine.ADC(27) sensor_3 = machine.ADC(28) while True: reading_1 = sensor_1.read_u16() reading_2 = sensor_2.read_u16() reading_3 = sensor_3.read_u16() beeper.freq(1000) if reading_1 > 10000: beeper.freq(tones['C7']) #tempDuty=int((1/tones['a'])/2) #print(tempDuty) beeper.duty_u16(6000) time.sleep(0.25) #print(reading_1) #print("C7") reading_2 = 0 reading_3 = 0 if reading_2 > 10000: beeper.freq(tones['D7']) #tempDuty=int((1/tones['b'])/2) beeper.duty_u16(6000) time.sleep(0.25) #print(reading_2) #print("D7") reading_1 = 0 reading_3 = 0
from machine import Pin, PWM import utime anschluss = 16 frequenz = 1250 LED = Pin(25, Pin.OUT) pwm = PWM(Pin(anschluss)) pwm.freq(frequenz) pwm.duty_u16(30000) LED.on() utime.sleep(5) LED.off() pwm.duty_u16(40000)
self.write_data(0x00) self.write_data(0xBB) self.write_cmd(0x2C) self.cs(1) self.dc(1) self.cs(0) self.spi.write(self.buffer) self.cs(1) if __name__ == '__main__': pwm = PWM(Pin(BL)) pwm.freq(1000) pwm.duty_u16(32768) #max 65535 #------joystck pin declaration----- # NOTE: 0 = pressed, 1 = not pressed Akey = Pin(15, Pin.IN, Pin.PULL_UP) Bkey = Pin(17, Pin.IN, Pin.PULL_UP) joyUp = Pin(2, Pin.IN, Pin.PULL_UP) joySelect = Pin(3, Pin.IN, Pin.PULL_UP) joyLeft = Pin(16, Pin.IN, Pin.PULL_UP) joyDown = Pin(18, Pin.IN, Pin.PULL_UP) joyRight = Pin(20, Pin.IN, Pin.PULL_UP) joy = [joyUp, joyRight, joyDown, joyLeft, joySelect, Akey, Bkey] LCD = LCD_1inch14()
pulse.low() exitLoop = False loopcount = 0 #used as a failsafe if the signal doesn't return while receiver.value() == 0 and exitLoop == False: loopcount = loopcount + 1 delaytime = utime.ticks_us() if loopcount > 3000: exitLoop == True while receiver.value() == 1 and exitLoop == False: loopcount = loopcount + 1 receivetime = utime.ticks_us() if loopcount > 3000: exitLoop == True if exitLoop == True: #We failed somewhere return 0 else: distance = ((receivetime - delaytime) * SpeedOfSoundInMM) / 2 return distance while True: distance = CheckDistance() print(distance) if CheckDistance() < 2500: speaker.duty_u16(3000) speaker.freq(1700) utime.sleep(0.05) speaker.duty_u16(0) utime.sleep(CheckDistance() / 1000)
shoty = 140 loopCount = 0 define_aliens() score = 0 difficulty = 1 showufo = False ufoy = 0 ufoCount = 0 soundfreq = 160 shippos = 30 while True: if showufo: if soundfreq == 1100: soundfreq = 2000 else: soundfreq = 1100 speaker.freq(soundfreq) speaker.duty_u16(2000) if shotx > 36 and showufo == False: speaker.duty_u16(0) ufoChance = random.randrange( 1, 350, 1) # 1 in 1000 chance of running this loop that UFO will appear if ufoChance == 123 and showufo == False: showufo = True ufoy = 0 if showufo: ufoy = ufoy + 1 if ufoy > 64: showufo = False loopCount = loopCount + 1 oled.fill(0) if loopCount > 16 - difficulty: if showufo == False:
play_turn() # back up for a bit reverse() utime.sleep(REVERSE_TIME) # half right and half left turns if urandom.random() < .5: turn_right() else: turn_left() utime.sleep(TURN_TIME) forward() else: print('forward') forward() valid_distance = 1 led_show_dist(distance) utime.sleep(0.05) # clean up # This allows us to stop the sound by doing a Stop or Control-C which is a keyboard intrrup try: main() except KeyboardInterrupt: print('Got ctrl-c') finally: # Optional cleanup code print('turning off sound') buzzer.duty_u16(0) print('shutting motors down') stop()
from machine import Pin, PWM import time pwm_red = PWM(Pin(5, Pin.OUT)) pwm_green = PWM(Pin(6, Pin.OUT)) pwm_blue = PWM(Pin(13, Pin.OUT)) pwm_red.freq(100) pwm_green.freq(100) pwm_blue.freq(100) delaySec = 0.0001 while True: for i in range(65025): pos = i if pos < 21675: pwm_red.duty_u16(pos * 3) pwm_green.duty_u16(65025 - pos * 3) pwm_blue.duty_u16(0) elif pos < 43350: pos -= 21675 pwm_red.duty_u16(65025 - pos * 3) pwm_green.duty_u16(0) pwm_blue.duty_u16(pos * 3) else: pos -= 43350 pwm_red.duty_u16(0) pwm_green.duty_u16(pos * 3) pwm_blue.duty_u16(65025 - pos * 3) time.sleep(delaySec)
def encoderHandler(pin): global position global isHomed position = position + 1 #print ( "Position: ", position, " isHomed: ", isHomed ) def breakerHandler(pin): global position global isHomed print("Homing: ", isHomed, " Postion: ", position) position = 0 if (not isHomed): isHomed = True encoder1.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=encoderHandler) breaker.irq(trigger=Pin.IRQ_RISING, handler=breakerHandler) m1ena = Pin(3, Pin.OUT) m1enb = Pin(4, Pin.OUT) m1pwm = PWM(Pin(5)) m1ena.value(0) m1enb.value(1) m1pwm.freq(500) m1pwm.duty_u16(16000) utime.sleep(3) m1pwm.duty_u16(0)
from machine import Pin, PWM from utime import sleep # lower right corner with USB connector on top AUDIO_LEFT_PIN = 18 AUDIO_RIGHT_PIN = 19 # create a Pulse Width Modulation Object on this pin left_speaker = PWM(Pin(AUDIO_LEFT_PIN)) # set the duty cycle to be 50% left_speaker.duty_u16(1000) left_speaker.freq(1000) # 50% on and off sleep(1) # wait a second left_speaker.duty_u16(0) # turn off the PWM circuits off with a zero duty cycle left_speaker.duty_u16(0) sleep(1) # create a Pulse Width Modulation Object on this pin right_speaker = PWM(Pin(AUDIO_RIGHT_PIN)) # set the duty cycle to be 50% right_speaker.duty_u16(1000) right_speaker.freq(1000) # 50% on and off sleep(1) # wait a second right_speaker.duty_u16(0) # turn off the PWM circuits off with a zero duty cycle right_speaker.duty_u16(0)
class Servo(): __angle = 90 __name = "Servo" __pin = 0 __max_angle = 180 __min_angle = 0 __current_angle = 90 __transition = "ease_in_sine" __duration = 0.5 # this is in seconds __channel = 0 __pin = 0 __target_angle = 0 __current_time = 0 __start_value = 0 __change_in_value = 0 __tick_started = False __tick_start_time = 0 elapsed_time = 0 def tick_start(self): self.__tick_start_time = ticks_us() def tick(self): self.__current_time = ticks_us() elapsed_time = self.elapsed_time if elapsed_time >= self.__duration: return True cur_angle = self.__current_angle if self.__transition == 'ease_in_sine': cur_angle = Transition().ease_in_sine(current_time=self.elapsed_time, start_value=self.__start_value, change_in_value=self.__start_value-self.__target_angle, duration=self.__duration) self.angle = int(cur_angle) def __init__(self, name=None, pin=None): if name is not None: self.__name = name if pin is not None: self.__pin = pin self.__pwm = PWM(Pin(self.__pin)) self.__pwm.freq(1000) print("*** ", self.__name , "is Online ***") @property def duration_in_seconds(self): """ Returns the duration in Microseconds""" return self.__duration * 1000000 @duration_in_seconds.setter def duration_in_seconds(self, value): self.__duration = value * 1000000 @property def elapsed_time_in_seconds(self): """ Returns the elapsed time in seconds""" return self.__current_time - self.__tick_start_time / 1000000 @property def angle(self): return self.__angle @angle.setter def angle(self, value): if value <= 180 and value >= 0: self.__angle = value # Servo Setting Code my_angle = map(value, 0, 180, 0, 65025) self.__pwm.duty_u16(my_angle) sleep(0.01) # print("the angle is now", self.angle) else: print("The angle was too small or too large: ", value) @property def name(self): return self.__name @name.setter def name(self, value): self.__name = value print("Hello from", self.__name) @property def pin(self): return self.__pin @pin.setter def pin(self, value): if value >= 0 and value <= 40: self.__pin = value else: print("The Pin was too low or too large: ", value)
class Motor_Driver: def __init__(self, dir_pin, speed_pin, bk_pin, sleep_pin, motor_pot, current_sense, indicator): self.dir_pin = Pin(dir_pin, Pin.OUT) self.pwm = PWM(Pin(speed_pin)) if bk_pin is not None: self.bk_pin = Pin(bk_pin, Pin.OUT) if sleep_pin is not None: self.sleep_pin = Pin(sleep_pin.Pin.OUT) self.sleep_pin.value(1) if indicator is True: self.indicator_led = Pin(25, Pin.OUT) if motor_pot is not None: self.motor_pot = ADC(Pin(motor_pot)) if motor_pot is not None: self.current_sense = ADC(Pin(current_sense)) def speed(self, freq, duty): self.pwm.freq(freq) self.pwm.duty_u16(duty) def stop(self): self.pwm.duty_u16(0) def extend(self): self.dir_pin.value(0) try: self.indicator_led.value(0) except AttributeError: pass def retract(self): self.dir_pin.value(1) try: self.indicator_led.value(1) except AttributeError: pass def brake(self): self.bk_pin.value(1) def release(self): self.bk_pin.value(0) def sleep(self): self.sleep_pin.value(0) def wake(self): self.sleep_pin.value(1) def pot_read(self): filtered_pot = 1 for i in range(16): filtered_pot += self.motor_pot.read_u16() filtered_pot = filtered_pot / 16 self.travel = ((self.motor_pot.read_u16()) / 93617) self.travel = round(self.travel, 3) return filtered_pot def current_read(self): voltage = self.current_sense.read_u16() voltage = voltage / 19858 current = round(voltage / .5, 2) print("Amps: " + str(current))
from machine import Pin, PWM SPEAKER_PIN = 16 # create a Pulse Width Modulation Object on this pin speaker = PWM(Pin(SPEAKER_PIN)) speaker.duty_u16(0)
import time from machine import u2if, Pin, PWM led_pwm = PWM(Pin(u2if.GP_3)) led_pwm.freq(1000) while True: for i in range(0, 65535, 50): led_pwm.duty_u16(i) time.sleep(0.005) time.sleep(1) for i in reversed(range(0, 65535, 50)): led_pwm.duty_u16(i) time.sleep(0.005)