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.
Showing posts with label Lego. Show all posts
Showing posts with label Lego. Show all posts

Wednesday, 28 September 2016

Lego IR "train" controller

Just a quick update on the previous post where we used the Lego IR remote to control and Arduino. I've not got my hands on a Lego "train" controller which has two dials and two buttons. Pointing one of those at an Arduino with the IR receiver attached, produces a fairly simple set of codes.

The Left dial generates 100 and 101 as its turned in each direction, while right dial generates 116/117. When used with the regular IR receiver these mean speed up/slow down on the red and blue channels but you can use them in your code to mean anything you like. Each turn will generate a burst of codes, so you're likely to receive several at a time. This is intended to make sure that the code actually gets through. You might need to ignore repeats of a code if they arrive very close together, as its not multiple turns, but just multiple signals.

The left button generates 72,  while the right button generates 88. Somewhat surprisingly pressing both butts at the same time generates 31, which to the Lego decoder means brake both motors. The numbers don't appear to make sense as 31 is a code to control both motors, while 72/88 are codes to control individual motors so are sent in a very different way.

Unlike the regular Lego remote, the codes are never combined (except for 72+88=31), so if you press and hold a button, then turn a dual, you can no longer detect if the button is pressed. Turning both dials at once, results in both sets of messages being sent, rather than just a combined signal as per the regular remote.

Channels (1-4) work report in the irProtocal variable, so you can use up to four remotes at a time!

Friday, 23 September 2016

Receiving Lego IR

In the previous post, we used an IR LED to control Lego Power Functions motors, which was pretty useful, but what about going the other way - using a Lego PF remote to control an Arduino?

That standard Lego remote is really nice for controlling Robots as it has two levers, giving you forward/back tank style steering. There's a handy "reverse" switch for each lever, and best of all there's a channel selector, so you can operate up to four remotes at the same time. This is always a problem in workshops where everyone gets the same kit of parts, and everyones remote controls everyone else robots!

At about £7.50 from the Lego store, they're pretty reasonably priced if you're buying them for yourself, or even a classroom, though unfortunatly our workshop budget won't stretch to giving them away, as we do with the regular £1 remotes.

Lego uses a unique (but well documented) protocol, so which we've added to the regular receiveIR device, so if you have build a robot with an IR receiver you don't need to change anything, other than detect the new keypress codes.

Working with IR is cheap and easy - just get a  tsop-4828 receiver for about 50p, and wire it to a data pin on an Arduino (note that the transmit code should work on any micro controller, but the receive as some Arduino specific bits):



The code to read from an device, works exactly the same as it always did:

make remote receiveIR device D2
make irProtocol number
make keyPressed number

when start
.forever
..tell remote to "read"
..if not keyPressed = 0
...say join "Protocol:" [ irProtocol ]
...say join "KeyVal  :" [ keyPressed ]
...say ""

Now, if you point a lego transmitter at it you'll start getting key codes. The channel is returned in the variable irProtocal, so you can easily run multiple controllers at once. If you're really interested in making sense of keyPressed value then there's documentation available from lego. The value returned is the middle 2 nibbles of the data packet, with the escape bit tagged on the beginning.

While its possible to decode the packet based on the documentation, its probably easier to just look at the values that are being sent when each button/lever is pressed, and actual accordingly.

If we look at the codes sent by the regular remote, a value of 16 is sent when nothing is pressed. In fact you can subtract 16 from every received code and things start to make sense: Left stick generates 0 in the centre, 1 when forwards and 2 when backwards. Add these to the 16, that this remote always sends and you're in business. The right stick works the same except we multiple by four, so the value sent is 16+4*rightStick+leftStick.

Of course you can still use most other regular remotes to, but the Lego ones are a bit nicer. The code is now on live.sniff.org.uk along with an example and will by in the next desktop release.

Wednesday, 21 September 2016

Power Functions IR


Lego WEDO is great - you can control power functions motors, but its a bit expensive, and you need a computer. An alternative and cheaper way to control power functions is with the IR control, which you costs £11.50  (important hint: NEVER buy Lego on Ebay or Amazon without checking the lego site first. It's usually much cheaper. The logo consumer store is also much cheaper than the edu store, even though you're buying the same component from the same company). Of course you'll still need some motors and lights and the remote control, but you probably have some of those anyway. Either way you're in business for about £40 rather than £135 (though of course if you buy a few more bits you'll get free shipping, so a few extra parts is saving money in the long run).


It turns out that while the lego IR system is a bit quirky, its well documented, and pretty easy to control from an Arduino or similar. All you need is an IR LED, which cost a few pennies - wire it to one of the pins with a 500ohm(ish) resistor in series so you don't break anything, and you'r good to go.

To code for it in Sniff, just make a device:

make remote transmitLegoIR device D13
make blueValue number
make redValue number
make channel number



I've called it "remote" and attached it to pin 13. Then I powered up the receiver as normal, and connected a motor to the red output. You'll notice that there's an orange slider on the side of the receiver, which sets the channel. If you've only got one then you can just keep it set to 1, otherwise match the channel in the code to the receiver you want to control.

All I want to do is run a motor back and forth, so here's the code:

when start
.set channel to 1
.set blueValue to 0
.forever
..set redValue to sin of (timer*100)
..tell remote to "send"
..wait 0.1 secs

All the code does is set the blue output to 0 (Stop), then goes into a loop. The red value is set to range from -1 to +1: full reverse to full forwards, changing with time. Once you've set the red and blue values as you want them, just tell the remote to "send" and it fires of a few IR pulses and the Power functions should do whatever you command!

Normally at this point I'd tell you that the code would be in the next update of Sniff (and it will be!), but if you go to live.sniff.org.uk now you'll find the example code already there, and you can compile it for Arduino online!


Tuesday, 15 March 2016

Banana Physics

Yesterday I presented a talk at ICT Conference for Schools, in Southampton. We're (hopefully) going to be presenting something similar in Boston this summer. I thought it would be good to just summarise it here, and post the code examples I showed.

Banana Physics starts with the Banana Piano - the classic Makey Makey project... or should I say the ONLY Makey Makey project. Despite their claim its an "invention kit" which can "make anything", their idea of "anything" is rather limited to being a keyboard made out of fruit! More or less any fruit you'd like!

In addition to being limited, we don't actually learn anything from the piano project. It's fun (for a few minutes), but what are we trying to teach? That Banana's are fun? The best thing we might learn is that Banana's conduct electricity... 

Except they basically don't. To understand we need to investigate RESISTANCE. If we use a pico board, instead or a makey makey we can actually do science!


This is the circuit that the pico board (and pretty much everything else) uses to attach your banana to the computer. R1=10K, and the banana replaces R2. With a bit of good old school Ohm's law, we can write an equation to calculate R. It turns out the Banana's have a resistance of around 40K-50K ohms. Not good conductors at all.

The next step is to drop a thermistor in place of R2. With a bit more complex maths, we can turn that resistance into a pretty accurate temperature (or up to 4 different temperatures on the different channels). It's pretty easy to log that data over time. On the one hand Picoboards aren't cheap (about £30 in the UK), that's really nothing compared what you'd pay for a 4 channel data logger, or even a good multimeter.

We then switch out the thermistor for a light dependant resistor. We could track light levels, but we can also use it to detect an object moving in front of the sensor. We set up two about 70cm apart, and time a beanbag to fall from the top one to the bottom one. Applying kinetic equations we know starting speed (0m/s), distance (0.7m), and we measure time. Which allows us to calculate acceleration - gravity.

Alternatively we can use the Lego Wedo... Two distance sensors make a great speed trap, so we can measure the speed of an object. If we drop the beanbag 70cm, and measure its final speed, kinetic equations will give us gravity again. In the talk I just did a very casual demo, and dropped it from a very rough distance, and it came up with a value of 8.5m/s/s. Pretty good.

The final demo was using the wedo tilt to measure the period of a pendulum. Again putting together  a bit of maths/physics, and coding I got a value of 10.5 this time. Again, this is pretty good for a guy standing in a room with a laptop and a few bits of Lego.

Here's the code I used for the demos. Check out the "Science" tag on my blog posts, to get more detail on these projects (perhaps built with different hardware), and ideas for other code based science.

The point of the talk was (in addition to promoting Sniff!), to show how using coding and making you can make high school science really fun. If coding is writing, then the whole point of learning to code is to unlock new ways of expressing and exploring. If coding just lives in the ICT class then its a total waste of time. If it lets you explore and understand the universe better, then that's pretty amazing.


Tuesday, 8 March 2016

Lego Dacta Control Lab B

So far I'm very skeptical about the Wedo 2.0. It's yet another lego electrical plug standard that's incompatible with both the existing Wedo/PF range or the EV3. That means not only do we have to buy new motors and sensors but we have only two sensors and one motor (where as Wedo 1 can use st least use several motor types, the servo, and lights). The argument that the new plug will by more versatile and flexible is exactly the argument that was used when the Wedo/PF plug replaced the older Lego 9V system, but in practise there were less components produced for PF than for the 9V system.

In fact looking back at the Lego 9V/RCX system, it seems the most complete, and well thought out of the many the different (incompatible) Lego electrical systems. While it is a bit limited, and in theory the more modern systems should have a technical advantage the older and simpler system has one fantastic thing in its favour: compatibility. 

While currently lego uses one plug for its technics range (Power Functions) another for Wedo 2.0, and a third for EV3, the older system used the same plug for all its products, so technics users could add an RCX controller. Even when NXT (and subsequently EV3) was introduced an adapter cable allowed 9v/RCX sensors to be used. Even today the Power Functions extension cable allows 9V motors to be used (and PF motors to work with 9V controllers).
The old 9V plugs were also simple: a positive and negative terminal which could either provide power, or be connected to a resistive sensor. With a bit of cleverness, they could be persuaded to do both at the same time, so powered sensors were possible. Putting the same system in the hands of the public, and educators led to an explosion of creativity (that neither the Wedo or the Microbit are able to enjoy!).

However while the 9v system is well remembered, one of its greatest creations is all but forgotten:

 Dacta 9751 Control Lab B



Look at that thing and ask yourself what more you could ask for from a system. 8 inputs, 8 outputs, connected via a serial port (so no drivers needed). Compatable with a wide range of cheap sensors. You'd need 8 wedo to do the same job! It was released in 1995, and its bigger and better than anything available now.

As for what you could attach, there were a choice of motors in various sizes, various types of lights, two different sirens, a light sensor, a rotation sensor, a button, and temperature sensor. The light sensor is actually very similar to the Wedo distance sensor (though not quite as robust), but the rotation sensor leaves the Wedo Tilt in the dust - It can measure angles of rotation in 22.5 degree steps, which compared to the Tilt's forward/backwards just shows how much we've dumbed down!


We were able to pick up one of these, and a whole load of sensors for less than half the price of a Wedo set. We also got some PF extension cables so we can use our existing PF motors (or hack them up to make new sensors!).

Cables:

If you have the original cables and PSU then great, but if they've gone missing, the PSU is 10V AC, 7VA. Note that this is an AC-AC transformer, so most PSU's won't work.

The second thing you need is a serial cable. Again most probably won't work! For you youngsters too you wet behind the ears to remember serial cables, gather round and I'll tell you about the olden days...

You see serial cables were designed to connect computers to modems. Modems would talk over a phone line to the another Modem, which would then have another serial cable to a computer. The Modems just passed the message along, so were called Data Communications Equipment (DCE), while computers were at the ends of the signal path, so were called Data Terminal Equipment (DTE).

Now if you've ever encountered a pin on a circuit board marked "TX" you'll know the dilemma - is this the pin that the board is transmitting on (so you connect it to your RX) or is it the pin that you should use to transmit, so connect it to your TX. Well with DTE and DCE its really easy: DTE is "in charge", so TX on DTE is an output, and TX on DCE is an input.

On a 9pin conector, pin 2 is RX and pin 3 is TX. Thats the same for DTE (male plug) and DCE (female socket) so you just connect all the pins straight across and you're good to go...

But what if I'm not talking to a modem? I'm talking to an I/O board here... They should both be DTE? Well the "correct" thing to do is to use "null-modem". In theory thats a small box that has a DCE socket on each side. You connect each piece of DTE equipment to the Null Modem and the null modem crosses over the RX and TX wires.

But that's a lot of hassle - two cables and a box when we could just make our I/O board look like a modem. Put a female socket on, wire it like a modem, and use a regular cable. Or we could just get one cable and put a twist in it, so we'd have a female-female null modem cable. Or we could do something totally crazy...

which is exactly what Lego have done... They've put a female (DCE) connector on the box, so you need a male-female cable, but they've wired it as DTE. That means you need a M-F DB9 null modem cable!!! They do exist and you can get them cheaply on eBay, but they're not the sort of cable you're likely to have in your bits box.

Between the odd PSU and odd serial cable I hate to think how many of these gems have been thrown away as "not working", when they just need hooked up properly.

With that in place, you'll probably need a USB-Serial converter - any with a DB9 connector on will do. While using old school serial might seem tedious compared to USB, the benefit is that we're now good to go - no drivers, or difficult code to write. Just send some text and it works.

Lets Go:

Even when you get everything hooked up, you still need the right software to get the thing to jump into life. I spend some time wondering if mine was broken, before getting it working reliably.

Plug it all together and fire up Sniff, release 25 or later. It should find the serial port (it'll call it an Arduino, but it calls everything an Arduino!). If you're on Windows you'll need to set ARDUINODEV to be the com port you're using. The example files are in examples/Hosted/dacta/test.


make lego dacta device
make legoValue number
make motor dactaMotor device 1

when start
.forever
..set legoValue to cos of (timer * 60 )
..tell motor to "update"
..wait 0.1 secs


To control a motor, the first thing we need is a dacta device. the variable legoValue is used to communicate with modules. We then create a motor device on port 1. To set its speed, just set legoValue and tell the motor to update. If your familiar with the old Wedo Sniff API then you can also communicate with a specific port by using the legoConnector variable, but the new style API is nicer. The Wedo also can use this new Object based style (check the examples).

To read from a device like a button:

make lego dacta device
make legoValue number
make button dactaTouch device 1

when start
.forever
..tell button to "update"
..say [legoValue]
..wait 0.2 secs

Interestingly the lego "Touch" sensors are actually analog, and can report the strength of the push rather than just being on or off.

The dactaLight, dactaTemperature and dactaRotation devices work in exactly the same way, returning a value whenever you call "update".

 One minor thing to watch is that the Control Lab has a fail safe - it if doesn't receive a message within 2 seconds it shuts everything down. Normally this isn't a problem as you're probably reading sensors more often than that, but if it is just add

when start
.forever
..tell lego to "update"
..wait 1 secs

somewhere in your program, and it will just keep the board alive.

The Wedo 1 is a great device, the Wedo 2 maybe in the future, but the Control Lab B is really the Mother of all Wedo! It's an amazing device, and its a shame that we can't have something quite as cool available today.

Saturday, 6 February 2016

Lego Wedo Semaphore

After building the Semaphore robot, I was clearing up the Wedo Speed trap stuff, and wondered if we could make a semaphore robot from Lego?

The easiest way to do it would be using EV3 motors. We can run Sniff on the EV3, and the Mindstorm, and in fact EV3 motors are perfect for this task. We weren't able to use regular motors for the Arduino version, as normal motors just turn, and you can't figure out where they are (so we used stepper motors). EV3 Motors have an extra sensor built into them so you can position them exactly. That means they can easily turn the required angle, and move to specific positions. However setting up the EV3 is quite a bit of hassle.

That's one of the reasons I like the wedo so much. It's just quick, plug and play fun, without the "bigness" of EV3.


The Wedo supports motors by default, but it can also use Power Functions components like lights. One of the coolest Power Functions components is the Servo, which can move to a precise (ish) position over 180 degrees. It's not supported by the Official Wedo software but we can operate it from Sniff.


Check back with the previous post on semaphore for the bulk of the code and background on handling semaphore. We'll concentrate on the Wedo bit. Most of that is taken care of by a script called "update":


when update
.forever
..set wedoConnector to 1
..set wedoValue to -2*((target1+1)-3)/6
..tell wedo to "setMotorSpeed"
..set wedoConnector to 2
..set wedoValue to -2*((target2-3)-3)/6
..tell wedo to "setMotorSpeed"


This maps semaphore positions in the "target" variables to value between -1 and +1. However we need to be a bit careful. The Lego Servo is an odd machine, which only handles a fixed set of positions. It can move to centre (0) and 6 positions each side (even though the Lego website says 7!). A value to 1 means 90 degrees, and we can move in 15 degree increments. If you try and set a value between those increments strange things happen - sometimes the servo skips, or doesn't move, and sometimes it makes whining noises. For best operation we need to move the servo value in 1/6ths
 
For the left motor we have to support semaphore values between -1 and 5 so lets add 1 to it, so now its between 0 and 6. Now subtract 3 so its centred around 0 (ish), then divide by 6 so we get  nice reliable steps.

But each step is only 15 degrees. We want each step to be 45 degrees. We also need a travel of 270 degrees, which the Servo can't do... That's why we used a stepper last time. But now we're using Lego, we can easily build a gearing system. A Lego small cog has 8 teeth, and a large one has 24, so if we use the servo to drive a large cog, it will turn a small cog 45 degrees, and we will have a potential travel of 540 degree!

That sort of works, but neither the servo or the gearing is that precise - there's a lot of play in both, which means that it isn't accurate enough to clearly signal. Instead we multiply by 2, so each semaphore position is two steps separate (30 degrees). Now we need a gearing ration of 1.5, which turns out to be quite hard to make. However if you have Extra large cogs they have 40 teeth, so if we drive a large cog from an extra large cog we get a ration of about 1.6 which is close enough.

The minus sign just flips the direction, as the gearing reverses the direction of rotation and we need to compensate. We have a similar mapping for the right hand servo which is on Wedo connector 2.

The rest of the changes from last time are just about tweaking the code to work right with the specifics of the build, and evolution of the code. Left and right ware swapped just because of the way I connected it, and target is now specified in semaphore positions rather than stepper positions. The timings change a bit just because of the speed of the motors and we have no way of knowing when they arrive in position (thought the lego servo is much faster than the steppers).


make theLetter string
make theLeftPos number
make theRightPos number
when getPositionsForLetter
.make counter number
.repeat length of key using counter
..if letter counter of key=theLetter
...set theLeftPos to item counter of leftFlag
...set theRightPos to item counter of rightFlag
...stop script
.set theLeftPos to 0
.set theRightPos to 8


when attention
.repeat 3
..set target1 to 1
..set target2 to 7
..wait 1 secs
..set target1 to 3
..set target2 to 5
..wait 1 secs
.set target1 to 0
.set target2 to 8
.wait 2 secs

when start
.make counter number
.
.set target1 to 0
.set target2 to 8
.
.broadcast update
.broadcast load and wait
.forever
..ask "What's the message?" and wait
..broadcast attention and wait
..
..repeat length of answer using counter
...set theLetter to letter counter of answer
...broadcast getPositionsForLetter and wait
...say join [theLeftPos] join ":" [theRightPos]
...set target1 to theLeftPos
...set target2 to theRightPos
...wait 2 secs
..
..set target1 to 0
..set target2 to 8

And here's the "finished" version:


Unfortunatly now I have to admit, I couldn't finish the project - I've only got 1 PF Servo... They cost £20.99 + postage and my lego budget has to cover a lot of other things! Even worse on Ebay there are buy it nows from £28 to £60!!!!! (EV3 medium motors are £19.99 on lego.co.uk but £34.99 on eBay!) I've noticed this before - ebay is some kind of crazy place to buy Lego. Sometimes you get bargains, but on newer stuff you can pay more than buying direct.

Rant Warning - you can skip the next few paragraphs...

To make things worse, Lego just obsoleted Power Functions. PF isn't officially dead (yet), but the new Wedo 2.0 uses a completly different connector. According to Lego PR, the Bluetooth connection between the computer and 2.0 hub means they "needed" to change the cable between the hub and motors... and the tilt sensor now has a "shake" mode... so they needed to change the cable! This is obviously untrue. Previously Wedo used standard PF components, but now the Wedo 2.0 has it's own connector and won't plug into anything else (whereas the old version plugged together like... you know... Lego?). The explanation is that PF is about to be replaced by PF 2.0 (there's a reference here: https://education.lego.com/en-gb/lesi/elementary/wedo-2/faqs) . There's no backward compatibility so throw out all your old sensors and motors!!

It's really about time Lego got its act together on this... three generations of Mindstorms used different cabling (with some backward compatibility at least), Power Functions was introduced to replace the old 9V technics motor system (and versions before that!), with the claim it allowed for future expansion - which only materialised as Wedo. Technics never got any sensor features, and Wedo was kept secret from the public. Each generation of Lego engineers decides that the old plug system is too limiting. Wedo 2.0 delivers nothing in terms of new sensors (yet) and in fact we loose lights and servo's, but they're asking me to throw out about £500 of my own motors sensors and hubs, just to avoid the cable to the computer.

Going Bluetooth has benefits (and disadvantages if you have a lot of them in the same room and group 1's computer pairs to group 2's build - accidentally or deliberately!),  and if I could buy a Bluetooth hub to use with my current motors and sensors and ADD to my wedo system I'd be first in the queue, but starting over with a system that's less capable...

With that rant out of the way, now might not be a great time to invest in Power Functions components! At some point there's going to be some tough decisions whether to invest more in established (but obsolete) 1.0 tech or throw out a lot of expensive stuff, and  start over.

And we're back...


Anyway I was able to test and get both arms working - just not at the same time! It's less precise that the stepper version, and but it works really well. Cost wise its a bit crazy - the hub and two servos would cost about £80, whereas the Arduino version cost less than £10. On the other hand, the lego version demonstrated the power of Lego - I was able fabricate the supporting structure, including gearing way more easily -  building a gearbox for arduino and servo's isn't something I could do. That's where the Wedo really pays off - just being able to combine building and coding so easily...

Thursday, 28 January 2016

Wedo Speed Trap

We've got a couple of live events coming up in the next few months, and at one of them we plan to talk about how the Picoboard, Wedo and Flotilla can be used to do "real" science experiments rather than just fun e-toys. While there's nothing wrong with fun gadgets and demo's to attract attention at some point we need to harness that interest and show that programming can solve "real" problems. (I need a way of advancing my presentation slides and all I've got is this size of pizza and a $50 interface box designed for this exact situation is neither real nor a problem). It doesn't really matter what that problem is, but there needs to be some element of writing code to do something that's extrinsically relevant (and better in some way than alternative approaches - pizza has many great features, but some kind of ir or bt remote is a way better and cheaper method of controlling slides).

This led to revisiting a few of our old experiments, and prepping to fit as many cool demo's into 30minutes as possible. On of the things we wanted to demo was the hot wheels speed trap, but based using the pico board or the wedo. Both proved pretty easy to do, but we found that the pico board doesn't deal well with updating more than about 100 times per second. It gets swamped somehow, and just gives up. This is fine for measuring longer time intervals, and we set up a tube, with a light sensor at the top and bottom to measure how long a beanbag took to fall the length of the tube. However for measuring the small intervals required of the speed trap it was too slow.

The wedo on the other hand proved to be very reliable, and worthy of a mention here.

We simply placed two motion sensors at opposite ends of a board, and measured that the distance between them. Just by being Lego we git instant "extra" value (I hesitate to say free value, as its stupid expensive), it makes a big difference just being able to stuck together some kind of structure, even as simple as this, just to hold things in place.

Then just wait for the first to detect something, then wait for the second and measure the time between them (15 studs 0.8mm per stud=12cm)



make wedo device
make wedoConnector number
make wedoValue number

make startTime number
make recordedTime number
make recordedSpeed number
make sensorDistance number 0.12

make message string 

when start
.forever
..say ""
..set wedoConnector to 1
..tell wedo to "readDistance"
..repeat until wedoValue < 0.06
...tell wedo to "readDistance"
..
..set startTime to timer
..say "go"
..
..set wedoConnector to 2
..tell wedo to "readDistance"
..repeat until wedoValue < 0.06
...tell wedo to "readDistance"
..
..set recordedTime to timer - startTime
..set recordedSpeed to sensorDistance/recordedTime
..
..set message to "time      :"
..set message to join message [ recordedTime ]
..say message
..
..set message to "speed     :"
..set message to join message [ recordedSpeed ]
..say message

The "readDistance" command sets wedoValue to an estimate of the distance in metres, so we check to see if its less tham 6cm. Then we switch to the second sensor and check that. Once we have the time, we divide that into the distance (14 studs x 0.8mm/stud) to get the speed.

If we drop a beanbag from a know height, and measure how fast its going when it passes the beam we can use the equation:

Vf^2=Vi^2+2ad

As we're dropping it, its initial velocity is 0, so we can simplify and rewrite as:

a=(Vf^2)/2d

So we can calculate gravity (again!) - it came out at about 9m/s/s this time, which is pretty close.

Best of all the sensor proved to be very robust. We've used light dependant resistors to do this sort of things before, and there's always a bit of tweaking involved to get the lighting, and threshold values just right. Because the lego sensors are self illuminating and (semi) calibrated, they work without requiring much adjustment in a wide range of conditions. The lego sensors detect things in front of them rather than shadowing them, which is much easier to work with. They're also easy to mount, so you could use them for all sorts of things where you need to measure speed.

Wednesday, 6 May 2015

Measuring Lego Motors with Wedo

If you've read through Lego's intro to wedo material (and the related simple mechanical machines) you'll find its an excellent introduction to gearing and ratios. Using a big and a small cog you get taught how to speed up, slow down and reverse the direction of rotation from either a hand crank or a motor.

But that section of the material doesn't actually use the Wedo... perhaps we could use it to put some numbers on those observations! How fast does a lego motor actually turn, and do the gear ratio's do what they're supposed to?

Here's the experimental setup:



The motor (driven by the wedo) drives the propeller blades which pass in front of the distance sensor (motor on connector 2, sensor on 1).  The first thing to do is check that the setup is viable:

make wedo device
make wedoConnector number
make wedoValue number

when start
.set wedoConnector to 2
.set wedoValue to 0
.tell wedo to "setMotorSpeed"
.forever
..set wedoConnector to 1
..forever
...tell wedo to "readDistance"
...say [wedoValue]
...wait 0.5 secs


This just turns the motor off, and prints out the reading from the sensor. Turning the blades slowly by hand shows that the value reported by the sensor does change. While we don't really care about the exact value, we can detect that the blade passes in front of the sensor when the value drops below 0.1.

when start
.set wedoConnector to 2
.set wedoValue to 0.3
.tell wedo to "setMotorSpeed"
.forever
..set wedoConnector to 1
..repeat until wedoValue >0.1
...tell wedo to "readDistance"
..say "ping"
..repeat until wedoValue <0.1
...tell wedo to "readDistance"
..say "pong"

Now we can check to see if there's a blade present - wait until there isn't (print ping), wait until there isn't (print pong). As the motor turns we're not tracking its rotation.

when start
.set wedoConnector to 2
.set wedoValue to 0.3
.tell wedo to "setMotorSpeed"
.forever
..reset timer
..set wedoConnector to 1
..repeat until wedoValue >0.1
...tell wedo to "readDistance"
..repeat until wedoValue <0.1
...tell wedo to "readDistance"
..say [1/(timer*2)]



Now we just measure the time it takes us to go around the loop. As there are two blades to the propeller, each iteration represents half a turn. A full turn takes twice that. We could print that out as time per revolution, but if we take the reciprocal that gives us revolutions per second.

For my motor (regular Wedo M-size) 0.3 is about as slow as it can go (in fact it takes a nudge to get started at this speed). We can measure speed for a few power settings:



0.3 Power = 0.85rps
0.5 Power = 1.55rps
0.75 Power =2.5rps
1(full) power=3.5rps



Theres a bit of variation, as the wedo probably only updates the reported value on a periodic basis, but the results are fairly consistent and representative.

Now lets mod the setup, and add an extra gear. This makes the fan turn faster (according to the lego introduction to cogs!)

0.3 Power = 2.5
0.5 Power = 4.6
0.75 Power = 7rps
1(full) power=10.4rps

In each case the new speed is almost exactly three times the previous one... The exception to that is the 0.75 which is a little low... However looking at the raw data for this particular measurement, it seemed to present the most variation 6.94 was the most common reading, but it was also the lowest, with occasional readings of 7.6 and 7.9 - no other reading had any where near such a wide variation, so it looks like this speed doesn't mesh well with the underlying sampling rate - lets just put it down to experimental error.


Now the moment of truth... Lets count the number of teeth on the cogs: The small one has 8, while the big one has 24... a factor of THREE!!!! One turn of the big cog turns the little cog three times, so the blade spins three times faster.
Awesome!


Tuesday, 5 May 2015

Lego Wedo Alligator

The Lego Wedo is awesome! It comes with a great set lesson plans, with lots of great projects, and ideas for how you can use the items you build as part of larger topics. However they're firmly aimed at KS2, which is a great shame as everyone loves Logo and having bought expensive hardware, far too many schools use it for a few sessions in year 4, then put it back in the cupboard.

The Wedo software is nice but limited and expensive, and its probably the main reason that Lego haven't made the Wedo available outside of primary education. Fortunately the Wedo works with Scratch and Sniff. This means there's lots of opportunity for frameworking and progression: we can revisit familiar (and fun) projects which have been completed in the Wedo Software, and rebuild them in Scratch and subsequently Sniff.

My favourite official project from the Lego set is the Hungry Alligator. Building instructions are built into the Wedo software, but you can download regular instructions here: https://education.lego.com/en-us/lesi/support/product-support/wedo/wedo-base-set-9580/building-instructions

Now lets code this in Sniff:

make wedo device
make wedoConnector number
make wedoValue number

when start
.set wedoConnector to 1
.
.forever
..set wedoValue to -1
..tell wedo to "setMotorSpeed"
..
..wait 0.4 secs
..
..set wedoValue to 1
..tell wedo to "setMotorSpeed"
..
..wait 0.35 secs

We start by making a wedo hub device. You can connect any number of hubs (more or less!), but we're just going to have one. Each hub as two connectors, and we've plugged the motor into connector 1 (the left 1). We set the wedoConnector and wedoValue, and the tell the wedo to "setMotorSpeed". -1 closes the mouth, while +1 opens it (that's just the way this model is built/geared), so this code closes the mouth, then opens it, repeating forever. We close for slightly longer than we open to ensure that the jaws fully close - the drive bands will slip when we get that far.

Having got the jaws snapping, we can move that into a separate script.

when snap
.set wedoConnector to 1
.repeat 3
..set wedoValue to -1
..tell wedo to "setMotorSpeed"
..wait 0.4 secs
..set wedoValue to 1
..tell wedo to "setMotorSpeed"
..wait 0.35 secs
.set wedoValue to 0
.tell wedo to "setMotorSpeed"

when start
.forever
..set wedoConnector to 2
..tell wedo to "readDistance"
..repeat until wedoValue <0.07
...tell wedo to "readDistance"
..broadcast snap and wait
..wait 0.2 secs

Then we use the distance sensor to wait until there's something to eat! The sensor is on connector 2, and we readDistance until it reads less than 8cm, at which point we fire off the snap script. You may need to tweak the timings, and range value to get everything working smoothly (so the jaws don't trigger another Snap)


It's impossible not to love this guy! Just leave him sitting on your desk, and feed him occasionally! If you've got some Wedo kicking around from working with younger year groups, then get them out, and get excited about building and programming!

Sunday, 22 February 2015

Wedo Thermostatic Fan

Now we've got a thermometer for the wedo, we can start doing some fun things!

The most obvious is a wedo thermostat which controls a fan. I quickly hooked up a couple of lego propeller blades to a medium PF motor (like the one in the standard wedo kit), and attached that to channel 2 on the wedo, and attached the wedo temperature sensor to channel 1.

Calibration is definitely a bit dodgey, but between sitting on my desk and grasping the sensor in my hand I got raw readings of between 0.6 and 0.7 (your sensor might report differently, so check for yourself).

make wedo device
make wedoConnector number
make wedoValue number

when start

.forever
..set wedoConnector to 1
..tell wedo to "readRaw"
..#say [wedoValue]
..
..set wedoValue to (wedoValue-0.6)*10
..if wedoValue <0 
...set wedoValue to 0
..if wedoValue >1 
...set wedoValue to 1
..#say [wedoValue]
..
..set wedoConnector to 2
..tell wedo to "setMotorSpeed"

..wait 0.5 secs

All we need to do is subtract 0.6 and multiply by 10 to get a value that should be between 0 and 1. Just in case it goes outside this range we check and clamp the value - otherwise the fan could start going backwards (which isn't going to warm the room up!).

Having built version 1.0, I realised it wasn't actually moving much air - everything was working as it was supposed to,  but the blades just weren't moving fast enough. On a normal project this would be a problem, but... it's LEGO! another minute rummaging through the parts bucket and I'd made a gearbox, which sped up the fan so that it was at least moving some air!





If you hold the sensor in your hand the fan speeds up (as it thinks it's hot), and if you cool it, it slows down! AWESOME!

For extra awesome you can piggyback the PF Servo on the back of the motor, connect a pointer to it, and it gives you an analog(ish) temperature readout!

Friday, 20 February 2015

Wedo Thermometer

Minecraft has been a lot of fun the last week to so, and I'll be back with more of it next week, but I thought it was time to get back to basics, play with some Lego, and do some science!

The Wedo has amazing untapped potential as a simple and convenient way of connecting computers and Lego. It's based on the Lego Power Functions system which allows it to drive motors, and lights, but it also can use special Wedo sensors. Unfortunately Lego only make two sensors: the distance sensor and the tilt sensor. While that's a great start they're really missing out on what could be an amazing science tool, if only more stuff could be hooked up easily.

Well as it turns out, it can... provided you're prepared to do a little DIY work.The wired of the Wedo cable are (from bottom to top) 0V, C1, C2, and 9V. When driving a motor C1 and C2 are used to provide power to the motor, while sensors (and the IR remote) draw power from the 0/9V lines, and signal the Wedo hub by applying a voltage to C1 and C2. The C1 wire is used to tell the software what kind of thing is attached, while the C2 line is used to provide the reading. The hub converts both voltages to a number between 0 and 255, and sends this over USB to the computer.

Sniff doesn't really use the C1 line, as it doesn't auto detect like the lego software does (though you can use the wedoScan command to read that value and check whats plugged in). If we can generate a suitable voltage and apply it to C2 we can hook anything we like to the Wedo!

One of the things I keep coming back to over and over is measuring temperature. If we could use this approach to make a Wedo thermometer we could start doing more science with lego. And it turns out to be really cheap and easy.

Ingredients:

1xLego Power Functions extension cable #8886(£2.99 from Lego)
1x10K NTC Thermister (about £1 on ebay - treat yourself to the waterproof version)
1x10K resistor (about £0.02)
1xcup of hot water (available around the home)
1xcup of ice (available around the home)
1xglass of red wine (available around the home)
A regular thermometer

Cut the power functions cable about an inch from the end THAT DOESNT PLUG INTO THE WEDO. This might be handy for something, so don't cut that end too short, but we can put the short end in the spares box for now, and keep the cable that fits the Wedo hub.

Laying it flat with the bare end of the cable to the right, solder the 10K resistor between the bottom wire (earth) and third wire (C2). Wire the Thermistor between the third wire and the 4th/top wire (9v).

Check nothing is shorting out, and plug into the wedo. It should report that nothing is connected, but it you read a value back you should see you're getting a reading that varies with temperature. I added a readRaw function to the Sniff wedo device to work with unofficial hardware, so I could write the code:

make wedo device
make wedoConnector number
make wedoValue number

when start
.forever
..set wedoConnector to 2
..tell wedo to "readRaw"
..say [wedoValue]

..wait 0.5 secs

(this won't compile in Sniff 14 - you'll need to wait for 15). Warming and cooling the device by just holding it tightly shows that the value changes with temperature.

Now drink the glass of red wine. This stage is strictly optional, but highly recommended (unless you're under 18 or live in the USA, in which case... you know... drugs are bad).

Now we need to calibrate it.


I used a ds18 thermometer connected to an Arduino and put both the new sensor and the ds18 into first ice and then a cup of hot water, recording the values on each.

0.87=50.25deg
0.5607=1.13deg

Now we just need to fit a straight line through that (these things are supposed to be pretty linear, but we'll see!).

50.25 =0.87 *m+c
1.13= 0.56*m+c

Subtract:

49.12 1=0.31*m

m=49.12/0.31

m=158.4

Substitute into either equation:

c=50.25-0.87*158.4

c=-87.56

So to convert from a reading to a temperature we multiply by 158.4 then subtract 87.6.

Just sitting on the bench I got a reading of 0.67, which would be 18.5 degrees - about right. 


The only thing left to do is revisit the coffee going cold experiment. There are a couple of versions of coffee.sniff included in the current Sniff release, and its one of the very first science experiments I did with Sniff. I hooked up a ds18 thermometer to an Arduino, attached a tft screen, and plotted a graph as the sensor recorded the temperature of my coffee as it went cold. I later repeated it with a Raspberry Pi.

I reworked the code to use the Wedo sensor, and plot the results in a window. The code is 99% the same as before.

One of the first things that becomes clear is that we're never going to get a lot of accuracy - the wedo is an 8 bit analog to digital converter, which in this case means we're going to only get readings in about 0.5 degree steps, even if our calibration is spot on.

That means we get gaps in the graph, so it doesn't look quite so pretty as the ds18. However it does show the slight curve we expect from this experiment.  We could probably tweak the components to get a slightly better accuracy, but realistically we need to treat the Wedo as what it is - a fun and easy way to hook things up and try things out - not a precision instrument. It would be perfectly good for tracking the temperature of the classroom to see show it getting hotter and colder throughout the day.

We can hook a light sensor up in pretty much the same way... More on that another time.



Wednesday, 17 September 2014

Wedo physics

I'm really excited about getting the Wedo working with Sniff - it seems to be a missing piece of the puzzle that makes it easier to get in on the fun of physical computing without having to wire stuff up, or worry about class 6B shorting out the GPIO on all your Pi's!

It's been ages since we've done any science here on the Sniff blog, so lets do some basic physics with the Wedo...

One of the really useful parts - perhaps one of the most culturally significant of its day is the discovery of the pendulum. A pendulums period depends on its length, and NOT its mass. That let people build clocks, and measure time accurately - without the pendulum there'd be not time keeping, which rules out accurate navigation (remember the original Longitude prize?), pretty much any kind of science (cause we're always measuring how long things take), no school time tables, and no iWatch. I'm sure you could integrate this into a wider cross curriculum activity about time and timekeeping, but for now lets get back to the experiment.


This is the easiest Lego build ever:At one end we've got the Wedo, and an axle. On the axle is a long brick, which is connected to other long bricks to make the arm. At the end of the arm are a couple of tires to make a weight. A little way down the arm I 've attached the wedo tilt sensor, so that its horizontal when the arm is vertical. Strictly for this to work the arm should be much lighter than the weight - we'll see how that works out...

make wedo device
make wedoConnector number

make wedoValue number
make startTime number

when start
.set wedoConnector to 1
.forever
..repeat until wedoValue=1
...tell wedo to "readTilt"
..
..repeat until not wedoValue=1
...tell wedo to "readTilt"
..
..say [timer - startTime]
..set startTime to timer

The code is equally trivial. If we ignore the timer code for now, we wait until the sensor is reading one indicating the sensor is tipped forwards, then wait until it leaves that region. At the moment the sensor stops reading 1 we print out the time since we started, then go back ground, and wait for it to happen again.

It turns out to be pretty accurate - our makeshift pendulum is accurate to within a few hundredths of a second. Using the internationally recognised standard of unit of measurement : the Lego Stud, out arm is 49studs long and has a period of 1.2 seconds (give or take about 2 hundredths of a second). 

Taking out 2 of the bars gives us a length of 27studs, and a pretty reliable period of 0.9s.

So what does the maths tell us to expect? Well assuming a "perfect" pendulum, swinging over a small angle, then:

T_0 = 2\pi\sqrt{\frac{\ell}{g}}

Where T is the time period, l is the pendulum length, and g is the gravitational force which on earth is 1226studs per second squared (you may be more familiar with the metric version of 9.81 m/s/s).

Plugging 49 studs into this equation gives 1.25s, while 27studs give 0.93s

WOW!!!!! That's pretty much spot on...

But there's another way to spin this - I knew T and l, and I looked up g (then converted it to Lego). I used that to check my experiment. My experiment was how accurate is a lego Wedo pendulum at keeping time (pretty good!).

But there's something in that equation that we actually might not have known: g. It's been pretty well measured and documented, but when did you last check?

We can rearrange that equation, and using 49studs and 1.2 seconds we get g=1343studs/s/s  (or 10.7m/s/s). That's about a 10% error, which considering the pendulum equation is only an approximation, and we build it out of Lego, that's pretty amazing.

WE JUST MEASURED GRAVITY WITH LEGO!