Micro:bit controls Neopixels

micro:bit, Python3.X

How to set up the hardware

Please follow the wiring shown on the photo below. There are two connections to the micro:bit, one is on the GND connector (the yellow cable on the picture), the other is on PIN0 (the white cable on the picture).

The Neopixels get their power from a battery pack, as they may draw too much current to be run via the USB interface and the micro:bit. The battery holder is made for 4 batteries, as we can only use 3, the missing battery is replaced with a wire (the green cable). The 3 batteries supply 4.5V, this is sufficient and safe.

IMG_1373

Here are some code snippets to upload, try out and modify to your liking.

You need to start a web browser and go to micro:bit to copy and paste the code below. Then press “Download” to create an executable file with the extension .hex. You find this file in your download folder. Next connect the micro:bit to an USB port and make sure that you see the micro:bit as a drive in the File Explorer. Then drag and drop the file onto the micro:bit drive icon. The yellow LED on the micro:bit will start to flash. If the program is correct, the program will start to run once the yellow LED lights up steadily. Otherwise you will get error messages with line numbers on the LED matrix of the micro:bit. Once you have fixed the errors, download again.

This first example changes the colour of the Neopixels one after another and leaves each pixel on until it is refreshed in a different colour.

"""
Repeatedly displays random colours onto the Neopixels.
Works for Neopixel strips of 30.
"""

from microbit import *
from neopixel import NeoPixel
from random import randint

# Setup the Neopixel strip on pin0 with a length of 30 pixels
np = NeoPixel(pin0, 30)
while True:
#Iterate over each LED in the strip
for pixel_id in range(0, len(np)):
red = randint(0, 60)
green = randint(0, 60)
blue = randint(0, 60)
# Assign the current LED a random red, green and blue value between 0 and 60
np[pixel_id] = (red, green, blue)
# Display the current pixel data on the Neopixel strip
np.show()
sleep(100)

Here is another example with a different lighting pattern:


"""
Adafruit example, modified to run with 30 LED strip.
see at
https://learn.adafruit.com/pages/11472/elements/2981640/download
for the basic version with one running neopixel
180815 Modified the original version, but not yet debugged.
181001 Debugged and running!
"""

from microbit import *
from neopixel import NeoPixel

num_pixels = 30
foreground = [255, 0, 0] # Int color - red, green and blue
foreground2 = [0, 255, 0]
background = [16, 16, 16]

ring = NeoPixel(pin0, num_pixels)

while True:
# red/green dot circles around a white background (for 30 neopixel strip)
for i in range(0, num_pixels-1):
ring[i] = foreground # set pixel i to foreground
ring[i+1] = foreground2
ring.show() # actually display it
sleep(50) # milliseconds
ring[i] = background # set pixel to background before moving on
ring[i+1] = background
ring.show()
# implement the closing of the circle for last and first element.
ring[num_pixels-1] = foreground
ring[0] = foreground2
sleep(50)
ring[num_pixels-1] = background
ring[0] = background

ATTENTION: This code snippet uses the concept of a block of code. The lines in a block of code belong together, here they are inside loops starting with while and for …  Everything inside the loop is repeated. In order for the interpreter to see where the blocks begin and end, each line inside is indented by four/eight spaces.

When copying the code over to your editor, please make sure that these lines remain indented.

The micro:bit

Blocks, micro:bit, Scratch2.0

The micro:bit is a tiny computer that you can program with blocks and also with other programming languages. It has two buttons, 25 LEDS, and some more sensors built in, you can add more sensors (to pick up and measure events and data) and activators (lamps, other items to do something). If you are fancy to see more, have a look here on this website, there are more projects! Today you can create a small Rock, Paper, Scissor game, follow the link below.

190918 GOLForMicroBit.jpg

Rock Paper Scissors Activity

How to use the micro:bit?

First, connect your micro:bit with the USB cable to the computer. Then you launch the editor  and write your code. At the end you need to compile (translate) the code into something the processor on the micro:bit can understand and download it. When the download is finished (a red LED on the micro:bit will stop blinking) the program will start automatically. You’re done, congratulations!

Getting started with p5.js

p5js

p5.js is a programming language created for artists. It is easy to learn and uses Javascript, the computer language of the internet and beyond. p5.js runs on a web browser, recent versions of Firefox, Chrome or Safari are fine. As such you can even run it on a mobile phone or tablet. Here you go to the p5js homepage to get an overview over the language.

Normally you need to open several windows to run Javascript on a browser, and you also need to embed your code in some basic HTML and CSS structure. p5.js provides a so called IDE that allows you to focus on the main part, coding with Javascript. It consists of an editor, allows you to execute the code, read and write data, save code and more. Launch the p5.js Web Editor by clicking on the link. Then you can code away!

First, please create an account by clicking on Sign Up in the top right corner of the window and follow the instructions to create an user account.

Don’t forget to write down your username and the password! It is a good idea to save these credentials on your Google account, then you have it always available.

A short introduction to p5.js you find here. Whenever you have finished a program or need to stop, don’t forget to save your file by selecting Save in the File menu item of the editor. Later you can reload your project with Open and continue to work.

A more comprehensive source to learn p5.js is Getting Started With p5js. This is a good introductory book with lots of code samples you can copy and paste into the editor and try out. Happy Coding is another site that introduces you to p5.js covering some topics with tutorials, and others with sample code.

These information will allow you to get up and running, on this site you also find more posts on p5.js going into more detail and showcasing sample projects.

Alice 3: Make a biped walk

Alice

There is a nice video on how to create procedures that allow you to make bipeds (i.e. characters with two feet) walk. It is here

The movement has been separated into two procedures, the first halfstep called “firstStep()”.

181210 Alice firstStep.jpg

Next we create a procedure for a full step with both legs called “walk()”.

For that we also need to create a Biped property that keeps track of which leg moves last so that next time the other leg moves. You create it also by clicking on the yellow hexagone and choose create Biped property. Here is the requester that comes up with all data you need to fill in. This property only has two values signaling which leg to move next. Values of type Boolean have only two values, they are suitable for this task.

181210 createBipedPropertyLeg.jpg

 

181210 Alice walk.jpg

Here are the two procedures used inside “myFirstMethod()”, the rest of the program is for another project, it also contains code to use colour effects.

181210 Alice walkInMyFirstMethod.jpg

Here is an add-on, it is the function walkSteps(steps). Here steps is a parameter that tells the method how many steps to take.

181211 walkSteps.jpg

 

Object oriented design elements with classes and their properties and methods as well as inheritance as a way to structure classes.

All sprites and props in Alice are arranged in a class hierarchy.

You have already encountered class hierarchies in biology. They allow animals and plants to be classified by certain criteria in a taxonomy or hierarchy. The criteria go from more generic at the top of the tree (Domain in biology) to more specific at the bottom of the tree (Species in biology). A species shares most of the properties of the respective genus, and has different ones to distinguish itself from other species.

640px-Taxonomic_Rank_Graph.png

Source:

The same concept is applied in the class hierarchie in Alice. Here the more generic classes are called parent classes, a class derived from one parent may be called child class. When you are on the “Setup Scene”, you see all characters and props arranged in classes at the bottom. The class Biped contains humanoids, but also monkeys and other animals, all of them are walking on two legs, at least in Alice. In order to create a biped character on your scene, you select the class Biped, being the parent class, and then define a child class with individual properties as age, clothes, hair, … . The class Biped also provides methods that allow you to let them act that inherited to the child class. Inside the child class you can then define own properties and methods that are only applicable to that particular class.

Inside Alice the class hierarchie can be visualised by clicking on the yellow hexagone beside the Scene Tab in the Code Editor. Here is a screenshot how it may look like. You can see the inhertance structure be the amount of identation, i.e. AdultPerson is a child class of Person that is a child class of Biped.

181210AliceInheritage1.jpg

If you want to create a procedure to make a biped walk, you select the Biped class, and then code your procedure. As a result, the procedure is available to all characters that are derived from the biped class, existing ones, but also those you may create in the future.

This is a major characteristic of so called Object Oriented Programming and helps you to structure your work and avoid repetitions of similar properties and methods.

Alice 3: Making a biped talk or sing

Alice

This video revises again the concept of objects and shows you how to create talking person, with sound and movement of the mouth.

Here is a code snippet for this, and a short description on how to create it:

  1. Add it as a procedure to the biped class, so that you can use it for all your bipeds later. For this, go the Code Editor, select the yellow hexagone at the top beside the Scene tab, and then select “Add Biped Procedure” after choosing “Biped”. in the example below the procedure is called “moveMouthToTalk()”.
  2. Next click the “this” biped above the Procedures/Functions tab on the left and by clicking and then hovering select the SBipedJoint mouth. This gives you access to all procedures and functions available for the mouth.
  3. Next drag and drop two turn method blocks on the left under “do in order” and change the parameters as shown in the screenshot below. You are now done with the mouth movements.
  4. That’s it, you have created the moveMouthToTalk procedure. In order to use it, you need to call it from within the myFirstMethod(). Make sure that you select the correct character that you want to sing and use “do in order” and “do together” blocks properly nested.

181210 moveMouthToTalk.jpg

 

Alice 3: Audio Files in Alice

Alice

181210 AudioInAlice1

When importing audio files into Alice, they should be as small as possible, not exceeding 3.6MB, this value may vary.

There are audio files with music and sounds provided as part of Alice, you can access them by clicking in the menu on “Project” and then select “Resource Manager”. The above panel will pop up, click on “Import Audio” and then browse and select the content you like to have. All these files do not exceed 1.6MB.

You can also import an own music file to Alice. Find a audio file in the internet, make sure that it is legal for you to copy it.  If the file is in mp3 format, you can directly import it into Alice. You just follow the instructions above, locate your audio file as explained before and import it. Try to play the file with the built in audio player, If it is not playing, it most likely exceeds the size limit. Then you need to minimize the size of your audio file with programs as Garageband (Mac) or Audacity (Windows). The best way is normally to reduce the audio compression to a bitrate of 64kBit or 128kBit, both values give you still a sufficient audio quality. You may also shorten the playtime of your song. You can find instructions on how to do change the bitrate with the search term “compress audio audicity” or “compress audio Garageband”.

If you are curious to learn more about audio quality and compression algorithms, have a look here.

Make the Pong game with p5.js

Game, p5js

191017 PongWithTwo.jpg

Introduction

The game is derived from the video Codetrain: pong game. The coding is broken down into different phases, implement each phase, do the testing and then proceed. Have fun!

We are using object oriented programming to make our game.

Object oriented programming (OOP):

So far we have made simple programs with procedural programming. We were putting all the code in one file, sketch.js.. In this paradigm, one line is executed after the other, loops and conditionals (if statements) control the flow of the program. We “outsourced” repetitive tasks into functions, these we could call whenever we needed their functionality.

Objectoriented Programming is different as we are modelling our problem into parts or objects. These objects have properties and methods and are interacting via their methods.  What does this mean, how does this apply to our game?

In a pong game we have two types of objects, the puck (ball) and the paddles to play the puck. The objects are defined within a class, that is a sort of template defining the properties (for a puck location, speed and size) and what it can do (show itself, change its location, react when been hit by the paddle, etc).

191016 PongObjects.jpg

Phase 1: Get the puck

Objective: Get a puck that launches in the middle and then moves towards the borders of the canvas.

The class Puck is defining the properties and actions what the puck can do.

The puck has five properties, location (with its coordinates x, y), its speed (also broken down into two components, speed in x direction vx and in y direction vy and its radius (size) r.

Inside this first version of the class Puck,we have four methods. The constructor() is creating a new puck, it also defines variables for its size, location and speed and puts some initial values to those.

The methods update() and show() change the location of the puck and show it on the canvas.

The method reset() is defining the location, direction and speed of a  new ball. We will use it later in the game whenever a point has been made and the puck needs to reappear.

To create a puck, we are calling puck = new Puck() in the setup() function. puck is then the name of the object. Methods of an object are executed with the syntax OBJECTNAME.METHODNAME(…). Example, in order to change the location of the puck, we call puck.update(), puck.show() will then draw the puck. These commands are inside the function draw that is bascially a loop.

191017 Pongp5jsPhase1.jpg

 

Phase 2: Create the paddles

Objective: Get two paddles, located at the left and right side of the canvas.

Now we create a new a class Paddle describing the “racket” to play the puck. As a first step we only create two static (i.e. fixed) paddles. The constructor has this time a variable isLeft. It can take two values, true or false. If it has true, we create the left paddle when called, if it is false it creates the right paddle.

191017 Pongp5jsPhase2A.jpg

Then create the two paddles by calling the constructor in the setup() function, we show them by using the update() and show() methods. Add the highlighted lines to your exisiting functions:

191017 Pongp5jsPhase2B.jpg

Phase 3: Move the paddles

Objective: Move the paddles with the keyboard.

Now we add an event loop. Event loops are checking the status of events, i.e. mouse buttons pressed, keyboard entries. We will use the keyboard to control the paddles. First, only enter the function keyPressed(). How do the paddles behalf?

Then add the keyReleased() method and see if the paddles are easier to handle.

IMPORTANT: After starting your sketch, you must click the mouse once inside the canvas for the events to reach your program.

191017 Pongp5jsPhase3.jpg

Phase 4: Let the paddles hit the puck

Objective: The puck is reflected from the paddle.

The following two methods allow the puck to be hit by the paddle. Add them inside the class Puck.

191017 Pongp5jsPhase4A.jpg

In order call the new methods, add the highlighted code inside the function draw().

191017 Pongp5jsPhase4B.jpg

Phase 5: The puck recognizes the borders of the canvas

Objective: The puck is reflected from the upper and lower edge of the canvas, it disappears when passing the left or right border. Furthermore, in the later case a new puck appears in the middle and starts moving.

191017 Pongp5jsPhase5A.jpg

Here is the addition to the function draw(). Make sure that the methods are called in the same order as shown here. You may need to rearrange their order.

191017 Pongp5jsPhase5B.jpg

Phase 6: The complete game:

Here is the complete game with the counter. You need to add the declaration of the two variables to count (i.e. leftscore and rightscore, line 4 and 5 in the main function. Line 31 to 33 show the counter on the canvas.

Inside the class Puck, you add the counter to the method edges(). leftscore++ and rightscore++ add 1 to the counter whenever the puck passes the left or right border of the canvas.

The main function:

191017 Pongp5jsSketch.jpg

Class Puck

191017 Pongp5jsPuck1.jpg

191017 Pongp5jsPuck2.jpg

Class Paddle

191017 Pongp5jsPaddle.jpg

Further things to do:

  1. Change the size of the puck.
  2. Change the paddle size, where do you do it? Do the changes apply for both paddles and why?
  3. Change the colour of background, puck and paddles.
  4. Can you control one paddle with the mouse, what do you need to add/change and where? The paddle should only move on the y axes, irrespective on the x location of the mouse.
  5. Add a second puck. You only need to make changes in function draw(), adding six lines of code will do the job. Do you have an idea how to do it?

Program:

Pong for Two

Scratch

Animation, Blockly, Blocks, Game

Scratch is a block based programming language. You do not need to type code, but you just assemble projects with blocks of different functionality and configure those with simple entry of numbers and text. Scratch runs on a web browser and you can also interface it with some hardware. But where to start with Scratch?

The Code Club is a UK charity that promotes computer science for young people as yourself.  They offer very comprehensive and detailed project tutorials, from small animations to a more complex  RPG(*) game.

Here is the link to the site:

Code Club Project Create your own world

(*) A role-playing game (sometimes spelled roleplaying game;[1][2] abbreviated RPG) is a game in which players assume the roles of characters in a fictional setting. Players take responsibility for acting out these roles within a narrative, either through literal acting, or through a process of structured decision-making regarding character development.[3] Actions taken within many games succeed or fail according to a formal system of rules and guidelines.[4] [Source: Wikipedia]

Make with the Arduino, with discrete hardware and Grove

Arduino, C

This blog describes the basics on how to use the Arduino with the installable Arduino IDE application. This is the program you need to write code for the Arduino and then upload it on the hardware. Following are three examples on what you can do with the Arduino.

  1. Set up LEDs on a breadboard anc control them with the Arduino.
  2. A short introduction to the GROVE platform that allows you to connect various sensors and actuators to the Arduino by simply plugging connectors to an interface board. This section also gives you links to look for sample projects and code snippets.
  3. A project using NEOPIXELs, controlled by the Arduino.

The following image shows a traffic light arrangement of LEDs. The three LEDs are connected to the Ports 2, 3 and 4. The minus cable from the breadboard gets connected to the GND port of the Arduino.

Arduino with breadboard, a traffic light with LEDs

The wiring scheme on photo.

UNADJUSTEDNONRAW_thumb_2b8d.jpg

Here is the code doing some on and off with the LEDs.

190502LEDTrafficCode.jpg

Using the Arduino with the Grove platform

Introduction

UNADJUSTEDNONRAW_thumb_2b8c.jpg

The Grove platform consists out of a shield with 4 pin connectors that allow to easily connect sensors and activators to the Arduino board. The shield is stacked on top of the Arduino board. There are

  1. 4 Analog inputs or outputs, labeled A0 to A3
  2. 7 Digital inputs or outputs, labeled D2 to D8
  3. 1 UART interface for serial communication
  4. 4 I2C communication ports, that’s a serial bus, labeled I2C. This bus is used for devices as the Ultrasoundsensor, LCD display and other sensors or activators that send or receive more complex data than what can be handled with the analog and digital ports. Each of the I2C device gets a hardware or software assigned ID so that your code can address each device individually and make it do the things it can do.

Each 4 pin connector has GND (or minus, OV), VCC (this is 3.3V or 5V depending on the switch setting beside the reset button/green power LED) and two data pins, they are different for each connector. When you are using the Grove cables,

  1. red is 3.3V/5V or VCC
  2. black is GND or 0V
  3. white is a data wire, look at the Grove shield
  4. yellow is the other data wire, look at the Grove shield

Project Ideas

Here is a link to the manufacturer of the Grove system, Seeedstudio. The Project One to Project Eight are good ways to create small projects.

190507SeeedExProjects.jpg

Here is a photo with some of the Grove sensors and activators available.

UNADJUSTEDNONRAW_thumb_2b8e.jpg

For Project Six, you can also use the “Grove LCD RGB Backlit”. You can find more information including wiring and sample code here. Please also use the code sample shown here as the function calls may be different to those in Project Six.

External libraries for the Arduino IDE (required for the following project with the Neopixels)

For some sensors and activators you need to download external libraries. These contain functions that make it easier for you to use the devices. With the Arduino Version 1.8.9 you can download them easily by selecting “Tools” in the menu and then “Library Manager”.

190507ArduinoLib1.jpg

The photo above shows the library you need to download to run the Grove LCD RGB Backlit module.

The Grove website shown above has a good document for all sensors and activator boards. So check there for more information and in particular sample code that you can then remix to your liking.

Arduino With Neopixel

Here you find a tutorial on how to connect a chain of Neopixels to the Arduino, which library to download and some sample code.

Setup the Hardware

The Neopixel requires more power than the Arduino can handle if all LEDs are on and will destroy it. Therefore you need to beef up the power supply and run the Neopixels with 3 x 1.5V batteries. Have a look again at the first lesson we had and ask for help, here is also a photo of the full hardware setup for your reference.

UNADJUSTEDNONRAW_thumb_2b93.jpg

The red and white cable coming from the Grove shield remain unconnected, the black is 0V and connects to the OV or Minus of the battery pack and the black cable coming from the Grove shield. A red cable with crocodile clamps connects the Plus (+) of the battery pack with the red cable from the Neopixels.

If that’s too much of a hazzle for you, just use the stripe with 5 Neopixels, you can easily fix it on the breadboard, it does not require any additional power. Connect matching cable colours to the Grove interconnection cable, red to red, black to black and yellow to yellow. Then download the library and follow the instructions below. You will need to initialise the Neopixel for 5 Pixels only.

Coding

Once you have the Neopixels and the PC connected to the Arduino, open up the Arduino IDE, download the Adafruit Neopixel library. It also contains sample projects to start with. Have a look in the Menu under File/Example/Adafruit Neopixel. A good starting point is the sketch “simple”. You need to change two values in this program.

  1. The numerical value for the constant PIN needs to match the port number you have chosen. On the photo it is D4, so you enter the number 4.
  2. Next you have to tell the program how many Neopixel your stripe has. The long one has 32, so change the value of the constant NUMPIXELS to 32.

The program is well documented, so just read and do the two changes where it is highlighted.

Here is the complete sample code, reduced to the parts you really need and their comments, all changes have been done already.

190514 neopixelSample.jpg

When you experiment with the code, the following hints may be helpful:

  1. random(min, max) is a function that returns a random integer number between min and max-1. If you declare random(0, 128) the function will return a value between 0 and 127. You may use it to choose a random colour.
  2. In the programming language C you need to declare the type of a variable before using it. int jvariable is declaring the variable with name jvariable as of type integer, so it can contain whole numbers.
  3. Otherwise loops (for …, while …) and conditionals (if else …) and the highlighting of blocks with curly brackets ( {}  ) is similiar to Javascript.