RPi Minecraft Cannon

Goal:

Using Minecraft’s API and the Python programming language, spawn a cannon that’s orientation and launch trajectory can be adjusted in real time.

What You Will Learn:

  • Introduction to Github

What is GitHub?

GitHub is an online repository that offers version control.  It is most often used for computer code and interacted with using a command line tool called git.

Getting Started:

Open a terminal either using the icon or the keyboard shortcut CTRL+ALT+t.

When opening the terminal like this we are placed in the home directory.  In RPi: Minecraft + Python Introduction we created a directory named code in the home directory.  We will now navigate into that directory using cd (change directory). Enter the following into the terminal.

cd code

You may have noticed that the prompt that was previously

pi@raspberrypi:~ $

Has now become

pi@raspberrypi:~/code $

It is informing you of the directory you are currently in, also known as the current working directory.  Remember that ~ (tilde) refers to the home directory.

 

Now that we are in our code directory, lets use git to download the cannon code from this GitHub repository

git clone https://github.com/martinohanlon/minecraft-cannon.git

Now the code has been cloned from the specified github repository into the current working directory.  Lets inspect ours with the ls (lists all files and directories)

ls

You should notice that a new directory “minecraft-cannon” has been created.  Lets navigate into the directory using cd and then inspect the contents using ls

cd minecraft-code

ls

There are several files and directories here, feel free to explore them using cd.  

Note that,

cd ..

will move your current working directory “up” one or backwards into the directory containing the current directory.

At this point we need to launch Minecraft and get into a game.

Once Minecraft is open, click Start Game then join a preexisting world or Create New.  

Back in the terminal we want Python to execute the “minecraft-cannon.py”.  If you left the directory we downloaded with git you can get back there with the following

cd ~/code/minecraft-cannon

Then,

python minecraft-cannon.py

this instructs the Raspberry Pi to use Python to run the “minecraft-cannon.py” file.

Your prompt in the terminal should have changed to

Stuffaboutcode.com Cannon >>

You can now use the following list of special commands to create, aim and fire a cannon in the running Minecraft game.

  • start
  • rotate [0-360]
  • tilt [0-90]
  • fire
  • exit

Start  spawns a cannon, exit an active cannon.  Using start multiple times in a row will construct multiple cannons however only the most recently made cannon can be controlled with the other commands.  You do not need to include the square brackets when typing the commands. 

Whats Next?

  • RPi: Minecraft Clock
  • RPi: Minecraft Snake

Article adapted from source

RPi Minecraft + Python Introduction

Goal:

Interact with Minecraft using the Python programming language and Minecraft’s application programming interface(API).

What You Will Learn:

  • Basic Python Programming
  • Use of the Minecraft API

What is an API?

To put it simply an API is a well defined method of interacting with some kind of software.  Think of it like the rules to a game, the rules dictate how the game is played and how you are able to interact with the game state.

What is Python?

Python is an interpreted programming language that is designed to be easy to learn and easy to use.  Python has many available libraries for the Raspberry Pi and is a very useful tool on the platform. Keep in mind that python uses white space (spaces, tabs, etc) to format and organize it’s instructions, take close care when typing to avoid these sometimes unobvious mistakes.

Getting Started:

Open a terminal either clicking the icon on the top bar or using the keyboard shortcut CTRL+ALT+t.

We are going to make a folder to store help organize the code we will be writing.  Enter the following into a terminal

mkdir ~/code

The mkdir command creates a new directory at the specified location, in this case “~/code”.

The “code” directory is created at the “~/” location ~ or tilde is a shortcut for the home directory.  We can verify the success of the command by entering

ls

In the terminal (this command lists all files and directories), or using a file explorer.

Next, open Thonny Python IDE by navigating to the Raspberry Pi icon in the upper left side of the desktop, click on Programming  and look at the bottom of the list for Thonny Python IDE.

Click on File and select New.

Click on File and Save As “minecraft_python.py” in the code folder we created earlier(/home/pi/code).

Now we are ready to start programming in Python.

Into your empty Python file type

import mcpi.minecraft as minecraft
import mcpi.block as block
from time import sleep

The “import” keyword load a specific code module.  The “as” keyword allows you to rename a code module to something else.  The “from” keyword allows you to load a submodule as it’s own module.

Currently this python program does nothing exciting however lets learn how to execute the program. You can either use they keyboard shortcut F5 or click on the green play icon.

After program execution the shell at the bottom of the window should have some lines of text appear, however nothing should else should happen.

Now type the following into your program

mc = minecraft.Minecraft.create()

mc.postToChat("Hello, world!")
sleep(5)

The first line creates an object that is connected to running an instance of Minecraft.  Setting it equal to mc lets us access the Minecraft game using mc within the code. The second line uses the mc object and a method “postToChat” to send text to the games chat.  The third line delays the program for the specified number of seconds, in this case 5 seconds.

Before running the code this time, we need to open Minecraft and enter a new world.  Click on the Raspberry Pi icon in the upper left, click on Games and then Minecraft Pi.

Once Minecraft is open, click Start Game then join a preexisting world or Create New.  

Using the tab key to free your mouse from the Minecraft window, run the code and switch back to the Minecraft window.  “Hello, world!” should appear in the chat.

Going back to the code, type in the following

playerPos = mc.player.getPos()
mc.player.setPos(playerPos.x, playerPos.y + 50, playerPos.z)
mc.postToChat("Don’t look down!")
sleep(5)

The position of the players head is stored in the playerPos object.  The players new position is then set relative to the previous position (In Minecraft you stand on the XZ plane with the Y axis being vertical).

 

Running this code will in addition to the previous action of sending text to the chat but then teleport the player 50 blocks vertically of their current position.

 

It is ideal to type in code whenever possible as it helps with learning however this next section is rather large and copy-paste will make quick work.

playerTilePos = mc.player.getTilePos()
blockBelowPlayerType = mc.getBlock(playerTilePos.x, playerTilePos.y - 1, playerTilePos.z)
mc.setBlock(playerTilePos.x + 1, playerTilePos.y + 1, playerTilePos.z, blockBelowPlayerType)
mc.setBlock(playerTilePos.x, playerTilePos.y + 1, playerTilePos.z + 1, blockBelowPlayerType)
mc.setBlock(playerTilePos.x - 1, playerTilePos.y + 1, playerTilePos.z, blockBelowPlayerType)
mc.setBlock(playerTilePos.x, playerTilePos.y + 1, playerTilePos.z - 1, blockBelowPlayerType)
mc.postToChat("Trapped you")
sleep(5)

mc.setBlock(playerTilePos.x + 1, playerTilePos.y + 1, playerTilePos.z, block.AIR)
mc.postToChat("Be free!")
sleep(5)

Notice that a different method is called to identify the position of the tile the player is standing in.  The setBlock method allows a single block specified with an (X,Y,Z) coordinate and a block

After running the code try to look back and see if you can identify what each line is doing.

Now add the following to your code.

mc.setBlocks(playerTilePos.x - 25, playerTilePos.y - 1, playerTilePos.z - 25, playerTilePos.x + 25, playerTilePos.y - 1, playerTilePos.z + 25, block.DIAMOND_BLOCK)
mc.postToChat("Now that's a big diamond floor!")

Notice that the setBlocks method unlike the setBlock method can take a range of X, Y, and Z coordinates.

Running the code this time in addition to the previous actions will change the blocks in a 50 x 50 x 1 shape 1 block beneath the players feet.

Whats Next?

  • Modify the code, move the player in different directions.  
  • Add additional blocks to the trap.
  • Try changing DIAMOND_BLOCK to another block type, a list of the block types can be found in the API documentation, about halfway down the page
  • Inspect the API documentation to see how else you can interact with Minecraft using Python

Article and code adapted from source

RPi Node-Red: Neopixel LED Ring

Goal:

Use string injection nodes and a specific LED ring node to control a LED ring

What You Will Learn:

  • Basic Node-Red Programming

What You Need to Know:

Parts List:

12 pixel LED ring

3x male to female jumper wires

Getting Started:

Setting up the Hardware

Use jumper cables to attach the LED ring as in the image.
Attach the red wire to +5v, the black to ground, and the white data line to GPIO pin 18.

Setting up Node-Red

Start Node-Red and navigate to 127.0.0.1:1880  using the web browser.
Drag in the ‘rpi neopixels’ node; and double click on it to start editing its properties.



Set the LEDs field to the number of LED on the ring: 12. Set the Mode to ‘bar – Number of pixels’.  The other fields are all optional, but it might be nice to lower the Brightness, here I lowered it to 15 to lower eye damage. The LED ring can be painfully bright if you are indoors.

Next we drag in the ‘injection’ node, the LED ring node reads strings of text-based commands, and turns them into output on the ring.
We configure our injector like this; setting up Payload to be a string, and contents to be  ‘Blue’. Set the checkbox for Inject once after and set the timer to 1 seconds. Repeat can be set to ‘none’.

Connect the two nodes up like this, check your wiring from the start of the tutorial; and then you’re ready to hit Deploy.
If everything is setup correctly the LED ring should display blue within a few seconds.

The command ‘Purple’ sets the background color to purple on the LED ring.
When the LED ring is initialized all the LEDs are changed to the background color, this can also be set in the node preferences as one of the fields we ignored earlier.
If you read the ‘Node Help’ page for the LED ring node you can see further commands.

For example if we change the payload in the injection node to ‘5,Red’ and Deploy then the first 5 LED will be turned Red; the rest of the LED will remain at the background color we can set in the properties field.

Another possible command is a range of pixels, for example the command ‘3,7,Red’ will set pixels 3-7 Red.
The Color names the LED ring will accept can be found here on Wikipedia : https://en.wikipedia.org/wiki/Web_colors

CONTINUING
the next step is to connect this knowledge with other tutorials, see other tutorials to maybe connect the LED ring to a physical button, or use it in concert with other outputs like speakers.
More advanced logic can be used to turn the LED ring into a clock, or dial.

3D Printing: QIDI 3D Printer + Software Setup

Goal:

Setup your QIDI 3D printer from un-boxing to first print – you can use other 3d printers but will have to find their own instructions

What You Will Learn: 

  • How to assemble your printer
  • How to level the bed of your printer
  • How to slice 3D STL models into files the printer can print

Parts List:

Un-boxing and Assembly

Printer Bed Leveling

 

Since the Qidi printer is based on an open source design there are quite a few different printer control software packages you can use. The one we have settled on that seems to work best with the most useful features is the Flashforge Flashprint printer software. When using this software you need to select “flashforge

 

Steps:

  • Download Appropriate Software for your computer:
  • Choose Creator Pro as your printer: 
  • Load your STL file, if you need a 3D model to slice you can download your T3 logo here from Thingiverse!
  • Slice your 3D model by clicking on Print and selecting the appropriate settings
  • PLA is the recommended material – make sure you have PLA loaded into the printer also
  • Save your .x3g file to the 3D printer SD card you should have plugged into your laptop
  • Thats it! your file should be ready to print on the QIDI 3D printer!

 

RPi Node-Red: Camera

Goal:

Install the Raspberry Pi camera and take a picture using Node-Red

Parts List:

  • Pi Camera
  • Pi Camera Ribbon Cable

Getting Started:

Power off your Raspberry Pi and the follow the instructions on this page to install the camera.

Setting up Node-Red

Start Node-Red and navigate to 127.0.0.1:1880.  Into the flow area drag an “inject” node and a “camerapi takephoto” node.

Link them together.

Deploy the flow, then point the camera at something and press the inject button.  The camera will take a picture and then store it in /home/pi/Pictures by default.  Open the file explorer.

Click on the Pictures folder.

There your photo is!

Whats Next?

  • Try and trigger the camera node with a Raspberry Pi input node connected to a button or PIR sensor.

(Archive) RPi Node-Red: PIR(motion) Sensor

Goal:

Learn how to wire a passive infrared sensor and read it’s state in Node-Red.

What You Will Learn:

  • Basic Circuit Prototyping
  • Basic Node-Red Programming

What You Need To Know:

Parts List:

  • One PIR
  • Breadboard
  • Some Jumper Wires
  • One 100 Ohm Resistor

What is a PIR?

A passive infrared sensor or PIR is able to detect movement by measuring the change of infrared radiation.  This PIR comes in a 3 pin package, if you remove the diffusion cap you can see that the pins are labeled “VCC”, “OUT”, and “GND”.  VCC means “voltage at the common collector” and normally refers to a power rail within a circuit, this sensor requires 5 volts. OUT is the pin we will read information from.  GND is the ground connection.

Getting Started:

Setting up the Hardware

I encourage gently taking off the diffusion cap on the PIR to view the pins labels.  GND goes to ground, VCC goes to 5V, and OUT is connected to a 100 ohm resistor and then to GPIO20.  

Setting up Node-Red

Start Node-Red and navigate to 127.0.0.1:1880.  Drag a Raspberry Pi input node and a Debug node into the flow area.

Double click on the Raspberry Pi input node to open its configuration menu.  Set the Pin to GPIO20.  Name the node “PIR”.

The debug node can be left with it’s default settings, wire the button node to the debug node and deploy the flow.

If everything has been put together correctly, the state under the PIR node should change from a 0 to a 1 if movement has been detected and then back to 0 after a period of time, inspect the debug tab to view a log of these state transitions.  You may have noticed the two components under the PIR with a plus pattern on them. These are adjustable potentiometers, they control the sensitivity of the PIR and the duration of the activated state.

Whats Next?

RPi Node-Red: Push Button + LED or Buzzer

Goal:

Combine the use of Raspberry Pi input and output nodes in Node-Red to control an LED or buzzer with a push button.

What You Will Learn:

  • Basic Circuit Prototyping
  • Basic Node-Red Programming

What You Need to Know:

Parts List:

  • At Least 1 LED
  • At Least 1 Resistor
  • Piezoelectric Buzzer
  • Some Jumper Wires
  • Breadboard

Optional

  • Needle Nose Pliers

Getting Started:

Setting up the Hardware

This wiring diagram is simply the combination of the individual LED, buzzer, and push button circuits.  Make sure that the LED has a resistor on it. Wire a pin on the buzzer to GPIO16, wire the positive leg of the LED to GPIO12, and wire one of the pins on the button to GPIO25.  You can wire all the grounds to a rail and then to the GPIO GND or the connections can be made individually.

If it is difficult to put the components into the breadboard without the legs bending try and use needle nose pliers to help push the pins in.

Setting up Node-Red

Start Node-Red and navigate to 127.0.0.1:1880.  Drag one Raspberry Pi input node and two Raspberry Pi output nodes into the flow area.

Double click the Raspberry Pi input node to open its configuration menu.  Set the Pin to GPIO25.  Set Resistor? to pulldown.  I set the Name to “button”.

Double click one of the Raspberry Pi output nodes to open its configuration menu.  This will be the LED so set the Pin to GPIO12.  Leave Type set to Digital output, Initialise the pin state to low.  Name the node “LED”

Double click the other Raspberry Pi output node to open it’s configuration menu.  Set Pin to GPIO16.  Set Type to PWM output.  Set Frequency to 100.  Name the node “buzzer”.

Wire each output node to the single input node and deploy the flow.

If everything works properly activating the button should turn on the LED and activate the buzzer.  To stop either output node from activating just remove its connection to the button node and redeploy the flow.

Whats Next?

  • What other combinations can you make with the items in your kit?

(Archive) RPi Node-Red: Push Button

Goal:

Learn how to wire a push button and read it’s current state in Node-Red

What You Will Learn:

  • Basic Circuit Prototyping
  • Basic Node-Red Programming

What You Need to Know:

Optional

Parts List:

  • 1 Push Button
  • Breadboard
  • Some Male-Female Jumper Wires

Optional

  • Multi Meter
  • Needle Nose Pliers

What is a Push Button?

A push button is a momentarily activated button.  When the button mechanism is fully depressed an internal electrical connection is made and this newly made connection can be read as the activation of the button.

What is a Breadboard?

A breadboard is a prototyping platform that allows the easy creation of circuits without having to solder.  Each row of the breadboard is connected internally (not across the middle break). This mean that putting something into position 1a and 1b connects them electrically together while something plugged into position 1a and 2a are electrically isolated.  

The power rails on the left and right hand side of the breadboard are connected in a column and can be an easy way to access ground of power if you choose to route it there.  The color red and by extension the red column is often used for power while blue is often associated with ground and thus used for a ground connection.

Getting Started:

Setting up the Hardware

Take care when wiring the button to the GPIO, you want to connect the correct pins.  In it’s 4 pin package only some pins are isolated in the inactivated state.  A pair of pins that come out of the same side of the button are isolated as well as diagonal partners.  A multi meter on the diode setting can also be used to test if there is a connection between pins in an activate/inactivated state. Once you have identified the correct pair of pins attach one to 5V and the other to GPIO25.

Additionally it can be difficult to get the short legs of the push button to correctly make contact with the breadboard, I find that using needle nose pliers to straighten the legs of the push button and then inserting them 2 at a time to be a successful method.

Setting up Node-Red

Start Node-Red and navigate to 127.0.0.1:1880.  Drag a Raspberry Pi input node and a Debug node into the flow area.

Double click on the Raspberry Pi input node to open its configuration menu.  Set the Pin to GPIO25.  Set Resistor? to pulldown.  You can Name the node anything, I chose “button”.

The debug node can be left with it’s default settings, wire the button node to the debug node and deploy the flow.

If everything has been put together correctly you should see the number under the button node in the Node-Red flow change from a 0 to a 1 when the button is activated and from 1 to 0 when the button is deactivated.  You should also be able to see a record of the button activation in the debug tab of Node-Red.

Whats Next?

(Archive) RPi Node-Red: LED

Goal:

Turn a light emitting diode(LED) on and off using a button in Node-Red.

What You Will Learn: 

  • Basic circuit prototyping
  • Basic Node-Red programming

What You Need to Know:

  • Node-Red Basics

Optional

Parts List:

  • At Least 1 LED
  • At Least 1 resistor
  • Breadboard
  • At least 2 male-female jumper wires

What is a Breadboard?

A breadboard is a prototyping platform that allows the easy creation of circuits without having to solder.  Each row of the breadboard is connected internally (not across the middle break). This mean that putting something into position 1a and 1b connects them electrically together while something plugged into position 1a and 2a are electrically isolated.  

The power rails on the left and right hand side of the breadboard are connected in a column and can be an easy way to access ground of power if you choose to route it there.  The color red and by extension the red column is often used for power while blue is often associated with ground and thus used for a ground connection.

What is a Resistor?

A resistor is an electrical component that has a specific value of resistance measured in ohms.  Resistors are used to restrict the amount of current in a circuit or facilitate a drop in voltage.  Its value of resistance can be read in ohms using the colored bands on the body of the resistor.

What is an LED?

An LED is a light emitting diode.  Diode’s are a class of electronic components that are designed to only allow current to pass through them in one direction.  This means that LEDs are polar meaning they have an anode (positive) and a cathode (negative). Current must flow into the anode and the cathode must be attached to ground.  

There are several methods of identifying the anode and cathode:

  • Look at the lengths of the pins, If the LEDs’ pin have not been modified the longer pin is the anode and the shorter pin is the cathode
  • Look at the sides of the LED a portion of the case will be flat the pin on that flat side is the cathode 
  • Look inside of the bulb, each pin is connected to a flat piece of metal internally.  The pin that is attached to the larger piece is the cathode

An LED must have a current limiting resistor between it and ground or between it and power.  An unprotected LED will pull more and more current until it burns itself out. The value of the resistor will have an effect on the LEDs’ luminosity.  The higher the value of resistance the resistor has the less current will get to the LED and thus the dimmer the bulb will shine. The amount of current can be calculated in milliamps with Ohm’s Law, using the value in ohm’s for resistance

text{current} = frac{text{voltage}}{text{resistance}}

Getting Started:

Setting up the Hardware

If you are following the wiring diagram make sure to attach the cathode (straight leg in the diagram) of the LED to a resistor and then to GND (ground).  Attach the anode (leg with the kink) to GPIO #12.

Setting up Node-Red

Start Node-Red and navigate to 127.0.0.1:1880  using the web browser. Drag two inject nodes and a Raspberry Pi output node into the flow area

Double click on the Raspberry pi output node to open its configuration menu.  Set the Pin to the same pin you physically connected the LED to. If you are following the wiring diagram this is GPIO12.  Leave the Type as Digital Output.  We can also Name the node, since I used a green LED I named it “Green led”, this follows a good programming practice of accurately and succinctly naming variables.

Double click one of the inject nodes.  Use the drop down menu to change the Payload data type number, type a “1” in the text box.  Name the inject node “on”.

Double click the unmodified inject node.  Use the drop down menu to change the Payload data type to number, except type a “0” in the text box.  Name this node “off”.

1 and 0 correspond for to values of a binary digit(bit) true and false, high and low, on and off respectively.  These are called boolean values and are a fundamental data type in Computer Science.

Connect the inject nodes to the output node and then deploy the flow.

The green square under the Green LED node tells us what state the LED is in, 1 being on and 0 being off.  Injecting a different value will change the state from off to on or from on to off.

Whats Next?

RPi Node Red + Camera

RPi GPIO + Scratch 2.0

In this activity we will use Scratch 2.0 to light LED bulbs and sense a button push.

Begin by lighting a LED bulb with an always on 3.3 v pin and a resistor. If this isn’t working, check your connections or see the post on getting started with GPIO. Change the pin for the 3.3 volt to pin 17 on the GPIO board and open Scratch 2.0.  Follow the steps outlined below.

 

3D Printing: CAD – Design your thing!

Overview

3D Printing & Computer Aided Design (CAD) will allow students to discover the potential and limitations of 3D Printing through a build intensive design project. Students will learn how to use CAD software such as AutoDesk, SolidWorks, etc. An excellent opportunity for anyone interested in prototyping, creating artworks, or product customizations.

TinkerCAD

TinkerCAD is a simple, online 3D design and 3D printing app for everyone. TinkerCAD is used by designers, hobbyists, teachers, and kids to make prototypes, artworks, and Minecraft models!

TinkerCAD Website

Next Lesson: Slicing your CAD model and sending files to the printer.

RPi Minecraft + Networking

In this activity students will learn about networking on the Raspberry Pi using a popular pre installed game called Minecraft.

I use this opportunity to speak about the human networking that happens when a team of individuals work together. Minecraft is known as a sandbox game where blocks can be created or destroyed.   Many students have played Minecraft in a way that players attack each other known as player vs player, or PVP. Establish that this is not the kind of environment that is being created.  Students will work together to build something cool.

Establishing a level of experience with Minecraft is a good way to start.  I like to group advanced users with each other and beginning users together.  Each group needs to brainstorm, plan and build something in a specified amount of time.  I usually give students between 15 and 30 minutes and encourage them to stretch to collaborate.   Groups can range in size from 2 – 5 players.  One student will “host” the world on their device and will need to identify their I.P address to share with partner players.

Immediately upon opening up Minecraft students given an option to join game or create a new world.  If they create a world, it exists on their pi, if they join a world they need to know who’s world they are joining.  This becomes a process of students calling out and identifying who’s pi is at which IP address.  The IP address can be found by hovering over the Wifi signal in the upper right corner of the screen.

Students who have never used Minecraft will need assistance learning to move within the world, to place a block and to change their inventory.  These students should focus on building something very simple.  Advanced students might build a castle or a huge underground maze.  At the end of the build time, join into the world on your Pi and let one of the students from each group share what they created.

If students wish to save the world they are working on, they will need to navigate to the .minecraft folder from and drill down to the folder of the world they were playing in.  The following video goes over how to do this.

RPi Scratch Reaction Time

Programing is about giving a computer a set of instructions. Instructions can be given in a text based format or in a visual format. Scratch is a visual programing language that allows a user to easily create interactive stories, games, and animations by dragging specific bits of code to an area and running the program. To get an idea of what Scratch can do, share this overview video.

Scratch can be run in a browser on a regular computer but it is a bit resource intensive to run on a Pi. Two versions come installed on the Raspberry Pi, the classic version labeled Scratch, and an updated version Scratch 2.0.  Scratch 2.0 tends to be a bit less responsive, however it has some very cool features that are explored in a later lesson.

Have students open Scratch (not scratch 2) from the program menu and follow along with the tutorial below.

When students have been able to do some basic functions in a Scratch environment introduce them to this project creating a reaction time game.

Continue reading

RPi: Editing Text files and Python Scripts with Raspbian

Getting Started

There are a myriad of ways to edit text files and code built into the Raspbian distribution; several even inside the terminal. But here we will cover some of the easier to use graphical programs.

It’s important you know your way around the terminal before continuing, please see the terminal tutorial -> here

Editing config files with leafpad

Leafpad is a lightweight notepad-like text editor that is bundled with Raspbian; we will use it here to edit simple config files in the file system.
For example the led ring tutorial directs us to edit the /boot/config.txt and comment out some lines.
To do this navigate to the /boot/ directory in the terminal; and then run ‘sudo leafpad config.txt’, this is similar to other commands you have seen taking a path as an argument, the important difference is the ‘sudo’ prefix which tells the terminal to run this command as a ‘super user’. This allows us to overwrite important system files and access gpio pins ect. You’ll have to use it often but you should still be careful.

We get an editor window like notepad on windows, we can insert a ‘#’ before dptparam to comment it out, and then save with control s
after exiting the editor you will regain control of your terminal.

Editing and running python scripts with Thonny

Next we can use a slightly complicated editor, Thonny is specifically for python ‘.py’ files and has some features that make debugging scripts easier.
Thonny can be found in the menu in the top left corner, or again opened from the terminal with ‘sudo thonny’.
Most scripts accessing the GPIO require sudo powers to work correctly, so its best to get used to running it as sudo.
You open a file to edit by navigating to it in the thonny gui; like notepad on windows.


We can enter python scripts line by line into the main window, and at any moment run our script with F5 or the gui button (green arrow).
Here is what it looks like to run a simple program inside thonny.
note the output in the lower window, this is the result of pressing F5 or the run button

RPi Sense HAT+Minecraft

The Sense HAT was developed by the folks at Raspberry Pi as an add on board that contains a number of sensors and a LED display. In this lesson we can demonstrate how to use the Sense HAT in conjunction with Minecraft to visualize real world data and control the LED Screen.

I use this lesson primarily to get students excited about the connection between a sensor and the way that we can visualize data through Minecraft.  This worksheet from the folks at the Raspberry Pi foundation is an excellent resource. In the latter portions of the lesson it goes into methods of collecting data from the Sense HAT and displaying it within the Minecraft world.

https://www.raspberrypi.org/learning/exploring-space-with-minecraft/

Follow along with the Sense HAT installation and the first several worksheets of this project.

4. Github Intro

Github is known as a repository for cool programs that can be used in all sorts of ways on your Pi. In this lesson we will learn how to install programs from Github using the terminal.

First lets install a program that can do screen captures. Something that is handy when students have created something amazing in their Minecraft world.

Lets follow the instructions for taking screenshots provided by Martin O’Hanlon.

http://www.stuffaboutcode.com/2016/03/raspberry-pi-take-screenshot-of.html

Here is a video going through the process.

Students will be really excited when they learn to download programs that can run within their Minecraft world. Lets go back to Martin’s API tutorial and have students select one of the first three items, clock, cannon, or snake video game.

http://www.stuffaboutcode.com/2013/04/minecraft-pi-edition-api-tutorial.html

In each of these examples, there is a section of code that should be copied into the terminal. When enter is pressed on the keyboard, a bunch of code will appear and a new program file will be placed in the home directory on the Pi

Have students navigate to the file folder and open the file with the .py extension by right clicking on the file and selecting open with python 2 from the drop down menu.  If the program is run while Minecraft is open it will place an exciting new feature in the Minecraft world. This will hopefully trigger a desire to try downloading other python programs to modify their Minecraft worlds.

RPi: Terminal + Python Intro

Navigating with the terminal

Like on windows or any other computer, files in Linux are arranged in a hierarchical directory structure; meaning starting at root there is a sort of tree of folders containing files and other folders.
The terminal has a concept of ‘working directory’ ; using the metaphor of navigating an office building this is simply what room the terminal is in. If you use a command to list files it will look around the current directory and return you a list of files currently visible.

After opening a terminal with the icon in the upper left you will be confronted with something like this (but most likely with a different color-scheme and font)

upon opening terminal

We can now use the ‘pwd’ print working directory command to see what directory or room we are in; the result is returned to us in simple text:

Now we know what directory we are in, but we still don’t have any idea what accompanies us; for that we can use ‘ls’ list command; which returns us a list of files and directories in our working directory.

I have added a file here to demonstrate that files are coloured differently to directories.
Now we can try entering one of the directories listed, for this we can use the cd change directory command. This command takes a ‘path’ as an argument. Paths are just strings of text describing the location of a directory or file; pwd returns the ‘path’ of our current working directory. Another path could be ‘/home/pi/Documents/’. Paths can also be relative to our current location, so if our current working directory is ‘/home/pi’ then ‘Documents’ would be a valid path.

Most of the time you will use relative paths, they are shorter and easier to work with too.
To navigate to a directory relative to our own we first use ls to see what our options are.

Then we use the cd command with a path to enter one, we’ll use the python_games directory because we know ahead of time its not empty: cd python_games

Another valid and equivalent command would again be cd /home/pi/python_games

Once we enter the directory we can use the ls command to orient ourselves.

We can see dozens of files and no directories, here we can practice running and terminating a python script.

Running and Exiting python scripts

Just like the cd command there is a python command pre-installed that takes a python script as an argument, python scripts are files with a .py extension.
To run a game choose any file with a .py extension and use it as an argument to run python.

To exit the program at any time use the Control-C keybind, this sends a kill signal to the python process we just started; this will also be used regularly when you want to exit python scripts you are testing.

Next we will navigate back home using terminal commands and create our own directories and files.
Apart from relative and absolute paths that we already covered there are some more special cases, for example the ‘..’ path refers to the directory one level above our current working one. This makes it easy to navigate upwards out of whatever area we entered.
To navigate back to the home directory use ‘cd ..’, and then use ‘pwd’ to check if you made it back.

Finally we will create our own directory and some files to populate it. Just like the cd command there exists a mkdir command which again takes a path. This command simply spawns a folder with our chosen path, for example..

At first we have no indication that our command did anything, but a simple ls will reveal all.

We don’t want to spam files all over our home directory, so before we start making them lets enter our directory with cd.
The command for creating files in the terminal is called touch, it takes a path and creates an empty file whereever we tell it too, or if the file already exists it just ‘touches’ it; updating its last modified date ect.

Now that we are safely in our own directory we can try it out:

There does exist a rm command to remove files, but it can be dangerous if you accidentally delete some script or important document you were just working on!
as you can guess it takes a path as its argument; here we can see it at work.

Last of all we can clean up after our empty directory, navigate back to the home using cd, and then use the sister to rm, rmdir to remove our directory.

Conclusions

In this tutorial we reminded ourselves what directories and files are, how to find our current working directory in the terminal, how to list files and folders, how to enter and leave directories, how to run and exit python scripts, and how to create and delete files / folders.