def PlayGame(): turn = 0 sequence = GetRandomSequence() userSequence = [0] * 100 seqlen = 0 playing = True played = False while playing == True: if turn == 0: # Just started Win() turn = turn + 1 if seqlen == 0 and played == False: # Sequence needs playing PlaySequence(turn, sequence) played = True elif seqlen == turn: # User has entered the sequence Win() played = False turn = turn + 1 seqlen = 0 else: # User still entering pattern for i in range(0, 4): if button_pins[i].read_digital() == 1: userSequence[seqlen] = i if userSequence[seqlen] != sequence[seqlen]: Loss() playing = False else: seqlen = seqlen + 1 led_pins[i].write_digital(1) music.pitch(notes[i], 500) led_pins[i].write_digital(0)
def updown(): for p in range(10, 1000, 10): pitch(p, wait=False) sleep(10) for p in range(1000, 10, -10): pitch(p, wait=False) sleep(10)
def run(self): ''' Eine Runde - Zufaellige Flugbahn - Ball hin - Check, ob getroffen - Ball zurueck ''' self.ball.current_trail = randint(0, 4) # Ball hin for self.ball.x in range(5): self.action() if self.ball.y != self.bat.y: # nicht getroffen. Game over return False else: music.pitch(880, 12) # ... und zurueck for self.ball.x in range(4, -1, -1): self.action() self.round += 1 # naechste Runde return True
def playmusic(): for i in range(0, len(musiclist), 1): display.show(str(musiclist[i])) music.pitch(round(round(tonelist[musiclist[i]])), PWM(Pin(27))) time.sleep_ms(round(500 * rhythmlist[i])) music.stop(PWM(Pin(27))) time.sleep_ms(10)
def lav_alarm(): # tilpas med lyd og billed/animation i MicroBit display som I synes det skal være # Test udskrift - som kan fjernes i endeligt produkt print("Nu er der alarm - Der er een som er kommet for tæt på") # Her vises sur smiley og en et lille beep med høj frekvens, som kører i baggrund display.show(Image.SAD) music.pitch(1000,500,wait=False)
def draw(self): """ Draw the player """ display.set_pixel(self.x, self.y, 9) if self.just_scored: music.pitch(400, 40)
def keyer(): buffer = '' #for di or dah sent started = running_time() #timer while True: waited = running_time() - started key_down_time = None while button_b.is_pressed() or pin2.is_touched( ): #button B keying or capacitive touch (tip: lick 2 fingers one on gnd one on pin 2) if not key_down_time: key_down_time = running_time() music.pitch(tone, -1, pin0, False) pin1.write_digital(1) while True: if not button_b.is_pressed() and not pin2.is_touched(): break music.stop() pin1.write_digital(0) key_up_time = running_time() if key_down_time: duration = key_up_time - key_down_time if duration < dah: buffer += '0' display.clear() display.set_pixel(2, 2, 9) elif duration: buffer += '1' display.show('-') started = running_time() elif len(buffer) > 0 and waited > dah: #or DASH_THRESHOLD = di * 5 character = decoder(int("0b1" + buffer, 2)) buffer = '' display.show(character) if tx: radio.send(character) else: menu(character) if waited > space * 2: return
def Win(): for i in range(0, 4): for j in range(0, 4): led_pins[j].write_digital(1) music.pitch(notes[j], 50) led_pins[j].write_digital(0) sleep(1000)
def playSiren(self): if self.doPlay: for freq in range(880, 1760, 16): music.pitch(freq, 6) for freq in range(1760, 880, -16): music.pitch(freq, 6) self.doPlay = False display.set_pixel(0, 0, 8)
def ding(): # 叮叮响 global touch_stat if touchPad_T.read() < 300 and touch_stat == 0: # 检测按键按下时,发出‘ding’响,并广播 music.pitch(500, 100, wait=False) # 播放"ding" radio.send('ding') # radio 广播 "ding" touch_stat = 1 elif touchPad_T.read() >= 300: touch_stat = 0
def tick(): global neues_jetzt, jetzt display.scroll(str(beruehrt) + str(jetzt)) neues_jetzt = running_time() // 1000 if jetzt > 0 and neues_jetzt > jetzt: jetzt = neues_jetzt music.pitch(440, 6)
def play(pom, img_1, img_2): music.stop() for p in melody: music.pitch(p) if pom: display.show(img_1) pom = False else: display.show(img_2) pom = True sleep(200)
def action(self): ''' Innere Spielschleife: Ball, Schlaeger, kurze Pause ''' display.clear() music.pitch(440, 6) self.ball.run() self.bat.run() print("Round:", self.round, "Ball:", self.ball.y, "Bat:", self.bat.y) sleep(400)
def scroll_walls(init=False): global scroll scroll -= 1 if scroll == 0 or init: scroll = scroll_def erase_aim() for y in range(4, 0, -1): for x in range(5): buf[y][x] = buf[y - 1][x] flash_buf[y] = flash_buf[y - 1] flash_buf[0] = 0 new_wall() if sound == 1: music.pitch(440, duration=16, wait=False)
def show_start_msg(): # Count down for start sending morse codes. COUNT_DOWN = ['3', '2', '1', Image.HAPPY] START_HINT = 'PRESS BUTTON A TO START' # show start hint and waiting to start signal display.scroll(START_HINT, wait=False, loop=True) while True: if button_a.was_pressed(): # count down for start sending morse code display.show(COUNT_DOWN, delay=1000) # beep for start music.pitch(880, 300) break
def alarm(enable): """闹钟事件""" rgb.brightness(0.1) oled.fill_rect(80,32,128-80,16,0) if enable: music.play(music.MO_LI_HUA ,wait=False,loop=True) rgb.fill((100,0,0)) rgb.write() oled.DispChar("时间到",80,32,2) oled.show() else: music.pitch(0) rgb.fill((0,0,0)) rgb.write()
def fx(length_ms, pitch, delta_pitch, steps_count): """Produce sound effect shifting pitch by delta_pitch in steps_count steps""" end_time = round(microbit.running_time() + length_ms) step_length_ms = round(length_ms / steps_count) while microbit.running_time() < end_time: if pitch > 0: music.pitch(round(pitch)) microbit.sleep(step_length_ms) pitch += delta_pitch steps_count -= 1 music.stop()
def Keyer(): buffer = '' message = '' started = running_time() while True: waited = running_time() - started key_down_time = None while button_b.is_pressed(): ## button B keying if not key_down_time: key_down_time = running_time() music.pitch(sidetone, -1, pin0, False) pin1.write_digital(1) while True: if not button_b.is_pressed(): music.stop() pin1.write_digital(0) break while pin2.is_touched(): ## touch keying if not key_down_time: key_down_time = running_time() music.pitch(sidetone, -1, pin0, False) pin1.write_digital(1) while True: if not pin2.is_touched(): music.stop() pin1.write_digital(0) break key_up_time = running_time() if key_down_time: duration = key_up_time - key_down_time if duration < DOT_THRESHOLD: buffer += '.' display.show(DOT) elif duration: buffer += '-' display.show(DASH) started = running_time() elif len(buffer) > 0 and waited > DASH_THRESHOLD: display.clear() character = decodemorse.get(buffer, '?') buffer = '' display.show(character) if txenabled: radio.send(character) message += character if waited > WORD_THRESHOLD * 2: return
def compassOutput(compassDir, directionDeg, pitch, displayChars): global compassTotal global pitchDuration #North has to be treated differently due to being greater than 0 and less than 360 if directionDeg == 0: if compassDir > 315: pitchChange = pitch - (360 - compassDir) else: pitchChange = pitch - compassDir else: if compassDir > (directionDeg - 45) and compassDir <= directionDeg: pitchChange = pitch - (directionDeg - compassDir) else: pitchChange = pitch - (compassDir - directionDeg) display.show(displayChars) music.pitch(pitchChange, 50)
def handle_run_state(): global state, mins, secs, last_tick_time if button_b.was_pressed(): state = SET display_mins(mins) time_now = running_time() if time_now > last_tick_time + 5000: last_tick_time = time_now secs -= 5 if secs < 0: secs = 55 mins -= 1 display_time(mins, secs) if mins == 0 and secs == 0: state = ALARM music.pitch(440, wait=False) display.show(Image.HAPPY)
def rest(seconds): display.show([x / 9 for x in Image.ALL_CLOCKS], delay=(seconds * 1000) // 12, wait=False) for i in range(1, seconds + 1): if i % 15 == 0: pitch = 900 elif i % 2 == 0: pitch = 600 else: pitch = 800 music.pitch(pitch, 50) sleep(1000 - 50) music.play(music.POWER_UP)
def playMorse(*binarycw): for x in binarycw: for i in x: if i == 1: sleep(space) pattern = bin(i)[3:] for c in pattern: if c == "0": display.set_pixel(2, 2, 9) pin1.write_digital(1) music.pitch(tone, di) elif c == "1": display.show("-") pin1.write_digital(1) music.pitch(tone, dah) display.clear() pin1.write_digital(0) sleep(di) sleep(dah)
def FlashMorse(pattern): for c in pattern: if c == ".": display.show(DOT) pin1.write_digital(1) music.pitch(sidetone, dotlength) display.clear() pin1.write_digital(0) sleep(interelement) elif c == "-": display.show(DASH) pin1.write_digital(1) music.pitch(sidetone, dashlength) display.clear() pin1.write_digital(0) sleep(interelement) elif c == " ": sleep(interletter) return
def main(): threshold = 1000 * 60 * 6 #threshold = 1000 * 30 start = utime.ticks_ms() while True: now = utime.ticks_ms() seconds = now // 1000 if seconds % 2 == 0: display.show(Image.CLOCK3) else: display.show(Image.CLOCK9) beep1 = utime.ticks_ms() beep2 = beep1 + 200 while utime.ticks_diff(now, start) > threshold: buzz_start = now display.show(Image.HEART) # beep if utime.ticks_diff(utime.ticks_ms(), beep1) > 0: music.pitch(1760, 100, wait=False) beep1 = beep1 + 2000 # beep if utime.ticks_diff(utime.ticks_ms(), beep2) > 0: music.pitch(1760, 100, wait=False) beep2 = beep2 + 2000 # button if button_a.is_pressed(): action = utime.ticks_ms() spend = utime.ticks_diff(action, buzz_start) display.scroll(str(spend)) if spend < 3000: threshold = 1000 * 60 * 6 else: threshold = 1000 * 60 * 3 #if spend < 3000: threshold = 1000 * 30 #else: threshold = 1000 * 10 start = utime.ticks_ms() break sleep(1000)
def sonic(f=3000, fstep=32, fdepth=100, ton=10, toff=0, duration=2000): # from sonic screwdriver, written by D.J.Whale for BBC Doctor Who. # first surfaced in "mission sonic' in April 2017. try: ft = f music.pitch(ft) st = running_time() while running_time() < st+duration: sleep(ton) if toff != 0: music.stop() sleep(toff) fn = ft + fstep if fn >= f + fdepth: fstep *= -1 fn = f + fdepth elif fn <= f - fdepth: fstep *= -1 fn = f - fdepth if fn != ft: ft = fn music.pitch(int(ft)) finally: music.stop()
from microbit import * import music lives = 3 display.show(str(lives)) while lives > 0: if pin1.read_digital(): display.show(Image.SAD) music.pitch(200, 800) lives -= 1 display.show(str(lives)) SKULL = [ '09990', '90909', '99999', '09990', '09990', ] for i in range(5): display.show(Image(":".join(["00000"] * (4 - i) + SKULL[:i + 1]))) sleep(500) music.play(music.FUNERAL) brightness = 9 direction = -1 while True: if brightness == 1: direction = +1
while True: v = pin2.read_analog() if v < ACTION_VALUE: l,r = True, True elif v < VOLUMEUP_VALUE: l,r = False, True elif v < VOLUMEDOWN_VALUE: l,r = True, False else: l,r = False, False if l != prev_l: prev_l = l if l: music.pitch(PITCH, pin=pin0) display.set_pixel(0,2,9) else: display.set_pixel(0,2,0) music.stop(pin0) if r != prev_r: prev_r = r if r: display.set_pixel(4,2,9) music.pitch(PITCH, pin=pin1) else: display.set_pixel(4,2,0) music.stop(pin1)
def __init__ (self, freq, duration): music.pitch(freq, duration) sleep(50)
def soundAlarm(): for i in range(0, 4): music.pitch(freq * i, 100) display.show(Image.ANGRY)
def accel(): while not button_a.is_pressed(): p = abs(accelerometer.get_z()) pitch(p, wait=False) sleep(10)
def test_rapid_pitch_switch(): for i in range(20): for freq in FREQS: music.pitch(freq, wait=False)
if low_range == True: frequency = int( (wide_frequency * 0.33) + ( 0 * range_factor ) ) elif high_range == True: frequency = int( (wide_frequency * 0.33) + ( 2 * range_factor ) ) else: frequency = int( (wide_frequency * 0.33) + ( 1 * range_factor ) ) # calculate a good duration acc_y = accelerometer.get_y() # normalise Y value (duration) if acc_y >= upper_bound: acc_y = upper_bound elif acc_y <= lower_bound: acc_y = lower_bound duration = acc_y + upper_bound div_factor = 2000 / max_duration duration = math.ceil(duration / div_factor) music_duration = max(duration, min_duration) gesture = accelerometer.current_gesture() if gesture == "face down": music.pitch(frequency, music_duration)
def beep(): music.pitch(1760, 100) sleep(200) music.pitch(1760, 100) sleep(200)
# ===================== # Save previous ball "x,y" location oldBallX = ballX oldBallY = ballY ballY = ballY + ballDirection # Case where paddle hit ball if ballY == 7 and padX == ballX: npPlot2(oldBallX, oldBallY, black) # Turn-off LED at old ball location npPlot2(ballX, ballY, colors[1]) # On hit, paint ball green np.show() # Use two short beeps at high pitch to indicate a "hit" music.pitch(880, 100) sleep(50) music.pitch(990, 100) ballDirection *= -1 hitCount += 1 # Increment score if hitCount >= numScores: # When you have "numScores" hits you win! gameOn = False continue # Case where paddle missed ball elif ballY == 7 and padX != ballX: npPlot2(oldBallX, oldBallY, black) # Turn-off LED at old ball location npPlot2(ballX, ballY, colors[0]) # On miss, paint ball red np.show()
else: # off if value == 0x00: buildingbit.car_HeadRGB(0, 0, 0) # up elif value == 0x80: buildingbit.car_run(speed, speed, 0) # light elif value == 0x40: buildingbit.car_HeadRGB(255, 255, 255) # left elif value == 0x20: buildingbit.car_left(speed, 0) # buzzer elif value == 0xa0: music.pitch(698) sleep(400) music.stop() # right elif value == 0x60: buildingbit.car_right(speed, 0) # spinleft elif value == 0x10: buildingbit.car_spinleft(speed, speed, 0) # down elif value == 0x90: buildingbit.car_back(speed, speed, 0) # spinright elif value == 0x50: buildingbit.car_spinright(speed, speed, 0) # +
# Holds the translated Morse as normal text. message = '' # The time from which the device has been waiting for the next keypress. started_to_wait = running_time() # Put the device in a loop to wait for and react to key presses. while True: # Work out how long the device has been waiting for a keypress. waiting = running_time() - started_to_wait # Reset the timestamp for the key_down_time. key_down_time = None # If button_a is held down, then... while button_a.is_pressed(): # Play a beep - this is Morse code y'know ;-) music.pitch(880, 10) # ...and if there's not a key_down_time then set it to now! if not key_down_time: key_down_time = running_time() # Get the current time and call it key_up_time. key_up_time = running_time() # If there's a key_down_time (created when button_a was first pressed # down). if key_down_time: # ... then work out for how long it was pressed. duration = key_up_time - key_down_time # If the duration is less than the max length for a "dot" press... if duration < DOT_THRESHOLD: # ... then add a dot to the BUFFER containing incoming Morse codes # and display a dot on the display. buffer += '.'
# 4b - mag felt til lyd.py # Omsæt magnet felt styrke til lyd (pitch) Version 1.1 0-nov-2020 # Først importeres det generelle microbit bibliotek (for at nå compass() funktionen) # og music (for at nå music.pitch() funktionen) from microbit import * import music # Da felt styrken ser ud til at kunne nå op til ca. 2.5 mill og altid er positiv # divideres med 1000 for at ramme indenfor det som pitch kan håndtere. # MEN skal desuden få det til at være et heltal og ved normal division (/) får vi decimaler. # - derfor bruges funktionen int() til at konvertere til heltal. # Adderer 50 til for at vi kan høre det. while True: x = compass.get_field_strength() print(x) music.pitch( int(x / 1000) + 50 ) # Kan også bruge floor division // - Se python aritmetiske operatorer sleep(100)
durationlen = len(note_durations) notelen = len(notes) duration = 100 play_music = True while True: #get accelerometer readings xreading = abs(accelerometer.get_x()) yreading = abs(accelerometer.get_y()) #use a to toggle music if button_a.was_pressed(): play_music = not play_music if not play_music: continue #get a note based on tilt note = xreading*.01 pitch = notes[int(note)%notelen] #if b is pressed, alter the length based on tilt if button_b.is_pressed() == 1: #pitch *= .5 duration = note_durations[int(yreading*0.01)%durationlen] #play our sound! music.pitch(int(pitch), duration)
import music from microbit import accelerometer buckets = [ 262, # C 294, # D 330, # E 392, # G 440, # A ] while True: reading = abs(accelerometer.get_x()) bucket = min(4, max(0, reading // 200)) # quantize! music.pitch(buckets[bucket], 20)
# ... and cycle through them on the display. pause = 1000 for img in images: display.show(img) sleep(pause) pause -= 50 if pause < 100: pause = 100 display.clear() # Aural testing of the accelerometer. display.scroll("Accelerometer") display.show("X") while not button_a.is_pressed(): music.pitch(abs(accelerometer.get_x()), 20) sleep(500) display.show("Y") while not button_a.is_pressed(): music.pitch(abs(accelerometer.get_y()), 20) sleep(500) display.show("Z") while not button_a.is_pressed(): music.pitch(abs(accelerometer.get_z()), 20) # Aural testing of the compass. display.scroll("Compass") compass.calibrate() while not button_b.is_pressed(): music.pitch(abs(compass.heading()), 20)