示例#1
0
文件: myMain.py 项目: ArmyAntSEC/RHex
    def __init__(self):
        num = NumericOutput("hello")
        num((1, 2))

        m1ena = Pin(3, Pin.OUT)
        m1enb = Pin(4, Pin.OUT)
        m1pwm = PWM(Pin(5))
        m1pwm.freq(1000)

        self.driver1 = MotorDriver()
        self.driver1.config(m1ena, m1enb, m1pwm)

        self.homingEncoder1 = HomingEncoder(10000)
        self.homingEncoder1.config(6, 7, 28)

        self.controller1 = MotorController(10000)
        self.controller1.config(self.driver1, self.homingEncoder1, 0.0003)

        self.taskScheduler = TackScheduler()
        #self.taskScheduler.addTask( Beacon() )
        self.taskScheduler.addTask(FastBeacon())
        #self.taskScheduler.addTask( self.controller1 )
        #self.taskScheduler.addTask( self.homingEncoder1 )

        self.commands = {
            "info": self.cmdInfo,
            "move": self.cmdSimpleMove,
            "const": self.cmdMoveAtConstantSpeed,
            "stats": self.cmdStats,
            "exit": self.cmdExit
        }

        # Start the infitine loop
        self.run()
def play_mario():
    """
    play Mario Bros tone example
    source from here http://www.linuxcircle.com/2013/03/31/playing-mario-bros-tune-with-arduino-and-piezo-buzzer/
    """
    p5 = Pin(5, Pin.OUT)
    pwm5 = PWM(p5)
    # mario = [E7, E7, 0, E7, 0, C7, E7, 0, G7, 0, 0, 0, G6, 0, 0, 0, C7, 0, 0, G6, 0, 0, E6, 0, 0, A6, 0, B6, 0, AS6, A6, 0, G6, E7, 0, G7, A7, 0, F7, G7, 0, E7, 0,C7, D7, B6, 0, 0, C7, 0, 0, G6, 0, 0, E6, 0, 0, A6, 0, B6, 0, AS6, A6, 0, G6, E7, 0, G7, A7, 0, F7, G7, 0, E7, 0,C7, D7, B6, 0, 0]
    mario = [
        E5, E5, 0, E5, 0, C5, E5, 0, G5, 0, 0, 0, G4, 0, 0, 0, C5, 0, 0, G4, 0,
        0, E4, 0, 0, A4, 0, B4, 0, AS4, A4, 0, G4, E5, 0, G5, A5, 0, F5, G5, 0,
        E5, 0, C5, D5, B4, 0, 0, C5, 0, 0, G4, 0, 0, E4, 0, 0, A4, 0, B4, 0,
        AS4, A4, 0, G4, E5, 0, G5, A5, 0, F5, G5, 0, E5, 0, C5, D5, B4, 0, 0
    ]

    for note in mario:
        if note == 0:
            pwm5.duty(0)
        else:
            pwm5.freq(note)  # change frequency for change tone
            pwm5.duty(30)

        sleep_ms(150)

    pwm5.deinit()
示例#3
0
class SOUND():
    def __init__(self):
        pin = Pin(piNo)
        self.buzzer = PWM(pin)
        self.buzzer.duty(0)
        self.pr = False

    def __del__(self):
        self.buzzer.duty(0)
        self.buzzer.deinit()

    def debug(self, deb=True):
        self.pr = deb

    def sound(self, freq, duration=1, duty=512):
        if self.pr:
            print("sound start:" + str(freq) + " :" + str(duration) + " :" +
                  str(duty))

        self.buzzer.duty(duty)
        self.buzzer.freq(freq)
        sleep_ms(int(duration * 1000))
        self.buzzer.duty(0)
        #self.buzzer.deinit()

    def sound_off(self):
        self.buzzer.freq(0)
        self.buzzer.duty(0)
示例#4
0
class Stepper:
    def __init__(self, dirPin, stepPin, msPin):
        self.dirPin = dirPin
        self.stepPin = PWM(stepPin, freq=0, duty=0)
        self.msPin = msPin  #microstep pin M0
        #M0,M1,M2,ms
        self.timeTable = [(1, 0, 0, 2000), (0, 0, 0, 20000), (1, 0, 0, 2000)]
        self.tim = Timer(-1)
        self.stepPin.freq(1000)
        self.index = 0

    #travel (in steps), speed (in steps / seconds)
    def Schedule(self, travel, speed):
        #converti les steps en millisecondes en tenant compte
        #cree une rampe d'acceleration / deceleration par paliers
        #en utilisant les microsteps

        #for i in
        #    self.timeTable[]int(steps/self.freq)*1000)
        pass

    #integre une compensation du temps du retard moyen du Timer (1_ms)
    def Run(self, t):
        self.stepPin.duty(32)
        try:
            print(time.ticks_us())
            self.msPin.value(self.timeTable[self.index][0])
            self.tim.init(period=(self.timeTable[self.index][3]) - 1,
                          mode=Timer.ONE_SHOT,
                          callback=self.Run)
            self.index += 1
        except:
            self.stepPin.duty(0)
class StatusLED():
    def __init__(self, gpio=2):
        self.led = Pin(gpio, Pin.OUT)
        self.pwm = PWM(self.led)

    def on(self):
        self.pwm.deinit()
        self.led.off()
        sleep_ms(200)
        self.led.off()

    def off(self):
        self.pwm.deinit()
        self.led.on()
        sleep_ms(200)
        self.led.on()

    def invert(self):
        self.pwm.deinit()
        self.led.value(not led.value())

    def set(self, state):
        if state:
            self.on()
        else:
            self.off()

    def slow_blink(self):
        self.pwm.freq(1)
        self.pwm.duty(512)

    def fast_blink(self):
        self.pwm.freq(3)
        self.pwm.duty(512)
def sound_after_1_count():
    buzzer = 0
    for i in range(2):
        buzzer = PWM(Pin(25))
        buzzer.freq(10)
        sleep(1)
    buzzer.deinit()
示例#7
0
class BuzzerDrum(AbstractInstrument, M5StackPlatform):

    FREQ_NORMAL = 500
    FREQ_ACCENT = 800
    VOLUME = 500
    BEEP_LENGTH = 0.07

    pinNumber = None

    def __init__(self, pin):
        super().__init__()
        self.pinNumber = pin
        self.buzzer = PWM(Pin(self.pinNumber))
        # stáva sa že na začiatku defaultné bzučí, tak ho tu stíšim:
        self.buzzer.duty(0)

    def playNormal(self, note):
        self.buzzer.freq(self.FREQ_NORMAL)
        self.buzzer.duty(self.VOLUME)
        sleep(self.BEEP_LENGTH)
        self.buzzer.duty(0)
        return self.BEEP_LENGTH

    def playAccent(self, note):
        self.buzzer.freq(self.FREQ_ACCENT)
        self.buzzer.duty(self.VOLUME)
        sleep(self.BEEP_LENGTH)
        self.buzzer.duty(0)
        return self.BEEP_LENGTH
示例#8
0
class Motor:
    def __init__(self, m1, m2, dir, step, freq=50, duty=0):
        self.m1 = Pin(m1, Pin.OUT)
        self.m2 = Pin(m2, Pin.OUT)
        self.dir = Pin(dir, Pin.OUT)
        self.drive = PWM(Pin(step), freq, 0)
        self.duty = getDuty(duty)
        self.m1.value(0)
        self.m2.value(0)
        self.dir.value(0)

    def setDuty(self, duty):
        self.duty = duty
        self.drive.duty(duty)

    def setFreq(self, freq):
        self.drive.freq(freq)

    def setStepMode(self, mode):
        if 0 <= mode and mode <= 3:
            self.m1.value(1 & mode)
            self.m2.value(1 & (mode >> 1))

    def setDir(self, dir):
        if 0 == dir or 1 == dir:
            self.dir.value(dir)

    def driveOn(self):
        self.drive.init()
        self.drive.duty(self.duty)

    def driveOff(self):
        self.drive.deinit()
示例#9
0
def play_show(tune, pin=27, display=matrix.display, duration=None):
    from machine import Pin, PWM
    from utime import sleep_ms

    try:
        pwm = PWM(Pin(pin))
        if duration is None:
            set_default(tune[0])
        else:
            set_duration(duration)
        for tone in tune:
            tone = tone.upper()  # all to upper
            if tone[0] not in Letter:
                continue
            if len(tone) == 4:
                display.showstatic(tone.replace(":", ""))
            else:
                display.showstatic(tone)
            m = midi(tone)
            pwm.freq(m[0])  # set frequency
            pwm.duty(m[1])  # set duty cycle
            sleep_ms(m[1])
        display.clear()
    finally:
        pwm.deinit()
 def angle(self, angle, pin):
     pwm = PWM(Pin(pin))  #Set pin
     pwm.freq(50)  #Set Frequency
     servo_position = (
         (angle * 650 / 3 + 9500) / 6
     )  # Formula to convert angle to correct pwm; Don't worry I wont repeat that formula again ;) DRY - Don't Repeat Yourself.
     pwm.duty_u16(int(servo_position))  #Set servo position
示例#11
0
def pitch(freq, tim):
    pwm = PWM(Pin(25))
    pwm.freq(freq)  # set frequency
    # print('pwm.freq ' + str(pwm.freq()))  # get current frequency
    pwm.duty(500)  # set duty cycle
    sleep_ms(tim)
    pwm.deinit()
示例#12
0
def sound_on_off():
    buzzer = 0
    for i in range(5):
        buzzer = PWM(Pin(25))
        buzzer.freq(10)
        sleep(1)
    buzzer.deinit()
示例#13
0
def laser():
    global statBuzzer
    #statBuzzer = 'off'
    while (1):
        infra.value(1)
        sleep(2)
        if ldr.read() > 4000 and infra.value() == 1:
            while (1):
                buzzer = PWM(Pin(2))
                buzzer.freq(20)
                #statBuzzer = 'on'
                R.value(1)
                G.value(0)
                B.value(0)
                sleep(0.5)
                R.value(0)
                G.value(0)
                B.value(1)
                sleep(0.5)
                #print(SW.value())
                if SW.value() == 0 or count % 2 == 1:
                    buzzer.deinit()
                    #statBuzzer = 'off'
                    R.value(0)
                    G.value(0)
                    B.value(0)
                    break
            sleep(0.2)
        if SW.value() == 0 or count % 2 == 1:
            infra.value(0)
            break
示例#14
0
def setup():
    #setup light to voltage sensor
    adc = ADC(Pin(34))  # define the pin as an analog-to-digital converter
    adc.atten(ADC.ATTN_11DB)  # set the atten..?
    adc.width(ADC.WIDTH_12BIT)  # set the width of the available bits

    #setup measurement LED for PWM
    dpin = Pin(12)
    pwm = PWM(dpin)
    pwm.freq(78000)  # set frequency
    pwm.duty(0)  # set current

    #setup RGB LED
    red = Pin(15, Pin.OUT)
    green = Pin(32, Pin.OUT)
    blue = Pin(14, Pin.OUT)

    #setup embedded LED
    emb = Pin(13, Pin.OUT)

    #setup button 1
    button = Pin(33, Pin.IN, Pin.PULL_UP)

    # setup button 2
    button2 = Pin(27, Pin.IN, Pin.PULL_UP)

    return (adc, pwm, button, button2, red, green, blue, emb)
示例#15
0
def play_show(tune, pin=27, display=matrix.display, duration=None):
    from machine import Pin, PWM
    from utime import sleep_ms

    try:
        pwm = PWM(Pin(pin))
        if duration is None:
            set_default(tune[0])
        else:
            set_duration(duration)
        for tone in tune:
            tone = tone.upper()  # all to upper
            if tone[0] not in Letter:
                continue
            if len(tone)==4:
                display.showstatic(tone.replace(":",""))
            else:
                display.showstatic(tone)
            m = midi(tone)
            pwm.freq(m[0])  # set frequency
            pwm.duty(m[1])  # set duty cycle
            sleep_ms(m[1])
        display.clear()
    finally:
        pwm.deinit()
示例#16
0
class Servo:
    def __init__(self,
                 pin: int or Pin or PWM,
                 minVal=2500,
                 maxVal=7500,
                 maxDegrees=180):
        if isinstance(pin, int):
            pin = Pin(pin, Pin.OUT)
        if isinstance(pin, Pin):
            self.__pwm = PWM(pin)
        if isinstance(pin, PWM):
            self.__pwm = pin
        self.__pwm.freq(50)
        self.minVal = minVal
        self.maxVal = maxVal
        self.maxDegrees = maxDegrees

    def deinit(self):
        self.__pwm.deinit()

    def goto(self, value: int):
        delta = self.maxVal - self.minVal
        target = int(self.minVal + ((value / 1024) * delta))
        self.__pwm.duty_u16(target)

    def gotoDeg(self, value: int):
        diff = int(self.maxVal - self.minVal)
        oneDegree = int(diff / self.maxDegrees)
        self.__pwm.duty_u16(self.minVal + (oneDegree * value))

    def free(self):
        self.__pwm.duty_u16(0)
示例#17
0
def initialise(settings):
  global duty_cycle_max, duty_cycle_min, pwm_frequency
  global left_motor1, left_motor2, right_motor1, right_motor2
  global servo
  global i2c_bus

  if "duty_cycle_max" in settings:
    duty_cycle_max = int(settings["duty_cycle_max"])
  if "duty_cycle_min" in settings:
    duty_cycle_min = int(settings["duty_cycle_min"])
  if "pwm_frequency" in settings:
    pwm_frequency = int(settings["pwm_frequency"])

  left_motor1 = initialise_motor(settings, "left_motor_pin1")
  left_motor2 = initialise_motor(settings, "left_motor_pin2")
  right_motor1 = initialise_motor(settings, "right_motor_pin1")
  right_motor2 = initialise_motor(settings, "right_motor_pin2")

  servo_pin = Pin(settings["servo_pin"], Pin.OUT)
  servo = PWM(servo_pin)
  servo.freq(50) # Set 50Hz PWM
  servo.duty(77) # Off

  scl = settings["scl_pin"]
  sda = settings["sda_pin"]
  i2c_bus = machine.I2C(scl=machine.Pin(scl), sda=machine.Pin(sda))
示例#18
0
class Servo:
    def __init__(self, p, name):
        self.name = name
        self.port = p

        self.pin = Pin(p,Pin.OUT)
        self.pulser = PWM(self.pin)
        self.pulser.freq(50)

    def setRaw(self, value):
        print ("raw %s %d" % (self.name, value))
        self.pulser.duty(value)


    def setPercentage(self, angle):
        if angle > 90:
          angle = 90
          
        if angle < 0:
          angle = 0
          
        #33 - 130  33= top 130 = min
        val = (angle)+33
        val = int(val)
        print ("%s %d %d" % (self.name, angle, val))
        self.pulser.duty(val)
示例#19
0
class Motor:
    def __init__(self,in1,in2,pwm):
        self.pwm    = PWM(Pin(pwm))
        self.in1    = Pin(in1,Pin.OUT)
        self.in2    = Pin(in2,Pin.OUT)
        self.pwm.freq(1000)
        
    def aus(self):
        self.pwm.duty_u16(0)
        self.in1.off()
        self.in2.off()
    
    def vor(self,geschw):
        if geschw<0:
            self.back(geschw*(-1))
        if geschw>100:
            geschw=100
        self.in1.on()
        self.in2.off()
        self.pwm.duty_u16(650*geschw)
        
    def back(self,geschw):
        if geschw<=0:
            self.aus()
        if geschw>100:
            geschw=100
        self.in1.off()
        self.in2.on()
        self.pwm.duty_u16(650*geschw)
示例#20
0
class BuzzerDrum(AbstractInstrument, PikoPlatform):

    FREQ_NORMAL = 500
    FREQ_ACCENT = 800
    VOLUME = 150
    BEEP_LENGTH = 0.07

    pin = None

    def __init__(self, pin):
        super().__init__()
        self.pin = pin
        self.buzzer = PWM(Pin(self.pin))

    def playNormal(self, note):
        self.buzzer.freq(self.FREQ_NORMAL)
        self.buzzer.duty_u16(self.VOLUME)
        sleep(self.BEEP_LENGTH)
        self.buzzer.duty_u16(0)
        return self.BEEP_LENGTH

    def playAccent(self, note):
        self.buzzer.freq(self.FREQ_ACCENT)
        self.buzzer.duty_u16(self.VOLUME)
        sleep(self.BEEP_LENGTH)
        self.buzzer.duty_u16(0)
        return self.BEEP_LENGTH
示例#21
0
def onofflight():
    SWon = False
    while (1):
        buzzer = PWM(Pin(2))
        if SW.value() == 0 and SWon == False:
            SWon = True
            while (1):
                buzzer.freq(20)
                R.value(1)
                G.value(0)
                B.value(0)
                sleep(0.5)
                R.value(0)
                G.value(0)
                B.value(1)
                sleep(0.5)

                if SW.value() == 0:
                    break

        buzzer.deinit()
        R.value(0)
        G.value(0)
        B.value(0)
        SWon = False
示例#22
0
class GPIO():
	def __init__(self,pin,pulse=0):
		self.pin = pin
		self.pulse = pulse
		if pulse == 0:
			self.pin=Pin(self.pin,Pin.OUT)
			self.pin.value(0)
		elif pulse == 1:
			self.pin=PWM(Pin(self.pin),Pin.OUT)
			self.pin.freq(500)
               
        def on(self):
                self.pin.value(1)

        def off(self):
                self.pin.value(0)

        def toggle(self):
		self.pin.value(not self.pin.value())

	def repeat(self,n,t=0.5):
		for i in range(n):
			self.toggle()
			time.sleep(t)
		self.off()

	def scale(self,n):
                if n > 100:
                        n = 100
                elif n < 0:
                        n = 0
                percent = n*10
		self.pin.duty(percent)
		return (percent)

	def fade_in(self,step=5,t=0.1):
                for i in range(0,100,step):
                        self.scale(i)
                        time.sleep(t)
        def fade_out(self,step=5, t=0.1):
                for i in range(0,100,step):
                        self.scale(100-i)
                        time.sleep(t)
                self.scale(0)

        def help():
                print("")
                print("Cheat Sheet Wemos D1 Mini")
                print("-------------------------")
                print("                   ____________")
                print("                  /            |")
                print("             RST-|         =   |- TX")
                print("              A0-|   ESP8266   |- RX")
                print("NO PWM GPIO16 D0-|         SCL-|- D1 GPIO5")
                print("       GPIO14 D5-|-SCK     SDA-|- D2 GPIO4")
                print("       GPIO12 D6-|-MISO        |- D3 GPIO0 PullUp")
                print("       GPIO13 D7-|-MOSI        |- D4 GPIO2 PullUp Built-in Led")
                print("PullDn GPIO15 D8-|             |- G")
                print("             3v3-|_____________|- 5V")
                print("")
示例#23
0
class Servo:
    

    # This class holds the methods to control the servo motor 
    # A single instance of this class will be insantized during the lifetime of the main program

    def __init__(self):
        self.servo = PWM(Pin(config.pins["servo_pin"]))
        self.servo.freq(frequency) #This has to do with the servo expecting a pulse every 20ms
        self.servo.duty(smallDuty) 

    def changeSize(self, size):
        
        if size == 'big':
            self.servo.duty(bigDuty)

        elif size == 'small':
            self.servo.duty(smallDuty)
    
    #The following function will toggle between the sizes of the servo
    def toggleSize(self):

        if(self.servo.duty() == smallDuty):
            self.servo.duty(bigDuty)

        else:
            self.servo.duty(smallDuty)
示例#24
0
class PWMOut(object):
    """PWM output."""
    def __init__(self, pin, freq=50, duty=0, verbose=False, channel=-1):
        self._pin = PWM(Pin(pin))
        self._pin.freq(freq)
        self._pin.duty_u16(duty)
        self._verbose = verbose
        if self._verbose:
            self.__logFrequency()

    def deinit(self):
        self._pin.deinit()

    @property
    def duty_percent(self):
        """ duty in percent
    """
        return self._pin.duty_u16() / MAX_DUTY * 100

    @duty_percent.setter
    def duty_percent(self, value):
        self._pin.duty_u16(int(min(max(0, value / 100.0 * MAX_DUTY),
                                   MAX_DUTY)))

    @property
    def duty(self):
        """ duty as raw value
    """
        return self._pin.duty_u16()

    @duty.setter
    def duty(self, value):
        self._pin.duty_u16(int(value))

    @property
    def freq_Hz(self):
        """ frequency in [Hz]
    """
        return self._pin.freq()

    @freq_Hz.setter
    def freq_Hz(self, value):
        self._pin.freq(value)
        if self._verbose:
            self.__logFrequency()

    @property
    def max_duty(self):
        return MAX_DUTY

    @property
    def uses_rmt(self):
        return False

    def __logFrequency(self):
        print("PWM frequency is {0:.1f} kHz".format(self.freq_Hz / 1000))

    def __setRMTDuty(self, value):
        pass
示例#25
0
class PulseGenerator:
    def __init__(self):
        #self._pin = Pin(4, mode=Pin.OPEN_DRAIN, value=1, pull=Pin.PULL_DOWN)
        self._pin = Pin(4, mode=Pin.OUT, value=1, pull=Pin.PULL_DOWN)
        self._timer = None
        self._sleep_ms = 0
        self._pwm = None

    def reset(self):
        if self._timer is not None:
            self._timer.deinit()
            self._timer = None
        if self._pwm is not None:
            self._pwm.deinit()
            self._pwm = None
        self._pin.value(1)

    def run(self):
        while True:
            self.print_menu()
            try:
                value = int(input('Enter selection: '))
                selected = OPTIONS[value]
            except Exception:
                print('Invalid input')
                continue
            self.reset()
            if selected[0] == 0 and selected[1] == 0:
                self.reset()
            elif selected[0] == 0:
                self.handle_slow(selected[1])
            else:
                self.handle_fast(selected[1])
            print('Set to: %s' % selected[2])

    def print_menu(self):
        for idx, item in enumerate(OPTIONS):
            print('%d) %s' % (idx, item[2]))

    def handle_fast(self, freq):
        self._pwm = PWM(self._pin)
        self._pwm.freq(freq)
        self._pwm.duty(512)

    def handle_slow(self, sleep_ms):
        self._sleep_ms = sleep_ms
        self._timer = Timer(0)
        self._timer.init(period=self._sleep_ms,
                         mode=Timer.ONE_SHOT,
                         callback=self.slow_timer_callback)
        self.slow_timer_callback()

    def slow_timer_callback(self, *args):
        self._pin.value(0)
        sleep_ms(2)
        self._pin.value(1)
        self._timer.init(period=self._sleep_ms,
                         mode=Timer.ONE_SHOT,
                         callback=self.slow_timer_callback)
示例#26
0
class Motor:
    class MotorDirection(enumerate):
        FORWARD = 1
        REVERSE = 0

    def __init__(self,
                 pin_dir,
                 pin_speed,
                 duty_ratio=65535,
                 reverse_sense=False):
        self._pin_dir = pin_dir
        self._pin_dir.init(Pin.OUT)
        self._pin_dir.off()

        self._pin_speed = pin_speed
        self._pwm = PWM(self._pin_speed)
        self._pwm.duty_u16(0)
        self._pwm.freq(1000)

        if reverse_sense:
            self._rev_sense = True
        else:
            self._rev_sense = False

        self._duty_ratio = duty_ratio
        self._dir = self.MotorDirection.FORWARD

    def set_direction(self, dir):
        if dir != self.MotorDirection.FORWARD and dir != self.MotorDirection.REVERSE:
            return

        if self.MotorDirection.FORWARD == dir:
            if self._rev_sense:
                self._dir = self.MotorDirection.REVERSE
            else:
                self._dir = self.MotorDirection.FORWARD
        else:
            if self._rev_sense:
                self._dir = self.MotorDirection.FORWARD
            else:
                self._dir = self.MotorDirection.REVERSE

        if self._dir == self.MotorDirection.FORWARD:
            self._pin_dir.on()
        else:
            self._pin_dir.off()

    def set_speed(self, duty):
        if duty < 0 or duty > 100:
            return
        duty = round(duty / 100 * self._duty_ratio)
        self._pwm.duty_u16(duty)

    def on(self, direction, duty):
        self.set_direction(direction)
        self.set_speed(duty)

    def off(self):
        self.set_speed(0)
示例#27
0
class MPythonPin():
    def __init__(self, pin, mode=PinMode.IN, pull=None):
        if mode not in [PinMode.IN, PinMode.OUT, PinMode.PWM, PinMode.ANALOG]:
            raise TypeError("mode must be 'IN, OUT, PWM, ANALOG'")
        if pin == 4:
            raise TypeError("P4 is used for light sensor")
        if pin == 10:
            raise TypeError("P10 is used for sound sensor")
        try:
            self.id = pins_remap_esp32[pin]
        except IndexError:
            raise IndexError("Out of Pin range")
        if mode == PinMode.IN:
            if pin in [3]:
                raise TypeError('IN not supported on P%d' % pin)
            self.Pin = Pin(self.id, Pin.IN, pull)
        if mode == PinMode.OUT:
            if pin in [2, 3]:
                raise TypeError('OUT not supported on P%d' % pin)
            self.Pin = Pin(self.id, Pin.OUT, pull)
        if mode == PinMode.PWM:
            if pin not in [
                    0, 1, 5, 6, 7, 8, 9, 11, 13, 14, 15, 16, 19, 20, 23, 24,
                    25, 26, 27, 28
            ]:
                raise TypeError('PWM not supported on P%d' % pin)
            self.pwm = PWM(Pin(self.id), duty=0)
        if mode == PinMode.ANALOG:
            if pin not in [0, 1, 2, 3, 4, 10]:
                raise TypeError('ANALOG not supported on P%d' % pin)
            self.adc = ADC(Pin(self.id))
            self.adc.atten(ADC.ATTN_11DB)
        self.mode = mode

    def irq(self, handler=None, trigger=Pin.IRQ_RISING):
        if not self.mode == PinMode.IN:
            raise TypeError('the pin is not in IN mode')
        return self.Pin.irq(handler, trigger)

    def read_digital(self):
        if not self.mode == PinMode.IN:
            raise TypeError('the pin is not in IN mode')
        return self.Pin.value()

    def write_digital(self, value):
        if not self.mode == PinMode.OUT:
            raise TypeError('the pin is not in OUT mode')
        self.Pin.value(value)

    def read_analog(self):
        if not self.mode == PinMode.ANALOG:
            raise TypeError('the pin is not in ANALOG mode')
        return self.adc.read()

    def write_analog(self, duty, freq=1000):
        if not self.mode == PinMode.PWM:
            raise TypeError('the pin is not in PWM mode')
        self.pwm.freq(freq)
        self.pwm.duty(duty)
示例#28
0
def stop(pin=27):
    from machine import Pin, PWM
    try:
        pwm = PWM(Pin(pin))
        pwm.duty(0)
        pwm.freq(1)
    finally:
        pwm.deinit()
示例#29
0
def kick():
    motor = PWM(Pin(16))
    motor.freq(50)
    motor.duty(25)

    time.sleep(1)

    motor.duty(0)
示例#30
0
def stop(pin=27):
    from machine import Pin, PWM
    try:
        pwm = PWM(Pin(pin))
        pwm.duty(0)
        pwm.freq(1)
    finally:
        pwm.deinit()
示例#31
0
def tone(frequency, duration=100, pin=None, volume=1):
    if pin is None:
        pin = Pin(SPEAKER_PIN)

    pwm = PWM(pin, duty=volume % 50)
    pwm.freq(frequency)
    time.sleep_ms(duration)
    pwm.deinit()
示例#32
0
 async def _blink(self, led: PWM) -> None:
     """ Blink led 3 times and wait
     """
     led.freq(10)
     led.duty(round(self.rgb_intensity / self.INTENSITY_MAX_SCALE * 100, 2))
     await asyn.sleep(0.3, 10)
     led.duty(0)
     await asyn.sleep(0.2, 10)
示例#33
0
def pitch(freq,pin=27,tim=1000):
 from machine import Pin,PWM
 from utime import sleep_ms
 try:
  pwm=PWM(Pin(pin))
  pwm.freq(freq)
  pwm.duty(tim)
  sleep_ms(tim)
 finally:
  pwm.deinit()
示例#34
0
文件: music.py 项目: radiumray/mdxly
 def pitch(self,pin=27,freq=440,tim=0):
  from machine import Pin,PWM
  from utime import sleep_ms
  pwm=PWM(Pin(pin))
  if freq>0:
   pwm.freq(int(freq))
  else:
   pwm.duty(0)
  if tim>0:
   sleep_ms(tim)
   pwm.deinit()
示例#35
0
class MPythonPin(Pin):
    def __init__(self, pin, mode=PinMode.IN):
        if mode not in [PinMode.IN, PinMode.OUT, PinMode.PWM, PinMode.ANALOG]:
            raise TypeError("mode must be 'IN, OUT, PWM, ANALOG'")
        if pin == 3:
            raise TypeError("pin3 is used for resistance sensor")
        if pin == 4:
            raise TypeError("pin4 is used for light sensor")
        if pin == 10:
            raise TypeError("pin10 is used for sound sensor")
        self.id = pins_remap_esp32[pin]
        if mode == PinMode.IN:
            super().__init__(self.id, Pin.IN, Pin.PULL_UP)
        if mode == PinMode.OUT:
            if pin == 2:
                raise TypeError('pin2 only can be set "IN, ANALOG"')
            super().__init__(self.id, Pin.OUT)
        if mode == PinMode.PWM:
            if pin == 2:
                raise TypeError('pin2 only can be set "IN, ANALOG"')
            self.pwm = PWM(Pin(self.id), duty=0)
        if mode == PinMode.ANALOG:
            if pin not in [0, 1, 2, 3, 4, 10]:
                raise TypeError('the pin can~t be set as analog')
            self.adc = ADC(Pin(self.id))
            self.adc.atten(ADC.ATTN_11DB)
        self.mode = mode

    def read_digital(self):
        if not self.mode == PinMode.IN:
            raise TypeError('the pin is not in IN mode')
        return super().value()

    def write_digital(self, value):
        if not self.mode == PinMode.OUT:
            raise TypeError('the pin is not in OUT mode')
        super().value(value)

    def read_analog(self):
        if not self.mode == PinMode.ANALOG:
            raise TypeError('the pin is not in ANALOG mode')
        return self.adc.read()

    def write_analog(self, duty, freq=1000):
        if not self.mode == PinMode.PWM:
            raise TypeError('the pin is not in PWM mode')        
        self.pwm.freq(freq)
        self.pwm.duty(duty)
示例#36
0
文件: music.py 项目: radiumray/mdxly
 def play(self,tune,pin=27,duration=None):
  from machine import Pin,PWM
  from utime import sleep_ms
  pwm=PWM(Pin(pin))
  if duration is None:
   self.set_default(tune[0])
  else:
   self.set_duration(duration)
  for tone in tune:
   tone=tone.upper()
   if tone[0]not in Letter:
    continue
   midi=self.midi(tone)
   pwm.freq(midi[0])
   sleep_ms(midi[1])
  pwm.deinit()
示例#37
0
class Buzz(object):
 def __init__(self,pin=6):
  self.id=pins_remap_esp32[pin]
  self.io=Pin(self.id)
  self.io.value(1)
  self.isOn=False
 def on(self,freq=500):
  if self.isOn is False:
   self.pwm=PWM(self.io,freq,512)
   self.isOn=True
 def off(self):
  if self.isOn:
   self.pwm.deinit()
   self.io.init(self.id,Pin.OUT)
   self.io.value(1)
   self.isOn=False
 def freq(self,freq):
  self.pwm.freq(freq)
示例#38
0
def play(tune,pin=27,duration=None):
 from machine import Pin,PWM
 from utime import sleep_ms
 try:
  pwm=PWM(Pin(pin))
  if duration is None:
   set_default(tune[0])
  else:
   set_duration(duration)
  for tone in tune:
   tone=tone.upper()
   if tone[0]not in Letter:
    continue
   m=midi(tone)
   pwm.freq(m[0])
   pwm.duty(m[1])
   sleep_ms(m[1])
 finally:
  pwm.deinit()
示例#39
0
文件: music.py 项目: radiumray/mdxly
 def play_show(self,tune,pin=27,display=matrix.display,duration=None):
  from machine import Pin,PWM
  from utime import sleep_ms
  pwm=PWM(Pin(pin))
  if duration is None:
   self.set_default(tune[0])
  else:
   self.set_duration(duration)
  for tone in tune:
   tone=tone.upper()
   if tone[0]not in Letter:
    continue
   if len(tone)==4:
    display.showstatic(tone.replace(":",""))
   else:
    display.showstatic(tone)
   midi=self.midi(tone)
   pwm.freq(midi[0])
   sleep_ms(midi[1])
  display.clear()
  pwm.deinit()
示例#40
0
文件: music.py 项目: radiumray/mdxly
 def stop(self, pin=27):
     from machine import Pin, PWM
     pwm = PWM(Pin(pin))
     pwm.duty(0)
     pwm.freq(1)
     pwm.deinit()
示例#41
0
文件: servo.py 项目: radiumray/mdxly
def servo_write_angle(pin,angle):
	pwm=PWM(Pin(pin))
	pwm.duty(int(40 + 75 * angle / 180))
	pwm.freq(50)