Saturday, March 14, 2015

16-channel relay box controlled by a Raspberry Pi

It's not quite finished yet, but it's in a usable state. This isn't full instructions, but hopefully enough to get you started if you're interested. Please comment below if you'd like more information.

Some of the Parts:
8-Channel 5V Relay Board (two of these)
Raspberry Pi, SD card, associated cables
female to female jumper wire for connecting Raspberry Pi GPIO pins to relay board pins
thick wire for connecting relays to outlets
nine outlets
CNC or laser-cut front plate from this drawing
LightShow Pi software (haven't tried this yet)




An example Python script to flash through the relays one at a time:


import time
delayTime = 0.25
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
pins = [2, 3, 4, 17, 27, 22, 10, 9, 14, 15, 18, 23, 24, 25, 8, 7]

for pin in pins:
    GPIO.setup(pin, GPIO.OUT) 
    GPIO.output(pin, GPIO.HIGH)
    time.sleep(delayTime)
    GPIO.output(pin, GPIO.LOW)
    time.sleep(delayTime)
GPIO.cleanup

Wednesday, March 11, 2015

Elementary Music and Notes in Sonic Pi

In this activity we are going to play some notes with Sonic Pi.

The song "Johnny Works With One Hammer" is a fairly simple tune, listen to someone singing it:



Did you hear how the sound goes higher and lower? Sonic Pi will play higher sounds when you tell it to play higher numbers, and lower sounds with lower numbers. Try pasting this into Sonic Pi and pushing play to see how it sounds:

# Johnny part one
use_bpm 200
play_pattern [53, 53, 53, 57, 60, 53, 53]

Each of those numbers is a different sound, what we would call a different note. You heard higher numbers as higher sounds, which are higher notes. The use_bpm part is just telling Sonic Pi how fast to play.
But let's get back to our song. We've seen that we can play high and low sounds by telling Sonic Pi to play different numbers.

The number pattern for the first part of "Johnny Works With One Hammer" would be:
53 53 53 57 60 53 53
55 60 60 57 53 53

I've done the first line of the song, try pasting it into Sonic Pi and then completing the second line of numbers.

# Johnny part one
use_bpm 200
play_pattern [53, 53, 53, 57, 60, 53, 53]
play_pattern []

Did that sound like the song we are trying to play? It was close, but some of the notes are supposed to be longer than others. So instead of play_pattern we can use play_pattern_timed, like this:

# Johnny part one and two, with timing
play_pattern_timed [53, 53, 53, 57, 60, 53, 53], [0.25, 0.25, 0.25, 0.25, 0.5, 0.25, 0.25]
play_pattern_timed [55, 60, 60, 57, 53, 53], [0.5, 0.25, 0.25, 0.5, 0.25, 0.25]

The second list of numbers on each line is the amount of time that Sonic Pi will play the note for. Notice that the note 60 will be played for a longer time (0. 5 seconds). In musical notation we say that the shorter notes are "quarter notes" because they take up a quarter of a bar. The longer notes here are half notes. See what the notes would look like for this part of the song.


A quarter note is sort of a filled-in circle, a half note looks kind of hollow. Now let's try to make our program easier for humans to read by storing the note patterns and timing patterns before we actually play them:

# Johnny part one and two, with timing
play_pattern_timed [53, 53, 53, 57, 60, 53, 53], [0.25, 0.25, 0.25, 0.25, 0.5, 0.25, 0.25]
play_pattern_timed [55, 60, 60, 57, 53, 53], [0.5, 0.25, 0.25, 0.5, 0.25, 0.25]

That's starting to look complicated, but hopefully you can see how it can be broken down into parts. There are four "arrays" there, which are basically lists of numbers. The first one is called notes1 and it contains the notes for the first line of the song. The array called timings1 is a list of how long to play each of those notes. Then we just say play_pattern_timed notes1, timings1 when we want to have Sonic Pi play that list of notes with those timings. Let's try it including variables as well. Will this play the same song?

# Johnny with variables and arrays
quarter = 0.25
half = 0.5
notes1 = [53, 53, 53, 57, 60, 53, 53]
timings1 = [0.25, 0.25, 0.25, 0.25, 0.5, 0.25, 0.25]
notes2 = [55, 60, 60, 57, 53, 53]
timings2 = [0.5, 0.25, 0.25, 0.5, 0.25, 0.25]
play_pattern_timed notes1, timings1
play_pattern_timed notes2, timings2

In this example, we said the time for the shorter notes (quarter notes) should be a quarter of a second (0.25) and the time for a longer note (half note) should be half of a second (0.5). We could also have said:

quarter = 1.0/4
half = 1.0/2

or even:

quarter = 1.0/4
half = quarter/2

In case you're curious, the reason it is 1.0/4 instead of 1/4 is that we need to tell Sonic Pi that we want the numbers to be type float instead of integer. If we said1/4 it would equal 0. Don't worry about this yet though.

Hopefully you are starting to see that there can be a lot of math in music. So far we have done the first half of the song "Johnny Works With One Hammer". If I show you the musical notation version of the whole song, do you think you could translate it into something that Sonic Pi could play? It's a little bit like figuring out a code, you need to figure out what numbers mean the same thing as the notes in the musical notation.



You can also try out different instruments by putting a line like one of these at the top of your code:
use_synth :pretty_bell
use_synth :fm

So now you can make music with Sonic Pi. Try some other songs, and tell your friends.

Monday, February 23, 2015

Elementary Music and Sonic Pi Drum Loops

We are going to investigate drum beats and learn a little programming. If you don't have Sonic Pi installed, you'll need to have that done.

Paste the following code into one of the Sonic Pi workspaces, and click Run.


# Drum loop one, half notes
beat_length = 0.25

4.times do
sample :drum_heavy_kick
sleep beat_length
sample :drum_snare_hard
sleep beat_length
end

This is a basic drum loop. Let’s look at the parts of the code line by line.
  1. The # symbol means that anything on the rest of the line is a comment. It’s for humans to read, the computer ignores it.
  2. We’ve made a variable named beat_length that means a value of 0.25. We’ll use this a few times later.
  3. This line is blank so we know that there is something different coming next.
  4. Here we are creating a loop that will do something four times.
  5. This plays a sample (recording) of a kick drum.
  6. The command sleep means to rest for a certain amount of time (in seconds). It will rest for the time stored in the variable beat_length.
  7. Play a different sample, this time a snare drum.
  8. This tells the computer that it is the end of the loop that started on line 4.


Now lets try adding a few things to the code to make it look like this:


# Drum loop two, quarter notes
beat_length = 0.5

4.times do
sample :drum_heavy_kick
sample :drum_cymbal_closed
sleep beat_length
sample :drum_snare_hard
sample :drum_cymbal_open
sleep beat_length
end


When you click Run you’ll hear high hat cymbal playing at the same time as the kick and snare drums.


Bars of music often have four beats in them, so let’s change it to this and it will play four bars with four beats in each:


# Drum loop three, quarter notes
beat_length = 0.5

4.times do
sample :drum_heavy_kick
sample :drum_cymbal_closed
sleep beat_length
sample :drum_snare_hard
sample :drum_cymbal_open
sleep beat_length
sample :drum_heavy_kick
sample :drum_cymbal_closed
sleep beat_length
sample :drum_snare_hard
sample :drum_cymbal_open
sleep beat_length
end


Now try changing the value in the beat_length variable to 0.25 or 0.7, and try replacing some of those samples with different drum samples:
sample :drum_heavy_kick
sample :drum_tom_mid_soft
sample :drum_tom_mid_hard
sample :drum_tom_lo_soft
sample :drum_tom_lo_hard
sample :drum_tom_hi_soft
sample :drum_tom_hi_hard
sample :drum_splash_soft
sample :drum_splash_hard
sample :drum_snare_soft
sample :drum_snare_hard
sample :drum_cymbal_soft
sample :drum_cymbal_hard
sample :drum_cymbal_open
sample :drum_cymbal_closed
sample :drum_cymbal_pedal
sample :drum_bass_soft
sample :drum_bass_hard


Cool, eh.


Next we’ll try some different rhythms by playing some samples halfway between beats. If each beat before was a quarter note, these would be eighth notes (because half of a quarter is an eighth). Listen to the kick drum:


# Drum loop four, quarter and eighth notes
beat_length = 0.5

4.times do
sample :drum_heavy_kick
sample :drum_cymbal_closed
sleep beat_length
sample :drum_snare_hard
sample :drum_cymbal_open
sleep beat_length/2
sample :drum_heavy_kick
sleep beat_length/2
sample :drum_heavy_kick
sample :drum_cymbal_closed
sleep beat_length
sample :drum_snare_hard
sample :drum_cymbal_open
sleep beat_length
end

That seems to be getting a little long, though, let’s try the same thing with a loop:


# Drum loop five, another loop
beat_length = 0.5

4.times do
sample :drum_heavy_kick
sample :drum_cymbal_closed
sleep beat_length
sample :drum_snare_hard
sample :drum_cymbal_open
2.times do
  sleep beat_length/2
  sample :drum_heavy_kick
end
sample :drum_cymbal_closed
sleep beat_length
sample :drum_snare_hard
sample :drum_cymbal_open
sleep beat_length
end


Not much shorter, but hopefully you get the idea. We two spaces at the beginnings of lines 11 and 12 to show that they belong to a different loop. The computer ignores the spaces, but it makes it easier for other people to read your code. If you want to learn more about code style in this language, check out the Ruby Style Guide.


Getting back to loops, though, try this:


# Drum loop six, another loop
beat_length = 0.5

4.times do
3.times do
  sample :drum_heavy_kick
  sample :drum_cymbal_closed
  sleep beat_length
end
sample :drum_snare_hard
sample :drum_cymbal_open
sleep beat_length
end


You can see that on the first three beats we played the same samples, then different samples on the fourth beat.


Now let’s try some functions.


# Drum loop seven, with functions
beat_length = 0.5

def kickAndClosed
  sample :drum_heavy_kick
  sample :drum_cymbal_closed
end

def kickAndOpen
  sample :drum_heavy_kick
  sample :drum_cymbal_open
end

4.times do
3.times do
  kickAndClosed
  sleep beat_length
end
kickAndOpen
sleep beat_length
end


First we define two functions (using the term def) and then we can call them by their names to get them to do their thing. A function is just a set of instructions that you can reuse later. You might also hear them called methods, procedures, subroutines, or callable units.


Let’s try something with parameters.


# Drum loop eight, with parameters
def play_a_beat(chosen_sample, beat_length)
  sample chosen_sample
  sleep beat_length
end

4.times do
  play_a_beat(:drum_cymbal_closed,0.25)
end


The variables chose_sample and beat_length are passed to the function when it is called.


Now see if you can figure out what this next section of code will do, and then run it to check if you’re right.


# Drum loop nine, nested functions
def cymbalClosed(beat_length)
  sample :drum_cymbal_closed
  sleep beat_length
end

def loop_this(n)
  n.times do
  cymbalClosed 0.25
  end
end

loop_this 16


One more thing, if you want your beat to go on forever, or until you stop it, try this.


# Drum loop ten, in_thread
beat_length = 0.25

in_thread do
  loop do
  sample :drum_heavy_kick
  sample :drum_cymbal_closed
  sleep beat_length
  sample :drum_snare_hard
  sample :drum_cymbal_closed
  sleep beat_length
  end
end


So now you know the basics of creating beats in Sonic Pi. Show your friends.


If you’d like to play with electronic drum machines and make different rhythms, check out free drum machines such as:
DMach (Android)
Hydrogen (Windows, Mac, or Linux)
GarageBand (iOS or Mac)
HammerHead (Windows)

Wednesday, February 18, 2015

what I'm up to these days

A while back I had been blogging daily about what I do, but had found that I seemed to then gravitate towards tasks that I could accomplish easily and then write about at the end of the day.

Instead, I'm going to occasionally write about some things I'm working on. This will include work-related things as well as tasks and projects related to the Masters in Education that I'm hoping to have completed by April 2016.

One of the bigger work-related projects I'm working on these days is open data. We are working on getting some of our data on Strathcona County's Open Data Portal, as well as taking data that we already release and posting it in a more accessible format. We are also interested in getting teachers and students utilizing open data. As I write this, International Open Data Day is coming up soon.

On a somewhat-related note, we're also looking at Open Badges to highlight professional learning among staff in EIPS.

In terms of ongoing work in EIPS, I wrote up a list the other day of things we are often talking to staff about these days.
And a few things on my to do list at work:
  • publish to do list
  • plan Scratch Day
  • Moodle migration
  • automate creation of Google Apps users from PowerSchool
  • build a Minecraft server image with a web-based (or VNC) control panel
  • help plan summer school technology camps
  • explore web-based project management ideas
And a little Python script I wrote today to translate addresses into latitude and longitude coordinates:

Hopefully next time I'll write about some course-related things that are in progress.

Saturday, February 14, 2015

Datalogging to the Web with Python, Requests, and Phant

wikimedia.org
I've been looking at various ways of logging data to a web-accessible location, both for students and for my own learning. I think I've come across the simplest and most elegant way of doing this, using data.sparkfun.com (a free data logging service based on their phant engine).

Basically there are three parts to this, setting up the phant storage location, getting the data, and pushing it to the web. Aside from the hardware setup, this all should take about five minutes.

To set up the data storage location, visit data.sparkfun.com/streams/make and enter the appropriate information. Title and Description are required, and the Fields are the things you will be recording (e.g. humidity and temperature). You can change these later. For more information, check the documentation.

After you click Save, it is very important to make a note of the provided values since this is the only time you will get to see them. Copy them to a document and also use the "Send yourself a copy of your keys" option at the bottom of the page.

So now you have a free, Internet-accessible place to log your data. Of course if you'd like, you can even set up your own phant server.

Step two is developing a way to collect data. This could be something like a barometric pressure sensor connected to an ESP8266 module, a button connected to the GPIO pins of a Raspberry Pi, or data that are already available on the Internet. For this post, we'll use weather data from openweathermap.org.

Step three is to push the data. I like Python and I've recently discovered the excellent Requests HTTP library. If you're using a Chromebook or you don't want to bother setting up Python 2.7 and installing that library, you can use c9.io.

Assuming that you have Python 2.7 set up and the Requests library installed, here's some code that will log the current atmospheric pressure.


And there you have it, a few minutes to set up and a few lines of Python to start logging data to the web. Next I'd like to see this all done with a sensor or two connected directly to an ESP8266 module.

Monday, October 27, 2014

A Picture is Worth a Thousand Dollars

Recently one of our schools received an invoice for $1000 for their use of a small copyrighted image on one of their newsletters. After determining that it was in fact a legal invoice, they were forced to pay the royalty for their use of that image.

To avoid this, there are a few ways you can find images (or other media such as songs) that are safe to use for newsletters, websites, etc.

The easiest way to find usable images is the "Usage rights" menu on Google Image Search results. After searching for something, click the Search tools button.


Then click Usage rights and select Labeled for reuse with modification.

This will filter your results to display only images that are likely able to be used. Remember that you still need to provide attribution, unless the image is explicitly tagged as Public Domain. Attribution can be as simple as providing a link to the original source.

For more information, check out the different types of Creative Commons licenses. For songs that you can use in projects check out Jamendo or the YouTube Audio Library.

Thursday, October 9, 2014

Python and Google Apps Provisioning with the Admin SDK Directory API

After wading through documentation, blog posts, and StackOverflow answers I've finally figured out a way to authenticate using OAuth 2.0. Since we didn't want to have to interactively grant "user consent" for each of our domains, this is acting as a "web server" for computer-computer interactions.

I assume that you have Python 2.7 installed (three shalt thou not use), but I'd recommend installing Anaconda to make your life easier for all of this. You'll also need to install the Google APIs Client Library for Python.

EDIT: I was finally able to get it to work with the default SignedJwtAssertionCredentials.
 as well as PyCryptoSignedJWT. To install PyCryptoSignedJWT, download and unzip, then from the command line (in the directory you unziped to) type python setup.py install in order to install.

The next step is to set up your project. Here's the documentation from here to "Set up your API":
  • Enable the API access from the Admin console in order to make requests to the Directory API. To enable the API, log in to your admin account and select Security. If you do not see Security listed, select More controls and then Security from the options shown in the gray box. Select API reference, and then select the checkbox to Enable API access. Save your changes.
  • Set up a new project in the Google APIs Console and activate Admin SDK service for this project. See the Google APIs Console Help in the upper right corner of the Console page for more information about creating your API project.




Still in the Developers Console, you'll need to create credentials for your project. Click on Credentials (under APIs) and click the button Create new Client ID and then select Service account.


Download the key file, and make a note of the private key password (which is always "notasecret"). Then click the Okay, got it button.

You'll need to make a note of the Service Account EMAIL ADDRESS that is displayed (a long string of characters ending in @developer.gserviceaccount.com) and the CLIENT ID (the same string ending with .apps.googleusercontent.com).

The next step requires you to authorize your API client to access your admin console. Assuming your're still logged in to your Super Admin account, go to Manage API client access (or go to Security, Advanced Settings, Authentication, Manage third party OAuth Client access). For the Client Name, paste in the CLIENT ID that you noted previously. In the One or More API Scopes, put in a comma-separated list of the scopes that you'll be using. For our example I'd suggest https://www.googleapis.com/auth/admin.directory.user, https://www.googleapis.com/auth/admin.directory.orgunit (you can always change this later). Then click the Authorize button.



The file you downloaded previously will be something like APIProject.p12 but we'll need to convert it to a PEM file. On a Mac or Linux machine this can be done from the command line ( openssl pkcs12 -passin pass:notasecret -in APIProject.p12 -nocerts -out APIProject.pem ), but on Windows other software is required (try Win32OpenSSL that can be downloaded from here). As a last resort for those who don't worry about security, you can convert it using this site.

So you now have a p12 key file, a Service Account Email Address, and of course your Super Admin account. You're set to start writing some code. I like the Spyder development environment that is installed with Anaconda, but feel free to just use Notepad (or Notepad++) if you're so inclined.

Here's the minimum Python code that works for me, fill in the appropriate values for yourself.


superAdmin = 'you@example.com'
serviceAccount = 'somethingorother@developer.gserviceaccount.com'
pemFile = 'APIProject.p12'
scope = 'https://www.googleapis.com/auth/admin.directory.user'

import httplib2
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials

keyFile = file(p12File, 'rb')
key = keyFile.read()
keyFile.close()
credentials = SignedJwtAssertionCredentials(serviceAccount,
  key,
  scope,
  prn=superAdmin)

http = httplib2.Http()
httplib2.debuglevel = False #change this to True if you want to see the output
http = credentials.authorize(http=http)
directoryService = build(serviceName='admin', version='directory_v1', http=http)

# You are now authenticated, so you can say something like this:
user = directoryService.users().get(userKey = 'me@example.com')
print user.execute()



Hopefully that's enough to get you started. The documentation about what you can do with the Admin Directory API is here. just remember that some of them will require you to declare other scopes.