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 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()
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())
class ScopePin: def __init__(self, pin_name): self.pin = Pin(pin_name, Pin.OUT_PP) self.pin.low() def pulse(self, n=1): for i in range(n): self.pin.high() self.pin.low()
def drive_motor(): A1 = Pin('Y9',Pin.OUT_PP) A2 = Pin('Y10',Pin.OUT_PP) A1.high() A2.low() motor = Pin('X1') tim = Timer(2, freq = 1000) ch = tim.channel(1, Timer.PWM, pin = motor) while True: ch.pulse_width_percent(50)
class vactrolControl: """simple class providing on/off functionality of a vactrol controlled by a pyboard bin. """ def __init__(self, vactrolPin): self.vactrol = Pin(vactrolPin, Pin.OUT_PP) self.vactrol.low() def on(self): self.vactrol.high() def off(self): self.vactrol.low()
def motor_control(): # define various I/O pins for ADC adc_1 = ADC(Pin('X19')) adc_2 = ADC(Pin('X20')) # set up motor with PWM and timer control A1 = Pin('Y9',Pin.OUT_PP) A2 = Pin('Y10',Pin.OUT_PP) pwm_out = Pin('X1') tim = Timer(2, freq = 1000) motor = tim.channel(1, Timer.PWM, pin = pwm_out) A1.high() # motor in brake position A2.high() # Calibrate the neutral position for joysticks MID = adc_1.read() # read the ADC 1 value now to calibrate DEADZONE = 10 # middle position when not moving # Use joystick to control forward/backward and speed while True: # loop forever until CTRL-C speed = int(100*(adc_1.read()-MID)/MID) if (speed >= DEADZONE): # forward A1.high() A2.low() motor.pulse_width_percent(speed) elif (speed <= -DEADZONE): A1.low() # backward A2.high() motor.pulse_width_percent(-speed) else: A1.low() # stop A2.low()
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 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): self.dbg = Pin("X9", Pin.OUT_PP) self.dbg.low() self.spi = SPI(2, SPI.MASTER, baudrate=5250000) ss = Pin(self.CS_TFT, Pin.OUT_PP) ss.low() self.dc = Pin(self.DC, Pin.OUT_PP) self.dc.low() self.DC_flag = False cs_sd = Pin(self.CS_SD, Pin.OUT_PP) cs_sd.high() self.lite = Pin(self.LITE, Pin.OUT_PP) self.lite.high() reset = Pin(self.RST, Pin.OUT_PP) reset.low() delay(2) reset.high() delay(200)
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 MotorDriver: def __init__(self, a, b, p, c, d, q, e): self._left = MotorPWM(a, b, p) self._right = MotorPWM(c, d, q) self._standby = Pin(e, Pin.OUT_PP) self._standby.high() # Automatically enables driver when setting speed def drive(self, left, right, enable = True): pass def driveL(self, speed, enable = True): pass def driveR(self, speed, enable = True): pass def stop(self): pass def stopL(self): pass def stopR(self): pass def freewheel(self): pass def freewheelL(self): pass def freewheelR(self): pass def enable(self): self._standby.low() def disable(self): self._standby.high()
class SpiMaster: 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 write_status(self, status): self.ss.low() self.spi.send(0x01) self.spi.send(status & 0xFF) self.spi.send((status >> 8) & 0xFF) self.spi.send((status >> 16) & 0xFF) self.spi.send((status >> 24) & 0xFF) self.ss.high() def read_status(self): self.ss.low() self.spi.send(0x04) self.spi.recv(self.status) self.ss.high() return ( self.status[0] | (self.status[1] << 8) | (self.status[2] << 16) | (self.status[3] << 24) ) def read_data(self): self.ss.low() self.spi.send(0x03) self.spi.send(0x00) self.spi.recv(self.msgbuf) self.ss.high() return self.msgbuf def read_msg(self, encoding='utf-8'): return bytes(self.read_data()).strip('\0').decode(encoding) def write_data(self, data): self.msgbuf[:] = data[:32] + b'\0' * (32 - len(data[:32])) self.ss.low() self.spi.send(0x02) self.spi.send(0x00) self.spi.send(self.msgbuf) self.ss.high()
def remote(): #initialise UART communication uart = UART(6) uart.init(9600, bits=8, parity = None, stop = 2) # define various I/O pins for ADC adc_1 = ADC(Pin('X19')) adc_2 = ADC(Pin('X20')) # set up motor with PWM and timer control A1 = Pin('Y9',Pin.OUT_PP) A2 = Pin('Y10',Pin.OUT_PP) pwm_out = Pin('X1') tim = Timer(2, freq = 1000) motor = tim.channel(1, Timer.PWM, pin = pwm_out) # Motor in idle state A1.high() A2.high() speed = 0 DEADZONE = 5 # Use keypad U and D keys to control speed while True: # loop forever until CTRL-C while (uart.any()!=10): #wait we get 10 chars n = uart.any() command = uart.read(10) if command[2]==ord('5'): if speed < 96: speed = speed + 5 print(speed) elif command[2]==ord('6'): if speed > - 96: speed = speed - 5 print(speed) if (speed >= DEADZONE): # forward A1.high() A2.low() motor.pulse_width_percent(speed) elif (speed <= -DEADZONE): A1.low() # backward A2.high() motor.pulse_width_percent(-speed) else: A1.low() # idle A2.low()
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.wr(LIS302DL_CTRL_REG1_ADDR, bytearray([LIS302DL_CONF])) def rd(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 self.cs_pin.high() return buf def wr(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.rd(LIS302DL_WHO_AM_I_ADDR, 1) def get_xyz(self): val = self.rd(LIS302DL_OUT_X, 5) x = signed8(val[0]) * 18.0 / 1000 y = signed8(val[2]) * 18.0 / 1000 z = signed8(val[4]) * 18.0 / 1000 return [x, y, z]
def start(self, speed, direction): """ method to start a motor Arguments: speed : speed of the motor 0-100 (as percentage of max) direction : CW or CCW, for clockwise or counterclockwise """ PWMpin = Pin(self.PWMpin) DIRpin = Pin(self.DIRpin, Pin.OUT_PP) # DIR1 and DIR2 have to be opposite to move, toggle to change direction if direction in ('cw','CW','clockwise'): DIRpin.high() elif direction in ('ccw','CCW','counterclockwise'): DIRpin.low() else: raise ValueError('Please enter CW or CCW for direction.') # Start the motor if 0 <= speed <= 100: # self.PWMpin = Pin('X4') tim = Timer(self.timer_id, freq=1000) ch = tim.channel(self.channel_id, Timer.PWM, pin=PWMpin) ch.pulse_width_percent(speed) # PWM.start(self.PWMpin, speed) else: raise ValueError("Please enter speed between 0 and 100") # set the status attributes self.isRunning = True self.currentDirection = direction self.currentSpeed = speed while self.isRunning: print("\nMotorA =", enc_timer.counter()) print("\nMotorB =", enc_timer_1.counter())
class Motor( ): """Control a motor connected to the L298N Dual motor controller.""" 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 @property def speed( self ) : return self._speed @speed.setter def speed( self, value ) : self._speed = value if (value == 0): self._forward.low() self._backward.low() elif (value < 0): self._forward.low() self._backward.high() else: self._forward.high() self._backward.low() self._speedControl.pulse_width_percent = min(100, abs(value)) def brake( self ) : """ Brake the motor by sending power both directions. """ self._forward.high() self._backward.high() self._speedControl.pulse_width_percent = 100 delay(1000) self.speed = 0
class IgnitionModule(object): ignited = False ign_point = 0 def __init__(self, pin="X5", ignition_length=500): self.pin = Pin(pin, Pin.OUT_PP) self.ignition_length = ignition_length self.pin.low() def ignite(self, ign_point=0): self.ignited = False self.ign_point = ign_point def update(self, round_start): if not self.ignited: while elapsed_micros(round_start) < self.ign_point: self.pin.low() self.pin.high() udelay(self.ignition_length) self.pin.low() self.ignited = True else: self.pin.low()
p_in_7 = Pin( 'P7', Pin.IN, Pin.PULL_UP) #设置p_in为输入引脚,并开启上拉电阻 Pin.PULL_DOWN 输入下拉电阻 根据抽签决定分球颜色 p_in_8 = Pin( 'P8', Pin.IN, Pin.PULL_DOWN) #设置p_in为输入引脚,并开启上拉电阻 Pin.PULL_DOWN 输入下拉电阻 判断是否开始分球 p_in_9 = Pin('P9', Pin.IN, Pin.PULL_DOWN ) #设置p_in为输入引脚,并开启上拉电阻 Pin.PULL_DOWN 输入下拉电阻 判断是否开始分球判断射球是否就绪执行分球 p_out_0.high() #设置p_out引脚为高 p_out_1.high() #设置p_out引脚为高 p_out_2.high() #设置p_out引脚为高 p_out_3.high() #设置p_out引脚为高 p_out_4.low() #设置p_out引脚为高 传给射球单元黑/白的信号 p_out_5.low() #设置p_out引脚为高 传给射球单元粉色的信号 color_value = 1 # 红队为白球 蓝队为黑球 Ready_value = 1 judge_value = 1 ball_flag = 0 #0为无球 1为有球 possible_color = 0 no_ball = 0 w = 0 p = 0 t = 0 b = 0 def find_initpoint():
else: # host invia dati a pyBoard - host send deta to pyBoard. uart.write('Invio dato a pyBoard :'+'\n') uart.write(inBuffer_rx+'\n') bkram[0] = len(inBuffer_rx) ba[4: 4+len(inBuffer_rx)] = inBuffer_rx restore_data() uart.write('Settaggio RTC'+'\n') set_rtc() # sincronizzo RTC con orario host -sync MCU RTC with host time. set_allarms() # imposto allarmi secondo dati ricevuti da host -set alarms based on host input. reason='' upower.wkup.enable() pin_FF_reset.low() pyb.standby() if reason=='ALARM_A': uart.write('Evento Alarm A'+'\n') verde.on() pyb.delay(30) verde.off() print('Gestione Alarm A') restore_data() uart.write('Relay A :'+pkl['relay_a']+ '\n') if enable_sonda_a==True: uart.write('Soglia Lettura A :'+ '\n') lettura_sonda_a=leggi_sonda_a() uart.write('Lettura Sonda A :'+str(lettura_sonda_a)+ '\n')
class BLE: BLE_NONE=0 BLE_SHIELD=1 def command(self, cmd): if self.type==self.BLE_SHIELD: self.uart.write(cmd) self.uart.write("\r\n") r=self.uart.read(9) if r[0]!=82: raise OSError("Response corrupted!") if r[1]==49: raise OSError("Command failed!") if r[1]==50: raise OSError("Parse error!") if r[1]==51: raise OSError("Unknown command!") if r[1]==52: raise OSError("Too few args!") if r[1]==53: raise OSError("Too many args!") if r[1]==54: raise OSError("Unknown variable or option!") if r[1]==55: raise OSError("Invalid argument!") if r[1]==56: raise OSError("Timeout!") if r[1]==57: raise OSError("Security mismatch!") if r[1]!=48: raise OSError("Response corrupted!") for i in range(2,6): if r[i]<48 or 57<r[i]: raise OSError("Response corrupted!") if r[7]!=13 or r[8]!=10: raise OSError("Response corrupted!") l=((r[2]-48)*10000)+\ ((r[3]-48)*1000)+\ ((r[4]-48)*100)+\ ((r[5]-48)*10)+\ ((r[6]-48)*1) if not l: return None if l==1 or l==2: raise OSError("Response corrupted!") response=self.uart.read(l-2) if self.uart.readchar()!=13: raise OSError("Response corrupted!") if self.uart.readchar()!=10: raise OSError("Response corrupted!") return response def deinit(self): if self.type==self.BLE_SHIELD: self.uart.deinit() self.rst=None self.uart=None self.type=self.BLE_NONE 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 def uart(self): if self.type==self.BLE_SHIELD: return self.uart def type(self): if self.type==self.BLE_SHIELD: return self.BLE_SHIELD def __init__(self): self.rst=None self.uart=None self.type=self.BLE_NONE
from pyb import Pin from utime import sleep_ms p_out = Pin('X1', Pin.OUT_PP) p_out.high() sleep_ms(500) p_out.low() sleep_ms(500)
# main.py -- put your code here! from pyb import udelay, Pin pin = Pin('X1', pyb.Pin.OUT_PP) HIGHTIME = 6000 POSTIME = 1000 LOWTIME = 800 while True: pyb.udelay(HIGHTIME) pin.low() pyb.udelay(LOWTIME) pin.high() pyb.udelay(POSTIME) pin.low() pyb.udelay(LOWTIME) pin.high() pyb.udelay(HIGHTIME - POSTIME - LOWTIME) pin.low() pyb.udelay(LOWTIME) pin.high() pyb.udelay(HIGHTIME) pin.low() pyb.udelay(LOWTIME) pin.high() pyb.udelay(HIGHTIME) pin.low()
print('Log Closed') # print(ticks) # Debounce ticks = 0 # If light switch is still On, turn off the light anyway if headlight_switch.value(): light_on = False hmi.light = 0 # Off headlight.high() if bike_on: if (horn_switch.value()) and (ticks > 5): if not horn_on: horn.low() horn_on = True ticks = 0 if (not horn_switch.value()) and (ticks > 5): if horn_on: horn_on = False horn.high() ticks = 0 if (headlight_switch.value()) and (ticks > 5): # If we enter here, there is a change of state and we # must debounce key if not light_on: hmi.light = 1 light_on = True
from pyb import Timer from pyb import Pin from network import WLAN from pyb import Sleep def Setup_Pins() # initialize GPIO7 and GPIO 8 in gpio mode (af=0) and make output # These will be the standard pins required for motor control LMotorB = Pin('GPIO7', af=0, mode=Pin.OUT) RMotorB = Pin('GPIO8', af=0, mode=Pin.OUT) LMotorB.low() RMotorB.low() # assign GPIO9 and 10 to alternate function 3 (PWM) # These will be the pins to control speed LMotorA = Pin('GPIO9', af=3, type=Pin.STD) RMotorA = Pin('GPIO10', af=3, type=Pin.STD) # Enable timer channels 3B and 4A for PWM pins LMTimer = Timer(3, mode=Timer.PWM, width=16) RMTimer = Timer(4, mode=Timer.PWM, width=16) # enable channel A @1KHz with a 50% duty cycle LMT_a = LMTimer.channel(Timer.B, freq=1000, duty_cycle=50) RMT_a = RMTimer.channel(Timer.A, freq=1000, duty_cycle=50) def Setup_WIFI() wifi = WLAN(WLAN.STA) # go for fixed IP settings wifi.ifconfig('192.168.0.107', '255.255.255.0', '192.168.0.1', '8.8.8.8') wifi.scan() # scan for available netrworks wifi.connect(ssid='mynetwork', security=2, key='mynetworkkey')
from pyb import Pin, ADC adc = ADC(Pin('X1')) # LDR p_out1 = Pin('X2', Pin.OUT_PP) # Relay p_in = Pin('X3', Pin.IN, Pin.PULL_DOWN) # PIR p_out2 = Pin('X4', Pin.OUT_PP) # Buzzer while 1: if adc.read() < 200: p_out1.low() else: p_out1.high() if p_in.value() == True: p_out2.high() pyb.delay(2000) p_out2.low()
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) blobs = img.find_blobs([green_threshold], area_threshold=1, pixels_threshold=1) biggestArea = 0 bigBlob = None turnDone.low() if blobs: # 问吴老师 模板是什么? #如果找到了目标颜色 for b in blobs: #迭代找到的目标颜色区域 # Draw a rect around the blob.# 问吴老师 模板是什么? if b.area() > biggestArea: biggestArea = b.area() bigBlob = b # 问吴老师 模板是什么? img.draw_cross(bigBlob[5], bigBlob[6]) # cx, cy circlex = bigBlob[5] circley = bigBlob[6] # 问吴老师 模板是什么? relatedX = circlex - img.width() / 2 relatedX = -relatedX # 问吴老师 模板是什么? relatedY = circley - img.height() / 2
class RFM69: def __init__(self, reset_pin=None, dio0_pin=None, spi_channel=None, config=None): self.reset_pin = reset_pin self.nss = Pin('X5', Pin.OUT_PP) self.reset = self.reset() self.spi_channel = spi_channel self.spi = SPI(1, SPI.MASTER, baudrate=50000, polarity=0, phase=0, firstbit=SPI.MSB, crc=None) self.dio0_pin = 'X3' self.conf = self.configure() self.mode = self.set_mode() self.txBufLen = 0 self.txBuf = bytearray(registers["RFM69_MAX_MESSAGE_LEN"]) self.rxBufLen = 0 self.rxBuf = bytearray(registers["RFM69_MAX_MESSAGE_LEN"]) self.version = self.getVersion() self.lastRssi = -(self.spi_read(registers["RFM69_REG_24_RSSI_VALUE"])/2) self.paLevel = 15 def configure(self): print ("Configuring...") for reg, value in config.items(): self.spi_write(registers.get(reg), value) return True def getVersion(self): self.version = self.spi_read(registers["RFM69_REG_10_VERSION"]) return self.version def set_mode(self, newMode=registers["RFM69_MODE_RX"]): self.spi_write(registers["RFM69_REG_01_OPMODE"], (self.spi_read(registers["RFM69_REG_01_OPMODE"]) & 0xE3) | newMode) while(self.spi_read(registers["RFM69_REG_01_OPMODE"]) != newMode): self.spi_write(registers["RFM69_REG_01_OPMODE"], (self.spi_read(registers["RFM69_REG_01_OPMODE"]) & 0xE3) | newMode) print ("Waiting... Attempted mode: %d" % newMode) sleep(1) pass self.mode = newMode return newMode def get_mode(self): #self.mode = self.spi_read(registers["RFM69_REG_01_OPMODE"]) return self.mode def init_gpio(self): self.dio0_pin = Pin('X3', Pin.IN, Pin.PULL_DOWN) def init_spi(self): self.spi = SPI(1, SPI.MASTER, baudrate=50000, polarity=0, phase=0, firstbit=SPI.MSB, crc=None) 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 checkRx(self): print ("MODE: %d" % self.get_mode()) print ("Waiting for Payload") while ((self.spi_read(registers["RFM69_REG_28_IRQ_FLAGS2"]) & registers["RF_IRQFLAGS2_PAYLOADREADY"]) != registers["RF_IRQFLAGS2_PAYLOADREADY"]): pass print ("MODE: %d" % self.spi_read(registers["RFM69_REG_01_OPMODE"])) print ("IRQ Flag: %d" % self.spi_read(registers["RFM69_REG_28_IRQ_FLAGS2"])) self.rxBufLen = self.spi_read(registers["RFM69_REG_00_FIFO"])+1 print ("RX Buffer Length: %d" % self.rxBufLen) self.rxBuf = self.spi_burst_read(registers["RFM69_REG_00_FIFO"], registers["RFM69_FIFO_SIZE"]) self.lastRssi = -(self.spi_read(registers["RFM69_REG_24_RSSI_VALUE"])/2) self.clearFifo() def recv(self): # Store received data for return rxTuple = (self.rxBuf, self.rxBufLen, self.lastRssi) # Clear RX buffer self.rxBufLen = 0 self.rxBuf = bytearray(registers["RFM69_MAX_MESSAGE_LEN"]) # Return received telemetry return rxTuple def send(self, data, length, power): if (power<2 or power > 20): return False #Dangerous power levels oldMode = self.mode # Copy into TX buffer self.txBuf = data self.txBufLen = length # Start Transmitter print ("OLD MODE: %d" % self.mode) self.set_mode(registers["RFM69_MODE_TX"]) print ("NEW MODE: %d" % self.mode) #Setup PA if (power <= 17): # Set PA Level self.paLevel = power + 14 self.spi_write(registers["RFM69_REG_11_PA_LEVEL"], registers["RF_PALEVEL_PA0_OFF"] | registers["RF_PALEVEL_PA1_ON"] | registers["RF_PALEVEL_PA2_ON"] | self.paLevel ) else: # Disable Over Current Protection self.spi_write(registers["RFM69_REG_13_OCP"], registers["RF_OCP_OFF"]) # Enable High Power Registers self.spi_write(registers["RFM69_REG_5A_TEST_PA1"], 0x5D) self.spi_write(registers["RFM69_REG_5C_TEST_PA2"], 0x7C) # Set PA Level self.paLevel = power + 11 self.spi_write(registers["RFM69_REG_11_PA_LEVEL"], registers["RF_PALEVEL_PA0_OFF"] | registers["RF_PALEVEL_PA1_ON"] | registers["RF_PALEVEL_PA2_ON"] | self.paLevel ) # Wait for PA ramp-up print ("Waiting for PA ramp-up") while((self.spi_read(registers["RFM69_REG_27_IRQ_FLAGS1"]) & registers["RF_IRQFLAGS1_TXREADY"]) != registers["RF_IRQFLAGS1_TXREADY"]): pass # Transmit self.write_fifo(self.txBuf) # Wait for packet to be sent print ("Waiting for packet to be sent") while ((self.spi_read(registers["RFM69_REG_28_IRQ_FLAGS2"]) & registers["RF_IRQFLAGS2_PACKETSENT"]) != registers["RF_IRQFLAGS2_PACKETSENT"]): pass # Return Transceiver to original mode print ("OLD MODE: %d" % self.mode) self.set_mode(oldMode) print ("NEW MODE: %d" % self.mode) # If we were in high power, switch off High Power Registers if (power > 17): self.spi_write(registers["RFM69_REG_5A_TEST_PA1"], 0x55) self.spi_write(registers["RFM69_REG_5C_TEST_PA2"], 0x70) self.spi_write(registers["RFM69_REG_13_OCP"], (registers["RF_OCP_ON"] | registers["RF_OCP_TRIM_95"])) # Clear TX buffer self.txBufLen = 0 self.txBuf = bytearray(registers["RFM69_MAX_MESSAGE_LEN"]) print ("Transmission complete!") def setLnaMode(self, lnaMode): self.spi_write(registers["RFM69_REG_58_TEST_LNA"], lnaMode) def clearFifo(self): self.set_mode(registers["RFM69_MODE_STDBY"]) self.set_mode(registers["RFM69_MODE_RX"]) def readTemp(self): oldMode = self.mode self.set_mode(registers["RFM69_MODE_STDBY"]) self.spi_write(registers["RFM69_REG_4E_TEMP1"], registers["RF_TEMP1_MEAS_START"]) print ("Temp Measurement Running") while (self.spi_read(registers["RFM69_REG_4E_TEMP1"]) == registers["RF_TEMP1_MEAS_RUNNING"]): pass rawTemp = self.spi_read(registers["RFM69_REG_4F_TEMP2"]) self.set_mode(oldMode) return (168 - rawTemp) - 5 # Offset and compensate for self-heating def lastRssi(self): return self.lastRssi def sampleRssi(self): # Must only be called in RX mode if (self.mode != registers["RFM69_MODE_RX"]): # Not sure what happens otherwise, so check this return 0 # Trigger RSSI Measurement self.spi_write(registers["RFM69_REG_23_RSSI_CONFIG"], registers["RF_RSSI_START"]) # Wait for Measurement to complete print ("Wait for RSSI") while((self.spi_read(registers["RFM69_REG_23_RSSI_CONFIG"]) & registers["RF_RSSI_DONE"]) != registers["RF_RSSI_DONE"]): pass # Read, store in _lastRssi and return RSSI Value self.lastRssi = -(self.spi_read(registers["RFM69_REG_24_RSSI_VALUE"])/2) return self.lastRssi # Read/Write Functions def spi_read(self, register): data = bytearray(2) data[0] = register & ~0x80 data[1] = 0 resp = bytearray(2) self.nss.low() self.spi.send_recv(data, resp, timeout=5000) self.nss.high() return resp[1] def spi_burst_read(self, register, length): data = bytearray(length+1) data[0] = register & ~0x80 for i in range(1,length+1): data[i] = 0 # We get the length again as the first character of the buffer buf = bytearray(length+1) self.nss.low() self.spi.send_recv(data, buf, timeout=5000) self.nss.high() return buf[1:] def spi_write(self, register, value): data = bytearray(2) data[0] = register | 0x80 data[1] = value self.nss.low() self.spi.send(data, timeout=5000) self.nss.high() def write_fifo(self, data): fifo_data = bytearray(len(data)+2) fifo_data[0] = registers["RFM69_REG_00_FIFO"] | 0x80 fifo_data[1] = len(data) for i in range(2,len(data)+2): fifo_data[i] = data[i-2] self.nss.low() self.spi.send(fifo_data, timeout=5000) self.nss.high()
class motor(object): """ Convenience class for controlling a motor Arguments ControlPin1 : the x01 pin ControlPin2 : the x02 pin PWMpin : the PWM pin STBYpin : the STBY (standby) pin on the board Other atributes isRunning : Boolean describing if motor is running or not speed : current speed of the motor direction : current direction the motor is running =None if the motor is not currently moving """ 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 start(self, speed, direction): """ method to start a motor Arguments: speed : speed of the motor 0-100 (as percentage of max) direction : CW or CCW, for clockwise or counterclockwise """ # Standby pin should go high to enable motion self.STBYpin.high() # STBYpin.high() # GPIO.output(self.STBYpin, GPIO.HIGH) # x01 and x02 have to be opposite to move, toggle to change direction if direction in ('cw', 'CW', 'clockwise'): self.ControlPin1.low() # GPIO.output(self.ControlPin1, GPIO.LOW) self.ControlPin2.high() # GPIO.output(self.ControlPin2, GPIO.HIGH) elif direction in ('ccw', 'CCW', 'counterclockwise'): self.ControlPin1.high() # GPIO.output(self.ControlPin1, GPIO.HIGH) self.ControlPin2.low() # GPIO.output(self.ControlPin2, GPIO.LOW) else: raise ValueError('Please enter CW or CCW for direction.') # Start the motor # PWM.start(channel, duty, freq=2000, polarity=0) if 0 <= speed <= 100: self.PWMpin = Pin('X4') tim = Timer(2, freq=1000) ch = tim.channel(4, Timer.PWM, pin=self.PWMpin) ch.pulse_width_percent(speed) # PWM.start(self.PWMpin, speed) else: raise ValueError("Please enter speed between 0 and 100, \ representing a percentage of the maximum \ motor speed.") # set the status attributes self.isRunning = True self.currentDirection = direction self.currentSpeed = speed def stop(self): """ redirects to a soft stop """ self.soft_stop() def hard_stop(self): """ Method to hard stop an individual motor""" self.PWMpin = Pin('X4') tim = Timer(2, freq=1000) ch = tim.channel(4, Timer.PWM, pin=self.PWMpin) ch.pulse_width_percent(0) # PWM.set_duty_cycle(self.PWMpin, 0.0) # set the status attributes self.isRunning = True self.currentDirection = None self.currentSpeed = 0 def soft_stop(self): """ Method to soft stop (coast to stop) an individual motor""" # Make both control pins low self.ControlPin1.low() # GPIO.output(self.ControlPin1, GPIO.LOW) self.ControlPin2.low() # GPIO.output(self.ControlPin2, GPIO.LOW) self.PWMpin = Pin('X4') tim = Timer(2, freq=1000) ch = tim.channel(4, Timer.PWM, pin=self.PWMpin) ch.pulse_width_percent(0) self.STBYpin.low() # GPIO.output(self.STBYpin, GPIO.LOW) # set the status attributes self.isRunning = True self.currentDirection = None self.currentSpeed = 0.0 def set_speed(self, newSpeed): """ Method to change the speed of the motor, direciton is unchanged Arugments newSpeed : the desired new speed 0-100 (as percentage of max) """ self.PWMpin = Pin('X4') tim = Timer(2, freq=1000) ch = tim.channel(4, Timer.PWM, pin=self.PWMpin) ch.pulse_width_percent(newSpeed) # PWM.set_duty_cycle(self.PWMpin, newSpeed) self.currentSpeed = newSpeed
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) p = Pin('X1', mode=Pin.IN, pull=Pin.PULL_UP) print(p) print(p.value()) p.init(p.IN, p.PULL_DOWN) p.init(p.IN, pull=p.PULL_DOWN) p.init(mode=p.IN, pull=p.PULL_DOWN) print(p) 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())
################################################################################ # 叁议电子 # www.ppptalk.com # 版本: pyboard改进版(V1.0) # 文件名: main.py # 说明: 继电器实验 # 淘宝店地址: https://shop115025335.taobao.com # 免责声明: 该程序仅用于学习与交流 # (c) PPPTalk All Rights Reserved ################################################################################ #******************************************************************************/ # import Pin/time #******************************************************************************/ from pyb import Pin import time #******************************************************************************/ # 继电器模块连接到PYBOARD开发板Y5引脚 #******************************************************************************/ relay = Pin('Y5', Pin.OUT_PP) #******************************************************************************/ # relay.low() - 常开 relay.high() - 常闭 #******************************************************************************/ while 1: relay.low() time.sleep_ms(1000) relay.high() time.sleep_ms(1000)
from pyb import Pin pinX1 = Pin('X1', Pin.IN, Pin.PULL_UP) pinX2 = Pin('X2', Pin.OUT_PP) while True: if pinX1.value() == 0: pinX2.high() else: pinX2.low()
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())
Echo = Pin('X4', Pin.IN) # Create a microseconds counter. micros = pyb.Timer(5, prescaler=83, period=0x3fffffff) #** Use timer 5 instead of 2 micros.counter(0) TIME_OUT_1 = 2000 #** maximum delay for echo signal to go high TIME_OUT_2 = 29000 #** maximum pulse width equal 5m distance while True: # Send a 20usec pulse every 20ms micros.counter(0) #** reset microsecond counter Trigger.high() pyb.udelay(20) Trigger.low() # Wait until echo pulse goes from low to high while Echo.value() == 0: if micros.counter() > TIME_OUT_1: #** maximum wait time is 2ms micros.counter(0) #** reset microsecond counter Trigger.high() #** trigger ultrasound sensor again! pyb.udelay(20) Trigger.low() micros.counter(0) #** reset microsecond counter # Wait until echo pulse goes from high to low while Echo.value() == 1: # do nothing pulse_width = micros.counter() #** record end time of pulse if pulse_width > TIME_OUT_2: #** check for time out again break #** waited too long for falling edge
class MATRIX: DEBUG = True PORT2GPIO = [stm.GPIOA, stm.GPIOB, stm.GPIOC, stm.GPIOD, stm.GPIOE] 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 pixel(self, x, y, col=None): if (0 <= x < self.__width) and (0 <= y < self.__height): lower = (y < 16) x_col = x // 4 * 3 + (0 if x % 4 == 3 else (x & 0x03)) if col is None: r, g, b = 0, 0, 0 for ln2w in range(self.__BITPERCOLOR): addr = ln2w * self.__BYTES_PER_WEIGHT + (y & 0x0F) * ( self.__bwidth) + x_col if (x & 0x03) != 0x03: val = self.__buffer[addr] if self.DEBUG: print("Eval %s value at %d = 0x%02x weight %d" % ("lower" if lower else "upper", addr, val, ln2w)) if lower: r += ((val) & 0x01) * (1 << ln2w) g += ((val >> 2) & 0x01) * (1 << ln2w) b += ((val >> 4) & 0x01) * (1 << ln2w) else: r += ((val >> 1) & 0x01) * (1 << ln2w) g += ((val >> 3) & 0x01) * (1 << ln2w) b += ((val >> 5) & 0x01) * (1 << ln2w) else: shift = 6 if lower else 7 r += ((self.__buffer[addr] >> shift) & 0x01) * (1 << ln2w) g += ((self.__buffer[addr + 1] >> shift) & 0x01) * (1 << ln2w) b += ((self.__buffer[addr + 2] >> shift) & 0x01) * (1 << ln2w) if self.DEBUG: print( "%s r,g,b @ %d ln2w %d = (0x%02x, 0x%02x, 0x%02x) val (0x%02x, 0x%02x, 0x%02x)" % ("lower" if lower else "upper", addr, ln2w, r & (1 << ln2w), g & (1 << ln2w), b & (1 << ln2w), self.__buffer[addr], self.__buffer[addr + 1], self.__buffer[addr + 2])) return r, g, b else: # col[0] is red # col[1] is green # col[2] is blue for ln2w in range(self.__BITPERCOLOR): addr = ln2w * self.__BYTES_PER_WEIGHT + (y & 0x0F) * ( self.__bwidth) + x_col if (x & 0x03) != 0x03: val = self.__buffer[addr] if lower: val &= 0xEA val |= 0x01 if col[0] & (1 << ln2w) else 0x00 val |= 0x04 if col[1] & (1 << ln2w) else 0x00 val |= 0x10 if col[2] & (1 << ln2w) else 0x00 else: val &= 0xD5 val |= 0x02 if col[0] & (1 << ln2w) else 0x00 val |= 0x08 if col[1] & (1 << ln2w) else 0x00 val |= 0x20 if col[2] & (1 << ln2w) else 0x00 if self.DEBUG: print("Set %s regular buffer@ %d to 0x%02x" % ("lower" if lower else "upper", addr, val)) self.__buffer[addr] = val else: mask = 0x40 if lower else 0x80 for i in range(3): self.__buffer[addr + i] &= ~mask self.__buffer[addr] |= mask if col[0] & ( 1 << ln2w) else 0x00 self.__buffer[ addr + 1] |= mask if col[1] & (1 << ln2w) else 0x00 self.__buffer[ addr + 2] |= mask if col[1] & (1 << ln2w) else 0x00 if self.DEBUG: print( "Set %s iregular buffer@ %d, %d %d to 0x%02x 0x%02x 0x%02x" % ("lower" if lower else "upper", addr, addr + 1, addr + 2, self.__buffer[addr], self.__buffer[addr + 1], self.__buffer[addr + 2])) else: raise Exception("Pixel (%d, %d) is not on canevas" % (x, y)) def select_line(self, line_number): if line_number & 0x01: self.__a.high() else: self.__a.low() if line_number & 0x02: self.__b.high() else: self.__b.low() if line_number & 0x04: self.__c.high() else: self.__c.low() if self.__d is not None: if line_number & 0x08: self.__d.high() else: self.__d.low() #@micropython.native def set_data_f(self, ln2w: int, line_nr: int): offset = ln2w * int(self.__BYTES_PER_WEIGHT) + (line_nr & 0x0F) * int( self.__bwidth) val_11 = 0 idx = int(0) for x in range(self.__width): s_idx = x & 0x03 ser_val = 0 if s_idx == 3: ser_val = val_11 val_11 = 0 else: ser_val = int(self.__buffer[offset + idx]) val_11 |= (ser_val >> (6 - 2 * s_idx)) idx += 1 for pin_nr in range(int(len(self.__color))): pin = self.__color[pin_nr] mask = 1 << pin_nr if ser_val & mask: #self.__set_hi[pin.port] = 1 << pin.pin pin.high() else: #self.__set_lo[pin.port] = 1 << pin.pin pin.low() self.__clk.high() self.__clk.low() def update(self): #print("Show line %d, weight %d" % (self.__next_linenr, self.__next_ln2weight)) self.__oe.high() # disable led driver output self.__latch.high() # latch data of last call to output # Select group self.select_line(self.__next_linenr) # Set output enable for last data self.__oe.low() self.__latch.low() # Select next group self.__next_linenr = (self.__next_linenr + 1) if self.__next_linenr == self.__cycle_max: self.__next_linenr = 0 self.__next_ln2weight = (self.__next_ln2weight + 1) % self.__BITPERCOLOR # Set data for next group self.set_data_f(self.__next_ln2weight, self.__next_linenr) def show(self, single=False): cnt = 0 while True: self.update() cnt += 1 if single and cnt > self.__height: break def test(self): col = (15, 0, 0) clear = (0, 0, 0) for y in range(self.__height): for x in range(self.__width): self.pixel(x, y, col) self.show(True) self.pixel(x, y, clear) self.show(True) def non_zero(self): res = [] for x in range(self.__width): for y in range(self.__height): val = self.pixel(x, y) if any(val): res.append("Pixel at (%d, %d) = (%d, %d, %d)" % (x, y, val[0], val[1], val[2])) return "\n".join(res) def __str__(self): res = [] res.append("Set up led matrix with:") res.append("red : %s %s" % (self.__red[0], self.__red[1])) res.append("green: %s %s" % (self.__green[0], self.__green[1])) res.append("blue : %s %s" % (self.__blue[0], self.__blue[1])) res.append("clk : %s" % self.__clk) res.append("latch: %s" % self.__latch) res.append("oe : %s" % self.__oe) res.append("a, b, c, d = %s %s %s %s" % (self.__a, self.__b, self.__c, self.__d)) res.append("line sel: %d " % self.__next_linenr) return "\n".join(res)
#Task 2: motor control print('This is Task 2: Motor Control') from pyb import Pin, Timer A1 = Pin('Y9', Pin.OUT_PP) A2 = Pin('Y10', Pin.OUT_PP) A1.high() A2.low() motor = Pin('X1') tim = Timer(2, freq=1000) ch = tim.channel(1, Timer.PWM, pin=motor) ch.pulse_width_percent(50)
# 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 MOTOR(object): 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') # Configure timer to provide PWM signal self.tim = Timer(2, freq=10000) self.motorA = self.tim.channel(1, Timer.PWM, pin=self.PWMA) self.motorB = self.tim.channel(2, Timer.PWM, pin=self.PWMB) # initialise variables for motor drive strength (PWM values) self.Aspeed = 0 # PWM value for motorA self.Bspeed = 0 # PWM value for motorB def drive(self): # drive motors at Aspeed and Bspeed if self.Aspeed > 0: self.A_forward(self.Aspeed) else: self.A_back(self.Aspeed) if self.Bspeed > 0: self.B_forward(self.Bspeed) else: self.B_back(self.Bspeed) def up_Aspeed(self, value): # increase motor A speed by value self.Aspeed = min(100, value) self.drive() def up_Bspeed(self, value): # increase motor B speed by value self.Bspeed = min(100, value) self.drive() def dn_Aspeed(self, value): # decrease motor A speed by value self.Aspeed = max(-100, value) self.drive() def dn_Bspeed(self, value): # decrease motor B speed by value self.Bspeed = max(-100, value) self.drive() def A_forward(self, value): # Drive motor A forward by value self.Aspeed = min(100, value) self.A2.high() self.A1.low() self.motorA.pulse_width_percent(abs(value)) def A_back(self, value): # Drive motor A backward by value self.Aspeed = min(100, value) self.A2.low() self.A1.high() self.motorA.pulse_width_percent(abs(value)) def B_forward(self, value): # Drive motor B forward by value self.Bspeed = min(100, value) self.B1.high() self.B2.low() self.motorB.pulse_width_percent(abs(value)) def B_back(self, value): # Drive motor B backward by value self.Aspeed = min(100, value) self.B1.low() self.B2.high() self.motorB.pulse_width_percent(abs(value)) print('Hey') print('back {}'.format(value)) def A_stop(self): # stop motor A self.Aspeed = 0 self.motorA.pulse_width_percent(0) def B_stop(self): # stop motor B self.Bspeed = 0 self.motorB.pulse_width_percent(0)
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
def read_temp_hum(self): data=[] j=0 gpio_pin=self.gpio_pin gpio_pin = Pin(self.PinName, Pin.OUT_PP) # can not ignore gpio_pin.low() time.sleep(0.018) gpio_pin.high() #wait to response gpio_pin = Pin(self.PinName,Pin.IN) while gpio_pin.value()==1: continue while gpio_pin.value()==0: continue while gpio_pin.value()==1: continue #get data while j<40: k=0 while gpio_pin.value()==0: continue while gpio_pin.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 temp_negative=0 # data[24] = 1 # print(data[24:32]) #means temperature value is negative,set data[24] with 0 to ignore it. if data[24] == 1: data[24] = 0 print(data[24:32]) temp_negative = 1 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: if temp_negative == 1: return -(temperature+temperature_point/10),humidity+humidity_point/10 temp_negative = 0 else: return temperature+temperature_point/10,humidity+humidity_point/10 else: print('checksum ERROR') return 0,0
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)
''' Rotate the motor with TMCM1270 using CAN interface. Created on 05.10.2020 @author: LK ''' from PyTrinamic.modules.TMCM1270.TMCM_1270 import TMCM_1270 from PyTrinamicMicro.platforms.motionpy.connections.can_tmcl_interface import can_tmcl_interface from pyb import Pin import time con = can_tmcl_interface() module = TMCM_1270(con) en = Pin(Pin.cpu.A4, Pin.OUT_PP) en.low() module.rotate(0, 1000) time.sleep(5) module.stop(0) en.high() con.close()
spi.send(c) cs.high() def write_command(c, *data): write_command_byte(c) if data: for d in data: write_data_byte(d) def write_image(img): cs.low() rs.high() spi.send(img) cs.high() # Reset the LCD. rst.low() time.sleep(100) rst.high() time.sleep(100) write_command(0x11) # Sleep Exit time.sleep(120) # Memory Data Access Control write_command(0x36, 0xC0) # Interface Pixel Format write_command(0x3A, 0x05) # Display On write_command(0x29)
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)
# Motor in idle state A1.high() A2.high() speed = 0 DEADZONE = 5 # Use keypad U and D keys to control speed while True: # loop forever until CTRL-C while (uart.any()!=10): #wait we get 10 chars n = uart.any() command = uart.read(10) if command[2]==ord('5'): if speed < 96: speed = speed + 5 print(speed) elif command[2]==ord('6'): if speed > - 96: speed = speed - 5 print(speed) if (speed >= DEADZONE): # forward A1.high() A2.low() motor.pulse_width_percent(speed) elif (speed <= -DEADZONE): A1.low() # backward A2.high() motor.pulse_width_percent(-speed) else: A1.low() # idle A2.low()
import pyb from pyb import Pin import time import utime from random import randint import framebuf #LCD usrspi = USR_SPI(scl=Pin('X6', Pin.OUT_PP), sda=Pin('X7', Pin.OUT), dc=Pin('X8', Pin.OUT)) disp = DISPLAY(usrspi, cs=Pin('X5', Pin.OUT), res=Pin('X4', Pin.OUT), led_en=Pin('X3', Pin.OUT)) r = Pin('X9', Pin.OUT_PP) r.low() pins = ['Y7', 'Y8', 'Y5', 'Y6'] keys = [] for p in pins: keys.append(Pin(p, Pin.IN, Pin.PULL_UP)) class Grid(object): #网格类 def __init__(self, master=None, x=8, y=8, w=12, h=12): self.x = x self.y = y self.w = w self.h = h self.width = w self.height = h self.bg = disp.WHITE
lcd.display(myImage) pyb.delay(400) print(matrix.payload()) if not matrices: qcode = img.find_qrcodes() for code in qcode: img.draw_rectangle(code.rect(), color=(255, 0, 0)) myImage = image.Image("indication.ppm", copy_to_fb=True) lcd.display(myImage) pyb.delay(400) print(code.payload()) if not qcode: bcode = img.find_barcodes() for code in bcode: img.draw_rectangle(code.rect(), color=(255, 0, 0)) myImage = image.Image("indication.ppm", copy_to_fb=True) lcd.display(myImage) pyb.delay(400) print(code.payload()) lcd.display(img) # Take a picture and display the image.s else: led.low() lcd.set_backlight(False) #lcd.deinit() #sensor.sleep(True)
#************************************ (C) COPYRIGHT 2019 ANO ***********************************# import sensor, image, time, math, struct import json from pyb import LED,Timer,Pin from struct import pack, unpack import Message,LineFollowing,DotFollowing #初始化镜头 sensor.reset() sensor.set_pixformat(sensor.RGB565)#设置相机模块的像素模式 sensor.set_framesize(sensor.QQVGA)#设置相机分辨率160*120 sensor.skip_frames(time=3000)#时钟 sensor.set_auto_whitebal(False)#若想追踪颜色则关闭白平衡 #配置引脚,初始化为高电平(此时蜂鸣器不响)。 p_out = Pin('P7', Pin.OUT_PP) p_out.low()#设置p_out引脚为低 wait_state = 1 clock = time.clock()#初始化时钟 #主循环 while(True): clock.tick()#时钟初始化 DotFollowing.Isblob() #检测是否有色块。 #接收串口数据 # Message.UartReadBuffer() if DotFollowing.Dot.blob_state: p_out.high()#开启蜂鸣器
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)
def kastelu(): p_out = Pin('X11', Pin.OUT_PP) p_out.high() pyb.delay(1000) p_out.low()
class SPIMgr(): """ This class provides an interface to the hardware level SPI object which it encapsulates as a member. When creating an instance you must provide the pyboard side and the latch pin's name, eg. >>> from spiMgr import SPIMgr >>> from state import State >>> s = SPIMgr(State.spiOnX,State.spiLatchPinName) >>> print(s) SPIMgr: SPI: BoardSide: 1 MasterOrSlave: Master STCP: Pin: LatchPin: X5 PinOut: OUT_PP Value: 0 ++ The class only provides one method: update(bitArray). This method is called with an array of ints representing the bits to be set to one via an SPI call. The process is 1. set the latch pin LOW 2. send the bits, int by int 3. set the latch pin to high Note that when doing Off-board tests, the 'send' message will appear twice. usage: >>> s.update([0,1,2,4,8,16]) Pin: LatchPin: X5 PinOut: OUT_PP Value: 0 set: LOW Simulated: send: 0b0 send: 0b0 Simulated: send: 0b1 send: 0b1 Simulated: send: 0b10 send: 0b10 Simulated: send: 0b100 send: 0b100 Simulated: send: 0b1000 send: 0b1000 Simulated: send: 0b10000 send: 0b10000 Pin: LatchPin: X5 PinOut: OUT_PP Value: 1 set: HIGH """ 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 update(self,bitArray): # send the data bits to the shift register # unset the latch self.stcp.low() # send the bits i=0 # remove for production for r in bitArray: self.spi.send(r) #### COMMENT NEXT LINE FOR Off-Board TESTS! #State.printT('send reg:\t' + str(i)+ '\t{0:08b}'.format(r)) i += 1 # remove for production # turn on the latch self.stcp.high() def __repr__(self): return 'SPIMgr:' + \ '\n' + str(self.spi) + \ '\nSTCP:\n' + str(self.stcp)
class RGBLed(object): colors = ('red', 'blue', 'green', 'yellow', 'pink', 'marine') def __init__(self): self.pRed = Pin('lRed') self.pGreen = Pin('lGreen') self.pBlue = Pin('lBlue') self.color = None self.active = [] self.timer = Timer(2, freq=1) self.timer.callback(self.__toggle__) self.off() def red(self): if self.color == 'red': return self.pGreen.low() self.pBlue.low() self.active.clear() self.active.append(self.pRed) self.color = 'red' def blue(self): if self.color == 'blue': return self.pRed.low() self.pGreen.low() self.active.clear() self.active.append(self.pBlue) self.color = 'blue' def green(self): if self.color == 'green': return self.pRed.low() self.pBlue.low() self.active.clear() self.active.append(self.pGreen) self.color = 'green' def yellow(self): if self.color == 'yellow': return self.off() self.active.append(self.pGreen) self.active.append(self.pRed) self.color = 'yellow' def pink(self): if self.color == 'pink': return self.off() self.active.append(self.pBlue) self.active.append(self.pRed) self.color = 'pink' def marine(self): if self.color == 'marine': return self.off() self.active.append(self.pGreen) self.active.append(self.pBlue) self.color = 'marine' def off(self): self.pRed.low() self.pGreen.low() self.pBlue.low() self.active.clear() def __toggle__(self, tim): if self.color is None: return for pin in self.active: pin.off() if pin.value() else pin.on()
# Task 4: Joystick Controlling the Motor # Author: BSG # Version 1.0 # 26 May 2016 print ('This is Test 4: Joystick Controlling the Motor') from pyb import Pin, Timer, ADC while True: pyb.delay(1) A1 = Pin('Y9',Pin.OUT_PP) A2 = Pin('Y10',Pin.OUT_PP) A1.high() A2.low() motor = Pin('X1') tim = Timer(2, freq = 1000) ch = tim.channel(1, Timer.PWM, pin = motor) adc_1 = ADC(Pin('X19')) #vertical adc_2 = ADC(Pin('X20')) #horizontal J_sw = Pin('Y11', Pin.IN) #switch vertical = (int(adc_2.read()) / 1700)*100 ch.pulse_width_percent(vertical)
class si2c: __scl = Pin.__class__ __sda = Pin.__class__ __scl_pin = '' __sda_pin = '' def __init__(self, scl, sda): try: self.__scl_pin = scl self.__sda_pin = sda self.__scl = Pin(scl, Pin.OUT_PP, pull=Pin.PULL_UP) self.__sda = Pin(sda, Pin.OUT_PP, pull=Pin.PULL_UP) self.__scl.high() self.__sda.high() pass except: pass def __sda_in(self): self.__sda = Pin(self.__sda_pin, Pin.IN, pull=Pin.PULL_UP) def __sda_out(self): self.__sda = Pin(self.__sda_pin, Pin.OUT_PP, pull=Pin.PULL_UP) def start(self): self.__sda_out() self.__scl.high() self.__sda.high() utime.sleep_us(5) self.__sda.low() utime.sleep_us(6) self.__scl.low() def end(self): self.__scl.low() self.__sda_out() self.__sda.low() self.__scl.high() utime.sleep_us(6) self.__sda.high() utime.sleep_us(6) def wait_ack(self): time = 0 self.__sda_in() self.__sda.high() utime.sleep_us(2) self.__scl.high() while self.__sda.value() == 1: time += 1 if time > 250: self.end() return 1 #应答失败 self.__scl.low() return 0 #应答成功 #产生应答,state=1应答,state=0无应答 def ack(self, state=0): self.__scl.low() self.__sda_out() if state == 1: self.__sda.low() else: self.__sda.high() utime.sleep_us(2) self.__scl.high() utime.sleep_us(5) self.__scl.low() def send_byte(self, b): b = bin(b).replace('0b', '') b = '{0:0>8}'.format(b) # print(b) self.__sda_out() # 输出模式 # self.start() for ch in b: if ch == '0': self.__sda.low() else: self.__sda.high() utime.sleep_us(2) self.__scl.high() utime.sleep_us(2) self.__scl.low() utime.sleep_us(2) def read_byte(self, ask=1): self.__sda_in() b = '0b' for i in range(8): self.__scl.low() utime.sleep_us(2) self.__scl.high() if self.__sda.value() == 1: b += '1' else: b += '0' return int(b)
class STAccel: 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) def debug(self, *msg): if self._debug: print(" ".join(str(m) for m in msg)) def _convert_raw_to_g(self, x): if x & 0x80: x -= 256 return x * self.sensitivity / 1000 def read_bytes(self, addr, nbytes): self.cs_pin.low() if nbytes > 1: self.spi.send(addr | READWRITE_CMD | MULTIPLEBYTE_CMD) else: self.spi.send(addr | READWRITE_CMD) # read data, MSB first buf = self.spi.recv(nbytes) self.cs_pin.high() return buf def write_bytes(self, addr, buf): if not isinstance(buf, (int, bytes, bytearray)): buf = bytes(buf) if not isinstance(buf, int) and len(buf) > 1: addr |= MULTIPLEBYTE_CMD self.cs_pin.low() self.spi.send(addr) self.spi.send(buf) 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 write_command(c, *data): write_command_byte(c) if data: for d in data: write_data_byte(d) def write_image(img): cs.low() rs.high() spi.send(img) cs.high() # Reset the LCD. rst.low() time.sleep(100) rst.high() time.sleep(100) write_command(0x11) # Sleep Exit time.sleep(120) # Memory Data Access Control write_command(0x36, 0xC0) # Interface Pixel Format write_command(0x3A, 0x05) # Display On write_command(0x29)
#GND #Communication mode is 0, need to set M0 and M1 to 0. #JSON data format: #{ID:123,CMD:heartbeat,DATA:hello,SEQUENCE:123} from pyb import Pin from pyb import UART from pyb import Timer import time #LED shining regularly(using timer) to indicate the program is running correctly tim1 = Timer(1, freq=1) tim1.callback(lambda t: pyb.LED(1).toggle()) M0 = Pin('X3', Pin.OUT_PP) M1 = Pin('X4', Pin.OUT_PP) M0.low() M1.low() u4 = UART(4, 9600) u4.init(9600, bits=8, parity=None, stop=1) u4.write('{ID:1,CMD:OnLine,DATA:TYPBoard1,SEQ:0}') if __name__ == '__main__': while True: len = u4.any() if (len > 0): print(u4.read())
adc = ADC(Pin('X5')) L1 = Pin('X1', pyb.Pin.OUT_PP) L2 = Pin('X2', pyb.Pin.OUT_PP) L3 = Pin('X3', pyb.Pin.OUT_PP) L4 = Pin('X4', pyb.Pin.OUT_PP) L5 = Pin('X6', pyb.Pin.OUT_PP) while True: x = adc.read() if x > 110 and x < 300: L1.high() elif x > 301 and x < 500: L1.high() L2.high() elif x > 501 and x < 700: L1.high() L2.high() L3.high() elif x > 701 and x < 1000: L1.high() L2.high() L3.high() L4.high() L5.high() else: L2.low() L3.low() L4.low() L5.low() L1.low()