Sunday 19 November 2017

Micro:bit Robot Arm

In this post, I am discussing using a recently bought  CBIS BBC micro:bit RobotArm, but play with it using Python (or rather micropython).




Set Up
Not a lot to set up really. The base and the arm are separate and are attached with four screws (so you will need a screwdriver). 

The most difficult bit is the wiring the arm to the circuit/breakout board on the base, but instructions are available through CBiS Resource portal http://portal.cbis.education/teacher/hardware. You will need a log-in for this. Also on that site, there is an example Microsoft Blocks code which includes some instructions on inserting the microbit as well - the micro:bit goes in buttons side facing upwards.


Code
Taking the values from the instruction sheet for setting it - the micro:bit key bit - the following pins were selected.
Base                     Pins 0 and 1
Shoulder               Pins 8 and 12
Elbow                   Pins 2 and 13
Wrist                    Pins 14 and 15
Gripper                 Pins 16 and 11 - this is the only one I haven't got working yet.

So to test it out, a simple bit of code to drive each motor in both directions was produced and is shown below.



This is good fun to play with. The use of the micro:bit is a good idea because it's ease of use to plug-in and play with.

All opinions in this blog are the Author's and should not in any way be seen as reflecting the views of any organisation the Author has any association with. Twitter @scottturneruon

Monday 30 October 2017

Crumble based Junk-Eggbot

Full details at http://bit.ly/2yZ3dZT



There was three inspirations for this project
·   Femi Owolade supported by Nic Hughes ran a session at Mozilla Festival 2016 using the Crumble’s to make a wheeled robot.
·   The junkbot project https://junkbots.blogspot.co.uk/
Kit
·      Kinder Egg (without the Chocolate and toy)
·      Battery pack and 3xAA
·      Vibrating motor
·      Tape (lots of)
. Sticky-tack of some form.
·      Pens
·      Paper
·      Scissors
·      Glue and Gluegun (optional)


Stage 1: Fix the vibrating motor into the Egg.
Stick (sticky-tack is a good temporary method) the vibrating motor into the Egg with the motor electrical connections sticking out the bottom larger half of the egg. Make sure the unbalanced load is free to move – this is bit that causes the vibrations needed to move the egg.
IMG_0578.JPG


Stage 2: Sticking the pens on.
This is the trickiest bit. Tape the pens on the egg. One suggestion that someone who tried it out suggested, was to use little bits of sticky-tack to position the pens on the egg before tapping the pens onto the egg.

IMG_0579.JPG
If you are using three pens, the third pen should be placed so that all three form a triangle with equal sides, that means the egg can stand-up on a piece of paper on the pen nibs, without anything supporting it.
If you are using four pens, the other two pens should be placed so that all four form a square with equal sides, that means the egg can stand-up on a piece of paper on the pen nibs, without anything supporting it.
Stage 3: Add the battery pack and go.
Using two wires connecting the battery, to the motors. Remove the nibs and set the bot off. It is hopefully vibrating and shaking and scribbling lines on the paper.
IMG_0580.JPG IMG_0582.JPG


To see one in action go to: https://www.youtube.com/watch?v=NRlntdmdQRo


Stage 4: Crumble Controlling
Disconnect the battery connection (the connections on the motor can stay as they are) from the junkbot. Connect the USB cable to the Crumble. To the right of the USB connect there are two connections marked + and -. Connect one wire to the + connection and the other end to the red wire of the battery pack. Connect a one wire to the – connection and the other end to the black wire of the battery pack.
IMG_0583.JPG IMG_0584.JPG
Stage 5: Connect the Egg!
On the Crumble, on the right-side there are two motor connections connect the Motor to these connections. Don’t worry about which of the motors wires is need you swap them around later.


IMG_0585.JPG
Stage 6: Programming it – Making the bot moves.
The software can be found at https://redfernelectronics.co.uk/crumble-software/ it includes how to set it up on your own machine.
Start the Crumble software. Drag from the left the Program start, motor, and wait blocks. Now join the up start block at the top and the motor block next and the wait block last.
Screen Shot 2017-10-23 at 16.23.51.png
Your code should look like this.
Screen Shot 2017-10-23 at 16.23.43.png


Click on the stop within the motor block. It should change to forward. Now you are ready to make it move. Press the green arrow and with the battery pack on, it should (hopefully) keep moving.
Screen Shot 2017-10-23 at 16.24.12.png
If you put a second motor block after the wait block with the stop in the block. It such then stop after 1 second of moving.
Stage 7: Making it do more.
-    Drag a do-until block in (found in the control menu).
-    Go to variable menu and add a new variable, I have used t, select the block marked let=, and drag a t into the blank space.
-    Drag an increase block onto the screen and drag a t into the blank space.
Screen Shot 2017-10-23 at 16.27.45.png
Go to the operator menu and drag onto the screen an = block, go back to variables menu and drag a t into the first space on the = block and click on the second space on the block and type in 5.
Screen Shot 2017-10-23 at 16.29.02.png
Now for the challenge put all these together to copy what is shown below. Now, but the egg-bot on the paper, with the pen lids off, press the green triangle and the motors should be spun in different directions.
This is a junkbot so it may just cause the bot to move a slightly different directions but hopefully it should just draw some squiggly lines.


© Scott Turner
Attribution-ShareAlike
CC BY-SA






All opinions in this blog are the Author's and should not in any way be seen as reflecting the views of any organisation the Author has any association with. Twitter @scottturneruon

Monday 9 October 2017

Sphero Mini - fun-sized Sphero


The Sphero Mini has been recently launched and at the time of writing seems to be popular, Amazon.co.uk delivery times vary depending on the colour you select. There are some very good reasons for it to be popular.


It's a ping-pong sized ball, much smaller than the normal Sphero's and approximately half the price. Though slightly less featured, what it has got, is good. 

In the box, you get the sphero-mini, a charging cable, as well as packet of mini-skittles and cones. There is no charging station for this one, you charge it taking the outer shell off (it splits into two pieces) and the socket is on the ball inside. Actually, it is quite interesting to see the insides (I know the Spheros SPRK+ have a transparent shell to show the innards) and handle the ball inside, trying to see what it does. The ball is a little slower than the other Spheros, but this is not a problem in my opinion.



There is an app for playing the games, and this is fun to play with; providing control via the app to make the ball move and many features I have yet to explore. Alternatively, the SpheroEdu app, running on a tablet, allows programming via blocks or JavaScript. Had to have a go with writing a JavaScript routine.




The routine just makes the robot go in a square and not really much of a test, but a start. I especially liked the visual display of the sphero-mini's route on the tablet's screen.

I think this little robot, the price is not bad, though less featured than their bigger 'sibling' Spheros it is still good. I would like to see support for Swift in the future but it is early days for this kit and the skittles and cones are a good touch.


All opinions in this blog are the Author's and should not in any way be seen as reflecting the views of any organisation the Author has any association with. Twitter @scottturneruon

Sunday 3 September 2017

LittleBits Star Wars Droid and Swift Playgrounds

On the 1st September 2017, during 'Force Friday', LittleBits launched their new kit Star Wars Droid Inventor Kit an R2D2 shaped robot, though you are encouraged to customise it to form your own designs. It comes a number of tutorials, that take you through building a moving head, a proximity sensor to move away from you, and many others.


So confession time, I am not the target audience for this kit, but I have enjoyed playing with it. The tutorials take you through building and dismantling the kit, doing a range of different activities and in most cases controlling it remotely from an iPad. You can even record your voice and have it played back from the Droid, in my opinion, the wide of sounds is one of the things that lift this from being just a nice kit -  I will get onto the other one soon. Though good fun, I was left with a question can it be programmed?

This was my first time using a LittleBits kit I didn't know what the options were available for programming it, a quick search around online was not initially that helpful it looked like this was not an obvious way forward. 

Now for the good news on the LittleBit site there is a relatively easy solution to this see https://littlebits.cc/littlebits-droid-inventor-kit-swift-playgrounds on an iPad. Swift Playgrounds can be used to program it, you need to download the separate playground after the Swift Playgrounds App (if you haven't already got it) is installed, After that it is follow the tutorials.


 Below is an example part of the code, I tried to make the Droid dance and makes some noises.

Below the video of the code in action.



The combination of Swift Playgrounds and Star Wars Droid Inventor Kit works well, perhaps you can't go wrong with R2D2. I would suggest the text from the website about linking to Swift Playgrounds should be included with the box and it would be nice to see some more commands. Apart from these very minor criticisms the kit and Swift Playgrounds is a nice combination (and the kit even comes with battery included), well worth a look and extending it to a wider age range. 


All opinions in this blog are the Author's and should not in any way be seen as reflecting the views of any organisation the Author has any association with. Twitter @scottturneruon

Wednesday 30 August 2017

Robots, fruit and computer coding

Taken from: https://www.northampton.ac.uk/news/robots-fruit-and-computer-coding-sixth-formers-get-a-taste-of-university-research/ by University of Northampton Press Team

A select group of sixth-form pupils has spent the summer working on a series of research projects at the University of Northampton.
Four pupils from Northampton and Kettering schools undertook projects involving robotics, coding and urban orchards after each were awarded a Nuffield Research Placement – a scheme which offers sixth formers the chance to work on university research projects.
David Obreja, from Northampton School for Boys, spent his time at the University researching the amount of fruit-bearing plants and trees in areas of Northampton, and mapping them on a computer.
He said: “We need more fruit-bearing plants and trees in the town to provide food for wildlife, encourage biodiversity and improve the aesthetics of urban areas. I hope my research might encourage residents to plant more species, which would also have a social benefit as people may take it up as a hobby. Growing their own produce will also increase their food security.
“The research might also inspire housing developers to consider the mix of planting on their new developments, by including more fruit-bearing plants, rather than planting that is purely architectural.”
Fellow Northampton School for Boys pupil, Nathaniel Roberts, spent his time at the University making a junkbot – a robot made from waste items, such as a drinks can, powered by a kit.
He then coded the junkbot to make it move and used his experiences to produce an instruction manual for junkbot beginners.
Nathaniel said: “The project has taught me how to manage myself, set aims and work towards completing them, and given me an insight into how to write a technical manual in language that’s informative and easy to understand.”
Michael Welsh, from Kettering Buccleuch Academy, spent the summer programming a robot to learn how to follow a straight line, using sensors.
He said: “It works as a concept, but pretty difficult to get it right in practice, and has meant lots of methodical research. I’d like a career in computer science and this project has been pretty intense and demonstrated things can be a lot more work than you initially assume, but I like a challenge.”
Hiren Mistry, from Caroline Chisholm School in Northampton, learnt how to program a robot before creating a set of tasks for Year 7 pupils to do the same.
He said: “It’s been fairly tricky, with a lot of research and testing, and has given me a real insight into computer science.”
The University’s Associate Professor in Computing and Immersive Technologies, Dr Scott Turner, said: “The Nuffield placements have been incredibly successful. The students were all set very challenging university level projects and have enjoyed a real taste of the work we do here.
“I was very impressed with their commitment and aptitude for their subjects and am sure they will all go on to be a success at university, should they choose to go down that route.”


Related Links to their work.




All opinions in this blog are the Author's and should not in any way be seen as reflecting the views of any organisation the Author has any association with. Twitter @scottturneruon

Thursday 24 August 2017

Robot control by a neuron.

This year the Computing team has been fortunate enough to host three Nuffield Research Placement students (https://www.nuffieldresearchplacements.org/) all working with Dr Scott Turner.


Michael Welsh
Michael has been working on using a micro:bit based bitbot from 4tronix to produce a potential teaching tool; an example of artificial neurons used control a robot. The aim is for this tool to be used with 3rd-year Undergraduates, as part of a module on Artificial Intelligence.

Michael's solution was to use the computer to run and train a single neuron; then for the robot to send values from the line sensors back to the program running on a Computer and receive control signals. 

Sounds easy? No really, in the end, the software running on the computer had to also send and receive the data through a microbit (via USB) and then use radio to communicate with the bit:bot robot. All the various developed parts of the solution were implemented in Python by Michael.




Example of the code.

import serial
from math import fabs
import random
import sys
import glob


#TO DO: GUI, implement manual mode. Make manual mode a button?? When in automatic, weight boxes are greyed out. Otherwise, they are able to be typed into.

def forward(n):
    microbit.write(('f'+str(n)).encode('utf-8'))
def backward(n):
    microbit.write(('b'+str(n)).encode('utf-8'))
def turnR(n):
    microbit.write(('r'+str(n)).encode('utf-8'))
def turnL(n):
    microbit.write(('l'+str(n)).encode('utf-8'))
def end():
    microbit.write('e'.encode('utf-8'))


def serial_ports():
    """ Lists serial port names

        :raises EnvironmentError:
            On unsupported or unknown platforms
        :returns:
            A list of the serial ports available on the system
    """
    if sys.platform.startswith('win'):
        ports = ['COM%s' % (i + 1) for i in range(256)]
    elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
        # this excludes your current terminal "/dev/tty"
        ports = glob.glob('/dev/tty[A-Za-z]*')
    elif sys.platform.startswith('darwin'):
        ports = glob.glob('/dev/cu.*')
    else:
        raise EnvironmentError('Unsupported platform')

    result = []
    for port in ports:
        try:
            s = serial.Serial(port)
            s.close()
            if '/dev/cu' in port:
                if '/dev/cu.usbmodem' in port:
                    result.append(port)
            else:
                result.append(port)
        except (OSError, serial.SerialException):
            pass
    return result


class neuron:

    def __init__(self,ins):

        self.inputs = [1]

        self.weights = []

        for i in range(ins+1):
            self.weights.append(random.uniform(-1,1))
        #print(self.weights)

        self.LC = 0.005
        
    def get_output(self,inputs):
        self.inputs = [1]+inputs

        WSum = 0

        for i in range(len(self.inputs)):
            WSum += int(self.inputs[i]) * self.weights[i]

        sums = sorted([fabs(WSum), fabs(WSum - (1/3)), fabs(WSum-(2/3)), fabs(WSum-1)])
        #print(sums)
        if sums[0] == fabs(WSum): #return 0 - move backwards
            backward(5)
            return 'B',WSum
        elif sums[0] == fabs(WSum - (1/3)):
            turnR(5)
            return 'R', WSum
        elif sums[0] == fabs(WSum - (2/3)):
            turnL(5)
            return 'L', WSum
        else:
            forward(20)
            return 'F', WSum

    def train(self,inputs,desired):

        result = self.get_output(inputs)[1]
        print(result)
        error = desired - result
        #print(error)

        for w in range(len(self.weights)):

            change = self.LC * int(self.inputs[w]) * error

            print('change in weight ' + str(w) + ': ' + str(change))

            self.weights[w] += change


for i in serial_ports():
    try:
        microbit = serial.Serial(port=i, baudrate=115200)
        break
    except:
        pass

microbit.setDTR(1)
microbit.close()
microbit.open()

control = neuron(2)

mode = input('Automatic or Manual? (A/M)\n')
while mode.lower() not in ['a','m']:
    mode = input('Automatic or Manual? (A/M)\n')
if mode == 'm':
    control.weights[0],control.weights[1],control.weights[2] = int(input('Enter weight 0/bias: ')),int(input('Enter weight 1: ')), int(input('Enter weight 2: '))
while True:
    #microbit.write(input('input: ').encode('utf-8'))
    out = microbit.read(6)
    microbit.flush()
    try:
        out = out.decode()
    except:
        pass
    for i in range(len(out)):
        if str(out[i]) in ['0','1']:
            if i == 0:
                if out[1] == ']':
                    num2 = out[i]
                elif out[1] == ',':
                    num1 = out[i]
            elif i == 5:
                if out[4] == '[':
                    num1 = out[i]
                elif out[4] == ' ':
                    num2 = out[i]
            else:
                if out[i-1] == '[':
                    num1 = out[i]
                elif out[i-1] == ' ':
                    num2 = out[i]
                elif out[i+1] == ']':
                    num2 = out[i]
                elif out[i+1] == ',':
                    num1 = out[i]
        
        #print(out)
    try:
        sleft=int(num1)
        sright=int(num2)
        print([sleft, sright])
        if mode == 'a':
            if [sleft, sright] == [0, 0]:
                control.train([sleft,sright],0)
            elif [sleft, sright] == [0, 1]:
                control.train([sleft,sright], 1/3)
            elif [sleft,sright] == [1, 0]:
                control.train([sleft,sright], 2/3)
            else:
                control.train([sleft,sright], 1)
        else:
            if [sleft, sright] == [0, 0]:
                control.get_output([sleft,sright])
            elif [sleft, sright] == [0, 1]:
                control.get_output([sleft,sright])
            elif [sleft,sright] == [1, 0]:
                control.get_output([sleft,sright])
            else:
                control.get_output([sleft,sright])
    except:
        pass


All opinions in this blog are the Author's and should not in any way be seen as reflecting the views of any organisation the Author has any association with. Twitter @scottturneruon

ChatGPT, Data Scientist - fitting it a bit

This is a second post about using ChatGPT to do some data analysis. In the first looked at using it to some basic statistics  https://robots...