def __init__(self, gp_pin, frequency, full_range100, pulse_min, pulse_max): """ :param gp_pin: GPIO pin :param frequency: in Hz :param full_range100: in deg * 100 :param pulse_min: in µs :param pulse_max: in µs :return: """ if not gp_pin in VALID_GP_PINS: print('invalid GP pin:', gp_pin) # Get WiPy PWM configuration constants pin_alt = PIN_PWM_ALT[gp_pin] timer_nr = PIN_PWM_TIMER[gp_pin] timer_channel = PIN_PWM_CHANNEL[gp_pin] # Configure PWM timer to pin flow Pin('GP' + str(gp_pin), mode=Pin.ALT, alt=pin_alt) timer = Timer(timer_nr, mode=Timer.PWM) self.channel = timer.channel(timer_channel, freq=frequency) # Store object properties self.PWM_frame = 1000000 // frequency # in µs self.full_range100 = full_range100 self.pulse_min = pulse_min self.pulse_diff = pulse_max - pulse_min
class IR_RX(): # Result/error codes # Repeat button code REPEAT = -1 # Error codes BADSTART = -2 BADBLOCK = -3 BADREP = -4 OVERRUN = -5 BADDATA = -6 BADADDR = -7 def __init__(self, pin, nedges, tblock, callback, *args): # Optional args for callback self._pin = pin self._nedges = nedges self._tblock = tblock self.callback = callback self.args = args self._errf = lambda _: None self.verbose = False self._times = array('i', (0 for _ in range(nedges + 1))) # +1 for overrun self.tim0 = Timer(0, freq=1000000) self.tim0chan = self.tim0.channel(Timer.IC, pin=self._pin, polarity=Timer.RISING) self.tim0chan.callback(self._cb_pin) self.edge = 0 self.tim = Timer(1) # Hardware Timer 1 self.cb = self.decode # Pin interrupt. Save time of each edge for later decode. def _cb_pin(self, line): t = self.tim0chan.capture() # On overrun ignore pulses until software timer times out if self.edge <= self._nedges: # Allow 1 extra pulse to record overrun if not self.edge: # First edge received self.tim.init(freq=int(1 / self._tblock * 1000), mode=Timer.ONESHOT, callback=self.cb) self._times[self.edge] = t self.edge += 1 def do_callback(self, cmd, addr, ext, thresh=0): self.edge = 0 if cmd >= thresh: self.callback(cmd, addr, ext, *self.args) else: self._errf(cmd) def error_function(self, func): self._errf = func def close(self): self.tim0chan.callback(None) self.tim.deinit()
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
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
def main(): # set internal clock rtc = settime(timezone_offset=TIMEZONE_OFFSET) year, month, day, hour, minute, second, *_ = rtc.now() trigger = Pin('GP5', mode=Pin.OUT) trigger.value(0) # initial trigger timer timer = Timer(3, mode=Timer.PERIODIC, width=32) timer_channel = timer.channel(Timer.A | Timer.B, period=30000000) timer_channel.irq(handler=lambda t: trigger.toggle(), trigger=Timer.TIMEOUT) try: while True: leds = clock2matrix(hour=hour, minute=minute).columns # led matrix multiplexing current_trigger = trigger.value() while trigger.value() == current_trigger: for col in leds: latch.value(0) # write current time spi.write(col) # update LEDs latch.value(1) sleep_ms(1) latch.value(0) spi.write(OFF) latch.value(1) sleep_us(50) latch.value(0) spi.write(OFF) latch.value(1) year, month, day, hour, minute, second, *_ = rtc.now() # update rtc at 04:00 if hour == 4 and minute == 0: rtc = settime(timezone_offset=TIMEZONE_OFFSET) except Exception as e: matrix_off() while True: print(e) sleep_ms(2000)
def send_id(out_signal, pin_name): L2 = Pin(pin_name, mode=Pin.AF_PP, af=Pin.AF1_TIM2) timer = Timer(2, freq=38000) ch = timer.channel(1, Timer.PWM, pin=L2, pulse_width_percent=0.5) sleep_us(9000) ch = timer.channel(1, Timer.PWM, pin=L2, pulse_width_percent=0) sleep_us(4500) for i in out_signal: if i == "0": ch = timer.channel(1, Timer.PWM, pin=L2, pulse_width_percent=0.5) sleep_us(560) ch = timer.channel(1, Timer.PWM, pin=L2, pulse_width_percent=0) sleep_us(565) else: ch = timer.channel(1, Timer.PWM, pin=L2, pulse_width_percent=0.5) sleep_us(560) ch = timer.channel(1, Timer.PWM, pin=L2, pulse_width_percent=0) sleep_us(1690) ch = timer.channel(1, Timer.PWM, pin=L2, pulse_width_percent=0.5) sleep_us(560) ch = timer.channel(1, Timer.PWM, pin=L2, pulse_width_percent=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(True) elif direction in ('ccw', 'CCW', 'counterclockwise'): DIRpin(False) else: raise ValueError('Please enter CW or CCW for direction.') # Start the motor for item in speed: if 0 <= item <= 100: # self.PWMpin = Pin('X4') tim = Timer(self.timer_id, freq=5000) ch = tim.channel(self.channel_id, Timer.PWM, pin=PWMpin) ch.pulse_width_percent(item) # 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())
from machine import Timer import os import time mch = os.uname().machine if 'LaunchPad' in mch: pwm_pin = ('GP24') elif 'WiPy' in mch: pwm_pin = ('GP24') else: raise Exception('Board not supported!') for i in range(4): tim = Timer(i, mode=Timer.PERIODIC) print(tim) ch = tim.channel(Timer.A, freq=5) print(ch) ch = tim.channel(Timer.B, freq=5) print(ch) tim = Timer(i, mode=Timer.ONE_SHOT) print(tim) ch = tim.channel(Timer.A, freq=50) print(ch) ch = tim.channel(Timer.B, freq=50) print(ch) tim = Timer(i, mode=Timer.PWM) print(tim) ch = tim.channel(Timer.A, freq=50000, duty_cycle=2000, polarity=Timer.POSITIVE)
#turn LED on # (says v1.6, led works/HB is incorrect?) https://micropython.org/resources/docs/en/latest/wipy/wipy/tutorial/repl.html#linux led = Pin('GP25', mode=Pin.OUT) led(1) #simple function to blink lamp blink = lambda f:led.toggle() #Much of 1.4.6 doc is just bad/does not match actual v1.4.6 WiPy firmware #https://github.com/micropython/micropython/blob/v1.4.6/docs/pyboard/tutorial/timer.rst #initialize a timer tim = Timer(4) #1-14 exist; 3 is for internal use; avoid 5+6 (used for servo control or ADC/DAC) tim.init(mode=Timer.PERIODIC) #configure a timer 'channel' tim_a = tim.channel( tim.A, freq=5) #less than 5per sec did not work #add something useful to the running channel tim_a.irq(handler=blink) #blinks strangely rapidly #disable the timer 'channel' tim_a = None #still blinking #tim.deinit() #stopped, terminal froze. tim.channel( tim.A, freq=5) #stopped blinking #reinitialize, for a slower blink tim.deinit() #tim.init(mode=Timer.PERIODIC, width=32)#terminal froze. tim = Timer(4,mode=Timer.PERIODIC, width=32) tim_ab = tim.channel( Timer.A | Timer.B, freq=4) #does not work tim_ab.irq(handler=blink) #does not start blinking
from machine import Pin power_pin = Pin("GP6", Pin.OUT) power_pin(1) dac_reset_pin = Pin("GP7", Pin.OUT) dac_reset_pin(1) green_led_pin = Pin("GP25", Pin.OUT) green_led_pin(1) blue_led_pin = Pin("GP24", Pin.OUT) #blue_led_pin(1) #is always on - can't be switched from machine import Timer timer1 = Timer(1, mode=Timer.PWM, width=16) timer1a = timer1.channel(Timer.A, freq=1000, duty_cycle=5000) #Green LED PWM 50% timer1b = timer1.channel(Timer.B, freq=1000, duty_cycle=5000) #Red LED PWM 50% - doesn't work from machine import SD sd = SD(pins=('GP10', 'GP11', 'GP9')) #won't work Error 5 EIO - SD has no voltage?!
from machine import Timer skip_test = 0 go_test = 1 test_list = [[skip_test, skip_test, skip_test], [go_test, go_test, go_test], [go_test, go_test, go_test], [go_test, go_test, go_test], [skip_test, skip_test, skip_test], [skip_test, skip_test, skip_test], [go_test, go_test, go_test], [go_test, go_test, go_test]] total_timer_num = 8 max_channel_num = 3 cur_ch = 0 timer_id = 1 while timer_id < total_timer_num: while cur_ch < max_channel_num: if test_list[timer_id][cur_ch] != go_test: print('skip timer ' + str(timer_id) + ' pwm_' + str(cur_ch)) cur_ch += 1 continue tim = Timer(timer_id, mode=Timer.PWM) #创建Timer为PWM信号输出 print(tim) pwm = tim.channel(cur_ch, freq=1, duty_cycle=5055) #PWM输出频率1Hz, 占空比50.55%. cur_ch += 1 print(pwm) tim.deinit() cur_ch = 0 timer_id += 1
# main.py -- put your code here! from machine import Pin, Timer import machine p7 = Pin('X7', Pin.IN, Pin.PULL_UP) p8 = Pin('X8', Pin.IN, Pin.PULL_UP) p9 = Pin('Y9', Pin.IN) check_p = 3 check_p1 = 3 i = 7.5 # 20ms内的0.5-2.5换成百分比形式就是2.5%-12.5%。7.5即为中间。 sw = pyb.Switch() # 用板子上的按键控制 #tm2 = Timer(2, freq=100) tm3 = Timer(5, freq=50) # 选择定时器5,频率50hz #led3 = tm2.channel(1, Timer.PWM, pin=Pin.cpu.A15) #led3.pulse_width_percent(50) a4 = tm3.channel(1, Timer.PWM, pin=Pin.cpu.A0) # 选择通道1和定时器5对应引脚A0 X1 def check(t): global p7, p8, check_p, check_p1 if (p7.value() == 1 and p8.value() == 0) or p9.value() == 1: check_p = 1 elif p7.value() == 0: check_p = 3 #elif p9.value()==0: # check_p1 =1 #elif p9.value()==1 and check_p ==1: # check_p1=3 tim = Timer(4)
from machine import Timer from machine import PIN tim = Timer(1, mode=Timer.PERIODIC) #创建Timer 1为一个频率定期运行对象 tim_a = tim.channel(Timer.A, freq=1) #创建Timer A其频率为1Hz p = PIN('P21', mode=PIN.OUT) print_sec = 3 irq_count = 0 print_count = 0 def toggle(t): global irq_count global print_count if (irq_count % print_sec) == 0: print(print_count) print_count = print_count + 1 irq_count = irq_count + 1 tim_a.irq(trigger=Timer.TIMEOUT, handler=toggle) #回调函数将使用设置的频率定期执行中断
print('IP address:', wifi.ifconfig()[0]) # assign GP9, GP10, GP11, GP24 to alternate function (PWM) p9 = Pin('GP9', mode=Pin.ALT, alt=3) p10 = Pin('GP10', mode=Pin.ALT, alt=3) p11 = Pin('GP11', mode=Pin.ALT, alt=3) p24 = Pin('GP24', mode=Pin.ALT, alt=5) # timer in PWM mode and width must be 16 buts timer10 = Timer(4, mode=Timer.PWM, width=16) timer9 = Timer(3, mode=Timer.PWM, width=16) timer1 = Timer(1, mode=Timer.PWM, width=16) # enable channels @1KHz with a 50% duty cycle pwm9 = timer9.channel(Timer.B, freq=700, duty_cycle=100) pwm10 = timer10.channel(Timer.A, freq=700, duty_cycle=100) pwm11 = timer10.channel(Timer.B, freq=700, duty_cycle=100) pwm24 = timer1.channel(Timer.A, freq=700, duty_cycle=100) def v3_write_handler(value): pwm9.duty_cycle(int(value)) def v4_write_handler(value): pwm10.duty_cycle(int(value)) def v5_write_handler(value): pwm11.duty_cycle(int(value))
from machine import Timer import os import time mch = os.uname().machine if 'LaunchPad' in mch: pwm_pin = ('GP24') elif 'WiPy' in mch: pwm_pin = ('GP24') else: raise Exception('Board not supported!') for i in range(4): tim = Timer(i, mode=Timer.PERIODIC) print(tim) ch = tim.channel(Timer.A, freq=5) print(ch) ch = tim.channel(Timer.B, freq=5) print(ch) tim = Timer(i, mode=Timer.ONE_SHOT) print(tim) ch = tim.channel(Timer.A, freq=50) print(ch) ch = tim.channel(Timer.B, freq=50) print(ch) tim = Timer(i, mode=Timer.PWM) print(tim) ch = tim.channel(Timer.A, freq=50000, duty_cycle=2000, polarity=Timer.POSITIVE) print(ch) ch = tim.channel(Timer.B, freq=50000, duty_cycle=8000, polarity=Timer.NEGATIVE) print(ch)
print('IP address:', wifi.ifconfig()[0]) # assign GP9, GP10, GP11, GP24 to alternate function (PWM) p9 = Pin('GP9', mode=Pin.ALT, alt=3) p10 = Pin('GP10', mode=Pin.ALT, alt=3) p11 = Pin('GP11', mode=Pin.ALT, alt=3) p24 = Pin('GP24', mode=Pin.ALT, alt=5) # timer in PWM mode and width must be 16 buts timer10 = Timer(4, mode=Timer.PWM, width=16) timer9 = Timer(3, mode=Timer.PWM, width=16) timer1 = Timer(1, mode=Timer.PWM, width=16) # enable channels @1KHz with a 50% duty cycle pwm9 = timer9.channel(Timer.B, freq=700, duty_cycle=100) pwm10 = timer10.channel(Timer.A, freq=700, duty_cycle=100) pwm11 = timer10.channel(Timer.B, freq=700, duty_cycle=100) pwm24 = timer1.channel(Timer.A, freq=700, duty_cycle=100) def v3_write_handler(value): pwm9.duty_cycle(int(value)) def v4_write_handler(value): pwm10.duty_cycle(int(value)) def v5_write_handler(value): pwm11.duty_cycle(int(value)) def v6_write_handler(value):
import micropython micropython.alloc_emergency_exception_buf(100) from machine import UART import os uart = UART(0, baudrate=115200) os.dupterm(uart) print ('UART initialised') #uart.irq(trigger=UART.RX_ANY, wake=machine.IDLE) from machine import Pin from machine import Timer led_out = Pin('GP16', mode=Pin.OUT) tim = Timer(1, mode=Timer.PERIODIC) tim_a = tim.channel(Timer.A, freq=5) # The slowest frequency the timer can run at is 5Hz # so we divide the frequency down to toggle the LED # BUT the callback function doesn't appear to have been developed # Worth trying again as it is now included in the documentation tim_a.irq(handler=lambda t:led_out.toggle(), trigger=Timer.TIMEOUT) # Toggle LED on Timer interrupt #btn_in = Pin('GP17', mode=Pin.IN, pull=Pin.PULL_UP) # Connect to my WiFi import machine from network import WLAN wlan = WLAN() # get current object, without changing the mode
class DAQ_Unit(object): def __init__(self):#, freqVal=10000, numpnts = 1000): if RDB.ping(): self.daqDict = pullRedisJson(RDB, DAQPARAMKEY) gc.collect() else: self.daqDict = DAQPARAMS self.setDaqParams() self.curPos = 0 self.setupADC() self.setupTimer() def updateDaqParams(self): if RDB.ping(): self.daqDict = pullRedisJson(RDB, DAQPARAMKEY) gc.collect() else: print("Redis DAQ Param Pull Failed\n\tReverting to defaults...") self.setDaqParams() def setDaqParams(self): self.gpw = self.daqDict['gpw'] self.numPnts = self.daqDict['numPnts'] self.acqSpeed = self.daqDict['acqSpeed'] self.freq = self.daqDict['freq']#40000#1//(self.acqSpeed*1000)#acqSpeed is in microseconds self.acqType = self.daqDict['acqType'] self.numAves = self.daqDict['numAves'] self.multiplexParam = self.daqDict['multiplexParam'] self.dataArray = array.array('H', range(self.numPnts))#initialize data array self.dataID = uniqid() self.daqDict['dataCode'] = self.dataID self.filePath = self.dataID+'.txt' self.daqDict['filePath'] = self.filePath self.daqDict['data'] = self.dataArray gc.collect() def pushData(self, writeSD = False): t = time.time() RDB.rpush(self.dataID, self.dataID) RDB.rpush(self.dataID, self.numPnts) RDB.rpush(self.dataID, self.numAves) RDB.rpush(self.dataID, self.gpw) RDB.rpush(self.dataID, self.acqSpeed) RDB.rpush(self.dataID, self.freq) RDB.rpush(self.dataID, self.filePath) RDB.rpush(self.dataID, self.acqType) RDB.rpush(self.dataID, self.multiplexParam) print(time.time()-t) j = 0#Break and send data (Not optimum but better than one by one) for i in range(1+len(self.dataArray)//INDEXVAL): RDB.rpush(self.dataID, str(self.dataArray[j:j+INDEXVAL])) j+=INDEXVAL RDB.rpush('activeData', self.dataID) if writeSD: self.writeData() gc.collect() print("Push Time") t = time.time()-t print(t) def stopTimer(self): self.tim.deinit() def setupTimer(self): ''' Need to look at the following: But how to average? (Do we need two buffers) http://docs.micropython.org/en/latest/pyboard/library/pyb.ADC.html ''' #How to stop timer? self.tim = Timer(0, mode = Timer.PERIODIC, width = 32)#what is this width? Timer resolution? self.timChannel = self.tim.channel(Timer.A, freq = self.freq) #What is the function of the trigger, do we need to implement external vs internal? self.timChannel.irq(handler=self._addData_, trigger = Timer.TIMEOUT) def setupADC(self): self.adc = ADC() self.adcPin = self.adc.channel(pin = 'GP3') def _addData_(self, timer, saveData = False): self.dataArray[self.curPos] = self.adcPin() self.curPos+=1 self.curPos%=self.numPnts#this value can ultimately help us with the number of aves. def writeData(self): t = time.time() curDir = os.getcwd() os.chdir("/sd")#change directory to SD card try: f = open(self.filePath, 'w') # json.dump(self.daqDict, f)#assumes the data has already been converted to a string-Redis doesn't like arrays f.write("%s\n"%self.dataID) f.write("%s\n"%str(self.numPnts)) f.write("%s\n"%str(self.numAves)) f.write("%s\n"%str(self.gpw)) f.write("%s\n"%str(self.acqSpeed)) f.write("%s\n"%str(self.freq)) f.write("%s\n"%self.filePath) f.write("%s\n"%str(self.acqType)) f.write("%s\n"%str(self.multiplexParam)) for d in self.dataArray: f.write("%s,\n"%str(d)) f.close() os.chdir(curDir) except: os.chdir(curDir) print("Saving to %s failed"%fileName) gc.collect() print("Write Time: %s"%(time.time()-t))