def battle_me():
    display.show(Image.YES)
    play_number = MY_NUMBER + COMP_NUMBER
    games_won = 0

    prepared_choises = [random.choice(GAME_CHOISES) for i in range(GAME_ROUNDS)]

    ctr = 1
    while True:
        radio.send("{pn} {ctr} {gc}".format(pn=str(play_number),
                                            ctr=ctr,
                                            gc=prepared_choises[ctr-1]))
        #display.scroll(str(ctr))
        sleep(100)
        received = radio.receive()
        if received and received.startswith(str(play_number)):
            #display.scroll(received)
            _, game_round, game_choice = received.split(" ")
            if int(game_round) != ctr:
                radio.send("{pn} {ctr} {gc}".format(pn=str(play_number),
                                                    ctr=game_round,
                                                    gc=prepared_choises[int(game_round) - 1]))
                continue
            if has_won(prepared_choises[int(game_round)-1], game_choice):
                games_won += 1
            ctr += 1

            if ctr >= GAME_ROUNDS:
                break

    while True:
        display.scroll(str(games_won))
        display.scroll(str(ctr))
示例#2
0
文件: spyfall.py 项目: MoMaT/slides
def start():
    for i in range(5):
        sleep(500)
        if not (button_a.is_pressed() and button_b.is_pressed()):
            return

    location = random.choice(LOCATIONS)
    radio.send(location)
    play(location)
示例#3
0
文件: memory.py 项目: MoMaT/slides
def sync():
    number = random.randrange(1, 10000)
    message = None

    while not message:
        radio.send(str(number))
        sleep(250)
        message = radio.receive()

    return number < int(message)
示例#4
0
文件: memory.py 项目: MoMaT/slides
def game_over(move):
    radio.send("gg")
    radio.off()

    images = [ICONS[move], Image(" ")]
    display.show(images, loop=True, wait=False)
    sleep(3000)

    display.show(Image.SAD)
    shutdown()
示例#5
0
def sync():
    display.show(Image.ALL_CLOCKS, delay=100, loop=True, wait=False)

    n = random.randrange(1, 10000)
    radio.send(str(n))

    message = None
    while not message:
        sleep(500)
        message = radio.receive()
    return n < int(message)
示例#6
0
文件: memory.py 项目: MoMaT/slides
def add_new_move():
    display.show("?")

    move = read_move()
    while not move:
        move = read_move()

    display.show(ICONS[move])
    radio.send(move)
    sequence.append(move)
    sleep(2000)
def send():
    plaintext = input("message? ")
    key = input("hex number for key? ")
    key = int(key, 16)

    cyphertext = cypher(plaintext, key)
    radio.on()
    for i in range(10):
        print(i, cyphertext)
        radio.send(cyphertext)
        sleep(100)
    radio.off()
示例#8
0
def position(sprite, board, send=False):
    blink(sprite, board)

    while not (button_a.is_pressed() and button_b.is_pressed()):
        sleep(100)
        # if button is pressed but not released yet, keep waiting
        if button_a.is_pressed() or button_b.is_pressed():
            continue

        a = button_a.was_pressed()
        b = button_b.was_pressed()
        if a or b:
            sprite = move(sprite, b, a)
            blink(sprite, board)
            if send:
                radio.send("{}{}".format(*sprite[0]))

    return sprite
示例#9
0
文件: spyfall.py 项目: MoMaT/slides
def play(location):
    display.show(Image.ALL_CLOCKS, delay=50, loop=True, wait=False)

    number = random.randrange(1, 10000)
    sleep(random.randrange(10, 500))
    radio.send(str(number))

    sleep(3000)

    numbers = []
    while True:
        message = radio.receive()
        if not message:
            break
        numbers.append(int(message))

    if number < min(numbers):
        location = "UNKNOWN"

    radio.off()

    display.show(Image.ARROW_E)

    seconds = 0
    start_time = running_time()
    button_b.was_pressed()

    while seconds < 8 * 60:
        if accelerometer.was_gesture("shake"):
            minutes = seconds // 60
            display.scroll("{0}:{1:02d}".format(minutes, seconds - minutes * 60))
        if button_b.was_pressed():
            display.scroll(location.upper())

        sleep(10)
        seconds = (running_time() - start_time) // 1000

    animation = [Image.SKULL, Image()]
    display.show(animation, delay=500, loop=True, wait=False)

    while True:
        sleep(10000)
        display.off()
示例#10
0
def attack(board):
    target = [(1, 1)]
    while True:
        target = position(target, board, send=True)
        if board.get_pixel(*target[0]) == 0:
            break

    radio.send("fire")
    sleep(500)

    message = radio.receive()
    if message == "gg":
        game_over(Image.HAPPY)

    value = 8 if message == "hit" else 2
    board.set_pixel(target[0][0], target[0][1], value)

    display.show(board)
    sleep(2000)
def handshake():
    global COMP_NUMBER
    while True:
        if button_a.was_pressed():
            radio.send("".join((GAME_MESSAGE, str(MY_NUMBER))))

        listening = radio.receive()
        if listening and listening.startswith(GAME_MESSAGE):
            game_str = listening[len(GAME_MESSAGE):]

            if '+' in game_str:
                my_rec_number, comp_number = game_str.split('+')[:2]
                if MY_NUMBER == int(my_rec_number) and COMP_NUMBER == int(comp_number):
                    radio.send("{gm} {gn}+{mn}".format(gm=GAME_MESSAGE, mn=MY_NUMBER, gn=COMP_NUMBER))
                    display.show(Image.HEART)
                    sleep(1000)
                    break
            elif not COMP_NUMBER:
                COMP_NUMBER = int(game_str)
                radio.send("{gm} {gn}+{mn}".format(gm=GAME_MESSAGE, mn=MY_NUMBER, gn=COMP_NUMBER))
示例#12
0
def defend(board):
    message = None
    while message != "fire":
        if message:
            x, y = (int(i) for i in message)
            blink([(x, y)], board)
        sleep(100)
        message = radio.receive()

    hit = board.get_pixel(x, y) == 8
    board.set_pixel(x, y, 2)
    display.show(board)

    if hit:
        if "8" in repr(board):
            radio.send("hit")
        else:
            radio.send("gg")
            game_over(Image.SAD)
    else:
        radio.send("miss")

    sleep(2000)
示例#13
0
def send_valid(packet):
    # Appends packet header to packet bytes object and transmits on the radio
    radio.send(packet_header + packet)
示例#14
0
def	hdr_ba() :

	radio.send( 'run')
	sleep( 200)
'''
Code for a microbit in my pocket to control lights. When button_a
is pressed, lights toggle on and off and button_b can switch designs
'''

from microbit import *
import radio

radio.on()
radio.config(channel=63)

ON_FLAG = False

while True:
    if button_a.was_pressed():
        if ON_FLAG:
            radio.send('display:off')
        else:
            radio.send('display:on')

        ON_FLAG = not ON_FLAG

    if button_b.was_pressed():
        radio.send('alternate')
示例#16
0
文件: queen.py 项目: bhive-team/bHive
            primes.append(int(prime))
        display.scroll(" ".join([str(n) for n in primes]))
    elif params[0] == "spyRSA":
        if params[2] == "True":
            display.scroll(" ".join(params[3:]))

    # Handle error.
    elif params[0] == "err":
        handleError(params[1], " ".join(params[2:]))


# Constantly sending worker_request
while True:
    # Casting to check for clients
    if button_a.is_pressed() and not isPolling:
        radio.send("ping")
        isPolling = True
        active = "spy"
        pollTime = 0

    if isPolling:
        sleep(1)  # sleep 1 ms
        pollTime += 1
        if pollTime >= 200:
            isPolling = False
            pollTime = 0

    if active == "spy" and not isPolling:
        for i, client in enumerate(clients):
            radio.send(client + " spyRSA " + str(getChannel(i)) + " 20000")
        active = ""
示例#17
0
from microbit import *
import radio

radio.enable(32, 4)

was_pressed = False
while True:
    is_pressed = button_a.is_pressed()
    if is_pressed is not was_pressed:
        if is_pressed is True:
            radio.send(b'\x01')
        else:
            radio.send(b'\x00')
    was_pressed = is_pressed
    rec = radio.recv()
    if rec == b'\x01':
        display.show(Image("99999:99999:99999:99999:99999"))
    elif rec == b'\x00':
        display.clear()
    sleep(5)
示例#18
0
# Write your code here :-)
from microbit import *
import radio

radio.on()
while True:
    if button_a.was_pressed():
        sleep(100)
        if button_b.was_pressed():
            radio.send("end")
            display.show(Image.TARGET)
            sleep(750)
            display.clear()
        else:
            radio.send("dot")
            display.show(Image('00000:00000:00900:00000:00000'))
            sleep(750)
            display.clear()
    elif button_b.was_pressed():
        sleep(100)
        if button_a.was_pressed():
            radio.send("end")
            display.show(Image.TARGET)
            sleep(750)
            display.clear()
        else:
            radio.send("dash")
            display.show(Image('00000:00000:09990:00000:00000'))
            sleep(750)
            display.clear()
示例#19
0
from microbit import *
import radio
radio.on()

while True:
    
    if button_a.was_pressed():
        radio.send('hi')

    if button_b.was_pressed():
        display.clear()

    Happy = radio.receive()
    
    if Happy == 'bye':
        display.show(Image.SAD)
示例#20
0
from microbit import *
import radio

radio.on()
radio.config(channel=28)

display.show(Image.BUTTERFLY * 0.2)

while True:
    try:
        if button_a.was_pressed():
            radio.send('a')
        if button_b.was_pressed():
            radio.send('b')
    except:
        radio.off()
        radio.on()
示例#21
0
# Import Modules
from microbit import *
import radio
# Set Radio
radio.on()
radio.config(channel=41)
# Set Variables
prev_time = 0
time = 0
# Loop Program
while True:
    # Read Gesture
    if accelerometer.was_gesture("shake"):
        # Set Time Between Gestures
        time = running_time() - prev_time
        # Display And Send Time
        print(time)
        radio.send('r' + str(time))
        display.show(Image.HAPPY)
        sleep(100)
        # Reset Time
        prev_time = running_time()
        display.clear()
示例#22
0
                    'first_contact': timestamp,
                    'last_timestamp': timestamp
                }
                #print("C", received_id, contacts[received_id])

            if contacts[received_id]['last_timestamp'] - contacts[received_id][
                    'first_contact'] > CLOSE_CONTACT_TIME:
                # record close contact
                contactID = received_id + ":" + str(
                    contacts[received_id]['first_contact'])
                close_contacts[contactID] = contacts[received_id][
                    'last_timestamp']
                #print("CLOSE", contactID, close_contacts[contactID])
        d = radio.receive_full()  # get next message from queue
    sleep(DELAY_BETWEEN_BROADCASTS / 2)
    radio.send(ID)
    display.show([Image.SQUARE_SMALL, Image.SQUARE],
                 delay=50,
                 wait=True,
                 clear=True)
    sleep(DELAY_BETWEEN_BROADCASTS / 2)

    if close_contacts and last_data_save + TIME_BETWEEN_DATA_SAVES < time.ticks_ms(
    ):
        f = open(DATA_FILENAME, "w")
        f.write("ID,Time of First Contact (ms),Total Contact Time (ms)\n")
        for contactID, last_timestamp in close_contacts.items():
            user_id, first_timestamp = contactID.split(":")
            contact_time = last_timestamp - int(first_timestamp)
            f.write(user_id + "," + first_timestamp + "," + str(contact_time) +
                    "\n")
header = my_address + their_address

acknowledge_string = "ACK"
acknowledge_packet = header + acknowledge_string

### TASK 2 ###
data_received = []

# Adds data received to data_received
# Sends back an acknowledgment after every message received
while True:
    message = radio.receive()
    if message is not None:
        if len(message) >= 5 and message[:2] == their_address and message[2:4] == my_address:
            data = message[4:]

            # There is a % chance for the acknowledgment not to be sent
            # ToDo: Use send with Error function. 
            generated = random.randint(1, 100)
            if generated >= 25: # 75% chance of sending, 25% chance of not sending
                radio.send(acknowledge_packet)
                
            if data != "Start" and data != "End":
                data_received.append(data)
            elif data == "End":
                data_uniques = list(dict.fromkeys(data_received))
                duplicates = len(data_received) - len(data_uniques)
                display.scroll(str(duplicates))
                data_received = []
            
            message = None
from microbit import *
import radio

radio.on()
radio.config(channel=1)

while True:
    pcwrite = uart.read()
    incoming = radio.receive()
    if pcwrite:
        ch = msg[:2]
        ch = int(channel)
        radio.config(channel=ch)
        display.scroll(pcwrite, delay=70)
        radio.send(pcwrite[2:])
    if incoming:
        print(incoming)
# Old-timey twitter

from microbit import *
import radio
 
radio.on()

your_tweet = 'hi'

while True:
	
    if button_a.was_pressed():
	   radio.send(your_tweet)
  
    received_tweet = radio.receive()
    
    if received_tweet:
        display.scroll(received_tweet)
示例#26
0
# A micro:bit Firefly.
# By Nicholas H.Tollervey. Released to the public domain.
import radio
import random
from microbit import display, Image, button_a, sleep

# Create the "flash" animation frames. Can you work out how it's done?
flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]

# The radio won't work unless it's switched on.
radio.on()

# Event loop.
while True:
    # Button A sends a "flash" message.
    if button_a.was_pressed():
        radio.send('flash')  # a-ha
    # Read any incoming messages.
    incoming = radio.receive()
    if incoming == 'flash':
        # If there's an incoming "flash" message display
        # the firefly flash animation after a random short
        # pause.
        sleep(random.randint(50, 350))
        display.show(flash, delay=100, wait=False)
        # Randomly re-broadcast the flash message after a
        # slight delay.
        if random.randint(0, 9) == 0:
            sleep(500)
            radio.send('flash')  # a-ha
示例#27
0
    z >>= 4
    #
    # Convert to 2s complement
    #
    x %= 256
    y %= 256
    z %= 256
    #
    # Encode the button presses
    #
    if button_a.is_pressed():
        a = 1
    else:
        a = 0
    if button_b.is_pressed():
        b = 1
    else:
        b = 0
    #
    # Encode into a single integer
    #
    x <<= 18
    y <<= 10
    z <<= 2
    a <<= 1
    v = hex(x + y + z + a + b)[2:]
    #
    # v has length 7 characters
    #
    radio.send(v + ':' + NAME)
     if button_a.was_pressed():
         shoot = True
     else:
         show_ships = False
         display.clear()
         fire_y += 1
         if fire_y >= 5:
             fire_y = 1
         display.set_pixel(fire_x, fire_y, 9)
  
 # If both buttons are pressed at the same time, send the chosen 
 # coordinate to the opponent
 if shoot or (button_a.is_pressed() and button_b.is_pressed()):
     show_ships = True
     shoot = False
     radio.send(str(fire_x + 5 * fire_y))
     sleep(500)
     
 # Check if packet received
 incoming = radio.receive()
 if incoming:
     # if it is a miss, just turn on the pixel on (4, 0)
     # But (0, 0) pixel may be already on, so turn it off
     if incoming == "Miss":
         display.set_pixel(4, 0, 9)
         sleep(500)
         display.set_pixel(0, 0, 0)
     # if it is a hit, turn on the pixel on (0, 0)
     # but (4, 0) pixel may be already on, so turn it off
     # incraese the hit count
     # if we reached 5, we won - display HAPPY! Game over
示例#29
0
buttonStat = "off"
alexaStat = "waiting"
remote = True

radio.on()

while True:
    ticker = ticker+1
    if (ticker%len(think)==0) and (ticker%len(talk)==0):
        ticker = 0
        
    stat = "on" if button_a.is_pressed() else "off"
    if stat != buttonStat:
        if remote:
            buttonStat = stat
            radio.send(buttonStat)
    
    if not pin1.is_touched() and not pin2.is_touched():
        stat = "thinking"
    elif not pin1.is_touched():
        stat = "talking"
    elif not pin2.is_touched():
        stat = "listening"
    else:
        stat = "waiting"
        remote = False
        
    if stat != alexaStat:
        if not remote:
            alexaStat = stat
            radio.send(alexaStat)
示例#30
0
    return try_group  # Returns the ID of the available group currently configured to


# Checks to see if group currently on is available up to 'checks' times
# User should not call this function
def checkGroup(checks, wait):
    available = True
    for i in range(checks):
        radio.send("TAKEN?")
        for j in range(wait):  # How long to wait to see if taken
            message = radio.receive()
            if message is not None:
                # If group is taken, try a different group
                if message == "TAKEN?" or message in other_master_queries or message == "GROUP TAKEN":  # Other messages are ignored
                    available = False
                    return available
            sleep(1)
    return available


group = findAvailableGroup(3, 250)
while True:
    message = radio.receive()
    if message is not None:
        if message == (master_name + "?"):
            radio.send(master_name
                       )  # Notifies slave microbits it is the correct group
        else:
            radio.send("GROUP TAKEN")  # Other microbits told group is full
    display.show(str(group))
示例#31
0
MAIN LOOP
'''
on = False
display.show(Image.NO)

while True:
    button = button_press()
    if button == 'F':
        radio.on()
        display.show(Image.YES)
        on = True

    while on is True:
        button = button_press()
        if button == 'E':
            radio.send('stop')
            radio.off()
            display.show(Image.NO)
            on = False
        elif button == 'A':
            radio.send('angry')
            sleep(100)
        elif button == 'B':
            radio.send('frown')
            sleep(100)
        elif button == 'C':
            radio.send('smile')
            sleep(100)
        elif button == 'D':
            radio.send('line')
            sleep(100)
示例#32
0
            sleep(200)
            display.clear()
            if button_b.was_pressed():
                if (sensitivity_counter + 1) > 4:
                    sensitivity_counter = 0
                else:
                    sensitivity_counter += 1
                display.show(sensitivity_icons[sensitivity_counter])
                sleep(200)
                display.clear()

    while scanning:
        radio.config(channel=7)
        radio.config(power=7)
        radio.on()

        if button_a.was_pressed():
            scanning = False

        incoming = radio.receive()
        if incoming == 'send':
            display.show(flash, delay=100, wait=False)
            radio.send('receive')
        if incoming == 'receive':
            display.show(flash, delay=100, wait=False)

        display.show(scanning_cycle1, delay=100)
        radio.send('send')
        display.show(scanning_cycle2, delay=100)
        display.clear()
示例#33
0
from microbit import *
import radio

radio.config(channel=22)
radio_status = False
emission_status = True

while True:
    if button_a.was_pressed():
        if radio_status == False:
            radio.on()
            display.show(Image.YES)
            radio_status = True
            sleep(300)
            display.clear()
        else:
            radio.off()
            display.show(Image.NO)
            radio_status = False
            sleep(300)
            display.clear()

    if radio_status == True:
        incoming = radio.receive()
        if incoming:
            if incoming == "OK":
                display.scroll(incoming)
                emission_status = True
            if emission_status == True:
                radio.send("Ok")
示例#34
0
from microbit import *
import radio

radio.on()

while True:
    if accelerometer.was_gesture('shake'):
        radio.send('     ')
        display.show(Image.SQUARE)
        sleep(200)
    elif button_a.was_pressed():
        radio.send('dot ')
        display.show(Image('00000:00000:00900:00000:00000'))
        sleep(200)
    elif button_b.was_pressed():
        radio.send('dash ')
        display.show(Image('00000:00000:09990:00000:00000'))
        sleep(200)
    else:
        display.clear()
示例#35
0
import microbit as mb
import radio  # Needs to be imported separately

# Change the channel if other microbits are interfering. (Default=7)
radio.on()  # Turn on radio
radio.config(channel=4, length=100)

print('Program Started')
mb.display.show(mb.Image.HAPPY)

while not mb.button_a.is_pressed(
):  # wait for button A to be pressed to begin logging
    mb.sleep(10)

radio.send('start')  # Send the word 'start' to start the receiver
mb.sleep(1000)
mb.display.show(mb.Image.HEART)  # Display Heart while logging

totaltime = 0
# Read and send accelerometer data repeatedly until button A is pressed again
while not mb.button_a.is_pressed():
    ######################################################
    # FILL In HERE
    # Need to collect accelerometer and time measurements
    # Need to format into a single string
    # Send the string over the radio
    ######################################################
    time0 = mb.running_time()
    mb.sleep(100)
    time1 = mb.running_time()
示例#36
0
            num = ord(symbol)
            num += key
            if symbol.isupper():
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26
            elif symbol.islower():
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26
            translated += chr(num)
        else:
            translated += symbol
    return translated


display.show(Image.TARGET)
while True:
    for number in channels:
        radio.config(channel=int(number))
        if number == 12:
            radio.send("X")
        else:
            encrypted = encrypt(number, start + password[number-13])
            encrypted = encrypted.upper()
            radio.send(encrypted)
            #print(encrypted)
    sleep(200)
           853: 'E',
           819: 'F'}

def button_press():
    press = pin2.read_analog()
    if press < 900:
        for number in range(press-5, press+5):
            if number in buttons:
                return buttons[number]

def joystick_push():
    x = pin0.read_analog() - 518
    y = pin1.read_analog() - 523
    left = (y + x)
    right = (y - x)
    return left, right

while True:
    joystick = joystick_push()
    button = button_press()
    message = str(joystick[0]) + " " + str(joystick[1])
    radio.send(message)
    sleep(100)
    if button == "F":
        radio.config(channel=4, group=96, queue=1)
        sleep(100)
    if button == "E":
        radio.config(channel=10, group=100, queue=1)
        sleep(100)
    print(str(channel) + ' ' + str(group))
示例#38
0
sent = False
switch_state = pin0.is_touched()

while True:
  message = radio.receive()
  if message:
    try:
      team, score = map(int, message.split(':'))
      scores[team] = (score, team)
      uart.write('Team '+str(team)+': '+str(score)+'\r\n')
      with open('scores.txt', 'w') as scores_file:
        scores_file.write('\n'.join(str(team)+':'+str(score) for score in scores))
    except ValueError:
      pass

  if button_a.was_pressed():
    try:
      with open('scores.txt', 'r') as scores_file:
        scores = [score.split(':')[::-1] for score in scores_file.read().split() if score]
    except OSError:
      pass

    score_strings = [str(team)+':'+str(score) for score, team in scores]

    uart.write('='*40+'\r\n')
    for score_string in score_strings:
      radio.send(score_string)
      uart.write(score_string+'\r\n')
    uart.write('='*40+'\r\n')
示例#39
0
def	hdr_bb() :

	radio.send( 'back')
	sleep( 200)
# This script will allow to or more BBC
# Microbits to transmit data. This is the
# sending part of the system so it will
# send data.

from microbit import *
import radio

commands = [
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
    'F'
]
selection = 0

while True:
    if button_a.is_pressed():
        if selection >= 15:
            selection = 0
        else:
            selection = selection + 1
        display.show(commands[selection])
        sleep(250)
    if button_b.is_pressed():
        radio.send(commands[selection])
        display.scroll('Sent')
        sleep(500)

def xy(channel):
    x = channel // 20
    y = channel // 4 % 5
    return x, y

radio.on()

channel = new_channel()
x, y = xy(channel)
radio.config(channel=channel)

while True:
    display.set_pixel(x, y, 4)
    radio.send('hello, microbit')
    display.set_pixel(x, y, 0)
    if accelerometer.is_gesture('shake'):
        channel = new_channel()
        radio.config(channel=channel)
        x, y = xy(channel)
    if button_a.was_pressed():
        channel += 1
        radio.config(channel=channel)
        if channel > 99:
            channel = 0
        x, y = xy(channel)
    if button_b.was_pressed():
        channel -= 1
        radio.config(channel=channel)
        if channel == 0:
示例#42
0
from microbit import uart
import radio

uart.init(baudrate=115200)
radio.on()

while True:
    msg = uart.read()
    if msg:
        # if msg is in format "!#SET-x-y"
        # set radio.config(x=y)
        if msg.startswith("!#SET-"):
            radio.config({msg.split('-')[1]: msg.split('-')[2]})
        # if not !#SET message, send message via radio
        else:
            radio.send(str(msg, 'UTF-8'))
示例#43
0
import radio
from microbit import *

DELAY = 100
NAME = "Niphredil"
#NAME = "Alfirin"
radio.on()

while True:
    sleep(DELAY)
    if button_a.was_pressed():
        radio.send(NAME)
        display.show([Image.DIAMOND_SMALL,Image.DIAMOND],wait=True,clear=True)
示例#44
0
        if msg.startswith("MEM:"):
            radio.on()
            print(msg)
            receivedsequence = msg[4:]
            display.clear()

            while len(inputsequence) < len(receivedsequence):
                if button_a.was_pressed():
                    inputsequence += ('A')

                elif button_b.was_pressed():
                    inputsequence += ('B')

                if button_a.is_pressed():
                    display.show("A")

                elif button_b.is_pressed():
                    display.show("B")
                else:
                    display.clear()
            if inputsequence == receivedsequence:
                radio.send("REC:CORRECT")
                display.show(Image.YES)
                inputsequence = ''
                receivedsequence = ''

            else:
                radio.send("REC:INCORRECT")
                display.show(Image.NO)
                inputsequence = ''
                receivedsequence = ''
示例#45
0
def drawPaddle(x):
  display.set_pixel(x,4,9)
  display.set_pixel(x+1,4,9)

def getX():
  acx = accelerometer.get_x()
  if acx < -500:
    return 0
  elif acx >= -500 and acx < 0:
    return 1
  elif acx >= 0 and acx < 500:
    return 2
  elif acx >= 500:
    return 3
  return 0

display.on()
display.clear()
radio.on()
while True:
  #uart.write(str(x) + "\r\n")
  x = getX()
  display.clear()
  drawPaddle(x)
  drawBall()
  time+=1
  if button_a.is_pressed():
    radio.send('msg')
    display.show(Image.HAPPY)
    break
示例#46
0
文件: queen.py 项目: bhive-team/bHive
def releaseAllClients():
    for client in clients:
        radio.send(client + " release")
示例#47
0
def send_image(image):
    radio.send(repr(image))
from microbit import *
import radio

balance = 0
send_amt = 400

while True:
    received = radio.receive() #constantly checks if there's a message
    if received is not None:
        balance = balance + int(received)
        #TODO: Unlock servo
        sleep(1000)
    else:
        pass # Do nothing if we receive nothing
    # When A and B are pressed, return some money back
    if button_a.is_pressed() and button_b.is_pressed():
        radio.send(str(send_amt))
        balance = balance - send_amt
        # TODO: Lock servo
        sleep(1000)    
    else:
        pass
a0 = 1000
da = 50
A = accelerometer.get_values()
G = A[:]
b = 0.9
c = 0.99
d = 0.5
breaklight.set_analog_period_microseconds(10000)
breaklight.set_analog_period_microseconds(10000)
while True:
    headlight_mode = (headlight_mode + headlight_control.get_presses()) % len(values)
    headlight.write_analog(values[headlight_mode])
    emo_mode0 = emo_mode
    emo_mode = (emo_mode + emo_control.get_presses()) % len(images)
    if emo_mode != emo_mode0:
        radio.send("emo_mode = %d" % emo_mode)
    message = radio.receive()
    if message:
        try:
            exec(message, globals(), locals())
        except:
            pass
    acc = accelerometer.get_values()
    G = [c * a0 + (1 - c) * a for a0, a in zip(G, acc)]
    A = [b * a0 + (1 - b) * a for a0, a in zip(A, acc)]
    a_rms = sqrt(sum([(a - g) ** 2 for a, g in zip(A, G)]))
    i = (emo_mode + int(a_rms / da)) % len(images)
    display.show(images[i])
    brakelight_value = d * brakelight_value + (1 - d) * (0x100 + 0x2FF * (i % 2))
    breaklight.write_analog(brakelight_value)
    print((headlight_mode, int(a_rms / da), i))
示例#50
0
文件: radio.py 项目: AvdN/micropython
# A micro:bit Firefly.
# By Nicholas H.Tollervey. Released to the public domain.
import radio
import random
from microbit import display, Image, button_a, sleep

# Create the "flash" animation frames. Can you work out how it's done?
flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]

# The radio won't work unless it's switched on.
radio.on()

# Event loop.
while True:
    # Button A sends a "flash" message.
    if button_a.was_pressed():
        radio.send('flash')  # a-ha
    # Read any incoming messages.
    incoming = radio.receive()
    if incoming == 'flash':
        # If there's an incoming "flash" message display
        # the firefly flash animation after a random short
        # pause.
        sleep(random.randint(50, 350))
        display.show(flash, delay=100, wait=False)
        # Randomly re-broadcast the flash message after a
        # slight delay.
        if random.randint(0, 9) == 0:
            sleep(500)
            radio.send('flash')  # a-ha
示例#51
0
import radio

# Set up variables
cost = 10 # Cost to borrow one umbrella
balance = 100 # Current balance
DEBUGGING = True # we will print stuff during development
borrowing = 0 # indicate whether the current holder is borrowing anything

# The logic
while True:
    # Press a to borrow, press b to return
    if button_a.was_pressed():
        radio.on()
        # indicate borrow an umbrella
        # TODO: set up the handshake
        radio.send('Borrow')

        # and deduct account only if balance has enough
        if balance > 0:
            balance = balance - cost
            borrowing = borrowing + 1
        # for us to know we have just sent a notice
        if DEBUGGING:
            display.show('Borrow')
            display.show(str(balance))
        # TODO: unlock umbrella

    if button_b.was_pressed(): # return
        if borrowing > 0:
            balance = balance + cost
            borrowing = borrowing - 1
# Task 3:

from microbit import *
import radio
import random

radio.on()
# List of strings that can be sent
stringlist = ["Message received!", "Incoming message!", "New message!", "Hello"]

while True:
    # Press button A to send a number
    if button_a.is_pressed():
        # Choose a random number between 0-9 
        number = str(random.randint(0, 9))
        radio.send(number)
        sleep(1000)
    # Choose a random string to send
    elif button_b.is_pressed(): 
        string = random.choice(stringlist)
        radio.send(string)
        sleep(1000)
# Presenter microbit, listens for card selection (in case robot breaks down) 
# and is able to trigger robot announcement via button 
from microbit import *
import radio

radio.on()

display.show(Image.SKULL)
sleep(500)

selected_card = ''

while True:
    
    if selected_card:
        display.scroll(selected_card, delay=75)
    
    if button_b.was_pressed():
        radio.send('announce')
        
    message = radio.receive()

    if message:
        if message != 'announce':
            selected_card = message
            display.show(Image.RABBIT)
            sleep(500)
示例#54
0
from microbit import *
import radio

radio.on()
radio.config(channel=41)

race_going = 0
while True:

    msg = radio.receive()
    if msg:
        if msg == "start":
            display.scroll("started")
            race_going = 1

    if button_a.is_pressed() == 1 and race_going == 1:
        radio.send("time")
        race_going = 0
示例#55
0
        display.show(Image('09990:90009:00000:09090:09090'))
        radio.send("W:1")

    sleep(1000)
    while 1:
        if button_a.is_pressed() or button_b.is_pressed():
            reset_game()
            break


while 1:
    if (ticks - last_hit) % max(10, 30 - hits) == 0:
        move_ball()

    update_screen()
    radio.send("US:" + str(ball[0]) + ":" + str(ball[1]) + ":" +
               str(paddle_2))  #add paddle
    if ball[1] == 0:
        end_game('1')
    if ball[1] == 9:
        end_game('0')
    if button_a.was_pressed():
        paddle_1 = shift_paddle(paddle_1, -1)

    if button_b.was_pressed():
        paddle_1 = shift_paddle(paddle_1, 1)
    b = radio.receive()
    if b:
        b = b.split(":")
        if b[0] == "MP":
            if b[1] == '1':
                if b[2] == "r":
示例#56
0
    if button_a.was_pressed():
        answer = "true"
        start_time = running_time()
        question_asked = True
    if button_b.was_pressed():
        answer = "false"
        start_time = running_time()
        question_asked = True
    # Checks for incoming answer, checks if answer is correct, subtracts points based on time elapsed and INCORRECT_PENALTY.
    incoming = radio.receive()
    if question_asked:
        if incoming and incoming.startswith("tof:"):
            if incoming == "tof:" + answer:
                questions_answered += 1
            else:
                points -= INCORRECT_PENALTY
            question_asked = False
            display.scroll("Score: {}".format(points), wait=False)
            radio.send("tof:" + answer + "-answer")
        else:
            end_time = running_time()
            elapsed_time = end_time - start_time
            start_time = end_time
            points -= elapsed_time

    if points <= 0:
        display.scroll("Game over! {} questions answered correctly!".format(
            questions_answered))
        questions_answered = 0
        points = START_POINTS
        question_asked = False
示例#57
0
    "right": [pin1, pin1.read_analog(), 1],
    "left": [pin2, pin2.read_analog(), 1],
    "for": [pin3, pin3.read_analog(), 1],
    "back": [pin4, pin4.read_analog(), 1]
}
#asd


def check(inf):
    p = inf[0]
    initial_flex = inf[1]
    flex_scale = inf[2]
    flex = abs((p.read_analog() - initial_flex) / flex_scale)
    #print(flex)
    if flex > 10:
        #print('PRESSED')
        return True

    else:
        #print('NOT PRESSED')
        return False

    sleep(20)


while True:
    for i in ["left", "right", "for", "back"]:
        if check(pins[i]):
            print(i)
            radio.send(i)
            sleep(2)
示例#58
0
    display.scroll("You won! You took " + str(ms) + " ms.",
                   wait=True,
                   loop=False)


def scroll_finish_time_lost(ms):
    display.scroll("You lost! You took " + str(ms) + " ms.",
                   wait=True,
                   loop=False)


while True:
    if not running:
        if button_a.was_pressed():
            display.scroll("waiting", wait=False, loop=True)
            radio.send("ready " + PLAYER_NAME)

        msg = radio.receive()
        if msg:
            if msg == "ready both":
                display.clear()
                display.show("3")
                sleep(1000)
                display.show("2")
                sleep(1000)
                display.show("1")
                sleep(1000)
                display.show(Image.HEART)
                running = True

    else:
    ["H", "Harts"],
    ["C", "Clubs"],
    ["S", "Spades"],
    ["D", "Die a monds"]
]

display.show(Image.RABBIT)
sleep(500)

radio.on()

selected_card = ''

while True:
    
    if selected_card:
        display.scroll(selected_card)
    
    # pick a card at random
    if button_a.was_pressed():
        card = random.choice(cards) 
        suit = random.choice(suits)
        radio.send(card[1] + ' of ' + suit[1]) # broadcast the selected card.
        selected_card = card[0] + ' of ' + suit[0]
        display.show(Image.RABBIT)
        sleep(500)
    
    if button_b.was_pressed():
        # prompt announcement of "guess"
        radio.send('announce')
示例#60
0
from microbit import *
import radio

radio.on()
display.scroll("Send")

while True:
    x = accelerometer.get_x()
    #y = accelerometer.get_y()
    #z = accelerometer.get_z()
    a = int(button_a.is_pressed())
    b = int(button_b.is_pressed())
    gesture = accelerometer.current_gesture()
    shake = 0
    if gesture is 'shake':
        shake = 1
    msg = str(x) + "," + str(a) + "," + str(b) + "," + str(shake)
    radio.send(msg)