def receive_new_move(): wait_animation() move = radio.receive() while move not in ICONS: sleep(100) move = radio.receive() display.show(ICONS[move]) sequence.append(move) # other player lost the game if move == "gg": radio.off() shutdown()
def receive(self, radio_config=None): # -> (radio_measurements, address or None, payload or None) # radio_params is an overlay on top of radio rx defaults (e.g. poll rate, timeout, min payload, max payload) # radio_measurements might include rssi reading, short payload report, etc #TODO: merge radio_params with self.tx_defaults #TODO: configure radio modulation based on merged params #TODO: poll radio at rate until timeout or received #TODO: start timeout timer payload = None radio.receiver(ook=True) while True: # timer not expired if radio.is_receive_waiting(): #TODO: radio config should set receive preamble 4 bytes to prevent false triggers payload = radio.receive(size=12) #TODO: payload, radio_measurements = radio.receive() p = TwoBit.decode(payload) #TODO: if failure, report it, but keep trying #if check passes... break #TODO: inter-try delay #TODO: return radio to state it was before receiver (e.g. standby) - radio needs a pop() on this too? if payload == None: # nothing received in timeout return (None, None, None) # (radio_measurements, address, payload) #TODO: might be measurements, average min max? #TODO: extract addresses (house_address, device_index) radio_measurements = None #TODO: return this from radio.receive() h = 0xC8C8C #TODO: Get house address from TwoBit.decode()[:10] d = 0xEE #TODO: Get device command from TwoBit.decode()[11:12] address = (h, d) return (radio_measurements, address, payload)
def receive(): """Starts a receiver program""" radio.on() channel_idx = 0 while True: # Handle the display switching # A for prev channel, B for next channel channel_selector = button_incdec() if channel_selector != 0: # Switch the channel channel_idx = (channel_idx + channel_selector) % MAX_DISPLAY_IDX radio.config(channel=BASE_CHANNEL + channel_idx, length=251) radio.on() # Give the user some feedback display.show(str(channel_idx)) sleep(750) display.clear() msg = radio.receive() if msg: # TODO: validate that we have received a valid frame try: display.show(eval(msg)) except Exception as e: display.show(Image.SAD) print(repr(e))
def receive(self, radio_config=None): # -> (radio_measurements, address or None, payload or None) # radio_params is an overlay on top of radio rx defaults (e.g. poll rate, timeout, min payload, max payload) # radio_measurements might include rssi reading, short payload report, etc pass # TODO #TODO: set radio to receive mode #TODO: merge radio_params with self.tx_defaults #TODO: configure radio modulation based on merged params #TODO: poll radio at rate until timeout or received #TODO: start timeout timer payload = None radio.receiver(fsk=True) while True: # timer not expired if radio.is_receive_waiting(): payload = radio.receive() #TODO: payload, radio_measurements = radio.receive() now = time.time() p = OpenThings.decode(payload, receive_timestamp=now) #TODO: if crc failure, report it, but keep trying #if crc check passes... break #TODO: inter-try delay #TODO: return radio to state it was before receiver (e.g. standby) - radio needs a pop() on this too? if payload == None: # nothing received in timeout return (None, None, None) # (radio_measurements, address, payload) #TODO: might be measurements, average min max? #TODO: extract addresses: header_manufacturerid, header_productid header_deviceid -> (m, p, d) m, p, d = None, None, None radio_measurements = None #TODO: get from radio.receive() address = (m, p, d) return (radio_measurements, address, payload)
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))
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)
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)
def receive(): key = input("hex number for key? ") key = int(key, 16) radio.on() while True: try: cyphertext = radio.receive() if cyphertext is not None: plaintext = cypher(cyphertext, key) print(plaintext) except: radio.off() radio.on()
def recv( self) : recvstr = radio.receive() if recvstr is None : return None, None print( recvstr) items = recvstr.split( ':') if len( items) != 2 : return None, recvstr print( items) return items
def getMessage(): data = radio.receive() if data == 'None': return False if type(data) is not str: return False v = int(data.split(':')[0],16) b = (v & 1 == 1) v >>= 1 a = (v & 1 == 1) v >>= 1 z = v & 255 v >>= 8 y = v & 255 v >>= 8 x = v & 255 if x > 127: x -= 256 if y > 127: y -= 256 if z > 127: z -= 256 x *= -1 y *= -1 name = data.split(':')[1] e = { 'name': name, 'accelerometer': { 'x': x, 'y': y, 'z': z, }, 'button_a': { 'pressed': a, 'down': a and not state['a'], 'up': not a and state['a'] }, 'button_b': { 'pressed': b, 'down': b and not state['b'], 'up': not b and state['b'] } } state['a'] = a state['b'] = b return e
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()
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))
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)
def run(): while True: display.show(Image.DIAMOND_SMALL) try: msg = radio.receive() except: radio.off() radio.on() msg = None buttons = read_buttons() if msg is not None: display.show(Image.DIAMOND) if buttons == "action": speech.say(msg) else: speech.say("a") # music.pitch(PITCH, pin=pin0) # music.pitch(PITCH, pin=pin1) # sleep(100) # music.stop(pin0) # music.stop(pin1) sleep(250) # keep image on display for a bit longer
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)
for prime in range(int(numberOfIterations)): prime = int(prime) + start if rmTest(prime, 5): verifiedPrimes.append(prime) return verifiedPrimes # Main loop :) while True: if heldByQueen: display.show("H") else: display.clear() # Keep polling BLE for data recv = radio.receive() # If not empty if recv is not None: # Parse the radio data into something useful params = str(recv).split(" ") # Queen looking for available workers if params[0] == "ping": if not heldByQueen: # Let them know that we're free and our unique ID for future interaction radio.send("pong " + macAddr) # Check that the instruction is intended for us elif params[0] == macAddr: if (params[1] in locals()) and (params[1] in ALLOWED_FUNCS): # Compute the task requested (and note that we're busy and haven't broken)
radio.on() radio.config(address = 23456789) def convert(string_sum): new_Str = "" for i in string_sum: new_Str = new_Str + i #reference-https://www.geeksforgeeks.org/sum-of-list-with-string-types-in-python/ return new_Str def split(word): return [char for char in word] #reference-https://www.geeksforgeeks.org/python-split-string-into-list-of-characters/ while True: received = radio.receive() if received != None: p0 = received[0:] sum_of_p0 = (sum(int(c) for c in p0)) parity_bit_1 = int(received[1:2]) + int(received[3:4]) + int(received[5:6]) + int(received[7:8]) + int(received[9:10]) + int(received[11:]) parity_bit_2 = int(received[2:3]) + int(received[3:4]) + int(received[6:7]) + int(received[7:8]) + int(received[10:11]) + int(received[11:]) parity_bit_4 = int(received[4:5]) + int(received[5:6]) + int(received[6:7]) + int(received[7:8]) parity_bit_8 = int(received[8:9]) + int(received[9:10]) + int(received[10:11]) + int(received[11:]) if parity_bit_1 % 2 != 0 or parity_bit_2 % 2 != 0 or parity_bit_4 % 2 != 0 or parity_bit_8 % 2 != 0: if sum_of_p0 % 2 == 0: display.show(Image.SAD)
from microbit import * import radio radio.on() while True: if button_a.was_pressed(): radio.send('bye') if button_b.was_pressed(): display.clear() Happy = radio.receive() if Happy == 'hi': display.show(Image.HAPPY)
searching = True listening = True sender = False display.show(Image.TARGET) wait_time = random.randint(2000, 10000) radio.on() while searching: #The M:B will listen for a server unless the user presses B. if button_b.was_pressed(): #Send the generated wait time to a waiting client. radio.send(str(wait_time)) display.show("S") sender = True #Listen for confirmation from any client M:B. while listening: confirmation = radio.receive() if confirmation is not None and int(confirmation) == wait_time: listening = False searching = False display.show(Image.YES) else: sleep(10) elif button_a.was_pressed(): #Need to do this to reset the number of times A was pressed. button_a.get_presses() display.show("R") while listening: wait_time = radio.receive() if wait_time is not None: radio.send(wait_time) wait_time = int(wait_time)
print(str(self.name) +": "+ str(self.acc_x) + ", " + str(self.acc_y) + ", " + str(self.acc_z)) radio.on() radio.config(channel = 41) radio.config(power=7) display.show("C") time_list=[] left_list=[] right_list =[] centre_list =[] for t in range(500): acc_string = radio.receive() if acc_string is not None: tokens = acc_string.split(", ") Test = Measurement(tokens[0],tokens[1],tokens[2],tokens[3]) print(Test) if(tokens[0]=="Left"): if(len(left_list) - len(right_list) <1): left_list.append(Test) t += 1 elif (tokens[0] == "Right"): if(len(right_list) - len(left_list) <1): right_list.append(Test) while True:
# 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
# start the communication over usb, with baudrate 115200 # make sure you set the same baudrate on the other end of this communication uart.init(115200) # start the radio, with all settings to default radio.on() # a bytearray with a linefeed character buffer = bytearray(1) buffer[0] = 10 while True: try: # receive a string over radio input = radio.receive() if input is not None: # write the string to the USB communication uart.write(input) # also write a linefeed character uart.write(buffer) else: # if we didn't receive anything show an F on the display display.scroll("F", 80) except ValueError: # Not sure why this happens, but sometimes the received information throws this error # Restarting the radio seems to be needed input = None radio.reset() radio.off() radio.on()
from microbit import * import radio radio.on() radio.config(channel=41) start_time = 0 finish_time = 0 score = 0 while True: if radio.receive() == "start": print("start") start_time = running_time() if radio.receive() == "end": finish_time = running_time() score = finish_time - start_time score = score // 100 score = score / 10 print(score)
note = ("D{}:{}", "G{}:{}", "B{}:{}") elif tilt > -(-spectrum + 2 * (2 * spectrum / 5)): note = ("E{}:{}", "G{}:{}", "C{}:{}") elif tilt > -(-spectrum + 3 * (2 * spectrum / 5)): note = ("G{}:{}", "D{}:{}", "B{}:{}") else: note = ("A{}:{}", "E{}:{}", "C{}:{}") pitch = note[part] display.show(pitch[0]) if play1 == 1: music.play(note[part].format(octave[part], duration), wait=False) while True: sig = '' try: sig = radio.receive() except: continue if (sig == 'allIn' or sig == '1') or sig == '12': toneSig = '' while toneSig != 'end': sleep(10) try: toneSig = radio.receive() except: pass if not (toneSig == '' or toneSig == 'end'): play(toneSig) display.clear()
return msg def decrypt(msg): i = len(msg) - 1 msg = cipher_key(msg, key) msg = reverse(msg, i) return msg def send(msg): radio.send_bytes(msg) def send_key(key): radio.send_value("key") while True: receivedMsg = radio.receive() if receivedMsg: p_msg = parse(receivedMsg) if p_msg.type == "key": key = p_msg.msg radio.send("keyOK") if p_msg.type == "ch1": msg = decrypt(p_msg.msg) send_txt = encrypt("OK") #radio.send(send_txt) send_msg="ch1"+send_txt radio.send(send_msg) #display.set_pixel(2, 2, 5) radio.config(channel=10)
import radio def get_serial_number(type=hex): NRF_FICR_BASE = 0x10000000 DEVICEID_INDEX = 25 # deviceid[1] @micropython.asm_thumb def reg_read(r0): ldr(r0, [r0, 0]) return type(reg_read(NRF_FICR_BASE + (DEVICEID_INDEX*4))) mx = 2 my = 2 bx = 0 by = 0 firetoggle = False radio.on() print("Go") while True: s = radio.receive() if s is not None: print(s[0],s[1],s[2]) sleep(10)
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) msg = radio.receive() if msg in ["on", "off"]: buttonStat = msg elif msg in ["listening", "waiting", "thinking", "talking"]: alexaStat = msg if buttonStat == "on": pin0.write_digital(1) else: pin0.write_digital(0) if alexaStat == "thinking": display.show(think[ticker%len(think)]) sleep(50) elif alexaStat == "talking": display.show(talk[ticker%len(talk)])
# NEW CODE HERE def time_500(): global time # needed to allow the function to affect the main 'time' variable on_the_moon() time = 500 # the time in miliseconds before the buggy will do the next command def time_1000(): global time on_the_moon() time = 1000 # NEW CODE ENDS time = 500 while True: message = radio.receive() if message is not None: if message == 'forward': display.show(Image.ARROW_N) drive(500, 500) elif message == 'left': display.show(Image.ARROW_W) drive(-500, 500) elif message == 'right': display.show(Image.ARROW_E) drive(500, -500) elif message == 'backward': display.show(Image.ARROW_S) drive(-500, -500) elif message == 'stop': display.show(Image.HAPPY)
from microbit import * import radio radio.on() # Radio paalle radio.config(channel=50) # valitse kanava valilta 0 -100 while True: display.clear() viesti = radio.receive() # haetaan radioviestia if viesti != None: display.show("!") pin0.write_digital(0) pin1.write_digital(0) pin2.write_digital(0) if viesti == "eteenpain": pin0.write_digital(1) elif viesti == "vasemmalle": pin1.write_digital(1) elif viesti == "oikealle": pin2.write_digital(1) else: display.show(".")
# 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)
from microbit import display, Image, sleep import radio radio.on() radio.config(channel=7) while True: msgin = radio.receive() if msgin == 'f': display.show(Image.ARROW_N) sleep(100) elif msgin == 'b': display.show(Image.ARROW_S) sleep(100) elif msgin == 'l': display.show(Image.ARROW_W) sleep(100) elif msgin == 'r': display.show(Image.ARROW_E) sleep(100) else: display.show("-") sleep(100)
# append each pixel in 5 x 5 grid to line of text. for x in range(5): for y in range(5): text = text + str(image.get_pixel(x, y)) # add in colon delimiters so microbit can # work out it's an image if x < 4: text = text + ":" return text radio.on() pic_to_send = Image("90909:09090:90909:09090:90909") while True: if button_a.was_pressed(): pic_as_text = convert_image_to_text(pic_to_send) radio.send(pic_as_text) received_pic_as_text = radio.receive() if received_pic_as_text: received_pic = Image(received_pic_as_text) display.show(received_pic) sleep(5000) display.clear()
temperature = tmp[3].split(":")[1].replace("[", "") light = tmp[4].replace("]", "") data = [temperature, light] return data def parsePassword(json): tmp = json[1:len(json) - 1] tmp = tmp.replace("\"", "") tmp = tmp.split(",") password = tmp[2].split(":")[1] return password def checkPassword(password): return password == NWK_IDFR while True: incomingJSON = radio.receive() if incomingJSON != None: parsePassword(incomingJSON) if checkPassword(parsePassword(incomingJSON)): add_text(0, 3, "vrai") order = parseData(incomingJSON)[0] if (order != DISP_ORD) and (order == "TL" or order == "LT"): DISP_ORD = order displayToScreen(DISP_ORD) radio.send(getJSONToSend())
from microbit import * import radio radio.on() while True: value = radio.receive() if value is not None: uart.write(str(value))
# Add your Python code here. E.g. from microbit import * import radio radio.on() radio.config(channel=72) radio.config(power=7) while True: #If shaken, send data temp = radio.receive() if temp: print(temp)
time = 2000 radio.on() radio.config(channel=9, address=0x12345678) directions = { "right": Image.ARROW_E, "for": Image.ARROW_N, "back": Image.ARROW_S, "left": Image.ARROW_W } direction = ["right", "left", "for", "back"] sent = False start_time, end_time = running_time(), running_time() while True: if sent == False: arrow = radio.receive() if arrow in direction: display.show(directions[arrow]) sleep(time) display.clear() radio.config(channel=9, address=0x87654321) radio.send(arrow) radio.config(channel=9, address=0x12345678) # sent = True time = max(int(time * 0.95), 650) start_time, end_time = running_time(), running_time() else: end_time = running_time() if end_time - start_time > 4000: time = 2000
# # Reading the value from the potentiometer (plugged on pin0) # value = pin0.read_analog() # # Receiving the acceleration data from the transmitter micro:bit # incoming_command = radio.receive() # if incoming_command == 'turn_left': # turn_left(value) # elif incoming_command == 'turn_right': # turn_right(value) # elif incoming_command == 'go_forward': # go_forward(value) # else: # meaning that incoming_command == 'go_backward' # go_backward(value) ## 0) Receiving the acceleration data from the transmitter micro:bit incoming_accel_data = radio.receive() # Simple "receive" test if incoming_accel_data == 'heart': display.clear() display.show(Image.HEART) sleep(1000) if incoming_accel_data: x_accel = float(incoming_accel_data.split(";")[0]) y_accel = float(incoming_accel_data.split(";")[1]) display.clear() display.show(Image.YES) ## 1) Orienting the buggy left and right desired_x_accel = 0 # (i.e. value of the x accel. when the transmitting micro:bit is horizontal)
def tohex(p): return ''.join(['%02x' % c for c in p]) # enable radio (RX) radio.on() # enable xn297 compatibility radio.cx() radio.config(channel=0x45) n = 0 start = 0 stop = 0 while True: pkt = radio.receive() if pkt is not None: if pkt[0] == 0x93: if n == 0: start = running_time() n += 1 if n == 50: stop = running_time() interval = (stop - start) / 50 print('interval: %0.2f' % interval) break print('done') while True: pass
###########################HOST################################## radio.on() ###Variables##################### count = 0 while True: ###Sender#################### if button_a.is_pressed(): count = 0 radio.send("Check") sleep(500) display.clear() ###Feedback################### incoming = radio.receive() if incoming == 'Feedback': count += 1 ###Count Check################ oled_add_text(4, 1, str(count) + '/' + str(totalno_people)) ###Count Status################ if count == totalno_people: pin0.write_digital(1) pin1.write_digital(0) else: pin0.write_digital(0) pin1.write_digital(1) sleep(100) needle = ((15 - compass.heading()) // 30) display.show(Image.ALL_CLOCKS[needle])
from quokka import * import radio import ubinascii np = neopixel.NeoPixel() radio.config(channel=15) radio.on() while True: msg = radio.receive() if msg: print(msg) msg_bytes = ubinascii.a2b_base64(msg) print(msg_bytes) for i in range(0, len(msg_bytes) - 3, 3): pixel = [int(c) for c in msg_bytes[i:i + 3]] np.set_pixel(i // 3, pixel[0], pixel[1], pixel[2]) np.show()
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
# function takes the transmission as an input, and converts it to a tuple # transmission is a string in the format [time, accx, accy, accz] # function splits the string at the commas and adds the four values to a list # it then converts the list to a tuple and plots it transmissionlist = transmission.split(',') list2 = [] for i in range(0, len(transmissionlist)): list2.append(float(transmissionlist[i])) transmissiontuple = tuple(list2) print(transmissiontuple) # MAIN SCRIPT print('Program Started') mb.display.show(mb.Image.HAPPY, delay=1000, clear=True) # Wait for start message before beginning printing incoming = '' while not incoming == 'start': incoming = radio.receive() mb.display.show(mb.Image.SQUARE) while True: incoming = radio.receive() # Read from radio if incoming is not None: # message was received plot(incoming) mb.display.show(mb.Image.HEART, delay=10, clear=True, wait=False) mb.display.show(mb.Image.CONFUSED) # shows transmission is finished
# 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)
from microbit import * import radio radio.on() radio.config(channel=16) # Choose your own channel number radio.config(power=7) # Turn the signal up to full strength # Event loop. while True: incoming = str(radio.receive()) print(incoming) sleep(200)
self.motor_left.write_analog(50) def stop(self): display.show(Image.HAPPY) for i in range(5): self.np[i] = (0, 0, 0) self.np.show() self.motor_right.read_digital() self.motor_left.read_digital() car = MoveMini() while True: sleep(25) direction = radio.receive() if direction == None: continue if direction == 'forward': car.forward() elif direction == 'backward': car.backward() elif direction == 'left': car.left() elif direction == 'right': car.right() else: car.stop()
def rec_loop(): # radio接收循环 while True: temp = radio.receive(True) # radio 接收数据,返回(msg,mac) # temp=radio.receive() # radio 接收数据,返回msg if temp: # 当接收到数据时打印 print(temp)
pin1.write_digital(0) # Capacitor: 3.3uF, Resistor: 15kO (I think, could be 10kO) # Signal resolution: 16, corresponds to about 5 on the RCX DELAY=1000 def setnum(n,m): # display.show(str(n)) pin1.write_analog(m) # sleep(DELAY) pin1.set_analog_period(1) while True: data = radio.receive() if data == 'None': continue if type(data) is not str: continue v = int(data.split(':')[0],16) b = (v & 1 == 1) v >>= 1 a = (v & 1 == 1) v >>= 1 z = v & 255 v >>= 8 y = v & 255 v >>= 8 x = v & 255
radio.send(k + name) print("Hello World - Klar på den serielle ", name) display.show(Image.HAPPY) sleep(2000) display.clear() radio.on() while True: # Forever - at least until power off/reset - generate events on USB or radio key_read_1 = read_key() sleep(50) # 2 readings with same to detect for removing worst jitter key_read_2 = read_key() if (key_read_1 == key_read_2) and (key_read_1 != last_key_sent): send_streng(key_read_1) if key_read_1 == "0": display.clear() else: display.show(key_read_1) last_key_sent = key_read_1 check_mode_shift() if local_connected: r = radio.receive() if r: print(r) if button_a.was_pressed(): print("A") if button_b.was_pressed(): print("B")
for j in range(15): oneLineAry[startx + j] = oneLineAry[startx + j + 1] oneLineAry[endx] = 0 def shiftByNeg1(inc): for i in range(16): endx = i * 16 + 15 for j in range(15): oneLineAry[endx - j] = oneLineAry[endx - j - 1] for i in range(16): startx = i * 16 oneLineAry[startx] = int(inc[i]) def draw2led(r, g, b): for i in range(0, 256): if oneLineAry[i] == 1: led1[getSPos(i)] = (r, g, b) else: led1[getSPos(i)] = black radio.on() while True: inc = radio.receive() if inc: draw2led(randint(0, 255), randint(0, 255), randint(0, 255)) led1.show() shiftByNeg1(str(inc))
from microbit import * import utime import radio #temperature rescale after calibration def rescaleTemp(temp): T_actual = 0.888*temp - 0.635 return round(T_actual) emptySign = Image('00000:' '00000:' '00000:' '00000:' '00000') #Switch radio on radio.on() display.scroll("ON") while True: messageIn = radio.receive() if messageIn == "MEASURE": tempActual = rescaleTemp(temperature()) lightLevel = display.read_light_level() messageOut = str(tempActual) + ',' + str(lightLevel) radio.send(messageOut) for loop in range(3): display.show(Image.ARROW_N) utime.sleep_ms(125) display.show(emptySign) utime.sleep_ms(125)
#======================== # Adjustments to avoid drift right_motor_adjustment = 5 left_motor_adjustement = 3 #======================== # Radio initialization radio.config(group=23) # The radio won't work unless it's switched on radio.on() ## Event loop while True: ## Receiving the measured distance from the first micro:bit incoming_measured_distance = radio.receive() if (not disable_program): # Checking that the received data from the radio is not None if incoming_measured_distance: incoming_measured_distance_float = float( incoming_measured_distance) ## 0) Go forward if state_forward_access and ( incoming_measured_distance_float < 0 or incoming_measured_distance_float > 10): state = 'going forward' ## Otherwise, entering the obstacle avoidance procedure
from microbit import * import radio radio.on() radio.config(length=64, queue=1, channel=5, power=7, data_rate=radio.RATE_1MBIT) dot_image = Image("00000:" "08880:" "08880:" "08880:" "00000:") dash_image = Image("00000:" "00000:" "88888:" "00000:" "00000:") while True: if button_a.was_pressed(): radio.send("DOT") elif button_b.was_pressed(): radio.send("DASH") else: data = radio.receive() if data == 'DOT': display.show(dot_image) sleep(200) display.clear() elif data == 'DASH': display.show(dash_image) sleep(200) display.clear()
def listen(): location = radio.receive() if location: play(location)
# Bitbot RC from microbit import * import radio bitbot = BitBot() bitbot.lights(20, 0, 20) sleep(move_duration) radio.on() while True: received = radio.receive() if received: if received == 'S': bitbot.stop() elif received == 'F': bitbot.headlights(50) bitbot.forward(50) elif received == 'B': bitbot.reversing_lights(50) bitbot.reverse(50) elif received == 'L': bitbot.blink_left(50) bitbot.circle_left(50) elif received == 'R': bitbot.blink_right(50) bitbot.circle_right(50)
from microbit import * import radio import music # Sæt radio op til at kommunikere på bestemt kanal - her 10 og tænd for radio så MB kan sende/modtage radio.config(channel=80) # Brug kanal som I har til den enkelte gruppe! radio.on() # For at identificere MB som hørende til opgave 6d - modtager delen! # Den er ikke på nogen måde afgørende for testen af modtagelse af 'signal' på radio. display.show("6d-M") sleep(1000) # Venter 1 sekund while True: heart_beat = radio.receive() if heart_beat: # Det samme som "heart_beat != None" - Betingelse "noget modtaget" vs "ingenting modtaget" music.pitch(440, 20) # Lyd i 20 ms med frekvens 440 når signal modtaget print("heart beat" ) # teksten "heart beat" i shell når radio signal er modtaget display.show(Image.HEART) # Hjerte vises i display på MB else: print("None") # Tekst "None" i shell når radio signal IKKE er modtaget music.stop( ) # Clear pin setting på music når signal ikke modtages. Har her ikke stor effekt display.clear() # Clear lokal display sleep( 100 ) # Pause på 100 ms - hvis den samme pause er i sender delen så kan de følges ad # og er sender og modtager 'helt' tæt på hinanden kommer der ingen 'Nones' i modtager.