def saveVideo(save_start=1, frames=100000, format="mjpeg"): global save_flag if save_flag: global FRAMES if format == "mjpeg": global m else: global g if save_start == 0: pyb.LED(3).on() if format == "mjpeg": m = mjpeg.Mjpeg("test_%s.mjpeg" % pyb.rng()) else: g = gif.Gif("test_%s.gif" % pyb.rng()) FRAMES = frames elif save_start == 1: global img # 记录帧 if record_pin.value() and FRAMES > 0: if format == "mjpeg": m.add_frame(img, quality=30) else: g.add_frame(img, delay=6) # 10FPS FRAMES -= 1 else: saveVideo(2) else: pyb.LED(3).off() if format == "mjpeg": m.close(clock.fps()) else: g.close() save_flag = 0
def __init__(self, ssid, ssid_key, ssid_security, port=554, mode=network.WINC.MODE_STA, static_ip=None): # private self.__winc = network.WINC(mode=mode) if mode == network.WINC.MODE_STA: if static_ip is not None: self.__winc.ifconfig(static_ip) self.__winc.connect(ssid, key=ssid_key, security=ssid_security) if not self.__winc.isconnected(): raise OSError("Failed to connect to network!") elif mode == network.WINC.MODE_AP: self.__winc.start_ap(ssid, key=ssid_key, security=ssid_security) else: raise ValueError("Invalid mode") self.__myip = self.__winc.ifconfig()[0] self.__myaddr = (self.__myip, port) self.__tcp__socket = None self.__udp__socket = None self.__setup_cb = None self.__play_cb = None self.__pause_cb = None self.__teardown_cb = None self.__pathname = "" self.__session = pyb.rng() self.__transport_is_tcp = False self.__client_rtp_addr = None self.__playing = False self.__sequence_number = pyb.rng() & 0xFFFF self.__ssrc = pyb.rng() print("IP Address:Port %s:%d\nRunning..." % self.__myaddr)
def enterObstacleAvoidanceState(self): self.log('Entering ObstacleAvoidanceState') self.ikEngine.travelX = 0 self.turnTimeoutTime = pyb.millis() + FRONT_OBSTACLE_TURN_TIMEOUT if (self.leftRangeDistance < SIDE_SENSOR_CLEAR_OBSTACLE) & ( self.rightRangeDistance < SIDE_SENSOR_CLEAR_OBSTACLE): # stuff on both sides, pick a direction at random to turn if pyb.rng() & 1 == 0: self.log('Obstacles on both sides, turning right') self.ikEngine.travelRotZ = -FRONT_OBSTACLE_TURN_SPEED else: self.log('Obstacles on both sides, turning left') self.ikEngine.travelRotZ = FRONT_OBSTACLE_TURN_SPEED elif self.leftRangeDistance < SIDE_SENSOR_CLEAR_OBSTACLE: self.log('Obstacle on left side, turning right') self.ikEngine.travelRotZ = -FRONT_OBSTACLE_TURN_SPEED elif self.rightRangeDistance < SIDE_SENSOR_CLEAR_OBSTACLE: self.log('Obstacle on right side, turning left') self.ikEngine.travelRotZ = FRONT_OBSTACLE_TURN_SPEED else: # nothing on either side, so pick a side at random if pyb.rng() & 1 == 0: self.log('Only front obstacle, turning right') self.ikEngine.travelRotZ = -FRONT_OBSTACLE_TURN_SPEED else: self.log('Only front obstacle, turning left') self.ikEngine.travelRotZ = FRONT_OBSTACLE_TURN_SPEED
def addbomb(self): x = int(randval(self.ds[0])) y = int(randval(self.ds[1])) rad = randval(20) + 5 r = pyb.rng() & 0xFF g = pyb.rng() & 0xFF b = pyb.rng() & 0xFF spd = randval(30.0) + 1.0 clr = self.display.color(r, g, b) self.bombs.insert(0, bomb((x, y), rad, clr, spd))
def addbomb( self ) : x = int(randval(self.ds[0])) y = int(randval(self.ds[1])) rad = randval(20) + 5 r = pyb.rng() & 0xFF g = pyb.rng() & 0xFF b = pyb.rng() & 0xFF spd = randval(30.0) + 1.0 clr = self.display.color(r,g,b) self.bombs.insert(0, bomb((x, y), rad, clr, spd))
async def do_test(loop, t): myio = MyIO() while True: tr = t * 1000 + (pyb.rng() >> 20) # Add ~1s uncertainty tw = t * 1000 + (pyb.rng() >> 20) print('Timeouts: {:7.3f}s read {:7.3f}s write'.format( tr / 1000, tw / 1000)) loop.create_task(run(receiver(myio), tr)) await run(sender(myio), tw) await asyncio.sleep(2) # Wait out timing randomness
def __init__(self, width, height, x=None, y=None, shape_nr=None): self.size = width, height self.shape_nr = shape_nr if not shape_nr: self.shape_nr = (pyb.rng() % (len(self.SHAPES) - 1)) + 1 self.shape = self.SHAPES[self.shape_nr] if x is None: x = pyb.rng() % (self.size[0] - len(self.shape[0])) if y is None: y = pyb.rng() % self.size[1] self.coord = x, y self.color = self.COLORS[self.shape_nr] self.last_coord = (0, 0)
def random(*arg): # soit forme random(max), soit forme random(min,max) # Renvoie une valeur aléatoire entiere if len(arg) == 1: #return rd.randint(0,arg[0]) return round(pyb.rng() * arg[0] / 1073741824.0) elif len(arg) == 2: # genere 1 valeur aléatoire entre 2 bornes delta = abs(arg[1] - arg[0]) values = round(pyb.rng() * delta / 1073741824.0) return arg[0] + values else: return 0 # si argument invalide
def update(self): pyb.rng() self.buf_timer.callback(None) self.dac_timer.prescaler(65535) self.dac_timer.period(65535) self.dac_timer.counter(0) self.dac1.init(bits=12) self.dac2.init(bits=12) self.dac1.write_timed(self._outHBuf1,self.dac_timer,mode=pyb.DAC.CIRCULAR) self.dac2.write_timed(self._outHBuf2,self.dac_timer,mode=pyb.DAC.CIRCULAR) self.dac_timer.init(freq=self.rate) self.buf_timer.init(prescaler=self.dac_timer.prescaler(),\ period=(self.dac_timer.period()+1)*(len(self._outFBuf)//2)-1) self.buf_timer.callback(self._fillbuf) self._phase = 0 self.ready = True
def test_gather(self, shots=2, gain_start=0, gain_step=16, gain_limit=128, shutter_start=500000, shutter_step=250000, shutter_limit=1500000): shot = 0 rnd = pyb.rng() % 1000 gain = gain_start shutter = shutter_start while True: self.init(gain_db=gain, shutter_us=shutter, framesize=sensor.WQXGA2, force_reset=False, flip=True) fn = "%u_%u_%u_%u_%u.jpg" % (rnd, self.fileseq, shot, round(self.gain), self.shutter) print(fn + " ... ", end="") self.snapshot(filename=fn) print("done") shot += 1 if shot >= shots: shot = 0 gain += gain_step if gain > gain_limit: gain = gain_start shutter += shutter_step if shutter > shutter_limit: return
def perk(self, delay, color, start=None): #print("perk(%d, %r, %r)" % (delay, color, start)) stoichiometric = self.stoichiometric i = None while True: if i is None: if start is None: i = self.top_i else: i = start self.add_color_to(i, color) yield from self.show_for(delay) if self.at_mid(i): new_color = yield from self.react_at(i) if new_color is None: return else: color = new_color prev_i = i i = self.down(i, rng()&1) self.sub_color_from(prev_i, color) self.leds_need_sync = True if i is None: return color if self.perk_quit: break self.perk_quit -= 1
def make_sample(bufin, coeffs, siglen, max_rl): actual_max_rl = 0 while True: rl = 0 for x in range(siglen): bit = 1 if pyb.rng() & 1 else -1 if rl < max_rl: coeffs[x] = bit last_bit = bit if rl > actual_max_rl: actual_max_rl = rl rl += 1 else: last_bit *= -1 coeffs[x] = last_bit rl = 1 if sum(coeffs) == 0: # No DC component # Signal is N zeros followed by N values of +-1 # For autocorrelation signal == coeffs for x in range(siglen): bufin[x] = 0 for x in range(siglen): bufin[x + siglen] = coeffs[x] # range +-1 return actual_max_rl
def randomise(self): array = ptr8(self._array) idx = int(self._size_elements) while idx: val = int(pyb.rng()) & 0xff array[idx] = val idx -= 1
def seed(): for x in range(0, width-1): for y in range(0, height-1): if pyb.rng() % 2 == 1: grid[x][y] = 1 else: grid[x][y] = 0
def perk(self, delay, color, start=None): #print("perk(%d, %r, %r)" % (delay, color, start)) stoichiometric = self.stoichiometric i = None while True: if i is None: if start is None: i = self.top_i else: i = start self.add_color_to(i, color) yield from self.show_for(delay) if self.at_mid(i): new_color = yield from self.react_at(i) if new_color is None: return else: color = new_color prev_i = i i = self.down(i, rng() & 1) self.sub_color_from(prev_i, color) self.leds_need_sync = True if i is None: return color if self.perk_quit: break self.perk_quit -= 1
def list_shuffle(list): for i, item in enumerate(list): list[i] = (pyb.rng(), item) list.sort() for i, item in enumerate(list): list[i] = item[1] return list
def tick(): global wheelColour, ledcount, sequence, ledpin pin = pyb.Pin(ledpin) neo = pyb.Neopix(pin) leds = [0x000000] * ledcount if (sequence == "rainbow"): wheelColour = (wheelColour + 8) & 255 for ledNumber in range(0, ledcount): pos = ((ledNumber*8)+wheelColour) pos = pos & 255 leds[ledNumber] = Wheel(pos).get_neo() elif (sequence == "matrix"): for ledNumber in range(0, ledcount): led_green = (pyb.rng() & 255) led_colour = Colour(0, led_green, 0) if led_green < 230: led_colour.set_g(int(led_green / 8)) if led_green > 253: led_colour.set_hex('#ffffff') leds[ledNumber] = led_colour.get_neo() elif (sequence == "colour"): colour = database.database_get("led-colour", "#ffffff") tmp_colour = Colour() tmp_colour.set_hex(colour) leds = [tmp_colour.get_neo()] * ledcount neo.display(leds)
async def run_test(): loop = asyncio.get_event_loop() loop.call_after(1, cb, 'One second has elapsed.') # Test args loop.call_after_ms(500, cb, '500ms has elapsed.') print('Callbacks scheduled.') while True: loop.call_after(0, callback, pyb.rng()) # demo use of args yield 20 # 20ms
def spawn_hab(): if len(quadcopters) > level: print("Too many copters! Call the CAA") #global tmc_count #tmc_count += 1 return quadcopter = HAB(pyb.rng()%300, 180, speed=1) quadcopters.append(quadcopter)
def testpixel(display): print('testing pixels') displaysize = display.size() r = 255 x = -10 g = 0 b = 0 for y in range(-10, displaysize[1] + 10): display.pixel((x, y), pyb.TFT.color(r, g, b)) x += 1 g += 2 b += 1 for i in range(100): x = pyb.rng() % displaysize[0] y = pyb.rng() % displaysize[1] display.pixel((x, y), randcolor()) pyb.delay(2000)
def nick_screen(container_handle): if not container_handle: container_handle = ugfx.Container(0, 0, 320, 240) container_handle.area(0, 0, 320, 240, ugfx.html_color(pyb.rng()%0xffffff)) ugfx.display_image(0, 0, "apps/sponsors/splash3.gif") container_handle.show() return container_handle
def full_test(ws): n = len(ws) print(n, ws.spi) # cycle for i in range(4 * n): for j in range(n): ws[j] = (0, 0, 0) ws[i % n] = (255, 255, 255) ws.write() time.sleep_ms(25) # bounce for i in range(4 * n): for j in range(n): ws[j] = (0, 0, 128) if (i // n) % 2 == 0: ws[i % n] = (0, 0, 0) else: ws[n - 1 - (i % n)] = (0, 0, 0) ws.write() time.sleep_ms(60) # fade in/out for i in range(4 * 256): for j in range(n): if (i // 256) % 2 == 0: ws[j] = (i & 0xff, 0, 0) else: ws[j] = (255 - (i & 0xff), 0, 0) ws.write() import pyb if hasattr(pyb, 'rng'): # twinkle for i in range(500): ws[pyb.rng() % n] = (pyb.rng() % 32, pyb.rng() % 32, pyb.rng() % 32) ws[pyb.rng() % n] = (0, 0, 0) ws.write() time.sleep_ms(5) # clear for i in range(n): ws[i] = (0, 0, 0) ws.write()
def spawn_enemy(): if level == 1: spawn_quadcopter() else: if pyb.rng() % 5 == 0: spawn_hab() else: spawn_quadcopter()
def testpixel( display ) : print('testing pixels') displaysize = display.size() r = 255 x = -10 g = 0 b = 0 for y in range(-10, displaysize[1] + 10) : display.pixel((x, y), pyb.TFT.color(r, g, b)) x += 1 g += 2 b += 1 for i in range(100): x = pyb.rng() % displaysize[0] y = pyb.rng() % displaysize[1] display.pixel((x,y), randcolor()) pyb.delay(2000)
def gen_uuid(): """ :return uuid of a message 32 random hexadecimal chars """ res = '' for i in range(0, 32): res += hex(pyb.rng() % 16)[2:].upper() return res
def get_new_game_state(w, h): angle = pyb.rng() % MAX_ANGLE + 360 - MAX_ANGLE return {'player': {'x': 0, 'y': 0}, 'ai': {'x': w - 2, 'y': h - 15}, 'ball': {'x': 5, 'y': 5, 'velocity': get_velocity(angle)}, 'score': 0}
def brown(screen): screen.clear() xdim = screen.xdim ydim = screen.ydim x = xdim // 2 y = ydim // 2 mls = 255 * xdim // 8 on = True while True: if on: on = any(sum(line) < mls for line in screen.lines) else: on = all(sum(line) == 0 for line in screen.lines) for i in range(1000): x = (x + rng()%3 - 1) % xdim y = (y + rng()%3 - 1) % ydim screen.set_pix(x, y, on) screen.sync()
def spawn_quadcopter(): if len(quadcopters) > level: print("Too many copters! Call the CAA") global tmc_count tmc_count += 1 return right = pyb.rng() % 2 if right: x = 0 direction = '+' else: x = 320 direction = '-' speed = (pyb.rng() % (level)) if speed == 0: speed = 1 quadcopter = Quadcopter(x, pyb.rng() % 160, direction=direction, speed=speed) quadcopters.append(quadcopter)
def __init__(self, network_if, port=554): # private self.__network = network_if self.__myip = self.__network.ifconfig()[0] self.__myaddr = (self.__myip, port) self.__tcp__socket = None self.__udp__socket = None self.__setup_cb = None self.__play_cb = None self.__pause_cb = None self.__teardown_cb = None self.__pathname = "" self.__session = pyb.rng() self.__transport_is_tcp = False self.__client_rtp_addr = None self.__playing = False self.__sequence_number = pyb.rng() & 0xFFFF self.__ssrc = pyb.rng() print("IP Address:Port %s:%d\nRunning..." % self.__myaddr)
def generate_board(): """ Returns random board. """ board = set() for x in range(8): for y in range(8): if pyb.rng() % 2 == 0: board.add((x, y)) return board
def testmeter(self, meter): oldvalue = 0 yield while True: val = pyb.rng() / 2**30 steps = 20 delta = (val - oldvalue) / steps for _ in range(steps): oldvalue += delta meter.value(oldvalue) yield 0.1
async def testmeter(self, meter): oldvalue = 0 await asyncio.sleep(0) while True: val = pyb.rng() / 2**30 steps = 20 delta = (val - oldvalue) / steps for _ in range(steps): oldvalue += delta meter.value(oldvalue) await asyncio.sleep_ms(100)
def minnow(t): minnows = self.minnows fut = Future() minnows.add(fut) while True: try: yield from wait_for(fut, pyb.rng() % t) return except TimeoutError: if len(minnows) < 32: yield minnow(t) # Create another
def bingo(self): stars = list(range(7, 63, 7)) p = self.percolator lattice = p.lattice rand.shuffle(stars) for i in stars: yield from sleep(200) color = tuple(lattice[i]) p.set_color_of(i, (0, 0, 0)) i = self.percolator.down(i, rng() & 1) yield self.perk_and_roll(100, color, i)
async def coro(self): oldvalue = 0 await asyncio.sleep(0) while True: val = pyb.rng() / 2**30 steps = 20 delta = (val - oldvalue) / steps for _ in range(steps): oldvalue += delta self.meter.value(oldvalue) await asyncio.sleep_ms(100)
def bingo(self): stars = list(range(7, 63, 7)) p = self.percolator lattice = p.lattice rand.shuffle(stars) for i in stars: yield from sleep(200) color = tuple(lattice[i]) p.set_color_of(i, (0,0,0)) i = self.percolator.down(i, rng()&1) yield self.perk_and_roll(100, color, i)
def orc_kicking(strength, orc, hp): ugfx.area(190,30,300,180, ugfx.BLACK) damage_orc = (pyb.rng()%6) ugfx.text(190, 30, "You kick the orc!", ugfx.WHITE) ugfx.text(190, 50, "The orc takes", ugfx.WHITE) ugfx.text(190, 70, str(damage_orc)+" damage.", ugfx.WHITE) orc = orc-damage_orc tone(155.563,250,30) pyb.delay(1000) damage = (pyb.rng()%strength) ugfx.text(190, 100, "The orc kicks you!", ugfx.WHITE) ugfx.text(190, 120, "You take "+str(damage)+" damage.", ugfx.WHITE) hp = hp-damage tone(174.614,250,30) ugfx.text(190, 150, "A: Kick again", ugfx.RED) ugfx.text(190, 170, "B: Run away", ugfx.RED) ugfx.area(30,200,180,250, ugfx.BLACK) ugfx.text(30, 200, "HP: "+str(hp), ugfx.BLUE) return orc,hp
def dance(): n = pyb.rng() % 10 + 1 #n = 1 if n == 1: print('forward') A_forward(75) B_forward(75) if n == 2: print('backwards') A_back(75) B_back(75) if n == 3: print('left turn') A_forward(75) B_forward(0) if n == 4: print('right turn') A_forward(0) B_forward(75) if n == 5: print('bare left forward') A_forward(75) B_forward(30) if n == 6: print('bare right forward') A_forward(30) B_forward(75) if n == 7: print('bare right back') A_back(75) B_back(30) if n == 8: print('bare left back') A_back(30) B_back(75) if n == 9: print('clockwise spin') A_forward(75) B_back(75) if n == 10: print('anticlockwise spin') A_back(75) B_forward(75) if n == 11: print('forward back') A_back(90) B_forward(90) pyb.delay(500) A_back(0) B_forward(0) A_forward(90) B_back(90) pyb.delay(500)
def random_dots(addr, dt=10): """ Set random colors at random positions """ import pyb while True: rn = pyb.rng() r = rn & 0xff g = (rn >> 8) & 0xff b = (rn >> 16) & 0xff x = (rn >> 24) % 36 y = x // 6 x %= 6 set_dot(addr, x, y, r, g, b) time.sleep_ms(dt)
def fib(n, fut): yield from sleep(pyb.rng() % n) if n <= 2: fut.set_result(1) else: f1 = Future() f2 = Future() yield fib(n - 1, f1) yield fib(n - 2, f2) v1 = yield from wait_for(f1) v2 = yield from wait_for(f2) fut.set_result(v1 + v2) return (v1 + v2)
def fib(n, fut): yield from sleep(pyb.rng() % n) if n <= 2: fut.set_result(1) else: f1 = Future() f2 = Future() yield fib(n-1, f1) yield fib(n-2, f2) v1 = yield from wait_for(f1) v2 = yield from wait_for(f2) fut.set_result(v1 + v2) return(v1+v2)
def test(): mgr = TimeLocationManager() print("Start Time From File: " + str(mgr.start_time)) print("File Time Stamp %u" % mgr.start_sec) i = 0 ms = pyb.millis() while i < 5: mgr.tick() print("tick " + fmt_time(mgr.get_time())) pyb.delay(1001) i += 1 print("=============") print("Time Test") i = 0 while i < 3: utc_yr = 2020 + (pyb.rng() % 2) utc_month = 1 + (pyb.rng() % 12) utc_day = 1 + (pyb.rng() % 27) utc_hr = (pyb.rng() % 24) utc_min = (pyb.rng() % 60) utc_sec = (pyb.rng() % 60) mgr.set_utc_time(utc_yr, utc_month, utc_day, utc_hr, utc_min, utc_sec) print("%s = %s" % (str((utc_yr, utc_month, utc_day, utc_hr, utc_min, utc_sec)), str(mgr.get_time()))) i += 1 print("=============") print("Rotation Test") i = 0 while i < 10: longitude = pyb.rng() % 360 if longitude > 180: longitude -= 360 mgr.set_location(longitude, None) mgr.set_utc_time(2021 + (pyb.rng() % 20), 1 + (pyb.rng() % 12), 1 + (pyb.rng() % 27), pyb.rng() % 24, pyb.rng() % 60, pyb.rng() % 60) ang = mgr.get_angle() if ang < 1 or ang > 359: print("%d, %s, %0.4f" % (longitude, fmt_time(mgr.get_time()), ang)) i += 1 print("=============")
def selfTest(self): i = 0 while i < self.capacity: save = self.readEEPROM(i) out = pyb.rng() & 0xFF self.writeEEPROM(i, out) check = self.readEEPROM(i) if out == check: print(("00000000" + hex(i)[2:])[-8:], "passed") else: print(("00000000" + hex(i)[2:])[-8:], "failed") break i += 1024 print("Capacity:", i, "vs", self.capacity, "declared.")
def selfTest(self): i=0 while i<self.capacity: save=self.readEEPROM(i) out=pyb.rng() & 0xFF self.writeEEPROM(i, out) check=self.readEEPROM(i) if out==check: print(("00000000"+hex(i)[2:])[-8:],"passed") else: print(("00000000"+hex(i)[2:])[-8:],"failed") break i+=1024 print("Capacity:",i,"vs",self.capacity,"declared.")
def get_initial_game_state(state): state['status'] = GAME_ACTIVE state['bricks'] = [{'x': x, 'y': yn * BRICK_H} for x in range(0, state['display']['width'], BRICK_W) for yn in range(BRICK_ROWS)] state['paddle'] = {'x': (state['display']['width'] - PADDLE_W) / 2, 'y': state['display']['height'] - PADDLE_H} ball_vx = BALL_SPEED_BORDER + pyb.rng() % (BALL_SPEED - BALL_SPEED_BORDER) ball_vy = -math.sqrt(BALL_SPEED ** 2 - ball_vx ** 2) state['ball'] = {'x': (state['display']['width'] - BALL_W) / 2, 'y': state['display']['height'] - PADDLE_H * 2 - BALL_W, 'vx': ball_vx, 'vy': ball_vy} return state
def shark(t, n): self.n_sharks += 1 belly = n while belly > 0: yield from sleep(t) # If well-fed, reproduce if belly > 2 * n: yield shark(t, n) belly -= n # Try to bite a minnow if len(self.minnows) > pyb.rng() & 0x1f: f = self.minnows.pop() f.set_result(None) belly += 2 else: belly -= 1 # Starved. Die. self.n_sharks -= 1
def get_new_game_state(w, h): angle = pyb.rng() % MAX_ANGLE + 360 - MAX_ANGLE return { 'player': { 'x': 0, 'y': 0 }, 'ai': { 'x': w - 2, 'y': h - 15 }, 'ball': { 'x': 5, 'y': 5, 'velocity': get_velocity(angle) }, 'score': 0 }
def shark(t, n): self.n_sharks += 1 belly = n while belly > 0: yield from sleep(t) # If well-fed, reproduce if belly > 2*n: yield shark(t, n) belly -= n # Try to bite a minnow if len(self.minnows) > pyb.rng() & 0x1f: f = self.minnows.pop() f.set_result(None) belly += 2 else: belly -= 1 # Starved. Die. self.n_sharks -= 1
def basic_np(outport = 'Y2', opentime = 13, pokeport = 'X8', trials = 100, iti = [3500, 7000, 9000], outtime = [250,250]): i = 1 ii = 0 nopoke = 0 light = pyb.Pin('X9', pyb.Pin.OUT_PP) light.low() water = pyb.Pin(outport, pyb.Pin.OUT_PP) poke = pyb.Pin(pokeport, pyb.Pin.IN, pyb.Pin.PULL_UP) pyb.delay(10000) while i <= trials: time1 = pyb.millis() if i - ii >= 1.0: ii = i time2 = pyb.millis() light.high() pyb.delay(5) if poke.value() == 0: time3 = pyb.millis() time4 = pyb.millis() time5 = pyb.millis() while (time4 - time3) < outtime[0]: if poke.value() == 0: time3 = pyb.millis() time4 = pyb.millis() water.high() pyb.delay(opentime) water.low() light.low() poketime = pyb.millis() curtime = poketime rand = pyb.rng()*(1.0/(2**30-1)) if i <= (trials/2): trial_iti = math.floor(rand*(iti[1]-iti[0])+iti[0]) else: trial_iti = math.floor(rand*(iti[2]-iti[0])+iti[0]) while (curtime-poketime) <= trial_iti: if poke.value() == 0: poketime = pyb.millis() curtime = pyb.millis() totaltime = time5 - time2 print('Trial '+str(i)+' of '+str(trials)+' completed. Last poke took '+str(totaltime)+'ms. The iti was '+str(trial_iti)) i +=1 print('Shrek says: It\'s all ogre now.')
def draw(self): if not self.crashing: self.crashing = not (pyb.rng() % 500) ugfx.area(self.x-QUADCOPTER_BODY_SIZE, self.y-QUADCOPTER_BODY_SIZE, QUADCOPTER_BODY_SIZE*2, QUADCOPTER_BODY_SIZE*2, self.color) self.animation_frame += 1 self.animation_frame %= 4 for armature_x, armature_y in ( (-QUADCOPTER_BODY_SIZE*3, -QUADCOPTER_BODY_SIZE*2), (QUADCOPTER_BODY_SIZE*3, -QUADCOPTER_BODY_SIZE*2), (-QUADCOPTER_BODY_SIZE*3, QUADCOPTER_BODY_SIZE*2), (QUADCOPTER_BODY_SIZE*3, QUADCOPTER_BODY_SIZE*2) ): rotor_center_x = self.x + armature_x rotor_center_y = self.y + armature_y ugfx.thickline(rotor_center_x, rotor_center_y, self.x, self.y, self.color, 2, False) if self.animation_frame == 0: ugfx.line(rotor_center_x - int(QUADCOPTER_BODY_SIZE*0.7), rotor_center_y - int(QUADCOPTER_BODY_SIZE*0.7), rotor_center_x + int(QUADCOPTER_BODY_SIZE*0.7), rotor_center_y + int(QUADCOPTER_BODY_SIZE*0.7), ugfx.BLACK) elif self.animation_frame == 1: ugfx.line(rotor_center_x, rotor_center_y - QUADCOPTER_BODY_SIZE, rotor_center_x, rotor_center_y + QUADCOPTER_BODY_SIZE, ugfx.BLACK) elif self.animation_frame == 2: ugfx.line(rotor_center_x + int(QUADCOPTER_BODY_SIZE*0.7), rotor_center_y - int(QUADCOPTER_BODY_SIZE*0.7), rotor_center_x - int(QUADCOPTER_BODY_SIZE*0.7), rotor_center_y + int(QUADCOPTER_BODY_SIZE*0.7), ugfx.BLACK) elif self.animation_frame == 3: ugfx.line(rotor_center_x + QUADCOPTER_BODY_SIZE, rotor_center_y, rotor_center_x - QUADCOPTER_BODY_SIZE, rotor_center_y, ugfx.BLACK) draw_crosshair(crosshair_x, crosshair_y)
import sensor, image, time, pyb sensor.reset() sensor.set_pixformat(sensor.RGB565) # or GRAYSCALE... sensor.set_framesize(sensor.QVGA) # or QQVGA... sensor.skip_frames(time = 2000) clock = time.clock() while(True): clock.tick() img = sensor.snapshot() for i in range(10): x = (pyb.rng() % (2*img.width())) - (img.width()//2) y = (pyb.rng() % (2*img.height())) - (img.height()//2) r = (pyb.rng() % 127) + 128 g = (pyb.rng() % 127) + 128 b = (pyb.rng() % 127) + 128 # If the first argument is a scaler then this method expects # to see x, y, and text. Otherwise, it expects a (x,y,text) tuple. # Character and string rotation can be done at 0, 90, 180, 270, and etc. degrees. img.draw_string(x, y, "Hello World!", color = (r, g, b), scale = 2, mono_space = False, char_rotation = 0, char_hmirror = False, char_vflip = False, string_rotation = 0, string_hmirror = False, string_vflip = False) print(clock.fps())
def randcolor( ) : r = pyb.rng() & 0xFF g = pyb.rng() & 0xFF b = pyb.rng() & 0xFF return pyb.TFT.color(r, g, b)
def conway_rand(): lcd.fill(0) # clear the LCD for x in range(128): # loop over x coordinates for y in range(32): # loop over y coordinates lcd.pixel(x, y, pyb.rng() & 1) # set the pixel randomly
def rand_np_pun(tastes = ['Y1','Y2','Y3','Y4'], opentimes = [11, 10, 10, 9], trials = 100, iti = 15000, file = 'JW05_110414'): inport_1 = 'X7' # port connected to nose poke 1 inport_2 = 'X8' # port connected to nose poke 2 i = 1 # trial counter correct = 0 # correct pokes counter log = open('/sd/'+file+'.out', 'w') # open log file on upython SD card trialarray = [] for i in range(trials): trialarray.append(i%2) # randomize trials array for i in range(trials-1): # total-1 so that the last position does not get randomized rand = pyb.rng()*(1.0/(2**30-1)) if rand >= (0.5): rand_switch = pyb.rng()*(1.0/(2**30-1)) rand_switch = int(rand_switch*(trials-i-2))+1 # random number between 1 remaining trials trialarray[i], trialarray[i+rand_switch] = trialarray[i+rand_switch], trialarray[i] # swap values while i <= trials: if trialarray[i] == 0 and pyb.Pin(inport_1, pyb.Pin.IN).value() == 0: pyb.Pin(tastes[1], pyb.Pin.OUT_PP).high() pyb.delay(opentimes[1]) pyb.Pin(tastes[1], pyb.Pin.OUT_PP).low() correct +=1 correct1 = 1 poketime = pyb.millis() # get current time curtime = poketime while (curtime-poketime) <= iti: if pyb.Pin(inport_1, pyb.Pin.IN).value() == 0 or pyb.Pin(inport_2, pyb.Pin.IN).value() == 0: poketime = pyb.millis() curtime = pyb.millis() pyb.Pin('Y8', pyb.Pin.OUT_PP).high() pyb.delay(300) pyb.Pin('Y8', pyb.Pin.OUT_PP).low() if trialarray[i+1] == 0: pyb.Pin(tastes[0], pyb.Pin.OUT_PP).high() pyb.delay(opentimes[0]) pyb.Pin(tastes[0], pyb.Pin.OUT_PP).low() elif trialarray[i+1] == 1: pyb.Pin(tastes[2], pyb.Pin.OUT_PP).high() pyb.delay(opentimes[2]) pyb.Pin(tastes[2], pyb.Pin.OUT_PP).low() log.write(str(correct1)+'\n') print('Trial '+str(i)+' of '+str(trials)+' completed. '+str(correct)+' correct.') i +=1 elif trialarray[i] == 1 and pyb.Pin(inport_2, pyb.Pin.IN).value() == 0: pyb.Pin(tastes[1], pyb.Pin.OUT_PP).high() pyb.delay(opentimes[1]) pyb.Pin(tastes[1], pyb.Pin.OUT_PP).low() correct +=1 correct1 = 1 poketime = pyb.millis() # get current time curtime = poketime while (curtime-poketime) <= iti: if pyb.Pin(inport_1, pyb.Pin.IN).value() == 0 or pyb.Pin(inport_2, pyb.Pin.IN).value() == 0: poketime = pyb.millis() curtime = pyb.millis() pyb.Pin('Y8', pyb.Pin.OUT_PP).high() pyb.delay(300) pyb.Pin('Y8', pyb.Pin.OUT_PP).low() if trialarray[i+1] == 0: pyb.Pin(tastes[0], pyb.Pin.OUT_PP).high() pyb.delay(opentimes[0]) pyb.Pin(tastes[0], pyb.Pin.OUT_PP).low() elif trialarray[i+1] == 1: pyb.Pin(tastes[2], pyb.Pin.OUT_PP).high() pyb.delay(opentimes[2]) pyb.Pin(tastes[2], pyb.Pin.OUT_PP).low() log.write(str(correct1)+'\n') print('Trial '+str(i)+' of '+str(trials)+' completed. '+str(correct)+' correct.') i +=1 elif trialarray[i] == 0 and pyb.Pin(inport_2, pyb.Pin.IN).value() == 0: pyb.Pin(tastes[3], pyb.Pin.OUT_PP).high() pyb.delay(opentimes[3]) pyb.Pin(tastes[3], pyb.Pin.OUT_PP).low() correct1 = 0 poketime = pyb.millis() # get current time curtime = poketime while (curtime-poketime) <= iti: if pyb.Pin(inport_1, pyb.Pin.IN).value() == 0 or pyb.Pin(inport_2, pyb.Pin.IN).value() == 0: poketime = pyb.millis() curtime = pyb.millis() pyb.Pin('Y8', pyb.Pin.OUT_PP).high() pyb.delay(300) pyb.Pin('Y8', pyb.Pin.OUT_PP).low() if trialarray[i+1] == 0: pyb.Pin(tastes[0], pyb.Pin.OUT_PP).high() pyb.delay(opentimes[0]) pyb.Pin(tastes[0], pyb.Pin.OUT_PP).low() elif trialarray[i+1] == 1: pyb.Pin(tastes[2], pyb.Pin.OUT_PP).high() pyb.delay(opentimes[2]) pyb.Pin(tastes[2], pyb.Pin.OUT_PP).low() log.write(str(correct1)+'\n') print('Trial '+str(i)+' of '+str(trials)+' completed. '+str(correct)+' correct.') i +=1 elif trialarray[i] == 1 and pyb.Pin(inport_1, pyb.Pin.IN).value() == 0: pyb.Pin(tastes[3], pyb.Pin.OUT_PP).high() pyb.delay(opentimes[3]) pyb.Pin(tastes[3], pyb.Pin.OUT_PP).low() correct1 = 0 poketime = pyb.millis() # get current time curtime = poketime while (curtime-poketime) <= iti: if pyb.Pin(inport_1, pyb.Pin.IN).value() == 0 or pyb.Pin(inport_2, pyb.Pin.IN).value() == 0: poketime = pyb.millis() curtime = pyb.millis() pyb.Pin('Y8', pyb.Pin.OUT_PP).high() pyb.delay(300) pyb.Pin('Y8', pyb.Pin.OUT_PP).low() if trialarray[i+1] == 0: pyb.Pin(tastes[0], pyb.Pin.OUT_PP).high() pyb.delay(opentimes[0]) pyb.Pin(tastes[0], pyb.Pin.OUT_PP).low() elif trialarray[i+1] == 1: pyb.Pin(tastes[2], pyb.Pin.OUT_PP).high() pyb.delay(opentimes[2]) pyb.Pin(tastes[2], pyb.Pin.OUT_PP).low() log.write(str(correct1)+'\n') print('Trial '+str(i)+' of '+str(trials)+' completed. '+str(correct)+' correct.') i +=1 log.close() print('It\'s all ogre now.')
def rand_np(tastes = ['Y1','Y2','Y3','Y4'], opentimes = [11, 10, 10, 9], trials = 120, iti = 15000, file = 'JW05_110614'): inport_1 = 'X7' # port connected to nose poke 1 inport_2 = 'X8' # port connected to nose poke 2 log = open('/sd/'+file+'.out', 'w') # open log file on upython SD card trialarray = [] for i in range(trials): trialarray.append(i%2) # randomize trials array for i in range(trials-1): # total-1 so that the last position does not get randomized rand = pyb.rng()*(1.0/(2**30-1)) if rand >= (0.5): rand_switch = pyb.rng()*(1.0/(2**30-1)) rand_switch = int(rand_switch*(trials-i-2))+1 # random number between 1 remaining trials trialarray[i], trialarray[i+rand_switch] = trialarray[i+rand_switch], trialarray[i] # swap values print(trialarray) i = 0 # trial counter ii = -1 # trial start counter errors = 0 # error tracker pyb.delay(10000) # delay start of experiment while i <= (trials-1): if i - ii >= 1.0: pyb.Pin('Y8', pyb.Pin.OUT_PP).high() # play tone cue pyb.delay(300) pyb.Pin('Y8', pyb.Pin.OUT_PP).low() if trialarray[i] == 0: # give passive taste cue pyb.Pin(tastes[0], pyb.Pin.OUT_PP).high() pyb.delay(opentimes[0]) pyb.Pin(tastes[0], pyb.Pin.OUT_PP).low() elif trialarray[i] == 1: pyb.Pin(tastes[2], pyb.Pin.OUT_PP).high() pyb.delay(opentimes[2]) pyb.Pin(tastes[2], pyb.Pin.OUT_PP).low() ii = i elif trialarray[i] == 0 and pyb.Pin(inport_1, pyb.Pin.IN).value() == 0: pyb.Pin(tastes[1], pyb.Pin.OUT_PP).high() pyb.delay(opentimes[1]) pyb.Pin(tastes[1], pyb.Pin.OUT_PP).low() poketime = pyb.millis() # get current time curtime = poketime while (curtime-poketime) <= iti: if pyb.Pin(inport_1, pyb.Pin.IN).value() == 0 or pyb.Pin(inport_2, pyb.Pin.IN).value() == 0: poketime = pyb.millis() curtime = pyb.millis() log.write(str(errors)+'\n') i +=1 print('Trial '+str(i)+' of '+str(trials)+' completed. Errors last trial = '+str(errors)) errors = 0 elif trialarray[i] == 1 and pyb.Pin(inport_2, pyb.Pin.IN).value() == 0: pyb.Pin(tastes[1], pyb.Pin.OUT_PP).high() pyb.delay(opentimes[1]) pyb.Pin(tastes[1], pyb.Pin.OUT_PP).low() poketime = pyb.millis() # get current time curtime = poketime while (curtime-poketime) <= iti: if pyb.Pin(inport_1, pyb.Pin.IN).value() == 0 or pyb.Pin(inport_2, pyb.Pin.IN).value() == 0: poketime = pyb.millis() curtime = pyb.millis() log.write(str(errors)+'\n') i +=1 print('Trial '+str(i)+' of '+str(trials)+' completed. Errors last trial = '+str(errors)) errors = 0 elif trialarray[i] == 0 and pyb.Pin(inport_2, pyb.Pin.IN).value() == 0: errors +=1 pyb.delay(500) elif trialarray[i] == 1 and pyb.Pin(inport_1, pyb.Pin.IN).value() == 0: errors +=1 pyb.delay(500) log.close() print('It\'s all ogre now.')