Sniff is a "Scratch-like" programming language that's designed to help Scratchers move gently from Scratch to more conventional languages. They can start writing programs, without having to learn a new language because Sniff is based on Scratch. They learn a little more about variables, compiling, syntax errors (!), and they can have fun controlling real hardware while they're doing it.

Tuesday, 9 August 2016

ScratchMIT2016

We just got back from Boston, where we attended out third Scratch conference. It was lots of fun to be back at MIT, and meet up with everyone, including lots of people we met in Amsterdam last year.

Officially we had a poster, and were talking about Banana Physics which I've written about here already. Here's an updated PDF with our slides. Thanks to Andy for his help on the stand, and spreading the word.

We also showed off our online editor: live.sniff.org.uk. This is very experimental, but is working well - its the fastest, and easiest way to get started with Sniff, as there are installs required - It all runs in the browser (and compiles on our server), so you can just make an account, and start programming. In the future we hope to be able to support local hardware with a small browser plugin. We'll have a dedicated post on this very soon, and making bigger announcement, as it is a big thing.

We also met lots of new people - too numerous to mention, so I'll just call out some specific work that was on show:

The Colour Divide: https://scratch.mit.edu/projects/71447764/ is a great animation done in Scratch by bubble103 (who was an invited speaker at the conference as a result - aged 16!). As someone who works full time in the computer animation field, I generally don't get that excited by Scratch animations, but this is a great piece of work that deserves all the recognition its getting.

There were a lot of students from Warwick techvolenteers who are doing a lot of great schools outreach doing science projects much like we've been building in Sniff, though they were showing off work aimed at slightly younger kids. They've just transitioned from Picoboard to a custom Arduino shield, which we hope to get a good look at soon.

We finally got hands on with the wedo2, and it was as much a let down as we expected. Driver compatabilities, HW limitations on about 50% of the laptops, binding problems and battery requirements all make it a pretty unconvincing upgrade. While we didn't do any serious testing  it seemed like the motor was lacking in torque, and struggled to handle gearing well. Maybe in the future things will get better, but right now we'll hang on to Wedo V1.0 (or better yet Control Centre B).
There were a couple of companies showing of their robot buggies. Dexter Industries had a session on their GoPiGo, which is a lot like our SniffBotJr that we use for workshops. However unfortunately its based around a Pi, which means it costs $210 for their starter kit.

The robot kit from ROBBO costs about the same at 250Euros and is Arduino based, which is a lot of money for an Arduino based robot, but it is beautifully made. The sensors attach magnetically providing both physical and electrical connections to both digital and analog pins, which is incredibly clever. The sensors just clip on, so you can reconfigure in seconds and they're physically polarised by the shape cut in the acrylic housing, so its impossible to connect them incorrectly. We spend a chunk of time on Friday night, and Saturday afternoon playing with both their robot, and their "lab kit" (an arduino powered pico board style device), and they are sweet if your budget can handle them. Both work out of the box with Sniff (once we figured the pins being used) - program them using the nano-sniff command, and they work great.


If I can make it to the conference next year I think we'll run a workshop on building a real low cost robot - we spend about £25 per robot to cover hardware costs on our workshops, which means every student gets to build a robot, and take it home with them! Check the "Robot" posts here on the blog to see what we've built, and information on how to build your own, or just get in touch if you need help.

Finally Derek Breen (no fixed abode - coming to a sofa near you soon) has a couple of "new" books - well not really... he's quite open that they're cut down rehashes of is original Scratch for Kids book, but they're smaller, and focus on specific things: one on animation and on one games, which means they're much more approachable for a kid with a specific interest. 

And then it was over - a quick stop at the MIT Museum and we were back on a plane to the UK - missing the Delta datacenter outage but a few hours!

Thursday, 21 July 2016

Getting Friendly with Hue

Philips Hue system is an expensive addiction. I picked up a cheap starter kit that was on sale, and a couple of months later, I've spent hundreds of pounds installing it in as many rooms as I can afford. It's crazy fun, and while its not without technical issues, it works really great and does simple stuff that's genuinely useful. While the colour changing is its headline feature, having timers to turn lights on and off automatically, and being able turn on/off multiple table lamps when you enter/leave a room is something you grow to love quickly.

It's also very hacker friendly. Philips have built it as a totally open system. Not only do they provide a documented API and tutorials, but there are even tools built into the Hue Bridge to encourage you to play with the thing. Now with Sniff support its really easy to turn a hue light on and off, just as easily as you flash an LED!


The first thing you need to do is find the IP address of your bridge. It should be four numbers, something like 192.168.0.164. Then open up the Hue's debug tool in a web browser: 

http://<bridge ip address>/debug/clip.html

fill out the first two fields
URL: 
/api
Message Body:
{"devicetype":"Sniff"}

then press physical button on your Hue Bridge (a security feature, so it knows its you and not someone hacking your network). Finally press the  POST button on the web page.

In the response box you should see a value for your "username", which looks something like: 1028d66426293e821ecfd9ef1a0731df. Though they call it a username, its actually like more like  a password. It's whats know as a sparse space - a really big number, where only a few numbers are accepted to let you in. If you know the number then we know who you are, even though you haven't explicitly told us.

If you have problems, then check the linked tutorials from Philips to get the data you need. Now we've got a password we can start writing in Sniff. The first thing we need to do is make a device, and set up the "username" we got from the bridge:

make bridge hueBridge device
make bridgeAddress string
make authorisation string

when start
.set bridgeAddress to "192.168.0.164"
.set authorisation to "oCckjJ2ApQNHc76Q6vrAVmnrsnOJKaLESMK2uqLk"


There are lots of tutorials on how to blink and LED, but now we can "go large":

make bridge hueBridge device

make bridgeAddress string
make authorisation string
make light number
make state boolean

when start
.set bridgeAddress to "192.168.0.164"
.set authorisation to "oCckjJ2ApQNHc76Q6vrAVmnrsnOJKaLESMK2uqLk"
.
.set light to 1
.forever
..set state to on
..tell bridge to "set state"
..wait 1 secs
..set state to not state

To turn a light on or off, just select the light by number, (here we're using light number 1! The Philips tutorial shows you how to get a list of all your lights, and see there names - we'll probably support this in the future), set state to be on or off, and then tell the bridge to set the state.

The next thing to do would be to control brightness:

make brightness number

when start
.set bridgeAddress to "192.168.0.164"
.set authorisation to "oCckjJ2ApQNHc76Q6vrAVmnrsnOJKaLESMK2uqLk"
.
.set light to 1
.set state to on
.tell bridge to "set state"
.
.forever
..set light to 1
..set brightness to (sin of (timer*100))*0.5+0.5
..tell bridge to "set brightness"
..wait 0.2 secs

Here we turn the light on as before, but now we set the variable brightness, and call "set brightness to fade it in and out (using a value between 0 and 1). Note the delay - It's recommended not to send more than about 10 requests per second, just so the system can keep up.

Finally if you have a colour bulb can set the colour, using Hue, Saturation and Brightness, and telling the bridge to "set color". Hue is from 0 to 360, while Saturation is 0-1.


Running this from the desktop is fun, but we can go a stage further. If you've got an Arduino with an Ethernet shield then everything will work exactly the same on the stand alone hardware. All you need to do is tell it to use the ethernet shield instead of normal networking, so you need to add the following lines at the beginning of your code:

make spi device
make ethernet device D10
make networkMAC string "b6:ee:63:ed:95:cb"
make networkIP string "192.168.0.200"


Then use uno-sniff to download your program to an Arduino with an ethernet shield attached. That means you can write code to turn the lights on in response to any kind of hardware event. You could use a PIR motion sensor to turn the lights on automatically when you go into a room (and off when you leave), or just add a whole load of buttons to make a monster Hue control panel!

Release 28: And About Time too...

We normally seem to push out a release every month or so, with some new drivers and a few fixes and optimisations. However since the massive Microbit push back in April we've got almost 3 months without an update. I'm blaming end of school year burn out!

So here we have release 28. To be honest, its been such a long release cycle some of the thing that have gone into it seem like ancient history. There are lots of updates, and fixes for Microbit that just missed the last release, including code for the demos. It should also be a little faster.

jsniff has seen a lot of work. This lets you compile sniff programs to javascript and embed them in a web page. We've been using this internally for a fairly major application that we'll announce soon. If you compile with "jsniff -S xxx.sniff" it will include code to load and save files to a web server for permanent storage, so you can make really advanced web apps. There's a bit of work you need to do server side, but we'll document that soon. If you get a compiler error about "blacklist"ing when compiling with jsniff then you need to make a minor mod to your emscripten install - check the error line which should specific a line of code in the emscripten code... just edit that file, and delete the two lines and you're good to go again. More details later...

If you use the Arduino ethernet shield we've made a change to the way the ip address is specified. Previously this was stored in eeprom, but to increase portability you need to add this to your code. Check the examples/Embedded/webclient example to see how.

Finally we added support for Philips Hue light bulbs!! This is lots of fun, as you can make your own devices to turn your lights on and off. This is still a pretty basic implementation, and we'll probably add more to it in the future

There's a few other odds and ends in there too, but head over to the downloads page and try it out!

Incidentally "and about time too" is the title of Bernie Marsden's first solo album from 1979.

Wednesday, 1 June 2016

Talk to me Sniff!

In all the excitement over the microbit, we forgot a fun little feature we added in release 27. On "hosted" systems (Mac, Windows and Linux) you can now make Sniff speak. On Mac and Windows it uses the built in voices which sound pretty good. On Linux you may need to install the speech software (using apt-get, or yum).

To make the computer talk to you, all you need to do is create a speech device:

make voice speech device
make message string

Then just set the message and tell it to "speak"

when start
.set message to "hello world"
.tell voice to "speak"
.wait 3 secs


It's that easy! It'll read out any text you like, so to make it count:

make counter number
when start
.set counter to 1
.repeat 10
..set message to [counter]
..tell voice to "speak"
..change counter by 1
..wait 1 secs

That's pretty much all there is to it!

Thursday, 12 May 2016

Skylanders Vs Infinity on the Microbit

It's just been announced that Disney Infinity is dead. This isn't so much of a surprise - V1 showed some promise, but V2 didn't include any Disney characters, alienating the market they'd grown with V1 (I would have bought it if the selection of Marval characters included Jessica Jones, just to unlock the empty whiskey bottle in the toy box), while lacking depth to appeal to older players.

Skylanders has also jumped the shark... I quite liked Swap Force, but Super Chargers was just dull - probably because as a parent my role was to hold the second controller and press fire, while offspring got to do all the driving. 

So the only think left to do with all those figures - let them battle it out one last time with your Microbit! Both Skylanders and Disney Infinity use "RFID" tags inside the figures, so that the base station can identify them. It's the same technology that's used for contactless credit cards.


To teach your Microbit to read RFID tags you need a "Mifare RC522", sometimes called MF522. These cost about £2.50 on eBay, and you can use them to read all sorts of cards. You can even buy "blank" cards, which you can store data on. Inifiity/Skylanders use this feature to record the progress on the figure rather than in the game, but they have a security code so you can't easily write to them yourself. All we're going to do is read the ID of the card.

Hook up is really easy: If you've checked out our other microbit posts you'll have used SPI. Just connect the power, and the 4 SPI wires from the MF522 to equivalent ones on your microbit, and you're good to go. There may also be a "reset" pin but just ignore that.

make spi device
make cardReader rfid device D16
make cardData string
make cardAddr number

make message string
make scrollDone boolean

First thing to do is make an SPI device and then an rfid device. I used D16 for "CS/SS" though you could use something else if you wanted to. I'm going to display the data on the screen using a script called scroll, so I also set up some variables for that.

when start
.set message to "ready"
.broadcast scroll and wait
.
.forever
..repeat until not cardData = ""
...tell cardReader to "get card"
..set message to cardData
..
..if message="12,5c,20,10"
...set message to "Bash"
..if message="88,4,7e,eb"
...set message to "Elsa"
..
..say message
..broadcast scroll
..tell cardReader to "release card"
..wait until scrollDone

To use the "scroll" script we set the message and run the script. We kick of by saying "ready". Now we're going going to tell the reader to "get card", which tells it to start talking to a card. If it finds one it puts its card ID into cardData, so when we find one we can set that as the message.

The card ID will look like four hexadecimal numbers. I check them against the figures I already know about, and if they match, I replace the ID with the characters name. I picked Elsa and Legendary Bash to use (remember these are the numbers for my figures - yours will be different). You can add as many as you like. If you have a lot you could write some code to check them against a list rather than testing teach one. You could even add an SD card, and have a file of known figures.

Once I know the character I "say" it to the computer, and run "scroll". We don't "and wait" this time as we need to tell the card reader that we're now done with this card, and it should disconnect. Then we wait until the scrolling is complete.

The code to display/scroll text is something we've also seen before:

make display microbitDisplay device
make displayX number
make displayY number
make displayColor number
make displayFlush boolean

when start
.forever
..tell display to "tick"

make offset number
when scroll
.set scrollDone to no
.set displayColor to 0
.tell display to "clear"
.set displayX to 1
.set displayY to 1
.set offset to 8
.repeat until displayX<0
..set displayColor to 0
..tell display to "clear"
..set displayColor to 777
..set displayX to offset
..tell display to "show"
..change offset by -1
..wait 0.08 secs
.set scrollDone to yes

The only new thing I've added is that it sets scrollDone to no at the beginning and scrollDone to yes when its finished. This allows the main script to wait until the full text is displayed before going again.

And that's it - really easy. You could use figures to control anything you can connect to your microbit. Use them to unlock doors, control lights, make your buggy move. You could write your own "credit card" system and pretend to shop! When you've done that have a look at examples/Embedded/rfid which includes reading and writing data to programmable cards. 

Wednesday, 11 May 2016

Microbit Thermometers - is it hot in here?

If you go through the posts here, you'll find that a bit part of what we think is important is taking computing and linking it to the rest of the curriculum. We did a presentation at a recent event called "Banana Physics", which shows how you can use devices you probably already have like the Lego Wedo, and Scratch Picoboard to do real science (We'll also be showing this as a poster at Scratch@MIT2016). Measuring and recording real data and combining that with maths and physics to actually learn real things about the world - stuff you might have learned in KS4 or A Level physics in a chalk and talk class you can easily turn into practical sessions which put computing to work for real applications. By making it practical much younger kids can apply results from much more advanced theoretical classes.

One of the things you should absolutely do with your microbit is measure and record temperatures. This is one of the cheapest, and simplest pieces of equipment you can attach to a Microbit, so (as many of you are probably new to this),  I thought I'd do a quick roundup of the options available to do that:

Built in Sensor

Wait a minute, doesn't the Microbit have a built in thermometer? Well yes, sort of... it actually has two - one built into the bluetooth chip, and another in the magnetometer. So what's wrong with these? Well they're designed to monitor the chip, not the outside world. If the chip is working too hard, smart software will give it a rest to cool down (your phone does this, so it gets slower when it gets how. Similarly for laptops - they also use this to control the fans). As a result they can misleading readings. They're also not really calibrated, so you may need to add/subtract an offset before they're even slightly meaningful. 

make thermometer microbitTemperature device
make temperature number

when start
.forever
..tell thermometer to "read"
..say [temperature]
..wait 1 secs


As of release 28 (not out yet, as I write this), you can use this device just by telling it to "read". It's probably good for saying "its hot in here" at appropriate moments, but after that you should think about something more accurate.

Thermistor

The classic way to measure temperature is with a Thermistor - their resistance changes with temperature. The most common type is a 10K NTC, so you can connect one from 0V to D0, and a 10K resistor from D0 to 3V. We can measure the voltage using an analog input and use that to calculate the resistance (using Ohms law!), and then apply another equation to convert resistance to temperature:

make v analog input D0
make r number
make t number

when start
.forever
..say join "Voltage:" [v]
..
..set r to v/((1-v)/10000)
..say join "Resistance:" [r]
..
..set t to (ln of (picoRa/10000))/3950
..change t by 1/(25+273)
..set t to 1/t
..change t by -273
..
..wait 1 secs

The 10000 is the nominal resistance of the device at 25C. 3950 is the B value for the thermistor, and we need to remember to switch between C and Kelvin at appropriate points.

This does work pretty well, and should be pretty accurate. It's super cheap (a thermometer costs pennies), and for not much more you can get on enclosed in a waterproof case so you can put it "in" things to measure their temperature.

DHT11, DHT22

While thermistors are great,and the programming is at a level that if you put the equations on a worksheet kids should be able to work through it, the coding just to measure temperature is a lot of work in itself. Sometimes we want to do the measuring and do something with the result. In which case the dht11 (blue) is a go-to component for anyone doing this kind of thing. They cost less than a pound and can be just connected directly to 0V, 3V and a data pin (one pin is unused).

make thermometer dht11 device D0
make temperature number
make humidity number

when start
.forever
..tell thermometer to "read"
..say [temperature]
..say [humidity]
..wait 1 secs

Not only do they measure temperature, they also measure humidity. However they're not that accurate. If the data you're collecting is important, then you'll need to spend £2 on a dht22 (white). This is an almost identical device, but has a much better spec, for both accuracy and range.

make thermometer dht22 device D0

Functionally they're identical so all you need to do is swap out the line which makes the dht11 to one that makes a dht22. You can buy a load of dht11's for everyone to play with, and just replace them with a dht22, when it comes to actually recording real data. In fact you'll see that all of the devices apart from the thermistor work very similarly. They can also all be wired up to a 3 pin connector (0v,3v, signal) like the one on the MB^5 we designed.

DS18B20

The final way to measure temperature is using a DS18B20. Again these cost about £1 for a waterproof version, and connect via three pins to the microbit (you need an additional 4k7 resistor between signal and 3v). We used two of these connected to an Arduino to compare the temperature of our pond to the air temperature - it was very exciting! You can connect multiple sensors, of the same or different types to different pins  and see how different things behave differently (block box/white box/shiny box?).

make thermometer ds18 device D0
make temperature number
make humidity number

when start
.forever
..tell thermometer to "start"
..wait 1 secs
..tell thermometer to "read"
..say [temperature]

One gotcha here is that the ds18 takes about 1 second to take a reading. We don't want to hang around for 1 second doing a reading, so we tell it to start, wait 1 second and then come back to collect the result. If this starts to make your code more complex that you'd like, remember you can always do this in a separate script, and then just use the measured temperature in a another script.

DS18's are a bit timing sensitive, and don't work reliably on Microbit in Release27. Release 28 fixes this.

i2c

There are couple of other devices you can use (like the bmp180) which include temperature, that can be connected via i2c. However even if you have the kitronik breakout, it puts the i2c pins on a separate connector, making external i2c devices a bit clunky to wire up. In any case these devices are generally designed to do something else (air pressure) and temperature is just an "extra", so if you just want temperature they're not the best choice.

In summary, I'd go for a dht11 as my basic choice, dht22 if I need more accuracy, and ds18b20 if I need waterproof.

All of the simple devices can be easily attached to the Microbit just using croc clips if necessary, and if you have some kind of break-out then they can be wired to just plug straight in. Add an SD card and you've got a great data-logger. However you choose to measure temperature, its really easy and the potential to link coding, building and science is really great. What's the point in coding if you only ever code in computer class?

Monday, 9 May 2016

Microbit Sat-Nav

One of the features we added in a recent build of Sniff was support for a GPS module. These cost less than £10, and are really easy to hook up. However so far, I've only tested them at home. While that was initially exciting, it quickly became very boring, as I always got the same (pretty accurate and correct) reading for where my house is.

Note, this one has an integrated antenna on the board,
Many have an exteneral one which probably performs
better, but it going to be more fragile/tricky to hook up

Once I realised I could hook it up to a microbit, things got more interesting, as combined with the built in screen and compass we could build something that would be sufficiently portable to be viable. Unfortunatly when I hooked up the GPS to the microbit a few weeks ago it didn't work. The problem was that the Microbit is pretty slow, and couldn't keep up with the required maths and timing to process the data from the gps as fast as the gps was sending it. A helpful suggestion (and sympathic ear to my rambling DM's) from @whaleygeek sorted the bit timing, and once stuff started getting decoded I was able to optimise the handling of the data so the Microbit could keep up. The new GPS code will be in Release 28, or if you really can't wait, then drop me an email/DM (ian at dctsystems.co.uk, or @sniffCode on twitter). The code should also work on a Arduino with minor tweaks.

To hook up the GPS Module, connect 0v, and Vcc (it works find on 3v), and then connect "tx" to a data pin on the Microbit. There's also an rx pin which allows you to change settings on the GPS, but we shouldn't need to change anything, so we can ignore it.

make gps device D2
make longitude number
make latitude number

Here I tell Sniff there's gps plugged into D2. As we're only ever likely to have one gps device plugged in at the same time, I've not bothered to give it a name. You can miss out the names on devices and they just inherit the device name, so this is equivalent to :

make gps gps device D2

The gps is going to return out longitude and latitude in degrees. It can also give us the time/date, speed and heading, but we're not going to need any of those.

make deltaX number
make deltaY number
make distance number

when start
.set targetLat to 50.7429791
.set targetLong to -1.89716810
.
.forever
..tell gps to "update"
..set deltaX to targetLong-longitude
..set deltaY to targetLat-latitude
..
..set distance to sqrt of (deltaX*deltaX+deltaY*deltaY)
..if abs of distance < 0.001
...set deltaX to 0
...set deltaY to 0
..else
...set deltaX to deltaX/distance
...set deltaY to deltaY/distance
..wait 9.5 secs

This is the main script which updates the position every 9.5 seconds. I've pre-programmed in the location that I want to go to, and work out the direction I need to go in by subtracting my current position. This is incorrect. This would be right if the earth was flat, but long lat aren't cartesian coordinates, they're spherical polar. This will particularly break if you're traveling ling distances, or are traveling within the arctic circle. In either case I suggest you make more serious navigational plans! If you're in the UK and traveling normal distances then its close enough for a fun project... or you could look up the maths for doing this properly yourself - I just wanted to see if it would work at all!

We also approximate the distance, and divide the direction vectors by the distance so that they're normalised. We also check if the distance is very small, in which case we're there, and don't need to display anything.

Now lets make a compass and display:
make i2c device
make compass mag3110 device
make heading number

make display microbitDisplay device
make displayX number
make displayY number
make displayColor number

when start
.forever
..tell display to "tick"

All of this should be familiar - if not, check out our Microbit tutorials on using the compass and screen. We can now write another script that will run at the same time as the previous one, which do our drawing (this is a handy devision of tasks that is very "scratch-like").

make midX number 3
make midY number 3
make rX number
make rY number

when start
.forever
..tell compass to "read"
..change heading by -90
..set rX to (cos of heading)*deltaX-deltaY*(sin of heading)
..set rY to (sin of heading)*deltaX+deltaY*(cos of heading)
..
..set displayColor to 000
..tell display to "clear"
..
..set displayColor to 777
..set displayX to midX
..set displayY to midY
..tell display to "move"
..change displayX by midX*rX
..change displayY by midY*rY
..tell display to "draw"
..tell display to "flush"
..wait 0.1 secs

Now we tell the compass to read, and use the heading to rotate the deltaX/Y that we calculated in the previous script. We have to adjust heading by -90 so that North is at the top. This is just a quirk of the way the magnetometer is attached relative to the orientation of the screen. Then we just clear the screen and draw the rotated vector!


So how did it work out? Pretty well. The only issue is that reading from the GPS can take up to a second, as the simple device driver code just waits for the GPS to send it a message, which happens once per second. That's normally fine, but means the microbit display blinks off for half a second too. That's one of the reasons for only updating every 10 seconds.

I had a Sniff workshop (building robots) at the weekend and had someone in the car to check the microbit, so though I'd test it out on the way there (I did know where I was going, just in case). This is the first time I've used the microbit compass inside a metal box! Normally when you start using the compass you need to wave the microbit around, but that's a bad idea in a car, as you want it to learn the car's magnetic field as well as its own. That meant the car had to take few turns before the microbit settled down, but from then on it was pretty much spot on. We drove for about ten minutes, and by the end it was pretty solid. It even noticed when we drove past the destination to find parking, and started pointing backwards. It was really pretty good!

In the version I used I had another script which ran, checking the buttons so if you pressed one of them it would set the target location to be the current location - get me back to here, but you could pre-program several locations, and switch between them (great for geo-caching). When I googled for similar projects I found something called a "Jerusalem Compass", which is supposed to point to Jerusalem, but actually just points East - we've made a real one which can point wherever you want to!