class TrackBall: def __init__(self,qq): self.volEnQueueable = EnQueueable((EnQueueable.INC,EnQueueable.VOL),qq) self.toneEnQueueable = EnQueueable((EnQueueable.INC,EnQueueable.TONE),qq) self.targCoilID = 0; self.x1=Pin(State.trackballStateDict['x1'], Pin.IN, Pin.PULL_DOWN) self.x2=Pin(State.trackballStateDict['x2'], Pin.IN, Pin.PULL_DOWN) self.y1=Pin(State.trackballStateDict['y1'], Pin.IN, Pin.PULL_DOWN) self.y2=Pin(State.trackballStateDict['y2'], Pin.IN, Pin.PULL_DOWN) self.extInts = (ExtInt(State.trackballStateDict['x1'], ExtInt.IRQ_RISING, Pin.PULL_DOWN, self.x11), ExtInt(State.trackballStateDict['y1'], ExtInt.IRQ_RISING, Pin.PULL_DOWN, self.y11)) def x11(self,unused): if self.x2.value(): self.volEnQueueable.push(self.targCoilID,-1) else: self.volEnQueueable.push(self.targCoilID,1) def y11(self,unused): if self.y2.value(): self.toneEnQueueable.push(self.targCoilID,-1) else: self.toneEnQueueable.push(self.targCoilID,1)
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
class Relay(object): """Control a relay board with an output pin. Set on to True to drive the relay pin low which turns the relay on.""" def __init__( self, pin ) : """Pin may be a pin name or pyb.Pin object set for output.""" if type(pin) == str: self._pin = Pin(pin, Pin.OUT_PP, Pin.PULL_DOWN) elif type(pin) == Pin: self._pin = pin else: raise Exception("pin must be pin name or pyb.Pin") self.on = False @property def on( self ) : return self._pin.value() @on.setter def on( self, value ) : if value: self._pin.low() else: self._pin.high()
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)
class STAccel: def __init__(self): self.cs_pin = Pin('PE3', Pin.OUT_PP, Pin.PULL_NONE) self.cs_pin.high() self.spi = SPI(1, SPI.MASTER, baudrate=328125, polarity=0, phase=1, bits=8) self.who_am_i = self.read_id() if self.who_am_i == LIS302DL_WHO_AM_I_VAL: self.write_bytes(LIS302DL_CTRL_REG1_ADDR, bytearray([LIS302DL_CONF])) self.sensitivity = 18 elif self.who_am_i == LIS3DSH_WHO_AM_I_VAL: self.write_bytes(LIS3DSH_CTRL_REG4_ADDR, bytearray([LIS3DSH_CTRL_REG4_CONF])) self.write_bytes(LIS3DSH_CTRL_REG5_ADDR, bytearray([LIS3DSH_CTRL_REG5_CONF])) self.sensitivity = 0.06 * 256 else: raise Exception('LIS302DL or LIS3DSH accelerometer not present') def convert_raw_to_g(self, x): if x & 0x80: x = x - 256 return x * self.sensitivity / 1000 def read_bytes(self, addr, nbytes): if nbytes > 1: addr |= READWRITE_CMD | MULTIPLEBYTE_CMD else: addr |= READWRITE_CMD self.cs_pin.low() self.spi.send(addr) #buf = self.spi.send_recv(bytearray(nbytes * [0])) # read data, MSB first buf = self.spi.recv(nbytes) self.cs_pin.high() return buf def write_bytes(self, addr, buf): if len(buf) > 1: addr |= MULTIPLEBYTE_CMD self.cs_pin.low() self.spi.send(addr) for b in buf: self.spi.send(b) self.cs_pin.high() def read_id(self): return self.read_bytes(WHO_AM_I_ADDR, 1)[0] def x(self): return self.convert_raw_to_g(self.read_bytes(OUT_X_ADDR, 1)[0]) def y(self): return self.convert_raw_to_g(self.read_bytes(OUT_Y_ADDR, 1)[0]) def z(self): return self.convert_raw_to_g(self.read_bytes(OUT_Z_ADDR, 1)[0]) def xyz(self): return (self.x(), self.y(), self.z())
def __init__( self, forward, backward, speed ) : """forward pin name, backward pin name, speed = (pin name, timer#) Need to make sure the given timer # is associated with the speed pin or an exception will be raised. The speed pin must support PWM.""" self._forward = Pin(forward, Pin.OUT_PP) self._backward = Pin(backward, Pin.OUT_PP) self._speedControl = PWM(speed[0], speed[1]) self._speed = 0
def check_joystick(): adc_1 = ADC(Pin('X19')) adc_2 = ADC(Pin('X20')) J_sw = Pin('Y11', Pin.IN) while True: print('Vertical: ',adc_1.read(), 'Horizontal: ', adc_2.read(), 'Switch: ',J_sw.value()) pyb.delay(2000)
def declare_channel(self, channel, direction): try: self.available_pins.index(channel) if self._find_channel(channel): return ; pin = Pin(channel) if direction: pin.init(Pin.OUT_PP) else: pin.init(Pin.IN, Pin.PULL_UP) self.channels += [pin] except: pass
def __init__(self,qq): self.x1=Pin('Y9', Pin.IN, Pin.PULL_DOWN) self.x2=Pin('Y7', Pin.IN, Pin.PULL_DOWN) self.y1=Pin('Y10', Pin.IN, Pin.PULL_DOWN) self.y2=Pin('Y8', Pin.IN, Pin.PULL_DOWN) self.extInts = (ExtInt('Y9', ExtInt.IRQ_RISING, Pin.PULL_DOWN, self.x11), ExtInt('Y10', ExtInt.IRQ_RISING, Pin.PULL_DOWN, self.y11))
def ultrasound(): Trigger = Pin('X3', Pin.OUT_PP) Echo = Pin('X4',Pin.IN) # Create a microseconds counter. micros = pyb.Timer(2, prescaler=83, period=0x3fffffff) micros.counter(0) start = 0 end = 0 # Send a 20usec pulse every 10ms while True: Trigger.high() pyb.udelay(20) Trigger.low() # Wait until pulse starts while Echo.value() == 0: # do nothing start = micros.counter() # mark time at rising edge # Wait until pulse goes low while Echo.value() == 1: # do nothing end = micros.counter() # mark time at falling edge # Duration echo pulse = end - start # Divide this by 2 to take account of round-trip # Speed of sound in air is 340 m/s or 29 us/cm # Distance in cm = (pulse_width)*0.5/29 distance = int(((end - start) / 2) / 29) print('Distance: ', distance, ' cm') pyb.delay(500)
def flash_LEDs(): rLED = Pin('Y9', Pin.OUT_PP) bLED = Pin('Y10',Pin.OUT_PP) while True: rLED.high() pyb.delay(250) bLED.high() pyb.delay(250) rLED.low() pyb.delay(250) bLED.low() pyb.delay(250)
class TrackBall: def __init__(self,qq): self.volEnQueueable = EnQueueable((EnQueueable.INC,EnQueueable.VOL),qq) self.toneEnQueueable = EnQueueable((EnQueueable.INC,EnQueueable.TONE),qq) self.targCoilID = 0; self.x1=Pin(State.trackballStateDict['x1'], Pin.IN, Pin.PULL_DOWN) self.x2=Pin(State.trackballStateDict['x2'], Pin.IN, Pin.PULL_DOWN) self.y1=Pin(State.trackballStateDict['y1'], Pin.IN, Pin.PULL_DOWN) self.y2=Pin(State.trackballStateDict['y2'], Pin.IN, Pin.PULL_DOWN) self.extInts = (ExtInt(State.trackballStateDict['x1'], ExtInt.IRQ_RISING, Pin.PULL_DOWN, self.x11), ExtInt(State.trackballStateDict['y1'], ExtInt.IRQ_RISING, Pin.PULL_DOWN, self.y11)) def x11(self,unused): if self.x2.value(): irq_state = disable_irq() self.volEnQueueable.push(self.targCoilID,-1) enable_irq(irq_state) else: irq_state = disable_irq() self.volEnQueueable.push(self.targCoilID,1) enable_irq(irq_state) def y11(self,unused): if self.y2.value(): irq_state = disable_irq() self.toneEnQueueable.push(self.targCoilID,-1) enable_irq(irq_state) else: irq_state = disable_irq() self.toneEnQueueable.push(self.targCoilID,1) enable_irq(irq_state) def __repr__(self): res = 'TrackBall:' + \ '\nvolEnQueueable: \t' + repr(self.volEnQueueable) + \ '\ntoneEnQueueable:\t' + repr(self.toneEnQueueable) + \ '\ntargCoilID: \t' + str(self.targCoilID) + \ '\nx1: \t' + str(self.x1) + \ '\nx2: \t' + str(self.x2) + \ '\ny1: \t' + str(self.y1) + \ '\ny2: \t' + str(self.y2) #+ \ #'\nExtInts: \t' + str([i for i in self.extInts]) return res
def __init__(self): self.cs_pin = Pin('PE3', Pin.OUT_PP, Pin.PULL_NONE) self.cs_pin.high() self.spi = SPI(1, SPI.MASTER, baudrate=328125, polarity=0, phase=1, bits=8) self.write_bytes(LIS302DL_CTRL_REG1_ADDR, bytearray([LIS302DL_CONF])) if self.read_id() != LIS302DL_WHO_AM_I_VAL: raise Exception('LIS302DL accelerometer not present')
def __init__(self,qq): self.volEnQueueable = EnQueueable((EnQueueable.INC,EnQueueable.VOL),qq) self.toneEnQueueable = EnQueueable((EnQueueable.INC,EnQueueable.TONE),qq) self.targCoilID = 0; self.x1=Pin(State.trackballStateDict['x1'], Pin.IN, Pin.PULL_DOWN) self.x2=Pin(State.trackballStateDict['x2'], Pin.IN, Pin.PULL_DOWN) self.y1=Pin(State.trackballStateDict['y1'], Pin.IN, Pin.PULL_DOWN) self.y2=Pin(State.trackballStateDict['y2'], Pin.IN, Pin.PULL_DOWN) self.extInts = (ExtInt(State.trackballStateDict['x1'], ExtInt.IRQ_RISING, Pin.PULL_DOWN, self.x11), ExtInt(State.trackballStateDict['y1'], ExtInt.IRQ_RISING, Pin.PULL_DOWN, self.y11))
def __init__(self, bus=1, baudrate=328125, polarity=0, phase=0, ss='A4'): self.ss = Pin(ss, Pin.OUT) self.ss.high() self.spi = SPI(bus, SPI.MASTER, baudrate=baudrate, polarity=polarity, phase=phase) self.msgbuf = bytearray(32) self.status = bytearray(4)
def __init__(self, cs='PE3', spi=1, debug=False): self._debug = debug self.cs_pin = Pin(cs, Pin.OUT_PP, Pin.PULL_NONE) self.cs_pin.high() self.spi = SPI(spi, SPI.MASTER, baudrate=328125, polarity=0, phase=1, bits=8) self.read_id() # First SPI read always returns 255 --> discard and read ID again self.who_am_i = self.read_id() self.debug("Accel-ID: %s" % self.who_am_i) if self.who_am_i == LIS302DL_WHO_AM_I_VAL: self.write_bytes(LIS302DL_CTRL_REG1_ADDR, LIS302DL_CONF) self.sensitivity = 18 elif self.who_am_i == LIS3DSH_WHO_AM_I_VAL: self.write_bytes(LIS3DSH_CTRL_REG4_ADDR, LIS3DSH_CTRL_REG4_CONF) self.write_bytes(LIS3DSH_CTRL_REG5_ADDR, LIS3DSH_CTRL_REG5_CONF) self.sensitivity = 0.06 * 256 else: msg = 'LIS302DL or LIS3DSH accelerometer not present' if self._debug: self.debug(msg) else: raise IOError(msg)
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
class STAccel: def __init__(self): self.cs_pin = Pin('PE3', Pin.OUT_PP, Pin.PULL_NONE) self.cs_pin.high() self.spi = SPI(1, SPI.MASTER, baudrate=328125, polarity=0, phase=1, bits=8) self.write_bytes(LIS302DL_CTRL_REG1_ADDR, bytearray([LIS302DL_CONF])) if self.read_id() != LIS302DL_WHO_AM_I_VAL: raise Exception('LIS302DL accelerometer not present') def read_bytes(self, addr, nbytes): if nbytes > 1: addr |= READWRITE_CMD | MULTIPLEBYTE_CMD else: addr |= READWRITE_CMD self.cs_pin.low() self.spi.send(addr) #buf = self.spi.send_recv(bytearray(nbytes * [0])) # read data, MSB first buf = self.spi.recv(nbytes) self.cs_pin.high() return buf def write_bytes(self, addr, buf): if len(buf) > 1: addr |= MULTIPLEBYTE_CMD self.cs_pin.low() self.spi.send(addr) for b in buf: self.spi.send(b) self.cs_pin.high() def read_id(self): return self.read_bytes(LIS302DL_WHO_AM_I_ADDR, 1)[0] def x(self): return convert_raw_to_g(self.read_bytes(LIS302DL_OUT_X, 1)[0]) def y(self): return convert_raw_to_g(self.read_bytes(LIS302DL_OUT_Y, 1)[0]) def z(self): return convert_raw_to_g(self.read_bytes(LIS302DL_OUT_Z, 1)[0]) def xyz(self): val = self.read_bytes(LIS302DL_OUT_X, 5) return [convert_raw_to_g(val[0]), convert_raw_to_g(val[2]), convert_raw_to_g(val[4])]
def __init__(self, index): timer = timers[rc_pins_timers[index]] self.pin = Pin(rc_pins[index]) self.channel = timer.channel(rc_pins_channels[index], Timer.IC, pin=self.pin, polarity=Timer.BOTH) self.channel.callback(self.callback)
class JoyStick: # expo formula # ouput =((EXPO*POW(input,3))+((1-EXPO)*input))*RATE # where input & output are on [-1,1] def __init__(self,xp,yp, pbp, pbFunc): # last arg is a pointer to the interrupt handler self.XPin = ADC(Pin(xp)) self.YPin = ADC(Pin(yp)) self.PBPin = Pin(pbp, Pin.IN, Pin.PULL_UP) self.maxAnalog = 4095 self.minAnalog = 0 self.maxOutput = 100 self.minOutput = -100 self.pinExpo = 25 self.onPB = pbFunc self.changeDelta = 400 # ms self.lastChangeTime = 0 # ms self._calibrateXY() def _calibrateXY(self): xSum = 0 ySum = 0 for i in range(100): xSum += self.XPin.read() ySum += self.YPin.read() self.X0 = round(xSum/100.0) self.Y0 = round(ySum/100.0) def checkPB(self): now = time.ticks_ms() if now-self.lastChangeTime > self.changeDelta: if not self.PBPin.value(): self.onPB() self.lastChangeTime = now def _read(self, x): pin = self.XPin V0 = self.X0 if not x: pin = self.YPin V0 = self.Y0 val = pin.read() if abs(val - V0) < self.pinExpo: return(0) return arduino_map(val,V0,self.maxAnalog,0,self.maxOutput) \ if val > self.X0 else \ arduino_map(val,self.minAnalog,V0,self.minOutput,0) def readX(self): return self._read(True) def readY(self): return self._read(False)
def __init__(self, width, height, depth, red, green, blue, a, b, c, d, clk, latch, oe): self.__width = width self.__bwidth = width//4*3 self.__height = height self.__BYTES_PER_WEIGHT= 3*width*height>>3 self.__BITPERCOLOR = depth self.__red = tuple(Pin(i, Pin.OUT_PP) for i in red) self.__green = tuple(Pin(i, Pin.OUT_PP) for i in green) self.__blue = tuple(Pin(i, Pin.OUT_PP) for i in blue) self.__color = list(Pin(i, Pin.OUT_PP) for i in color_sel) self.__color.extend(list(Pin(i, Pin.OUT_PP) for i in green)) self.__color.extend(list(Pin(i, Pin.OUT_PP) for i in blue)) print(self.__color) self.__a = Pin(a, Pin.OUT_PP) self.__b = Pin(b, Pin.OUT_PP) self.__c = Pin(c, Pin.OUT_PP) self.__d = None self.__cycle_max = 8 if d is not None: self.__d = Pin(d, Pin.OUT_PP) self.__cycle_max = 16 self.__clk = Pin(clk, Pin.OUT_PP) self.__latch = Pin(latch, Pin.OUT_PP) self.__oe = Pin(oe, Pin.OUT_PP) self.__buffer = bytearray(self.__width*self.__height*2) self.__next_linenr = 0 self.__next_ln2weight = 1 self.__set_hi = [] self.__set_lo = [] if self.DEBUG: print(self)
def __init__(self,spiOnX,latchPin): # create an SPI.MASTER instance on the 'X' side of the board, # first arg=1 means 'X side' of the board boardSide = 1 if not spiOnX: boardSide = 2 self.spi = SPI(boardSide,SPI.MASTER) # create the stcp pin on the "latch" pin self.stcp = Pin(latchPin, Pin.OUT_PP)
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)
def __init__( self, pin ) : """Pin may be a pin name or pyb.Pin object set for output.""" if type(pin) == str: self._pin = Pin(pin, Pin.OUT_PP, Pin.PULL_DOWN) elif type(pin) == Pin: self._pin = pin else: raise Exception("pin must be pin name or pyb.Pin") self.on = False
def __init__(self, uart_num, pin_rw, dev_id): self.error = [] self.uart = UART(uart_num) self.uart.init(57600, bits=8, parity=0, timeout=10, read_buf_len=64) self.pin_rw = Pin(pin_rw) self.pin_rw.init(Pin.OUT_PP) self.pin_rw.value(0) self.dev_id = dev_id self.file_parts = 0 self.file_parts_i = 1 self.file_is_open = False
def init(timer_id=2, data_pin='Y2', the_dhttype='DHT22'): global _dataDHT global micros global timer global dhttype if (the_dhttype == 'DHT11'): dhttype = 0 else: dhttype = 1 # Configure the pid for data communication _dataDHT = Pin(data_pin) # Save the ID of the timer we are going to use _dataDHT = timer_id # setup the 1uS timer micros = pyb.Timer(timer, prescaler=83, period=0x3fffffff) # 1MHz ~ 1uS # Prepare interrupt handler ExtInt(_dataDHT, ExtInt.IRQ_FALLING, Pin.PULL_UP, None) ExtInt(_dataDHT, ExtInt.IRQ_FALLING, Pin.PULL_UP, _interuptHandler) _dataDHT.high() pyb.delay(250)
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)
def reset(self): """ Reset the module, then check it's working. """ print ("Initialising RFM...") self.nss.high() self.reset_pin = Pin('X4', Pin.OUT_PP) self.reset_pin.low() sleep(0.1) self.reset_pin.high() sleep(0.1) self.reset_pin.low() sleep(0.1)
def init(self, type=BLE_SHIELD): self.deinit() if type==self.BLE_SHIELD: self.rst=Pin("P7",Pin.OUT_OD,Pin.PULL_NONE) self.uart=UART(3,115200,timeout_char=1000) self.type=self.BLE_SHIELD self.rst.low() sleep(100) self.rst.high() sleep(100) self.uart.write("set sy c m machine\r\nsave\r\nreboot\r\n") sleep(1000) self.uart.readall() # clear
class TrackBall: def __init__(self,qq): self.x1=Pin('Y9', Pin.IN, Pin.PULL_DOWN) self.x2=Pin('Y7', Pin.IN, Pin.PULL_DOWN) self.y1=Pin('Y10', Pin.IN, Pin.PULL_DOWN) self.y2=Pin('Y8', Pin.IN, Pin.PULL_DOWN) self.extInts = (ExtInt('Y9', ExtInt.IRQ_RISING, Pin.PULL_DOWN, self.x11), ExtInt('Y10', ExtInt.IRQ_RISING, Pin.PULL_DOWN, self.y11)) def x11(self,unused): if self.x2.value(): print('X axis:\t-1') else: print('X axis:\t+1') def y11(self,unused): if self.y2.value(): print('Y axis:\t-1') else: print('Y axis:\t+1') def __repr__(self): res = 'TrackBall:' + \ '\nvolEnQueueable: \t' + repr(self.volEnQueueable) + \ '\ntoneEnQueueable:\t' + repr(self.toneEnQueueable) + \ '\ntargCoilID: \t' + str(self.targCoilID) + \ '\nx1: \t' + str(self.x1) + \ '\nx2: \t' + str(self.x2) + \ '\ny1: \t' + str(self.y1) + \ '\ny2: \t' + str(self.y2) + \ '\nExtInts: \t' + str([i for i in self.extInts]) return res
sensor.__write_reg(0x3026, 0x00) sensor.__write_reg(0x3027, 0x00) sensor.__write_reg(0x3028, 0x00) sensor.__write_reg(0x3029, 0x7f) sensor.__write_reg(0x3000, 0x00) while (True): result = sensor.__read_reg(0x3029) print('FW_STATUS: %X' % result) if result != 0x7F: break sleep(500) blue_led = LED(1) KEY = Pin('C13', Pin.IN, Pin.PULL_DOWN) sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QVGA) if sensor.get_id() != sensor.OV5640: print('Only run for ov5640') sys.exit(0) print('ov5640 AF Firmware Init ...') OV5640AF_Init() clock = time.clock() keycount = 0
import time from pyb import Pin, SPI cs = Pin("P3", Pin.OUT) rst = Pin("P4", Pin.OUT) dc = Pin("P5", Pin.OUT) # The hardware SPI bus for your OpenMV Cam is always SPI bus 2. spi = SPI(1, SPI.MASTER, baudrate=50000000, polarity=0, phase=0) TFT_DISPLAY_DIR = 2 #0 竖屏模式 #1 竖屏模式 旋转180 #2 横屏模式 #3 横屏模式 旋转180 if TFT_DISPLAY_DIR < 2: TFT_X_MAX = 128 TFT_Y_MAX = 160 else: TFT_X_MAX = 160 TFT_Y_MAX = 128 TFT_BLACK = 0X0000 #黑色 TFT_WHITE = 0XFFFF #白色 TFT_RED = 0XF800 #红色 TFT_GREEN = 0X0F01 #绿色 TFT_BLUE = 0X085F #蓝色 TFT_PINK = 0XF81F #粉紫 TFT_YELLOW = 0XFFE0 #黄色 TFT_CYAN = 0X07FF #青色 TFT_ORANGE = 0XFBE0 #橙色 #定义写字笔的颜色 PENCOLOR = 0XFFFF
from pyb import Pin pin = Pin("D8", Pin.OUT_PP) # En sortie "classique" (push-pull) pin.on() # Etat haut (3,3 V) #pin.off() # Etat bas (0 V)
def __init__(self, out1, out2, pwm, chan, tim): self.o1 = Pin(out1, Pin.OUT_PP) self.o2 = Pin(out2, Pin.OUT_PP) self.pwm = Pin(pwm) self.ch = tim.channel(chan, Timer.PWM, pin = self.pwm) self.speed = 50
''' Example using the MAX14914PMB. This scripts toggles output of MAX14914. Created on 9.03.2021 @author: JH ''' from pyb import Pin import time import logging logger = logging.getLogger(__name__) logger.info("MAX22191PMB example running") DI1 = Pin(Pin.cpu.C1, Pin.OUT_PP) DI2 = Pin(Pin.cpu.A7, Pin.OUT_PP) while (True): for cursor in '|/-\\': DI1_lvl = DI1.value() DI2_lvl = DI2.value() text = cursor + " DI1 state: " + str(DI1_lvl) + "; DI2 state: " + str( DI2_lvl) print(text, end='\r') time.sleep(0.2)
micropython.alloc_emergency_exception_buf(100) # I2C connected to Y9, Y10 (I2C bus 2) and Y11 is reset low active oled = OLED_938(pinout={ 'sda': 'Y10', 'scl': 'Y9', 'res': 'Y8' }, height=64, external_vcc=False, i2c_devid=61) oled.poweron() oled.init_display() # define ports for microphone, LEDs and trigger out (X5) mic = ADC(Pin('Y11')) MIC_OFFSET = 1523 # ADC reading of microphone for silence dac = pyb.DAC(1, bits=12) # Output voltage on X5 (BNC) for debugging b_LED = LED(4) # flash for beats on blue LED N = 160 # size of sample buffer s_buf[] s_buf = array('H', 0 for i in range(N)) # reserve buffer memory ptr = 0 # sample buffer index pointer buffer_full = False # semaphore - ISR communicate with main program def flash(): # routine to flash blue LED when beat detected b_LED.on() pyb.delay(20) b_LED.off()
#main.py import pyb from pyb import Pin from ds18b20 import DS18X20 DQ = DS18X20(Pin('PD4')) #DQ while True: tem = DQ.read_temp() print(tem) pyb.delay(1000)
from pyb import Pin, ADC from ds18b20 import DS18X20 gl = ADC(Pin('Y12')) #300亮-1700暗 sd = ADC(Pin('Y11')) #1800干-800湿 wd = DS18X20(Pin('Y10')) ks = Pin('Y9', Pin.OUT_PP) jr = Pin('Y8', Pin.OUT_PP) while True: print('\t光照强度:',gl.read(),'\t土壤湿度:',sd.read(),'\t当前温度:',wd.read_temp()) pyb.delay(200) if gl.read()<=250 : #阳光充足 if sd.read()>800 : #多浇水 ks.value(1) else : ks.value(0) elif gl.read()>=1300 : #阳光不足 if sd.read()>1200 : #少浇水 ks.value(1) else : ks.value(0) else : #阳光一般 if sd.read()>1000 : #正常浇水 ks.value(1) else : ks.value(0) if wd.read_temp()<18 : #温度过低 jr.value(1) else : jr.value(0)
def sw2_callback(pin): print(pin) sw2 = Pin.board.SW2 sw2_af = sw2.af_list() #sw2 already in inport mode print(sw2) print(sw2.af_list()) #set pin to alterate function #d1 = Pin(Pin.board.D1, Pin.ALT, alt = 0) #d1 = Pin(Pin.board.D1, Pin.ALT, alt = Pin.AF_PB3_EADC0_CH3) sw2.irq(handler=sw2_callback, trigger=Pin.IRQ_RISING) #change ledr to output mode r = Pin('LEDR', Pin.OUT) #r = Pin('LEDR', Pin.OUT, pull = None, value = 0) #Defalut output low print(r) print(r.af_list()) while True: pin_value = sw2.value() if pin_value == 0: print('key press') break print('demo done')
class DS18X20(object): def __init__(self, pin): self.ow = OneWire(pin) # Scan the 1-wire devices, but only keep those which have the # correct # first byte in their rom for a DS18x20 device. self.CLK = Pin("Y11", Pin.OUT_PP) self.roms = [ rom for rom in self.ow.scan() if rom[0] == 0x10 or rom[0] == 0x28 ] def read_temp(self, rom=None): """ Read and return the temperature of one DS18x20 device. Pass the 8-byte bytes object with the ROM of the specific device you want to read. If only one DS18x20 device is attached to the bus you may omit the rom parameter. """ self.CLK.high() self.CLK.low() rom = rom or self.roms[0] ow = self.ow ow.reset() ow.select_rom(rom) ow.write_byte(0x44) # Convert Temp while True: if ow.read_bit(): break ow.reset() ow.select_rom(rom) ow.write_byte(0xbe) # Read scratch data = ow.read_bytes(9) return self.convert_temp(rom[0], data) def read_temps(self): """ Read and return the temperatures of all attached DS18x20 devices. """ temps = [] for rom in self.roms: temps.append(self.read_temp(rom)) return temps def convert_temp(self, rom0, data): """ Convert the raw temperature data into degrees celsius and return as a float. """ temp_lsb = data[0] temp_msb = data[1] if rom0 == 0x10: if temp_msb != 0: # convert negative number temp_read = temp_lsb >> 1 | 0x80 # truncate bit 0 by shifting, fill high bit with 1. temp_read = -((~temp_read + 1) & 0xff ) # now convert from two's complement else: temp_read = temp_lsb >> 1 # truncate bit 0 by shifting count_remain = data[6] count_per_c = data[7] temp = temp_read - 0.25 + (count_per_c - count_remain) / count_per_c return temp elif rom0 == 0x28: return (temp_msb << 8 | temp_lsb) / 16 else: assert False
# Voir class FrameBuffer pour les méthodes d'écriture et de dessin from pyb import Pin from machine import I2C from ssd1306 import SSD1306_I2C i2c = I2C(scl=Pin('SCL'), sda=Pin('SDA')) oled = SSD1306_I2C(128, 32, i2c, 0x3c) oled.fill(0) oled.text("Hello David", 0, 0) oled.text("R =", 0, 10) oled.show()
class Motor: def __init__(self, out1, out2, pwm, chan, tim): self.o1 = Pin(out1, Pin.OUT_PP) self.o2 = Pin(out2, Pin.OUT_PP) self.pwm = Pin(pwm) self.ch = tim.channel(chan, Timer.PWM, pin = self.pwm) self.speed = 50 def forward(self): self.o1.high() self.o2.low() self.ch.pulse_width_percent(self.speed) def stop(self): self.o1.low() self.o2.low() self.ch.pulse_width_percent(0) def backward(self): self.o1.low() self.o2.high() self.
# Detection sound intensity # Hardware : SoundSensor, OpenMV # connect: # SoundSensor OpenMV # VCC 3V3 # GND GND # data P6 from pyb import ADC,Pin import time adc0=ADC(Pin('P6')) # Connect sensor to 'P6', Must always be "P6". while True: val=adc0.read() # Read data print(val) time.sleep(100)
import pyb from pyb import * from pyb import Pin, ADC, Timer print('ms2+ms3_taking_penalty') print('group 15: Fan & Grace') # Variable -------------------------------------------------- speed = 50 # standard driving speed # Defining the motor modules and servo-------------------------------------- A1 = Pin('Y9', Pin.OUT_PP) # motor A is on the RHS of the vehicle A2 = Pin('Y10', Pin.OUT_PP) motor1 = Pin('X1') B1 = Pin('Y11', Pin.OUT_PP) # motor B is on the LHS of the vehicle B2 = Pin('Y12', Pin.OUT_PP) motor2 = Pin('X2') tim = Timer(2, freq=1000) ch1 = tim.channel(1, Timer.PWM, pin=motor1) ch2 = tim.channel(2, Timer.PWM, pin=motor2) servo = Servo(3) # servo on position 3 (X3, VIN, GND) # Defining button functions-------------------------------------------------- def stop(): ch1.pulse_width_percent(0) # send a pulse of width 0% to motor A ch2.pulse_width_percent(0) # send a pulse of width 0% to motor B
import sensor, image, time, math, pyb from pyb import Pin p_out = Pin('P1', Pin.OUT) p_out.low() po = Pin('P2', Pin.OUT) po.low() s1 = pyb.Servo(1) s2 = pyb.Servo(2) sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QVGA) sensor.skip_frames(time=2000) sensor.set_auto_gain(False) sensor.set_auto_whitebal(False) clock = time.clock() while (True): clock.tick() img = sensor.snapshot() img.lens_corr(1.8) matrices = img.find_datamatrices() for matrix in matrices: img.draw_rectangle(matrix.rect(), color=(255, 0, 0)) print_args = (matrix.rows(), matrix.columns(), matrix.payload(), (180 * matrix.rotation()) / math.pi, clock.fps()) print("Matrix [%d:%d], Payload \"%s\", rotation %f (degrees), FPS %f" % print_args)
from pyb import Pin, ADC from math import log from time import sleep_ms adc = ADC(Pin("A2")) # Déclaration de l'ADC sur la broche A0 Ro = 10e3 # Résistance série A = 0.0010832035972923174 # Coeff. de Steinhart-Hart B = 0.00021723460553451255 # ... C = 3.276999926128753e-07 # ... while True: N = adc.read() # Mesure de la tension R = Ro * N / (4095 - N) # Calcul de R_CTN T = 1 / (A + B * log(R) + C * log(R)**3) - 273.15 # Relation de Steinhart-Hart print("R =", R, "T =", T) # Affichage sleep_ms(1000) # Temporisation
def __init__(self): self.adc = ADC(Pin('rINC')) self._timer = Timer(7, freq=100) self._buffer = bytearray(10)
''' ------------------------------------------------------- Name: main Creator: Higor Alves ------------------------------------------------------- ''' import pyb from pyb import Pin, LED # Configure X2:4, X7 as setting input pin - pull_up to receive switch settings s0=Pin('Y3',pyb.Pin.IN,pyb.Pin.PULL_UP) s1=Pin('X6',pyb.Pin.IN,pyb.Pin.PULL_UP) r_LED = LED(1) g_LED = LED(2) y_LED = LED(3) b_LED = LED(4) ''' Define various test functions ''' def read_sw(): value = 3 - (s0.value() + 2*s1.value()) if (not s0.value()): y_LED.on() if (not s1.value()): g_LED.on() return value if read_sw() == 0: print('Running Milestone 1: BLE Control')
ballThreshold = [(52, 94, 9, 76, -44, 57)] sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QVGA) sensor.skip_frames(time=2000) sensor.set_auto_gain(False) # must be turned off for color tracking sensor.set_auto_whitebal(False) # must be turned off for color tracking sensor.set_brightness(-2) clock = time.clock() # Only blobs that with more pixels than "pixel_threshold" and more area than "area_threshold" are # returned by "find_blobs" below. Change "pixels_threshold" and "area_threshold" if you change the # camera resolution. "merge=True" merges all overlapping blobs in the image. p0 = Pin('P0', Pin.OUT_PP, Pin.PULL_NONE ) # p0, p1 11 - straight 10 - left 01 - right 00 - do not see p1 = Pin('P1', Pin.OUT_PP, Pin.PULL_NONE) initPin = Pin('P2', Pin.IN, Pin.PULL_NONE) #initialize input proxValuePin = Pin('P3', Pin.IN, Pin.PULL_NONE) #proximity sensor input seeBallPin = Pin('P4', Pin.OUT_PP, Pin.PULL_NONE) #have ball or not output diagPin = Pin('P5', Pin.OUT_PP, Pin.PULL_NONE) isInitialized = False def initialize(): while (True): print("Trying to Initialize") img = sensor.snapshot() goalBlobs = img.find_blobs(goalThresholds, pixels_threshold=100,
# main.py -- put your code here! from pyb import SPI, Pin, LED, delay, UART push_button = pyb.Pin("PA0", pyb.Pin.IN, pyb.Pin.PULL_DOWN) uart = UART(2, 115200) CS = Pin("PE3", Pin.OUT_PP) SPI_1 = SPI( 1, SPI.MASTER, baudrate=50000, polarity=0, phase=0, ) CS.low() SPI_1.send(0x0F | 0x80) tab_values = SPI_1.recv(1) CS.high() value = tab_values[0] while True: uart.write(value)
class can_tmcl_interface(tmcl_interface, tmcl_host_interface): def __init__(self, port=2, data_rate=None, host_id=2, module_id=1, debug=False, can_mode=CanModeNormal()): del data_rate tmcl_interface.__init__(self, host_id, module_id, debug) tmcl_host_interface.__init__(self, host_id, module_id, debug) self.__silent = Pin(Pin.cpu.B14, Pin.OUT_PP) self.__mode = can_mode self.__flag_recv = False self.__set_mode() CAN.initfilterbanks(14) self.__can = CAN(port, CAN.NORMAL) # PCLK1 = 42 MHz, Module_Bitrate = 1000 kBit/s # With prescaler = 3, bs1 = 11, bs2 = 2 # Sample point at 85.7 %, accuracy = 100 % self.__can.init(CAN.NORMAL, prescaler=3, bs1=11, bs2=2, auto_restart=True) self.__can.setfilter(0, CAN.LIST16, 0, (host_id, host_id, host_id, host_id)) self.__can.rxcallback(0, self.__callback_recv) def __enter__(self): return self def __exit__(self, exitType, value, traceback): del exitType, value, traceback self.close() def close(self): pass def data_available(self, hostID=None, moduleID=None): del hostID, moduleID return self.__can.any(0) def _send(self, hostID, moduleID, data): del hostID, moduleID self.__can.send(data[1:], data[0]) def __callback_recv(self, bus, reason): if (reason != 0): pass self.__flag_recv = True def _recv(self, hostID, moduleID): del hostID, moduleID while (not (self.__flag_recv)): pass self.__flag_recv = False received = self.__can.recv(0, timeout=1000) read = struct.pack("B", received[0]) + received[3] return read def printInfo(self): pass def enableDebug(self, enable): self._debug = enable def set_mode(self, mode): self.__mode = mode self.__set_mode() def get_mode(self): return self.__mode def __set_mode(self): if (isinstance(self.__mode, CanModeNormal)): self.__silent.low() elif (isinstance(self.__mode, CanModeSilent)): self.__silent.high() elif (isinstance(self.__mode, CanModeOff)): pass # Not supported by TJA1051T/3 def get_can(self): return self.__can @staticmethod def supportsTMCL(): return True @staticmethod def supportsCANopen(): return False @staticmethod def available_ports(): return set([2])
from pyb import Pin, Timer p = Pin('X1') # X1 has TIM2, CH1 tim = Timer(2, freq=1000) ch = tim.channel(1, Timer.PWM, pin=p) ch.pulse_width_percent(50)
import machine, network, ubinascii, ujson, urequests, utime from pyb import Pin pin1 = Pin('Y4', Pin.IN) pin2 = Pin('Y3', Pin.IN) runPin = Pin('X3', Pin.OUT) class Encoder(object): def __init__(self, pin_x, pin_y, reverse, scale): self.reverse = reverse self.scale = scale self.forward = True self.pin_x = pin_x self.pin_y = pin_y self._pos = 0 self.x_interrupt = pyb.ExtInt(pin_x, pyb.ExtInt.IRQ_RISING_FALLING, pyb.Pin.PULL_NONE, self.x_callback) self.y_interrupt = pyb.ExtInt(pin_y, pyb.ExtInt.IRQ_RISING_FALLING, pyb.Pin.PULL_NONE, self.y_callback) def x_callback(self, line): self.forward = self.pin_x.value() ^ self.pin_y.value() ^ self.reverse self._pos += 1 if self.forward else -1 def y_callback(self, line): self.forward = self.pin_x.value() ^ self.pin_y.value( ) ^ self.reverse ^ 1 self._pos += 1 if self.forward else -1 @property
import math import json import sys from pyb import Pin import utime sys.path.append('/Localization') sys.path.append('/tools') from robot import Robot from field import Field from median import median from ParticleFilter import updatePF, ParticleFilter pin9 = Pin('P9', Pin.IN, Pin.PULL_UP) pin3 = Pin('P3', Pin.IN, Pin.PULL_UP) pin2 = Pin('P2', Pin.IN, Pin.PULL_UP) class Localization: def __init__(self, x, y, yaw, side, button=True): b_time = utime.ticks_ms() print(b_time) side_loop = 0 side = False while (side_loop == 0): if (pin9.value() == 0): # нажатие на кнопку на голове side_loop = 1 side = True print("I will attack blue goal") break
# Detect infrared (IR) of people/ animals in motion # Hardware : PIRMotionSensor, OpenMV # connect: # PIRMotionSensor OpenMV # VCC 3V3 # GND GND # data P0 from pyb import Pin, LED import time ir = Pin('P0', Pin.IN) # Connect sensor to 'P0' led = LED(1) while (1): state = ir.value() # Read value of ir if (state != 0): led.on() print("Somebody is in this area!") else: led.off() print("No one!") time.sleep(500)
import pyb from pyb import LED, DAC, ADC, Pin from oled_938 import OLED_938 from mpu6050 import MPU6050 # Define various ports, pins and peripherals a_out = DAC(1, bits=12) pot = ADC(Pin('X11')) b_LED = LED(4) # Use OLED to say what it is doing oled = OLED_938(pinout={'sda': 'Y10', 'scl': 'Y9', 'res': 'Y8'}, height=64, external_vcc=False, i2c_devid=61) oled.poweron() oled.init_display() oled.draw_text(0, 0, 'Measure pitch and pitch_dot') oled.draw_text(0,20, 'CCW: pitch (deg)') oled.draw_text(0,30, 'CW: pitch_dot (deg/s)') oled.display() # IMU connected to X9 and X10 imu = MPU6050(1, False) # Pitch angle calculation using complementary filter def pitch_estimate(pitch, dt, alpha): theta = imu.pitch() pitch_dot = imu.get_gy() pitch = alpha*(pitch + pitch_dot*dt) + (1-alpha)*theta return (pitch, pitch_dot) ''' Main program loop
from sequence_factory import SequenceFactory import dma_controller import time import config from pyb import Pin import pyb p_SICL = Pin(config.SICL, Pin.OUT_PP) p_SIBL = Pin(config.SIBL, Pin.OUT_PP) p_CK = Pin(config.CK, Pin.OUT_PP) p_LAT = Pin(config.LAT, Pin.OUT_PP) p_CH = Pin(config.CH, Pin.OUT_PP) p_NCHG = Pin(config.NCHG, Pin.OUT_PP) p_LAT.value(0) p_NCHG.value(0) dac = pyb.DAC(1) def latch_data(): p_LAT.value(1) p_LAT.value(0) def fire(): p_NCHG.value(1) output_waveform() p_NCHG.value(0) def output_waveform(): dac.write_timed(waveform_buf, freq=4000000, mode=pyb.DAC.CIRCULAR)
import sensor, image, time, math from pyb import Pin, Timer tim = Timer(4, freq=1000) # Frequency in Hz # 生成1kHZ方波,使用TIM4,channels 1 and 2分别是 50% 和 75% 占空比。 ch1 = tim.channel(1, Timer.PWM, pin=Pin("P7"), pulse_width_percent=100) sensor.reset() sensor.set_pixformat(sensor.GRAYSCALE) # grayscale is faster sensor.set_framesize(sensor.QQVGA) sensor.skip_frames(time=1000) clock = time.clock() grayscale_thres = (100, 255) thres = (0, 50) while (True): clock.tick() img = sensor.snapshot() img.binary([grayscale_thres]) blobs = img.find_blobs([thres], roi=[0, 33, 160, 3], pixels_threshold=20, margin=0) pixels_total = 0 max_pixels = 0 max_index = 0 i = 0 x = 240 if blobs: for blob in blobs:
yellow_threshold = (0, 72, -10, 1, 11, 42) #设置绿色的阈值,括号里面的数值分别是L A B 的最大值和最小值(minL, maxL, minA, # maxA, minB, maxB),LAB的值在图像左侧三个坐标图中选取。如果是灰度图,则只需 #设# 问吴老师 模板是什么?置(min, max)两个数字即可。 sensor.reset() # 初始化摄像头 sensor.set_pixformat(sensor.RGB565) # 格式为 RGB565. sensor.set_framesize(sensor.QQVGA) # 使用 QQVGA 速度快一些 sensor.skip_frames(10) # 跳过10帧,使新设置生效 sensor.set_auto_whitebal(False) # 问吴老师 模板是什么? #关闭白平衡。白平衡是默认开启的,在颜色识别中,一定要关闭白平衡。 clock = time.clock() # 追踪帧率 turn_threshold = 15 # rotate threshold turn = Pin('P0', Pin.OUT_PP) turnDone = Pin('P1', Pin.OUT_PP) red = LED(1) green = LED(2) blue = LED(3) blue.on() time.sleep(2) blue.off() arduino = UART(3, 19200) while (True): clock.tick() # Track elapsed milliseconds between snapshots(). img = sensor.snapshot() # 从感光芯片获得一张图像 img = img.lens_corr(2.5, 1.0)
from pyb import Pin #Set pin to alterate function #a3 = Pin(Pin.board.GPA3, Pin.ALT, alt = Pin.AF_PA3_KPI0_SI0) #print(a3) #For GPIO output #a3 = Pin(Pin.board.GPA3, Pin.OUT) #print(a3) #a3.value(1) count = 0 def pa3_callback(pin): count = count + 1 #For GPIO input a3 = Pin(Pin.board.GPA3, Pin.IN) a3.irq(handler=pa3_callback, trigger=Pin.IRQ_RISING) while True: print(count) pyb.delay(2000)