Showing posts with label RaspberryPi. Show all posts
Showing posts with label RaspberryPi. Show all posts

Thursday, 12 March 2020

PiWars 2020: Collision warning!

A major cause of the disasters that International Rescue get called out to are caused by collisions. Whether its a fuel tanker hitting a rock slide, or an experimental jet crashing into the ground, it usually results in a large explosion (regardless of how explosive the objects involved actually are). So when running autonomously how do we avoid Thunderbird 2 running into things? (Obviously in a manually controlled environment nothing is going to stop us crashing !).
Boom!
The answer is to add sensors that are capable of detecting how close it is to an object. Generally these are referred to as 'distance sensors', which come in a variety of form factors and types, and tend to work by 'firing' something outwards, waiting for it to bounce off a surface, return to the sensor and then measuring the travel time to determine how far away it is. This process is similar to working out how far away an object is by making a loud sound and listening for the echo.

Popular choices are ultrasonic sensors, which uses sound waves to determine distance, Time-of-Flight sensors, which use lasers, and some camera based systems (which use magic... or possibly maths).

Sensors!

My requirements for Thunderbird 2 are that the distance sensors are small enough to be hidden behind the 'air intakes' for the jet engines, and that multiple sensors can be used at the same time. This rules out the ultra sonic sensors, as the sound waves they fire out could get picked up by multiple sensors, giving an invalid reading, as well as the camera based systems. Instead I'll be using several VL53L1X Time-of-Flight sensors.

There are a number of different models of the VL53L1X sensors, all built around the same core module, and which one you select depends on your requirements. In this case I wanted a module that had a small physical size, and exposed all the control pins.

The VL53L1X  sensor communicate via I2C. This is a protocol that allows multiple devices to be connected to the same physical bus (i.e. The communication pins are all connected together), which greatly simplifies the wiring as it allows you to chain multiple I2C devices together instead of needing each one to be directly connected to the Raspberry Pi.

All connected to the same I2C bus.

To talk to an I2C device you need to know its address, similar to how you specify a house on a street by its number. According to the VL53L1X  datasheet its default address is 0x52 (82 in decimal), which we use to make sure our post (the commands) reach the correct house.

Unfortunately if all the sensors share the same I2C address then the postman is going to get very confused about where these messages should be delivered to. Luckily this particular sensor allows its I2C address to be changed, by sending a command. This could be considered a bit of a chicken or the egg issue, how do you tell a sensor to changes its address when you can't send a message until the addresses have been changed?

Luckily the designers of the VL53L1X  sensor did consider this and provide an extra PIN, called XSHUT, that can be connected to a GPIO which turns on or off the sensor. Allowing us to turn on one at a time, reconfigure it,s address and move to the next. Now not all ToF sensor models expose this PIN, so this is another item we need to check for,

After a bit of searching around, and measuring of space, I found one produced by Pololu that looked like it would meet all the criteria. Purchasing one to double check the fit, always a sensible idea before you commit, before getting all 4.
It fits!
I initially connected the sensors via jumpers leads, but quickly decided this was too bulky and inflexible to fit inside the case, especially as I had four to connect up! Taking advantage of the ability to chain I2C devices I switched to ribbon cable, a thinner and more flexible cable, along with some 1x7 connectors. This worked at first, but when I came to chain two I managed to get the cable a little twisted, mis-wired the connector, and managed to produce a 'burning' smell from a sensor... Ooops!
To avoid this in future I purchased some multi coloured ribbon cable, making it much easier to work out where each cable goes (Even later on I found the roll of rainbow colour ribbon cable I'd bought a year or two earlier...
Two sensors in a nice, neat, rainbow coloured line.
Repeating the setup on the other side I know have a full set of four sensors, two pointing forwards and one pointing to either side. This allows Thunderbird 2 to detect walls in front, and either side, in theory allowing it to safely navigate through the maze and the lava palava course.

Now all it needs is someway of actually moving! Which I plan on covering next time!

Leo

Thursday, 20 February 2020

PiWars 2020: Brains

Mr X and Mr Hackenbacker
With the chassis cut to size its time to start thinking about brains. No, neither Mr X. or Mr Hackenbacker, nor the type of brains that the targets in the Zombie Apocalypse challenge would be interested in snacking on.  

Instead the brains of a PiWars robot has to be a Raspberry Pi, and in this case a Raspberry Pi 3A. Its combination of smaller size, whilst maintaining the power of its full sized brethren, makes it a go-to solution for many of the PiWars competitors.

Why not a shiny new Raspberry Pi 4 I hear you ask? Well for one a full sized Raspberry Pi takes up too much space in the cockpit, it would fit but then the battery wouldn't. Its also unlikely that any processing I need to do for the challenges would noticeably benefit from the increased performance, whereas the increased power draw, and heat produced, could have a detrimental affect on the robot. The additional i2c buses might be of use, but unless a 4A is suddenly announced I'll be sticking with the 3A.
Too big on the left, fits on the right (Battery hidden out of sight)
Now a brain is of limited use without inputs to process and outputs to control. For the manual challenges the input will be a Bluetooth connected PS4 controller, an upgrade for this year as my, more traditional, PS3 controllers are starting to show their age with the joysticks being a little unreliable.

For the autonomous challenges the main inputs will be a Raspberry Pi camera, and a set of 4 VL53L1X Time of Flight (ToF) sensors positioned around Thunderbird 2. The camera, when combined with opencv, will be used to take pictures and perform either object, or more simply, colour recognition to aid in navigation. The ToF sensors, which work by firing lasers, will be used to detect how close Thunderbird 2 is to a wall or object.

RPi Camera and ToF sensor 
The camera will be positioned above the cockpit so it can look ahead, but might get moved to more suitable locations as required for the various challenges. The ToF sensors will be aimed forwards and to the sides, which I'm hoping will help in navigating the 'Escape route' and 'Lava Palava' courses, allowing Thunderbird 2 to maintain a set distance away from a wall, and to detect when its about to drive into one.

The obvious output will be the motors that drive Thunderbird 2 around, with the less obvious being the gun for Zombie Apocalypse and, if I manage to get to it in time, a mechanism for capturing barrels in 'Eco Disaster'. I also hope to have an actual GUI this year that will be displayed on a wrist mounted Raspberry Pi (Fitting in with the newer 'Thunderbirds Are Go' way of remotely controlling one of the Thunderbirds).
Motors!
Connecting everything up is liable to be a python program or two, hopefully reusing some of last year's code, but most likely a whole bunch of new stuff. I'm currently feeling drawn to having dedicated python processes to monitor different aspects, say a dedicated process for dealing with the ToF sensors, feeding the results to the main controlling application that then decides if its interested in the information or not.

Of course I'll be going into more detail on these items in future blog postings, unless I completely run out of time and abandon them!

Leo

Thursday, 23 January 2020

PiWars 2020: Making the cut

Before I can best plan out how to convert the Thunderbird 2 toy into a successful PiWars competing robot I need to open it up and see what I'm working with. Happily the toy opens up quite nicely, just a case of removing every screw you can see on the underside of the chassis and popping the two halves apart. Most of the internal items also unscrew easily with the notable exception of the tail. Whilst it looks to just be held in place by 2 screws either side, it appears that the manufacturer also glued it into place for extra strength, and by the time I realised this I'd snapped off one of the supports...

Opening up the chassis
The pod themselves open up nicely too, just remove a couple of screws and pop it apart. Remove a few more screws and the launching mechanism for Thunderbird 4 comes out as well.
And opening up a Pod.

In terms of usable space the main two areas of interest are the inside of the cockpit and pod. These can both house a full size Raspberry Pi, barely in the case of the cockpit, and with room to spare in the pod. As my plans are to swap out the pods for different challenges this means the controlling Raspberry Pi must be housed in the cockpit (to comply with the rules of PiWars), leaving the Pod to house the motors and any additional hardware required to complete the challenges.
Tight squeeze on the left, roomy on the right.
With the toy opened up what's the next step? Well, those who read through my PiWars application details in the last posting may have spotted the line at the end stating that the Thunderbird 2 model is too long and needs cutting down to size...
So the length limit is 300mm...
Last year, in PiWars 2019, I made an effort to keep Wall-E looking like the original toy, which turned out to be a challenging task, but at the end I was happy with my decision (Apart from maybe the gear box failures!). With Thunderbird 2 that just isn't going to be an option, so with the cockpit ear marked for holding a Raspberry Pi then its the tail that will have to be chopped off. I had hoped to keep the battery compartment, which is towards the rear, but the vast majority of that also fell outside the 300mm length limit.

Big and cutty
But how to remove it? As I have recently started attending a MakerLab, I've gained access to a variety of big cutting tools  and I decided to give one of those a go. After all a mains powered, table mounted bandsaw thingie should have no trouble cutting through toy grade plastic...
Well technically it had little trouble cutting through Thunderbird 2, however it generated so much heat that the plastic melted back together again afterwards! Requiring a bit of wiggling and hacking at until the tail could be broken away, plus a bunch of post processing to tidy up the cut.
Transitioning from scruffy to nice and smooth.
The tail section has quite a lot of weight to it, so now its been removed Thunderbird 2 gets a little front heavy, and will get even more so when the battery and Raspberry Pi are installed. So the plan is to install counter weights to balance things out. Where I can I hope to reconnect the tail section as an 'attachment' for some of the challenges, and Mike has helpfully confirmed its okay for the attachment section to be on the back. Hopefully a few magnets will be strong enough to hold it in place, whilst also allowing for easy removal. However this isn't strictly necessary and will be in the 'nice to have' list of features.
Thunderbird 2 - Compact edition
With the chassis cut down to size the next step will be installing the brains!

Leo

Tuesday, 14 January 2020

PiWars 2020 : Calling International Rescue!

Wall-E from PiWars 2019
Its a New Year and a new PiWars. PiWars 2020 is coming in March and once again I've managed to get selected as a competitor! After the success of last years' Space themed event (My entry being the lovable robot Wall-E) Mike and Tim decided to repeat it for 2020, this time going for a 'disaster' theme, either natural or man-made, with a leaning towards disaster related movies.

I can come up with a lot of ideas for disaster themed robots, one with a volcano on it, or a bursting dam (pumping water back behind the dam so it can burst again), or just an alien robot come down to Earth to destroy and invade.

All fun projects, but there was a toy conversion I've had on the back burner for a while and this seemed an appropriate time to use it. After checking that 'rescue' themed robots were included in the 'disaster' category I submitted my application for Thunderbird 2. After all, where there's a disaster International Rescue won't be far behind!

Thunderbird 2!

As this is the 5th time I've entered PIWars you'd think I'd have a good handle on what to do. However, in reality, I'm still making a lot of this stuff up as I go along. But.... as long as I write down my ideas it becomes 'planning' which is a much more responsible sounding word.

So what sort of ideas did I write down? Mmmm rather a lot!  Here's a copy of my application (Might also be of interest to anyone wondering what to put in a future Pi Wars application)

Robot will be built around the Thunderbird 2 Supersize toy (From 2015).

The main chassis will contain a RPi 3A+ as the main controller, as well as a battery, camera and multiple ToF sensors (One under each air intake on the front, plus one on either side). Other sensors/components may be added as the build progresses..

Actual propulsion will be contained inside the Pod (As this is the only section that touches the ground) and it is planned that the Pod will be swapped out for the various challenges. Initially the RPi 3A+ will be connected physically to the motor driver inside the Pod (e.g. via i2c), but if development goes well this will change to a wireless communication (NFC, bluetooth, WiFi, something else?). Ideally I’d want to get to the point where the Pod can just be swapped out, the RPi 3A+ automatically detects this (via NFC) and the software updates as appropriate.


Current plans for Pods are

Pod 1: This will be the standard Pod that will be used in the majority of challenges. Current plan is that it’ll contain a twin set of tracks, that come through the floor of the pod, which also includes some limited vertical movement. So for the obstacle course the ‘bottom’ of TB2 can be raised by 1 or 2 cms to clear obstacles, ramps etc. It may also contain a line following sensor for the ‘Lava palaver’ challenge, if that doesn’t end up being carried in the main chassis.

Pod 2: This pod will be targeted at the ‘Zombie Apocalypse’ challenge. It will have a much simpler motor mechanism to free up space inside the pod (prob. Just a couple of wheels to allow movement over flat terrain). This extra space will be used to house a rotating turret to fire foam darts at the targets. Expectations are that this will rotate left and right to allow more precise targeting, compared to moving the entire robot, as well as some limited up and down movement to fire up and down. A laser will be installed to improve aiming.

Pod 3: This pod will be targeted at the ‘Eco-Disaster’ challenge. Again this will have a simpler motor mechanism, probably a match for Pod 2, but this time the space will contain a gripper arm that will be deployed out the front of the Pod (The main TB2 chassis will be raised to accommodate this). This will have to be fairly long, as TB2’s nose can’t clear the barrel height, and will be used to grip and capture the barrels. Holding them in place as they are delivered to the target areas. Expectation is to use an IR beam, or physical button, in the gripper to detect when it should close. As well as a second camera that will be used to verify the colour of the barrel (This will be streamed to the RPI 3A+ over WiFi for processing).

If time permits, and it turns out to be practical, a mask will come out the top of the Pod and hold a third camera that points downwards (With a wide lens) to better detect barrels in all directions, instead of having to rotate around until one crosses the LoS of the front mounted camera (Or this may end up coming out of the top of the TB2 cockpit for ease of connecting up)

This camera mask mechanism may also be used for the ’Minesweeper’ challenge, to detect which square is lit up.

Control will be done via a simple UI accessed via VNC or web page from a wrist mounted device (vaguely matching how remote control of TB2 is done in the newer ‘Thunderbirds Are Go’ series). This is liable to be another RPi with a touch screen display.

Note: As the TB2 model is too long, the engines and tail have been cut off to meet the max length in the rules. Outside of the challenges this will prob. Be attached via magnets for appearances sake.

Will I complete all these tasks? Well I've never managed it before! But only time will tell...

 Leo

Wednesday, 7 June 2017

Basic Bluetooth Network using Raspbian Jessie

Recently I wanted to setup a Bluetooth network to allow several Raspberry Pis to communicate amongst themselves and, as I'd not done this before, tried to search for articles on how to achieve this. I managed to find many, many articles covering this subject, unfortunately they tended to be either out of date (e.g. using Raspbian Wheezy + BlueZ 4.x), incomplete (starting from X do Y, without explaining how to achieve X) or just plain confusing.

After some further research, plus plenty of trial and error, I eventually got a bluetooth network up and running, connecting together one Raspberry Pi 3 with four Raspberry Pi Zero Ws, and decided to document the steps I took for my own reference, as well as for anyone else who would like to achieve the same.

To setup the Bluetooth network we need to allocate one Raspberry Pi to act as the central hub, responsible for allocating IP addresses, IP forwarding (if needed), along with one or more client Raspberry Pis to connect to it.

Setting up the Hub

  • Download the latest Raspbian image (Here I am using 2017-04-10-raspbian-jessie-lite.zip) and write to an SD Card.
  • Boot the Raspberry Pi, login and run the 'raspi-config' application.
pi@raspberrypi:~$ sudo raspi-config
  • Select option 2 to change the hostname, setting it to 'hub'.
  • Select 'Finish', followed by 'Yes' to reboot.
  • Wait for the Raspberry Pi to reboot and log in again.
  • Setup a network connection. Depending on your setup this can be either by plugging in an Ethernet cable or by setting up a Wireless connection.
  • Install the packages required for setting up the bluetooth network.
pi@hub:~$ sudo apt-get install bluez-test-scripts bridge-utils dnsmasq python-dbus
  • Next we need to add the network interface we'll be using for Bluetooth. Edit the /etc/network/interfaces file and add the following to it.
auto pan0
 iface pan0 inet static
         address 172.168.10.1
         netmask 255.255.255.0
         bridge-ports none
         bridge-fd 0
  • And then we need to configure dnsmasq to listen on the pan0 interface and assign IP addresses in the correct range. Edit the /etc/dnsmasq.conf file and add the following
domain-needed
 bogus-priv
 no-resolv
 no-poll
 server=8.8.8.8
 local=/localnet/
 interface=pan0
 no-hosts
 expand-hosts
 domain=local
 # Enable DHCP for the 172.168.200.X range
 dhcp-range=172.168.10.10,172.168.10.50,12h
  • To setup the bluetooth network we'll be using one of the BlueZ test scripts (installed as part of the bluez-test-scripts package earlier), however the test script exits after 16 minutes, so we need to copy and edit the script.
pi@hub:~$ sudo cp /usr/share/doc/bluez-test-scripts/examples/bluezutils.py /usr/local/sbin/
pi@hub:~$ sudo cp /usr/share/doc/bluez-test-scripts/examples/test-nap /usr/local/sbin/
pi@hub:~$ sudo chmod +x  /usr/local/sbin/test-nap
  • To keep the script running edit /usr/local/sbin/test-nap and change the lines :-
try:
        time.sleep(1000)
  • to
try:
        while True:
            time.sleep(1000)
  • We want the script to run at startup and one of the easiest ways is using the crontab file. Edit your crontab by running crontab -e and add the following line to the end.
@reboot sudo nohup /usr/local/sbin/test-nap pan0  &
  • Reboot once more (sudo reboot), log in and check that the pan0 interface exists, and the test-nap script is running.

pi@hub:~$ ifconfig pan0
pan0      Link encap:Ethernet  HWaddr da:87:54:2c:f8:66
          inet addr:172.168.10.1  Bcast:172.168.10.255  Mask:255.255.255.0
          inet6 addr: fe80::d887:54ff:fe2c:f866/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:60 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:9090 (8.8 KiB)

pi@hub:~$ ps ax | grep test-nap
   438 ?        S      0:00 sudo nohup /usr/local/sbin/test-nap pan0
   470 ?        S      0:00 /usr/bin/python /usr/local/sbin/test-nap pan0
   851 ttyS0    S+     0:00 grep --color=auto test-nap
  • If everything is running as expected we just need to take a note of the Bluetooth MAC so we can tell the clients who they need to contact. We can find this by running 'hciconfig dev'.

pi@hub:~$ hciconfig dev
hci0:   Type: BR/EDR  Bus: UART
        BD Address: B8:27:EB:25:A0:AE  ACL MTU: 1021:8  SCO MTU: 64:1
        UP RUNNING
        RX bytes:731 acl:0 sco:0 events:44 errors:0
        TX bytes:1784 acl:0 sco:0 commands:44 errors:0

Setting up a client

  • Download the latest Raspbian image (Here I am using 2017-04-10-raspbian-jessie-lite.zip) and write to an SD Card.
  • Boot the Raspberry Pi, login and run the 'raspi-config' application.
pi@raspberrypi:~$ sudo raspi-config
  • Select option 2 to change the hostname, change it to 'client0'.
  • Select 'Finish', followed by 'Yes' to reboot.
  • Wait for the Raspberry to reboot and log in again.
  • Setup a network connection. Depending on your setup this can be either by plugging in an Ethernet cable or by setting up a Wireless connection.
  • Install the packages required for setting up the bluetooth network.
pi@client0: sudo apt-get install python-dbus
  • Download a helper script for establishing the bluetooth network.
pi@client0:~ $ wget https://raw.githubusercontent.com/mk-fg/fgtk/master/bt-pan
pi@client0:~ $ sudo mv bt-pan /usr/local/sbin/
pi@client0:~ $ sudo chmod +x /usr/local/sbin/bt-pan
  • Again we want to run this script at startup, so run crontab -e and add the following, replacing the MAC Address with that of your bluetooth dongle.
@reboot sudo noup /usr/local/sbin/bt-pan client B8:27:EB:25:A0:AE &

Pair client to hub

Before the network can be established a bluetooth connection first needs to be setup between the client device and the hub. This is achieved by making use of the 'bluetoothctl' application.
  • First setup the client so it can be discovered by running the commands in bold below.
pi@client0:~ $ sudo bluetoothctl

[NEW] Controller B8:27:EB:5B:CB:74 client0 [default]
[bluetooth]# power on
Changing power on succeeded
[bluetooth]# discoverable on
Changing discoverable on succeeded
[CHG] Controller B8:27:EB:5B:CB:74 Discoverable: yes
  • Then scan for, and connect to it, from the hub (again using the commands in bold). Once its found we want to pair and trust the client to allow it to auto connect in future,

pi@hub:~$ sudo bluetoothctl
[NEW] Controller B8:27:EB:25:A0:AE hub [default]
[bluetooth]# power on
Changing power on succeeded
[bluetooth]# agent on
Agent registered
[bluetooth]# scan on
Discovery started
[CHG] Controller B8:27:EB:25:A0:AE Discovering: yes
[NEW] Device B8:27:EB:5B:CB:74 client0
[bluetooth]# pair B8:27:EB:5B:CB:74
Attempting to pair with B8:27:EB:5B:CB:74
[CHG] Device B8:27:EB:5B:CB:74 Connected: yes
[CHG] Device B8:27:EB:5B:CB:74 UUIDs:
        0000110c-0000-1000-8000-00805f9b34fb
        0000110e-0000-1000-8000-00805f9b34fb
        00001200-0000-1000-8000-00805f9b34fb
        00001800-0000-1000-8000-00805f9b34fb
        00001801-0000-1000-8000-00805f9b34fb
[CHG] Device B8:27:EB:5B:CB:74 Paired: yes
Pairing successful
[bluetooth]# trust B8:27:EB:5B:CB:74
[CHG] Device B8:27:EB:5B:CB:74 Trusted: yes
Changing B8:27:EB:5B:CB:74 trust succeeded
[CHG] Device B8:27:EB:5B:CB:74 Connected: no
[bluetooth]#
  • With the client paired and trusted we can exit out of the bluetoothctl app on both the hub and client by using the quit command.
  • To check that the Bluetooth network is working reboot the client device (sudo reboot), log in and check if the bnep0 interface now exists and has been assigned an IP address.

pi@client0:~ $ ifconfig bnep0
bnep0     Link encap:Ethernet  HWaddr b8:27:eb:5b:cb:74
          inet addr:172.168.10.45  Bcast:172.168.10.255  Mask:255.255.255.0
          inet6 addr: fe80::ba27:ebff:fe5b:cb74/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:60 errors:0 dropped:0 overruns:0 frame:0
          TX packets:53 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
  • To confirm the connection has been established attempt to connect to the hub from the client.

pi@client0:~ $ ping 172.168.10.1
PING 172.168.10.1 (172.168.10.1) 56(84) bytes of data.
64 bytes from 172.168.10.1: icmp_seq=1 ttl=64 time=190 ms
64 bytes from 172.168.10.1: icmp_seq=2 ttl=64 time=33.7 ms

--- 172.168.10.1 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 33.782/112.324/190.867/78.543 ms

If all has gone well you now have a working Bluetooth network, which you can now extend with multiple clients.

Optional extras

Setup static IP for a client

Sometimes its useful for a client to always be assigned the same IP address when it establishes the network connection and, luckily, this is easy to achieve.
  • First look up the client's bluetooth address using the 'hciconfig dev' command used earlier.
  • Then, on the hub, edit the /etc/dnsmasq.conf file and add the following entry, replacing the MAC with that of your client device.
dhcp-host=B8:27:EB:5B:CB:74,172.168.10.101,client0
    • Once the file has been updated we need to restart the dnsmasq service so the changes take effect.
    pi@hub:~$ sudo service dnsmasq restart
    • Now the next time the client requests an IP address it will receive the one listed in the file, and additional entries can be added for every client in the Bluetooth network.

    Enable IP port forwarding

    If your 'hub' Raspberry Pi has a Wireless or Ethernet network connection you can choose to share it with the client Raspberry Pis, in theory allowing them to access the internet via bluetooth.
    • To configure the 'hub' to forward its network connection first edit the /etc/sysctl.conf file and uncomment line 28 to read :-
    net.ipv4.ip_forward=1
    • Next edit the /etc/rc.local file and add, the following. Updating 'eth0' to match your upstream network interface (e.g. wlan0).
    
    # Enable port forwarding. Change eth0 to match the primary network connection name
    /sbin/iptables -P FORWARD ACCEPT
    /sbin/iptables --table nat -A POSTROUTING -o eth0 -j MASQUERADE
    • Finally reboot (sudo reboot), and you should now be able to access this shared network connection from any of the client Raspberry Pis.

    Wrap up

    Hopefully this set of instructions are relatively clear and cover all the steps needed to get a basic Bluetooth network up and running (Either using a Raspberry Pi with built in Bluetooth, or an older model with a USB bluetooth adaptor). More work would be needed to make this a robust solution (i.e. the client only tries to establish a connection when it first starts up) but its a solid base to build upon. In theory it should also work on none Raspberry Pi based hardware that is also running Debian Jessie or equivalent, but I've not tried myself.

    Whilst a bluetooth network is not as fast as a Wifi one (in my tests 200KB/s vs 1500KB/s) it uses slightly less power to run. On a PiZero W transferring files over WiFi seemed to pull about 0.1A more than when using Bluetooth, of course WiFi was also about 8 times faster. Not a huge difference, but if you are running the Raspberry Pi off battery, e.g. running a remote sensor, and are only transferring smaller amounts of data then this could add up to make a difference to the run time of the Pi.

    Leo


    Friday, 24 March 2017

    Pi Wars 2017 - Scaling things up

    Whilst the robot I posted about in my last blog entry is reasonably compact and contains most of the components I'll be needing for the PiWars 2017 challenges, in practice it feels a little bit sluggish and under powered, and not something I'd be confident entering into the Pi Noon challenge. So I decided what was need was a slightly bigger robot.

    Now as the robot is 3D printed I can just scale it up to the size I want yes?  Well, unless you have a fully working replicator, its not quite that easy. The plastic parts scale up nicely the motors and other electronics don't. The weight increases, so you need bigger motors, then bigger, however the batteries, and possibly a higher rated motor controller. Then you need to make all these bigger components fit on the robot and suddenly it feels like you have less space than you did before!

    I stripped all the parts from my PiWars 2015 entry and went through several revisions of the scaled up chassis, trying to work out how to make everything fix together.  Eventually I did a spot of rewiring on the controller, cut off some pins and finally came up with the following.

    Old vs New

    The new Pi Squared chassis is considerably larger than the previous variant, as well as gaining a rear wing, just fitting inside the maximum dimensions allowed for PiWars. The front wing is now removable, allowing the chassis a bit more space on my 3D printer, and can be swapped out for the various different challenges, although the only one I have prepped so far is for Pi Noon.
    Removable front wings
    The downside to the increased size is it takes a lot longer to print. The chassis takes just over 20 hours to print, the rear wing 5 and the front wing another 2...So my printer has been running almost constantly for the past week!

    The control method is my usual PS3 controller, with a simple python script driving the motors, making use of pygame and the GPIOZero library to keep everything simple. In fact the entire code is rather small.


    import pygame
    import os
    import time
    import gpiozero
    
    os.environ["SDL_VIDEODRIVER"] = "dummy"
    
    pygame.init()   
    
    pygame.display.set_mode((1,1))
    
    # Wait for a joystick
    while pygame.joystick.get_count() == 0:
      print 'waiting for joystick count = %i' % pygame.joystick.get_count()
      time.sleep(1)
      pygame.joystick.quit()
      pygame.joystick.init()
    
    
    j = pygame.joystick.Joystick(0)
    j.init()
    
    print 'Initialized Joystick : %s' % j.get_name()
    
    from gpiozero import OutputDevice
    from gpiozero import Robot
    EN1 = OutputDevice(17)
    EN2 = OutputDevice(6)
    EN1.on()
    EN2.on()
    r = Robot(left=(27,5), right=(13,4))
    
    
    try:
        # Only allow axis and button events
        pygame.event.set_allowed([pygame.JOYAXISMOTION, pygame.JOYBUTTONDOWN])
        left = 0.0
        right = 0.0
    
        while True:
            time.sleep(0.1)
            events = pygame.event.get()
            for event in events:
              UpdateMotors = 0
    
              if event.type == pygame.JOYAXISMOTION:
                left = j.get_axis(1)
                right = j.get_axis(3)
    
                r.value = (left, right)
    
    except KeyboardInterrupt:
        # Turn off the motors
        j.quit()
    
    
    

    Finally here's a quick view of the new and improved Pi Squared running around.


    With only a week left until PiWars I still have a lot to do, sensors to attach, code to write, practising driving.. So its going to be a busy weekend and evenings for the rest of the month!

    Leo

    Wednesday, 1 March 2017

    Pi Wars 2017- How to build robot?

    Having considered the various challenges that will be present at Pi Wars 2017 next step is to give some thought on what type of robot I'll be needing to tackle them. Now the sensible approach would be to use my Pi Wars 2015 entry as a starting point, after all its a fairly solid base, improve on the returning challenges (e.g. the line following) and add additional functionality to handle the new challenges.

    Of course that isn't the approach I'll be taking, although it will be the backup plan, instead I'm looking at starting afresh and putting together a new robot for Pi Wars 2017. To a degree this is because I have new ideas and new components I want to try out, as well as the fact that my Pi Wars 2015 entry didn't turn out to be all that interesting.

    There are various components you need to put together a robot and, fortunately, in the run up to PiWars 2017 the MagPi Magazine has run a few articles, starting in Issue 51, on how to build a remote controlled robot suitable for Pi Wars.


    Lots of wheels and motors.
    So what do we need? Well I will be going for a wheeled robot once more, either a two or four wheeled variety, and I'll be aiming to reuse some of the motors and wheels from previous robots. At last PiWars I took a selection of wheels but ended up not swapping them out for specific events as the motor connections were a little fragile, so that's an area I want to improve this year.

    As far as the motors go I want to investigate using stepper motors to try and get a bit more precision in some of the autonomous challenges. I have a set of four from a 3D printer, as well as a couple of larger ones salvaged from an old Laser printer.


    Motor drivers

    Next up is the motor controller. Here I have a choice of reusing the motor driver from last year as well as using some of the other's I've purchased over the years. The final choice is liable to be determined by the motors/wheels I end up using, and indeed I may need more than one motor driver, especially if I want something to propel the skittle or golf ball at a high speed.

    Batteries!
    A robot won't move without power, and once more I'll be going with Lithium Polymer ones for their high power in a small package. I've not yet had one explode on me... however there have been a few sparks, so you need to be careful handling these.


    Pis!


    Next is the brains of the robot, last time I used a Raspberry Pi A+ for its mix of smaller size, reduced power consumption and camera connector. This year I'm currently using a RPi 3B for its additional power (In case I do image processing) and its built in WiFi and bluetooth. Although I'm also planning on using some PiZero for supporting roles.


    Toys!
    Boxes and containers

    Next up on the list is the chassis, something to fit all the above components into, along with the connecting wires as well as any extra sensors or components required. My first Raspberry Pi robots were based around the BigTrak toy and other people have has success with other large plastic toys (preferably ones that already have motors in them!).

    Cheaper alternatives are empty food or packaging boxes (e.g. ice cream tubs, the CamJam EduKit box) as well as various project boxes available at Maplins or similar places. I used a project box for PiWars 2015, but ended up finding it to be a little restrictive in getting all the components connected to it, and overall ended up with a fairly plain looking robot (especially when compared to my Pirate ship from the first PiWars!).

    Luckily I have a much more flexible option this year, a 3D printer! Allowing me to, in theory, print out the exact shaped chassis I want.  Of course that is entirely dependant on me being able to design it in the first place....


    I've only created fairly basic objects to print before, so I thought I'd have a little practice by creating a chassis for a simple ZeroBorg based robot using 4 of the little micro metal gear motors to drive around. This took a few iterations but I generated a simple chassis that looked like it was going to work... apart from one small detail I missed.
    Yes... I forgot to allow space for batteries to drive the motors.... I ended up balancing a 9V battery pack on top of the PiZero, but that wasn't exactly ideal...

    So it was back to the drawing board to come up with something a little better looking for PiWars and, after quite a few more iterations I've come up with the following (Which takes over 4 hours to print if I want it good quality!).

    Still needs more work but its a Raspberry Pi 3, with camera, along with 2 motors, a LiPo battery and an AdaFruit PowerBoost 1000C to allow the LiPo battery to be charged without having to remove it, or interrupt power to the Pi3. There are liable to be many more iterations (It needs sensors/attachments for some challenges, maybe bigger motors/batteries too), but I'm hoping to keep to this general shape for the final event (only a month away now!).

    So that is how I'm planning on building my robot! More or less.. Obviously I have a lot more work to do, but already its looking nicer than my last attempt!.

    Leo

    Thursday, 29 December 2016

    PiWars 2017 - Autonomous challenges

    Its the autonomous challenges at Pi Wars that separate the robots from the radio controlled cars, requiring one or more sensors on the robot to collect information about the real world, process it and make decisions on how to react in order to successfully complete the task at hand.

    To add to the complexity you are competing against a whole raft of other robots, so you have to balance between going slow and steady or quick and fast. Do you concentrate on completing the course without any penalties, or risk pushing things to get a good time?

    Of course the first step is working out how to approach each of the challenges and get a working, reliable system up and running, before trying to push things to the limits!

    Line following

    A returning event for Pi Wars 2017, the robot needs to follow a black line on the ground, following it around a twisty course as many times as possible within the time limit provided.

    My attempts at line following in the last Pi Wars didn't go so well... In testing the night before the Arduino controlling the line sensor started triggering the watchdog and restarting, clearing the calibration data and causing the robot to lose the line, so on the day I only got about a quarter of the way around the course. So this time around I want to take an approach that uses just Raspberry Pis, partly to try and avoid this issue in future, and partly due to the fact it is a Raspberry Pi based event! 

    The first approach would to re-use the line sensor from last time, connecting it directly to a Raspberry Pi instead of an Arduino (something I've successfully done before using the pigpio library). Due to Raspbian not being a realtime OS it can take a lot of CPU time to ensure no data is lost, so for this approach I may have to use a dedicated Raspberry Pi to do the sampling, and send the data to the 'master' Raspberry Pi for processing.

    An alternate approach is to use the Raspberry Pi camera to do a spot of image processing to determine where the line is, and where it is going. I've not done image processing since University, so this would require lots of investigation, research and learning. As I like using these events to learn new things, I'll definitely be giving this approach some serous consideration.

    Straight line speed test

    Another returning event, the robot has to drive in a straight line as fast as possible along a 7.28m long trough. For Pi Wars 2017, however, the straight line speed test has been revised to be autonomous only, whereas previously I've only attempted this when under manual control (Attempts to use the compass on the Sense HAT having proven unreliable!).

    A few approaches spring to mind for this event... Utilising feedback from motor encoders to try and ensure the robot is maintaining a straight line, using a sensor to ensure the robot stays a set distance away from one wall (probably reusing the range sensor from last Pi Wars) or utilising the Raspberry Pi camera to try and detect where the walls of the trough are and ensuring the robot stays in the middle.

    Using the range sensor sounds the most feasible, but it would be nice to get something working with the camera.

    Minimal maze

    Another new event for Pi Wars 2017, the robot has to navigate its way through a maze, without touching the walls, to reach the exit. The walls will be of various colours, providing information the robot could potentially use to determine where in the maze it is.

    Initial thoughts on this challenge are that I could use a variation of the speed test solution, using a range sensor to keep the robot following the left or right wall, combined with a second sensor on the front to work out when a corner is coming up. Alternatively I could use a single range sensor and start out following the 'right' wall, then when the right wall turns blue (A camera being used to determine this) switch over to following the left wall. Hopefully avoiding hitting the outer wall as the direction changes!

    The maze needs to be completed twice, with the times combined for the final result, so can we be a little sneaky and use the first run through to 'map' out the maze? Then use this map on the second run to zoom through it? You'd need to get the starting point spot on for the second run, but it certainly sounds feasible!

    So those are my thoughts on the autonomous challenges... Do they sound good, bad, very bad? Is there enough time left to implement all of these?

    Leo

    Wednesday, 28 December 2016

    PiWars 2017 - Manual challenges.

    Its been a busy few months since I was accepted as a competitor for PiWars 2017, unfortunately very little of that time has been spent on PiWars itself. Work has been especially busy, culminating in a sudden business trip to Taiwan where I had access to shops with all the connectors, cables and components I'd need for a robot, but with no idea what I needed yet!

    So in this post I've decided to jot down my ideas for the various manual challenges, as most of them have similar requirements, and its considerably easier to manually control a robot compared to telling it to deal with things itself.

    My general approach will be similar to last PiWars, a four wheeled vehicle with tank style driving, controlled via a joystick, but with some improvements. Whilst I had the option on my previous robot to change the motors and wheels it ended up being too fiddly to do on the day and led to my robot being defeated by the 'humps' at the start of the obstacle course due to still being on small wheels. So this is an aspect I want to review and improve upon this time.

    Obstacle course

    As the exact details of the obstacle course won't be known until the day itself I have to make some assumptions about what will be required based on previous events. I would expect certain parts of the PiWars 2015 course to be reused (especially the rotating table) with a few new elements added. As such I'll be needing a setup with good ground clearance and fine controls. A high top speed won't help much here, with the marble obstacle from last year requiring the robot to drive slowly in order not to dislodge any and occur a time penalty.

    All the above is subject to change of course, the marbles may be swapped out with a gravel pit and I'll be wanting chunkier wheels to cope with that.

    Pi Noon

    Having gotten to the final of Pi Noon last time (with a lucky win or two I must admit) there's probably not much to change here. I'm tempted by the mecanum wheels that Triangula was sporting last year, but I would need quite a lot of practise to be good at using them, something I've never ended up having much time for in previous events!

    Skittles

    Skittles was a little hit and miss last time, with my robot knocking down more skittles during the practice run than it did in the official attempts. Due to time issues I ended up just pushing the ball for PiWars 2015 which, unsurprisingly, proved to be very unreliable.

    Possibly approaches to it this year could be a motorised launching system (a spinning wheel or two to get the ball up to speed), a catapult type system (pulling back and releasing an elastic band), a spring loaded system or maybe something that picks up the ball and rolls it. In theory anything that can propel the ball forwards in a straight line should work out okay for skittles, whereas the next challenge potentially requires a finer degree of control.

    Slightly Deranged Golf

    A new challenge for PiWars 2017 is golf, and apparently a slightly deranged variant of the game. As such its a bit of an unknown, with only the details of the challenge to base things on. The game is just a single hole (No 18 hole courses here!) and the robot is only allowed to push or hit the ball to get it around the obstacles. What those obstacles are we don't know (sand pits?) and whether its better to hit or push the ball won't be known until the day itself.

    The traditional approach would favour having a mechanism that can 'hit' (or propel) the ball forwards at different speeds, allowing the robot to progress through the course, changing directions to move around obstacles and eventually reach the hole. However this does sound like quite a complicated approach, as each time you need to judge how far to hit the ball, chase it with the robot, line up the next shot etc.

    A simpler approach maybe to push the ball the entire way, potentially lowering a cup over the top of it to ensure the ball doesn't get away from the robot, leaving you to just drive to the hole and drop it in. This, of course, assumes the course is flat and there is enough space between obstacles for the robot to drive through. If not the ball could escape and you'd be stuck trying to capture it again.

    So that's my current thoughts on the manual challenges, next up will be the autonomous ones!

    Leo

    Monday, 21 November 2016

    Controlling a 3D Printer with the new Raspberry Pi Zero 1.3 - follow up

    Back in May I wrote a blog entry describing how I'd used a Raspberry Pi Zero to control my 3D printer and, at the time, came to the conclusion that the RPi Zero was indeed a viable alternative to the standard model Raspberry Pi once they were more readily available.

    It took a while but I eventually ended up with enough Zeros that I felt I could dedicate one to controlling my printer and have been running it successfully for the past couple of months. My original goal for switching to a Zero was based around building a more compact solution, as opposed to a cheaper one, and I went through a couple of iterations to end up with my current solution.

    The original test setup had cables, adaptors and components all haphazardly laid out, but since then various adaptors and boards have come out to provide additional connectivity to the standard Zero.
    Its all a little messy
    The first setup I tried was the Zero4U board, a 4 port USB hub that fits underneath the Zero, allowing both the printer and a USB WiFi dongle to be connected. Whilst that worked I was under using the hub itself, and it still looked a little untidy with the dongle and cables sticking out on multiple sides.
    A Zero4U installed under the RPi Zero.
    My next, and ultimately final, setup was using the RedBear IoT pHAT to provide the Zero with a wireless connection, leaving the single USB port available for connecting to the printer. The final step was getting a USB micro to mini OTG cable to allow connecting the printer without needing an extra adaptor. I decided to use a ZeroView board to mount everything on (due to having one spare) and then quickly designed and printed a support to mount it all on, with the camera pointing at the bed.


    As mentioned earlier I've been running this setup for a few months now and the only issue I've run into was a failure when printing a 3D Benchy, which I thought may be an indication that the Zero was struggling to deal with larger gcode files. However I got a similar result after switching back to the RPi B+ (which had successfully printed 3D Benchy in the past) so have put that down to either one of the printers motors overheating, or an issue in the produced GCode.

    I never got around to mounting my RPi B to the printer, so whenever it got moved (albeit rarely) I had to move the RPi and printer separately. With this new setup I can just unplug the power and lift up everything as a single unit, and I have indeed taken this setup to a Raspberry Jam to show it off.
    Down at the Egham Raspberry Jam.

    Leo

    Monday, 17 October 2016

    PiWars 2017

    PiWars, the Raspberry Pi based robotics competition, is back for a third time and I will be, once again, competing. Last time I entered my robot 'OptimusPi' (Which I blogged about here) with my best result being runner up in the Pi Noon battle.

    OptimusPi - From PiWars 2015
    PiWars 2017 has grown in size and is being held over two days, instead of one, and I will be competing on Sunday 2nd April 2017 in the Pros/Veteran category as team 'Pi Squared'. Whilst I'm certainly a veteran of PiWars, I'm not sure I count as a Pro!

    So what is my plan this time? Well for OptimusPi I started on the basic chassis quite early, having a basic bot driving around before working on anything else, but in the end I found myself feeling quite constrained with the design, especially when getting all the sensors and other components to fit inside. So this time around I'll be starting with determining how I'll be approaching the various challenges, trying it out on one of my existing robots, and coming up with a chassis design later in the day.

    The challenges themselves are a mix of old and new with the speed test, skittles, Pi Noon, line following and obstacle course making a return. With the new challenges of Minimal Maze and Slightly Deranged Golf joining them. For the first set I can draw on  my experiences from previous events to know what approaches worked and what didn't, hopefully leaving most of the time to concentrate on the new events and actually having an interesting looking robot this time around (instead of a box on wheels that OptimusPi turned out to be).

    Of course the other question is what to wear! So far I've turned up as a pirate and then a scientist... I already have a few ideas, but I'll need some good time management to pull everything off. In theory I have just over six months to get everything sorted, but its surprising how fast that time can go.Plus there's also the blogging challenge, so stay tuned here for more updates!

    Leo






    Monday, 22 August 2016

    PiZero Bot V2.0

    Back in December 2015 I created my first Raspberry Pi Zero based Bot. It was a little ungainly with cables looping all over it and a USB WiFi dongle sticking out the side but it was relatively small, moved around and, at the time, I felt there was still plenty of room to make it more compact.
    PiZero Bot V1.0
    The aim of the next variant was to squeeze all the components into a mint tin that was only slightly larger than the Pi Zero itself. This proved something of a challenge and it wasn't until the release of Pimoroni's Zero LiPo board and Average Man's ProtoZero development board that I was able to get everything compact enough to fit inside.

    The tin is only slightly bigger then the Pi Zero
    I had never quite figured out how to best connect the AdaFruit PowerBoost to my PiZero without it getting in the way of the other components I needed to squeeze in, but the Zero LiPo fits snugly onto the Pi Zero PCB, taking up a minimal amount of space. With the power in place next step was to come up with a more minimal motor driver. After ordering a pack of L283D motor controllers (Buying several in case I killed one) I mounted it upside down on the ProtoZero board, after doing several dry runs to ensure I had enough space to fit in the wires and somewhere for the motors to attach.
    A thin, PCB sandwich.
    As this bot has no sensors (yet) it has to be manually controlled. After several attempts to squeeze in a USB dongle failed I settled on using a TTL to Bluetooth adaptor (A HC-06 module), soldering it to GPIO pins 15 and 18, the Tx and Rx pins on the Raspberry Pi. This particular TTL module is designed for 3.3V IO operations, so I didn't need to risk driving the pins at 5V, or trying to find space to fit a 5V to 3.3V converter.  Using an app called 'BlueTerm' I could now connect to the serial console on the Raspberry Pi and send it commands from my phone.


    Hardware is of little use without software to control it. Normally I'd be looking at connecting up a PS3 DualShock controller to drive the bot around, however that isn't quite so easy to set up over a serial link, so it was time to look at a different way to control a bot. A few weeks previous I had taken a look at the GPIO Zero python library and knew it had a variety of helper classes. Taking a look at the currently supported devices I found that it not only had a GPIO based Motor class but a fully implemented Robot class, allowing a 2 motor robot to be up and running in 3 lines of python.

    from gpiozero import Robot
    r = Robot(left=(23,22), right=(25,24))
    r.forward(1)

    A couple of tweaks to the connections to make sure the motors were going in the right direction and it was time to fit everything inside the tin. Being a metal tin it was conductive on the inside and, as I didn't want a short, I covered it as best as I could with Kapton tape, adding extra tape to the PiZero itself for extra safety.



    With the motors and ball caster glued into place, and the battery held in place with blu-tak, PiZero Bot V2 was almost ready to go. I extended the python code to listen for the WASD keys to drive the robot from my phone and it was off for a test drive.


    A relatively successful trip, although the battery appeared to be dying towards the end as it was starting to struggle to move. I know the battery wasn't fully charged at the time, so I'll have to test again to see how well it lasts. I do have a larger battery that is around the size of the mint tin, but I was avoiding using it as it adds to the height of the robot, and that somewhat defeated the point of making the smallest robot I can.

    Of course its also a little tricky to control when driving it via key presses alone, but it should be possible to write an Android app, or similar, that can implement an analogue controller that communicates over serial to the Raspberry Pi.

    As ever there is always more to do. I still want to add at least one sensor to this bot, probably a proximity detection one, so it can be left to drive around by itself. However with all the wires stuffed inside it there's not much room to extend it cleanly. I may have to look at designing my own PCB so I can get rid of most of the wires, freeing up some space to connect up a sensor, punching some holes in the front of the tin to allow it to be connected up. But that will have to wait for V3, as I have some other projects that need finishing up first.

    Leo