Wednesday, 13 September 2017

Micro:bit and the neo pixel strip / Codebug colour star

I have 5 codebug colour stars and one code bug. But I have access to many Micro:bits through work. Here is how to connect the codebug colour star to a MIcro:bit.

You will need:


  • A code bug colour star
  • 3 x jumper cables see below, fig 1
  • 3 x Crocodile clips see below, fig 2

fig 1

fig 2
 Instructions
1. Turn the colour star so you can see the pins on the back. Attach one jumper cable to the data in pin and then attach a crocodile cable see fig 2 to the jumper cable and attach to the Micro:bit pin 0.

2. Attach the second jumper cable to the GND pin on the colour star and then attach a crocodile cable see fig 2 to the jumper cable and attach to the Micro:bit GND pin.

2. Attach the third jumper cable to the 5V pin on the colour star and then attach a crocodile cable see fig 2 to the jumper cable and attach to the Micro:bit 3V pin.

3. Attach the Microbit to your PC/Pi Open MU micro python IDE.

4. Type in the following code:


from microbit import *
import neopixel
from random import randint


np = neopixel.NeoPixel(pin0,9)

while True:
    for pixel_id in range(0,len(np)):
        red = 255
        green = 0
        blue = 0
        
        np[pixel_id] = (red,green,blue)
        
        np.show()
        sleep(200)
        np.clear() 

5. Flash the code to the Micro:bit.
 
 This version is adapted from the MIcro:bit micropython website:
http://microbit-micropython.readthedocs.io/en/latest/neopixel.html

I have changed it to loop a red light around the neopixels. (See fig 3)
                                               

                                                      Fig 3

If you like this blog check out all the others here

BitIO blog 7: Minecraft CPU temperature monitor

BitIO blog 7: Minecraft CPU temperature monitor 



David Whale has been busy crafting more add on's to his BitIO library for the MIcro:bit. A few days ago he added the Micropython function to check the CPU temperature. His library can be accessed from here:





Here is the link to the code:


I have built / recycled Minecraft graphing code to create a CPU temperature monitor. Every time you press the a button it takes a temperature reading and then out puts this to Minecraft as a random coloured wool bar. Here is what you end up with:



Instructions:
1. Open python 3 on the Raspberry Pi.
2. Plug your Micro:bit into the Pi/PC.
3.   Ensure that you have read blog 1:
http://warksjammy.blogspot.co.uk/2017/07/blog-1-getting-started-with-bitio.html
and downloaded the BitIO master files from David Whales github

4. Go into the 'Bitio master' folder, find the 'src' folder 
5. Create a new Python 3 script.6. Call it "Minecraft CPU temperature monitor.py"
7. Type in the following code:

Code
import microbit
from mcpi import minecraft as minecraft
from mcpi import block as block
import time
import random

WoolList = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

 
mc = minecraft.Minecraft.create()
 
orx,ory,orz = mc.player.getPos()

mc.postToChat("Start Graph")

TempBlock = 35,14

HumidityBlock = 35,3
Temperature_List = []#stores temp data

DataStreamCount= 0

def BuildDataBlockTemp(ImportedBlock):# take data for temp
    temp = int(microbit.temperature())
    Temperature_List.append(temp)
    orx,ory,orz = mc.player.getPos()

    for i in range (0,temp):
        x,y,z = mc.player.getPos()  
        mc.setBlock(x+30,i,z,35,ImportedBlock)
    mc.player.setPos(orx,ory,orz+1)
    msg = "Temp = {0}".format(temp)
    
    print(msg)
while True:
    
    time.sleep(0.25)
    if microbit.button_a.was_pressed():
        TempBlock = random.choice(WoolList)
        BuildDataBlockTemp(TempBlock) 

8. Open Minecraft, create a new world.
9. Run the code by pressing f5, checking for any errors that arise.
10. Press the a button on the Micro:bit.

Extension:
Try automating the graph so that it carries on every 10 seconds


You can now download a pdf version of these tutorials as part of the updated #hackpack resource booklet here:
https://github.com/ncscomputing/HpAnthologyV2/raw/master/Hackpack%20Anthology%20V2%200.3.pdf

If you like this blog check out all the others here

Monday, 11 September 2017

24 hours tracking the ISS in Minecraft and Twitter


During the last week or so I have been gradually tweaking my spin on Damien Mooney's ISS tracker. link https://damianmooney.wordpress.com/2016/02/16/raspberry-pi-minecraft-iss-tracker/

My bolt on is to take a screenshot record of each ISS movement and then tweet that picture from a twitter bot that I set up (@warksmessabout1).

This has worked for a while in trials, but has always fallen flat after a few hours. By trial and error I have hit upon a version which has run for 27 hours continuously updating 4 times an hour.

Here is an example screenshot of one of the recent updates from earlier today:




Here is the main twitter bot code:

"""
Tweeting ISS current position at set intervals with Minecraft Pi.
Get current ISS position from http://wheretheiss.at/ and map it on
a raspberry pi with minecraft
Damian Mooney wrote this minecraft Tracker in 2016. I have added a few
features on top, namely:
walking random wool blocks to mark current and positions
ability to screenshot the position using Martin O'Hanlons raspi2png tutorial:
(http://www.stuffaboutcode.com/2016/03/raspberry-pi-take-screenshot-of.html)
ability to tweet that using twython python library
"""
__author__ = '@damianmooney' #additions by @ncscomputing
from mcpi import minecraft as minecraft
from mcpi import block as block
from datetime import datetime
import time
import urllib2
import json
import random
import subprocess # to run shell script to autocall raspi2png
import sys
from twython import Twython
import BuildWorldDM as BuildWorld


consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''
       
api = Twython(consumer_key,consumer_secret,access_token,access_token_secret)

WoolList = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

""" call where the iss at api thanks to Bill Shupp"""
def getiss():
    response = urllib2.urlopen('https://api.wheretheiss.at/v1/satellites/25544')
    mydata = response.read()
    return mydata

""" longitude: convert our longitude to a minecraft co-ordinate"""
def do_coord(longitude):
    mine_long = longitude * -.55
    return mine_long


#if __name__ == "__main__":


mc = minecraft.Minecraft.create()
mc.postToChat(" Minecraft ISS Tracker for @naascoderdojo")
mc.player.setting("autojump", False)
mc.player.setPos(6, 20, 50)
time.sleep(10)
while True:

    try:
        BuildWorld.Build()
        time.sleep(5)
        iss = getiss()
        pos = json.loads(iss)
        lat = pos['latitude']
        lon = pos['longitude']
        mc.postToChat("MC ISS tracker Version 1.4.1 of @naascoderdojo's Minecraft ISS Tracker")
        mc.camera.setFollow()
        mc.postToChat("Credits to @damianmooney")
        mc.postToChat(' ISS Location Lat: %.2f Long: %.2f' % (lat,lon))
        new_long = do_coord(lon)
        mc.player.setPos(int(new_long), 20, int(lat))
        mc.setBlock(int(new_long), 20-1, int(lat),35,random.choice(WoolList))
        msg = 'ISS pos '+'@SpacePiJam'+' lon %d lat %d' % (new_long, lat)
                    #print msg
        mc.postToChat(msg)
                    #ory to location that you havesaved raspi2png in
                    
        a=subprocess.check_output('./raspi2png -d 3 -p "myscreenshot.png"',shell=True)
        photo = open('myscreenshot.png', 'rb')
        time.sleep(8)
        api.update_status_with_media(status=msg, media=photo)
    except:
        mc.postToChat("update issue")
        a=subprocess.check_output('./raspi2png -d 3 -p "myscreenshot.png"',shell=True)
        photo = open('myscreenshot.png', 'rb')
        api.update_status_with_media(status="update issue", media=photo)

    time.sleep(450) # --only update once every 15 minutes


It reads in and renders the world text file from here:
https://raw.githubusercontent.com/ncscomputing/HpAnthologyV2/master/BuildWorldDM.py

The data file is here:
https://raw.githubusercontent.com/ncscomputing/HpAnthologyV2/master/world3.txt

Enjoy :)


If you like this blog check out all the others here

Friday, 18 August 2017

Sense Hat pixel art V1




Two weeks today is the first Nuneaton Raspberry Jam in the local library. Get your tickets here (
https://www.eventbrite.co.uk/e/nuneaton-raspberry-jam-tickets-36625343388
) We will be using the sense hat emulator on the pi to create sense hat sparkles and the some pi pixel art based on the demo code from trink.io (the link to their site is listed below) I have cut down and adapted their demo to simplify and inject a bit of disco :).

Here is the code for the sense hat / online emulator:

"""
 to run on the pi based emulator change the 1st import statement to 
from sense_emu import SenseHat 
"""

from sense_hat import SenseHat 
import time
import random

s = SenseHat()
s.low_light = False

green = (0, 255, 0)
yellow = (255, 255, 0)
blue = (0, 0, 255)
red = (255, 0, 0)
white = (255,255,255)
nothing = (0,0,0)
pink = (255,105, 180)

ColourList = [green,yellow,blue,red,white,pink]


def raspi_logo():
    G = green
    R = red
    O = nothing
    logo = [
    O, G, G, O, O, G, G, O, 
    O, O, G, G, G, G, O, O,
    O, O, R, R, R, R, O, O, 
    O, R, R, R, R, R, R, O,
    R, R, R, R, R, R, R, R,
    R, R, R, R, R, R, R, R,
    O, R, R, R, R, R, R, O,
    O, O, R, R, R, R, O, O,
    ]
    return logo

def raspi_logo_random():
    G = random.choice(ColourList)
    R = random.choice(ColourList)
    O = random.choice(ColourList)
    logo = [
    O, G, G, O, O, G, G, O, 
    O, O, G, G, G, G, O, O,
    O, O, R, R, R, R, O, O, 
    O, R, R, R, R, R, R, O,
    R, R, R, R, R, R, R, R,
    R, R, R, R, R, R, R, R,
    O, R, R, R, R, R, R, O,
    O, O, R, R, R, R, O, O,
    ]
    return logo




def heart():
    P = pink
    O = nothing
    logo = [
    O, O, O, O, O, O, O, O,
    O, P, P, O, P, P, O, O,
    P, P, P, P, P, P, P, O,
    P, P, P, P, P, P, P, O,
    O, P, P, P, P, P, O, O,
    O, O, P, P, P, O, O, O,
    O, O, O, P, O, O, O, O,
    O, O, O, O, O, O, O, O,
    ]
    return logo


while True: 
    s.set_pixels(raspi_logo())#images[count % len(images)]())
    time.sleep(0.75)
    s.set_pixels(raspi_logo_random())
    time.sleep(0.75)
    #count += 1


Here is a link to show you how the pixel Pi logo works:
https://twitter.com/Warksraspijam/status/898468180477214722

Here is the emulator that I used :
https://trinket.io/sense-hat

Here is the code in action:




Enjoy :)

If you like this blog check out all the others here

Wednesday, 9 August 2017

BitIO Blog 6: 'Touching pins....takes you places'


Part 2: Touching pins.....takes you places.



This takes the basic 'touched.py' demo from David Whales BitIO master available here:

As ever if you have not quite noticed may playground is Minecraft. This version builds on from the previous blog about 'touching pins'
(http://warksjammy.blogspot.co.uk/2017/08/bitio-blog-5-touch-pins.html)

In this version you will touch a Micro:bit pin 0-2 and either:

  • pin 0- build the world map in Minecraft.
  • pin 1- teleport to England.
  • pin 2- teleport to the USA.



To "touch a pin" you will need to touch pin 0 for example with one finger and complete the circuit by touching the 'gnd' pin and then the code will work. 

Here is a link to a video of what touching pins basic code does:
https://twitter.com/Warksraspijam/status/895355608404242436

Here is a photo of how it will look:

Here is the link to the simple version code:
Teleportation and pin reading code

Build world code:

Data file:

Credit Damien Mooney's world building code:
https://damianmooney.wordpress.com/2016/02/16/raspberry-pi-minecraft-iss-tracker/

Instructions:
1. Plug your Micro:bit into the Pi/PC.
2.   Ensure that you have read blog 1:
http://warksjammy.blogspot.co.uk/2017/07/blog-1-getting-started-with-bitio.html
and downloaded the BitIO master files from David Whales github

3. Go into the 'Bitio master' folder, find the 'src' folder 
4. Create a new Python 3 script.
5. Call it "touching pins takes you places.py"
6. Type in the following code:

Code
# touched.py - demonstrates using pin touch

import microbit

from mcpi import minecraft as minecraft
from mcpi import block as block
from datetime import datetime
import time
import serial
import random
import BuildWorldDM as bw

WoolList =[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
EngX = 1.0
EngZ = 50.0

UsaX = 53.8
UsaZ = 39.7
 
mc = minecraft.Minecraft.create()
  
def Teleport(x,z,Country):
    mc.player.setPos(x,20,z)
    mc.camera.setFollow()
    mc.setBlock(x,1, z,35,random.choice(WoolList))
    mc.postToChat(Country)


while True:
    time.sleep(1)
    if microbit.pin0.is_touched():
        print("Pin 0 touched, build world")
        bw.Build()
    elif microbit.pin1.is_touched():
        print("Pin 1 touched, teleport to England")
        Teleport(EngX,EngZ,"England")
    elif microbit.pin2.is_touched():
        print("Pin 2 touched, teleport to the USA") 
        Teleport(UsaX,UsaZ,"USA")



8. Open Minecraft, create a new world.
9. Run the code by pressing f5.
10. Try touching pin 0, what happens. Now try pin 1 and 2.

Extension:
Try adding in extra countries.


You can now download a pdf version of these tutorials as part of the updated #hackpack resource booklet here:
https://github.com/ncscomputing/HpAnthologyV2/raw/master/Hackpack%20Anthology%20V2%200.3.pdf




If you like this blog check out all the others here


BitIO blog 5: Touch the pins......

Part 1: Touching pins.....dropping blocks



This takes the basic 'touched.py' demo from David Whales BitIO master available here:

As ever if you have not quite noticed may playground is Minecraft. So in this simple version you will drop different wool blocks according to the pin that you touch. To "touch a pin" you will need to touch the metal end of the cable attached to the pin and then touch the ground pin to complete the circuit and for the code to work. It took me ten minutes to figure this out.


Here is a link to a video of what touching pins basic code does:

Here is a photo of how the pins were set up during the video:

Here is the link to the simple version code:

Instructions:
1. Set up the 3 cables as above on the Micro:bit
2. Plug your Micro:bit into the Pi/PC.
3.   Ensure that you have read blog 1:
http://warksjammy.blogspot.co.uk/2017/07/blog-1-getting-started-with-bitio.html
and downloaded the BitIO master files from David Whales github

4. Go into the 'Bitio master' folder, find the 'src' folder 
5. Create a new Python 3 script.6. Call it "touched_simple.py"
7. Type in the following code:

Code
# touched.py - demonstrates using pin touch

import microbit
from mcpi import minecraft as minecraft
from mcpi import block as block
import time
import random

WoolList = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

 
mc = minecraft.Minecraft.create()
 

while True:
    
    time.sleep(1)
    if microbit.pin0.is_touched():
        msg = "Pin 0 touched, Wool block colour 0"
        print(msg)
        mc.postToChat(msg)
        pos = mc.player.getTilePos()
        mc.setBlock(pos.x, pos.y-1, pos.z,35,0)
    if microbit.pin1.is_touched():
        msg = "Pin 1 touched, Wool block colour 1"
        print(msg)
        mc.postToChat(msg)
        pos = mc.player.getTilePos()
        mc.setBlock(pos.x, pos.y-1, pos.z,35,1)
    if microbit.pin2.is_touched():
        msg = "Pin 2 touched, Wool block colour 2"
        print(msg)
        mc.postToChat(msg)
        pos = mc.player.getTilePos() 
mc.setBlock(pos.x, pos.y-1, pos.z,35,2)

8. Open Minecraft, create a new world.
9. Run the code by pressing f5.
10. Try touching pin 0, what happens.

Extension:
Try changing the block ID's


You can now download a pdf version of these tutorials as part of the updated #hackpack resource booklet here:
https://github.com/ncscomputing/HpAnthologyV2/raw/master/Hackpack%20Anthology%20V2%200.3.pdf


If you like this blog check out all the others here

Sunday, 6 August 2017

BitIO tutorial 4:Tilt me ‘Around the World’



This takes the basic 'tilt_mc.py' demo from David Whales BitIO master available here:
https://github.com/whaleygeek/bitio


Credit to Damien Mooney for the world rendering script:
https://damianmooney.wordpress.com/2016/02/16/raspberry-pi-minecraft-iss-tracker/

In the second blog and third blog I extended the basic demo to drop random wool blocks where ever you tilted the Micro:bit and in tutorial three I extended this to lay a road of sorts. 


                                                                           
Blog 2   
(http://warksjammy.blogspot.co.uk/2017/07/blog-2-extending-accelerometer-demo.html) 


Blog 3



In this blog post we will hike up the challenge to combine both push buttons in addition to the accelerometer.

Section 1 of the code:

If you press the a button on the Micro:bit then a data file is read and world map is then rendered into the Minecraft world. You can then use the accelerometer to navigate the character around the map by tilting the Micro:bit.

Here is a video to show this in action:

https://twitter.com/ncscomputing/status/885213278007328772


Section 2 of the code:
If you press the B button then the character teleport's to predetermined locations on the map. Here is a video of this in action:

https://twitter.com/Warksraspijam/status/894492363330113540

Here are some static images:








The files you will need are here should you not want to code the BitIO python file:
Files:
World map data file:

Build world library:

BitIO file:
https://github.com/ncscomputing/HpAnthologyV2/blob/master/blog4AWACC.py

If you do want to have a go at making the BitIO file then here are your instructions:

This is what the code will do:

Instructions
1. Ensure that you have read blog 1:
http://warksjammy.blogspot.co.uk/2017/07/blog-1-getting-started-with-bitio.html
and downloaded the BitIO master files from David Whales github

2. Go into the 'Bitio master' folder, find the 'src' folder and save 'World map data file' and  'Build world library' from the links above into that folder.

3. Create a new Python 3 script and type out the following:
  


Code


#“Written by : @ncscomputing /@warksraspijam”
 
from mcpi import minecraft as minecraft
from mcpi import block as block
from datetime import datetime
import time
import random
import BuildWorldDM as bw

###
"""
Written by @ncscomputing on top of the bitio produced by David Whale
https://github.com/whaleygeek/bitio

world building code imported library from Damien Mooney's blog:
https://damianmooney.wordpress.com/2016/02/16/raspberry-pi-minecraft-iss-tracker/

"""
import serial
from mcpi.minecraft import Minecraft
import time
from mcpi import block as block
import random


mc = Minecraft.create()


# button.py - demonstrates using a button

import microbit

print("micro:bit connected - press button A to test")
WoolList = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
 
EngX = 1.0
EngZ = 50.0
 
UsaX =  53.8
UsaZ = 39.7
 
CanadaX = 59.0
CanadaZ = 61.3
 
IceLandX = 10.0
IceLandZ = 61.1



def Teleport(x,z,Country):
    mc.player.setPos(x,20,z)
    mc.camera.setFollow()
    mc.setBlock(x,1, z,35,random.choice(WoolList))
    mc.postToChat(Country)

while True:
    time.sleep(0.25)
    #=======buildworld call when a button pressed
    if microbit.button_a.was_pressed():
        mc.postToChat("Button A pressed: build world")    
        print("Button A pressed: build world")

        bw.Build()
        time.sleep(2)
 
        microbit.display.show("build world")


    # manual teleport using acceleromter readings
    pos = mc.player.getTilePos()
    x = microbit.accelerometer.get_x()/300 # -ve=left/+ve=right
    y = microbit.accelerometer.get_y()/300 # -ve=forward/+ve=backward

    pos.x += x # east/west
    pos.z += y # north/south

    mc.player.setTilePos(pos.x, pos.y, pos.z) # set player position

    #time.sleep(0.5)
    #=========
    if microbit.button_b.was_pressed(): 
        print ("Button B pressed: Manual teleport")
        mc.postToChat("Button B pressed: Teleport")  
        time.sleep(0.5)
        Teleport(EngX,EngZ,"England")
        time.sleep(8)
        Teleport(UsaX,UsaZ,"USA")
        time.sleep(8)
        Teleport(CanadaX,CanadaZ,"Canada")
        time.sleep(8)
        Teleport(IceLandX,IceLandZ,"Iceland")
        time.sleep(8)

4. Save it as something.py in the same 'src' folder as the previous files.
5. Open Minecraft, create a new world.
6. Make sure your Micro:bit is plugged in to your PC/Pi.
7. Run the python file that you created above.
8. Try pressing the 'a' button let it build the world map.
9. Try using tilting the Micro:bit to see if you can navigate around the world map.
10. Now try and press the 'b' button and see if the teleportation works.

Extension:

Try extending the teleportation code to go to extra countries on the word tour.

Enjoy :)


You can now download a pdf version of these tutorials as part of the updated #hackpack resource booklet here:







If you like this blog check out all the others here