All posts by admin

Live Music Coding on the Raspberry Pi

The arts are a powerful entrance into computer science. In fact, there’s a whole lot of creativity that can be done with CS. One of my absolute favorites is Sonic Pi. Sonic Pi is a free program that enables anyone to code music. It’s the brainchild of Sam Aaron from Cambridge, who teaches CS there. In his off-hours, however, he’s a massive electronic music fan and DJ. Naturally, the thought occurred to him of combining these two passions and giving young people the tools to create their own awesome music while learning how to code. Brilliant!

Sonic Pi is written in the Ruby programming language, but that’s pretty much transparent once you start coding. It’s a free program, available on all platforms and is currently included in the latest release of Raspian. It’s a wonderfully integrated IDE, with 10 “buffers” (coding windows), an extensive built-in help system with examples, a window where you can watch the code as it executes, as well as an internal musical graph, so you can visualize your sounds in terms of volume, length, etc.

You can run the whole thing from the RP, but you’ve got to provide your own speaker, since the Pi doesn’t have one (trying to keep the cost and size down, remember?). But there are plenty low-cost options. And headphones are another option; most students have a set of earbuds if you’re cash-strapped. Using speakers or headphones requires one more extra step. Be sure to left-click on the sound icon in the upper right of the main Pi window. Bump the volume all the way up. Then right-click on the same icon and change the output from digital to analog. You’re good to go.

Most people start with writing a simple tune. You can do this by using the “play” command followed by a number. The numbers correspond to the MIDI numbers, so middle C is 60, like so: play 60. That command plays one note of middle C for one beat. A beat is roughly a second, since the default bpm(beats per minute) is 60. It also plays that note with the “beep” synth. A synth is sound that the notes play their notes with. The default synth is a beep, but as we’ll see, there are dozens more available.

If you are familiar with musical notation, you may instead say “play :C4”. Watch that colon! It’s required for the name of the note, but not the number. The easiest way to set up your code is to put each command on a separate line, like so:

play 60
play 64
play 66

You then click the Run button at the top, and your music plays. Or not. If you’ve made an error, it won’t play, but the output window right beneath the code will tell you, in more or less intelligible English, where and what your error is. I find the Sonic Pi/Ruby error messages generally make more sense than the Python ones to most students. In the case of the above sample code, it will play, but the results will not be what we expect, because it will play all of the notes at the same time. In other words, it plays a chord. It’s all very well if that’s what we wanted, but it isn’t. We wanted three distinct notes in sequence. Why didn’t Sonic Pi know that? Well, as we’ve said before, computers are dumb. They also execute commands ridiculously fast, depending on the computer itself, what else it’s doing at the moment, and a host of other factors. So running that code essentially plays them all at once.

How do we avoid that? Simple, we’ve got to tell the music to pause after each note. Musical notation does this, of course, so we just have to know how to make Sonic Pi do it. The command we want is “sleep”, as in “sleep 1”. What if we want pause a half beat? sleep 0.5 (and yes, the 0 is necessary). So if we want to play those three notes, and vary the timing, we could do something like this:

play 60
sleep 1
play 64
sleep 0.5
play 66

Try it! Then experiment with the timing between the notes, then the notes themselves. Take on Twinkle, Twinkle or Mary Had a Little Lamb. I get bored with those; my personal favorite is Seven Nation Army! Just a bit funkier than Twinkle Twinkle.

Of course, the whole point of using a computer is to get it to do the boring, repetitive work. Why should I waste my time and energy typing the same code in twice? I do realize there is copy and paste available, but even with that, it clutters up the buffer and makes me crazy by forcing me to scroll up and down to look at the code. One simple command solves that:

2.times do

Here’s the tricky part. Just as with using indents in Python, we have to have a way to tell the computer exactly what it is we want it to repeat, we have to do the same with Sonic Pi. We do this be placing an “end” after the material we want repeated. Like so:

2.times do
play 60
sleep 1
play 64
sleep 0.5
play 66
end

Sonic Pi will usually indent the code for you, but it will still run even if not properly indented, unlike Python. I tell students that it’s like a pair of sneakers: they always come in pairs. Every “do” requires an “end”. Make sure you follow that rule, or you’ll get some unexpected results, or no results and an error message. And also note that can specify exactly how many times you want the code to repeat by just changing the number in front of .times: 33.times do.

Next question, of course, is…. how do I get it to play forever? Now we’re getting computer science tricky. In Scratch, it’s “forever”, and in Python it’s “while True”. In Sonic Pi, it’s called a live loop. And you set it up like this:

live_loop :twinkle do

Several things to observe here. First, don’t forget the underscore character between live and loop. Secondly, don’t forget that colon before the name of the live loop. Third, you can call the loop whatever you’d like, though it makes sense to call it what is, since you’ll have multiple loops, and if you call one “fuzzybunnies” and another “fattedfrogs”, after a while you probably won’t remember what exactly each one does. Fourth, don’t repeat the loop name in the same buffer, or Sonic Pi will just play one of them. And lastly, don’t forget that “do” at the end of the line! And you know what that means — yep, you’ve got to end the code with an “end”.

Seems like a lot to remember, but not really. After a little while it will become automatic, like all other coding conventions.

So we’ve learned how to pick out a simple tune, play it a few times or forever. But you have to admit that the excitement of that wears off pretty quickly. Partly because those beep notes aren’t too exciting, once you get over the initial excitement at coding a tune. How about we change the sound of the notes? We do that with what are called “synths”.

A synth is not the note itself, but the way the note sounds. For instance, you can play the same not on a clarinet, a piano, and a distorted electric guitar, and you’ll get three very different sounds, though the notes are all the same. Sonic Pi has many built-in synths, so we can create all kinds of moods and sonic layers with some simple code. The relevant code is “use_synth”, and it must be situated BEFORE the notes that you want to modify. The easiest way to experiment is to type the command on its own line and then hit the space bar. That will open up a dialogue box of all the synths that are available on your version of Sonic Pi. The list is alphabetical, and you can simply scroll through the list till you find one that sounds interesting and it will insert that on the line in correct Sonic Pi format. Find something that intrigues you and try it out! As Sam Aaron always says, there are no mistakes! If you don’t like it, cursor up to the line, hit backspace to erase the name of the current synth. Stop your backspacking just before you hit the h in use_synth, and then hit your space bar again. You’ll get that alphabetical list of available synths again. And if you get tired of arrowing down through the list, or you know that you want to use tb303, for example, hitting the “t” will jump you down to the synths that start with t.

Now, admittedly some of them don’t sound particularly musical, in fact some of them sound like noise! Which is, in fact, what they are. But there’s a place for noise in certain pieces, so maybe save those synths for when you need them.

The other magical thing about Sonic Pi is that it enables you to do LIVE music coding. Some students, especially if they have some musical background, want to recreate their favorite song and so want guitars, piano, bass, etc. My experience is that Sonic Pi can certainly do that, but that misses out on the fun. LIVE music coding means that you can change the sounds AS your piece plays, adding or subtracting synths, beats, and samples as you go. So it becomes a live performance piece, something like a DJ will do. By mixing in and out pieces of sound, the DJ creates something new on the fly, so it’s a performance. Fun!

There are so many amazing and truly advanced things that you can with Sonic Pi, that it goes beyond the scope of this book. There are a host of amazing resources out there and I’ve listed several of my personal faves at the end of this chapter. But I would be remiss if I didn’t at least touch on three other amazing tools in the Sonic Pi toolkit: samples and opts and effects.

A sample is simple a piece of sound. They’re used all the time in music. Hip hop artists routinely sample other songs or sounds and build their own songs out of them. Sonic Pi comes with a host of built-in samples. Some are musical (drums, for instance), and some are random sounds (like the ever-popular burp). They are used by the simple code “sample”. As with the synths, if you hit the space bar after you type e in sample, a dialogue box with a list of all the samples pops up, and you can scroll through till you find something you like. It plays like a note, for whatever duration you specify. So it’s a timed unit of sound, like a note.

The other cool thing that’s available in Sonic Pi is what we call an “opt”. That’s short for “option”. An opt is a device that lets you change the sound of the note or sample in some way. For instance, you have access to the entire ADSR filter range (Attack, Decay, Sustain, Release), by which you can shape the length of a note, how long it takes to trail off, etc. You also have access to a range of other options like panning, and volume. You use these by putting them on the line of the sound you want to effect. So if you want to add more volume to a note, you would code
play 60, amp: 4

That would make that note 4 times louder than the normal volume (which is 1).

And finally, there are multiple effects you can add, like reverb and delay. If you’re familiar with effects pedals for the guitar, this will make you feel right at home. Except instead of stepping on the pedal, you slap it into your code where you want the effect to start. And each effect us fully customizable, so you can code different types of reverb for instance (room, hall, plate, etc.).

with_fx :reverb do
play 60
sleep 1
play 64
sleep 0.5
play 66
end

Don’t forget the do at the end of the effect line, and of course, you need to tell Sonic Pi when to stop using it, so you’ll need an end for that.

It’s truly amazing what students can create with a few simple tools! And for those who will tell you “I’m not a musician”, I always give Sam Aaron’s answer: “Not yet!”

Coding on the Raspberry Pi

You can do a lot of amazing, creative and cool stuff with a Raspberry Pi. But for our purposes here, we’re going to discuss how you can use it in a middle school computer science context. And while that’s not strictly limited to code, that’s our emphasis.

So for beginners, RP comes with two standalone versions of Scratch: 1.4 and 2.0. What, no web-based Scratch with all the social and sharing features? Afraid not, but what we can do on the RP is pretty awesome. We can code using the GPIO pins using Scratch, which opens up a whole new world of physical computing, electronics, and digital making. Don’t get me wrong, I love online Scratch and its community. But RP Scratch allows your students to go beyond code-in-a-window and get it to interface with lights, buzzers, cameras, and anything else you can connect to your GPIO pins. Because it’s still block-based Scratch, it’s an excellent jumping off point to learning how to code physical things, like LED’s. And there are many resources available that allow you to create the same program in Python. So then your students can make that jump to text-based coding with the same setup. For instance, they can attach an LED and a resistor to a breadboard, get that LED blinking with Scratch, then when they’re ready, they can accomplish the same feat in Python. Doing the same thing in two languages increases the understanding, especially when you do them side by side. And that eases that sometimes tricky on-ramp to text-based coding.

Scratch 2.0 looks and acts a lot more like online Scratch. So why would you use 1.4? At this point, 2.0 is still a bit slow in executing code, and we all know how patient most middle schoolers are! For that reason, I’m still using 1.4. But I’m ready to switch up when a future version is zippier!

Once your students are comfortable with Scratch and block-based coding and ready to make the leap to text-based code, RP has Python 2 and 3 built in. Both run IDLE as the IDE, and while it’s pretty bare bones, sometimes that’s a good thing. Especially when students are learning not only a whole new language, but a whole new paradigm. Thonny, which is a great Python editor with many more bells and whistles, is also included in the install, but I’ve found it’s overkill for beginning Python students and creates unnecessary complexity.

I would highly recommend using Scratch, a breadboard, an LED, and a resistor to do your first “blinky lights”, which is the physical computing version of Hello World. It takes some patience and a serious attention to detail. If you’re also looking for a good way to introduce some electronics concepts (which are useful in understanding computers), such as voltage, resistance, ground, positive and negative… this is a great entry way. Once you get everything hooked up correctly, then you write the code in Scratch to use a particular pin as your output/input pin, and use those Scratch concepts that are so familiar: forever loops, waits, and broadcasts. And voila! Lights are blinking! From there, add something else — perhaps a different color LED or two, make some traffic lights… add a buzzer that sounds when your character reaches a certain score. Suddenly you’ve got code that works in two “dimensions” — on-screen and in the real world. Now it’s starting to get exciting!

The next step for students after Scratch is a subject of a lot of debate in the computer science education world. How do we get from dragging blocks, where it’s nearly impossible to create a syntax error, to text, where it’s nearly impossible NOT to have a syntax error? I personally agree with the Computing At School curriculum in the UK that Python is the next logical step. I have a couple of reasons for this. First off, the language is more “English-like” than other possibilities, like Javascript. Secondly, it’s an actual real-world language which has loads of libraries available for all kinds of applications. And there are actual Python jobs out there, so learning this language might someday lead to some money! I do like other introductory languages, like SmallBasic, but it’s a dead end.

Another plus with Python and the RP is the abundance of support material available. The RP website alone has hundreds of sample projects, code samples, and ideas, as well as Python tutorials. And there is a whole awesome Python code library for controlling the GPIO pins (gpiozero), which has built-in functions in the API that support many of the most popular hardware add-ons (called HATs in RP lingo — Hardware Attached to Top). I’ve found that segueing over from Scratch to Python using gpiozero code is a relatively painless transition.

Of course, no matter what you choose as your first foray into text-based coding, there is still a hurdle to overcome. Here are some strategies that I’ve found helpful for students.

The first one is reminding them that 1. computers are dumb and 2. you have to speak to them ONLY in the way they understand. Error messages are Python’s way of training you how it wants you to speak to it. I find that putting it this way, while it doesn’t eliminate frustration, does help the students to understand that it’s the computer that’s dumb, not them. A small shift in thinking, but powerful.

The second thing I do is to demo “live coding”. I pick a sample easy intro bit and code where they can see it, and I talk through it as I code. I say out loud what I’m thinking as I code. And inevitably I make mistakes. Then I look at the error message and talk through reading it and trying to figure out what it’s saying. You would be amazed how effective this is, for several reasons. First, I’m modelling the thought process of coding. That removes some of the mystique (and gypsy magic) of coding. And perhaps more importantly, I model that I, the supposedly know-it-all teacher, make boneheaded mistakes. Many times. And I have to fix them. Which includes reading the error messages, trying to puzzle it out, changing the code, trying again, getting another error perhaps, puzzling through that one, changing the code again, etc. It’s a process that EVERY coder must go through. Students who are not used to failure and fear it as a plague will learn that it’s all part of the process. Even Mr Irving fails all the time. That’s just normal.

On a more Python-specific note, I usually talk or demo the importance of indents. Python does not have much in the way of squiggly brackets, semi-colons, etc., that other languages do. What it does have is indents. And they really matter.

Raspberry Pi — the little computer that could

 

In the last few years, we’ve seen a slew of single board computers (SBC’s): Arduino, Beagle Board, Raspberry Pi…. They all have their place, and we’ll speak a bit later about what those places are. But I’m here to tell you that for all-around computer science use and mega bang-for-the-buck, you just can’t beat the Raspberry Pi.

By now, most people know about its back story, springing out of Cambridge University and a desire of their CS profs to acquaint their students with what a computer actually IS. There’s no doubt that computers are easy to use today, but that very ease of use has taken away some of the fun and excitement of learning how a computer works and how to get it to do what you want it to do. I’m totally dating myself here, but I do remember getting a Commodore 64 (cue the “backintheday” music as Grandpa regales the young’ns with tales of yesteryear). When the 64 first came out, there was a dearth of software available. But it did come with a thick spiral bound book called “Commodore Basic”. The expectation was that anyone who bought a computer would certainly want to program her own software, not just buy stuff off the shelf. And there were several magazines on the newstands that had “type-in” programs that ran several pages. I think some of it was even in assembly language! But the thinking was that computers helped you get stuff done, play games, etc., but also were things that you could use to make your own stuff.

Today, computers are a black-box technology, like a car. How does a computer work? I love asking that question and seeing the blank faces of my students! It’s easy, Mr I, you push the button! My personal favorite answer is “gypsy magic”; top points for creativity. But that doesn’t get us any closer to understanding what a computer actually is! Though it’s a wonderful fulfilment of Arthur C Clarke’s saying that any technology that we don’t understand is the same as magic. So if we can start to figure out how it works and get it to do stuff that we want it to do, then I guess we’re wizards! All right!

So this little credit-card sized, $35 computer is getting us closer to being magicians, and probably better than anything else available today. So how does it do this, exactly?

First of all, it’s not in a box. You can see the motherboard, the CPU, the traces on the board… You can plug sensors and wires into its 40 GPIO pins, which provide voltage and “channels” you can use to code attachments. And the attachments are plentiful and not too expensive, running the gamut from sensors to lights to buzzers to cameras to audio devices to… whatever! You can see both sides of the USB ports, so the mystery of the inside of the computer is laid bare.

The Raspberry Pi Foundation provides an updated OS, as well, called Raspian. It’s an offshoot of Linux (but so is the Apple OS, so don’t be scared). This OS has a modern looking GUI (graphical user interface) and comes with a host of programs that you can run right away. So it’s not too scary looking to students familiar with Windows and Apple: desktop, menus, icons, left and right clicks, etc. Pretty intuitive, we’d say. However, some tasks require digging into the terminal, a CLI (command line interface), which goes way back. And while that’s new and different to many students, it’s not impossible. Though, as I often remind them, spelling counts!

And it comes with an ever-changing assortment of free, open-source software (and that can actually be an interesting discussion. Why is this software free? Who writes and maintains it? I love seeing the students eyes widen as the catch a glimpse of an economic model that’s an alternative to individualized capitalism…). The current version as of this writing (Stretch, and yes, all of the versions of RP are named after characters in the Toy Story series. So if you had any doubts about how cool this all is….) includes the Libre Office productivity suite, Mathematica, a browser, some games, and most importantly for our purposes, a host of programming tools and environments. Scratch 1.4 and 2.0, Python 2 and 3, Java, Greenfoot. An older version of Minecraft is included FREE, and though it’s not the latest and greatest, it’s perfect for learning coding. Check out my chapter on that. And there’s even a live music coding application called Sonic Pi. While I wouldn’t use it for my everyday computer, it can do a lot that an everyday computer can’t do, like physical computing and attaching to other machines.

One thing that the Pi doesn’t have is a hard drive. In order to keep the form factor small and the cost down, they work by loading the OS (Raspian) from an SD card, which autoboots when the Pi is powered. Programs are saved to the SD card as well. So it’s a little bit of a throwback to DOS.

So what do you need to get started with RP in your classroom? Well, that $35 computer thing isn’t entirely accurate. You’ll need a few other things, but the RP people rightly figure that everybody already has a keyboard, mouse and monitor. All of these are plug and play. Latest version of the Pi has 4 USB ports and an HDMI port. You’ll also need some sort of power source, and the wall wart variety are available and usually come in a RP kit. In my classroom, I power them from power bars that have USB slots, which I’ve found preferable to having 25 wall warts to take care of. I use the power bar to power the monitor and the other computers I have in my room, which all run Windows 10.

How do you get Raspian on an SD card? Fortunately, www.raspberrypi.org has download links for the latest version, as well as instructions for how to download it and install it on an SD card. Once you put Raspian on the SD card, put the card in the Pi, and power it up, the installation software takes over, prompting you from time to time for your preferences. Don’t worry, all of the preferences can be changed from the settings menu on the Pi.

Because it’s based on Linux, which is based on Unix, which is a user-based system, the Pi requires a login. The initial default username is pi, and the password is raspberry. You should change that as soon as you can. One advantage to this is that if you have multiple students using the same Pi and the same SD card, you can set up different users so they don’t all save to the same folder. It’s not necessary but you might save yourself and your students some serious grief. I’m not sure why, but students sometimes all use the same filename when they save their Scratch game (“game” is a favorite). And if that happens, Johnny will overwrite Suzie’s Scratch “game”. Ouch.

Robots robots robots

There’s not much that can compare with the joy students get when they build and program a robot. I’m currently using 2 platforms — the Dash robot from Wonder Workshop, and NXT LEGO Mindstorms. I use the Dash in 5th grade, and the NXT in 7th grade.

What’s the attraction with robots? Well, they can move, make noises, and respond to their environment. What’s cooler than that? Not only that, but we can make them do what we want them to do, so they can become our own little minions!

The secret sauce of robotics is that we can actually watch the results of our code manifest right in front of us! We know right away if the code is right or wrong, so there’s immediate feedback. I always tell students that it’s not like other classes, where they take a quiz or test and have to wait for their teacher to grade them and get them back to you. You know right away! Not only that, but then you can modify your code and run it again. And you can do it as many times as you like in order to get it right. Yes, there’s frustration along the way when your robot doesn’t do what you want, but oh the joy when it does! Happy dance time!

Along the way, students learn something really important about robots — they’re kind of dumb. They can only do exactly what we tell them. They can’t figure out what we mean. We humans can “fill in the blanks” when others try to communicate something with us. We can infer meaning. Robots can’t, at least not yet! So that means we have to be super careful about all the instructions we give them. Welcome to computer science! As a side note, what a great training ground for middle schoolers who have organizational challenges and need to pay attention to detail! And I always tell them when they complain about how their robot is “dumb”, they’re only as smart as the instructions we give them! Ouch.

What about how many students per robot? I realize there is a range of opinion on this, and I get the importance of collaboration. However, I’m a big believer in each student having her own technology, if at all possible. There’s something to be gained from knowing that the success or failure of your robot rests entirely on you! But that may not be feasible in your situation. So work with whatever you have, but be sure that all members of the teams take ownership of the robot’s success and share the challenges as equally as possible.

So how to structure a robotics unit? My approach is to have the robots simulate a real-world series of tasks. In 5th grade, with the Dash robots, we are currently doing the “Robot Olympics”. Most of these challenges mirror Olympic events, but I’ve also taken the liberty to make up my own events. I made a 3X3 grid on the floor with duct tape or gaffer tape, which is where the events take place. Right now I’ve got Olympic tic-tac-toe, diagonal racing, curling (well, kind of), and whatever else inspires me. Teams compete and I keep a scoreboard on my whiteboard to let teams know how they’re doing. Because the Dash robots come pre-built, it’s really a matter of coding. Wonder Workshop provides 3 different platforms for coding Dash (and Dot, his less useful sidekick), and I use Blockly in 5th grade. It’s Scratch-like and fairly easy to do the dragging and dropping, making the coding the harder work. Students generally are fully engaged and love the competition. Since this is my first year of using Dash, I fully expect to build this out further. Wonder Workshop has all kinds of challenges on their site which I have yet to explore, so I anticipate continued success with this platform.

In 7th grade, I use the NXT LEGO Mindstorms platform. I realize that the EV3 has replaced the NXT, but I honestly have not seen enough compelling change in the new platform to convince me to do a wholesale switch. At some point it will happen, as the NXT bricks get harder and harder to find, but for now we’re good.

I have each student build the basic Tribot model, then add sensors as needed. I use the ultrasonic sensor first, then mix in challenges with the touch and light sensors. The sound sensor is less useful for my purposes, possibly because of the volume level of my classes (did I mention that it can get loud?). So I hardly ever use the sound sensor.

In my current iteration of challenges, I model them all after a real-life robot used in hospitals around the world called the TUG robot (built by Atheon). This robot can navigate through the hospital autonomously, avoiding obstacles and making deliveries. It can even call an elevator and choose which floor to exit at! My challenges model some of these functions. I chose the medical robot for a variety of reasons, not least of which is that it’s involved in helping people in a real way.

Some students find the building of the robot challenging, though I give them official LEGO building instructions printed out in official LEGO language (all pictures). Some students have spent much of their childhood playing with LEGO’s and are already “master builders”. Some have never connected any LEGO’s at all. Again, attention to detail is paramount. I tell them to make sure they double and triple check each part of the build, hold their robot up to the paper and be sure everything is correct. Why? In robot building, attention to detail is crucial, and if you find on step 22 that something’s wrong, you’ll have to “unbuild” your robot back to the point where you made the mistake, even if that’s on step 5! Ouch. Hard fun again.

So what does this look like in class? To be honest, sometimes it looks like complete pandemonium. Learning is messy. In one corner of the room, there are students moving a trash can in front of their robot, simulating a moving obstacle in a hospital hallway and trying to get their robot around it. In another corner, one student is helping another rebuild their robot so it works(though they have to follow my rule: don’t touch the other person’s bot!). In another corner, students are getting a mini-lesson from me on how to navigate the software and download it to the robot. On the board, I have my Help List, which determines in what order I answer questions. When students have tested their robot and know they have it working right on a particular challenge, they put their names on the Help List and excitedly demonstrate their bot meeting the challenge (or not. Sometimes it still doesn’t work, and they are back to coding and running the robot again, with some modifications on either the code or the bot). At another workstation, one student is helping another student with the code (again, following Mr I’s rule — don’t touch their keyboard or mouse), pointing to the screen and showing where their mistake is. 2 people are going through the bins in one corner of the room to find that special LEGO piece they’re missing, holding it up against the printout to make sure that axle’s the right size…

You get the picture.

What am I doing all this time? Trying to keep one eye on the Help List on the board, letting kids know they’re next for my help, circulating through the room, fending off questioners who want to skip the HelpList, listening and watching for frustration (not always a bad thing!), nabbing the odd student who isn’t focusing and getting him refocused, checking the clock so I don’t forget to give the 5-minute warning (time to clean up! LEGO sweep at your feet! turn off your robot and put it in the closet! hang up your programming cable and restart your computer!)… every class is a trip.

I wouldn’t have it any other way.

Minecraft and Python — text-based coding!

For my first foray into text-based coding, I recently moved to coding Minecraft with Python. Or “Mython”, as I affectionately call it. I’ve tried other things, like Small Basic and GameMaker (GML, their text language) and, while students can learn from any platform, I felt Minecraft offered more bang for the buck.

The engagement factor is off the charts for Minecraft. I’d be crazy not to try to tap into that. So I launched a year-long exploration of various coding environments for Minecraft(you can see my now somewhat-dated presentation from CSTA 2015 here). My conclusion was that Python offered the best entry-point, and the amount of support available tipped the scales for me. Here’s why:

It’s fairly easy to install and available on Mac, PC, Linux, and Raspberry Pi. For the first three, you’ll need Minecraft, Python, and an implementation of a Bukkit server so that each student can run her own instance of Minecraft. She will also need a Minecraft license (which does cost $27US, but many kids have one already). The beauty of Mython on the Raspberry Pi is twofold — no need to purchase a Minecraft license, since Mojang donated an early version of Minecraft to the Raspberry Pi Foundation. And the Bukkit server is not needed. So there are two big steps you can skip, if you’ve got a set of Raspberry Pi’s (see my chapter on RPi for many reasons why you should consider this).

So why Minecraft?

Engagement level is super high.

Most kids have some familiarity with the game.

The ability to “mod” Minecraft is enticing (though this isn’t modding in the strict sense of the word).

Support is good. I highly recommend getting a copy of the Mython “bible”: Adventures in Minecraft by David Whaley and Martin O’Hanlon. These two gents from Great Britain literally wrote the book on coding Minecraft with Python, and it’s all laid out in an attractive, logical, and clear way, with lots of cool challenges to extend your learning. The authors host an awesome website (www.stuffaboutcode.com) which has a forum for those thorny questions. They are more than willing to help out, and I’ve found these two to be always helpful. In addition, they are on Twitter and have always responded quickly, kindly, and accurately to my questions. And version 2 of Adventures in Minecraft now has support for the Microbit board!

Check out the appendix of the book for more resources.

Here’s how I “teach” Mython. As you might gather from my pedagogy, there’s a reason I put “teaching” in quotes. I stole the idea of the “hackpack” from Chris Penn in Great Britain, as well as some of his excellent code ideas and challenges. I print out “hackpacks” for each student. These include anywhere from 4-7 programs on a particular topic (the first covers basics and building, the second covers triggers, etc.). The code is liberally commented with explanations of what the code does, how it works, analogues to Scratch, gotchas, and whatever I think will help the students understand the code.

And yes, I give them a printed paper copy of the code. That’s by design. I know that copy/paste works great for getting code, and I use it all the time. However, I believe when a student is learning a new language, the muscle memory that she uses by actually hitting the keys and looking at the screen is invaluable in making it stick. It also gives the student a fabulous opportunity to become personally acquainted with error messages! I tell them that error messages are their friends. They don’t believe me, of course, but it’s true, because Python is training them to speak in a way that it understands!

That, of course, is the big difference when we take the training wheels off! It’s now possible to make syntax mistakes! Spelling! Punctuation! Capitalization! Indents! All of it matters. And Python doesn’t know “what you meant”; it only knows “what you said”. Sorry! But welcome to the wonderful world of code.

The good news is that students want to make their code work, and they’re willing to keep at it, fixing errors, until it works. Aha, the magic of Minecraft! Much preferable to doing coding exercises that sort lists or do math or any of the other introductory exercises I’ve seen. I have to confess that my reaction to all of those is a great big “meh”. Who cares? I already know what 8 + 7 equals. Doing it in Python doesn’t make it much more palatable. But if I can figure out how to teleport myself 80 blocks up in the air and 40 blocks to the east, well, that’s cool! And incidentally it’s also teaching a 3-dimensional coordinate system, but shhh…. stealth teaching, remember?

So they get their hackpack, and they type in the code, and it works! Fiero! The dance of joy! But they don’t actually earn any credit for that. I tell them, “Congratulations, that means you can type.” To earn points, they must code what I call a “reverse”. That is, they have to take that code and do something different with it. For instance, one of the hackpacks has code that updates my position every second and displays it in the chat window with the relevant x, y, and z position. The “reverse” is to display it every 4 seconds. Hmm… how to do that? Well, where in the code do you say to display it every second? We look at the loop (while True:) and find the code that says to get my position and post it to the chat. Do you see anything that says to do it every second? Oh… time.sleep(1)! The light goes on, and they swap out the 1 for a 4! Easy peasy! But they’ve learned about a loop, they’ve learned how to get and update my position continually, they’ve learned how to print that to the user (Hello World!), and they’ve learned about delays as well (and that you have to import the time library in Python for it to work).

And I didn’t have to stand at the front of the class and say, “Today, class, we are going to learn about… now follow me as I type on the screen and type that exactly, all together now…” Yawn. Students do it at their own speed and find their own “aha moments”! And they get to see it actually happen in Minecraft, on their screen, caused by the code that they just typed in! Woohoo!

So you can see why I’m excited about using Minecraft for teaching coding!

Another carryover, I’m hoping, is that when they go from my class in 8th grade to our 9th grade CS class, where they will code their own original games using the Pygame library, that at least some of this will be burned into their brains. At the very least, they’ll remember they have to be careful with what they type, since they learned firsthand how picky “the Python” can be!

So if I had a standards-based curriculum, what CS standards and concepts have I “covered”? By the time we’ve finished the unit, we can check off: conditionals, events, triggers, 3D coordinate systems, for loops, variables… in Python, they’ve learned about importing libraries, proper indents, colons and why they’re essential, and how to read Python error messages. But again, shh…. let’s not spoil the fun.

Taking off the training wheels – block and text coding

Most teachers agree that it’s better to start with block-based programming, and I heartily agree. I don’t introduce text-based coding till 8th grade and that’s only after my students have had a thorough exposure to a few different styles of BBP. There are so many possibilities that it’s just a matter of choosing what works for you and your students. Here’s what I’m using currently:

I think Microsoft really hit it out of the park with the MakeCode environment for several reasons:

it’s free.

it’s web-based, so accessible from a variety of devices.

it works on several different hardware and software platforms and more will be rolled out as we go. As of this writing, it supports Microbits, Circuit Playground Express, the Chibi Chip, Wonder Workshop’s Cue robot, and the queen of them all, Minecraft(only Education Edition, however)! That’s important to me because I use the Microbits in 5th grade, the CPX and Minecraft in 6th, so students can become familiar with the environment and make an easier transition from one to another.

also, did I mention that it’s free?

And of course, there is Scratch, just getting ready to release version 3.0 as of this writing. With their web-based environment as well as old-school standalone Scratch, it’s the perfect introduction to block-based coding. I use it for game creation in 7th grade. It’s a wonderful vehicle for learning some advanced CS principles in a relatively painless way: loops, conditionals, events, and variables. I say RELATIVELY painless because students still have to wrap their heads around the concepts. But they don’t also have to deal with syntax errors, and the results of their own misspellings and mispunctuations.

There are lots of other platforms that can work for you and your students. My advice is to pick one or two and stick with them. The important thing is for students to start to understand the CS concepts, so that when you introduce text-based coding, they understand what they’re doing.

A matter of debate is what should the first text-based coding language be, and when should it be introduced? I prefer Python. It’s more accessible, I think, than other languages, because it’s more like natural language than say, Javascript. So it has a pretty easy on-ramp, and lots of ceiling. It’s a language that students can grow with, with its thousands of libraries for everything from Raspberry Pi input/output to gaming to scientific algorithms. There are jobs out there that require Python. And the Computing At School curriculum in Great Britain uses it as the first text-based language. That’s a pretty powerful endorsement.

Downsides of Python? There are a couple. Perhaps the biggest is its sensitivity to incorrect tabbing. If you use IDLE, the built-in editor, it will automatically tab lines correctly in if statements and for loops, but I’ve seen students reach maximum frustration when the code just wouldn’t work, and it turned out to be a misplaced tab. Ouch.

Other languages? I’d suggest 2 other possibilities: Small Basic and Javascript, in that order. Small Basic is Microsoft’s technology for entry into text-based coding. It has auto-complete (usually useful), and introduces dot notation, an important feature that they’ll run into in many languages. It’s also very natural language-like, more so than Python. I’ve found that students find that it just makes sense. Plus it’s got a great built-in turtle graphics system, which is a fabulous way for students to SEE the results of their code.

Problems with it? No jobs out there that use it. And where do you go next? I suppose you could argue for Visual Basic, but that’s not a path that most schools go down in high school. So it’s a bit of a dead end.

Javascript was chosen by Microsoft to be the language that MakeCode translates to. I have to say that I really wish they had chosen Python for this. However, it is used widely everywhere, on the web and elsewhere. And it’s certainly more accessible to most students than C#, C++, or (God help us) Java.

Whatever language you choose, that initial experience of what I call “taking off the training wheels” can be challenging to most students. I try to liberally comment my Python sample code with references to what they know in Scratch. For instance, I will do this

while True: #same as “forever” in Scratch

But there is inevitably going to be that time of discomfort as students try to make that leap to Python syntax. This might be an argument for using Javascript in the MakeCode environment, since you can switch from blocks to text with the click of a button. I haven’t tried this, so I can’t recommend it. Truthfully, I think I’d rather not have those training wheels so convenient, since students might be tempted to not take them off, and thus never truly learn how to ride that bicycle (to strangle the metaphor).

Middle School Computer Science — whaat?

I’d like to say that this post will be the first in a series of posts. But I’m hesitating because I know how my relationship with this blog works. Kinda like a long-term friend that you know you should be contacting but somehow you don’t. And then you feel guilty.

So I’ll just start. I teach middle school computer science. That means grades 5-8 in my school. And I’m lucky that it’s a required course. I have every student in the middle school for a full quarter (about 9-10 weeks). 5th and 6th graders have me 3 times a week, 7th and 8th, 5 times. I’ve been at this for about 15 years and I’m busily building out my curriculum. As you know if you’re in this world, nothing ever remains the same. There’s always a new programming language, a new robot, a new board, a new computing platform… My job is to survey the landscape, see what’s new and cool, and decide what fits in my program.

I have a few guidelines that I use to decide what I incorporate. First and foremost, will kids love it? By that I mean, will they come running into the room, eager to fire up their computer or robot, and get started? If it doesn’t pass that test, it doesn’t make it into the program, sorry. So that means it’s got to have a fairly easy on ramp, and enough ceiling to keep even the advanced kids hopped up and moving ahead.

Secondly, will it work for what I call “stealth learning”? Will the projects and challenges that I use to frame their learning keep them engaged, challenge them, and advance their skills and knowledge in computer science? That’s the stealth part. I very rarely start a class with me talking about a concept (what the rest of the educational world calls “teaching”). I would much rather give them a challenge — as in, “Can you make this robot navigate around the room continually without bumping into anything?” I know this might go against the way that a lot of people frame learning, and I’m OK with that. I’m not saying it’s the only way to do this; it’s just the way that I prefer to do it. And I’m not opposed to “traditional teaching” if it’s obvious that it’s necessary for a student or a class. More on that later.

So for programming concepts, you can probably spot what the challenge up above requires. Events and loops, for starters. If/then… if the robot senses an obstacle, then do something to avoid it. And keep doing that, over and over again….

But how do they figure that out, you ask? You haven’t even introduced them to the programming environment! I’ve found that most middle schoolers only want enough “instruction” to get started and help them achieve their goal. So I give them as little as possible, and only when they’re wanting to learn it. It’s called just-in-time learning. Not a new concept, and I didn’t invent it. But I know it works.

Thirdly, will the tech support a big project? I believe in deep dives into the technology, and big projects that go for several weeks. I break them down into bite-size challenges, some hard and some easy-peasy. Finish all the required ones and you get an A- or 90. If your goal is to “level up” to an A+, you’ll have to complete an extra challenge of what I fondly call “extra awesomeness”. You’ll have to take the basics of what you’ve learned throughout this project and apply them and extend them in a new and creative way. And that’s your choice as a student. If you’re happy with that 90, that’s up to you. I will say that the great majority of my students opt to “level up”. But again, that’s up to them.

And lastly, where does this technology fit in providing an entry point into CS? There are so many avenues in — robotics, programming, game creation, physical computing, art and music… I try to make sure that each grade has a variety of entry points. What jazzes one kid won’t work for another, but I want to provide enough variety that every student will come out and say something was super fun for them!

And while we’re on that subject, let’s talk about the F-word.

Fun.

I know it’s a dirty word in some educational circles. If the kids are having fun, they obviously aren’t learning, because learning is supposed to be hard. My hero, Seymour Papert, coined a term that I live by: “hard fun”. I promise this to every class I have on Day One. I guarantee you that what you do will be fun… and it will be hard. And you may not know what I mean today, but in a few weeks, you will! The fun part is getting stuff to work, whether that’s a game mechanic or a robot challenge. But yes, it can be hard to get there. Fortunately, because it’s fun, you’ll stay engaged, on task, and working hard to get it going the way you want. And nothing is better than that feeling you get when it finally works!

Minefaire 2016

Wow, what a weekend!

I was thrilled to attend Minefaire 2016 near Philadelphia, PA this weekend, where a Guiness world record of attendees met their favorite YouTubers, played games, did build battles, sampled VR wares, and even experienced how Minecraft can be used in education. I presented on using Python in Minecraft as an intro to text-based coding, based on the book Adventures in Minecraft by David Whale and Martin O’Hanlon.

Finally met Joel Levin, @MinecraftTeachr, one of my heroes
Finally met Joel Levin, @MinecraftTeachr, one of my heroes.

It was also a personal thrill to meet so many of my online friends and heroes for the first time! Hard to believe that six or seven years ago, this amazing game was just in its infancy in all its 8-bit blocky splendor, causing people to scratch their heads and predict that this would never take off!

 

 

#Picademy!

picademy_cohort
The whole crew, complete with jazz hands.

Just spent a weekend in Baltimore at #picademy, a 2-day workshop presented by the Raspberry Pi Foundation for 40 teachers. And I have to say it’s near the top of a lifetime of PD experiences. Amazing instructors, an inspiring venue (shout out to the Digital Harbor Foundation), and a cohort of 40 enthusiastic, dedicated, funny, thoughtful, creative teachers. Couldn’t ask for more!

bob_computer_picademy
A picture of me taking a picture….

And school starts this week! I have 20 brand new Raspberry Pi’s, thanks to the generosity of the parents group at the Porter-Gaud School, and I can’t wait to get these Pi’s cranking!

What I hoped to get from Picademy was some practical ways to introduce the Pi’s and some ideas for extending Pi skills in the class. Whoa! I got all that and more! And in the best way possible… by experience. We were thrown in the deep end, coding Sonic Pi, Minecraft, lighting LED’s with Scratch and Python…. and even though I had some experience with some of this, I was challenged and inspired. The great thing was to see people with no background in computer science jumping in and trying to make new and cool stuff. On the second day, we have 5 hours to come up with something original. My amazing partner @scratch_boulder (Mai) and I made a Minecraft phonebooth that was triggered by a button or motion sensor, took a selfie, and then built that selfie in the Minecraft world. So much fun!

mc_selfie
Our selfie worked! Props to @scratch_boulder for being such a great partner!

And now on back to Charleston. Tonight is back-to-school night for the middle school, with games and general mayhem in the gym. School starts For Real in a few days.

But I hope to keep that spark alive and stay in contact with my new tribe. Once more into the breach!

Hal Abelson Keynote: MIT App Inventor Summit 2016

summit2016Every once in a while I read or hear something that literally makes me sit up and take notice. Hal’s keynote was one of those events. In a few brief moments, he sketched the development of the relationship between children and the computer. He was a participant and eyewitness from the late 60’s, a colleague of Seymour Papert’s, and a creator of some of the early incarnations of the Logo programming language.

Those of us in this field of computer science, especially those who teach it to children, owe a huge debt of gratitude to these pioneers. I also got to meet another giant in this field, Cynthia Solomon, another colleague of Papert and Marvin Minsky. What Hal did in 15 minutes was to trace the development of the connection between children and computers from the earliest days to the present. But it was no mere historical journey. He highlighted recent innovations, like the Internet of Things and physical computing, as well as mobile computing. Now the tools for creation in these areas are in the hands of young people, App Inventor being a very accessible drag and drop programming interface for mobile apps.


Young people of all ages now have in their pockets tools which they can use to shape the world in which they live. We saw one fabulous example of young girls in Moldova tracking water quality and then crowdsourcing the results. Present at the Summit were many young creators. I was particularly impressed with a group of 6 12-year-olds who created an app for autistic children, their parents, and their teachers. It was astonishing in its design and usability.

Hal not only traced the past, but laid out the present landscape of computing and children, and he pointed the way forward. We have truly entered into the next phase. It was such a thrill to be at MIT where so much of this started. I feel truly honored to be a part of this!