/* jquery */ /* jquery accordion style*/ /* jquery init */

1 December 2017

micro:bit MicroPython Coding Tutorials

It's easier than you think to begin coding in MicroPython with the micro:bit board.
My straightforward, step-by-step tutorials will to guide you through the coding process.
Have fun!

Getting Started

   • Introducing the micro:bit

   • MicroPython Coding in 4 Simple Steps

   • MicroPython Coding with the Mu Editor

LED and Button Coding Tutorials

   • Build a Countdown Timer

   • Display Images and Animations

   • Create Custom LED Images

   • Capture Button Presses

Sensor Coding Tutorials

   • Access CPU Temperature Sensor Data

   • Capture Accelerometer Movement Gestures

   • Accelerometer Gestures Dice Shaker

   • Accelerometer Spirit Level

   • Magnetometer Compass

Image Animation Tutorials

   • Image Animation Code

   • Image Animate Class

Discover More

You might also be interested in my post about using the Thonny Python editor with the micro:bit.

And for more information on the MicroPython language navigate to the official MicroPython website.

Try My Free Raspberry Pi Python Coding Tutorials

27 November 2017

From tkinter to AppJar (part 3)

In the previous tutorial, From tkinter to AppJar (part 2), we converted the file search tkinter app from an earlier tutorial to a shorter 30 line AppJar app.

This time we'll take the same file search app and add new code lines to enhance the user interface's look and feel via a series of configuration options.

With your favourite Python 3 editor open the previous file search code listing, then change the init() function to look like the listing below:

Let's take a closer look at the behaviour introduced by these new code lines.

On line 6 we create a splash screen with an appropriate text label.

On line 7 we set the background colour of the app window, in this case to orange.

On lines 8 and 9 we set the font size of the text labels and the buttons. Notice here the button font size is a little larger than the label font size.

Finally, on line 17 we ensure the "Start Path" text entry field is associated with the initial cursor focus.

You can find more information on AppJar's extensive widget collection and configuration capabilities at the official AppJar website.

Try My Free Raspberry Pi Python Coding Tutorials

15 November 2017

From tkinter to AppJar (part 2)

In the previous tutorial, From tkinter to AppJar (part 1), we converted a simple tkinter app to a short 8 line AppJar app.

This time we'll try out some of the other App Jar widgets by converting a tinter-based file search app from a previous tutorial.

With your favourite Python 3 editor, open a new code file and enter this code:

As you can see, we've replicated the functionality of the 53 line tkinter file search example with just 30 lines of AppJar code.

In part 3 we'll add new code lines to enhance the user interface's look and feel via a series of configuration options.

Try My Free Raspberry Pi Python Coding Tutorials

9 November 2017

From tkinter to AppJar (part 1)

As part of my free Raspberry Pi Python Coding tutorial series I showed how to create Graphical User Interfaces with the tkinter module.

However, while it's a very flexible piece of software, writing tkinter apps tends to involve quite a bit of code. In this post I'll look at a lightweight GUI alternative called AppJar.

Although App Jar is based on tkinter, it removes the need for much of the so-called 'boilerplate' code. And this means we can focus our attention on widget-based UI design.

Install AppJar

First, you'll need to install AppJar.

The easiest way is to use the following pip command:
sudo pip3 install appjar

Alternatively, download Appjar, unzip it and move the appjar folder to your source code folder.

Simple AppJar Example

Let's start with an AppJar version of my single button callback tkinter tutorial (which included a detailed walk-through of the code).

With your favourite Python 3 editor, open a new code file and enter this code:

Notice the size of this program. We've replicated the functionality of the 25 line tkinter example with just 8 lines of AppJar code.

In part 2 we'll converting a tinter-based file search app to App Jar.

Try My Free Raspberry Pi Python Coding Tutorials

15 October 2017

micro:bit MicroPython Animate Class

MicroPython for the micro:bit has a useful collection of images. And you can create your own custom LED images too. This time we'll write code to create an animation based on a collection of these images.

Python's list data type is ideal for our image collection. So, we'll define a class that inherits from the list data type. In this way we automatically have all the functionality of a list object and only need to add our own custom class methods.

In this case we're going to add two methods, the first to play (line 7) the image animation and the second to loop (line 13) through a series of animation plays.

Here's the code:

Now we've defined our class we can create an instance of the Animate class (line 19), then add a number of images using the append method inherited from the list data type. All we need to do now is call the play method (line 25) to display the animation, specifying the pause interval in microseconds.

Next we remove the image collection (line 29), using the clear method inherited from the list data type, then add more images. Finally, we call the loop method (line 35), specifying the number of loops and the pause interval in microseconds.

Here's the compete code listing:

Return to the micro:bit MicroPython Coding Tutorials page.

micro:bit MicroPython Animation Code

MicroPython for the micro:bit has a useful collection of images. And you can create your own custom LED images too. So let's write some code to animate a collection of these images.

We'll use Python's built-in list data type to hold our image collection. After adding the images with the append method we can create a for loop to iterate through the list.

Here's the code:

from microbit import *

# create an empty list
images = []

# add images to list
images.append(Image.TRIANGLE)
images.append(Image.DIAMOND)
images.append(Image.SQUARE)

# display each image in the list
for img in images:
   display.show(img)
   sleep(1000)

Note there is a one second pause between the display of each image so we can clearly see each one.

If you'd like to add code that builds a new image collection first use the clear method to remove the old images, like this:

images.clear()

Next time we'll see how to create an Animation Class that incorporates both one-time play and looping functionality.

Return to the micro:bit MicroPython Coding Tutorials page.

6 October 2017

Python's Popularity Soars

Python is an increasingly popular coding language. In fact, recently the IEEE Spectrum organisation put Python at number one in its programming languages popularity ranking; above C, Java, C++ and C#.

In other words, there's never been a better time to learn the Python language or extend your Python coding skills. Here are a few ideas.

Raspberry Pi

With well over 12 million boards in circulation the Raspberry Pi computer has undoubtably helped Python's impressive adoption rate. Start your Python journey with my free 'Learn Python on the Raspberry Pi' coding tutorial series.

micro:bit

Discover how to code MicroPython programs that run on the micro:bit board, using either a web browser or the free-to-download Mu editor. Tutorial code examples cover interacting with the LED display, A and B buttons plus the built-in sensors.

Minecraft

If you're a Minecraft fan then why not use the hackable Raspberry Pi Minecraft edition to write Minecraft Python code. Other development options include writing Java code using BlueJ.

Astro Pi Data Analysis

The newly launched Astro Pi Mission Zero initiative is designed to encourage young people to create Astro Pi programs. The winning programs will be uploaded and run on the International Space Station (ISS).

In the past I've shown how to explore the downloadable Astro Pi CSV data, associated with Tim Peake's ISS mission, and the related Python Date Filter post.

1 October 2017

Thonny for RPi and micro:bit

In a previous blog post I talked out the benefits of the Thonny Python IDE.

Now the latest Raspbian Stretch operating system for the Raspberry Pi family has an updated Thonny release.

In addition, if you click the Menu > Programming > Thonny (Simple Mode) option you'll find all the essential window panes for writing Python code, with the most common features just a click away via generously-sized icons.

And for micro:bit MicroPython coding fans there's a micro:bit Thonny plugin to download and try out.

Try My Free Raspberry Pi Python Coding Tutorials

20 September 2017

Learn Python 3 on the Raspberry Pi Tutorials

My popular Learn Python on the Raspberry Pi tutorial series is now Python 3 compatible.

I've updated all the code examples to run in Python 3, and tested them with version 3.5 and 3.6.

Where appropriate I make references to Python 2.7 differences, for example in the tkinter GUI tutorial series of posts.

Start My Free Raspberry Pi Python Coding Tutorials

1 August 2017

Java 9 and the Raspberry Pi

The Java coding language has been included in the Raspberry Pi's official Raspbian distro for some time now. Java 9, the latest incarnation of the language due for release in Autumn 2017, introduces raft of enhancements.

In this post I'll touch on some Pi-centric key aspects of Java 9, namely the new Java Shell, modularity and jlink, plus CPU support.

Java Shell - about time

Python has always had a read-eval-print loop (REPL) command-line option. It's a great way for newbies to get to grips with the coding basics and the language syntax.

Until now Java hasn't had a REPL option. But version 9 comes with jshell. Key features are: instant feedback, optional semicolons, a range of pre-imported libraries (like io, math, net and util) and a handy collection of slash commands to load, save, manipulate and analyse source code.

You can experiment with shell now in the Java 9 early release.

Modularity and JLink - smaller and faster

As your Java project grows the number of libraries and their dependencies starts to get increasing complex. This can mean your programs are slower to load and execute. Project Jigsaw set about changing this picture by breaking things up into a collection combinable blocks for system, jdk, source code and binary runtime elements.

This work lead to Java 9's new requires keyword, which helps to identify library dependencies. When compiling a runtime image this information is used by 'jlink' to assemble and size-optimize a binary runtime image.

CPU Support - not all Pi models

Java 9 takes advantage specific CPU instruction sets commonly found in modern 64-bit processors, like the ARM v7/8 CPUs and x86 range. This move will help improve runtime performance.

However, as of today, this does limit Java 9 to the Raspberry Pi 2 and Pi 3 boards. Owners of model As, Bs and Zeros, with their older ARM v6 processor chips, will therefore have to keep using Java 8.

Read all my Java coding posts

1 July 2017

Thonny Python REPL on the Raspberry Pi

Thonny IDE

Python coders who use the latest Raspberry Pi Raspbian Pixel distro will find the Thonny Python REPL development tool is pre-installed.

Thonny is a far better development option option than IDLE or many other Python editors. Thonny comes with Python 3.6 built-in, has many pro-level features, yet retains an easy-to-use user interface.

Thonny's advanced features include:

• Code completion: helps beginners explore the Python language and reduce typos

• REPL Shell: quickly try out Python statements and play with new packages

• Deep Code Debugger: step through actual code elements and expression evaluations

• Variable Viewer: monitor the value of your variables in real time

• Function Call Visualisation: including a way to see how recursion works in practice

• Syntax Error Highlighting: identifies common errors like missing quotes or parentheses

• Scope Detection: ensures local variables are visually distinguishable from global variables

Sound interesting? Then head over to the Thonny.org webpage where you'll find additional information, a Thonny in action video demo, plus download instructions for older Raspbian distro releases or Windows, macOS and Linux.

And there's more helpful information in an online MagPi Thonny tutorial.

Try My Free Raspberry Pi Python Coding Tutorials

11 June 2017

Tkinter Coding with AppJar and GuiZero

Previously we had a look at creating Graphical User Interfaces with Tkinter as part of my free Raspberry Pi Python Coding tutorial series.

Tkinter is certainly a very flexible piece of software, capable of implementing all kinds of user interface (UX) designs. However, the lines of code needed to create usable solutions tends to rise quite quickly. This can make things a little difficult for those with relatively limited Python coding experience.

Recently a couple of Tkinter-based Python modules have started to address this issue. One is GuiZero and the other is AppJar.

The idea behind these modules is to simplify the creation of grid-styled form-based apps, while still supporting a wide variety of widgets. Both are easy to install and use. Although be aware that as they are still in development sfeatures are subject to change and you may encounter the occasional bug.

AppJar documentation is based around a 'code sandwich' metaphor with a menu of widget-based fillings. Code examples include Minecraft interaction and there's also a series of hands-on AppJar coding tutorials.

The GuiZero documentation is also straightforward to follow with plenty of code examples, such as how to use the multi-cell Waffle grid layout.

Try My Free Raspberry Pi Python Coding Tutorials

9 June 2017

CoderDojo micro:bit MicroPython Sushi Cards

Here are details of the Sushi-style cards I created for the CoderDojo organisation.

Two ways to start MicroPython coding with your USB-connected micro:bit board.

• Quickest - point your web browser to the official MicroPython coding website.

• Most Flexible - download the free Mu MicroPython Editor, which is available for Windows, macOS, Linux and the Raspberry Pi.

MicroPython code examples covering the LED display, the A/B buttons, plus the temperature, magnetometer and accelerometer sensors.

Try My Free micro:bit MicroPython Coding Tutorials

29 May 2017

Magnetometer Compass (micro:bit MicroPython)

This time we'll take advantage of the micro:bit's magnetometer sensor (which detects magnetic fields) to build a North-finding compass app.

from microbit import *

# draw a circle calibration
compass.calibrate()

while True:
   sleep(100)
   val = compass.heading()
   if (val < 10 or val > 350):
      # the micro:bit is pointing North
      display.show('N')
   else:
      display.show(Image.NO)

Note that the magnetometer needs to be calibrated before we use it. This is done by tipping the micro:bit around to draw a circle on the LEDs. Be aware that sometimes the magnetometer calibration can be affected by the magnetic fields emanating from an electronic device, such as a computer.

As a coding challenge you could try to add compass directions for South, East and West.

Return to the micro:bit MicroPython Coding Tutorials page.

26 May 2017

Spirit Level (micro:bit MicroPython)

This time we'll create a spirit level that uses x-axis data from the micro:bit's built-in accelerometer sensor.

from microbit import *

while True:
   # obtain the accelerometer x-axis value
   x = accelerometer.get_x()
   # perform an integer division
   val = x // 20
   # test the value
   if val > 0:
      display.show(Image.ARROW_E)
   elif x < 0:
      display.show(Image.ARROW_W)
   else:
      # Yes – I am level
      display.show(Image.YES)

The micro:bit's accelerometer is sensitive to the slightest movement. In fact, it is too sensitive for our purposes. So here we take the returned accelerometer x value and divide it by 20 using the integer divide // symbol.

For a simple coding challenge try changing the integer division value from twenty to something smaller or larger, then discover how much harder or easier it is keep level.

A more advanced coding challenge would be to create a dual axis spirit level using both the get_x() and get_y() accelerometer functions.

Return to the BBC micro:bit MicroPython Coding Tutorials page.

24 May 2017

Dice Shaker (micro:bit MicroPython)

In this tutorial we'll take advantage of the 'shake' accelerometer gesture to build a dice shaker, which can be used to play all kinds of games.

from microbit import *
import random

while True:
   if accelerometer.was_gesture('shake'):
      # generate a random integer from 1 to 6
      diceNumber = random.randint(1,6)
      # show the dice number
      display.show(str(diceNumber))
      sleep(1000)

Notice here we import the random MicroPython library module as well as the standard microbit library module.

After you've downloaded this program to the micro:bit try to shake a six!

As a extra coding challenge you could modify the code to simulate two dice (hint: the minimum throw is 2 and the maximum is 12).

Return to the micro:bit MicroPython Coding Tutorials page.

23 May 2017

Capture Gestures (micro:bit MicroPython)

This time we'll capture movement gestures, as recognised by the micro:bit's built-in accelerometer sensor.

from microbit import *

while True:
   # obtain the current gesture
   g = accelerometer.current_gesture()

   # is the micro:bit face up or face down?
   if g == 'face up':
      display.show(Image.HAPPY)
   else:
      display.show(Image.SAD)

Once again we indent the main code inside a While True: endless loop so the program can continuously test for gesture changes.

After you've downloaded and run this program on the micro:bit modify the code to discover other recognised gestures, such as: 'up', 'down', 'left', 'right', 'freefall' and 'shake'.

Return to the BBC micro:bit MicroPython Coding Tutorials page.

22 May 2017

Temperature Sensor (micro:bit MicroPython)

In this example we obtain the temperature of the micro:bit processor, which rises quite quickly after it is powered on.

from microbit import *

while True:
   # obtain the CPU temperature
   t = temperature()
   display.scroll(str(t) + 'C')
   # wait 5 seconds before repeating
   sleep(5000)

Once again we indent the main code inside a While True: endless loop. However, this time there's a five second delay between each loop iteration.

Notice that we also use the str() function to convert the integer temperature value in the variable t into a string. Leaving it as an integer will result in an error condition when the program runs.

To see the temperature rise disconnect the micro:bit for a while, so it can cool down, then reconnect to downloaded and run the program. Next try modifying the code to display the temperature in Kelvin (hint: 0 Celsius is 273 Kelvin).

Return to the micro:bit MicroPython Coding Tutorials page.

21 May 2017

Custom LED Images (micro:bit MicroPython)

Sometimes the pre-defined MicroPython images don't cover what we need.

However, the good news is we can design our own custom images. Here's how it is done:

from microbit import *

# build a string with 25 digits using the numbers from 9 to 0
# where 9 is maximum brightness and 0 switches the LED off
img = Image('99999:07770:00500:03330:11111')
display.show(img)

The micro:bit's 25 pixel LED display is arranged as a five row and five column grid. We can create our own image by setting an LED brightness value for each LED. A value of 9 represents the maximum brightness while a value of 0 switches the LED off.

The image defined by a long string of digits. This string is divided up into five sections, separated by a colon (:) character, with the first section representing the top LED row. And each section contains five digits, with the first digit corresponding to the first column.

After you've downloaded and run this program on the micro:bit modify the string to display your own LED images. It's a good idea to sketch out the pattern designs on paper first using a simple 5x5 grid pattern.

Return to the micro:bit MicroPython Coding Tutorials page.

Images & Animations (micro:bit MicroPython)

Here's how to display images and image animations on the LEDs.

from microbit import *

# images
display.show(Image.HAPPY)
sleep(2000)
display.show(Image.HEART)
sleep(2000)
display.show(Image.PACMAN)
sleep(2000)
display.show(Image.SNAKE)
sleep(2000)
# animations
display.show(Image.ALL_CLOCKS)
sleep(2000)
display.show(Image.ALL_ARROWS)

After you've downloaded and run this program on the micro:bit try out these other image names: SMILE, SAD, CONFUSED, ANGRY, ASLEEP, SURPRISED, SILLY, FABULOUS, MEH, YES, NO, TRIANGLE, TRIANGLE_LEFT, CHESSBOARD, DIAMOND, SQUARE, RABBIT, COW, MUSIC_CROTCHET, MUSIC_QUAVER, MUSIC_QUAVERS, PITCHFORK, XMAS, TARGET, TSHIRT, ROLLERSKATE, DUCK, HOUSE, TORTOISE, BUTTERFLY, STICKFIGURE, GHOST, SWORD, GIRAFFE, SKULL, UMBRELLA, SNAKE.

Return to the BBC micro:bit MicroPython Coding Tutorials page.

20 May 2017

Capture Button Press (micro:bit MicroPython)

This little program display a different image when the 'A' and 'B' buttons are pressed.

from microbit import *

while True:
   if button_a.is_pressed():
      display.show(Image.HAPPY)
   if button_b.is_pressed():
      display.show(Image.SAD)

Here we use a While True: statement which create an endless loop. Make sure you use the correct indentation levels for the code inside the loop and inside the 'if' test statements to avoid errors when the program runs.

After you've downloaded and run this program on the micro:bit try changing the image names for the A and B buttons.

Return to the micro:bit MicroPython Coding Tutorials page.

Countdown Timer (micro:bit MicroPython)

Type in the following code to create a three second timer.

from microbit import *

display.show('3')
sleep(1000)
display.show('2')
sleep(1000)
display.show('1')
sleep(1000)
display.show('0')

Notice we put quotes around the countdown numbers so they appear as strings to the display.show() function.

After you've downloaded and run this program on the micro:bit have a go at building a 10 second timer.

Return to the BBC micro:bit MicroPython Coding Tutorials page.

MicroPython Coding with Mu

What is Mu?
Mu is a free BBC micro:bit code editor, written in Python 3, designed to run on Microsoft Windows, Apple Mac and Linux computers or the popular Raspberry Pi.

Why Mu?
Mu has built-in support for the MicroPython language. It can flash programs to the micro:bit with a single click. And it has a special panel to help locate and fix coding errors.

Install Mu
Visit the Mu website codewith.mu, then follow the download and install instructions for your PC or Raspberry Pi.

Using Mu
Here's what the most important Mu icons do:
  New, Load and Save manage your Python code files.
  Flash creates a '.hex' file and uploads it to the micro:bit.
  Repl opens a command console and error debugging panel.

Coding With Mu
To begin coding follow these steps:
  1) Connect the micro:bit to the PC with a USB cable
  2) Start the Mu app and open a New code file
  3) Type in your code (see below)
  4) Open the Repl window panel (in case of any errors)
  5) Click the Flash icon to transfer and run your program

Hello Code Example
Carefully enter these two lines of Python code into Mu, then click the Flash icon to transfer it to the micro:bit device.

from microbit import *
display.scroll('Hello!')

After watching the message scroll across the LED display try replacing 'Hello!' with your own message, remembering to put it inside the quotes ('').

Return to the micro:bit MicroPython Coding Tutorials page.

MicroPython Coding in 4 Simple Steps

Step 1
Connect your PC or Raspberry Pi to the micro:bit board with the USB cable.

Step 2
Using a web browser navigate to the python.microbit.org website.

Step 3
Now carefully enter these two lines of Python code into the editor...

from microbit import *
display.scroll('Hello!')

Step 4
Finally, click the 'Download' icon, select the micro:bit device and watch the message scroll LED display.

Create a Custom Message
Try replacing 'Hello!' with your own message, remembering to put it inside the quotes ('').

Return to the micro:bit MicroPython Coding Tutorials page.

micro:bit Overview

The micro:bit is a small embedded system designed to help schools teach coding and other constructional thinking activities.

Despite its diminutive size the board is loaded with features. The most obvious are the 5x5 LED matrix display and the two push buttons.

However, there's also temperature, accelerometer and magnetometer sensors, both radio and bluetooth wireless communication, plus an array of digital and analog I/O pins that interface connect the micro:bit to electronic circuits, additional sensors, robotic kits and other gadgets.

Once connected to a PC or Raspberry Pi via the USB cable you can write and download micro:bit programs using Code Blocks, MicroPython, C++ or Javascript/Typescript.

Return to the micro:bit MicroPython Coding Tutorials page.

1 April 2017

Learn Python on the Raspberry Pi

A Gentle Introduction to Python Coding on the Raspberry Pi

The Raspberry Pi is a low cost educational computing platform specifically aimed at hardware and software experimentation.

Starting at around £4 for the Pi Zero to around £30 for the powerful Raspberry Pi 3 it's an ideal product for anyone with a desire to learn the craft of software programming and explore the powerful Linux operating system.

This interactive tutorial is based around my multi-part Micro Mart magazine series Learn Python on the Raspberry Pi.

Learn Python by experimentation, typing in the fully documented code to discover how to program useful, educational and entertaining apps.

After each topic you'll know a little more about the Python coding and the art of programming.

The Python code runs on all Raspberry Pi boards; Pi Zero, Model A, Model B, Model A+, Model B+, Pi 2 and the Pi 3 (and should also run on Windows, Mac OS X and Linux).

Here's the list of all the 45+ topics (now with more advanced subjects in section 7):

Part 1: Diving In
Why Python?
Which Python?
 Interactive Python
Assigning Variables
Using Functions
Introducing Modules
Your First Program

Part 2: Going Loopy
 Introducing Loops
 While Loops
 Timer App
 Running Timer
 For Loops
 File Walk App

Part 3: Building Blocks
 Program Structure
 Using Functions
 Creating Functions
 Guessing Game

Part 4: A GUI World
GUI Windows
GUI Code Structure
GUI Event Handling
Installing Tkinter
Simple GUI App
GUI File Search App

Part 5: Turtle Graphics Fun
What is Logo?
The Turtle Module
Move That Turtle
Draw In Colour
Turtle Patterns
Turtle Shapes
Tom The Turtle
Tom and Tim Stomp
Python Turtle Graphics for 3D Printing

Part 6: PyGame Basics
Why PyGame?
PyGame Overview
PyGame Installation
PyGame Events
PyGame Event Handling
PyGame Colours
PyGame Init Code
PyGame Screen Drawing
PyGame Complete App

Part 7: More Advanced Python Topics
Python 2 to 3 Conversion Tips
Python Turtle Graphics for 3D Printing
Handling Python Exceptions
Python Multi-core Processor Threads
Understanding Web Server Python Scripts
Python Scripting for Applications
Python Mobile Apps with Kivy
BottlePy Web Server - Tiny, Fast and Lightweight

Visit my Raspberry Pi page for news, reviews, advice and tutorials.

1 March 2017

2017 Raspberry Pi Challenges

It's 2017 so why not set yourself some new year Raspberry Pi challenges. Here's a few ideas:

Start coding in Python with my free in-depth Learn Python on the Raspberry Pi series of posts.

Use Python code to explore the downloadable Astro Pi CSV data from Tim Peake's ISS mission and create a Python Date Filter.

Build your own Astro Pi computer using a Raspberry Pi 2 or 3 and a Sense HAT.

Learn the Java programming language with tools like BlueJ (maybe using the BlueJ Learning Videos), or the Greenfoot IDE or Dr Java.

Customise the hackable Raspberry Pi Minecraft edition using Python code or with Java using BlueJ.

More Raspberry Pi Coding, Tips and Tricks