def __init__(self): self.serial_ref = pyb.USB_VCP() self.buffer = "" self.paused = True self.who_i_am = "dummy" # put who_i_am ID here self.packet_end = "\n" self.accel = pyb.Accel() self.switch = pyb.Switch() self.switch.callback(lambda: self.write_switch()) self.should_write_switch = False self.leds = [pyb.LED(x + 1) for x in range(4)] self.led_colors = {'r': 0, 'g': 1, 'y': 2, 'b': 3} self.leds[0].on() self.py_version = sys.version self.upy_version = "%d.%d.%d" % sys.implementation[1] self.time0 = time.ticks_us() self.write_time0 = time.ticks_ms()
def main(): print('alevel test is running.') CWriter.set_textpos(ssd, 0, 0) # In case previous tests have altered it wri = CWriter(ssd, arial10, GREEN, BLACK, verbose=False) wri.set_clip(True, True, False) acc = pyb.Accel() dial = Dial(wri, 5, 5, height=75, ticks=12, bdcolor=None, label='Tilt Pyboard', style=Dial.COMPASS, pip=YELLOW) # Border in fg color ptr = Pointer(dial) scale = 1 / 40 while True: x, y, z = acc.filtered_xyz() # Depending on relative alignment of display and Pyboard this line may # need changing: swap x and y or change signs so arrow points in direction # board is tilted. ptr.value(-y * scale + 1j * x * scale, YELLOW) refresh(ssd) utime.sleep_ms(200)
def spirit(): xlights = (pyb.LED(2), pyb.LED(3)) ylights = (pyb.LED(1), pyb.LED(4)) accel = pyb.Accel() SENSITIVITY = 3 while True: x = accel.x() if x > SENSITIVITY: xlights[0].on() xlights[1].off() elif x < -SENSITIVITY: xlights[1].on() xlights[0].off() else: xlights[0].off() xlights[1].off() y = accel.y() if y > SENSITIVITY: ylights[0].on() ylights[1].off() elif y < -SENSITIVITY: ylights[1].on() ylights[0].off() else: ylights[0].off() ylights[1].off() pyb.delay(100)
def main(): import pyb serial = pyb.USB_VCP() midi = MidiOut(serial, channel=1) switch = pyb.Switch() if hasattr(pyb, 'Accel'): accel = pyb.Accel() SCALE = 1.27 else: from staccel import STAccel accel = STAccel() SCALE = 127 while True: while not switch(): pyb.delay(10) note = abs(int(accel.x() * SCALE)) velocity = abs(int(accel.y() * SCALE)) midi.note_on(note, velocity) while switch(): pyb.delay(50) midi.note_off(note)
def __init__(self, aCenter, aSpeed, aRadius, aColor): self.center = aCenter self.pos = aCenter self.oldpos = self.pos self.speed = aSpeed self.radius = int(aRadius) self.color = aColor self.accel = pyb.Accel()
def __init__(self): self.btn = Pin("Y8",Pin.IN,Pin.PULL_UP) self.accel = pyb.Accel() self.nbiot = NBIOT(3,9600) self.btn_state = 1 self.accel_state = 0 self.accel_thres = -11 self.time_regular = 1
def accelthread(): accelhw = pyb.Accel() # Instantiate accelerometer hardware yield from wait(0.03) # Allow accelerometer to settle accel = Accelerometer(accelhw) wf = Poller(accel.poll, (4,), 2) # Instantiate a Poller with 2 second timeout. while True: reason = (yield wf()) if reason[1]: # Value has changed print("Value x:{:3d} y:{:3d} z:{:3d}".format(accel.x, accel.y, accel.z)) if reason[2]: print("Timeout waiting for accelerometer change")
async def accel_coro(timeout=2000): accelhw = pyb.Accel() # Instantiate accelerometer hardware await asyncio.sleep_ms(30) # Allow it to settle accel = Accelerometer(accelhw, timeout) while True: result = accel.poll() if result == 0: # Value has changed x, y, z = accel.vector() print("Value x:{:3d} y:{:3d} z:{:3d}".format(x, y, z)) elif accel.timed_out(): # Report every 2 secs print("Timeout waiting for accelerometer change") await asyncio.sleep_ms(100) # Poll every 100ms
def __init__(self): self._accel = pyb.Accel() self._accel.write( 0x07, self._accel.read(0x07) & 0b11111110) # place in stand by mode to write registers self._accel.write(0x08, self._accel.read(0x08) & 0b11111000) # 120 samples/sec self._accel.write(0x07, self._accel.read(0x07) | 0b00000001) # return to active mode self._values = {"x": 0, "y": 0, "z": 0}
def face_up(): accel = pyb.Accel() light = pyb.LED(3) SENSITIVITY = 3 while True: x = accel.x() if abs(x) > SENSITIVITY: light.on() else: light.off() pyb.delay(100)
def __init__(self): self.btn = Pin("Y8", Pin.IN, Pin.PULL_UP) self.accel = pyb.Accel() self.nbiot = NBIOT(3, 9600) self.btn_state = 1 self.accel_state = 0 self.accel_thres = -11 self.sonic_thres = 0 self.real_time_delay = 0 self.time_regular = 1 self.reconnect_duration = 20 self.reconnect_count = 3 self.export()
def osc(n, d): for i in range(n): hid.send((0, int(20 * math.sin(i / 10)), 0, 0)) pyb.delay(d) osc(100, 50) # Connect to accel - NOTE you will need to use safe mode to stop - see webapge import pyb switch = pyb.Switch() accel = pyb.Accel() hid = pyb.USB_HID() while not switch(): hid.send((0, accel.x(), accel.y(), 0)) pyb.delay(20)
def __init__(self): self.serial_ref = pyb.USB_VCP() self.buffer = "" self.enable_write = False self.enable_read = False self.who_i_am = "dummy" # put who_i_am ID here self.packet_end = "\n" self.accel = pyb.Accel() self.leds = [pyb.LED(x + 1) for x in range(4)] self.led_colors = {'r': 0, 'g': 1, 'y': 2, 'b': 3} self.leds[0].on() self.py_version = sys.version self.upy_version = "%d.%d.%d" % sys.implementation[1] self.time0 = time.ticks_us()
def main(): a = pyb.Accel() pitches = [a.x, a.y] servos = [pyb.Servo(sn) for sn in servoNums] curangles = [-100, -100] # mn, mx, _, a, s = s1.calibration() # s1.calibration(mn, mx, servoCenter, a, s) # s1.speed(0) l = pyb.LED(ledNum) sw = pyb.Switch() while (1): if sw(): break for i in range(len(pitches)): p = pitches[i]() if curangles[i] != p: curangles[i] = p setservo(servos[i], p) pyb.delay(20)
def __init__(self): self.btn = Pin("Y8",Pin.IN,Pin.PULL_UP) self.water_adc = ADC(Pin.cpu.C4) self.accel = pyb.Accel() self.nbiot = NBIOT(3,9600,1,1) self.btn_state = 1 self.accel_state = 0 self.accel_thres = -11 self.sonic_thres = 0 self.real_time_delay = 0 self.time_regular = 1 self.reconnect_duration = 20 self.reconnect_count = 3 self.alter_ip1 = 0 self.alter_ip2 = 0 self.alter_ip3 = 0 self.alter_ip4 = 0 self.id_number = '00000058' self.export_id()
def led_angle(seconds_to_run_for): # make LED objects l1 = pyb.LED(1) l2 = pyb.LED(2) accel = pyb.Accel() for i in range(20 * seconds_to_run_for): # get x-axis x = accel.x() # turn on LEDs depending on angle if x < -10: l1.on() l2.off() elif x > 10: l1.off() l2.on() else: l1.off() l2.off() # delay so that loop runs at at 1/50ms = 20Hz pyb.delay(50)
import pyb leds = [pyb.LED(n) for n in range(1, 5)] acc = pyb.Accel() x = 0 led = 1 while True: leds[led].off() acc_reading = acc.x() x += acc_reading if x < 0: x += 799 elif x > 799: x -= 799 led = x // 200 leds[led].on() pyb.delay(5)
# main.py -- put your code here! import pyb # importing the board # move servo based on the movement of the board from pyb import Servo accel = pyb.Accel() # assigning the sensor to act as movement detector… ss = Servo(1) # servo on position 1 (X1, VIN, GND) while True: # while loop if accel.x() > 5: ss.angle(90) elif accel.x() < -5: ss.angle(-90) elif accel.x() == 0: ss.angle(0)
lta = (buf[3] << 8) + buf[4] if self.prev: self.prev = (acf < (lta / 2)) return False else: self.prev = (acf < (lta / 2)) return self.prev boop = capsense() ##----------------------------------------------- ## Accelerometer and Sleep Control ##----------------------------------------------- ## Bring up and configure the Accelerometer imu = pyb.Accel() imu.write(0x7, 0x00) # Switch to standby mode imu.write(0x8, 0x00) # Set sampling rate to 120Hz imu.write(0x6, 0xe4) # Enable shake and tap detection interrupts imu.write( 0x9, 0x6f) # Set tap threshold to 15 counts, disable all by Z-axis for tap. imu.write(0xA, 0x0f) # Increase the tap debounce threshold. imu.write(0x7, 0xc1) # Set push-pull active-high interrupt, back to active mode. ## For tracking orientation. xyz = [imu.x(), imu.y(), imu.y()] sensitivity = 5 ## Keep track of activity timing.
''' Code put in the file main.py ''' import pyb import time acc = pyb.Accel() # Accelerometer green = pyb.LED(2) green.on() yellow = pyb.LED(3) yellow.on() while 1: time.sleep(0.025) print(str(acc.x()) + ',' + str(acc.y()) + ',' + str(acc.z()))
# test we can correctly create by id or name for bus in (-1, 0, 1, 2, 3, "X", "Y", "Z"): try: I2C(bus) print("I2C", bus) except ValueError: print("ValueError", bus) i2c = I2C(1) i2c.init(I2C.MASTER, baudrate=400000) print(i2c.scan()) i2c.deinit() # use accelerometer to test i2c bus accel_addr = 76 pyb.Accel() # this will init the MMA for us i2c.init(I2C.MASTER, baudrate=400000) print(i2c.scan()) print(i2c.is_ready(accel_addr)) print(i2c.mem_read(1, accel_addr, 7, timeout=500)) i2c.mem_write(0, accel_addr, 0, timeout=500) i2c.send(7, addr=accel_addr) i2c.recv(1, addr=accel_addr)
def init(self): super().init() self._accel = pyb.Accel()
def __init__(self, sensor_id): super().__init__(sensor_id, 'i8', 'i8', 'i8') self.accel = pyb.Accel()
import pyb servo = pyb.Servo(1) ac = pyb.Accel() k = 3 while True: pyb.delay(250) servo.angle(ac.x()*k)
from pyb import I2C # test we can correctly create by id or name for bus in (-1, 0, 1, 2, 3, "X", "Y", "Z"): try: I2C(bus) print("I2C", bus) except ValueError: print("ValueError", bus) i2c = I2C(1) i2c.init(I2C.MASTER, baudrate=400000) print(i2c.scan()) i2c.deinit() # use accelerometer to test i2c bus accel_addr = 76 pyb.Accel() # this will init the bus for us print(i2c.scan()) print(i2c.is_ready(accel_addr)) print(i2c.mem_read(1, accel_addr, 7, timeout=500)) i2c.mem_write(0, accel_addr, 0, timeout=500) i2c.send(7, addr=accel_addr) i2c.recv(1, addr=accel_addr)
#hardware platform: pyboard V1.1 # use this demo you should do: # 1. open boot.py # 2. enable pyb.usb_mode('VCP+HID') # 3. close uPyCraft and reconnet pyboard for PC # 4. open uPyCraft and run this demo # 5. ctrl+c or stop could stop this demo # Restoring your pyboard to normal # 1. Hold down the USR switch. # 2. While still holding down USR, press and release the RST switch. # 3. The LEDs will then cycle green to orange to green+orange and back again. # 4. Keep holding down USR until only the orange LED is lit, and then let go of the USR switch. # 5. The orange LED should flash quickly 4 times, and then turn off. # 6. You are now in safe mode. import pyb switch = pyb.Switch() accel = pyb.Accel() #Accel is an object that controls the accelerometer hid = pyb.USB_HID( ) #create USB_HID object.it can be used to emulate a peripheral such as a mouse or keyboard. while not switch(): hid.send( (0, accel.x(), accel.y(), 0)) #Send data over the USB HID interface
import pyb if not hasattr(pyb, 'Accel'): print('SKIP') raise SystemExit accel = pyb.Accel() print(accel) accel.x() accel.y() accel.z() accel.tilt() accel.filtered_xyz()
# test I2C errors, with polling (disabled irqs) and DMA import pyb from pyb import I2C # init accelerometer pyb.Accel() # get I2C bus i2c = I2C(1, I2C.MASTER) # test polling mem_read pyb.disable_irq() i2c.mem_read(1, 76, 0x0a) # should succeed pyb.enable_irq() try: pyb.disable_irq() i2c.mem_read(1, 77, 0x0a) # should fail except OSError as e: pyb.enable_irq() print(repr(e)) i2c.mem_read(1, 76, 0x0a) # should succeed # test polling mem_write pyb.disable_irq() i2c.mem_write(1, 76, 0x0a) # should succeed pyb.enable_irq() try: pyb.disable_irq() i2c.mem_write(1, 77, 0x0a) # should fail except OSError as e:
sw = pyb.Switch() # USR button while True: # wait for user to press button pyb.delay(100) led3.toggle() if sw(): break led3.on() pyb.delay(2000) adc = pyb.ADC(pyb.Pin.board.Y12) # create an ADC on pin X19 buf = bytearray(100) # create a buffer of 100 bytes led2 = pyb.LED(2) #green led2.on() accel = pyb.Accel() # accellerometer f = open('log/data' + str(pyb.millis()) + '.dat', 'a') # generate & open file with new timestamp maxStrength = 0 # initialize max Strength while True: adc.read_timed( buf, 100) # read analog values into buf at 100Hz (will take 10 s) x, y, z = accel.filtered_xyz() # get the accelerometer data tm = pyb.millis() # get time in ms f.write("{} {} {} {} {}\n".format(tm, x, y, z, " ".join( str(e) for e in buf))) # write muscl_input and x,y,z # count=0 # for val in buf: # count=count+val # f.write("{} {} {} {} {}\n".format(tm, x, y, z, val[0])) # write muscl_input and x,y,z
# log the accelerometer values to a .csv-file on the SD-card import pyb accel = pyb.Accel() # create object of accelerometer blue = pyb.LED(4) # create object of blue LED log = open( '1:/log.csv', 'w' ) # open file to write data - 1:/ ist the SD-card, 0:/ the internal memory blue.on() # turn on blue LED for i in range( 100 ): # do 100 times (if the board is connected via USB, you can't write longer because the PC tries to open the filesystem which messes up your file.) t = pyb.millis() # get time since reset x, y, z = accel.filtered_xyz() # get acceleration data log.write('{},{},{},{}\n'.format(t, x, y, z)) # write data to file log.close() # close file blue.off() # turn off LED