Example #1
0
def main():
    # Initialize UART for MIDI
    uart = UART(2, baudrate=31250)
    midi = MidiOut(uart)
    button1 = Switch()
    button2 = Pin('PC0', Pin.IN, Pin.PULL_UP)
    button3 = Pin('PC1', Pin.IN, Pin.PULL_UP)
    led1 = LED(1)
    led2 = LED(2)
    led3 = LED(3)
    tune = program = 0

    # send a PROGRAM CHANGE to set instrument to #0 (Grand Piano)
    midi.program_change(program)

    while True:
        if button1():
            # When button 1 is pressed, play the current tune
            play(midi, TUNES[TUNENAMES[tune]], led1)
            led1.off()
        if not button2():
            # When button 2 is pressed, select the next of the tunes
            led2.on()
            tune = (tune + 1) % len(TUNENAMES)
            delay(BLINK_DELAY)
            led2.off()
        if not button3():
            # When button 3 is pressed, change to next program (instrument)
            led3.on()
            program = (program + 1) % len(PROGRAMS)
            midi.program_change(PROGRAMS[program])
            delay(BLINK_DELAY)
            led3.off()

        delay(200)
def led_control(name, stime):
    #亮灯和间隔时间
    led = LED(name)  # Red LED = 1, Green LED = 2, Blue LED = 3, IR LEDs = 4.
    led.on()
    time.sleep(stime)
    led.off()
    time.sleep(stime)
Example #3
0
def log_gps(uart, read_delay=100):
    led = LED(4)
    with open('/sd/gps.nmea', 'a') as f:
        print(file=f)

        try:
            while True:
                led.on()
                while uart.any():
                    line = str(uart.readline(), 'utf-8').rstrip()
                    print(line, file=f)
                    parse(line)
                    led.toggle()

                f.flush()
                led.off()
                wfi()
                #delay(read_delay)
        finally:
            led.off()
            LED(2).off()
            LED(3).off()
            os.sync()

    LED(1).on()
Example #4
0
    class LEDState(
            State
    ):  # Output is determined by ``__enter__`` and ``__exit__`` (common in embedded machines).
        def __init__(self, led_num, time_on, event):
            super().__init__(ident=led_num)  # Use the LED num as the ident.
            self.led = LED(self.ident)  # The LED to use.
            self.timer = Timer(timer0 + self.ident)  # The timer to use.
            self.timeout = time_on  # Time to wait before firing event.
            self.event = event  # Event to fire at end of time_on.

        def __enter__(self):
            self.led.on()
            self.timer.init(
                freq=1 / self.timeout,
                callback=lambda _: schedule(tl_fire_ref, self.event))
            return self

        def __exit__(self, exc_type, exc_value, traceback):
            self.led.off()
            self.timer.deinit()
            return False
Example #5
0
    def initialize(self):

        led_red = LED(1)
        led_green = LED(2)
        led_blue = LED(3)
        led_green.on()
        led_blue.on()
        while True:
            try:
                sensor.reset()
                sensor.set_pixformat(sensor.GRAYSCALE)
                sensor.set_framesize(sensor.QQVGA)
                sensor.skip_frames(time=1)  # 5000
                break
            except Exception as e:
                self.logger.info("{}".format(e))
                led_red.on()
                led_green.off()
                led_blue.off()
                utime.sleep_ms(1000)
                led_red.off()
                utime.sleep_ms(1000)

        led_red.off()
        led_green.off()
        led_blue.off()
        self.thermal_configure()
Example #6
0
async def main(loop):
    rtc = RTC()
    red = LED(1)
    red.on()
    grn = LED(2)
    sta_if = network.WLAN()
    sta_if.active(True)
    sta_if.connect(SSID, PW)
    while sta_if.status() in (
            1, 2):  # https://github.com/micropython/micropython/issues/4682
        await asyncio.sleep(1)
        grn.toggle()
    if sta_if.isconnected():
        red.off()
        grn.on()
        await asyncio.sleep(1)  # 1s of green == success.
        grn.off()  # Conserve power
        Latency(2000)
        count = 0
        while True:
            publish(ujson.dumps([count, rtc.datetime()]))
            count += 1
            await asyncio.sleep(120)  # 2 mins
    else:  # Fail to connect
        red.on()
        grn.off()
Example #7
0
def main():
    # Instantiate LEDs
    led_R = LED(1)
    led_G = LED(2)
    led_B = LED(3)
    led_R.off()
    led_G.off()
    led_B.off()

    # Switch ON 3.3V external LDO
    p33v_2 = Pin('Y5', mode=Pin.OPEN_DRAIN, pull=None, value=1)

    # Wait for few seconds to turn on the 3.3V supply
    sleep(3.0)

    # Initialize I2C X bus
    Pin('PULL_SCL', Pin.OUT, value=1)  # enable 5.6kOhm X9/SCL pull-up
    Pin('PULL_SDA', Pin.OUT, value=1)  # enable 5.6kOhm X10/SDA pull-up
    try:
        i2c_bus = I2C('X', freq=400000)
        print(i2c_bus.scan())
    except Exception as error:
        print(error.__class__.__name__ + ": " + str(error))
        i2c_bus = None

    try:
        lsm303 = LSM303D(i2c_bus)
    except Exception as error:
        print(error.__class__.__name__ + ": " + str(error))
        lsm303 = None

    if lsm303:
        x_p, y_p, z_p = lsm303.accelerometer()
        mx_p, my_p, mz_p = lsm303.magnetometer()
        for i in range(10):
            led_R.on()
            x_c, y_c, z_c = lsm303.accelerometer()
            #print("Current Acceleration: {:+06.2f}g : {:+06.2f}g : {:+06.2f}g".format(x_c, y_c, z_c))
            print("Accel Diff. : {:0.4f}g : {:0.4f}g : {:0.4f}g".format(x_c-x_p, y_c-y_p, z_c-z_p))
            (x_p, y_p, z_p) = (x_c, y_c, z_c)
            sleep(0.5)
            led_R.off()
            led_G.on()
            mx_c, my_c, mz_c = lsm303.magnetometer()
            #print("Magnetic Field: {:+06.2f} : {:+06.2f} : {:+06.2f}".format(mx_c, my_c, mz_c))
            print("Magnetic Diff. : {:0.4f} : {:0.4f} : {:0.4f}".format(mx_c - mx_p, my_c - my_p, mz_c - mz_p))
            (mx_p, my_p, mz_p) = (mx_c, my_c, mz_c)
            sleep(0.5)
            led_G.off()
            led_B.on()
            temperature = lsm303.temperature()
            print("Temperature : {:0.4f}".format(temperature))
            sleep(0.5)
            led_B.off()

    # Switch ON 3.3V to TTL-RS232 converter
    p33v_2.value(0)
Example #8
0
    # Higher threshold results in a higher detection rate, with more false positives.
    objects = img.find_features(face_cascade,
                                threshold=0.75,
                                scale_factor=1.25)

    # Draw objects
    for r in objects:
        img.draw_rectangle(r)

    # Print FPS.
    # Note: Actual FPS is higher, streaming the FB makes it slower.
    print(clock.fps())

    if KEY.value() == 1:
        while KEY.value() == 1:
            blue_led.on()
            sleep(0.05)
            blue_led.off()
            sleep(0.05)
            keycount += 1
            if keycount > 3:
                # 长按K1,释放对焦马达,镜头回到初始状态
                sensor.__write_reg(0x3022, 0x08)
                while KEY.value() == 1:
                    blue_led.on()
                    sleep(0.1)
                    blue_led.off()
                    sleep(0.1)
        if keycount <= 3:
            sensor.__write_reg(0x3022, 0x03)
Example #9
0
# Welcome to the OpenMV IDE! Click on the green run arrow button below to run the script!

import sensor, image, time, pyb
from pyb import LED

sensor.reset()  # Reset and initialize the sensor.
sensor.set_pixformat(
    sensor.RGB565)  # Set pixel format to RGB565 (or GRAYSCALE)
sensor.set_framesize(sensor.QQVGA)  # Set frame size to QVGA (320x240)
sensor.skip_frames(time=2000)  # Wait for settings take effect.
clock = time.clock()  # Create a clock object to track the FPS.

led_red = LED(1)
led_blue = LED(2)
led_green = LED(3)

while (True):
    led_red.on()
    led_blue.on()
    led_green.on()
    #clock.tick()                    # Update the FPS clock.
    img = sensor.snapshot()  # Take a picture and return the image.
    clock.tick()
    height = img.height()
    width = img.width()
    img.to_rgb565()

    print(
        clock.fps())  # Note: OpenMV Cam runs about half as fast when connected
    # to the IDE. The FPS should increase once disconnected.
sensor.skip_frames(time=2000)
sensor.set_auto_gain(False)  # must turn this off to prevent image washout...
sensor.set_auto_whitebal(
    False)  # must turn this off to prevent image washout...
clock = time.clock()

# LEDs
red_led = LED(1)
green_led = LED(2)

# Barcode
myCode = "031000048495"

while (True):
    clock.tick()

    # Capture snapshot
    img = sensor.snapshot()

    # Find barcode.
    codes = img.find_barcodes()

    for code in codes:
        img.draw_rectangle(code.rect())
        if code.payload() == myCode:
            print("Found")
            green_led.on()

    if not codes:
        print("FPS %f" % clock.fps())
Example #11
0
         if Work_mode == 2:  #二维码
             sensor.set_pixformat(sensor.RGB565)
             sensor.set_framesize(sensor.QVGA)
             #sensor.set_windowing((200,200))
         if Work_mode == 1:  #条形码
             sensor.set_pixformat(sensor.RGB565)
             sensor.set_framesize(sensor.VGA)
             sensor.set_windowing((200, 200))
         if Work_mode == 33:  #红色杆识别
             pass
         if Work_mode == 44:  #蓝色杆识别
             pass
         if Work_mode == 55:  #巡线模式
             pass
     else:
         led1.on()
         time.sleep_ms(1000)
         led1.off()
         time.sleep_ms(1000)
 while (Work_mode == 2):
     sensor.set_pixformat(sensor.RGB565)
     sensor.set_framesize(sensor.QVGA)
     #sensor.set_windowing((200,200))
     clock.tick()
     uart_read_buf(uart)
     now_Work_mode = uart_mode_secelt()
     if now_Work_mode == 0:
         img = sensor.snapshot()
         find_quarter(img)
     else:
         Work_mode = now_Work_mode
Example #12
0
import utime
from scd30 import SCD30
from machine import I2C

errled = LED(1)
led = LED(2)

# Get Sensor, should be scannable here...
i2c = I2C(1)
scd30 = SCD30(i2c, 0x61)

# Make sure we have a SD card!
sd = pyb.SDCard()

if sd.present() != 1:
    errled.on()
    machine.deepsleep()

# Power off the board...
sd.power(0)

en_3v3 = Pin('EN_3V3')
en_3v3.value(0)

while True:
    data = {}
    en_3v3.value(1)
    led.on()

    sd.power(1)
    os.mount(pyb.SDCard(), '/sd')
        # DEBUG: print( 'Running' )
        if u.distance_in_cm() < MIN_DISTANCE:
            r2.halt()
            delay(100)
            r2.right()
            delay(2500)
            r2.halt()
            delay(100)
        # Si rien devant --> Marche avant
        if (r2.state == Robot2Wheel.HALTED) and (u.distance_in_cm() > MIN_DISTANCE):
            r2.forward()
    r2.halt()


# Routine principale
l.off()
while True:
    # DEBUG: print( 'Wait' )
    if btn() == True:
        # Deparasitage logiciel
        delay(10)
        if btn() == True:
            # Signaler le démarrage
            l.on()
            delay(2000)
            # Piloter le robot
            drive_robot()
            l.off()
            delay(2000)
    delay(300)  # ne rien faire
Example #14
0
from pyb import LED
import pyb
import micropython

DESTINATION_CAN_ID = 123

ledBlue = LED(1)

switch = pyb.Switch()

# 50kBaud
can = CAN(1, CAN.NORMAL, extframe=False, prescaler=40, sjw=1, bs1=14, bs2=6)

print("Press Switch to send CAN-telegrams, press <ctrl-c> to abort.")

lastValue = None

while True:
    newValue = switch.value()
    if lastValue != newValue:
        lastValue = newValue
        if newValue:
            ledBlue.on()
            telegram = b'on'
        else:
            ledBlue.off()
            telegram = b'off'

        print("Sending %s to CAN-id %d" % (telegram, DESTINATION_CAN_ID))
        can.send(telegram, DESTINATION_CAN_ID)
Example #15
0
            #else:
                #motor.A_stop()
                #motor.B_stop()

        if mic.buffer_full():  # semaphore signal from ISR - set if buffer is full
            b_LED.off()  # flash off
            # Get instantaneous energy
            E = mic.inst_energy()

            # compute moving sum of last 50 energy epochs
            sum_energy = sum_energy - e_buf[e_ptr] + E
            e_buf[e_ptr] = E  # over-write earlest energy with most recent
            e_ptr = (e_ptr + 1) % M  # increment e_ptr with wraparound - 0 to M-1

            # Compute ratio of instantaneous energy/average energy
            c = E * M / sum_energy
            # Look for a beat
            if (pyb.millis() - tic2 > 500):  # if more than 500ms since last beat
                if (c > BEAT_THRESHOLD) or (pyb.millis()-tic1 > 600):  # look for a beat
                    # look for a beat, or if not found, timeout
                    tic2 = pyb.millis()      # reset tic2
                    b_LED.on()# beat found, flash blue LED ON REPLACE THIS WITH THE MOVES
                    # execute move function (if=='c' etc)
                    readmove(movelist, counter, u)# execute a move depending on the counter
                    counter += 1            # increment a counter when beat detected
            mic.set_buffer_empty()  # reset the buffer_full flag

finally: # in the event of a crash or keyboard interrupt turn of motors before exiting program
    motor.A_stop()
    motor.B_stop()
Example #16
0
                c[4]=c4[6]
                print(c)
                c[0]=c[1] #init c[0]
                m=1
                for j in range(2):
                    if (c[0]<c[j+2] ):
                        m=j+2
                        c[0]=c[j+2]

                if (c[0]>0 ): # above a bar = matching someone
                    if (m==1):
                        img.draw_cross(c1[0], c1[1], size=5)
                        img.draw_string(0, 10, "Match %d%%"%(c1[6]))
                        print("He jianfei DETECTED","Match %d%%"%(c1[6]))
                        i[1]=i[1]+1
                        green_led.on()
                        time.sleep(1000)
                        green_led.off()
                    if (m==2):
                        img.draw_cross(c2[0], c2[1], size=5)
                        img.draw_string(0, 10, "Match %d%%"%(c2[6]))
                        print("sun fang DETECTED","Match %d%%"%(c2[6]))
                        i[2]=i[2]+1
                        green_led.on()
                        time.sleep(300)
                        green_led.off()
                    if (m==3):
                        img.draw_cross(c3[0], c3[1], size=5)
                        img.draw_string(0, 10, "Match %d%%"%(c3[6]))
                        print("He zhiyuam DETECTED","Match %d%%"%(c3[6]))
                        i[3]=i[3]+1
Example #17
0
#########################
#     Prerequisites     #
#########################


#set up transceiver to receive data to from cansat
x3_pin = Pin('X3', Pin.OUT_PP)
x3_pin.high()

#create transceiver object on UART4
hc12 = UART(4, 9600)

#feedback-pyboard on and working
green = LED(2)
green.on()

#feedback-waiting for user to press button
orange = LED(3)
orange.on()


#########################
#      Sub Programs     #
#########################


def start():
	hc12.write('1')
	orange.off()
Example #18
0
led3 = LED(3)
led4 = LED(4)

print("LED")

punainen = True
keltainen = False
vihrea = False
keltainen2 = False

#pyb.delay(5000)

while True:

    if sw() and punainen:
        led.on()
        led3.off()
        punainen = False
        keltainen = True
    pyb.delay(200)
    if sw() and keltainen:
        led.on()
        led3.on()

        keltainen = False
        vihrea = True
        pyb.delay(200)
    if sw() and vihrea:
        led2.on()
        led.off()
        led3.off()
        #lcd.display(img)
    else:
        err_x = 0
        err_y = 0
    if (uart.any()):  #判断是否有串口数据
        uart_data = uart.readchar()
    if uart_data == 0XAA:
        err_min = err_min + 1
    elif uart_data == 0XBB:
        err_max = err_min - 1
    elif uart_data == 0XCC:
        err_max = err_max + 1
    elif uart_data == 0XDD:
        err_max = err_max - 1
    if err_x > err_min and err_x < err_max:
        red_led.on()
        blue_led.off()
        pin0.value(0)
        pin1.value(0)
    elif err_x < err_min:
        red_led.off()
        blue_led.on()
        pin0.value(1)
        pin1.value(0)
    elif err_x > err_max:
        red_led.off()
        blue_led.on()
        pin0.value(0)
        pin1.value(1)

    #数组中数据写入
Example #20
0
sensor.set_auto_gain(False)
sensor.set_auto_whitebal(False)  # must be turned off for color tracking
clock = time.clock()

x = 0
y = 0

while (True):
    clock.tick()

    img = sensor.snapshot()
    blobs = img.find_blobs([threshold],
                           pixels_threshold=10,
                           area_threshold=10,
                           merge=True)
    la_led.on()
    time.sleep(500)
    la_led.off()

    verify = bytearray([0xB3, 0xB3])
    uart.write(verify)

    for b in blobs:
        img.draw_rectangle(b[0:4])
        img.draw_cross(b.cx(), b.cy())
        img.draw_circle(b[5], b[6], 10, color=(255, 0, 0))
        x = b.cx()
        y = b.cy()
        area = w * h
        data = bytearray([x, y])
        uart.write(data)
Example #21
0
            delay(100)
            r2.backward( 50 )
            delay( 300 )

            r2.right()
            delay( 300 )

            r2.halt()
            delay(100)
        # Si rien devant --> Marche avant
        if (r2.state == Robot2Wheel.HALTED) and (r2.distance() > MIN_DISTANCE): 
            r2.forward()
    r2.halt()

# Routine principale
l.off()
while True:
    #DEBUG: print( 'Wait' )
    if r2.button_pressed(1):
        # Deparasitage logiciel
        delay( 10 )
        if r2.button_pressed(1) == True:
           # Signaler le démarrage
           l.on()
           delay( 2000 ) 
           # Piloter le robot
           drive_robot()
           l.off()
           delay( 2000 )

    delay( 300 ) # ne rien faire 
#找到最大色块
def find_max(blobs):
    max_size=0
    for blob in blobs:
        if blob.pixels() > max_size:
            max_blob=blob
            max_size = blob.pixels()
    return max_blob


while(True):
    clock.tick()
    img = sensor.snapshot()
    if a==0:
        blobs=img.find_blobs([thresholds[0]],roi=(50,50,100,100), pixels_threshold=60, area_threshold=60, merge=True)
        if blobs==0:
            led2.off()#灭
            send_data_packet(888,888)
        if blobs:
            max_blob=find_max(blobs)
            # These values depend on the blob not being circular - otherwise they will be shaky.
            # These values are stable all the time.
            led2.on()#亮
            img.draw_rectangle(max_blob.rect())
            img.draw_cross(max_blob.cx(), max_blob.cy())
            send_data_packet(max_blob.cx(), max_blob.cy())
            print(max_blob.cx(), max_blob.cy())
            # Note - the blob rotation is unique to 0-180 only.
            img.draw_keypoints([(max_blob.cx(), max_blob.cy(), int(math.degrees(max_blob.rotation())))], size=20)
    print(clock.fps())
Example #23
0
def console( derivative_fix=0 ):
	print( '-'*20 )
	print( 'MotorSkin Interactive Console')
	print( 'q: quit to REPL   - quitter vers REPL')
	print( '')
	print( '8: increase speed - accelerer' )
	print( '2: decrease speed - ralentir' )
	print( '7: going left     - aller a gauche')
	print( '9: going right    - aller a droite')
	print( '4: turn left      - tourner à gauche')
	print( '6: turn right     - tourner à droite')
	print( '5: HALT           - ARRET')
	print( '-'*20)
	print( 'INIT MOTORSKIN')
	l = LED(4)   # LED Bleue / Blue LED
	l.off()
	r2 = Robot2Wheel( derivative_fix=derivative_fix ) 
	r2.halt()

	print( 'READY')
	l.on()
	
	# User standard input to read instruction via the REPL connection.
	# Utiliser l'entrée standard pout lire les insctruction via la connexion REPL
	stdin = sys.stdin
	cmd = ''
	speed = 0
	# Difference of speed between wheel - to have a bend turning
	# Difference de vitesse entre les roues - pour prendre un virage 
	speed_delta = 0  
	while cmd!='q':
		# Blocking read 1 char from stdin
		# Lecture bloquante de 1 caractere sur stdin 
		cmd = stdin.read(1)

		if cmd == 'q':
			pass
		elif cmd == '5': # Halt
			r2.halt()
			speed = 0
			speed_delta = 0
			print('halted')

		elif cmd == '8': # Increase Speed
			if abs(speed_delta)>0: # abort bending
				speed_delta = 0
				speed = speed_control( r2, speed, +0 )
			if r2.state in [Robot2Wheel.RIGHT_ROTATE, Robot2Wheel.LEFT_ROTATE]:
				# stop the rotation... keep current speed
				speed = speed_control( r2, speed, +0 )
			else:
				speed = speed_control( r2, speed, +10 )
			print( 'speed:%i' % speed )

		elif cmd == '2': # Decrease speed
			if abs(speed_delta) >0: # abord bending
				speed_delta = 0
				speed = speed_control( r2, speed, 0 )
			else:
				speed = speed_control( r2, speed, -10 )
			print( 'speed:%i' % speed )

		elif cmd == '9': # Bending (turning) on right
			if speed<50:
				print( 'bending:speed-too-low!')
			else:
				speed_delta = speed_delta_control( r2, speed, speed_delta, +10 )
				print( 'bending:%i @ %i' %(speed, speed_delta) )

		elif cmd == '7': # Bending (turning) on left
			if speed<50:
				print( 'bending:speed-too-low!')
			else:
				speed_delta = speed_delta_control( r2, speed, speed_delta, -10 )
				print( 'bending:%i @ %i' %(speed, speed_delta) )

		elif cmd == '6': # Turning right
			r2.right( speed )
			print( 'right:%i' % speed )

		elif cmd == '4': # turning left
		    r2.left( speed )
		    print( 'left:%i' % speed )



	# End of software
	r2.halt()
	l.off()
	del(r2)
	print( 'BYE' )
Example #24
0
def main():
    # Switch ON 3.3V external LDO
    p33v_2 = Pin('Y5', mode=Pin.OPEN_DRAIN, pull=None, value=1)
    sleep(3.0)

    # Instantiate LEDs
    led_R = LED(1)
    led_G = LED(2)
    led_B = LED(3)
    led_R.off()
    led_G.off()
    led_B.off()

    # Intialize I2C Bus X
    Pin('PULL_SCL', Pin.OUT, value=1)  # enable 5.6kOhm X9/SCL pull-up
    Pin('PULL_SDA', Pin.OUT, value=1)  # enable 5.6kOhm X10/SDA pull-up
    try:
        i2c = I2C('X', freq=400000)
        print(i2c.scan())
    except Exception as error:
        print(error.__class__.__name__ + ": " + str(error))
        i2c = None
    """
    # Intialize I2C Bus Y
    y9 = Pin('Y9', Pin.OUT, Pin.PULL_UP)  # enable 5.6kOhm Y9/SCL pull-up
    y10 = Pin('Y10', Pin.OUT, Pin.PULL_UP)  # enable 5.6kOhm Y10/SDA pull-up
    try:
        i2c = I2C('Y', freq=400000)
        print(i2c.scan())
    except Exception as error:
        print(error.__class__.__name__ + ": " + str(error))
        i2c = None
    """

    # Instantiate TSYS01 (Temperature Sensor)
    try:
        tsys01 = TSYS01(i2c)
    except Exception as error:
        print(error.__class__.__name__ + ": " + str(error))
        tsys01 = None

    # Instantiate MS5837 (Pressure Sensor)
    try:
        ms5837 = MS5837(i2c)
    except Exception as error:
        print(error.__class__.__name__ + ": " + str(error))
        ms5837 = None

    # Initialize Temperature Sensor for reading
    tsys01.init()
    sleep(0.125)
    # Initialize Pressure Sensor for reading
    ms5837.init()
    sleep(0.125)
    for i in range(20):
        led_R.on()
        tsys01.read()
        sleep(0.5)
        led_R.off()
        led_G.on()
        ms5837.read()
        sleep(0.5)
        led_G.off()
        temperature_1 = tsys01.temperature()
        pressure = ms5837.pressure()
        temperature_2 = ms5837.temperature()
        print(
            "Temperature in Centrigrade from TSYS01: {:0.4f} and from MS5837: {:0.4f}"
            .format(temperature_1, temperature_2))
        print("Pressure in mBar from MS5837: {:0.4f}".format(pressure))

    # Switch OFF 3.3V external LDO
    p33v_2.value(0)
Example #25
0
write_reg(addr_ctrl_reg4, 0x77)
clear_ecran()
borders()

while True:
    x_accel = read_acceleration(0x28)
    y_accel = read_acceleration(0x2A)

    #print("{:20}, {:20}".format(x_accel, y_accel))
    print(vaisseau.x, vaisseau.y)

    seuil = 0x12C  #valeur de 300 mg
    led_px, led_nx = LED(1), LED(2)

    if x_accel > seuil:
        led_px.on()
        move(vaisseau.x, vaisseau.y)
        uart.write("      ")
        vaisseau.x += 1
        colision_right()()
        move(vaisseau.x, vaisseau.y)
        uart.write(vaisseau.skin)
    else:
        led_px.off()

    if x_accel < -seuil:
        led_nx.on()
        move(vaisseau.x, vaisseau.y)
        uart.write("      ")
        vaisseau.x -= 1
        colision_left()()
Example #26
0
#hardware platform: pyboard V1.1
from pyb import LED
import time
led1 = LED(1)
led1.toggle()  #turn on led
led2 = LED(2)
led2.toggle()
led3 = LED(3)
led3.toggle()
led4 = LED(4)
led4.toggle()
while 1:
    time.sleep(0.5)
    led1.on()
    time.sleep(0.5)
    led1.off()
    time.sleep(0.5)
    led3.on()
    time.sleep(0.5)
    led3.off()
    time.sleep(0.5)
    led2.on()
    time.sleep(0.5)
    led2.off()
    time.sleep(0.5)
    led4.on()
    time.sleep(0.5)
    led4.off()
Example #27
0
			print('mode 3')

#_____________________________________________________________________________
	if mode == 1:
		print('roaming activated')		#infrared
		if IR_sensor1.value() and IR_sensor2.value(): #no value
			RED.off()
			A1.high()
			A2.low()
			B1.low()
			B2.high()
			motor1.pulse_width_percent(50)
			motor2.pulse_width_percent(50)

		elif IR_sensor1.value() == 1:
			RED.on()
			print('LEFT')
			motor1.pulse_width_percent(0)
			motor2.pulse_width_percent(80)

		elif IR_sensor2.value() == 1:
			RED.on()
			print('RIGHT')
			motor1.pulse_width_percent(80)
			motor2.pulse_width_percent(0)

		else:
			motor1.pulse_width_percent(0)
			motor2.pulse_width_percent(0)
#_____________________________________________________________________________
	elif mode == 2:
Example #28
0
    'RED': 9,
    'MOTOR ON': 100,
    'MOTOR OFF': 200
}

sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time=2000)
sensor.set_auto_gain(False)
sensor.set_auto_whitebal(False)

# loop from -10 to 10
red_led = LED(1)
i = 0
red_led.on()
print("hi")
lpf2 = LPF2(3, 'P4', 'P5')  # OpenMV
lpf2.initialize()
print("initialized")

while True:
    if not lpf2.connected:
        red_led.on()
        utime.sleep(1)
        lpf2.initialize()
    else:
        red_led.off()

        while lpf2.connected:
            #i = 0
trigger = pyb.Switch()

while not trigger():
    pyb.delay(1)

while trigger():
    pass

tic = pyb.millis()  # mark time now in msec

while True:  # Main program loop
    if buffer_full:  # semaphore signal from ISR - set if buffer is full
        b_LED.off()
        E = energy(s_buf)  # compute moving sum of last 50 energy epochs
        sum_energy = sum_energy - e_buf[e_ptr] + E
        e_buf[e_ptr] = E  # over-write earlest energy with most recent
        e_ptr = (e_ptr + 1) % M  # increment e_ptr with wraparound - 0 to M-1
        c = E * M / sum_energy  # Compute ratio of instantaneous energy/average energy

        if (pyb.millis() - tic > 500):  # if more than 500ms since last beat
            if (c > BEAT_THRESHOLD):  # look for a beat
                tic = pyb.millis()  # reset tic
                b_LED.on()  # beat found, flash blue LED
                readmove(moves, current_move, 25)
        if current_move == 9:
            current_move = 0
        else:
            current_move += 1

        buffer_full = False  # reset status flag
Example #30
0
'''
import time

time.sleep(1)  # sleep for 1 second
time.sleep_ms(500)
time.sleep_us(10)
start = time.ticks_ms()
delta = time.ticks_diff(time.ticks_ms() - start)
''' 
1.3 LED 
'''
from pyb import LED

led = LED(1)
led.toggle()
led.on()
led.of()
'''
1.4 Pins and GPIO
'''
from pyb import Pin

p_out = Pin('X1', Pin.OUT_PP)
p_out.high()
p_out.low()

p_in = Pin('X1', Pin.IN, Pin.PULL_UP)
p_in.value()  # get value, 0 or 1
'''
1.5 Servo control
'''
Example #31
0
from pyb import Pin, Timer, LED
from oled_938 import OLED_938
from struct import unpack

# Constants
BLANK_LINE = "                   "

# Initialise OLED display
try:
    oled_port = pyb.I2C('Y', pyb.I2C.MASTER)
    if (not oled_port.scan()):
        oled = None
    else:
        oled = OLED_938(pinout={
            'sda': 'Y10',
            'scl': 'Y9',
            'res': 'Y8'
        },
                        height=64,
                        external_vcc=False,
                        i2c_devid=61)
        oled.poweron()
        oled.init_display()
        oled.draw_text(0, 0, "-- User's Program --")
        oled.draw_text(0, 40, "--  Edit user.py  --")
        oled.display()
        b_LED = LED(4)
        b_LED.on()
except ValueError:
    pass
Example #32
0
File: tph.py Project: xwct/upython

for i in range(3, 0, -1):
    GLED.toggle()
    time.sleep(1)
    print(i)

highLowValues = [[-100, 100], [300, 1100], [0, 100]
                 ]  #[high, low], init to values guaranteed to be lower/higher
_ = sensor_read()  # scrap first reading
values = sensor_read()
measurementTimer = time.ticks_ms()  # initial timer value
lcdTimeOut = measurementTimer
lcdOn = False
lcd_init(DISP)
GLED.on()
with open('tph', 'a') as f:  #write header
    f.write("#temperature, pressure, humidity\n")
    #print("header written")

while True:

    if (measurementTimer + MEASURE_DELAY) < time.ticks_ms():
        values = sensor_read()
        write_to_file(values)
        measurementTimer = time.ticks_ms()
        for i in range(3):
            highLowValues[i] = test_high_low(values[i], highLowValues[i])

        print(values)
            # compute moving sum of last 50 energy epochs
            sum_energy = sum_energy - e_buf[e_ptr] + E
            e_buf[e_ptr] = E  # over-write earlest energy with most recent
            e_ptr = (e_ptr +
                     1) % M  # increment e_ptr with wraparound - 0 to M-1

            # Compute ratio of instantaneous energy/average energy
            c = E * M / sum_energy

            if (pyb.millis() - tic_detect >
                    500):  # if more than 500ms since last beat
                print(c)
                if (c > BEAT_THRESHOLD):  # look for a beat
                    print('I made it')
                    tic_detect = pyb.millis()
                    b_LED.on()  # reset tic
                    move = readmove(moves, current_move, 25,
                                    False)  # beat found, flash blue LED
                    current_move += 1
                    if current_move == 8:
                        current_move = 0

                elif (pyb.millis() - tic_detect > 2000):
                    tic_detect = pyb.millis()  # reset tic
                    move = readmove(moves, current_move, 25,
                                    False)  # beat found, flash blue LED
                    current_move += 1
                    if current_move == 8:
                        current_move = 0

            micro.set_buffer_empty  # reset status flag