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.

Thursday, 28 April 2016

Release 27: Micro:bit!

Last week we took the unusual step of putting out Release 27pre, as we were keen to get Microbit support out as quickly as possible. We've now spend quite a bit of time with it, and have made a few minor fixes and changes. It's now pretty stable, and we've been able to test it with quite a bit of external hardware, including the Nokia 5110 screen, an SD Card reader, and a dht22.

Before you can use Sniff with Microbit you'll need to install Yotta from mbed.org. This is really easy on Mac and Windows. For Linux it may be more of an adventure! Let us know how you get on.

We've also produced a series of Tutorials for the Microbit, taking you from never used Sniff, through to using all the features of the Micro:bit.

We're really excited about the new platform, so have fun with it, and get in touch to let us know how you're getting on.

Release 27 is now now on the Downloads page.

ian@dctsystems.co.uk


Wednesday, 27 April 2016

Sniff From Scratch #6: Microbit Compass

In addition to the accelerometer the Microbit also includes a Magnetometer. It's two main uses are either to make a compass, or to detect the movement of metal objects around it. While in principle its pretty simple there are couple of gotchas:


make i2c device
make magnetometer mag3110 device
make xMagneticField number
make yMagneticField number
make zMagneticField number
make heading number

start by making an i2c bus (you only need this once even if you're using the accelerometer and the magnetometer), and adding a mag3110 device. This is the proper name for the chip that the Microbit uses.

Now we can just tell it to "read" and we get our results back:

when start
.forever
..tell magnetometer to "read"
..say [ xMagneticField ]
..say [ yMagneticField ]
..say [ zMagneticField ]
..say join "Heading " [ heading ]
..say ""
..wait 1 secs


The x/y/z values are the measured strength of the magnetic field on each axis and the heading is just calculated from the x and y values. You could calculate it in Sniff but while the maths is easy, its actually surprisingly hard to code (try it and check it your results agree).

To turn that into a proper compass we just use the angle of heading to draw a needle:

make i2c device
make magnetometer 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"

when start
.forever
..tell magnetometer to "read"
..set heading to heading/45
..set heading to round heading
..set heading to heading*45
..
..set displayColor to 000
..tell display to "clear"
..
..set displayX to 3-2*cos of heading
..set displayY to 3-2*sin of heading
..tell display to "move"
..
..set displayColor to 111
..set displayX to 3
..set displayY to 3
..tell display to "draw"
..set displayColor to 777
..set displayX to 3+2*cos of heading
..set displayY to 3+2*sin of heading
..tell display to "draw"
..
..wait 0.1 secs

The only "clever" bit here is that to get nice straight line on the low res display, we round the angle to the nearest 45 degrees, but dividing by 45 (to see how many 45's we have), rounding to the nearest whole number then multiplying back again.


So far so good... however you might find that you get some strange results. The thing is that the magnetometer is sensitive to magnetic and electric fields, but then we've gone and put on a circuit board surrounded by metal and electricity! While this is definitely a problem, its not as bad as it sounds because those bits of metal don't move relative to the chip, so we can calibrate them out.

By default the compass is constantly calibrating, so if you just write your code, you might find that it doesn't work properly for a few seconds, until its taken a few readings and the calibration settles down. Turning the microbit around while this is happening will help a lot, and it will fairly quickly start producing good results.

Where this can backfire is if you place the microbit in a changing magnetic field. The calibration method assumes you're in a constant field and that changes are due to the chip rotating. If you want to measure changes accurately, then you need to calibrate before you start measuring. The variable compassCalibrate is normally just set to yes, but if we want more control then set it to yes, take some readings to calibrate the system, then turn off calibration, so that from then on the calibration if fixed. This will give you a more accurate/reliable measurement of changes in the field (which might otherwise be partially calibrated out).

make compassCalibrate boolean

when start
.set compassCalibrate to yes
.
.say "Calibrating"
.repeat 50
..tell magnetometer to "read"
..wait 0.1 secs
.
.set compassCalibrate to no
.
.forever
..tell magnetometer to "read"
..say [ xMagneticField ]
..say [ yMagneticField ]
..say [ zMagneticField ]
..say join "Heading " [ heading ]
..say ""
..wait 1 secs

With a bit of tweaking you can use this to detect metal objects moving near the microbit.


Electric motors also mess with the magnetic field, which can be both a win or a loss - you can detect when devices turn on and off just by putting the microbit close to them. However it also means that if you have a robot buggy and want to use the magnetometer to detect which way its pointing (very handy, as you can now make precise 90 degree turns!) make sure you place the microbit well away from the motors.

Tuesday, 26 April 2016

Do the Microbit shake!


In the recent tutorial series we used the accelerometer on the Microbit make a spirit level. By detecting which way is down we can use it as a sort of virtual joystick, to make up for there only being two buttons. If you've looked at some of the block languages running on Microbit you might have noticed that they also have a "shake" function, which allows a script to be triggered when the microbit is shaken vigorously from side to side.

That's pretty handy. Wouldn't it be nice to have some code run whenever you do a shake? Well yes it is handy but how does it actually work? Sniff doesn't have shake detection built in, but its really easy to add it. By doing it in Sniff we actually get to see how it works, rather than it being buried away in a C++ module. In general its better to do the work in Sniff than having a "magic feature" (much as Sniff can handle scrolling text in the language without requiring specific runtime support). While this might look a little complex, its actually far simpler than the way it has to be done in the Microbit runtime.

make i2c device
make sensor mma8652  device
make accX number
make accY number
make accZ number


make shakeStart number
make shakeCounter number
when start
.set shakeCounter to 0
.forever
..set shakeStart to timer
..repeat until accX > 0.5
...tell sensor to "read"
..repeat until accX< -0.5
...tell sensor to "read"
..if timer-shakeStart<0.5
...change shakeCounter by 1
...if shakeCounter>2
....broadcast shake
..else
...set shakeCounter to 0


Firstly we set up the accelerometer. We're going to need two extra variables - one to count the shakes, and another to time them. We initialise both (to zero and the current time respectively). Then we wait for the shakes to start. We read the sensor until the acceleration is greater than 0.5 then wait for it to be less than -0.5. This represents one cycle of a vigorous shake.

Then we use the timer to see how long that took. If it was less than 0.5 seconds then it was actually proper back and forth shake rather than just a couple of separate movements, so we count that as one step of a shake sequence. If we ever get more than two of these, each within 0.5 seconds of the previous ones then we actually have a real shake, so we broadcast shake, telling the rest of the code that something happened. If a single shake takes more than 0.5 seconds then the sequence is broken so we reset the count.


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


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

when shake
.set displayColor to 777
.tell display to "clear"
.wait 1 secs
.set displayColor to 000
.tell display to "clear"

Here we have some code that waits for the shake. When it gets it, it flashes the screen for one second.

By coding the shake in Sniff we gain lot of benefits - its now maintainable, and customisable by Sniff programers, so if for example you find the shake requires to vigorous a movement for your liking, you can reduce the acceleration threshold. If you'd prefer a vertical or an in/out shake then change the axis. If your getting false triggers you can increase the number of cycles required to count as a proper shake.

Best of all we can see exactly how it works. There's no hidden magic function that just makes it happen. After all isn't the point that we might actually learn something?

Monday, 25 April 2016

Sniff from Scratch #5: Microbit Spirit Level

Now that we've used devices to access the Microbit Display, the next step is to look at the other sensors in the Microbit, the simplest of which is the accelerometer. Using it in Sniff is really easy:

make i2c device
make sensor mma8652  device
make accX number
make accY number
make accZ number


The microbit talks to the internal sensors using i2c (pronounced eye-squared-see). While this can be a bit intimidating, its really just like USB - a way of connecting the computer bit with some kind of peripheral. The Accelerometer plugs into the i2c, just like a mouse plugs into USB, so the first thing we need is an i2c device, so we can talk to devices using it.

Then we make a sensor.  The Microbit accelerometer is a chip called an "mma8652". In theory that's what is written on the top of the chip, but its too small for me to read! There's nothing particularly special about this - its just the number of the part that they chose to use. There are other chips which do the same job, and in fact you could connect one to the microbit and have two different accelerometers. Similarly you could connect an mma8652 to an Arduino or other board. That's why Sniff calls it by its proper name, rather than just "accelerometer".

when start
.forever
..tell sensor to "read"
..say [accX]
..say [accY]
..say [accZ]
..say ""
..wait 1 secs

Having made we can now just tell it to read, and we get back the acceleration in x,y, and z!

You'll see that if you hold it still and flat, then the x and y values are small/almost zero, while the Z value is either 1 or -1. That's because of physics! The force of gravity results in an effect which is exactly the same as if you were accelerating upwards at 9.8m/s/s. Imaging being pushed back into your seat in a car (or better a plane!) as it accelerates. It feels exactly the same as if you were just lying down, and facing upwards!

That means that the most common use of an accelerometer isn't to measure acceleration, but to figure out which way is down.

If we take the x/y acceleration and just plot it we can tell if the microbit is flat:

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

make i2c device
make sensor mma8652  device
make accX number
make accY number
make accZ number

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

when start
.
.forever
..tell sensor to "read"
..set displayColor to 000
..tell display to "clear"
..set displayColor to 777
..set displayX to 3
..set displayY to 3
..tell display to "move"
..tell display to "set pixel"
..change displayX by -accX*5
..change displayY by accY*5
..tell display to "draw"
..wait 0.1 secs


Here's the whole code, which uses what we learn in the last session do to drawing, and combines it with what we've learnt about the accelerometer. The only gotcha is that accX is reversed - that's just down to the way that the accelerometer is placed on the board, relative to the screen.

This actually shows a really effective use for the accelerometer as a pseudo joystick.The microbit only has two buttons which isn't enough to control a game, but using the accelerometer you can control a character in a game by tilting the board around.

Sunday, 24 April 2016

Sniff from Scratch #4 : Drawing on the Screen

So far we've covered handling inputs and outputs on the Microbit. In doing this we've introduced a little bit of Sniff, but not by teaching the language - you already know that because you've used Scratch. Rather we've focused on hooking Sniff into meaningful things, like leds and switches which is far more fun! These simple inputs and outputs are easy to handle directly in Sniff, but sometimes you need to interact with more complex devices like the microbit display.

Complex hardware is handled by creating "Devices". These are a little like objects if you've used more advanced languages. If you're fresh from Scratch, then they're just a way of wrapping up a bunch of code someone else has written and letting you easily talk to a piece of hardware. The microbit display device handles drawing on the screen.

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


Here we've made a variable (of sorts) called display, which is actually a microbit display. We've also made some other variables which we're going to use to talk to the display. Now for some actual code:

when start
.set displayColor to 700
.tell display to "clear"

Colours in Sniff are (usually) represented by a 3 digit number. If you've written HTML you'll know it uses 6 digits. Sniff is just a slightly simplified version of that. The first digit is the amount of red, the second green and the third blue. Each digit is allowed to go from 0 to 7. But wait a minute - the Microbit display can only do red? That's true, but Sniff runs on lots of different hardware with different kinds of displays. Here we're specifying 700 which is full red, but 700 is full red on all displays. It means we can take this code and run it on different hardware later, with only minimal changes.

Having set a colour we tell the display to "clear". Tell is the only extra thing that's in Sniff that isn't in Scratch. In Scratch when you want to talk to something that's not part of the core system you use an extension, but that causes all sorts of problems, as you end up with dozens of extension, and hundreds of new blocks. In Sniff there's only one "extension" - tell. It lets us send a message to the display device asking it to do something. Different devices understand different messages, but devices which can act as displays have a fairly standard set of message.

Now there's one more think we need to add to get the  display to do something: The Microbit display is actually broken down into three parts. At any time only 1/3 of the display can be lit up. In other languages there's a lot of really fancy code built into the system that automatically lights up different parts of the screen really quick so you can't see it move but in Sniff, its much simpler - we light up different parts of the screen by calling "tick". That means we need an extra script to handle that:

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

You need to include something like this in every Sniff program that uses the microbit display. It might look a bit clunky when you start out, but its actually quite clever - Sniff is doing the work for us that would be much harder to do in another language. You can even add a delay into this loop, and you'll see the different parts of the display light up, so you can really understand how the display works. If your program isn't displaying, then check you've remembered to include this.


The next thing to do is try setting some individual pixels:

when start
.set displayColor to 000
.tell display to "clear"
.set displayColor to 777
.set displayX to 3
.set displayY to 3
.tell display to "set pixel"

This just sets the middle pixel to be fully on.

when start
.set displayX to 1
.repeat 5
..set displayY to 1
..repeat 5
...set displayColor to (displayX+displayY-2)*100
...tell display to "set pixel"
...change displayY by 1
..change displayX by 1

Here we set every pixel on the screen with a colour based on its position. This forms a gradient, with the bottom left pixel being off, and the top right being fill on.

You can draw lines with "move" and "draw":

when start
.set displayColor to 000
.tell display to "clear"
.set displayX to 1
.set displayY to 1
.tell display to "move"
.set displayColor to 777
.set displayX to 5
.set displayY to 5
.tell display to "draw"

Finally we can display text:

when start
.set displayColor to 000
.tell display to "clear"
.set displayX to 1
.set displayY to 1
.set displayColor to 777
.set message to "hello"
.tell display to "show"

This tries to write "hello" on the screen. Unfortunately the microbit screen is rather limited, and all you'll see is the "h" - the rest doesn't fit. To make it fit we'll need so scroll it around:

when start
.set message to "hello"
.set displayY to 1
.forever
..set displayX to 1
..set offset to 1
..repeat until displayX<1
...set displayColor to 000
...tell display to "clear"
...set displayColor to 777
...set displayX to offset
...tell display to "show"
...change offset by -1
...wait 0.1 secs


We start by drawing the text at 1,1 and then change the offset, so the next time around the loop its printed one pixel to the left. After you've drawn some text, displayX tells us where then end of the text is, so when displayX is less than 1 we know we've scrolled the whole message off the left hand side of the screen, and we start again.

You can easily add this script to any of your Sniff programs, so that a message constantly scrolls. In your main script you can measure something and then just assign the results to message, and it will scroll. If you like you could use a slightly different version that just displays the message once:

when showMessage
.set displayY to 1
.set displayX to 1
.set offset to 1
.repeat until displayX<1
..set displayColor to 000
..tell display to "clear"
..set displayColor to 777
..set displayX to offset
..tell display to "show"
..change offset by -1
..wait 0.1 secs

Then in your main script

when start
.set message to "scroll me"
.broadcast showMessage
.say "there's a message scrolling!"

We're starting the showMessage script by calling broadcast,  and just like in Scratch the showMessage script runs at the same time as the main script continues. If you want to wait for the message to complete scrolling just use broadcast showMessage and wait.

This might look like a lot of code just to display a piece of text, but look at what we're actually doing. All of the scrolling, and timing is handled in Sniff. Scrolling a message continuously on the screen while doing another calculation is very hard in most languages, but in Sniff its easy. Of course Python on the microbit has a "displayScrollingMesssage" function built in which does all of this for us, but that's because actually doing it in Python would be too hard. Doing it in Sniff means you can see how it works, and change it around. How about making the text bounce left to right, then right to left?

While we've been specifically talking about the Microbit display, you can use exactly the same code to draw on all sorts of different display hardware, from and LED matrix connected to an Arduino, and GameBoy advance screen, through to an on-screen window on a Mac, or PC. They all use the same commands, so porting the code is just matter of changing the type of device you create, and then maybe adding some scaling to take into account for the different resolution.

Friday, 22 April 2016

Sniff from Scratch #3: Microbit inputs...

The next step in our Sniff Microbit Tutorial series to start collecting inputs to control things. Specifically lets press a button to turn an led on and off. The Microbit has two buttons which are connected to pins D5 and D11, so the first thing we need to do is to tell Sniff about that:

make buttonA digital input D5
make buttonB digital input D11

These lines of code will be the same for pretty much every microbit Sniff program, but if you wanted to take that program and run it on an Arduino you might hook buttons up do different pins. The only change you'd need to make is to these lines.

If we attach an LED to pad 2 then we can write:

make buttonA digital input D5
make buttonB digital input D11
make led digital output D2

when start
.forever
..if buttonA
...set led to on
..else
...set led to off

In fact we can shorten that a bit and just write:

when start
.forever
..set led to buttonA


There's a lot of variation on this - what if you want one button to turn the led on and the other to turn if off:

when start
.forever
..if buttonA
...set led to on
..if buttonB
...set led to off

However there's another way to write that, which is more "scratch" like:

when start
.forever
..if buttonA
...set led to on

when start
.forever
..if buttonB
...set led to off

Here we've got two scripts, which checking a button and doing something. Just like Scratch, when we click the green flag/start both scripts can run at the same time. Sometimes this can really simplify things. Lets say there are two leds, and each button will turn on its respective LED for 1 second. That's really hard to do in most programming languages because if I press buttonA to turn on led1, then wait 1 second and turn it off, then buttonB/led2 will stop working for that 1 second. In Sniff this is easy:

when start
.forever
..if buttonA
...set led1 to on
...wait 1 secs
...set led1 to off

when start
.forever
..if buttonB
...set led2 to on
...wait 1 secs
...set led2 to off


Just as we had two kinds of outputs - digital (on/off) or analog (varying brightness), we have two kinds of inputs: digital (like buttons) and analog where we're measuring something that is variable.

If you connect a Light dependant resistor or a thermistor between ground and one of the Microbit pads and a 10K resistor between the pad and 3v we can read in a value which will represent either brightness or temperature. To do that we just write:

make sensor analog input D0

when start
.forever
..say [sensor]
..wait 1 secs

This will print out the value to the computer. This value will go from 0-1. It's possible to convert these measurements into calibrated measurements, but often that's not necessary. We can just use the fact that the value goes up or down to trigger some event.

when start
.forever
..if sensor >0.5
...set led to on
..else
...set led to off

You will probably need to tweak the threshold value a bit to get this working reliably, but with a bit of   experimentation you could flash the LED when it gets cold. You could place a light sensor next to a door and detect when the door is opened or closed.

A favourite which I've used many times is to use two light sensors to detect an object passing over them - often a hot wheels toy car.

when start
.wait until startSensor <0.5
.reset timer
.wait until endSensor <0.5
.say [timer]

This measures the time between the two sensors being triggered. If we know how far apart the sensors are we can work out the cars speed!

Wednesday, 20 April 2016

Sniff from Scratch#2: Moving to Microbit

If you read the previous post in this series you're now writing programs in Scratch, running on your computer, but that can get a bit boring. With Sniff it's no harder to run code on a Microbit or an Arduino and its so much more fun. Most Sniff workshops we run involve some kind of hardware simply because it shows code doing something. For some people just writing code is enough - they love the puzzle aspect of it, but most people just ask "whats the point?". Well the point is I want this robot to drive around the room, or I want the lights to turn on if it gets dark, or I want to make a game.

The first step of hooking up a microbit is simply to plug it in via usb. It should appear as both a USB disk and a serial/com port. Once its plugged in and detected, when you run click on the "clickMe" shortcut you'll see that in the startup messages Sniff will say that a hardware device has been found. Hopefully this will be the right device but if you have multiple serial devices plugged in then make sure its the right one (unplug others just in case!).

Now you should be able to take a Sniff program you wrote in previous sessions, but instead of pressing the compile button press the microbit button in Sniffpad (or Arduino - they work the same, but I'll just say Microbit from now on!). This compiles and downloads your program into the Microbit - check that you don't get any error messages, it should say Download OK, and the light on the microbit should flash for a few seconds as the program downloads.

So far we've only written programs that print things out using "say", but the Microbit doesn't have a proper screen to print things on, so where does it go? Back to the computer! Press the terminal button in Sniffpad, and you should get a window appear. Anything the Microbit prints out will appear in that window.

We could run most Sniff programs on the Microbit, but really there's not much point - it would be just like running them on your main computer but MUCH slower. Instead we want to flash some LED's. If you've never done this, then you're going to love it!!!



Strictly we should have a resistor in series with an LED to limit the current, but LED's cost pennies and the microbit is 3.3 volts so we can cheat and not use one. This is BAD electronics. If you try it on a 5v system like Arduino you will damage the LED and/or board, but for Microbit its probably safe.

LED's always have a long leg and a short leg. The long leg goes to +ve and the short leg to negative. On the Microbit that's the two pads on the right marked 3v and GND. Connect an LED between them and see it light up! If it doesn't turn it around (and check the thing is plugged in to power!).

Now connect the +ve leg to the pad marked 0, and the short -ve leg to GND. You'll need some wires/clips to do this - I'm not sure they really thought this bit though... the edge connector is very pretty but not very practical. Now we need to write some code to drive the LED.

The first thing we need to do is tell the system which pad the LED is connected to, so we create an output with the line:

make led digital output D0

This is just like creating a variable, but instead of making a number we're making a digital output. Of course we've got lots of digital outputs, so we need to know which one "led" refers to, and in this case we've chosen pad 0. The "D" in D0 stands for Digital, and is a hangover from Arduino which has two sets of pins: the D pins and the A pins. However its important to include the D, as the Microbit does have another "secret" way of numbering its pins - the pads are numbered based on they way they're laid out on the edge connector, but actually that's not how they're numbered internally. The "D"tells Sniff that we want to use the simple numbering system rather than the secret numbering system.

make led digital output D0

when start 
.forever
..set led to on
..wait 1 secs
..set led to off
..wait 1 secs

Now we can flash the LED! We can use LED just like a variable but because its a digital output it can only be either on or off. If you prefer you can use the names yes/no, high/low or  true/false. They all mean the same thing, as they're just different terms frequently used for the two possible states that the pin can be in. Note that 1 and 0 (which are also frequently used to mean the same things) are not allowed. That's because they're numbers and we don't want to confuse numbers and boolean states. Its just simpler that way.

Try playing with the different durations of wait, flash different patterns...

at some point you'll end up setting both durations to be very small. Anything less than 0.01secs and you probably won't see the flashing. If you want to flash the LED really fast you can specify durations in millisecs or microsecs.

.wait 10 millisecs
.wait 100 microsecs

You won't be able to see these flashes but the LED will be dimmer as its now off half the time. In fact we can control exactly how bright by changing the relative duration of the two delays in the program, so its on or off for more or less of the time.

This is so useful that its actually built in as a feature of the hardware. If we redefine out LED as:

make led analog output D0

when start
.set led to 0.5

We can set its brightness to a value from 0 (off) to 1 (on). However its now a number so we can set it to half brightness using a value of 0.5. Strictly speaking the LED is never "half on" as the microbit is actually flashing the led on and off very quickly but the effect is pretty similar.

make led analog output D0

when start
.forever
..set led to (timer mod 5)/5

Now you should see the LED get brighter. Finally lets make something really cool:

when start
.forever
..set led to (0.5*sin of (timer*100))+0.5

Now at Yr 7 most kids won't know what a sin function is, even though it is in scratch exactly the same way as it is in Sniff, but you can still use it. 

Everything you need is in this diagram. It goes up and down in 360 steps so timer*100 will make it go up and down every 3.6 seconds. It's output is from -1 to +1, but our LED needs 0-1 so we multiply by 0.5 (its now -0.5 to +0.5), then add 0.5 to map its output to the range we need for our LED.

The result is an "Apple" style pulse, and its sufficient to make the most cynical of hardened engineers smile and sometimes even giggle! It's seriously impossible to understate how effective this is. Flashing an LED might not sound like the most exciting class, but everyone will love it!