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)
예제 #2
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()
예제 #3
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
예제 #4
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)
예제 #5
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()
예제 #6
0
    class FlashingRed(State):  # Special fault state that should never exit.
        def __init__(self):
            super().__init__(ident='error')
            self.timer = Timer(timer0 + 4)
            self.led = LED(1)

            # noinspection PyUnusedLocal
            def toggle_with_arg(
                not_used
            ):  # Toggle func that accepts an arg, because ``schedule`` *needs* an arg.
                self.led.toggle()

            self.led_tog_ref = toggle_with_arg  # Store the function reference locally to avoid allocation in interrupt.

        def __enter__(self):
            self.timer.init(
                freq=2, callback=lambda _: schedule(self.led_tog_ref, None))
            return self

        def __exit__(self, exc_type, exc_val, exc_tb):
            self.led.off()
            self.timer.deinit()
예제 #7
0
                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
                        blue_led.on()
                        time.sleep(1000)
예제 #8
0
            tic1 = pyb.micros()

            u = pidc.get_pwm(pitch, pitch_dot)

            if u > 0:
                motor.A_forward( (abs(u)+motor_offset) * mWeight.report('A') )
                motor.B_forward( (abs(u)+motor_offset) * mWeight.report('B') )
            elif u < 0:
                motor.A_back( (abs(u)+motor_offset) * mWeight.report('A') )
                motor.B_back( (abs(u)+motor_offset) * mWeight.report('B') )
            #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
예제 #9
0
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()
        vihrea = False
예제 #10
0
        return "DATABAR_EXP"
    if (code.type() == image.CODABAR):
        return "CODABAR"
    if (code.type() == image.CODE39):
        return "CODE39"
    if (code.type() == image.PDF417):
        return "PDF417"
    if (code.type() == image.CODE93):
        return "CODE93"
    if (code.type() == image.CODE128):
        return "CODE128"


while (True):
    clock.tick()
    blue_led.on()
    img = sensor.snapshot()
    codes = img.find_barcodes()
    for code in codes:
        img.draw_rectangle(code.rect())
        if (temp != code.payload()):
            temp = code.payload()
            result = code.payload()
            green_led.on()
            time.sleep(100)
            green_led.off()
            usb.send(result + '\r\n')
            time.sleep(1000)
    if not codes:
        pass
예제 #11
0
If there is one point, it will report that point
If there are two points, it will report midpoint between the two points
If there are 3 points, it will report midpoint between two most distant points (ignoring the flash from the flow deck)

'''

import sensor, image, pyb, os, time
from pyb import USB_VCP

from pyb import LED

red_led = LED(1)
green_led = LED(2)
blue_led = LED(3)
ir_led = LED(4)
red_led.off()
green_led.off()
blue_led.off()
ir_led.off()


def raise_error():
    print('{901$901}')
    red_led.on()
    blue_led.off()
    green_led.off()


def pad_with_0(string_to_pad, target_length):
    while len(string_to_pad) < target_length:
        string_to_pad = '0' + string_to_pad
예제 #12
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)
예제 #13
0
			mode = 1
			print('mode 1')

		elif command[2] == ord('2'):
			mode = 2
			print('mode 2')

		elif command[2] == ord('3'): #shootout
			mode = 3
			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()
예제 #14
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 
예제 #15
0
 elif (command == 'T'):
     g.put_triangle()
     done()
 elif (command == 'G'):
     sample = g.get()
     write_one(sample)
 elif (command == 'U'):
     sample = g.get_mean(value)
     m = "Sample: %4.2fV" % (sample * 3.3 / 4096)
     g.write_message(m)
     write_one(sample)
 elif (command == 'M'):
     y_LED.on()
     s_buf = g.get_block(value)
     write_block(s_buf)
     y_LED.off()
     gc.collect()
 elif (command == 'J'):
     y_LED.on()
     s_buf = g.get_mic(value)
     write_block(s_buf)
     y_LED.off()
     gc.collect()
 elif (command == 'I'):
     y_LED.on()
     [accel, gyro] = g.get_imu()
     u.send(accel)
     u.send(gyro)
     y_LED.off()
 elif (command == 'K'):
     y_LED.on()
예제 #16
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' )
예제 #17
0
파일: main.py 프로젝트: tfhulbert/FG-B-2018
class LEDController:
    def __init__(self):
        self.LED_GREEN = 2
        self.LED_RED = 1
        self.LED_IR = 4
        self.LED_BLUE = 3

        self.ledRed = LED(self.LED_RED)
        self.ledGreen = LED(self.LED_GREEN)
        self.ledBlue = LED(self.LED_BLUE)
        self.ledIR = LED(self.LED_IR)

        self.ledGreen.off()
        self.ledRed.off()
        self.ledIR.off()
        self.ledBlue.off()

        # blink var
        self.lastTime = 500

    def allOff(self):
        self.ledGreen.off()
        self.ledRed.off()
        self.ledIR.off()
        self.ledBlue.off()

    def on(self, led):
        if (led == self.LED_RED):
            self.ledRed.on()
        elif (led == self.LED_GREEN):
            self.ledGreen.on()
        elif (led == self.LED_IR):
            self.ledIR.on()
        elif (led == self.LED_BLUE):
            self.ledBlue.on()

    def off(self, led):
        if (led == self.LED_RED):
            self.ledRed.off()
        elif (led == self.LED_GREEN):
            self.ledGreen.off()
        elif (led == self.LED_IR):
            self.ledIR.off()
        elif (led == self.LED_BLUE):
            self.ledBlue.off()

    def toggle(self, led):
        if (led == self.LED_RED):
            self.ledRed.toggle()
        elif (led == self.LED_GREEN):
            self.ledGreen.toggle()
        elif (led == self.LED_IR):
            self.ledIR.toggle()
        elif (led == self.LED_BLUE):
            self.ledBlue.toggle()

    def blink(self):
        currentTime = millis()
        if currentTime > (self.lastTime):
            self.ledGreen.toggle()
            self.lastTime = currentTime + 500
예제 #18
0
#hardware platform: pyboard V1.1
from pyb import Pin
from pyb import LED
#from pyb import ExtInt
import pyb
import time
button = Pin('X1', Pin.IN)  #set Pin('X1') is input
led = LED(1)
led.off()

def mycallback(line):  #while press button,led turn on,otherwise led turn off
    if (button.value() == 0):
        led.off()
    else:
        led.on()

#every time a rising  edge is seen on the X1 pin, the callback will be called.
#produce a rising edge while button is pressed
extint = pyb.ExtInt('X1', pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_UP, mycallback)
while True:
    time.sleep(0.1)
예제 #19
0
             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
         led3.off()
         pass
예제 #20
0
                                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)

    # 判断对焦是否完成
    if keycount != 0:
예제 #21
0
class Robot(object):
    '''
    Handles the common objects, launches activities and keeps them running
    '''
    def __init__(self):
        '''
        Constructor
        '''

        self._ledMatrix = None
        self._buzzer = None
        self._sequencer = None

        #TODO: 20200917 DPM Get heartbeat led from settings
        self._heartbeatLed = LED(1)
        self._heartbeat = Heartbeat(self._heartbeatLed)
        self._testUserInterface()
        self._running = False
        self._activity = None
        self._activities = []
        self._activityIndex = 0

        self._loop = get_event_loop()

    def getLedMatrix(self):

        if self._ledMatrix == None:
            #TODO: 20200511 DPM Get I2C channel from settings
            self._ledMatrix = BiColorLedMatrix(1)
            self._ledMatrix.start()
            #TODO: 20200511 DPM Get default dim from settings
            self._ledMatrix.setDim(0x8)

        return self._ledMatrix

    def getBuzzer(self):

        if self._buzzer == None:

            #TODO: 20200526 DPM Get buzzer pin and timer-channel pair from settings
            self._buzzer = Buzzer(Pin.board.D12, 3, 1)

        return self._buzzer

    def getSequencer(self):

        if self._sequencer == None:

            self._sequencer = Sequencer(self.getBuzzer())

        return self._sequencer

    def addActivity(self, activity):
        '''
        Adds an activity to the robot
        
        @param activity: Activity
        '''

        self._activities += [activity]

    def _selectActivity(self, button):
        '''
        Selects the activity and sets the robot into the ready mode
        '''

        button.cleanup()

        self.getBuzzer().buzz(440, S)
        self.getBuzzer().buzz(440, S)

        self._activity = self._activities[self._activityIndex]
        self._activity.setDeviceProvider(self)

        Switch().callback(self._toggleActivity)

        self._heartbeat.setState(Heartbeat.States.Waiting)
        self._loop.create_task(self._heartbeat.run())

    def _rotateActivity(self, _):
        '''
        Rotates to the next available activity and shows its icon
        '''

        self.getBuzzer().buzz(220, E)
        self._activityIndex = (self._activityIndex + 1) % len(self._activities)
        self._preselectActivity()

    def _preselectActivity(self):

        if self._activityIndex < len(self._activities):
            iconRows = self._activities[self._activityIndex].getIconRows()
            self.getLedMatrix().updateDisplayFromRows(iconRows[0], iconRows[1])

    def run(self):
        '''
        Runs the execution of the activity 
        '''

        self._preselectActivity()
        #TODO: 20200515 DPM Get the Button's pin from settings.
        #PC13 is the Switch (a.k.a. user button) for the NUCLEO_F767ZI and NUCLEO_L476RG boards.
        #Please, check for other boards.
        Button(Pin.cpu.C13, lowOnPress=True).setLongPressHandler(
            self._selectActivity).setShortPressHandler(self._rotateActivity)

        self._running = True
        self._loop.run_until_complete(self._keepRunning())
        self._loop.close()

    def cleanup(self):
        '''
        Finalizes and releases the used resources 
        '''

        Switch().callback(None)
        self._heartbeatLed.off()
        if self._activity != None:

            self._activity.cleanup()

        if self._ledMatrix != None:

            self._ledMatrix.cleanup()

        #20200526 DPM Note that the sequencer's cleanup-method calls the buzzer's already
        if self._sequencer != None:

            self._sequencer.cleanup()

        elif self._buzzer != None:

            self._buzzer.cleanup()

    def _testUserInterface(self):

        ledMatrix = self.getLedMatrix()
        buzzer = self.getBuzzer()

        ledMatrix.updateDisplayFromRows(greenRows=bytes([0xff] * 8))

        buzzer.buzz(110, E - S)
        utime_sleep_ms(S)
        buzzer.buzz(110, E - S)
        utime_sleep_ms(S)
        buzzer.buzz(880, Q - S)
        utime_sleep_ms(H + S)

        ledMatrix.updateDisplayFromRows(
            [0xf0, 0xf0, 0xf0, 0xf0, 0xff, 0xff, 0xff, 0xff],
            [0xff, 0xff, 0xff, 0xff, 0x0f, 0x0f, 0x0f, 0x0f])

        buzzer.buzz(440, E)
        buzzer.buzz(220, E)
        buzzer.buzz(110, E + S)
        utime_sleep_ms(S)

        ledMatrix.updateDisplayFromRows(redRows=bytes([0xff] * 8))

        buzzer.buzz(880, E)
        buzzer.buzz(220, E)
        buzzer.buzz(440, E + S)
        utime_sleep_ms(S)

        ledMatrix.updateDisplayFromRows(bytes([0xff] * 8), bytes([0xff] * 8))

        buzzer.buzz(880, Q)
        buzzer.buzz(440, H + Q)

        ledMatrix.displayOff()
        ledMatrix.clear()

    def _runActivity(self):

        self._heartbeat.setState(Heartbeat.States.Active)
        self.getLedMatrix().displayOff()
        self.getLedMatrix().clear()
        if self._activity != None:
            self._loop.create_task(self._activity.start())

    def _stopActivity(self):

        self._heartbeat.setState(Heartbeat.States.Waiting)
        if self._activity != None:
            self._loop.create_task(self._activity.stop())

        self._running = False

    def _toggleActivity(self):

        # First at all try to debounce
        self.getBuzzer().buzz(440, E)
        if Switch().value():
            if self._activity == None or self._activity.isRunning():

                schedule(Robot._stopActivity, self)

            else:

                schedule(Robot._runActivity, self)

    async def _keepRunning(self):
        '''
        Let execute the activity until end request
        '''

        while self._running:
            await ua_sleep_ms(500)
예제 #22
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)
예제 #23
0
#找到最大色块
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())
예제 #24
0
파일: main1.py 프로젝트: zakejune/Ticup
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)
        print(x)
        print(y)
예제 #25
0
        # 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
    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)

    #数组中数据写入
    print(err_x, err_min, err_max)
예제 #27
0
    oled.draw_text(0, 10, 'PWM:{:4d}'.format(speed))
    oled.draw_text(0, 20, 'SpeedA:{:5.2f} rps'.format(motor.speedA / 39))
    oled.draw_text(0, 30, 'SpeedB:{:5.2f} rps'.format(motor.speedB / 39))

    oled.display()
    try:
        send_uart("Motor Test")
    except OSError:
        print('UART send error')


tic = pyb.millis()
while True:
    #	y_LED.off()
    g_LED.off()
    r_LED.off()
    b_LED.toggle()
    if (read_sw() == 0):
        motor.stop()
        test_mic()
    elif (read_sw() == 1):
        motor.stop()
        toc = pyb.millis()
        test_imu(toc - tic)
        tic = pyb.millis()
    elif (read_sw() == 2):
        test_motor()
    elif (read_sw() == 3):
        motor.stop()
        sine_gen()
예제 #28
0
 

#########################
#       Main Loop       #
#########################
 
while finished == False: #While loop that loops forever

	if hc12.any(): 
		data = hc12.readline()
		data = data.decode('utf-8')

		dataArray = data.split(',')   #Split it into an array called dataArray

		if dataArray[0] == 'end':
			green.off()
			sleep(0.5)
			green.on()
			sleep(0.5)
			green.off()
			finished == True
		elif len(dataArray) == 6:
			tagx = dataArray[0]
			temp = dataArray[1]
			pres = dataArray[2]
			alti = dataArray[3]
			lati = dataArray[4]
			loni = dataArray[5]

		#data to analyse later
			#print('TAGX:{}'.format(tagx))
예제 #29
0
# 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
            gc.collect()
            img = sensor.snapshot()
            img.lens_corr(1.6)
            for code in img.find_qrcodes():
                key = code.payload().upper()
                try:
                    print(key, send_nums[key])
                    i = send_nums[key]
                except KeyError:
                    pass
            print(i)
            lpf2.send_value(i)
        else:
            backward(abs(drive_signal * offset) + 5, move_left, move_right)

        tic = pyb.micros()

        if debug:
            oled.clear()
            oled.draw_text(0, 10, "Drive Signal: {}".format(drive_signal))
            oled.draw_text(0, 40, "Robot pitch: {}".format(current_pitch))

            oled.display()

        if micro.buffer_full:  # semaphore signal from ISR - set if buffer is full

            b_LED.off()
            # Calculate instantaneous energy
            E = micro.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

            if (pyb.millis() - tic_detect >
                    500):  # if more than 500ms since last beat
                print(c)
예제 #31
0
    flag = uart.readline()
    utime.sleep_ms(100)
    print(flag)

#print("done")

#set the uarm to the default position
utime.sleep_ms(500)

uart.write("G0 X250 Y0 Z")
uart.write("160 F15000\r\n")

utime.sleep_ms(8000)

#finish the initialization
led.off()

# Reset sensor
sensor.reset()

# Sensor settings
sensor.set_contrast(3)
sensor.set_gainceiling(16)
sensor.set_framesize(sensor.VGA)
sensor.set_windowing((320, 240))
sensor.set_pixformat(sensor.GRAYSCALE)

sensor.skip_frames(time=200)
sensor.set_auto_gain(False, value=100)

예제 #32
0
    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()()
        move(vaisseau.x, vaisseau.y)
        uart.write(vaisseau.skin)

    else:
        led_nx.off()
예제 #33
0
파일: tph.py 프로젝트: xwct/upython
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)

    if DISP.is_touched():
        lcdValues = sensor_read()
        #test_high_low(lcdValues, highLowValues)
        update_lcd(lcdValues, highLowValues)
        lcdTimeOut = time.ticks_ms()
        lcdOn = True
        YLED.on()
        #print("lcd update")

    if ((lcdTimeOut + 20000) < time.ticks_ms()) and lcdOn:
        DISP.set_brightness(0)
        YLED.off()
        lcdOn = False
        #print("lcd off")
예제 #34
0
#feedback-waiting for user to press button
orange = LED(3)
orange.on()

#boolean variable to manage main loop
finished = False

#########################
#       Main Loop       #
#########################


while finished == False:
	#if start command is received
	if hc12.any():
		orange.off()

		#for local use only
		for i in range(0,2):
			blue.toggle()
			sleep(0.4)
			blue.toggle()
			sleep(0.4)

		#X second loop, get data every half second and write to backup.csv, and also transmit to ground station
		for tag in range(1,61):

			green.off()
			
			temp = bmp180.temperature
			pres = bmp180.pressure