Example #1
0
async def _comain(mc):

    print("Press user switch to start.")
    userSwitch = Switch()
    while not userSwitch.value():
        await sleep_ms(200)

    print("Starting")
    await sleep_ms(1000)

    try:
        print("Go!")
        mc.goForwards()
        await sleep_ms(5000)
        mc.stop()
        await sleep_ms(1000)
        mc.goBackwards()
        await sleep_ms(5000)
        mc.stop()
        await sleep_ms(1000)
        mc.turnRight()
        await sleep_ms(2000)
        mc.stop()
        await sleep_ms(1000)
        mc.turnLeft()
        await sleep_ms(2000)

    finally:
        print("Stopping")
        mc.stop()
Example #2
0
def tmp_wfi():
    sw = Switch()
    sw.callback(f)
    global i
    while True:
        if (i == 1):
            read_tmp()
            i = 0
        else:
            pyb.wfi()
async def serve(esp):

    esp.initServer(EchoConnection)
    #esp.initServer(LedToggleConnection)
    print("Waiting for connections...")

    sw = Switch()
    while not sw.value():
        await ua_sleep_ms(200)

    esp.stopServer()
    print("Server stopped.")
Example #4
0
async def mainTask(mc, count):

    print("Press user switch to start.")
    userSwitch = Switch()
    while not userSwitch.value():
        await sleep_ms(200)

    print("Starting")
    await sleep_ms(1000)

    await mc.goForwardsTo(count)
    await sleep_ms(1000)
    await mc.goBackwardsTo(count)
Example #5
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)
Example #6
0
async def mainTask(motion):
    
    print("Press user switch to start.")
    userSwitch = Switch()
    while not userSwitch.value():
        await sleep_ms(200)
    
    print("Starting")
    await sleep_ms(1000)
    
    print("turning counter clockwise")
    await motion.turn(radians(-30))
    await sleep_ms(1000)
    print("turning clockwise")
    await motion.turn(radians(60))
    print("finished")
Example #7
0
def tmp_loop(num):
    sw = Switch()
    state = sw()
    while not state:
        print_tmp()
        delay(num)
        state = sw()
Example #8
0
def main():
    micropython.alloc_emergency_exception_buf(100)
    print('simp here')
    beam = LaserBeam('X1', 'X11')
    deck = CL1('X17', 'X18', 'X19', 'X20', 'X21', 'X22')
    piano = Piano(beam)
    lights = Lights(beam, deck)
    pushbutton = Switch()
    verbose = False

    def show():
        lights.update()
        if not verbose:
            return
        print('{}: laser {}'.format(ticks_ms(), beam.interrupted()), end=' ')
        sleep(0.1)
        print('deck %s' % deck.status(), end=' ')
        if piano.playing():
            print('Piano being played', end='')
        print()

    sleep(1)  # stabilize
    while True:
        show()
        if piano.playing() and not deck.recording():
            deck.record()
            print("record")
            while piano.playing():
                show()
            deck.stop()
            print("stop")
def set_point_tune():
    global set_point
    trigger = Switch()
    oled.clear()
    while not trigger():
        time.sleep(0.001)
        set_point = 0.5 + ((pot.read() / 4095)) * 2
        oled.draw_text(0, 10, "set point: {}".format(set_point))
        oled.display()
    oled.clear()
Example #10
0
def tilt_tune():
    global tilt
    trigger = Switch()
    oled.clear()
    while not trigger():
        time.sleep(0.001)
        tilt = 0 + ((pot.read() / 4095)) * 2
        oled.draw_text(0, 10, "Tilt: {}".format(tilt))
        oled.display()
    oled.clear()
def main():
    switch = Switch()

    while not switch():
        delay(200)

    # Initialize UART for MIDI
    uart = UART(2, baudrate=31250)
    midi = MidiOut(uart)
    seq = Sequencer(midi, bpm=124)
    seq.play(Pattern(PATTERN), kit=9)
Example #12
0
    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)
Example #13
0
async def mainTask(mc):

    print("Press user switch to start.")
    userSwitch = Switch()
    while not userSwitch.value():
        await sleep_ms(200)

    print("Starting")
    await sleep_ms(1000)

    await mc.turnTo(radians(30))
    await sleep_ms(1000)
    await mc.turnTo(0)
    await sleep_ms(1000)
    await mc.turnTo(radians(330))
    await sleep_ms(1000)
    await mc.turnTo(0)
    await sleep_ms(1000)
    await mc.turn(radians(15))
    await sleep_ms(1000)
    await mc.turn(radians(15))
    await sleep_ms(1000)
    await mc.turn(radians(-30))
Example #14
0
def tmp_loop_avg(num, wait):
    temps = [0] * num
    sw = Switch()
    state = sw()
    read_tmp()
    while not state:
        for i in range(num):
            temps.insert(0, read_tmp())
            temps.pop()
            delay(wait)
        tot = sum(temps)
        avg = tot / num
        print(avg, '°C average over ', num, ' readings.\n')
        delay(1000)
        state = sw()
def tune_k(tune_p=False,tune_i=False,tune_d=False,s_point=False):
	global kp
	global kd
	global ki
	global set_point
	trigger = Switch()
	oled.clear()
	if tune_p:
		while not trigger():
			kp = 0 + (pot.read() * 20 /4095)
			oled.draw_text(0,10,"kp: {}" .format(kp))
			oled.display()
		while trigger():
		        pass

	if tune_i:
		while not trigger():
			ki = 0 + (pot.read() * 0.5 /4095)
			oled.draw_text(0,10,"ki: {}" .format(ki))
			oled.display()

	while trigger():
	        pass
	if tune_d:
	    while not trigger():
	        kd = -1 + (pot.read() * 2 /4095)
	        oled.draw_text(0,10,"Kd: {}" .format(kd))
	        oled.display()

	    while trigger():
	        pass

	if s_point:

	    while not trigger():
	        set_point = -0.5 + (pot.read() * 2 /4095)
	        oled.draw_text(0,10,"set point: {}" .format(set_point))
	        oled.display()

	oled.clear()
	oled.draw_text(0,10,"Kp: {}" .format(kp))
	oled.draw_text(0,20,"Ki: {}" .format(ki))
	oled.draw_text(0,30,"Kd: {}" .format(kd))
	oled.draw_text(0,40,"set point: {}" .format(set_point))
	oled.display()
	time.sleep(1)
	oled.clear()
Example #16
0
    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())
Example #17
0
    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()
Example #18
0
'''
实验名称:按键
版本:v1.0
日期:2020.12
作者:01Studio
'''

from pyb import LED, Switch


def fun1():
    LED(4).toggle()


sw = Switch()  #定义按键对象名字为sw
sw.callback(fun1)  #当按键被按下时,执行函数fun1(),即LED(4)状态反转
# pbaudio_syn.py VS1053b driver demo/test for Pyboard

# (C) Peter Hinch 2020
# Released under the MIT licence

from vs1053_syn import *
from machine import SPI, Pin
from pyb import Switch  # For cancellation
import time
import os
switch = Switch()

# 128K conversion
# ffmpeg -i yellow.flac -acodec libmp3lame -ab 128k yellow.mp3
# VBR conversion
# ffmpeg -i yellow.flac -acodec libmp3lame -qscale:a 0 yellow.mp3
# Yeah, I know. I like Coldplay...

spi = SPI(2)  # 2 MOSI Y8 MISO Y7 SCK Y6
reset = Pin('Y5', Pin.OUT, value=1)  # Active low hardware reset
xcs = Pin('Y4', Pin.OUT, value=1)  # Labelled CS on PCB, xcs on chip datasheet
sdcs = Pin('Y3', Pin.OUT, value=1)  # SD card CS
xdcs = Pin('Y2', Pin.OUT, value=1)  # Data chip select xdcs in datasheet
dreq = Pin('Y1', Pin.IN)  # Active high data request
player = VS1053(spi,
                reset,
                dreq,
                xdcs,
                xcs,
                sdcs=sdcs,
                mp='/fc',
Example #20
0
from pyb import Switch

sw = Switch()
print(sw())
sw.callback(print)
sw.callback(None)
Example #21
0
from micropyGPS import MicropyGPS

try:
    from cal import *
except:
    MPUCalibrat = False
else:
    MPUCalibrat = True

#from micropyGPS import MicropyGPS
global offsetMag, scaleMag, sw, my_gps, logname, etapactual
logname = "0000/00/00_00:00"
i2c_gy91 = I2C(sda=pin.PB7, scl=pin.PB6)
uart_gps = UART(2, baudrate=9600, bits=8, parity=None, stop=1)
my_gps = MicropyGPS()
sw = Switch()
SF_DEG_S = 1

Pin('PB3', Pin.OUT_PP, Pin.PULL_NONE)


class color:
    GREEN = '\033[92m'
    ORG = '\033[33m'
    RED = '\033[91m'
    FLICK = '\033[5m'
    BOLD = '\033[1m'
    END = '\033[0m'


class msg:
Example #22
0
from pyb import Switch

sw = Switch()
print(sw())
sw.callback(print)
sw.callback(None)
Example #23
0
'''
实验名称:按键
版本:v2.0
日期:2020.12
作者:01Studio
'''

from pyb import LED, Switch

sw = Switch()  #定义按键对象名字为sw
sw.callback(lambda: LED(4).toggle())  #当按键被按下时,LED(4)状态反转
Example #24
0
micropython.alloc_emergency_exception_buf(100)

# List of pin to test
PINS = [
    PIN_A5, PIN_0, PIN_1, PIN_2, PIN_3, PIN_4, PIN_5, PIN_6, PIN_8, PIN_9,
    PIN_10, PIN_11, PIN_12, PIN_13, "Y10", "Y9"
]

PIN_NAMES = [
    "A5", "0", "1", "2", "3", "4", "5", "6", "8", "9", "10", "11", "12", "13",
    "Y10-SDA", "Y9-SCL"
]

__idx = -1

sw = Switch()


def setup_next_pin():
    global sw
    sw.callback(None)
    global __idx
    if __idx + 1 >= len(PINS):
        __idx = 0
    else:
        __idx += 1
    sleep(0.5)
    sw.callback(setup_next_pin)


sw.callback(setup_next_pin)
Example #25
0
Fiche produit:
---> https://shop.mchobby.be/fr/micropython/1830-pybstick-lite-26-micropython-et-arduino-3232100018303-garatronic.html

------------------------------------------------------------------------

History:
  19 june 2020 - Pierson F. - initial code
"""
import pyb
from pyb import LED, Switch
import time

orange = LED(3)
bleu = LED(4)
sw = Switch()

# pyb.freq(48000000)

# boucle d'affichage
while (1):
    for i in range(0, 255):
        while sw.value() == True:
            time.sleep_ms(1000)
        orange.intensity(i)
        bleu.intensity(255 - i)
        time.sleep_ms(5)
    for i in range(0, 255):
        while sw.value() == True:
            time.sleep_ms(1000)
        orange.intensity(255 - i)
Example #26
0
from pyb import Switch, Pin

led = Pin('LED_BLUE', Pin.OUT_PP)
btn = Switch()


def cb():
    state = btn.value()
    led.value(not led.value())
    print('ON' if led.value() else 'OFF')


btn.callback(cb)
led.on()
Example #27
0
#														SETUP												#
#############################################################################################################
uart = UART(4, 9600)  #UART for ESP communication
uart.init(9600, bits=8, parity=None, stop=1, read_buf_len=64)
dacA.write(init_dacA)
dacB.write(init_dacB)
motor_relay_L.high()
motor_relay_R.high()
motor1_switch.high()
motor2_switch.high()
motor_L_brake.high()
motor_R_brake.high()

setSpeedR(0)
setSpeedL(0)
Switch().callback(lambda: forward(2000))
tim.callback(speedCorrection)
ExtInt('Y1', ExtInt.IRQ_RISING_FALLING, Pin.PULL_NONE,
       cfreq_R)  #hall sensors as inperrupts
ExtInt('Y2', ExtInt.IRQ_RISING_FALLING, Pin.PULL_NONE, cfreq_L)
ExtInt(Pin('Y3'), ExtInt.IRQ_RISING, Pin.PULL_DOWN,
       brake_intr)  # external intrupt to have sudden brake
pyb.Timer(4, freq=33.33).callback(isr_speed_timer)

#############################################################################################################
#														LOOP												#
#############################################################################################################
while True:
    if (brake_status and status):
        motor1_switch.high()
        motor2_switch.high()
Example #28
0
	except ZeroDivisionError:
		print("Right error input")
	#print("Frequency Right =",freq_R)
	pyb.LED(2).toggle()

def stop():
	global motor_L_brake, motor_R_brake, tim, freq_L, freq_R
	tim.callback(None)
	motor_L_brake.low()
	motor_R_brake.low()
	pidL.setPoint(0)
	pidR.setPoint(0)
	freq_L = 0
	freq_R = 0

sw = Switch()
#sw.callback(lambda: print("Frequency L =",freq_L,"rpm and Frequency R =",freq_R,"rpm"))
sw.callback(lambda: forward(2000))
tim.callback(speedCorrection)
#tim1.callback(freq)

#forward(4000)

#hall sensors as inperrupts
hall_R = ExtInt('Y1',ExtInt.IRQ_RISING_FALLING,Pin.PULL_NONE,cfreq_R)
hall_L = ExtInt('Y2',ExtInt.IRQ_RISING_FALLING,Pin.PULL_NONE,cfreq_L)	

tim = pyb.Timer(10,freq=10)
#f.write("A AND B VARYING SPEED")
#f.write("Speed-A"+"\t"+"DAC-A"+"\t"+"Speed-B"+"\t"+"DAC-B"+"\n")
# push the USR button on the pyboard to flash the LEDs!
# try using the reset button on the pyboard to quit this script!

from time import sleep_ms
from pyb import LED, Switch

last = i =1

print("Demo start ... Press button")

while True:
    if Switch().value():        # USR button pressed ?
        LED(i).on()
        last=i
        i=i%4 +1                # choose next internal led # 1-4
        print("Switch pressed...",i)
    else:
        LED(last).off()
    
    sleep_ms(50)                # sleep for while

Example #30
0
Autores: Eduardo Destefani & Roberto Colistete Jr.
'''
from pyb import Switch
from ulab import numerical
from time import sleep
import mlx90615 as mlx

MIN_TEMP_ACCEPT = 3400  # (34.00 C)
MAX_TEMP_ACCEPT = 4200  # (42.00 C)
TIME_MS_BETWEEN_TEMP_MEASUREMENTS = 0.5  # 500 ms = 0.500 s
NUM_TEMP_MEASURE = 8
TIME_MS_AFTER_TEMP_MEASUREMENTS = 7  # 7000 ms = 7.000 s
# start's software

flag_exit = False
sw = Switch()
sw.value()  # returns True or False

while True:
    print('\nEsperando proximidade ...', end='')
    while (not flag_exit):
        if sw.value(
        ) == True:  # estímulo que indica a presença de uma pessoa/objeto perto do protótipo
            pyb.LED(2).on()
            print('\nOi, eu sou o uPyBodyTempIR-PYBD_v0.4\n')
            print('Fique a 3cm da tela.')
            sleep(2)
            print('Fique Parado!\n')
            break
        else:
            pyb.LED(2).off()
Example #31
0
#构建语音模块对象
wm = audio.WM8978()

record_flag = 0  #录音标志位


######################
# 开始录音 USR按键
######################
def rec_begin():
    global record_flag
    record_flag = 1


sw = Switch()
sw.callback(rec_begin)

######################
# 停止录音 A0按键
######################
KEY_A = Pin('A0', Pin.IN, Pin.PULL_UP)  #构建按键A0


def rec_stop(KEY_A):
    global record_flag
    #消除按键抖动
    if KEY_A.value() == 0:
        time.sleep_ms(5)
        if KEY_A.value() == 0:
Example #32
0
#feedback-waiting for user to press button
orange = LED(3)
orange.on()


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


def start():
	hc12.write('1')
	orange.off()

#create switch object
big_red_button = Switch()
big_red_button.callback(start)

finished = False
 

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

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