Esempio n. 1
0
async def led_fade_to(color, target_pct, step_delay=4):
    """
    Fades the LED diode of the center button to a certain value of intensity
    in steps with a sleep in between each step.

    :param int target_value: Target intensity (0 = off, 65535 = max bright)
    :param int step_size: Increment/decrement in steps of this size
    """
    start_color = hub.led()
    start_pct = get_color_percentage(start_color, color)

    if start_pct < target_pct:
        step_size = 1
    elif start_pct > target_pct:
        step_size = -1
    else:
        return

    for pct in range(start_pct, target_pct, step_size):
        hub.led(*color_percentage(color, pct))

        try:
            await sleep_ms(step_delay)
        except AttributeError:
            # uasyncio bug resulting in AttributeError when cancelled
            return
Esempio n. 2
0
def bootup_animation():
    for pct in range(100, 0, -10):
        hub.led(
            int(0 * (pct / 100)),
            int(0 * (pct / 100)),
            int(80 * (pct / 100)),
        )
        utime.sleep_ms(30)

    hub.led(0, 0, 0)

    # Phase 1
    hub.sound.play(Sounds.STARTUP, 16000)
    hub.display.show(frame1, fade=2, delay=25)
    hub.display.show(frame2, fade=2, delay=82)
    utime.sleep_ms(160)
    hub.display.show(frame3, fade=2, delay=15)
    hub.display.show(frame4, fade=2, delay=64)
    utime.sleep_ms(140)
    hub.display.show(frame5, fade=2, delay=9)
    hub.display.show(frame6, fade=2, delay=49)
    utime.sleep_ms(110)
    hub.display.show(frame7, fade=2, delay=6)
    hub.display.show(frame8, fade=2, delay=52)
    hub.display.show(frame9, fade=2, delay=4)
    hub.display.show(frame10, fade=2, delay=45)
    hub.display.show(frame11, fade=2, delay=41)

    # Phase 2
    utime.sleep_ms(80)
    hub.display.show(frame12, fade=2, delay=37)
    hub.display.show(frame13, fade=2, delay=34)
    hub.display.show(frame14, fade=2, delay=31)
    hub.display.show(frame15, fade=2, delay=29)
    hub.display.show(frame16, fade=2, delay=27)
    utime.sleep_ms(60)
    hub.display.show(frame17, fade=2, delay=25)
    hub.display.show(frame18, fade=2, delay=23)
    hub.display.show(frame19, fade=2, delay=21)
    hub.display.show(frame20, fade=2, delay=19)
    hub.display.show(frame21, fade=2, delay=17)
    hub.display.show(frame22, fade=2, delay=15)
    utime.sleep_ms(60)
    hub.display.show(frame23, fade=2, delay=14)
    hub.display.show(frame24, fade=2, delay=13)
    hub.display.show(frame25, fade=2, delay=12)
    hub.display.show(frame26, fade=2, delay=11)
    hub.display.show(frame27, fade=2, delay=10)
    utime.sleep_ms(50)
    hub.display.show(frame28, fade=2, delay=9)
    hub.display.show(frame29, fade=2, delay=8)
    hub.display.show(frame30, fade=2, delay=8)
    utime.sleep_ms(20)
    hub.display.show(frame31, fade=2, delay=200)
    utime.sleep_ms(15)
    if (hub.info()['product_variant'] == 1):
        hub.display.show(hub.Image.GO_RIGHT, fade=2, wait=True, delay=500)
    else:
        hub.display.show(hub.Image.HEART, fade=2, wait=True, delay=500)
async def on_start(vm, stack):
    for i in range(11):
        # Set LED color
        hub.led(i)
        # log values to console
        printsp(str(i))
        # Sleep 1 second
        yield 1000
    endprogram()  # end program
Esempio n. 4
0
 def on_program_loop_cancelled(self):
     """
     Invoked when the program loop is cancelled.
     Resets callbacks, display and leds.
     """
     hub.button.right.on_change(None)
     hub.button.left.on_change(None)
     hub.button.center.on_change(None)
     hub.button.connect.on_change(None)
     hub.display.clear()
     hub.led(*(PURPLE))
Esempio n. 5
0
def heart():
    print("heart")
    hub.led
    for i in range(5):
        hub.led(i)
        utime.sleep(1)
        hub.display.show([
            hub.Image("09090:99999:99999:09990:00900"),
            hub.Image("01010:11111:11111:01110:00100")
        ],
                         fade=2,
                         loop=1,
                         delay=500)
    hub.display.show("")
Esempio n. 6
0
    def request_child(self, child, message, wait_for_response=True):
        children = [child]
        if not self.is_connected():
            return

        for i in range(len(children)):
            data = {
                '_t': self._network[children[i]],
                '_f': self._name,
                '_m': message
            }
            if self._debug:
                print('send to: ', children[i])
            conn_handle = None
            if children[i] in self._children:
                conn_handle = self._conn_handle[self._chld_idx[children[i]]]
            else:
                for idx in range(len(self._children)):
                    if self._network[children[i]][:self._level +
                                                  1] is self._children_address[
                                                      idx][:self._level + 1]:
                        if self._debug:
                            print('send via ', self._children[idx])
                        conn_handle = self._conn_handle[idx]
            if conn_handle:
                if self._debug:
                    print('wait for tx to be available')
                    led(1)
                while (not self._tx_available) and (
                        not self._response_received):
                    pass
                if self._debug:
                    led(0)
                    print('tx available')
                    print('conn_handle: ', conn_handle)
                    print('data', str(data))
                try:
                    self._ble.gattc_write(conn_handle, self._rx_handle,
                                          str(data), 1)
                    self._tx_available = False
                    if wait_for_response:
                        self._response_received = False
                except:
                    print('Send to: ' + children[i] + ' failed')
            else:
                print('message cannot be send to this hub')
Esempio n. 7
0
async def on_start(vm, stack):
  hub.led(255, 0, 0) # red  (r,g,b)
  hub.led(3) # blue   (colors 0 - 10)
  hub.led
  for i in range(11):
      hub.led(i)
      utime.sleep(1)
async def stack_1(vm, stack):
    hub.led(*number_color_to_rgb(9))
    rotate_hub_display_to_value("2")
    global g_animation
    brightness = vm.store.display_brightness()
    frames = [
        hub.Image(convert_animation_frame(frame, brightness))
        for frame in g_animation
    ]
    vm.system.display.show(frames, clear=False, delay=200, loop=True, fade=2)
    vm.system.sound.play("/extra_files/Scanning",
                         freq=pitch_to_freq(vm.store.sound_pitch(), 12000,
                                            16000, 20000))
    (acceleration, deceleration) = vm.store.motor_acceleration("D")
    vm.store.motor_last_status(
        "D", await vm.system.motors.on_port("D").run_for_degrees_async(
            500,
            vm.store.motor_speed("D"),
            stall=vm.store.motor_stall("D"),
            stop=vm.store.motor_stop("D"),
            acceleration=acceleration,
            deceleration=deceleration))
    (acceleration_1, deceleration_1) = vm.store.motor_acceleration("D")
    vm.store.motor_last_status(
        "D", await vm.system.motors.on_port("D").run_for_degrees_async(
            1000,
            -vm.store.motor_speed("D"),
            stall=vm.store.motor_stall("D"),
            stop=vm.store.motor_stop("D"),
            acceleration=acceleration_1,
            deceleration=deceleration_1))
    (acceleration_2, deceleration_2) = vm.store.motor_acceleration("D")
    vm.store.motor_last_status(
        "D", await vm.system.motors.on_port("D").run_for_degrees_async(
            500,
            vm.store.motor_speed("D"),
            stall=vm.store.motor_stall("D"),
            stop=vm.store.motor_stop("D"),
            acceleration=acceleration_2,
            deceleration=deceleration_2))
Esempio n. 9
0
async def stack_1(vm, stack):
    hub.led(*number_color_to_rgb(9))
    rotate_hub_display_to_value("2")
    global g_animation
    brightness = vm.store.display_brightness()
    frames = [hub.Image(convert_animation_frame(frame, brightness)) for frame in g_animation]
    vm.system.display.show(frames, clear=False, delay=200, loop=True, fade=2)
    await bigBotCalibrate(vm)
    (acceleration, deceleration) = vm.store.motor_acceleration("D")
    vm.store.motor_last_status("D", await vm.system.motors.on_port("D").run_for_degrees_async(648, vm.store.motor_speed("D"), stall=vm.store.motor_stall("D"), stop=vm.store.motor_stop("D"), acceleration=acceleration, deceleration=deceleration))
    port = getattr(hub.port, "F", None)
    if getattr(port, "device", None) and is_type("F", 62):
        port.device.mode(5, bytes("".join([chr(percent_to_int(round(clamp(to_number(p), 0, 100)), 87)) for p in "100 100 100 100".split()]), "utf-8"))
    while True:
        sensor_value = get_sensor_value("F", 0, 200, (62,))
        if sensor_value is None:
            sensor_value = 200
        if sensor_value < 10:
            break
        yield 0
    await vm.system.sound.play_async("/extra_files/Target Acquired", freq=pitch_to_freq(vm.store.sound_pitch(), 12000, 16000, 20000))
    (acceleration_1, deceleration_1) = vm.store.motor_acceleration("D")
    vm.store.motor_last_status("D", await vm.system.motors.on_port("D").run_for_degrees_async(648, -vm.store.motor_speed("D"), stall=vm.store.motor_stall("D"), stop=vm.store.motor_stop("D"), acceleration=acceleration_1, deceleration=deceleration_1))
Esempio n. 10
0
        def on_rx(v):
            try:
                data = eval(v)
            except:
                print(
                    'A received message is probably to long, this data was collected:'
                    + v)
                print('Try to reduce the message length')

            data.setdefault('_t', [])
            data.setdefault('_m', {})

            if data['_t'] is self._address:
                respond_message = callback(data['_m'])
                if self._debug:
                    print('respond message', respond_message)
                if respond_message:
                    self.respond_to_client(respond_message)
            else:
                idx_addressed_child = [
                    idx for idx in range(len(self._children))
                    if data['_t'][:self._level + 1] is
                    self._children_address[idx][:self._level + 1]
                ]
                addressed_child_idx = []
                for idx in range(len(self._children)):
                    if self._children_address[idx][:self._level + 1] == data[
                            '_t'][:self._level + 1]:
                        addressed_child_idx.append(idx)

                if len(addressed_child_idx) > 0:
                    for idx in addressed_child_idx:
                        if self._debug:
                            print('route message to: ' + self._children[idx])
                        if self._conn_handle[idx]:
                            if self._debug:
                                print('wait for tx to be available')
                                led(1)
                            while (not self._tx_available) and (
                                    not self._response_received):
                                pass
                            if self._debug:
                                print('tx available')
                                led(0)
                            self._ble.gattc_write(self._conn_handle[idx],
                                                  self._rx_handle, str(data),
                                                  1)
                            self._response_received = False
                            self._tx_available = False
                        else:
                            respond_message = {
                                '_err':
                                'address: ' + data['_t'] + 'not connected'
                            }
                            self.respond_to_client(respond_message)
                            if self._debug:
                                print(respond_message)
                                print(
                                    'request received for child that is not connected'
                                )
                else:
                    respond_message = {
                        '_err': 'address: ' + data['_t'] + 'cannot be reached'
                    }
                    self.respond_to_client(respond_message)
                    if self._debug:
                        print(respond_message)
                        print(
                            'request received for child that cannot be reached from this hub'
                        )
Esempio n. 11
0
'''
The user RGB LED capabilities of the hub is a pair of RGB LEDs on 
      either side of the center button.
'''
import hub, utime

hub.led(255, 0, 0)  # red  (r,g,b)

hub.led(3)  # blue   (colors 0 - 10)

hub.led

for i in range(11):
    hub.led(i)
    utime.sleep(1)
# %%
import hub

# %%
print("-" * 15 + " Execution started " + "-" * 15 + "\n")

# %% [markdown]
# # Using `hub`
# Notice we won't be using the standard `MSHub`, but rather the "raw" `hub`.
# It is a little lower level, but it allows us making more things - like turning on the hub's pixels.
# Fore more information, see [Maarten Pennings brilliant explanation and unofficial documentation about it](https://github.com/maarten-pennings/Lego-Mindstorms/blob/main/ms4/faq.md#why-are-there-so-many-ways-to-do--in-python).

# %%
# Turn the central light off
hub.led(0, 0, 0)

# Alternatively, use
# hub.status_light.on('black')

# %% [markdown]
# # How to display an image
# Displaying an image is quite simple. We just need to define which pixels we will turn on and at what intensity.
# The pixel definition is done in a string in the shape
#
# `00000:00000:00000:00000:00000`
#
# where each number corresponds to a pixel. Each pixel can have a value between `0` (off) to `9` (on at full intensity).
# Each group of numbers (from left to right) correspond to a row of the hub (from top to bottom).
# Notice the groups (i.e., rows) are separated by a colon `:`.
#
Esempio n. 13
0
from hub import led
from utime import sleep

# Save current LED colour.
current_colour = led()

# The LEDs can be set to one of the built in colours:
# 0  = black/off
# 1  = pink
# 2  = purple
# 3  = blue
# 4  = cyan
# 5  = turquoise
# 6  = green
# 7  = yellow
# 8  = orange
# 9  = red
# 10 = grey
# 11 = white
for colour_code in range(11):
    led(colour_code)
    print(led())
    sleep(0.5)


# Colour conversion function to convert HSV to RGB.
def hsv_to_rgb(hue, saturation, value):
    if saturation == 0.0:
        return (value, value, value)
    hue_segment = int(hue * 6.0)
    hue_offset = (hue * 6.0) - hue_segment
async def on_start(vm, stack):
    for i in range(11):
        # Set LED color
        hub.led(i)
        # Sleep 1 second
        yield 1000