class SPI: def __init__(self, cs: int, baudrate: int = SPI_DEFAULT_BAUDRATE) -> None: self._SPICS = Pin(cs, Pin.OUT) self._SPI = self.init(baudrate=baudrate) # type: Any self.end() def init(self, baudrate: int) -> Any: raise NotImplementedError def start(self) -> None: self._SPICS.value(0) time.sleep_us(SPI_HOLD_US) # type: ignore def end(self) -> None: self._SPICS.value(1) time.sleep_us(SPI_HOLD_US) # type: ignore def transfer(self, value: int = SPI_DUMMY_INT, read: bool = False) -> Optional[int]: """Write int value to SPI and read SPI as int value simultaneously. This method supports transfer single byte only, and the system byte order doesn't matter because of that. The input and output int value are unsigned. """ value_as_byte = value.to_bytes(SPI_TRANSFER_LEN, sys.byteorder) if read: output = bytearray(SPI_TRANSFER_LEN) self._SPI.write_readinto(value_as_byte, output) return int.from_bytes(output, sys.byteorder) self._SPI.write(value_as_byte) return None
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 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)
class RotaryIRQ(Rotary): def __init__(self, pin_num_clk, pin_num_dt, min_val=0, max_val=10, reverse=False, range_mode=Rotary.RANGE_UNBOUNDED, pull_up=False, half_step=False, invert=False): super().__init__(min_val, max_val, reverse, range_mode, half_step, invert) if pull_up == True: self._pin_clk = Pin(pin_num_clk, Pin.IN, Pin.PULL_UP) self._pin_dt = Pin(pin_num_dt, Pin.IN, Pin.PULL_UP) else: self._pin_clk = Pin(pin_num_clk, Pin.IN) self._pin_dt = Pin(pin_num_dt, Pin.IN) self._pin_clk_irq = ExtInt(pin_num_clk, ExtInt.IRQ_RISING_FALLING, Pin.PULL_NONE, self._process_rotary_pins) self._pin_dt_irq = ExtInt(pin_num_dt, ExtInt.IRQ_RISING_FALLING, Pin.PULL_NONE, self._process_rotary_pins) # turn on 3.3V output to power the rotary encoder (pyboard D only) if 'PYBD' in os.uname().machine: Pin('EN_3V3').value(1) def _enable_clk_irq(self): self._pin_clk_irq.enable() def _enable_dt_irq(self): self._pin_dt_irq.enable() def _disable_clk_irq(self): self._pin_clk_irq.disable() def _disable_dt_irq(self): self._pin_dt_irq.disable() def _hal_get_clk_value(self): return self._pin_clk.value() def _hal_get_dt_value(self): return self._pin_dt.value() def _hal_enable_irq(self): self._enable_clk_irq() self._enable_dt_irq() def _hal_disable_irq(self): self._disable_clk_irq() self._disable_dt_irq() def _hal_close(self): self._hal_disable_irq()
def read_temps(self): #读取温度 data = [] j = 0 N1 = Pin(self.PinName, Pin.OUT_PP) #设置输出模式 #N1=self.N1 N1.low() #拉低引脚 time.sleep_ms(20) #保持20ms(最少18ms) N1.high() #拉高引脚 time.sleep_us(30) #保持30us(20~40us) #wait to response N1 = Pin(self.PinName, Pin.IN) #设置输入模式 while N1.value() == 1: #等待温度传感器响应 continue while N1.value() == 0: continue while N1.value() == 1: continue #get data while j < 40: #通过引脚接收数据 k = 0 while N1.value() == 0: continue while N1.value() == 1: k += 1 if k > 100: break if k < 3: data.append(0) else: data.append(1) j = j + 1 print('Sensor is working') #print(k) j = 0 #get temperature #利用接收的电平信号算出温湿度数值 humidity_bit = data[0:7] #0-7位湿度信息 humidity_point_bit = data[8:15] #8-15位湿度小数信息 temperature_bit = data[16:23] #16-23位温度信息 temperature_point_bit = data[24:31] #24-31位温度小数信息 check_bit = data[32:39] #32-39位校验信息 humidity = 0 humidity_point = 0 temperature = 0 temperature_point = 0 check = 0 for i in range(7): #计算温湿度 humidity += humidity_bit[i] * 2**(7 - i) humidity_point += humidity_point_bit[i] * 2**(7 - i) temperature += temperature_bit[i] * 2**(7 - i) temperature_point += temperature_point_bit[i] * 2**(7 - i) check += check_bit[i] * 2**(7 - i) tmp = humidity + humidity_point + temperature + temperature_point if check == tmp: #检验正确,输出结果 print('temperature is', temperature, 'wet is', humidity, '%') else: #检验错误,输出数据结果 print('SHUJUCUOWU', humidity, humidity_point, temperature, temperature_point, check) return str(temperature) + ',' + str(humidity)
def read_temps(self): data = [] j = 0 N1 = Pin(self.PinName, Pin.OUT_PP) N1.low() time.sleep(0.03) N1.high() #wait to response N1 = Pin(self.PinName, Pin.IN) while N1.value() == 1: continue while N1.value() == 0: continue while N1.value() == 1: continue #get data while j < 40: k = 0 while N1.value() == 0: continue while N1.value() == 1: k += 1 if k > 100: break if k < 3: data.append(0) else: data.append(1) j = j + 1 #print('Sensor is working') j = 0 #get temperature humidity_bit = data[0:8] humidity_point_bit = data[8:16] temperature_bit = data[16:24] temperature_point_bit = data[24:32] check_bit = data[32:40] humidity = 0 humidity_point = 0 temperature = 0 temperature_point = 0 check = 0 for i in range(8): humidity += humidity_bit[i] * 2**(7 - i) humidity_point += humidity_point_bit[i] * 2**(7 - i) temperature += temperature_bit[i] * 2**(7 - i) temperature_point += temperature_point_bit[i] * 2**(7 - i) check += check_bit[i] * 2**(7 - i) tmp = humidity + humidity_point + temperature + temperature_point if check == tmp: pass #print('temperature is',temperature,'wet is',humidity,'%') else: pass #print('SHUJUCUOWU',humidity,humidity_point,temperature,temperature_point,check) #return str(temperature)+','+str(humidity) return temperature, humidity
def __init__(self, chan, cs, xdim, ydim): self.spi = SPI(chan, SPI.MASTER, baudrate=1000000, polarity=0, phase=0, firstbit=SPI.LSB) self.xdim = xdim self.ydim = ydim if not isinstance(cs, Pin): cs = Pin(cs) cs.value(0) cs.init(Pin.OUT_PP) self.cs = cs self.usleep = udelay self.lines = [bytearray(xdim//8) for i in range(ydim)] self.changed = set()
def read_data(self): self.__init__(self.PinName) data = [] j = 0 N1 = self.N1 N1.low() delay(20) N1.high() N1 = Pin(self.PinName, Pin.IN) udelay(30) if N1.value() != 0: return [0, 0] while N1.value() == 0: continue while N1.value() == 1: continue while j < 40: k = 0 while N1.value() == 0: continue while N1.value() == 1: k += 1 if k > 100: break if k < 3: data.append(0) else: data.append(1) j = j + 1 print('Sensor is working') j = 0 humidity_bit = data[0:8] humidity_point_bit = data[8:16] temperature_bit = data[16:24] temperature_point_bit = data[24:32] check_bit = data[32:40] humidity = 0 humidity_point = 0 temperature = 0 temperature_point = 0 check = 0 for i in range(8): humidity += humidity_bit[i] * 2**(7 - i) humidity_point += humidity_point_bit[i] * 2**(7 - i) temperature += temperature_bit[i] * 2**(7 - i) temperature_point += temperature_point_bit[i] * 2**(7 - i) check += check_bit[i] * 2**(7 - i) tmp = humidity + humidity_point + temperature + temperature_point if check == tmp: print('temperature is', temperature, '-wet is', humidity, '%') else: print('Error:', humidity, humidity_point, temperature, temperature_point, check) return [str(temperature), str(humidity)]
class Laser: def init(self): #初始化 MyMapperDict = {'Laser': Pin.cpu.C2} Pin.dict(MyMapperDict) #映射引脚使用cpu的PC2 self.pin = Pin('Laser', Pin.OUT_PP) def on(self): #开 self.pin.value(1) def off(self): #关 self.pin.value(0)
class Buzzer: def init(self): #初始化 MyMapperDict = {'Buzzer': Pin.cpu.E2} Pin.dict(MyMapperDict) #映射引脚使用cpu的PE2 self.pin = Pin('Buzzer', Pin.OUT_PP) def on(self): #开 self.pin.value(1) def off(self): #关 self.pin.value(0)
class MAX14914: def __init__(self, do_set_pin=Pin.cpu.A5, do_pp_pin=Pin.cpu.A6, di_ena_pin=Pin.cpu.A7, dido_lvl_pin=Pin.cpu.C0, fault_pin=Pin.cpu.C1, ov_vdd_pin=Pin.cpu.A4): self.DO_SET = Pin(do_set_pin, Pin.OUT_PP) self.DO_PP = Pin(do_pp_pin, Pin.OUT_PP) self.DI_ENA = Pin(di_ena_pin, Pin.OUT_PP) self.DIDO_LVL = Pin(dido_lvl_pin, Pin.IN) self.FAULT = Pin(fault_pin, Pin.IN) self.OV_VDD = Pin(ov_vdd_pin, Pin.IN) def setIOMode(self, mode): ''' set input mode D0 = 0 or DI = 1''' if (mode == "0"): self.DI_ENA.low() elif (mode == "1"): self.DI_ENA.high() def setPPMode(self, mode): ''' set PP mode. In DO mode, set PP high (1) to enable push-pull mode operation of the DO driver. In DI mode, set PP low(0) for IEC Type 1/3 input characteristics and set high for Type 2 input characteristics. ''' if (mode == 0): self.DO_PP.low() elif (mode == 1): self.DO_PP.high() def setDO(self, state): '''set Digital Out''' self.DO_SET.value(state) def getDIDO_LVL(self): '''get level of DOI-PIN''' return self.DIDO_LVL.value() def getFault(self): '''getFault''' return not self.FAULT.value() def getOV_VDD(self): '''reports an overvoltage detection''' return self.OV_VDD.value()
def setupPin(pinLabel, pinMode, active_low): # pinMode is Pin.OUT_PP or Pin.IN if active_low == True: PULL_UP_DOWN = Pin.PULL_UP # An active low pin, so pull_up to ensure pin is low by default initial_state = 1 else: PULL_UP_DOWN = Pin.PULL_DOWN # active high pin, so use pull down resistors initial_state = 0 p = Pin(pinLabel, pinMode, PULL_UP_DOWN) p.value( initial_state ) # Sometimes, pull up/down resistors don'tt always seem to work for all pins to set an initial state return p
class SPI: def __init__(self): self.cs = Pin('X5', Pin.OUT_PP) self.cs.value(True) # Active low if 0: pd = Pin('X11', Pin.OUT_PP) pd.value(False) pd.value(True) self.sp = pyb.SPI(1, pyb.SPI.MASTER, baudrate=15000000, polarity=0, phase=0, bits=8, firstbit=pyb.SPI.MSB) def transfer(self, wr, rd=0): self.cs.value(False) self.sp.send(wr) if rd == 0: self.cs.value(True) else: r = bytearray(rd) self.sp.recv(r) self.cs.value(True) return r
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)
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('X5', Pin.OUT_PP) self.cs.value(True) # Active low if 0: pd = Pin('X11', Pin.OUT_PP) pd.value(False) pd.value(True) self.sp = pyb.SPI(1, pyb.SPI.MASTER, baudrate=15000000, polarity=0, phase=0, bits=8, firstbit=pyb.SPI.MSB)
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()
class Mode: def __init__(self, pin): #init constructor self.pin = Pin(pin, Pin.OUT_PP, pull=Pin.PULL_DOWN) self.is_active = False def activate(self): self.pin.value(1) self.is_active = True def deactivate(self): self.pin.value(0) self.is_active = False def toggle(self): if self.is_active: self.deactivate()
class encoder: # Init variables encoder_clk_prev = False i = 0 def __init__(self, clk_pin): # Configure the rotary encoder pins and interrupt self.clk = Pin(clk_pin, Pin.IN, Pin.PULL_UP) tim = Timer(-1) tim.init( # Timer to run self.update every 5ms period=5, mode=Timer.PERIODIC, callback=self.update) def getValue(self): return (self.i) # Return rotary encoder value # Non blocking delay of 5ms def update(self, p): # Read the rotary encoder pins self.encoder_clk = self.clk.value() if not self.encoder_clk and self.encoder_clk_prev: self.i += 1 if p == 0: self.i = 0 self.encoder_clk_prev = self.encoder_clk
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 read_data(self): self.__init__(self.PinName) data = [] j = 0 N1 = self.N1 N1.low() time.sleep(0.03) N1.high() N1 = Pin(self.PinName, Pin.IN) while N1.value() == 1: continue while N1.value() == 0: continue while N1.value() == 1: continue while j < 40: k = 0 while N1.value() == 0: continue while N1.value() == 1: k += 1 if k > 100: break if k < 3: data.append(0) else: data.append(1) j = j + 1 j = 0 humidity_bit = data[0:8] humidity_point_bit = data[8:16] temperature_bit = data[16:24] temperature_point_bit = data[24:32] check_bit = data[32:40] humidity = 0 humidity_point = 0 temperature = 0 temperature_point = 0 check = 0 for i in range(8): humidity += humidity_bit[i] * 2**(7 - i) humidity_point += humidity_point_bit[i] * 2**(7 - i) temperature += temperature_bit[i] * 2**(7 - i) temperature_point += temperature_point_bit[i] * 2**(7 - i) check += check_bit[i] * 2**(7 - i) tmp = humidity + humidity_point + temperature + temperature_point return [temperature, humidity]
class InputFromDue: def __init__(self, ip_pin): self.pin = ip_pin self.io_input = Pin(ip_pin, Pin.IN, Pin.PULL_UP) def value(self): return self.io_input.value()
class MAX14914: def __init__(self, do_set_pin=Pin.cpu.A5, do_pp_pin=Pin.cpu.A6, di_ena_pin=Pin.cpu.A7, dido_lvl_pin=Pin.cpu.C0, fault_pin=Pin.cpu.C1, ov_vdd_pin=Pin.cpu.A4): self.DO_SET = Pin(do_set_pin, Pin.OUT_PP) self.DO_PP = Pin(do_pp_pin, Pin.OUT_PP) self.DI_ENA = Pin(di_ena_pin, Pin.OUT_PP) self.DIDO_LVL = Pin(dido_lvl_pin, Pin.IN) self.FAULT = Pin(fault_pin, Pin.IN) self.OV_VDD = Pin(ov_vdd_pin, Pin.IN) def setIOMode(self, mode): ''' set input mode D0 = 0 or DI = 1''' if (mode == "0"): self.DI_ENA.low() elif (mode == "1"): self.DI_ENA.high() #DI_ENA = HIGH def setPPMode(self, mode): ''' set input mode D0 or DI''' if (mode == 0): self.DO_PP.low() elif (mode == 1): self.DO_PP.high() def setDO(self, state): '''set Digital Out''' self.DO_SET.value(state) def getDIDO_LVL(self): '''get level of DOI-PIN''' return self.DIDO_LVL.value() def getFault(self): '''getFault''' return not self.FAULT.value() def getOV_VDD(self): '''reports an overvoltage detection''' return self.OV_VDD.value()
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 write_frame(self): """ Send a DMX frame """ # DMX needs a 88us low to begin a frame, # 77uS us used because of time it takes to init pin dmx_uart = Pin(tx_pins[self.port], Pin.OUT_PP) dmx_uart.value(0) udelay(74) dmx_uart.value(1) # Now turn into a UART port and send DMX data dmx_uart = UART(self.port) dmx_uart.init(250000, bits=8, parity=None, stop=2) #send bytes dmx_uart.write(self.dmx_message) #Delete as its going to change anyway del (dmx_uart)
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)
class Switch(): def __init__(self, pin, debouncePeriod): self.pin = Pin(pin, Pin.IN, Pin.PULL_UP) self.db = debouncePeriod def getValue(self): return (self.pin.value()) def wait_pin_change(self): # wait for pin to change value # it needs to be stable for a continuous 50ms cur_value = self.pin.value() active = 0 while active < self.db: if self.pin.value() != cur_value: active += 1 else: active = 0 pyb.delay(1)
class Mode: def __init__(self): self.ultrasonic_sensor = ADC(Pin("X4")) self.hall_sensor = Pin("X6", Pin.IN) self.pot = ADC(Pin("X8")) self.ring = WS2812(spi_bus=2, led_count=15) self.red = Colour(1, 0, 0) self.green = Colour(0.4, 1, 0) self.purple = Colour(0.4, 0, 1) self.off = Colour(0, 0, 0) self.magnet_detected = self.green self.ultrasound_detected = self.purple self.colour = self.red self.HISTORY_DEPTH = 15 self.history = [0 for i in range(self.HISTORY_DEPTH) ] #stores the last few values recorded self.i = 0 def loop(self): self.i += 1 #increase the pointer by one self.i = self.i % self.HISTORY_DEPTH #ensure that the pointer loops back to 0 when it reaches the end of the list if self.ultrasonic_sensor.read( ) > 2800: #2700 is the threshold voltage, we found the value generally only exceeds 2600 if the ultrasonic sensor is nearby self.history[ self. i] = 1 #adds a 1 / True value to the history as the sensor has detected ultrasound else: self.history[ self. i] = 0 #adds a 0 / False value as the sensor hasn't detected ultrasound #calculates the number of times the ultrasound has been triggered within the alloted time self.total = 0 for x in self.history: self.total += x #if it's greater than one assume that an ultrasound has been detected #however the brightness of the LEDs can reflect the certainty (the more time's it has been triggered within the time, the more certain we are) if self.total > 0: self.colour = self.ultrasound_detected self.colour.brightness = self.total / self.HISTORY_DEPTH * 125 #the certainty is reflected in the brightness of the LEDs #checks to see if the hall sensor value elif not self.hall_sensor.value(): self.colour = self.magnet_detected self.colour.brightness = 100 else: self.colour = self.off self.data = [(self.colour.R, self.colour.G, self.colour.B) for i in range(15)] self.ring.show(self.data) def __repr__(self): return 'task_two'
class Button: def __init__(self, power_supply_pin, control_pin): self.pin = control_pin self.power_supply_pin = power_supply_pin self.operation = Pin(control_pin, Pin.IN, Pin.PULL_UP) self.power = Pin(power_supply_pin, Pin.OUT_PP) self.power.high() def value(self): return self.operation.value()
class Motor: def __init__(self, pinA, pinB): self._a = Pin(pinA, Pin.OUT_PP) #todo: check motor driver pins for internal pull resistors. or use pyboard pin pulling and open drain? self._b = Pin(pinB, Pin.OUT_PP) self.stop() # defaults to connect both terminals to GND, but can override to VCC def stop(self, val = False): self._a.value(val) self._b.value(val) def drive(self, direction): if direction > 0: self._a.high() self._b.low() elif direction == 0: self.stop() elif direction < 0: self._a.low() self._b.high()
class TouchSensor: def __init__(self, pin: Pin): self._pin = Pin(pin, mode=Pin.IN) def read(self): return self._pin.value() def pressed(self): return self.read() == 0 def released(self): return self.read() == 1
class rs485_tmcl_interface(uart_tmcl_interface): def __init__(self, port=4, data_rate=115200, host_id=2, module_id=1, debug=False): super().__init__(port, data_rate, host_id, module_id, debug) self.__dir = Pin(Pin.cpu.B1, Pin.OUT_PP) def _send(self, hostID, moduleID, data): buf = self.__dir.value() self.__dir.high() super()._send(hostID, moduleID, data) self.__dir.value(buf) def _recv(self, hostID, moduleID): buf = self.__dir.value() self.__dir.low() read = super()._recv(hostID, moduleID) self.__dir.value(buf) return read @staticmethod def available_ports(): return set([4])
class GroveBuzzer(object): def __init__(self, pin): self.buzz = Pin(pin,Pin.OUT) def value(self): return self.buzz.value() def toggle(self): self.buzz.value(not self.buzz.value()) def on(self): self.buzz.value(True) def off(self): self.buzz.value(False)
class GroveRelay(object): def __init__(self, pin): self.relay = Pin(pin,Pin.OUT) def value(self): return self.relay.value() def toggle(self): self.relay.value(not self.relay.value()) def on(self): self.relay.value(True) def off(self): self.relay.value(False)
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
class RC: start = width = last_width = 0 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) def callback(self, timer): if self.pin.value(): self.start = self.channel.capture() else: self.width = self.channel.capture() - self.start & 0x0fffffff def get_width(self): w = self.width self.last_width = w if w > 950 and w < 1950 else self.last_width return self.last_width def __del__(self): self.timer.deinit()
class SR04Distance(object): """ """ maxinches = 20 #maximum range of SR04. 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 __del__( self ) : self._micros.deinit() @property def counter( self ) : return self._micros.counter() @counter.setter def counter( self, value ) : self._micros.counter(value) @property def centimeters( self ) : start = 0 end = 0 self.counter = 0 #Send 10us pulse. self._tpin.high() udelay(10) self._tpin.low() while not self._epin.value(): start = self.counter j = 0 # Wait 'till the pulse is gone. while self._epin.value() and j < 1000: j += 1 end = self.counter # Calc the duration of the recieved pulse, divide the result by # 2 (round-trip) and divide it by 29 (the speed of sound is # 340 m/s and that is 29 us/cm). return (end - start) / 58 @property def inches( self ) : return self.centimeters * 0.3937
class Robot: 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() def Lights(self, status): if status == 1: self.HL.high() self.TL.pulse_width_percent(self.low_light) else: self.HL.low() self.TL.pulse_width_percent(0) def Brakes(self, status): if status == 1: self.TL.pulse_width_percent(100) elif status == 0: if self.HL.value() == 0: self.TL.pulse_width_percent(0) else: self.TL.pulse_width_percent(self.low_light) def Blink(self, side): if side == -1: self.RH.low() if self.LH.value() == 0: self.LH.high() else: self.LH.low() if side == 1: self.LH.low() if self.RH.value() == 0: self.RH.high() else: self.RH.low() if side == 2: if self.RH.value() == 0: self.RH.high() self.LH.high() else: self.RH.low() self.LH.low() if side == 0: self.RH.low() self.LH.low() def MotorStatus(self, left, right): if left == 1: self.LH_STBY.high() elif left != 1: self.LH_STBY.low() if right == 1: self.RH_STBY.high() elif right != 1: self.RH_STBY.low() def DoStep(self, dir_L, dir_R): if self.step_L == 0: self.LH_AIN1.high() self.LH_AIN2.low() self.LH_PWMA.pulse_width_percent(self.power_L) self.LH_PWMB.pulse_width_percent(0) elif self.step_L == 1: self.LH_AIN1.high() self.LH_AIN2.low() self.LH_PWMA.pulse_width_percent(self.power_L) self.LH_BIN1.high() self.LH_BIN2.low() self.LH_PWMB.pulse_width_percent(self.power_L) elif self.step_L == 2: self.LH_PWMA.pulse_width_percent(0) self.LH_BIN1.high() self.LH_BIN2.low() self.LH_PWMB.pulse_width_percent(self.power_L) elif self.step_L == 3: self.LH_AIN1.low() self.LH_AIN2.high() self.LH_PWMA.pulse_width_percent(self.power_L) self.LH_BIN1.high() self.LH_BIN2.low() self.LH_PWMB.pulse_width_percent(self.power_L) elif self.step_L == 4: self.LH_AIN1.low() self.LH_AIN2.high() self.LH_PWMA.pulse_width_percent(self.power_L) self.LH_PWMB.pulse_width_percent(0) elif self.step_L == 5: self.LH_AIN1.low() self.LH_AIN2.high() self.LH_PWMA.pulse_width_percent(self.power_L) self.LH_BIN1.low() self.LH_BIN2.high() self.LH_PWMB.pulse_width_percent(self.power_L) elif self.step_L == 6: self.LH_PWMA.pulse_width_percent(0) self.LH_BIN1.low() self.LH_BIN2.high() self.LH_PWMB.pulse_width_percent(self.power_L) elif self.step_L == 7: self.LH_AIN1.high() self.LH_AIN2.low() self.LH_PWMA.pulse_width_percent(self.power_L) self.LH_BIN1.low() self.LH_BIN2.high() self.LH_PWMB.pulse_width_percent(self.power_L) self.step_L += dir_L if self.step_L < 0: self.step_L = self.n_steps + dir_L if self.step_L >= self.n_steps: self.step_L = -1 + dir_L if self.step_R == 0: self.RH_AIN1.high() self.RH_AIN2.low() self.RH_PWMA.pulse_width_percent(self.power_R) self.RH_PWMB.pulse_width_percent(0) elif self.step_R == 1: self.RH_AIN1.high() self.RH_AIN2.low() self.RH_PWMA.pulse_width_percent(self.power_R) self.RH_BIN1.high() self.RH_BIN2.low() self.RH_PWMB.pulse_width_percent(self.power_R) elif self.step_R == 2: self.RH_PWMA.pulse_width_percent(0) self.RH_BIN1.high() self.RH_BIN2.low() self.RH_PWMB.pulse_width_percent(self.power_R) elif self.step_R == 3: self.RH_AIN1.low() self.RH_AIN2.high() self.RH_PWMA.pulse_width_percent(self.power_R) self.RH_BIN1.high() self.RH_BIN2.low() self.RH_PWMB.pulse_width_percent(self.power_R) elif self.step_R == 4: self.RH_AIN1.low() self.RH_AIN2.high() self.RH_PWMA.pulse_width_percent(self.power_R) self.RH_PWMB.pulse_width_percent(0) elif self.step_R == 5: self.RH_AIN1.low() self.RH_AIN2.high() self.RH_PWMA.pulse_width_percent(self.power_R) self.RH_BIN1.low() self.RH_BIN2.high() self.RH_PWMB.pulse_width_percent(self.power_R) elif self.step_R == 6: self.RH_PWMA.pulse_width_percent(0) self.RH_BIN1.low() self.RH_BIN2.high() self.RH_PWMB.pulse_width_percent(self.power_R) elif self.step_R == 7: self.RH_AIN1.high() self.RH_AIN2.low() self.RH_PWMA.pulse_width_percent(self.power_R) self.RH_BIN1.low() self.RH_BIN2.high() self.RH_PWMB.pulse_width_percent(self.power_R) self.step_R += dir_R if self.step_R < 0: self.step_R = self.n_steps + dir_R if self.step_R >= self.n_steps: self.step_R = -1 + dir_R def MoveStep(self, n): if self.sspeed_L < 0: ldir = -n else: ldir = n self.speed_L += (self.sspeed_L * ldir) if self.speed_L > 255: self.dir_L = ldir self.dist_L += ldir self.speed_L -= 256 * n else: self.dir_L = 0 if self.sspeed_R < 0: rdir = -n else: rdir = n self.speed_R += (self.sspeed_R * rdir) if self.speed_R > 255: self.dir_R = rdir self.dist_R += rdir self.speed_R -= 256 * n else: self.dir_R = 0 self.DoStep(self.dir_L, self.dir_R) def SetPower(self, left, right): self.power_R = right self.power_L = left self.DoStep(0,0) def GetDist(self): return (self.dist_L, self.dist_R) def SetDist(self, dl, dr): self.dist_L = dl self.dist_R = dr def SetTarget(self, t_L, t_R): self.target_L = t_L self.target_R = t_R def GetTarget(self): return(self.target_L, self.target_R) def SetMaxSpeed(self, s_L, s_R): self.max_speed_L = s_L self.max_speed_R = s_R def Stop(self): self.dts_L = (self.acc * (self.sspeed_L // self.acc) ** 2) // 512 self.dts_R = (self.acc * (self.sspeed_R // self.acc) ** 2) // 512 if self.sspeed_L < 0: self.dts_L *= -1 if self.sspeed_R < 0: self.dts_R *= -1 self.target_L = self.dist_L + self.dts_L self.target_R = self.dist_R + self.dts_R def Motion(self, n): self.dts_L = (self.acc * (self.sspeed_L // self.acc) ** 2) // 512 self.dts_R = (self.acc * (self.sspeed_R // self.acc) ** 2) // 512 if self.sspeed_L < 0: self.dts_L *= -1 if self.sspeed_R < 0: self.dts_R *= -1 if self.target_L > (self.dist_L + self.dts_L) and self.sspeed_L < self.max_speed_L: self.sspeed_L += self.acc elif self.target_L < (self.dist_L + self.dts_L) and self.sspeed_L > -self.max_speed_L: self.sspeed_L -= self.acc elif self.target_L == self.dist_L and abs(self.sspeed_L) < 50: self.sspeed_L = 0 if self.target_R > (self.dist_R + self.dts_R) and self.sspeed_R < self.max_speed_R: self.sspeed_R += self.acc elif self.target_R < (self.dist_R + self.dts_R) and self.sspeed_R > -self.max_speed_R: self.sspeed_R -= self.acc elif self.target_R == self.dist_R and abs(self.sspeed_R) < 50: self.sspeed_R = 0 self.MoveStep(n)
class RS485(object): 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 check_lan(self): res = [] uart = self.uart try: buf = uart.readall() if buf: buf = buf.decode("utf-8") LED(2).toggle() for pack in buf.split(chr(0x0)): if pack: try: data = False data = loads(pack) if len(data) > 0 and data[0] == self.dev_id: if data[2][0] == "SET_CONFIG_FILE": res = [data] if data[2][2] == False: self.file_parts = data[2][1] self.file_parts_i = 1 self._write_config(True, '') self.file_is_open = True else: if self.file_is_open: if self.file_parts_i == data[2][1]: self._write_config(False, data[2][2]) if self.file_parts_i == self.file_parts: self.file_is_open = False self.file_parts_i += 1 else: res = [[self.dev_id, 3]] self.error += ["Error 3 %s" % (data)] self.file_is_open = False break else: res = [[self.dev_id, 3]] self.error += ["Error 4 DATA: %s" % (data)] break else: self.file_is_open = False res = [data] except Exception as e: res = [[self.dev_id, 3]] if data: self.error += ["Error 1 {}".format(e.args) + " DATA: %s" % (data)] else: self.error += ["Error 1 {}".format(e.args) + " PACK: %s" % (pack)] LED(4).on() except Exception as e: res = [[self.dev_id, 3]] self.error += ["Error 2 {}".format(e.args)] LED(4).on() return res def send_pack(self, pack_type, pack_data): pin_rw = self.pin_rw.value uart = self.uart pin_rw(1) try: buf = [self.dev_id, pack_type, pack_data] data = dumps(buf).encode("utf-8") data += bytearray([0x0]) uart.write(data) except: #print("Возникла ошибка при отправке пакета") #print(data) LED(3).on() pin_rw(0) def _write_config(self, is_start, data): if is_start: f = open("config.py", "w") else: f = open("config.py", "a") try: f.write(data) except: pass f.close()
from pyb import Pin, Timer 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 # timestamp at rising edge of echo end = 0 # timestamp at falling edge of echo while True: # Send a 20usec pulse every 10ms Trigger.high() pyb.udelay(20) #udelay uses argument in microseconds Trigger.low() # Wait until echo pulse goes from low to high while Echo.value() == 0: start = micros.counter() # record start time of pulse # Wait until echo pulse goes from high to low while Echo.value() == 1: # do nothing end = micros.counter() # record end time of pulse # Calculate distance from delay duration distance = int(((end - start) / 2) / 29) print('Distance: ', distance, ' cm') pyb.delay(500)
############### BASIC LED on off ############# r.on() r.off() g.on() g.off() b.on() b.off() ##################### read out button states ################ btn1.value() btn2.value() ##################### define callbacks for buttons ################ def callback1(line): print("Callback 1: turn green led ON") g.on() def callback2(line): print("Callback 1: turn green led OFF") g.off() extint1 = pyb.ExtInt(btn1, pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_DOWN, callback1) extint2 = pyb.ExtInt(btn2, pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_DOWN, callback2)
class SC1602: sc1602pin_default = { 'RS': Pin.board.PE4, 'E': Pin.board.PE5, 'DB0': Pin.board.PE7, 'DB1': Pin.board.PE8, 'DB2': Pin.board.PE9, 'DB3': Pin.board.PE10, 'DB4': Pin.board.PE11, 'DB5': Pin.board.PE12, 'DB6': Pin.board.PE13, 'DB7': Pin.board.PE14, } def __init__(self, pin=None): Pin.dict(pin or self.sc1602pin_default) self.rs = Pin("RS", Pin.OUT_PP) self.e = Pin("E", Pin.OUT_PP) self.db0 = Pin("DB0", Pin.OUT_PP) self.db1 = Pin("DB1", Pin.OUT_PP) self.db2 = Pin("DB2", Pin.OUT_PP) self.db3 = Pin("DB3", Pin.OUT_PP) self.db4 = Pin("DB4", Pin.OUT_PP) self.db5 = Pin("DB5", Pin.OUT_PP) self.db6 = Pin("DB6", Pin.OUT_PP) self.db7 = Pin("DB7", Pin.OUT_PP) self.e.low() def initialize(self): for _ in range(3): self.rs.low() self.__set_databus(0x30) self.__enable() pyb.delay(5) # function set self.rs.low() self.__set_databus(0x38) self.__enable() self.display_on_off(False) self.clear() self.display_on_off(True) # entry mode set self.rs.low() self.__set_databus(0x06) self.__enable() def __set_databus(self, data): self.db0.value(data & 1) self.db1.value((data >> 1) & 1) self.db2.value((data >> 2) & 1) self.db3.value((data >> 3) & 1) self.db4.value((data >> 4) & 1) self.db5.value((data >> 5) & 1) self.db6.value((data >> 6) & 1) self.db7.value((data >> 7) & 1) def __enable(self): self.e.high() pyb.udelay(1) self.e.low() pyb.udelay(40) def clear(self): self.rs.low() self.__set_databus(1) self.__enable() pyb.udelay(1600) def cursor_at_home(self): self.rs.low() self.__set_databus(2) self.__enable() pyb.udelay(1600) def display_on_off(self, display, cursor=False, blink=False): self.rs.low() self.__set_databus(8) if display: self.db2.high() if cursor: self.db1.high() if blink: self.db0.high() self.__enable() def set_cursor(self, y, x=0): self.rs.low() self.__set_databus((y * 0x40 + x) | 0x80) self.__enable() def putc(self, c): self.rs.high() self.__set_databus(ord(c)) self.__enable() def write(self, string): for c in string: self.putc(c)
def beep(beeper): if sensor == 0: #create a buffer containing a sine-wave buf = bytearray(100) for i in range(len(buf)): buf[i] = 128 + int(127 * math.sin(2 * math.pi * i / len(buf))) #output the sine-wave at 400hz beeper.write_timed(buf, 400 * len(buf), mode = DAC.NORMAL) #Loop starts while True: #Read motionsensor value sensor = (motionsensor.value()) * 10 #Read temperature value temp = tempsensor.read() #Reaad light level value lightLevel = lightvalue(i2c) / 10 #Define doortrigger value trigger1 = doortrigger.value() trigger2 = doortrigger2.value() doortriggervalue = 10 * (trigger1 + trigger2) keypad() changetemp(temp) beep(beeper)
test_pin_af() # try the entire af range on all pins # test pin init and printing pin = Pin(pin_map[0]) pin.init(mode=Pin.IN) print(pin) pin.init(Pin.IN, Pin.PULL_DOWN) print(pin) pin.init(mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.LOW_POWER) print(pin) pin.init(mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.HIGH_POWER) print(pin) # test value in OUT mode pin = Pin(pin_map[0], mode=Pin.OUT) pin.value(0) pin.toggle() # test toggle print(pin()) pin.toggle() # test toggle again print(pin()) # test different value settings pin(1) print(pin.value()) pin(0) print(pin.value()) pin.value(1) print(pin()) pin.value(0) print(pin()) # test all getters and setters
uart.init(9600, bits=7, parity=1, stop=1) start_pressed = 0 # stop_pressed = 0 t1_set = 200 t1_last = 30 t2_set = 600 t1_t2_step = 1 t1_t2_last = 480 t2_last = 120 off_last = 390 cmd_prefix = '*P012' # Write to RAM of point 1 with positive sign and decimal point 2 cmd_standby = '*D03' # Standby mode with output off cmd_dis_standby = '*E03'# Disable standby start_value = 0 stop_value = 0 print("stop_pin.value="+str(stop_pin.value())) print("start_pin.value="+str(start_pin.value())) def start_callback(line): global start_pressed, start_int, pyb, start_pin, stop_pin #print("%d"%start_pin.value()) if ((start_pin.value() == 0) and (stop_pin.value() == 1)): # 1 = not pressed start_int.disable() start_pressed = 1 print("start_pressed=========") #pyb.hard_reset() else: #start_pressed = 0
from pyb import Pin p = Pin('X1') print(p) print(p.name()) print(p.pin()) print(p.port()) p = Pin('X1', Pin.IN, Pin.PULL_UP) #p = Pin('X1', Pin.IN, pull=Pin.PULL_UP) print(p.value()) p.init(p.IN, p.PULL_DOWN) #p.init(p.IN, pull=p.PULL_DOWN) print(p.value()) p.init(p.OUT_PP) p.low() print(p.value()) p.high() print(p.value()) p.value(0) print(p.value()) p.value(1) print(p.value()) p.value(False) print(p.value()) p.value(True) print(p.value())
class Mpl115A2(object): """ Reads temperature and pressure from a Freescale MPL115A2 sensor over I2C. See the module docstring for usage information. """ def __init__( self, bus, shutdown_pin=None, reset_pin=None, temperature_convertor=None, pressure_convertor=None, **kwargs ): """ Create the device on the specified bus. The bus must be a pyb.I2C object in master mode, or an object implementing the same interface. pyb.Pin objects can be provided for controlling the shutdown and reset pins of the sensor. They must be in output mode. The pins can also be specified as strings (e.g. 'X9'), for which Pin objects will be created and configured. Temperature and pressure convertor objects can be passed which will convert from celsius and kilopascals as necessary if you want to work in a different scale. """ # There doesn't seem to be a way to check this at present. The first # send or recv should throw an error instead if the mode is incorrect. #if not bus.in_master_mode(): # raise ValueError('bus must be in master mode') self.bus = bus self.address = 0x60 self.shutdown_pin = shutdown_pin if self.shutdown_pin is not None: if isinstance(self.shutdown_pin, str): from pyb import Pin # Not sure what are the appropriate settings here... self.shutdown_pin = Pin( self.shutdown_pin, Pin.OUT_PP, Pin.PULL_UP ) if 'shutdown' in kwargs: self.shutdown_pin.value(not kwargs['shutdown']) else: self.shutdown_pin.high() self.reset_pin = reset_pin if self.reset_pin is not None: if isinstance(self.reset_pin, str): from pyb import Pin # Not sure what are the appropriate settings here... self.reset_pin = Pin( self.reset_pin, Pin.OUT_PP, Pin.PULL_UP ) if 'reset' in kwargs: self.reset_pin.value(not kwargs['reset']) else: self.reset_pin.high() self.temperature_convertor = temperature_convertor self.pressure_convertor = pressure_convertor # Coefficients for compensation calculations - will be set on first # attempt to read pressure or temperature self._a0 = None self._b1 = None self._b2 = None self._c12 = None def _send_command(self, command, value=None): bvals = bytearray() bvals.append(command) if value is not None: for val in value: bvals.append(val) self.bus.send(bvals, addr=self.address) self._last_command = command def _read_coefficients(self): self._send_command(0x04) coefficients = self.bus.recv(8, addr=self.address) self._a0 = float(_parse_signed(coefficients[0], coefficients[1])) / 8.0 self._b1 = float(_parse_signed(coefficients[2], coefficients[3])) / 8192.0 self._b2 = float(_parse_signed(coefficients[4], coefficients[5])) / 16384.0 self._c12 = float(_parse_signed(coefficients[6], coefficients[7]) >> 2) / 4194304.0 def _read_raw_pressure(self): self._send_command(0x00) rp = self.bus.recv(2, addr=self.address) return int((rp[0] << 8 | rp[1]) >> 6) def _read_raw_temperature(self): self._send_command(0x02) rt = self.bus.recv(2, addr=self.address) return int((rt[0] << 8 | rt[1]) >> 6) def initiate_conversion(self): self._send_command(0x12, (0x00,)) @property def pressure(self): if self._a0 is None: self._read_coefficients() raw_pressure = self._read_raw_pressure() raw_temp = self._read_raw_temperature() compensated = (((self._b1 + (self._c12 * raw_temp)) * raw_pressure) + self._a0) + (self._b2 * raw_temp) kpa = (compensated * (65.0 / 1023.0)) + 50.0 if self.pressure_convertor is None: return kpa return self.pressure_convertor.convert_to(kpa) @property def temperature(self): if self._a0 is None: self._read_coefficients() raw_temp = self._read_raw_temperature() celsius = ((float(raw_temp) - 498.0) / -5.35) + 25.0 if self.temperature_convertor is None: return celsius return self.temperature_convertor.convert_to(celsius) def _set_shutdown(self, value): if self.shutdown_pin is None: raise Exception("No shutdown pin has been set") if not value: self._last_wake_millis = pyb.millis() self.shutdown_pin.value(not value) def _get_shutdown(self): if self.shutdown_pin is None: raise Exception("No shutdown pin has been set") return not self.shutdown_pin.value() shutdown = property(_get_shutdown, _set_shutdown) def _set_reset(self, value): if self.reset_pin is None: raise Exception("No reset pin has been set") if not value: self._last_wake_millis = pyb.millis() self.reset_pin.value(not value) def _get_reset(self): if self.reset_pin is None: raise Exception("No reset pin has been set") return not self.reset_pin.value() reset = property(_get_reset, _set_reset)
print("Press ENTER to start!\n") char.char_in("WELCOME TO PYGAME!", 1) char.char_in("PRESS UP TO MAKE A", 2) char.char_in("SMALL JUMP.", 3) char.char_in("PRESS ENTER TO MAKE A", 4) char.char_in("BIG JUMP.", 5) char.char_in("IF YOU FALL OR HIT A WALL,", 6) char.char_in("YOU WILL DIE!", 7) char.char_in("IF YOU WALK ON A YELLOW", 8) char.char_in("THING, YOU WILL MAKE A", 9) char.char_in("BIG JUMP.", 10) char.char_in("PRESS MENU TO GO TO THE", 11) char.char_in("GAME MENU.", 12) char.char_in("PRESS ENTER TO START!", 14) while True: if enter.value() is 0: udelay(1000000) break game = Game() ram = game.ram game.background() print("\nLevel", game.level) char.char_in("LEVEL 1", xx=104, yy=30) game.player(a=10, b=0) while True: game.game_menu() if enter.value() is 0: udelay(1000000) game.background() game.move() break
try: from pyb import DAC from pyb import LED from pyb import Pin from pyb import USB_VCP sensitivity, maxn, minn = .5, 255, 0 com = USB_VCP() light = DAC(2) y1, y2, y3 = Pin('Y1', Pin.IN), Pin('Y2', Pin.IN), Pin('Y3', Pin.IN) intensity, oldStr = maxn, str(y1.value()) + str(y2.value()) directTab = { '1000' : 1, '0001' : 1, '0111' : 1, '1110' : 1, '1011' : -1, '1101' : -1, '0100' : -1, '0010' : -1 } def setByte(i): return i.to_bytes(1) def limitNums(num, maxn, minn): return max(minn, min(maxn, num))
class Robot: def __init__(self): # Timer for motor PWM self.tim2 = Timer(2, freq=10000) # Timer to dim lights self.tim4 = Timer(4, freq=1000) # Timer for motion self.tim7 = Timer(7, freq=800) # Variables self.step_R = 0 #counter for (micro) step self.step_L = 0 #counter for (micro) step self.step = 0 #counter for motion interrupt self.n_steps = 64 #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 = 1 #motion control acceleration self.dts_R = 0 #motion distance to stop self.dts_L = 0 #motion distance to stop self.move = 0 #move motors or not # 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() def Lights(self, status): if status == 1: self.HL.high() self.TL.pulse_width_percent(self.low_light) else: self.HL.low() self.TL.pulse_width_percent(0) def Brakes(self, status): if status == 1: self.TL.pulse_width_percent(100) elif status == 0: if self.HL.value() == 0: self.TL.pulse_width_percent(0) else: self.TL.pulse_width_percent(self.low_light) def Blink(self, side): if side == -1: self.RH.low() if self.LH.value() == 0: self.LH.high() else: self.LH.low() if side == 1: self.LH.low() if self.RH.value() == 0: self.RH.high() else: self.RH.low() if side == 2: if self.RH.value() == 0: self.RH.high() self.LH.high() else: self.RH.low() self.LH.low() if side == 0: self.RH.low() self.LH.low() def mcallback(self, t): self.step += 1 def MotorStatus(self, status): if status == 1: self.LH_STBY.high() self.RH_STBY.high() self.tim7.callback(self.mcallback) elif status != 1: self.LH_STBY.low() self.RH_STBY.low() self.tim7.callback(None) def DoStep(self, dir_L, dir_R): percent_A = self.power_L * math.sin(self.step_L * 2 * math.pi / self.n_steps) percent_B = self.power_L * math.cos(self.step_L * 2 * math.pi / self.n_steps) if percent_A > 0: self.LH_AIN1.high() self.LH_AIN2.low() else: self.LH_AIN1.low() self.LH_AIN2.high() percent_A *= -1 if percent_B > 0: self.LH_BIN1.high() self.LH_BIN2.low() else: self.LH_BIN1.low() self.LH_BIN2.high() percent_B *= -1 self.LH_PWMA.pulse_width_percent(percent_A) self.LH_PWMB.pulse_width_percent(percent_B) self.step_L += dir_L if self.step_L < 0: self.step_L = self.n_steps + dir_L if self.step_L >= self.n_steps: self.step_L = -1 + dir_L percent_A = self.power_R * math.sin(self.step_R * 2 * math.pi / self.n_steps) percent_B = self.power_R * math.cos(self.step_R * 2 * math.pi / self.n_steps) if percent_A > 0: self.RH_AIN1.high() self.RH_AIN2.low() else: self.RH_AIN1.low() self.RH_AIN2.high() percent_A *= -1 if percent_B > 0: self.RH_BIN1.high() self.RH_BIN2.low() else: self.RH_BIN1.low() self.RH_BIN2.high() percent_B *= -1 self.RH_PWMA.pulse_width_percent(percent_A) self.RH_PWMB.pulse_width_percent(percent_B) self.step_R += dir_R if self.step_R < 0: self.step_R = self.n_steps + dir_R if self.step_R >= self.n_steps: self.step_R = -1 + dir_R def MoveStep(self, n): if self.sspeed_L < 0: ldir = -n else: ldir = n self.speed_L += (self.sspeed_L * ldir) if self.speed_L > 255: self.dir_L = ldir self.dist_L += ldir self.speed_L -= 256 * n else: self.dir_L = 0 if self.sspeed_R < 0: rdir = -n else: rdir = n self.speed_R += (self.sspeed_R * rdir) if self.speed_R > 255: self.dir_R = rdir self.dist_R += rdir self.speed_R -= 256 * n else: self.dir_R = 0 self.DoStep(self.dir_L, self.dir_R) def SetPower(self, left, right): self.power_R = right self.power_L = left self.DoStep(0,0) def GetDist(self): return (self.dist_L, self.dist_R) def SetDist(self, dl, dr): self.dist_L = dl self.dist_R = dr def SetTarget(self, t_L, t_R): self.target_L = t_L self.target_R = t_R def GetTarget(self): return(self.target_L, self.target_R) def SetMaxSpeed(self, s_L, s_R): self.max_speed_L = s_L self.max_speed_R = s_R def Stop(self): self.dts_L = (self.acc * (self.sspeed_L // self.acc) ** 2) // 512 self.dts_R = (self.acc * (self.sspeed_R // self.acc) ** 2) // 512 if self.sspeed_L < 0: self.dts_L *= -1 if self.sspeed_R < 0: self.dts_R *= -1 self.target_L = self.dist_L + self.dts_L self.target_R = self.dist_R + self.dts_R def Motion(self, n): self.dts_L = (self.acc * (self.sspeed_L // self.acc) ** 2) // 512 self.dts_R = (self.acc * (self.sspeed_R // self.acc) ** 2) // 512 if self.sspeed_L < 0: self.dts_L *= -1 if self.sspeed_R < 0: self.dts_R *= -1 if self.target_L > (self.dist_L + self.dts_L) and self.sspeed_L < self.max_speed_L: self.sspeed_L += self.acc elif self.target_L < (self.dist_L + self.dts_L) and self.sspeed_L > -self.max_speed_L: self.sspeed_L -= self.acc elif self.target_L == self.dist_L and abs(self.sspeed_L) < 50: self.sspeed_L = 0 if self.target_R > (self.dist_R + self.dts_R) and self.sspeed_R < self.max_speed_R: self.sspeed_R += self.acc elif self.target_R < (self.dist_R + self.dts_R) and self.sspeed_R > -self.max_speed_R: self.sspeed_R -= self.acc elif self.target_R == self.dist_R and abs(self.sspeed_R) < 50: self.sspeed_R = 0 self.MoveStep(n) def FWD(self, dist): dl = int(self.dist_L + dist * 3.5866) dr = int(self.dist_R + dist * 3.5866) self.SetTarget(dl, dr) self.move = 1 self.step = 0 while (self.move == 1): if self.step > 0: self.Motion(self.step) self.step = 0 if self.dist_L == dl and self.dist_R == dr: self.move = 0 def TRN(self, r, alpha): dl = self.dist_L + int((r + 40.75) * 2 * math.pi * alpha / 360 * 3.5866) dr = self.dist_R + int((r - 40.75) * 2 * math.pi * alpha / 360 * 3.5866) self.SetTarget(dl, dr) self.move = 1 self.step = 0 while (self.move == 1): if self.step > 0: self.Motion(self.step) self.step = 0 if self.dist_L == dl and self.dist_R == dr: self.move = 0
s3.angle(3*ax.x()) pyb.delay(500) l1.off() l2.off() l3.off() l4.off() # function definations ends # Define input pins with PULL UP mode Pinsw1 = Pin('Y6', Pin.IN,Pin.PULL_UP) Pinsw2 = Pin('Y7', Pin.IN,Pin.PULL_UP) Pinsw3 = Pin('Y8', Pin.IN,Pin.PULL_UP) #swArr = [Pinsw1.value(),Pinsw2.value(),Pinsw3.value()]; index = 0 while (index==0): swArr = [Pinsw1.value(),Pinsw2.value(),Pinsw3.value()]; if(swArr==[1,1,1]): straight() XControlAll() # Don't move #index=index+1 #pyb.delay(2000) endLight() elif(swArr==[0,0,1]): # Go to straight straight() halSquleft() halSquRight() endLight() #index=index+1 #pyb.delay(2000)
def test_noinit(): for p in pin_map: pin = Pin(p) pin.value()