Skip to content

Lists, buttons and Raspberry Pi with the microbit

ncscomputing edited this page Feb 21, 2016 · 6 revisions

This is my effort to help :) regards WarksRaspiJam

The first program you ever get started with is the obligatory "hello world". Here is my play on the classic. Entitled....

Hello world, hello...Dave

This does the basic hello world and says a hello to a few more people along the way using a basic list data structure to store the names, try it out:

Key concepts used here are:

  • Lists
  • Iteration
  • Index
  • Count controlled loops
  • Accessing values stored in a list
  • joining together string values
  • Casting

Code

import microbit

namesList = ["Dave","Fran","Beth"] #list of 3 names 

index = 0 # count of current location in the loop / list 

microbit.display.scroll("Hello World") # standard
while index <=2:
        msg = "Hello "+str(namesList[index]) # cherry on top :)
        microbit.display.scroll(msg)
        index = index +1

This is a test program

The second example uses the 'a' and 'b' buttons to print out messages to screen.

Testing out using the buttons try this code by creating a test program:

Code:

import microbit

while True:

    if microbit.button_a.is_pressed():
       microbit.display.scroll("This is a ...")

    if microbit.button_b.is_pressed():
       microbit.display.scroll("....test program")

Minecraft block Id and block name scroller.

This third program makes use of two lists and uses two lists to display some Minecraft block id's followed by the block name. It uses two lists and it prints out the values of each list after each loop/iteration through the list. Have a go a

Key concepts used here are:

  • Multiple lists
  • Iteration
  • Index
  • Infinite loops
  • Accessing values stored in two lists
  • Casting

Code

import microbit



BlockIdsList = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]



BlockNamesList = [

"Air",

"Stone",

"Grass",

"Dirt",

"Cobblestone",

"Wood Planks",

"Sapling",

"Bedrock",

"Water",

"Water Stationary",

"Lava flowing",

"Lava stationary",

"Sand",

"Gravel",

"Gold Ore",

"Iron Ore",

"Coal Ore",

"Wood",

"Leaves",]



Count = 0



while True:

    microbit.display.scroll(str(BlockIdsList[Count]))

    microbit.sleep(1000)

    microbit.display.scroll(str(BlockNamesList[Count]))

    Count = Count +1

    

    if Count == 19:

        Count = 0

    

Random nickname generator

The fourth example is a random nickname generator based on adjectives for body type and random names It uses the majority of the coding concepts previously looked at except it introduces the random.choice function

Code:

import microbit

import random

NameList = ["Dave","Frank","Dorothy","Roger","Tarquin","Simon","Melanie"]
BodyTypeAdjectiveList = ["Sturdy","Bullnecked","Gangling","Heavy-set","Lanky","Musclebound"]
while True: 
    RandomNickname = random.choice(BodyTypeAdjectiveList)+" "+random.choice(NameList)
    microbit.display.scroll(RandomNickname)

#Dice roller This simple dice simulation introduces the accelerometer and how to use it to randomly simulate a 6 sided dice.

##Code

from microbit import *
import random

DiceNumbers = [1,2,3,4,5,6]#List of 6 possible numbers

while True:
    if accelerometer.was_gesture('shake'):# if shaken then
    
        """create a string variable which puts out an intro message and joins it
        with a random number from the DiceNumbers list
        #cast the number to string so it can be displayed  
        """
        
        msg = "You rolled.. "+str(random.choice(DiceNumbers))
        display.scroll(msg)#show the text 
        

#Shake the bit, display a random picture This basically allows you to shake the microbit and this will randomly display one of the library of images. N.B. I have only implemented a few to give a brief idea :)

#Concepts covered:

  • Lists
  • Functions
  • Loops
  • Accelerometer
  • Random library *Conditional statements

##Code

from microbit import *
import random

"""
List of  possible pictures not sure if it is exhaustive, stored as string so they can be stored in a list
this process is called casting. 
"""
PicNamesList = [str(Image.SAD),str(Image.HEART),str(Image.MEH),str(Image.RABBIT),str(Image.COW)]

#other possible images I've not included as it is OTT for an example :)
#Image.DUCK, Image.SWORD, Image.GIRAFFE, Image.TARGET, Image.HOUSE, Image.TORTOISE, Image.UMBRELLA,
#Image.SNAKE, Image.SKULL, Image.BUTTERFLY, Image.TSHIRT, Image.XMAS, Image.STICKFIGURE,
#Image.MUSIC_CROTCHET, Image.CHESSBOARD, Image.YES, Image.NO, Image.CONFUSED, Image.ANGRY,
#Image.ARROW_N, Image.ARROW_S, Image.ARROW_E, Image.ARROW_W, Image.ARROW_SE]

"""
I have created a function that groups the code and makes the final program much cleaner
it basically:
*imports the list as a parameter
*creates a temp variable which stores the string representation of the image randomly selected 
*then uses if and elif statements to check which image it should display on microbit
"""

def checkWhichImageIAm(PicNamesList):
    chosenImage = random.choice(PicNamesList)
    if chosenImage == str(Image.SAD):
        display.show(Image.SAD)
    elif chosenImage == str(Image.HEART):
        display.show(Image.HEART)
    elif chosenImage == str(Image.MEH):
        display.show(Image.MEH)
    elif chosenImage == str(Image.RABBIT):
        display.show(Image.RABBIT)
    elif chosenImage == str(Image.COW):
        display.show(Image.COW)
    #you can implement every image if you want to....
    
    
while True:
    if accelerometer.was_gesture('shake'):# if shaken then
        checkWhichImageIAm(PicNamesList)# run check which image am I function