示例#1
0
    def __init__(self, pin, timerId=6, thresholdTime=1000, lowOnPress=False):
        '''
        Constructor
        
        @param pin: Pin object where the button is
        @param timerId: (default=6) Timer to determine the long press
        @param thresholdTime: Waiting time to determine a long press as milliseconds
        @param lowOnPress: Indicates whether the value is 0 when the button is pressed (pull-down)
                            The user (blue) button on the NUCLEO-L476RG board must have this parameter as True,
                            but for the case of the NUCLEO-F767ZI board, this parameter must be False
        '''

        self._pin = Pin(pin)
        self._pin.init(mode=Pin.IN)
        self._pin.irq(handler=self._onPinIrq)
        self._lowOnPress = lowOnPress

        self._thresholdTime = thresholdTime
        self._pressTime = 0

        self._timer = Timer(timerId)

        self._shortPressHandler = None
        self._longPressHandler = None

        self._isTimeout = False
示例#2
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)
示例#3
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
示例#4
0
class caliMagCtrl():
    def __init__(self, buf=array('H', [100]), ch=1):
        self.timer = Timer(6)
        self.dac = DAC(ch, bits=12)
        self.buf = buf
        self.dac_on = 0

    def reset_buf(self, buf):
        self.buf = buf

    def start(self, freq=10):
        self.dac.write_timed(self.buf, self.timer, mode=DAC.CIRCULAR)
        self.timer.init(freq=freq * len(self.buf))
        self.dac_on = 1

    def stop(self):
        self.timer.deinit()
        self.dac.write(0)
        self.dac_on = 0

    def toggle(self, freq=5):
        if self.dac_on:
            self.stop()
        else:
            self.start(freq)
示例#5
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
示例#6
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()
示例#7
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)
示例#8
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
示例#9
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
示例#10
0
 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)
示例#11
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)
示例#12
0
class caliMagCtrl1():
    def __init__(self, amps=[], freqs=[], bufs=[], ch=1):
        # amps: 幅值序列
        # bufs: 对应幅值的正弦序列

        self.timer = Timer(6)
        self.dac = DAC(ch, bits=12)
        self.amps = amps
        self.bufs = bufs

        self.freqs = freqs
        self.indx = range(len(amps))
        self.newtask = False

    def next(self):
        ind = self.indx.pop(0)
        self.indx.append(ind)

        self.amp = self.amps[ind]
        buf = self.bufs[ind]
        self.freq = self.freqs[ind]

        if self.amp == 0:
            self.timer.deinit()
            self.dac.write(0)
        else:
            self.dac.write_timed(buf, self.timer, mode=DAC.CIRCULAR)
            self.timer.init(freq=self.freq * len(buf))

        self.newtask = True
示例#13
0
class SPWM():
    def __init__(self, freq=100):
        self.pwm_pin = Pin('PA5', Pin.OUT)
        self.pwm_tim = Timer(2)  #not start
        self.flag = 0
        self.pp = 50

    def start(self):
        self.pwm()
        self.modulate()
        while 1:
            if self.flag:
                self.flag = 0
                #计算self.pp  占空比
                #配置pwm占空比
                self.ch.pulse_width_percent(self.pp)

    def pwm(self, enable=True):
        self.pwm_tim = Timer(2, freq=10000)
        self.ch = self.pwm_tim.channel(1, Timer.PWM, pin=self.pwm_pin)
        self.ch.pulse_width_percent(50)

    def modulate(self, freq_m=10):
        self.m_tim = Timer(5, freq=freq_m)
        self.m_tim.callback(lambda t: self.change())

    def change(self):
        self.flag = 1
 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)
 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
示例#16
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
示例#17
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)
示例#18
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
示例#19
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()		
示例#20
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')
示例#21
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)
示例#22
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)
示例#23
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()
示例#24
0
 def __init__(self):
     # self.LFront = SpiderLimbs(0, 1, 2)
     # self.RFront = SpiderLimbs(4, 5, 6)
     # self.LRear = SpiderLimbs(8, 9, 10)
     # self.RRear = SpiderLimbs(12, 13, 14)
     self.ready()
     tim = Timer(1, freq=2)
     tim.callback(self.actionIRQ)
示例#25
0
def main():
    # X1,X2路PWM波分别作为激励和采样保持开关信号,非晶丝串联150ohm电阻
    # 激励电流25-30mA
    tim = Timer(2, freq=500000)  #500Khz
    ch1 = tim.channel(1, Timer.PWM, pin=pyb.Pin('X1', pyb.Pin.OUT_PP))
    ch2 = tim.channel(2, Timer.PWM, pin=pyb.Pin('X2', pyb.Pin.OUT_PP))
    ch1.pulse_width_percent(20)
    ch2.pulse_width_percent(30)
示例#26
0
 def __init__(self):
     self._timer = Timer(8, freq=1)
     self._leds = [LED(i) for i in range(1, 5)]
     self._color = 'yellow'
     self._timer.callback(self._callback_)
     self._mode = False  #'deterministic'
     self._led = self._leds[0]
     self._status = False
示例#27
0
 def start_update(self):
     # 16-bit timer
     self.timer = Timer(9)
     self.timer.init(freq=100)
     self.timer.callback(self.update)
     self.enable = True
     self.error_sum = 0
     cmd.send_uart("PID timers started\n", log_flag)
示例#28
0
 def __init__(
     self, adc=CTRL_ADC, p_pin=PWM_PIN, t_num=PWM_TIMER_NO, chnum=PWM_TIMER_CHANNEL
 ):
     self.adc = adc
     dim_tim = Timer(t_num, freq=1000)
     self.ch = dim_tim.channel(chnum, Timer.PWM, pin=p_pin)
     self.current = self.increment = self.target = self.ticks_left = 0
     self.tr = self.tick_response
示例#29
0
class ZumoMotor(object):
    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
        # every change of speed
    def flipLeftMotor(self, flip):
        self.flipleft = flip

    def flipRightMotor(self, flip):
        self.flipRight = flip

    def setLeftSpeed(self, speed):
        reverse = 0
        if (speed < 0):  #if speed is negatif we make tha value positif again
            speed = -speed  #but put the reverse value to 1 so we know we need to go backwars
            reverse = 1
        if (speed > 400):  #speed can be maximum 400
            speed = 400

        self.ch_l.pulse_width_percent(
            int(speed /
                4))  # value goes from 0-400 but in python we need % for PWM.
        #We divide by 4 to have a value that goes from 0-100
        if (reverse ^ self.flipLeft):
            self.dir_l.value(1)
        else:
            self.dir_l.value(0)

    def setRightSpeed(self, speed):
        reverse = 0
        if (speed < 0):
            speed = -speed
            reverse = 1
        if (speed > 400):
            speed = 400

        self.ch_r.pulse_width_percent(int(speed / 4))
        if (reverse ^ self.flipLeft):
            self.dir_r.value(1)
        else:
            self.dir_r.value(0)

    def setSpeeds(self, leftSpeed, rightSpeed):

        self.setLeftSpeed(leftSpeed)
        self.setRightSpeed(rightSpeed)
示例#30
0
    def change_speed(self, newspeed):
        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)
        ch.pulse_width_percent(newspeed)
        self.currentSpeed = newspeed
        self.isRunning = True
示例#31
0
    def change_speed(self,newspeed):
        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)
        ch.pulse_width_percent(newspeed)
        self.currentSpeed = newspeed
        self.isRunning = True
示例#32
0
  def __init__( self, p, timernum, afreq = 100 ) :
    isname = type(p) == str
    pinname = p if isname else p.name()
    timernum, channel = PWM.timerandchannel(pinname, timernum)
    if isname:
      p = Pin(pinname)

    self._timer = Timer(timernum, freq = afreq)
    self._channel = self._timer.channel(channel, Timer.PWM, pin = p)
示例#33
0
class MOTORS():

    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)
    
    #设定右边电机的转速
    #-1 < ratio < 1
    def set_ratio_r(self, ratio):
        #check ratio
        if(ratio > 1.0):
            ratio = 1.0
        elif(ratio < -1.0):
            ratio = -1.0
        if(ratio > 0):
            self._rb_ch.pulse_width_percent(0)
            self._rf_ch.pulse_width_percent(ratio*100)
        elif(ratio < 0):
            self._rf_ch.pulse_width_percent(0)
            self._rb_ch.pulse_width_percent(-ratio*100)
        else:
            self._rf_ch.pulse_width_percent(0)
            self._rb_ch.pulse_width_percent(0)

    #设定左边电机的转速
    #-1 < ratio < 1
    def set_ratio_l(self, ratio):
        #check ratio
        if(ratio > 1.0):
            ratio = 1.0
        elif(ratio < -1.0):
            ratio = -1.0
        if(ratio > 0):
            self._lb_ch.pulse_width_percent(0)
            self._lf_ch.pulse_width_percent(ratio*100)
        elif(ratio < 0):
            self._lf_ch.pulse_width_percent(0)
            self._lb_ch.pulse_width_percent(-ratio*100)
        else:
            self._lf_ch.pulse_width_percent(0)
            self._lb_ch.pulse_width_percent(0)

    def all_stop(self):
        self.set_ratio_l(0)
        self.set_ratio_r(0)
def  drive_motor():
	A1 = Pin('Y9',Pin.OUT_PP)
	A2 = Pin('Y10',Pin.OUT_PP)
	A1.high()
	A2.low()
	motor = Pin('X1')
	tim = Timer(2, freq = 1000)
	ch = tim.channel(1, Timer.PWM, pin = motor)
	while True:
		ch.pulse_width_percent(50)
示例#35
0
class TimeThread(object):
    """
    This class allows to make a call of several functions with a specified time
    intervals. For synchronization a hardware timer is used. The class contains
    main loop to check flags of queue.
    """
    def __init__(self, timerNum, showExceptions = False):
        self.showExceptions = showExceptions
        self.timerQueue = []
        self.timer = Timer(timerNum, freq=1000)
        self.timer.callback(self._timer_handler)

    """
    The method adds a pointer of function and delay time to the event queue.
    Time interval should be set in milliseconds.
    When the method adds to the queue it verifies uniqueness for the pointer.
    If such a pointer already added to an event queue then it is not added again.
    When the queue comes to this pointer then entry is removed from the queue.
    But the pointer function is run.
    """
    def set_time_out(self, delay, function):
        b = True
        for r in self.timerQueue:
            if r[1] == function:
                b = False
        if b:
            self.timerQueue += [[delay, function]]        

    # The handler of hardware timer
    def _timer_handler(self, timer):
        q = self.timerQueue
        for i in range(len(q)):
            if q[i][0] > 0:
                q[i][0] -= 1

    """
    The method runs an infinite loop in wich the queue is processed. 
    This method should be accessed after pre-filling queue.    
    Further work is performed within the specified (by the method
    set_time_out()) functions.
    """
    def run(self):
        q = self.timerQueue
        while True:            
            for i in range(len(q) - 1, -1, -1):
                if q[i][0] == 0:
                    f = q[i][1]
                    del(q[i])
                    if self.showExceptions:                        
                        f()
                    else:
                        try:
                            f()
                        except Exception as e:
                            print(e)
示例#36
0
文件: motor.py 项目: CRAWlab/ARLISS
    def set_speed(self, newSpeed):
        """ Method to change the speed of the motor, direciton is unchanged
        Arugments
          newSpeed : the desired new speed 0-100 (as percentage of max)
        """

        PWMpin = Pin(self.PWMpin)
        tim = Timer(self.timer_id, freq=1000)
        ch = tim.channel(self.channel_id, Timer.PWM, pin=PWMpin)
        ch.pulse_width_percent(newSpeed)
        # PWM.set_duty_cycle(self.PWMpin, newSpeed)
        self.currentSpeed = newSpeed
示例#37
0
class Motor:
    _index = None

    _pin = None
    _timer = None
    _channel = None
    _rate = None

    _rate_min = None
    _rate_max = None

    # Each range represents 50% of the complete range
    _step = None

    _debug = False

    # ########################################################################
    # ### Properties
    # ########################################################################
    @property
    def rate(self):
        return self._rate

    @rate.setter
    def rate(self, value):
        self._rate = max(min(value, 100), 0)
        pulse_value = int(self._rate_min + self._rate * self._step)

        if not self._debug:
            self._channel.pulse_width(pulse_value)
        else:
            print("<<ESC>> %s: %.3d" % (self._pin, self._rate))

    # ########################################################################
    # ### Constructors and destructors
    # ########################################################################
    def __init__(self, esc_index, rate_min=1000, rate_max=2000, debug=False):
        if esc_index >= 0 & esc_index <= 3:
            self._debug = debug
            self._rate_min = rate_min
            self._rate_max = rate_max
            self._step = (rate_max - rate_min) / 100
            self._index = esc_index
            self._pin = ESC_PIN[esc_index]
            self._timer = Timer(ESC_TIMER[esc_index], prescaler=83, period=19999)
            self._channel = self._timer.channel(ESC_CHANNEL[esc_index], Timer.PWM, pin=Pin(self._pin))
            self.rate = 0
        else:
            raise Exception("Invalid ESC index")

    def __del__(self):
        self.rate(self._rate_min)
        self._timer.deinit()
示例#38
0
文件: motor.py 项目: CRAWlab/ARLISS
    def hard_stop(self):
        """ Method to hard stop an individual motor"""

        self.PWMpin = Pin('X4')
        tim = Timer(2, freq=1000)
        ch = tim.channel(4, Timer.PWM, pin=self.PWMpin)
        ch.pulse_width_percent(0)
        # PWM.set_duty_cycle(self.PWMpin, 0.0)

        # set the status attributes
        self.isRunning = True
        self.currentDirection = None
        self.currentSpeed = 0
示例#39
0
    def stop(self):
        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)
        for i in range(self.currentSpeed):
            ch.pulse_width_percent(self.currentSpeed-i)
            time.sleep(0.01)
        ch.pulse_width_percent(0)
        self.isRunning = False
        self.currentDirection = None
        self.currentSpeed = 0.0
示例#40
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)
示例#41
0
class ESC:
  freq_min = 950
  freq_max = 1950
  def __init__(self, index):
    self.timer = Timer(esc_pins_timers[index], prescaler=83, period=19999)
    self.channel = self.timer.channel(esc_pins_channels[index],
                                      Timer.PWM,
                                      pin=Pin(esc_pins[index]))
    self.trim = esc_trim[index]
  def move(self, freq):
    freq = min(self.freq_max, max(self.freq_min, freq + self.trim))
    self.channel.pulse_width(int(freq))
  def __del__(self):
    self.timer.deinit()
示例#42
0
文件: motor.py 项目: CRAWlab/ARLISS
    def soft_stop(self):
        """ Method to soft stop (coast to stop) an individual motor"""
        PWMpin = Pin(self.PWMpin)
        tim = Timer(self.timer_id, freq=1000)
        ch = tim.channel(self.channel_id, Timer.PWM, pin=PWMpin)
        for i in range(self.currentSpeed):
            ch.pulse_width_percent(self.currentSpeed-i)
            time.sleep(0.01)
        ch.pulse_width_percent(0)

        # set the status attributes
        self.isRunning = False
        self.currentDirection = None
        self.currentSpeed = 0.0
示例#43
0
文件: motor.py 项目: CRAWlab/ARLISS
    def __init__(self, PWMpin, DIRpin, timer_id, channel_id):
        self.PWMpin = PWMpin
        self.DIRpin = DIRpin
        self.timer_id = timer_id
        self.channel_id = channel_id

        self.isRunning = False
        self.currentDirection = None
        self.currentSpeed = 0

        # Set up the GPIO pins as output
        PWMpin = Pin(self.PWMpin)
        DIRpin = Pin(self.DIRpin, Pin.OUT_PP)

        tim = Timer(self.timer_id, freq=1000)
        ch = tim.channel(self.channel_id, Timer.PWM, pin=PWMpin)
示例#44
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)
def  remote():

	#initialise UART communication
	uart = UART(6)
	uart.init(9600, bits=8, parity = None, stop = 2)

	# 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)

	# Motor in idle state
	A1.high()	
	A2.high()	
	speed = 0
	DEADZONE = 5

	# Use keypad U and D keys to control speed
	while True:				# loop forever until CTRL-C
		while (uart.any()!=10):    #wait we get 10 chars
			n = uart.any()
		command = uart.read(10)
		if command[2]==ord('5'):
			if speed < 96:
				speed = speed + 5
				print(speed)
		elif command[2]==ord('6'):
			if speed > - 96:
				speed = speed - 5
				print(speed)
		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()		# idle
			A2.low()		
示例#46
0
文件: motor.py 项目: CRAWlab/ARLISS
    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
        """

        # Standby pin should go high to enable motion
        self.STBYpin.high()
        # STBYpin.high()
        # GPIO.output(self.STBYpin, GPIO.HIGH)

        # x01 and x02 have to be opposite to move, toggle to change direction
        if direction in ('cw','CW','clockwise'):
            self.ControlPin1.low()
            # GPIO.output(self.ControlPin1, GPIO.LOW)
            self.ControlPin2.high()
            # GPIO.output(self.ControlPin2, GPIO.HIGH)
        elif direction in ('ccw','CCW','counterclockwise'):
            self.ControlPin1.high()
            # GPIO.output(self.ControlPin1, GPIO.HIGH)
            self.ControlPin2.low()
            # GPIO.output(self.ControlPin2, GPIO.LOW)
        else:
            raise ValueError('Please enter CW or CCW for direction.')

        # Start the motor
        # PWM.start(channel, duty, freq=2000, polarity=0)
        if 0 <= speed <= 100:
            self.PWMpin = Pin('X4')
            tim = Timer(2, freq=1000)
            ch = tim.channel(4, Timer.PWM, pin=self.PWMpin)
            ch.pulse_width_percent(speed)
            # PWM.start(self.PWMpin, speed)
        else:
            raise ValueError("Please enter speed between 0 and 100, \
                              representing a percentage of the maximum \
                              motor speed.")

        # set the status attributes
        self.isRunning = True
        self.currentDirection = direction
        self.currentSpeed = speed
示例#47
0
文件: motor.py 项目: CRAWlab/ARLISS
    def soft_stop(self):
        """ Method to soft stop (coast to stop) an individual motor"""

        # Make both control pins low
        self.ControlPin1.low()
        # GPIO.output(self.ControlPin1, GPIO.LOW)
        self.ControlPin2.low()
        # GPIO.output(self.ControlPin2, GPIO.LOW)
        self.PWMpin = Pin('X4')
        tim = Timer(2, freq=1000)
        ch = tim.channel(4, Timer.PWM, pin=self.PWMpin)
        ch.pulse_width_percent(0)
        self.STBYpin.low()
        # GPIO.output(self.STBYpin, GPIO.LOW)

        # set the status attributes
        self.isRunning = True
        self.currentDirection = None
        self.currentSpeed = 0.0
示例#48
0
文件: motor.py 项目: CRAWlab/ARLISS
    def __init__(self, ControlPin1, ControlPin2, PWMpin, STBYpin):
        self.ControlPin1 = ControlPin1
        self.ControlPin2 = ControlPin2
        self.PWMpin = PWMpin
        self.STBYpin = STBYpin
        self.isRunning = False
        self.currentDirection = None
        self.currentSpeed = 0

        # Set up the GPIO pins as output
        self.STBYpin = Pin(self.STBYpin, Pin.OUT_PP)
        # GPIO.setup(self.STBYpin, GPIO.OUT)
        self.ControlPin1 = Pin(self.ControlPin1, Pin.OUT_PP)
        # GPIO.setup(self.ControlPin1, GPIO.OUT)
        self.ControlPin2 = Pin(self.ControlPin2, Pin.OUT_PP)
        # GPIO.setup(self.ControlPin2, GPIO.OUT)
        self.PWMpin = Pin(self.PWMpin)
        tim = Timer(2, freq=1000)
        ch = tim.channel(4, Timer.PWM, pin=self.PWMpin)
示例#49
0
 def __init__(self, esc_index, rate_min=1000, rate_max=2000, debug=False):
     if esc_index >= 0 & esc_index <= 3:
         self._debug = debug
         self._rate_min = rate_min
         self._rate_max = rate_max
         self._step = (rate_max - rate_min) / 100
         self._index = esc_index
         self._pin = ESC_PIN[esc_index]
         self._timer = Timer(ESC_TIMER[esc_index], prescaler=83, period=19999)
         self._channel = self._timer.channel(ESC_CHANNEL[esc_index], Timer.PWM, pin=Pin(self._pin))
         self.rate = 0
     else:
         raise Exception("Invalid ESC index")
示例#50
0
文件: tutorial01.py 项目: mbag/meetup
def gradient(ri,gi,bi,rf,gf,bf,wait,cycles):
  """
  ri = initial,  percent
  rf = final,  percent m
  gradient(0,10,0,0,100,0,10,4)
  for inverting:
  gradient(20,255,255,95,255,255,10,2)
  """
  tim = Timer(2, freq=1000)
  cr = tim.channel(2, Timer.PWM_INVERTED, pin=r.pin)
  cg = tim.channel(3, Timer.PWM_INVERTED, pin=g.pin)
  cb = tim.channel(4, Timer.PWM_INVERTED, pin=b.pin)
  for i in range(cycles):
    for a in range(100):
      cr.pulse_width_percent((rf-ri)*0.01*a+ri)
      cg.pulse_width_percent((gf-gi)*0.01*a+gi)
      cb.pulse_width_percent((bf-bi)*0.01*a+gi)
      pyb.delay(wait)
    for a in range(100):
      cr.pulse_width_percent((rf-ri)*0.01*(100-a)+ri)
      cg.pulse_width_percent((gf-gi)*0.01*(100-a)+gi)
      cb.pulse_width_percent((bf-bi)*0.01*(100-a)+gi)
      pyb.delay(wait)
示例#51
0
 def __init__(self):
     self.tmp = self.time = 0
     self.cnt = 0
     self.fr = 0
     self.trig = Pin('X12', Pin.OUT_PP, Pin.PULL_NONE)
     echoR = Pin('X1', Pin.IN, Pin.PULL_NONE)
     echoF = Pin('X2', Pin.IN, Pin.PULL_NONE)
     self.micros = pyb.Timer(5, prescaler=83, period=0x3fffffff)
     self.timer = Timer(2, freq=1000)
     self.timer.period(3600)
     self.timer.prescaler(1375)
     self.timer.callback(lambda e: self.run_trig())
     extR = ExtInt(echoR, ExtInt.IRQ_RISING, Pin.PULL_NONE, self.start_count)
     extF = ExtInt(echoF, ExtInt.IRQ_FALLING, Pin.PULL_NONE, self.read_dist)
示例#52
0
class UltraSonicMeter(object):

    def __init__(self):
        self.tmp = self.time = 0
        self.cnt = 0
        self.fr = 0
        self.trig = Pin('X12', Pin.OUT_PP, Pin.PULL_NONE)
        echoR = Pin('X1', Pin.IN, Pin.PULL_NONE)
        echoF = Pin('X2', Pin.IN, Pin.PULL_NONE)
        self.micros = pyb.Timer(5, prescaler=83, period=0x3fffffff)
        self.timer = Timer(2, freq=1000)
        self.timer.period(3600)
        self.timer.prescaler(1375)
        self.timer.callback(lambda e: self.run_trig())
        extR = ExtInt(echoR, ExtInt.IRQ_RISING, Pin.PULL_NONE, self.start_count)
        extF = ExtInt(echoF, ExtInt.IRQ_FALLING, Pin.PULL_NONE, self.read_dist)

    def run_trig(self):
        self.trig.high()
        pyb.udelay(1)
        self.trig.low()

    def start_count(self, line):
        self.micros.counter(0)
        self.time = self.micros.counter()
        self.timer.counter(0)

    def read_dist(self, line):
        end = self.micros.counter()
        micros = end-self.time
        distP1 = micros//5
        distP2 = micros//6
        distP3 = (distP1-distP2)//10*2
        dist = distP2+distP3

        if dist != 0:
            self.cnt += 1
            self.fr += dist

        if self.cnt == 15:
            tmp = self.tmp
            dist = self.fr//self.cnt
            if tmp != dist:
                print(dist, 'mm')
                self.tmp = dist
            self.cnt = 0
            self.fr  = 0
示例#53
0
文件: motor.py 项目: CRAWlab/ARLISS
    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
        while self.isRunning:
            print("\nMotorA =", enc_timer.counter())
            print("\nMotorB =", enc_timer_1.counter())
  def __init__( self, tpin, epin, timer=2 ) :
    """  """

    if type(tpin) == str:
      self._tpin = Pin(tpin, Pin.OUT_PP, Pin.PULL_NONE)
    elif type(tpin) == Pin:
      self._tpin = tpin
    else:
      raise Exception("trigger pin must be pin name or pyb.Pin configured for output.")

    self._tpin.low()

    if type(epin) == str:
      self._epin = Pin(epin, Pin.IN, Pin.PULL_NONE)
    elif type(epin) == Pin:
      self._epin = epin
    else:
      raise Exception("echo pin must be pin name or pyb.Pin configured for input.")

    # Create a microseconds counter.
    self._micros = Timer(timer, prescaler=83, period=0x3fffffff)
示例#55
0
    def __init__(self, pinA, pinB, mode = DUAL_MODE):
        """
        Instantiate an Encoder object.
        Initalises the Pins, Timer and TimerChannel for use as a quadrature
        decoder. Registers an overflow callback to elegantly handle counter
        register overflows.
        pinA: Any valid value taken by pyb.Pin constructor
        pinB: Any valid value taken by pyb.Pin constructor
        mode: Mode to use for decoding (Encoder.SINGLE_MODE or
                Encoder.DUAL_MODE)
        raises: Any exception thrown by pyb.Pin, pyb.Timer, pyb.Timer.channel
                or Exception if pins are not compatible pairs
        """
        self._chA = Pin(pinA)
        self._chB = Pin(pinB)
        self._ticks = 0

        # Check pins are compatible
        self._checkPins(pinA, pinB)

        # init pins for alternate encoder function
        af = self.AF_MAP[self._chA.names()[1]]
        channel = self.TIMER_MAP[af]
        af = getattr(Pin, af)
        self._chA.init(Pin.AF_PP, pull = Pin.PULL_NONE, af = af)
        self._chB.init(Pin.AF_PP, pull = Pin.PULL_NONE, af = af)
        # init timer
        self._timer = Timer(channel, prescaler = 0, period = 100000)
        # init encoder mode
        # self._channel = self._timer.channel(1, mode)
        self._timer.channel(1, mode)
        # setup overflow callback
        self._timer.callback(self._overflow)
        # init count register to middle of count
        self._timer.counter(self._timer.period()//2)
        self._lastRead = self._timer.counter()
示例#56
0
 def __init__(self, timerNum, showExceptions = False):
     self.showExceptions = showExceptions
     self.timerQueue = []
     self.timer = Timer(timerNum, freq=1000)
     self.timer.callback(self._timer_handler)
# Task 4: Joystick Controlling the Motor
# Author: BSG
# Version 1.0
# 26 May 2016

print ('This is Test 4: Joystick Controlling the Motor')
from pyb import Pin, Timer, ADC



while True:
    pyb.delay(1)
    A1 = Pin('Y9',Pin.OUT_PP)
    A2 = Pin('Y10',Pin.OUT_PP)
    A1.high()
    A2.low()
    motor = Pin('X1')
    tim = Timer(2, freq = 1000)
    ch = tim.channel(1, Timer.PWM, pin = motor)



    adc_1 = ADC(Pin('X19')) #vertical
    adc_2 = ADC(Pin('X20')) #horizontal
    J_sw = Pin('Y11', Pin.IN) #switch

    vertical = (int(adc_2.read()) / 1700)*100
    ch.pulse_width_percent(vertical)
示例#58
0
 def __init__(self):
     # Timer for motor PWM
     self.tim2 = Timer(2, freq=10000)
     
     # Timer to dim lights
     self.tim4 = Timer(4, freq=1000)
     
     # Variables
     self.step_R = 0          #counter for (micro) step
     self.step_L = 0          #counter for (micro) step
     self.n_steps = 16        #number of steps
     self.dir_R = 0           #direction 1=positive, -1=negative, 0=none
     self.dir_L = 0           #direction 1=positive, -1=negative, 0=none
     self.speed_R = 0         #speed counter. If >255 step will be executed
     self.speed_L = 0         #speed counter. If >255 step will be executed
     self.max_speed_R = 256   #maximum speed
     self.max_speed_L = 256   #maximum speed
     self.sspeed_R = 0        #set speed
     self.sspeed_L = 0        #set speed
     self.dist_R = 0          #distance counter
     self.dist_L = 0          #distance counter
     self.power_R = 0         #PWM power setting 0 - 100%
     self.power_L = 0         #PWM power setting 0 - 100%
     self.low_light = 20      #PWM setting for tail light
     self.target_R = 0        #motion control position target
     self.target_L = 0        #motion control position target
     self.acc = 0.5           #motion control acceleration
     self.dts_R = 0           #motion distance to stop
     self.dts_L = 0           #motion distance to stop
        
     # Lights:
     self.LH = Pin('PD12', pyb.Pin.OUT_PP)
     self.RH = Pin('PD13', pyb.Pin.OUT_PP)
     self.TL = self.tim4.channel(3, Timer.PWM, pin=Pin.cpu.D14)
     self.HL = Pin('PD15', pyb.Pin.OUT_PP)
     
     # RH Motor
     self.RH_STBY = Pin('PE6', pyb.Pin.OUT_PP)
     self.RH_PWMA = self.tim2.channel(1, Timer.PWM, pin=Pin.cpu.A15)
     self.RH_AIN1 = Pin('PE8', pyb.Pin.OUT_PP)
     self.RH_AIN2 = Pin('PE9', pyb.Pin.OUT_PP)
     self.RH_PWMB = self.tim2.channel(2, Timer.PWM, pin=Pin.cpu.A1)
     self.RH_BIN1 = Pin('PE10', pyb.Pin.OUT_PP)
     self.RH_BIN2 = Pin('PE11', pyb.Pin.OUT_PP)
     
     # LH Motor
     self.LH_STBY = Pin('PE7', pyb.Pin.OUT_PP)
     self.LH_PWMA = self.tim2.channel(3, Timer.PWM, pin=Pin.cpu.A2)
     self.LH_AIN1 = Pin('PE12', pyb.Pin.OUT_PP)
     self.LH_AIN2 = Pin('PE13', pyb.Pin.OUT_PP)
     self.LH_PWMB = self.tim2.channel(4, Timer.PWM, pin=Pin.cpu.A3)
     self.LH_BIN1 = Pin('PE14', pyb.Pin.OUT_PP)
     self.LH_BIN2 = Pin('PE15', pyb.Pin.OUT_PP)
     
     # Switch lights off
     self.LH.low()
     self.RH.low()
     self.TL.pulse_width_percent(0)
     self.HL.low()
     
     # Switch motor drivers off and PWM to low
     self.RH_PWMA.pulse_width_percent(self.power_R)
     self.RH_PWMB.pulse_width_percent(self.power_R)
     self.LH_PWMA.pulse_width_percent(self.power_L)
     self.LH_PWMB.pulse_width_percent(self.power_L)
     self.RH_STBY.low()
     self.LH_STBY.low()
     
     # Set all other motor pins low
     self.RH_AIN1.low()
     self.RH_AIN2.low()
     self.RH_BIN1.low()
     self.RH_BIN2.low()
     self.LH_AIN1.low()
     self.LH_AIN2.low()
     self.LH_BIN1.low()
     self.LH_BIN2.low()