Tuesday, 25 April 2017
GPIO zero Minecraft "Whack on board Led's"
This code uses Minecraft to turn on the on board leds by whacking either a TNT block or Glass block. It uses GPIO zero.
To find out about Gpio zero go here:
https://gpiozero.readthedocs.io/en/stable/notes.html#how-can-i-tell-what-version-of-gpiozero-i-have-installed
1. In Minecraft lay a TNT block, glass block and grass block.
2. Open the below code in Python 3.
3. Run the code below
4. Whack the one of the blocks and you should see some action with one of the on board LED's.
TNT turns on the red light
Grass turns on the green light
Glass is random
Code
#import minecraft libraries
import mcpi.minecraft as minecraft
import mcpi.block as block
#import gpio and time
from gpiozero import LED
from time import sleep
import random
mc = minecraft.Minecraft.create()
mc.postToChat("Turn on your Pi lights with MCPI and GPIO zero")
LightList= ["R","L"]
red = LED(35)
green = LED(47)
def RedOnMCPI(msg,time):
mc.postToChat(msg)
red.on()
sleep(time)
red.off()
def GreenOnMCPI(msg,time):
mc.postToChat(msg)
green.on()
sleep(time)
green.off()
def RandomLight():
for i in range(0,6):
light = random.choice(LightList)
if light == "R":
RedOnMCPI("Red",1)
if light == "L":
GreenOnMCPI("Green",1)
while True:
evs = mc.events.pollBlockHits()
for e in evs:
pos = e.pos
b = mc.getBlock(pos.x,pos.y,pos.z)
if b == 46:#tnt
RedOnMCPI("Red",1)
elif b == 2:#Grass
GreenOnMCPI("Green",1)
elif b == 20:#Glass
RandomLight()
Thursday, 20 April 2017
CPC UCreate Micro:bit resources all in one place
Over the last week I have compiled together all of the Micro:bit resources that I made last summer for CPC using Micro:bits.
Here is the full list:
Blog 1: http://warksjammy.blogspot.com/2017/04/what-can-ucreate-with-microbit-and-neo.html
Blog 2: http://warksjammy.blogspot.com/2017/04/blog-2-what-can-ucreate-with-microbit.html
Blog 3: http://warksjammy.blogspot.com/2017/04/blog-2-what-can-ucreate-with-microbit_17.html
Blog 4: http://warksjammy.blogspot.com/2017/04/blog-4-what-can-ucreate-with-microbit.html
Blog 5: http://warksjammy.blogspot.com/2017/04/blog-5-what-can-ucreate-with-microbit.html
Blog 6: http://warksjammy.blogspot.com/2017/04/blog-6-what-can-ucreate-with-microbit.html
Blog 7: http://warksjammy.blogspot.com/2017/04/blog-7-what-can-ucreate-with-microbit.htm
Blog 8: http://warksjammy.blogspot.com/2017/04/blog-8-what-can-ucreate-with-microbit_17.html
Here is the master file with all the above resources in all of which feature above:
Master file https://github.com/ncscomputing/Hackpack/raw/master/Microbit%20lessons%20v18.pdf
You can go and buy a Micro:bit project kit from here: http://cpc.farnell.com/bbc-micro-bit-kits
Here is the full list:
Blog 1: http://warksjammy.blogspot.com/2017/04/what-can-ucreate-with-microbit-and-neo.html
Blog 2: http://warksjammy.blogspot.com/2017/04/blog-2-what-can-ucreate-with-microbit.html
Blog 3: http://warksjammy.blogspot.com/2017/04/blog-2-what-can-ucreate-with-microbit_17.html
Blog 4: http://warksjammy.blogspot.com/2017/04/blog-4-what-can-ucreate-with-microbit.html
Blog 5: http://warksjammy.blogspot.com/2017/04/blog-5-what-can-ucreate-with-microbit.html
Blog 6: http://warksjammy.blogspot.com/2017/04/blog-6-what-can-ucreate-with-microbit.html
Blog 7: http://warksjammy.blogspot.com/2017/04/blog-7-what-can-ucreate-with-microbit.htm
Blog 8: http://warksjammy.blogspot.com/2017/04/blog-8-what-can-ucreate-with-microbit_17.html
Here is the master file with all the above resources in all of which feature above:
Master file https://github.com/ncscomputing/Hackpack/raw/master/Microbit%20lessons%20v18.pdf
You can go and buy a Micro:bit project kit from here: http://cpc.farnell.com/bbc-micro-bit-kits
Monday, 17 April 2017
Blog 8: What can "UCreate" with a Micro:bit and Micro python basics
This is the last one :)
Last summer I created some resources to use with Micro:bit/s for CPC and over the next few months and I will try and share the best bits with the kind permission of CPC.
You can go and buy a Micro:bit project kit from here: http://cpc.farnell.com/bbc-micro-bit-kits
Here are a series of basic micro python challenges to try out on the Micro:bit, enjoy!
Challenge 1 Hello world, hello mum!
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 = ["Nanny June","Daddy","Mum"] #list of 3 names
index = 0
microbit.display.scroll("Hello World") #message
while index <=2:
msg = "Hello "+str(namesList[index])
microbit.display.scroll(msg)
index = index +1
Challenge 2 using buttons
This challenge is a basic example of getting the Micro:bit to respond to buttons ‘A’ and ‘B’ being pressed. 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")
Challenge 3 Random Name scroller
This third program makes use of two lists and uses two lists to display a random name made up of a randomly selected first name then a randomly selected second name.
Key concepts used here are:
- Multiple lists
- Infinite loops
- Accessing values stored in two lists
Code
import microbit
import random
RandomFirstName = ["Steve","Shannon","Jenny"]
RandomSecondName = ["Debank","Green","Penny","Smith"]
while True:
microbit.display.scroll(random.choice(RandomFirstName)
microbit.sleep(1000)#wait 1 sec
microbit.display.scroll(random.choice(RandomSecondName))
microbit.sleep(1000)#wait 1 sec
Challenge 4 Shake it 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 shake.
Code:
from microbit import *
import random
NameList = ["Paul","Dave","Gem","Rachel","Chris"]
BodyTypeAdjectiveList = ["Sturdy","Bullnecked","Gangling","Heavyset","Lanky","Musclebound"]
while True:
if accelerometer.was_gesture('shake'):# if shaken then
RandomNickname = random.choice(BodyTypeAdjectiveList)+" "+random.choice(NameList)
display.scroll(RandomNickname)
Challenge 5 shake it, 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
msg = "You rolled.. "+str(random.choice(DiceNumbers))
display.scroll(msg)#show the text
Challenge 6 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)]
"""
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)
while True:
if accelerometer.was_gesture('shake'):# if shaken then
checkWhichImageIAm(PicNamesList)# run check which image am I function
That's it!
Blog 7: What can "UCreate" with a Micro:bit and a Rasperry Pi 3 (Minecraft random radio bounce)
Last summer I created some resources to use with Micro:bit/s for CPC and over the next few months and I will try and share the best bits with the kind permission of CPC.
You can go and buy a Micro:bit project kit from here: http://cpc.farnell.com/bbc-micro-bit-kits
This one uses the Micro:bit and Raspberry Pi. The Micro:bit uses a serial connection to the Pi to send data. The credit for this goes to Martin O'Hanlon and David Whale.
This builds on the previous blog:
http://warksjammy.blogspot.co.uk/2017/04/blog-6-what-can-ucreate-with-microbit.html
Here is a picture of the set up
Here is the updated version of the code the two Micro:bits:
Code to go on Python on the Pi
Python 2.7 needs to be used
You can go and buy a Micro:bit project kit from here: http://cpc.farnell.com/bbc-micro-bit-kits
This one uses the Micro:bit and Raspberry Pi. The Micro:bit uses a serial connection to the Pi to send data. The credit for this goes to Martin O'Hanlon and David Whale.
This builds on the previous blog:
http://warksjammy.blogspot.co.uk/2017/04/blog-6-what-can-ucreate-with-microbit.html
Which created random bouncing Minecraft character triggered by a Micro:bit. This extends this by using two Micro:bits one remains connected to the Pi and listens for messages from the second Micro:bit which runs off batteries. If you press "a" on the battery run Micro:bit then it sends a message via the radio module. The Pi connected Micro:bit then receives the message and then sends the message to the Python script through the serial connection. In a nutshell its a radio controlled bouncing character.
Here is a picture of the set up
Here is the updated version of the code the two Micro:bits:
from microbit import*
import random
import radio
radio.on()
REFRESH = 500
JumpStatus =
["Jump","Donotjump"]
def get_data():
if button_a.is_pressed():
a = random.choice(JumpStatus)
radio.send(random.choice(JumpStatus)) # a-ha
def run():
while True:
sleep(REFRESH)
get_data()
# Read any incoming messages.
incoming = radio.receive()
if incoming == 'Jump':
display.scroll("Jump")
print('Jump')
elif incoming == 'Donotjump':
display.scroll("Do not
jump")
print('Donotjump')
#display.show('J')
run()
Code to go on Python on the Pi
Python 2.7 needs to be used
"""
Code written by Martin O'Hanlon in
the following blog post:
http://www.stuffaboutcode.com/2016/03/microbit-get-data-from-usb.html
edited by @warksraspijam
"""
import time
import serial
from mcpi.minecraft import Minecraft
from time import sleep
from mcpi import block as block
import random
PORT = "/dev/ttyACM0"
BAUD = 115200
s = serial.Serial(PORT)
s.baudrate = BAUD
s.parity = serial.PARITY_NONE
s.databits = serial.EIGHTBITS
s.stopbits = serial.STOPBITS_ONE
#read the first line and flush any
bad data
s.readline()
def read_microbit_data():
#read a line from the microbit,
data = s.readline()
data_s = data.rstrip().split(" ")
JumpStatus = data_s[0]
print JumpStatus
return JumpStatus
mc = Minecraft.create()
try:
playerPos = mc.player.getTilePos()
while True:
JumpStatus = read_microbit_data()
if JumpStatus == "Jump":
pos = mc.player.getPos()
#change this to teleport
mc.player.setPos(random.randint(-100,100),
random.randint(1,45),random.randint(-100,100))
msg = JumpStatus
mc.postToChat(msg)
finally:
sleep(1)
s.close()Blog 6: What can "UCreate" with a Micro:bit and a Rasperry Pi 2 (Minecraft random serial bounce)
Last summer I created some resources to use with Micro:bit/s for CPC and over the next few months and I will try and share the best bits with the kind permission of CPC.
You can go and buy a Micro:bit project kit from here: http://cpc.farnell.com/bbc-micro-bit-kits
This one uses the Micro:bit and Raspberry Pi. The Micro:bit uses a serial connection to the Pi to send data. The credit for this goes to Martin O'Hanlon and David Whale.
The Micro:bit sends messages to the Pi when the "a" button is pressed, which then interprets that instruction and randomly bounces the Minecraft character to a random height.
Here is a picture of the set up
Here is the code for the Micro:bit:
Python code to go on the Raspberry Pi
You can go and buy a Micro:bit project kit from here: http://cpc.farnell.com/bbc-micro-bit-kits
This one uses the Micro:bit and Raspberry Pi. The Micro:bit uses a serial connection to the Pi to send data. The credit for this goes to Martin O'Hanlon and David Whale.
The Micro:bit sends messages to the Pi when the "a" button is pressed, which then interprets that instruction and randomly bounces the Minecraft character to a random height.
Here is a picture of the set up
Here is the code for the Micro:bit:
Written by David Whale and Martin
O’Hanlon edited by Chris Penn
from microbit import*
import random
REFRESH = 500
Message = "Bounce"
def get_data():
yValue = random.randint(2,20)
a, b = button_a.was_pressed(), button_b.was_pressed()
print(a, b, Message, yValue )
def run():
while True:
sleep(REFRESH)
get_data()
if button_a.is_pressed():
display.scroll(Message)
run()
|
Python code to go on the Raspberry Pi
N.b. This needs to be run in Python 2.7
"""
Code written by Martin O'Hanlon in the following blog post:
http://www.stuffaboutcode.com/2016/03/microbit-get-data-from-usb.html
"""
import time
import serial
from mcpi.minecraft import
Minecraft
from time import sleep
from mcpi import block as block
import random
PORT = "/dev/ttyACM0"
BAUD = 115200
s = serial.Serial(PORT)
s.baudrate = BAUD
s.parity = serial.PARITY_NONE
s.databits = serial.EIGHTBITS
s.stopbits = serial.STOPBITS_ONE
#read the first line and flush any
bad data
s.readline()
def read_microbit_data():
#read a line from the microbit,
data = s.readline()
#split the microbit data into x, y, z, a, b
data_s = data.rstrip().split(" ")
a = True if data_s[0] == "True" else False
b = True if data_s[1] == "True" else False
Message = data_s[2]
yValue = data_s[3]
return a,b,Message,yValue
mc = Minecraft.create()
try:
playerPos = mc.player.getTilePos()
while True:
a,b,Message,yValue =
read_microbit_data()
if a == True:
pos = mc.player.getPos()
mc.player.setPos(pos.x,yValue,pos.z)
msg = Message+""+yValue
mc.postToChat(msg)
finally:
sleep(1)
s.close()
|
Instructions
1. Having flashed your Micro:bit script and leaving your Micro:bit plugged into your Pi.
2. Open Minecraft, create a new world, ensure you can see the character like in the picture above, minimise the screen.
3. Run the Python code in 2.7 from above.
4. Press the A button on the Micro:bit, look at Minecraft and you should see the character jump up at a random height between 1 and 20!
5. Try it again.
Enjoy!
Why not try and extend the Python code to Teleport Steve
Updated Python code needs to be run in Python 2.7
Updated code is in red
import time
"""
Code written by Martin O'Hanlon in
the following blog post:
http://www.stuffaboutcode.com/2016/03/microbit-get-data-from-usb.html
"""
import serial
from mcpi.minecraft import
Minecraft
from time import sleep
from mcpi import block as block
import random
PORT = "/dev/ttyACM0"
BAUD = 115200
s = serial.Serial(PORT)
s.baudrate = BAUD
s.parity = serial.PARITY_NONE
s.databits = serial.EIGHTBITS
s.stopbits = serial.STOPBITS_ONE
#read the first line and flush any
bad data
s.readline()
def read_microbit_data():
#read a line from the microbit,
data = s.readline()
#split the microbit data into x, y, z, a, b
data_s = data.rstrip().split(" ")
a = True if data_s[0] == "True" else False
b = True if data_s[1] == "True" else False
Message = data_s[2]
yValue = data_s[3]
return a,b,Message,yValue
mc = Minecraft.create()
try:
playerPos = mc.player.getTilePos()
while True:
a,b,Message,yValue =
read_microbit_data()
if a == True:
pos = mc.player.getPos()
#change this to teleport
mc.player.setPos(random.randint(-100,100),
yValue,random.randint(-100,100))
msg = Message+""+yValue
mc.postToChat(msg)
finally:
sleep(1)
s.close()
|
Blog 5: What can "UCreate" with a Micro:bit and a Rasperry Pi 1 (Minecraft Pi and Micro:bit TNT roulette )
Last summer I created some resources to use with Micro:bit/s for CPC and over the next few months and I will try and share the best bits with the kind permission of CPC.
You can go and buy a Micro:bit project kit from here: http://cpc.farnell.com/bbc-micro-bit-kits
This project uses the Micro:bit serial connection with the Pi to randomly send 1 or 0 through the serial connection to tell the Pi based python script whether or not to lay an active TNT block or inactive TNT block. Thus it is called TNT roulette. :)
Picture of set up of Micro:bit plugged into the Pi
You can go and buy a Micro:bit project kit from here: http://cpc.farnell.com/bbc-micro-bit-kits
This project uses the Micro:bit serial connection with the Pi to randomly send 1 or 0 through the serial connection to tell the Pi based python script whether or not to lay an active TNT block or inactive TNT block. Thus it is called TNT roulette. :)
Picture of set up of Micro:bit plugged into the Pi
Instructions
You will need to have a Raspberry Pi and Micro:bit for this
to work. You will need to install MU on the Raspberry Pi to flash the micro python script. You will need to keep the Micro:bit plugged into the Pi usb port.
Here is the micro python script for the Micro:bit:
#Written by David Whale and Martin
O’Hanlon edited by Chris Penn
from microbit import*
import random
REFRESH = 500
BlockID = 46
ActiveValues = [0,1] # 0 = off
def get_data():
a, b = button_a.was_pressed(), button_b.was_pressed()
Active = random.choice(ActiveValues)
print(a, b, BlockID,Active)
def run():
while True:
sleep(REFRESH)
get_data()
display.show('M')
run()
Python code to go on the Raspberry Pi
N.b. This needs to be run in Python 2.7
"""
Code written by Martin O'Hanlon in
the following blog post:
http://www.stuffaboutcode.com/2016/03/microbit-get-data-from-usb.html
I have added a few bits on top
"""
import serial
from mcpi.minecraft import
Minecraft
from time import sleep
from mcpi import block as block
import random
PORT = "/dev/ttyACM0"
BAUD = 115200
s = serial.Serial(PORT)
s.baudrate = BAUD
s.parity = serial.PARITY_NONE
s.databits = serial.EIGHTBITS
s.stopbits = serial.STOPBITS_ONE
#read the first line and flush any
bad data
s.readline()
def read_microbit_data():
#read a line from the microbit,
data = s.readline()
#split the microbit data into x, y, z, a, b
data_s = data.rstrip().split(" ")
a = True if data_s[0] == "True" else False
b = True if data_s[1] == "True" else False
BlockID = int(data_s[2])
Active = int(data_s[3])
return a,b,BlockID,Active
mc = Minecraft.create()
try:
playerPos = mc.player.getTilePos()
while True:
a,b,BlockID, Active =
read_microbit_data()
if a == True:
pos = mc.player.getPos()
msg = "Button pressed =
",str(a),"+ Block ID = ",BlockID," + ",
"Active=",Active
mc.postToChat(msg)
mc.setBlock(pos.x,pos.y,pos.z,BlockID,Active)
finally:
sleep(1)
s.close()
|
Instructions
1. Having flashed your Micro:bit script and leaving your Micro:bit plugged into your Pi.
2. Open Minecraft, create a new world, ensure you can see the character like in the picture above, minimise the screen.
3. Run the Python code in 2.7 from above.
4. Press the A button on the Micro:bit, look at Minecraft and you should see a TNT block has been dropped. Whack it to see if it is active or not!
Enjoy!
Blog 4: What can "UCreate" with a Micro:bit and Neo-pixels (Radio activated lights V1)
Last summer I created some resources to use with Micro:bit/s for CPC and over the next few months and I will try and share the best bits with the kind permission of CPC.
This one uses Micropython and a neopixel again. The neopixel is from this kit:
The picture below shows how the Micro:bit is set up, This time it uses the radio module to light up an neo-pixel on another Micro:bit, after one of the buttons is pressed.
Instructions
You
will need to code the Micro:bit with MU either on a PC/ MAC or Linux machine.
At the time of writing the BBC website will not allow the radio module to work.
This program uses the radio on the
Micro:bit to send messages to trigger neo-pixels on other Micro:bits. The radio
code here is taken from the demo by N Toll on the Micro:bit read the docs
website.
You will need at least two
Micro:bits in order to see it working, both Micro:bits will need the same code
loaded onto each one.
Code to go on each Micro:bit:
from microbit import *
import neopixel
np = neopixel.NeoPixel(pin0,1)
import radio
import random
#import neopixel
#from microbit import display,
Image, button_a, sleep
#np = neopixel.NeoPixel(pin0,1)
def Angry():
np[0] = (255,0,0)#Red
np.show()
display.show(Image.ANGRY)
sleep(3000)
display.clear()
np.clear()
def Happy():
np[0] = (0,255,0)#Green
np.show()
display.show(Image.HAPPY)
sleep(3000)
display.clear()
np.clear()
def Meh():
np[0] = (255,69,0)#Yellow
np.show()
display.show(Image.MEH)
sleep(3000)
display.clear()
np.clear()
radio.on()
while True:
FeelingsList = ['Angry','Meh','Happy']
# Button A sends a "flash" message.
emo = random.choice(FeelingsList)
if button_a.was_pressed():
radio.send(emo) # a-ha
# Read any incoming messages.
incoming = radio.receive()
if incoming == 'Meh':
Meh()
elif incoming == 'Happy':
Happy()
elif incoming == 'Angry':
Angry()
|
Subscribe to:
Posts (Atom)