예제 #1
0
파일: main.py 프로젝트: bbk012/uPyBot
 def __init__(self):
     self._tmr2 = Timer(2, freq=20000,
                        mode=Timer.CENTER)  #used for PWM for motor control
     self._ch1 = self._tmr2.channel(1,
                                    Timer.PWM,
                                    pin=Pin.board.X1,
                                    pulse_width=(self._tmr2.period() + 1) //
                                    2)
     self._ch4 = self._tmr2.channel(4,
                                    Timer.PWM,
                                    pin=Pin.board.X4,
                                    pulse_width=(self._tmr2.period() + 1) //
                                    2)
     self._us_tmr = Timer(
         3, prescaler=83,
         period=0x3fffffff)  #used to measure US sensor pulse duration
     self._pin_in1 = Pin(Pin.board.X3, Pin.OUT_PP)  #motor control pins
     self._pin_in2 = Pin(Pin.board.X2, Pin.OUT_PP)
     self._pin_in3 = Pin(Pin.board.X5, Pin.OUT_PP)
     self._pin_in4 = Pin(Pin.board.X6, Pin.OUT_PP)
     self._pin_int7 = Pin(Pin.board.X7, Pin.IN)  #encoder interrupt pins
     self._pin_int8 = Pin(Pin.board.X8, Pin.IN)
     self._pin_trigger = Pin(Pin.board.X11, Pin.OUT_PP)  #US trig pin
     self._pin_echo = Pin(Pin.board.X12, Pin.IN)  #US echo pin
     self._pin_beep = Pin(Pin.board.X19, Pin.OUT_PP)  #beeper ctrl pin
     self._beeper = Beeper(self._pin_beep)
     self._left_motor = Motor(self._pin_in1, self._pin_in2, self._ch1)
     self._left_encoder = Encoder(self, self._pin_int7)
     self._right_motor = Motor(self._pin_in4, self._pin_in3, self._ch4)
     self._right_encoder = Encoder(self, self._pin_int8)
     self._us = UltraSonicSensor(self._pin_trigger, self._pin_echo,
                                 self._us_tmr)
예제 #2
0
def main():
    # Configure timer2 as a microsecond counter.
    tim = Timer(config["timer"],
                prescaler=(machine.freq()[0] // 1000000) - 1,
                period=config["timer-period"])
    tim2 = Timer(config["led-timer"], freq=config["led-freq"])
    tim2.callback(lambda t: pyb.LED(config["led-id"]).toggle())

    # Configure channel for timer IC.
    ch = tim.channel(1,
                     Timer.IC,
                     pin=config["pin-capture"],
                     polarity=Timer.FALLING)

    # Slave mode disabled in order to configure
    mem32[config["timer-addr"] + TIM_SMCR] = 0

    # Reset on rising edge (or falling in case of inverted detection). Ref: 25.4.3 of STM32F76xxx_reference_manual.pdf
    mem32[config["timer-addr"] +
          TIM_SMCR] = (mem32[config["timer-addr"] + TIM_SMCR]
                       & 0xfffe0000) | 0x54

    # Capture sensitive to rising edge. Ref: 25.4.9 of STM32F76xxx_reference_manual.pdf
    mem32[config["timer-addr"] + TIM_CCER] = 0b1011

    print("capturing")
    capture(ch)
예제 #3
0
 def __init__(self, pin, cfreq, asize, duty, verbose):
     if ESP32:
         self._rmt = RMT(0,
                         pin=pin,
                         clock_div=80,
                         carrier_freq=cfreq,
                         carrier_duty_percent=duty)  # 1μs resolution
     elif RP2:  # PIO-based RMT-like device
         self._rmt = RP2_RMT(pin_pulse=None,
                             carrier=(pin, cfreq, duty))  # 1μs resolution
     else:  # Pyboard
         if not IR._active_high:
             duty = 100 - duty
         tim = Timer(2,
                     freq=cfreq)  # Timer 2/pin produces 36/38/40KHz carrier
         self._ch = tim.channel(1, Timer.PWM, pin=pin)
         self._ch.pulse_width_percent(self._space)  # Turn off IR LED
         # Pyboard: 0 <= pulse_width_percent <= 100
         self._duty = duty
         self._tim = Timer(5)  # Timer 5 controls carrier on/off times
     self._tcb = self._cb  # Pre-allocate
     self._arr = array('H', 0 for _ in range(asize))  # on/off times (μs)
     self._mva = memoryview(self._arr)
     # Subclass interface
     self.verbose = verbose
     self.carrier = False  # Notional carrier state while encoding biphase
     self.aptr = 0  # Index into array
예제 #4
0
파일: NTSC.py 프로젝트: pramasoul/pyb-ntsc
 def redac(self):
     self.dac = DAC(Pin('X5'),buffering=self.buffer_dac)
     self.bmv = memoryview(self.buf)[:len(self)]
     self.dac_tim = Timer(6, freq=int(self.hres*1000000/self.line_time))
     self.dac.write_timed(self.bmv,self.dac_tim,mode=DAC.CIRCULAR)
     self.frame_tim = Timer(5, prescaler=self.dac_tim.prescaler(),period=self.dac_tim.period()*len(self))
     self.frame_tim.counter(self.phase)
예제 #5
0
  def __init__(self, X=True) :
    if X :
      self.pwmpin = Pin('X6', Pin.OUT_PP)
      self.pwmtim = Timer(2, freq=5000)
      self.pwm = self.pwmtim.channel(1, mode=Timer.PWM, pin=self.pwmpin)
      self.pwm.pulse_width(0)
      self.dir = Pin('X2', Pin.OUT_PP)
      self.dir.off()          # O = forward, 1 = reverse
      self.sleep = Pin('X3', Pin.OUT_PP)
      self.sleep.value(0)        # 0 = sleep, 1 = active
      self.enca = Pin('X4', Pin.IN, Pin.PULL_UP)
      self.encb = Pin('X5', Pin.IN, Pin.PULL_UP)
    else :
      self.pwmpin = Pin('Y1', Pin.OUT_PP)
      self.pwmtim = Timer(8, freq=5000)
      self.pwm = self.pwmtim.channel(1, mode=Timer.PWM, pin=self.pwmpin)
      self.pwm.pulse_width(0)
      self.dir = Pin('Y2', Pin.OUT_PP)
      self.dir.off()          # O = forward, 1 = reverse
      self.sleep = Pin('Y3', Pin.OUT_PP)
      self.sleep.value(0)        # 0 = sleep, 1 = active
      self.enca = Pin('Y4', Pin.IN, Pin.PULL_UP)
      self.encb = Pin('Y5', Pin.IN, Pin.PULL_UP)
    self.pwmscale = (self.pwmtim.period() + 1) // 10000 # scale factot for permyriad(10000 as it allows to get more distinct points and avoid divisions) power
    self.count_a = 0      # counter for impulses on the A output of the encoder
    self.target_a = 0     # target value for the A counter (for controlled rotation)
    self.count_b = 0      # counter for impulses on the B output of the encoder
    self.time_a = 0       # last time we got an impulse on the A output of the encoder
    self.time_b = 0       # last time we got an impulse on the B output of the encoder
    self.elapsed_a_b = 0  # time elapsed between an impulse on A and an impulse on B
    self.dirsensed = 0    # direction sensed through the phase of the A and B outputs
    self.rpm = 0          # current speed in rotations per second
    self.rpm_last_a = 0   # value of the A counter when we last computed the rpms
    self.cruise_rpm = 0   # target value for the rpms
    self.walking = False  # Boolean that indicates if the robot is walking or stationary
    self.desiredDir = True# Boolean that indecates the desired direction of the motor for move function


    self._control = PID() # PID control for the rotation of the wheels
    self._control.setTunings(KP, KI, KD);
    self._control.setSampleTime(1);
    self._control.setOutputLimits(-10000, 10000)

    self._control_distance = PID() # PID control for the cascade of the distance
    self._control_distance.setTunings(KP_DISTANCE, KI_DISTANCE, KD_DISTANCE);
    self._control_distance.setSampleTime(1);
    self._control_distance.setOutputLimits(-MAXIMUM_VELOCITY, MAXIMUM_VELOCITY)


    ExtInt(self.enca, ExtInt.IRQ_RISING, Pin.PULL_UP, self.enca_handler)
    ExtInt(self.encb, ExtInt.IRQ_RISING, Pin.PULL_UP, self.encb_handler)
    if RomiMotor.rpmtimer is None :   # create only one shared timer for all instances
      RomiMotor.rpmtimer = Timer(4)
      RomiMotor.rpmtimer.init(freq=100, callback=RomiMotor.class_rpm_handler)
    RomiMotor.rpm_handlers.append(self.rpm_handler) # register the handler for this instance
예제 #6
0
def main():
    pwm_timer = Timer(MOTOR_TIMER, freq=PWM_FREQ)

    ch1 = motorController(PIN_CH1, pwm_timer, 1)
    ch2 = motorController(PIN_CH2, pwm_timer, 2)

    adc = ADC(PIN_ADC)
    main_loop = loop(adc, ch1, ch2)

    event_timer = Timer(EVENT_TIMER, freq=1000)
    event_timer.freq(10)
    event_timer.callback(lambda t: next(main_loop))
예제 #7
0
def move_motor1(right, left):

    #W16 has Timer2, Channel1
    Apwm = Pin('W16')
    timerA = Timer(2, freq=1000)
    chA = timerA.channel(1, Timer.PWM, pin=Apwm)

    Ain1 = Pin('W22', Pin.OUT_PP)
    Ain2 = Pin('W24', Pin.OUT_PP)

    standBy = Pin('W29', Pin.OUT_PP)

    #W29 has Timer1, Channel3
    Bpwm = Pin('Y12')
    timerB = Timer(1, freq=1000)
    chB = timerB.channel(3, Timer.PWM, pin=Bpwm)

    Bin1 = Pin('W30', Pin.OUT_PP)
    Bin2 = Pin('W32', Pin.OUT_PP)

    def clockwise(motor, speed):
        if motor == 'a':
            Ain1.high()
            Ain2.low()
            chA.pulse_width_percent(speed)
        elif motor == 'b':
            Bin1.high()
            Bin2.low()
            chB.pulse_width_percent(100 - speed)

    def stop(motor):
        if motor == 'a':
            Ain1.low()
            Ain2.low()
            chA.pulse_width_percent(0)
        elif motor == 'b':
            Bin1.low()
            Bin2.low()
            chB.pulse_width_percent(0)

    def main():
        standBy.high()
        while (True):
            stop('a')
            stop('b')
            clockwise('a', 50)
            clockwise('b', 50)
            utime.sleep_ms(2500)
            break
            utime.sleep(1)

    main()
예제 #8
0
 def __init__(self):
     #设定Pin
     self._rForward = Pin('B8')
     self._rBackward = Pin('B9')
     self._lForward = Pin('B14')
     self._lBackward = Pin('B15')
     #set right motor pwm
     self._rTim = Timer(4, freq=3000)
     self._rf_ch = self._rTim.channel(3, Timer.PWM, pin=self._rForward)
     self._rb_ch = self._rTim.channel(4, Timer.PWM, pin=self._rBackward)
     #set left motor pwm
     self._lTim = Timer(12, freq=3000)
     self._lf_ch = self._lTim.channel(1, Timer.PWM, pin=self._lForward)
     self._lb_ch = self._lTim.channel(2, Timer.PWM, pin=self._lBackward)
예제 #9
0
 def __init__(self, dc1, dc2):
     self.m1 = Timer(12, freq=100000).channel(1,
                                              Timer.PWM,
                                              pin=Pin('Y7'),
                                              pulse_width=0)
     self.dc1 = dc1
     self.f1 = Pin("Y5", pyb.Pin.OUT_PP)
     self.b1 = Pin("Y6", pyb.Pin.OUT_PP)
     self.m2 = Timer(12, freq=100000).channel(2,
                                              Timer.PWM,
                                              pin=Pin('Y8'),
                                              pulse_width=0)
     self.dc2 = dc2
     self.f2 = Pin("X20", pyb.Pin.OUT_PP)
     self.b2 = Pin("X19", pyb.Pin.OUT_PP)
예제 #10
0
    def __init__(self, use_20khz_pwm=False):
        self.dir_l = Pin(DIR_L, Pin.OUT)
        self.dir_r = Pin(DIR_R, Pin.OUT)
        self.pwm_l = Pin(PWM_L, Pin.OUT)
        self.pwm_r = Pin(PWM_R, Pin.OUT)

        self.tim_r = Timer(4, freq=1000 if not (use_20khz_pwm) else 20000)
        self.ch_r = self.tim_r.channel(2, Timer.PWM, pin=self.pwm_r)
        self.tim_l = Timer(14, freq=500 if not (use_20khz_pwm) else 20000)
        self.ch_l = self.tim_l.channel(1, Timer.PWM, pin=self.pwm_l)

        self.flipLeft = False
        self.flipRight = False

        initialized = True  # This class is always initialised and doens't need to initialised before
예제 #11
0
 def __init__(
     self,
     clk_pin="X1",
     dt_pin="X2",
     switch_pin="X4",
     pwm_pin="X3",
     timer=2,
     channel=3,
 ):
     """
     Establish pin functions, create rotary control and initialise tick
     response.
     """
     self.switch_pin = Pin(switch_pin, mode=Pin.IN, pull=Pin.PULL_UP)
     self.pwm_pin = Pin(pwm_pin)  # X3 has TIM2, CH3 on PyBoard
     self.tim = Timer(timer, freq=1000)
     self.pwm_ch = self.tim.channel(channel, Timer.PWM, pin=self.pwm_pin)
     self.pwm_ch.pulse_width_percent(0)
     self.r = RotaryIRQ(
         clk_pin,
         dt_pin,
         max_val=MAX_SETTING,
         reverse=True,
         range_mode=RotaryIRQ.RANGE_BOUNDED,
     )
     self.on_off_count = self.current = 0  # Always fade up at power on
     self.target = INITIAL_TARGET
     self.running = True
     self.incr = 1
     self.r.set(value=self.target)
예제 #12
0
def motor_control():
	# define various I/O pins for ADC
	adc_1 = ADC(Pin('X19'))
	adc_2 = ADC(Pin('X20'))

	# set up motor with PWM and timer control
	A1 = Pin('Y9',Pin.OUT_PP)
	A2 = Pin('Y10',Pin.OUT_PP)
	pwm_out = Pin('X1')
	tim = Timer(2, freq = 1000)
	motor = tim.channel(1, Timer.PWM, pin = pwm_out)
	
	A1.high()	# motor in brake position
	A2.high()

	# Calibrate the neutral position for joysticks
	MID = adc_1.read()		# read the ADC 1 value now to calibrate
	DEADZONE = 10	# middle position when not moving
	
	# Use joystick to control forward/backward and speed
	while True:				# loop forever until CTRL-C
		speed = int(100*(adc_1.read()-MID)/MID)
		if (speed >= DEADZONE):		# forward
			A1.high()
			A2.low()
			motor.pulse_width_percent(speed)
		elif (speed <= -DEADZONE):
			A1.low()		# backward
			A2.high()
			motor.pulse_width_percent(-speed)
		else:
			A1.low()		# stop
			A2.low()		
예제 #13
0
    def __init__(self):

        # set up motor with PWM and timer control
        self.A1 = Pin('X3', Pin.OUT_PP)  # A is right motor
        self.A2 = Pin('X4', Pin.OUT_PP)
        self.B1 = Pin('X7', Pin.OUT_PP)  # B is left motor
        self.B2 = Pin('X8', Pin.OUT_PP)
        self.PWMA = Pin('X1')
        self.PWMB = Pin('X2')
        self.speed = 0  # +100 full speed forward, -100 full speed back
        self.turn = 0  # turn is +/-100; 0 = left/right same speed,
        # ... +50 = left at speed, right stop, +100 = right back full
        # Configure counter 2 to produce 1kHz clock signal
        self.tim = Timer(2, freq=1000)
        # Configure timer to provide PWM signal
        self.motorA = self.tim.channel(1, Timer.PWM, pin=self.PWMA)
        self.motorB = self.tim.channel(2, Timer.PWM, pin=self.PWMB)
        self.lsf = 0  # left motor speed factor +/- 1
        self.rsf = 0  # right motor speed factor +/- 1
        self.countA = 0  # speed pulse count for motorA
        self.countB = 0  # speed pulse count for motorB
        self.speedA = 0  # actual speed of motorA
        self.speedB = 0  # actual speed of motorB

        # Create external interrupts for motorA and motorB Hall Effect Senors
        self.motorA_int = pyb.ExtInt('Y4', pyb.ExtInt.IRQ_RISING,
                                     pyb.Pin.PULL_NONE, self.isr_motorA)
        self.motorB_int = pyb.ExtInt('Y6', pyb.ExtInt.IRQ_RISING,
                                     pyb.Pin.PULL_NONE, self.isr_motorB)
        self.speed_timer = pyb.Timer(8, freq=10)
        self.speed_timer.callback(self.isr_speed_timer)
예제 #14
0
 def __init__(self):
     global __bz_pin, __bz_tim, __bz_ch
     if not (__bz_pin):
         # Initialize timer and channels if not yet done
         __bz_pin = Pin("S5")  # Broche S5 avec timer 4 et Channel 3
         __bz_tim = Timer(4, freq=3000)
         __bz_ch = __bz_tim.channel(3, Timer.PWM, pin=__bz_pin)
예제 #15
0
    def start(self, speed, direction):
        """ method to start a motor
        Arguments:
          speed : speed of the motor 0-100 (as percentage of max)
          direction : CW or CCW, for clockwise or counterclockwise
        """

        PWMpin = Pin(self.PWMpin)
        DIRpin = Pin(self.DIRpin, Pin.OUT_PP)
        # DIR1 and DIR2 have to be opposite to move, toggle to change direction
        if direction in ('cw','CW','clockwise'):
            DIRpin.high()

        elif direction in ('ccw','CCW','counterclockwise'):
            DIRpin.low()

        else:
            raise ValueError('Please enter CW or CCW for direction.')

        # Start the motor
        if 0 <= speed <= 100:
            # self.PWMpin = Pin('X4')
            tim = Timer(self.timer_id, freq=1000)
            ch = tim.channel(self.channel_id, Timer.PWM, pin=PWMpin)
            ch.pulse_width_percent(speed)
            # PWM.start(self.PWMpin, speed)
        else:
            raise ValueError("Please enter speed between 0 and 100")

        # set the status attributes
        self.isRunning = True
        self.currentDirection = direction
        self.currentSpeed = speed
예제 #16
0
    def __init__(self,
                 pin="X8",
                 timer_id=1,
                 channel_id=1,
                 callback=None,
                 platform=None):

        if not platform:
            platform = sys.platform

        self.platform = platform

        if platform == "esp8266":
            from machine import PWM, Pin
            self.buzzer_pin = PWM(Pin(pin, Pin.OUT), freq=1000)

        elif platform == "pyboard":
            import pyb
            from pyb import Pin, Timer
            self.pyb = pyb
            self.sound_pin = Pin(pin)
            self.timer = Timer(timer_id, freq=10000)
            self.channel = self.timer.channel(1,
                                              Timer.PWM,
                                              pin=self.sound_pin,
                                              pulse_width=0)

        self.callback = callback
예제 #17
0
def main():
    ## 创建测试磁场对象,统一分配引脚
    tiny = pyb.Pin('X1', pyb.Pin.OUT_PP)  # 对应小电阻,  接CM1
    big = pyb.Pin('X2', pyb.Pin.OUT_PP)  # 对应大电阻,  接CM2
    rw = resistSwitch(big_resist_pin=big, tiny_resist_pin=tiny)

    bufs = generate_bufs()
    record_sig = syncSignal(pyb.Pin('X3', pyb.Pin.OUT_PP))  # X3 对应光耦IN1
    sync_sig = syncSignal(pyb.Pin('X4', pyb.Pin.OUT_PP))  # X4 对应光耦IN2

    freqs = [10]
    ch = 1  # X5 标定磁场输出
    repeat = 20
    timer_num = 6
    mctrl = magCtrl(bufs, freqs, ch, sync_sig, rw, repeat, timer_num)

    record_sig.falling_edge()  # 发送启动记录的信号
    led = ledCue()

    ## timer3,用于循环测试
    tim3 = Timer(3)
    tim3.init(freq=0.1)
    tim3.callback(mctrl.next)

    while not mctrl.end_flg:
        if mctrl.new_block:
            led.next(mctrl.stimulus_typ)
            mctrl.new_block = False
        time.sleep_us(500000)  # 每50ms

    record_sig.falling_edge()  # 发送结束记录的信号
    led.end()
예제 #18
0
    def __init__(self):
        #Defines the pins which the infrared sensors are connected to
        self.IR1 = Pin('X9', Pin.IN)
        self.IR2 = Pin('X10', Pin.IN)

        #sets up the timer
        self.tim = Timer(2, freq=1000)

        #Defines the pins that motor A is connected to
        self.A1 = 'Y9'
        self.A2 = 'Y10'
        self.PWMA = 'X1'
        self.chanA = 1
        self.motorA = Motor(self.A1, self.A2, self.PWMA, self.chanA)

        #Defines the pins which motor B is connected to
        self.B1 = 'Y11'
        self.B2 = 'Y12'
        self.PWMB = 'X2'
        self.chanB = 2
        self.motorB = Motor(self.B1, self.B2, self.PWMB, self.chanB)

        #Initial speed of the robot
        self.speed = 50

        #Initial state of the path
        self.pathBlocked = False

        #Defines the speed at which the robot rotate
        self.ROTATION_SPEED = 50

        #The pin which is connected to the potentiometer
        self.pot = ADC(Pin('X8'))
예제 #19
0
    def pwm(self, pin_name, duty_percent=0):
        """ Create or retreive a PwmPin object based on its pin_name. duty_percent can be used for initial duty_cycle initialization  """
        if pin_name in self.pins:
            # released pin ?
            if self.pins[pin_name].pin.mode() == Pin.IN:
                del (self.pins[pin_name])  # So pin will be recreated
            else:
                return self.pins[pin_name]

        # Create the needed ressources and associated PwmPin
        if not (pin_name in PWM_DEFS):
            raise PwmException("Pin %s not supported by pwm library" %
                               pin_name)
        pwm_def = PWM_DEFS[pin_name]

        # create the pin
        _pin = Pin(pin_name)
        # retreive initialized timer
        if not (pwm_def[0] in self.timers):
            self.timers[pwm_def[0]] = Timer(pwm_def[0], freq=self.freq)
        _timer = self.timers[pwm_def[0]]
        # each of the PinPwm instance (PWM output) uses its own channel, so no need to check for existence
        _channel = _timer.channel(pwm_def[1], pwm_def[2],
                                  pin=_pin)  # Timer, channel, pin
        _channel.pulse_width_percent(duty_percent)
        # register the PwmPin
        self.pins[pin_name] = PwmPin(_pin, _timer, _channel)
        return self.pins[pin_name]
예제 #20
0
    def __init__(self, pin, timer=None, length=None, freq=None):
        timers = af_map['P' + pin.name()]
        if not timers:
            raise PwmError("Pin does not support PWM.")

        if not timer:
            timer = 'TIM'
        for af, name in timers:
            if name.startswith(timer):
                timer_af, timer_name = af, name
                timer_full, channel = timer_name.split('_')
                if channel.startswith('CH'):
                    break
        else:
            raise PwmError("Pin does not support timer %s" % timer)

        if length:
            freq = 1000000 / length
        elif not freq:
            freq = 50
        pin.init(Pin.OUT, alt=af)
        self.timer = Timer(int(timer_full[3:]), freq=freq)
        self.channel = self.timer.channel(
            int(channel[2:3]),
            Timer.PWM_INVERTED if channel.endswith('N') else Timer.PWM,
            pin=pin)

        self.length = 1000000 / self.timer.freq()
        self.duty(0)
예제 #21
0
def main():
    # Configure the timer as a microsecond counter.
    tim = Timer(config["timer"],
                prescaler=(machine.freq()[0] // 1000000) - 1,
                period=config["timer-period"])
    print(tim)

    # Configure channel for timer IC.
    ch = tim.channel(1,
                     Timer.IC,
                     pin=config["pin-capture"],
                     polarity=Timer.FALLING)

    # Slave mode disabled in order to configure
    mem32[config["timer-addr"] + TIM_SMCR] = 0

    # Reset on rising edge (or falling in case of inverted detection). Ref: 25.4.3 of STM32F76xxx_reference_manual.pdf
    mem32[config["timer-addr"] +
          TIM_SMCR] = (mem32[config["timer-addr"] + TIM_SMCR]
                       & 0xfffe0000) | 0x54

    # Capture sensitive to rising edge. Ref: 25.4.9 of STM32F76xxx_reference_manual.pdf
    mem32[config["timer-addr"] + TIM_CCER] = 0b1001

    try:
        capture(ch, 50)

    finally:
        tim.deinit()
예제 #22
0
    def start(self, speed, direction):
        PWM_py_pin = Pin(self.PWMpin)
        DIR_py_pin = Pin(self.DIRpin, Pin.OUT_PP)

        tim = Timer(self.timer_id, freq=1000)
        ch = tim.channel(self.channel_id, Timer.PWM, pin=PWM_py_pin)

        if direction in ('cw', 'CW', 'clockwise'):
            DIR_py_pin.high()

        elif direction in ('ccw', 'CCW', 'counterclockwise'):
            DIR_py_pin.low()

        else:
            raise ValueError('Please enter CW or CCW')

        if 0 <= speed <= 100:
            ch.pulse_width_percent(speed)

        else:
            raise ValueError("Please enter a speed between 0 and 100")

        self.isRunning = True
        self.currentDirection = direction
        self.currentSpeed = speed
예제 #23
0
 def init_loop_timer(self, timer_number):
     self.rollover = 0
     self.loop_timer_period = 0xffff
     self.loop_timer = Timer(
         timer_number, prescaler=10800,
         period=self.loop_timer_period)  # timer fq = 10000Hz 1s = 10000
     self.loop_timer.callback(self.loop_counter_rollover)
예제 #24
0
    def __init__(self, timerId, pin):
        '''
        Constructor. Initializes a input-capture timer
        
        @param timerId: Id-number of the timer
        @param pin: Pin where the capture will be performed
        '''

        self._timerId = timerId
        self._timerAddr = InputCapture._addresses[timerId]
        self._pin = pin

        self._timer = Timer(self._timerId,
                            prescaler=(freq()[0] // 1000000) - 1,
                            period=0xffff)

        # Set the timer and channel into input mode
        self._channel = self._timer.channel(1,
                                            mode=Timer.IC,
                                            pin=self._pin,
                                            polarity=Timer.FALLING)

        mem32[self._timerAddr + TIM_SMCR] = 0
        mem32[self._timerAddr + TIM_SMCR] = (mem32[self._timerAddr + TIM_SMCR]
                                             & 0xfffe0000) | 0x54
        mem32[self._timerAddr + TIM_CCER] = 0b1001

        self.reset()
예제 #25
0
def main():
    ## 统一分配引脚
    bc = BoardCtrl('X1', 'X2', 'X3', 'X4')
    bufs = generate_bufs()
    DAC_ch = 'X5'
    sync_sig = syncSignal('X6')
    # record_sig = syncSignal('X7')

    freqs = [13]
    repeat = 1
    timer_num = 6
    mctrl = magCtrl(bufs, freqs, DAC_ch, sync_sig, bc, repeat, timer_num)

    # record_sig.falling_edge()   # 发送启动记录的信号
    led = ledCue()

    ## timer3,用于循环测试
    tim3 = Timer(3)
    tim3.init(freq=0.2)
    tim3.callback(mctrl.next)

    while not mctrl.end_flg:
        if mctrl.new_block:
            led.next(mctrl.stimulus_level)
            mctrl.new_block = False
        time.sleep_us(500000)  # 每50ms

    # record_sig.falling_edge()   # 发送结束记录的信号
    led.end()
예제 #26
0
def runLedStartNoBlock(flag=True, tim_num=14, tim_freq=0.3, led_num=4):
    """ """
    if flag:
        tim = Timer(tim_num, freq=tim_freq)
        tim.callback(lambda cb_fun: LED(led_num).toggle())
    else:
        pass
예제 #27
0
 def __init__(self):
     global __bz_pin, __bz_tim, __bz_ch
     if not (__bz_pin):
         # Initialize timer and channels if not yet done
         __bz_pin = Pin("Y11")  # Broche Y2 avec timer 8 et Channel 2
         __bz_tim = Timer(8, freq=3000)
         __bz_ch = __bz_tim.channel(2, Timer.PWM_INVERTED, pin=__bz_pin)
예제 #28
0
async def isr_test():  # Test trigger from hard ISR
    from pyb import Timer
    s = '''
Timer holds off cb for 5 secs
cb should now run
cb callback
Done
'''
    printexp(s, 6)

    def cb(v):
        print('cb', v)

    d = Delay_ms(cb, ('callback', ))

    def timer_cb(_):
        d.trigger(200)

    tim = Timer(1, freq=10, callback=timer_cb)

    print('Timer holds off cb for 5 secs')
    await asyncio.sleep(5)
    tim.deinit()
    print('cb should now run')
    await asyncio.sleep(1)
    print('Done')
예제 #29
0
    def __init__(self,
                 cs=Pin.cpu.A4,
                 trigger=Pin.cpu.C0,
                 echo=Pin.cpu.C1,
                 timer=Timer(2),
                 avg_window=1):
        self.__io = MCP23S08(cs=cs)
        self.__trigger = Pin(trigger, Pin.OUT_PP)
        self.__echo = Pin(echo, Pin.IN, pull=Pin.PULL_DOWN)
        self.__timer = timer
        self.__counter = 0
        self.__window_len = avg_window
        self.__window = []

        self.__trigger.high()
        self.__io.set_direction(0, 0)
        self.__io.set_direction(1, 0)
        self.__io.set_direction(2, 0)
        self.__io.set_direction(3, 0)
        self.__io.set_gpio(0, 0)
        self.__io.set_gpio(1, 0)
        self.__io.set_gpio(2, 0)
        self.__io.set_gpio(3, 0)

        self.select_sensor(3)
예제 #30
0
 def __init__(self, pin, fname, reps=5):
     self._pin = pin
     self._reps = reps
     with open(fname, 'r') as f:
         self._data = ujson.load(f)
     # Time to wait between nonblocking transmissions. A conservative value in ms.
     self._latency = (reps + 2) * max(
         (sum(x) for x in self._data.values())) // 1000
     gc.collect()
     if ESP32:
         self._rmt = RMT(0, pin=pin, clock_div=80)  # 1μs resolution
     elif RP2:  # PIO-based RMT-like device
         self._rmt = RP2_RMT(pin_pulse=pin)  # 1μs resolution
         # Array size: length of longest entry + 1 for STOP
         asize = max([len(x) for x in self._data.values()]) + 1
         self._arr = array('H',
                           (0 for _ in range(asize)))  # on/off times (μs)
     else:  # Pyboard
         self._tim = Timer(5)  # Timer 5 controls carrier on/off times
         self._tcb = self._cb  # Pre-allocate
         asize = reps * max([len(x) for x in self._data.values()
                             ]) + 1  # Array size
         self._arr = array('H',
                           (0 for _ in range(asize)))  # on/off times (μs)
         self._aptr = 0  # Index into array