Wednesday, October 12, 2016

Scratch 2.0 using Chromium on Raspberry Pi 3


Playing with Scratch and thought now that Chromium is the default browser in Raspbian Pixel whether the web based Scratch would work.

So, I went to http://scratch.mit.edu and picked a project to load. Up came the usual jigsaw piece saying a plug in was missing.  Right clicked to enable the plug in and nothing happened.  Oh, well nothing has changed.  We still have NuScratch installed on the Pi.

Before shutting down I did an update/upgrade, just to keep the machine up to date.
A whole bunch of updates for LibreOffice and NuScratch were downloaded as well as an update to Chromium.  Nothing looked too interested.

Then a strange thing happened.  Half way through the upgrade a screen appears asking me to confirm installing the Flash plugin.  I accepted and let the upgrade take it's course.

Intrigued by this I went back to the Scratch website and selected the project again.
Again, the jigsaw piece appeared.
Again, I selected to enable the plugin.
Except this time the outcome was different.  The panel went white and the familiar Scratch loading bar appeared.  It was working and working well.

See the video below.



Mike Horne did a post on his website  this and Simon Long who does Raspbian and specifically Pixel 



Looks like Chromium had an update on the 11th and by chance I did an update to my machine soon after the release.  From Simon's post this needs ARMv7 so  only works on Raspberry Pi 2 and 3. Not an option for older Raspberry Pi or the PiZero.


Wednesday, October 5, 2016

NexDock thoughts on using with Raspberry Pi


Earlier this year I backed the NexDock Indiegogo.  The NexDock was primarily being promoted as a Windows Phone accessory as it supports Continuum, but since it has a miniHDMI some of us thought it might be a great partner for the Raspberry Pi.

It took them 2 attempts to get funded but made it in the end.
Then they had a fire at the factory which set the project back even further.






All respect to the NexDock team, instead of throwing in the towel they rallied and with their ODM partner picked up the pieces, had new NexDock manufactured and in the end I took delivery on the 9th of September and have been using the NexDock a fair bit since.




Power, we have power. Oh!, maybe not

My life with a NexDock didn't start too well when I noticed it wasn't charging.
The charger did look a bit ropey but thought since it passed QA at the factory it must have been OK.

Not the cleanest. Should still be OK, right

A bit of dirt never hurt anyone

I'm sure it's fine

Checked the power supply with a multimeter and it was dead.
I submitted a Help Desk request on the support site and NexDock replied quickly that this shouldn't have happened and they were very sorry.  Advising it would take a while to send me a replacement power supply so as an alternative if I was OK with it they would refund me $15 as that is the equivalent cost of a PSU on Amazon.  Les Pounder who has blogged his experience here (http://bigl.es/nexdock-initial-impressions/) decided the US power supply with an adapter was not for him and he bought a suitable supply with 3.2A from CPC (http://cpc.farnell.com/stontronics/t5004st/ac-dc-power-supply-5v-3-2a-universal/dp/PW03046)

I still have to get a replacement power supply so in the short term I used a microUSB adapter board with the original cable to make a solution that would allow me to use any of the many microUSB chargers I have due to my Raspberry Pi addiction.

Functional, but maybe not a long term solution

This is what I have been using with the NexDock and it's served me well.  The green light you can see is the power LED.  Orange when charging and Green when fully charged.

Teething problems out of the way. What is the NexDock like to use.

Keyboard and Trackpad

The keyboard is a decent size.  The travel on the keys is comfortable.
One irritation for me is the power button is where the [delete] key should be and the [delete] key has been placed below the [backspace] . So, when I make a mistake and blindly stab at [delete] I'm pressing [power] and no delete happens.  Luckily the power button has to be held down for the usual 5 seconds to turn off the NexDock.  What it did mean is for a while I kept thinking the keyboard unpaired from the Pi and so I went into the menu, disconnected and reconnect the NexDock. 
Once I figured out it was user error all was good.  Still, funky placement of keys is becoming an ongoing annoyance on laptops as manufacturers pick different places for keys.
Oh, and the keyboard layout is US.  I'm in the UK.  I can live with it as I am comfortable using different keyboard layouts, just something to be aware of.

You can see the keyboard layout here


The trackpad works well once you up the speed of the  'mouse' on the Raspberry Pi.  No idea why this is needed but it does work.

It's important to note the keyboard and trackpad are Bluetooth and not USB.  So, for Pi users this works well for the Pi3, but not the Pi2 or PiZero as they do not have Bluetooth.  More on this later.

Screen

The screen, even though LCD and not IPS is sharp and works well for extended use.  The resolution is the classic 1366x768.  Fairly standard for laptops, but not a mode the Pi has automatically. (http://elinux.org/RPiconfig#Video_mode_options).  Not a problem if auto selected from HDMI, but as noted below can cause some fun when working with realVNC.

First boot with Pi3 powered from NexDock

Bluetooth and power 

As mentioned above the keyboard and trackpad are Bluetooth.  They are not available over USB.
With the Pi3 the NexDock is found when scanning and once paired works well.

You can't back power the Pi3 through USB so it has to be powered from the microUSB power connection.  This means when powering the Pi3 from the NexDock the USB devices built-in (webcam, microphone, microSD slot and USB port on the right) to the NexDock are not available.  The USB port on the left that provides  power is also the hub connection port.
On the Pimoroni Bilge Tank they had a a frankin-cable that does power the Pi3 and connect USB so all devices are available.


Also, Mike Redrobe did the diagram below showing the connections. 

Connections on NexDock

Personally, I haven't needed the webcam or other devices so it hasn't been a problem for me so far.
I just use the USB ports on the Pi3 to connect my devices.

We know that the PiZero can be back powered through  USB so this looked like it could be ideal, except the keyboard and trackpad are Bluetooth.
I connected a PiZero and powered it from the NexDock. Then connected a Bluetooth dongle bought on eBay to the port on the right.


All booted, Bluetooth dongle seen, paired with NexDock. Working great, then Bluetooth device disappears. Icon in top bar grayed out.  As an eBay purchase I suspected it might be faulty so used on a couple of PCs and plugged directly into a USB port on a Pi2 with the NexDock and all worked well.

My conclusion is that even though there is a nice big battery inside the NexDock the USB port on the right is not a powered port and so doesn't have enough power to support the Bluetooth Dongle.  It works great for an external mouse and other lower power devices, but this Bluetooth dongle seems to need more power than the port can handle.

Continuing my adventure with the PiZero I used a Zero4U USB hub bought at Cambridge Raspberry Jam from Ryanteck.



This attaches directly to the PiZero taking it's power from the 5V line directly to give a powered hub.
With this and again back powering the PiZero from the NexDock the Bluetooth dongle worked great.
Now I have a PiZero computer with keyboard/trackpad, webcam, microphone, speakers, 3.5MM headphone jack, another USB port and a microSD slot.

One thing to note on Bluetooth with the Raspberry Pi is that in Raspbian Bluetooth is not set up to auto pair with devices on boot up, so for first set up you need an external mouse to pair the NexDock and the Pi.
NexDock address this on their support page and give instruction on how to set up a cronjob to enable the pairing each time your Raspberry Pi starts up.
The support page also explains how to get the internal speakers working and a couple of other things.

The longest time the NexDock was running was at the Cambridge Jam in September which runs from 10:30am to 4:30pm.   The NexDock was set up with a Pi3 powered externally so the USB from the Pi3 was connected to the NexDock to enable the webcam.  It was running Scratch Pac Man and a simple webcam viewer python program showing the person using the computer their image. Code on GitHub


Battery test

The last thing is the battery in the NexDock.  It's a 10,000mA battery, so a decent size.

Powering a Pi3 idle it lasted ~6 hours and powering a Pi3 under load it lasted 3 1/2 hours..

These were the times I expected using back of an envelope calculations.

To run these tests I ran sysbench in one terminal window and in a second window ran a small python script that recorded to start time and every 60 seconds recorded the time.
The Pi3/NexDock ran until it shut down. Then starting the Pi3 again it was just a matter of subtracting one time from the other.


Other findings

I mentioned above about connecting over realVNC.  Using the Pi3 on a NexDock as the client and then realVNC running on a PiZero as the server. realVNC by default sets the screen resolution to 640x480 and this function, but as you'd expect a bit painful to do anything constructive.
You can change the Pi resolution by modifying the config.txt file in /boot.
Problem is there is no 1366x768 resolution option, meaning full native NexDock resolution wasn't possible. I could do 1360x768(mode 39) and this worked but it did leave a few unused pixels either side of the screen. Not a massive thing, just worth noting.

I also tried to enable the experimental OpenGL drivers and this failed completely.  Black screen.  No flashing cursor, no scrolling of the messages at start up (pre Raspbian PIXEL)
To be fair to the NexDock I have the same problem with the pi-topCEED, so it might be something to do with the default non-standard (to the Pi) resolution.

So, it looks like the experimental OpenGL drivers are not compatible with the NexDock display.  Pity as this could have been fun for Minetest, the Minecraft-a-like open source game that is in the repo so can be installed with apt-get install minetest.
It's not the latest version, but it plays great on a Pi3 with OpenGL enabled and 256MB set aside for the GPU.  NOTE: Minetest makes the SOC run hot. If you are going to play Minetest on the Pi2/3 then you will need a fan. I have a heatsink on a Pi3 and that's not enough. Previous blog post about Minetest on the Pi3

Also on Minetest, if you are walking/flying around and you use the trackpad to change direction you stop moving. I don't know if this is a Bluetooth keyboard/trackpad combo thing or if this is NexDock specific.  Either way it means on the NexDock you can play Minecraft, but if you want to change direction while moving you have to release the forward/backward key and press it again

Conclusions and wish list

With everything above I do like the NexDock.  It feels nice to use. The keyboard and trackpad work well.  For it's intended use with Windows Phone I expect it is a perfect match.  With the Raspberry Pi the needs are a bit different but it does provide what I need to use it regularly.

With that said for me it would go from being great to amazing as a Raspberry Pi device if:

  • Left side had 2 USB ports. One capable of providing power and USB connection, second one USB connection at standard power rating.
  • Keyboard/trackpad with the option to connect as Bluetooth or USB
  • 2 USB ports on the right.
  • Powered internal USB hub meaning the 2 (wish list) USB ports on the right would be able to handle devices that need power like the Bluetooth dongle and external hard drives.
  • UK Power supply instead of US with adapter
  • UK keyboard layout option

I see myself using the NexDock as my primary Pi device and will over time be doing the expected nerd/geek activity of covering it in stickers which to me is a real sign of a keeper that you expect to have part of your life for a good while to come.








Tuesday, August 23, 2016

buttonFlash - game made with Raspberry Pi and Arduino communicating using NRF24L01 modules

IMPORTANT: The code in this blog post is the original code which does work but may not have all the enhancements. If you're building your own I recommend grabbing the code from GitHub.
GitHub link: https://github.com/winkleink/buttonFlash

Update: 19th September:
Took buttonFlash to the Cambridge Raspberry Jam on the 17th of September and it got a proper outing.




UPDATE: 25th August:
Made Raspberry Pi program look prettier
Added sound effects


A few years ago I thought it would be fun to come up with an outdoor game that would get people running around. The Whack-a-Mole/reflexes button game came to mind and this is the result. A game where you have to press buttons as quickly as possible.



Since then a great Raspberry Pi version called Whack-a-Pi was done by +ForToffee
Here are his build instructions and videos. https://fortoffee.org.uk/2016/03/whack-a-pi/

Whack-a-Pi was in constant play at the Raspberry Pi 4th Party.


The concept for buttonFlash is similar to Whack-a-Pi but with the ability for the buttons to be much further apart.  Goal is to get people running around.  With the buttons further apart there was no way I was going to be managing physical wires as it would be a trip hazard and I didn't want to have to manage that many wires.  So, wireless communication between the base and the buttons seemed the obvious choice.

Most fields don't have wifi.  I could bring along my trusty Vocore and create a local WiFi hot spot but again I want this to be simple to set up and use.

VoCore.  Basically guts of a Wifi router

So, I thought the NRF24L01 would do the trick.  They're a really cheap transceiver. They can transmit and receive signals making them ideal for short range two way communication.

NRF24L01

This current UK eBay listing is for five NRF24L01 for £5.99
Also, there are stable libraries for Arduino and Raspberry Pi available.

On the Arduino I used the RF24 library.  If you've the latest version of the Arduino IDE you can install this through the library manager or if you prefer you can go old school and download it from the GitHub repository at the link above. More details on using the NRF24 with Arduino

On the Raspberry Pi I used the following Library https://github.com/BLavery/lib_nrf24

The Arduino side was relatively straightforward to get working while the Raspberry Pi side had me stumped for a while.  Then earlier this year I had a breakthrough when I met +Elliot Pittam.  He had seen the first Wimbledon Raspberry Jam and was interested in coming along.  On email we discussed what we were working on and Elliot said he was using the NRF24L01 with the Pi and Arduino.  We then met at a HackWimbledon event where he showed me his set up and shared his working code. Elliot helped me sort my circuit and pointed me to 2 great videos on using the NRF24L01 with both Arduino and Raspberry Pi.


Tutorial 34 - Part 1

Tutorial 35 - Part 2

With Elliot's assistance I successfully had the Raspberry Pi communicating with the Arduino.


Many of the example I found did not clearly identify which pins on the Arduino or Raspberry Pi were connected to which pins on the NRF24L01. Therefore, below is the wiring I used for the Raspberry Pi and the Arduino with the code provided.  So, it all matches up nicely.

NRF     Pi GPIO  Pin
VCC     3.3V       1
GND     GND        6
CSN     GPIO8     24
CE      CPIO17    11
MOSI    GPIO10    19
MISO    GPIO9     21
SCK     GPIO11    23

NRF           Arduino
VCC     3.3V
GND     GND
CSN     Digital 10
CE      Digital 9
MOSI    Digital 11
MISO    Digital 12
SCK     Digital 13 

For the Arduino to keep it compact I went with Arduino Nano compatible board on a small 170 pin breadboard. Easy build and easy maintenance.

Soldering on the headers to the Arduino Nano
All 5 completed

The Arduino Nano Compatible with a suitable short USB cable are ~£4.50 from the UK but can be ~£2.50 if time isn't an issue and you're happy to order from China/Hong Kong.
It's important to know these compatibles use the CH340G serial chip which is different to the Arduino branded.  You will need additional drivers to get these working with some computers.

To make each of the buttons base I needed a suitable container to hold the button and the rest of the electronics and of course the button.  I'd seen these great 60mm buttons with LEDs built in so I order some.  Again from eBay UK these are about ~£7.00 for five.  

RED 60mm LED button

The ones I ordered are 12V rated which is the power for the LED.  Opening it up these things just have a standard LED and a current limited resistors. The resistor was a 460 Ohm for the 12 volts. Without knowing the specific LEDs and their voltage drop and maximum current I played it safe and replaced the 460 Ohm with 150 Ohm resistors.  The buttons did light very dimly with the 460s but were far brighter with the 150 Ohm.  Below is the button being taken apart.

button in place 

unscrew the button/LED assembly

pull out the LED (like Christmas lights)

remove LED with resistor on Anode (+ side, other goes to GND)

solder on replacement resistor and put it all back together

To test the LED at each stage I ran an Arduino with the blink sketched and wired the LED across pins GND and 13.  Once all reassemble with the wires attached again I tested to make sure I didn't mess things up in putting it back together.

Next, for each Arduino I wired the NRF24L01 as per above.  The LED was wired to Pin 2 and Button was wired to Pin 3. In code I activated the internal pull up resistor so the button is held high until you press it and then it goes low.


it all wired up.

As the Raspberry Pi needed to send a message to the Arduinos to let them know which one is to activate their button and wait for it to be pressed before replying I came up with a simple message that is extendable.  Basically, the number of the Arduino followed by 'P' Examples: 1P, 2P, 3P, 4P, 5P
This would be the message sent out.
All Arduino would receive it and then using a simple IF statement would decide if it means they are to be activated. If not go back to listening. If yes light the button and wait for it to be pressed. Once pressed reply to the Raspberry Pi that the button has been pressed. 
In this way the Arduino are dumb.  They only respond to a request for the button and reply it's been pressed. They don't care if they are the first, second, third,... button to be pressed in the game.  All that is managed at the Raspberry Pi.

To make it easier to setup and to test I included a test mode.
When you press 't' it sends the test message and all the Arduino flash their LEDs 5 time.  Then Arduino 1 (as there will  always be at least 2 Arduino) replies that it is completed.
The Raspberry Pi doesn't do anything with this message as the test is to see if it is sent and replied to which the users sees in the console.
This means Button/Arduino 1 has slightly different code to all the rest of the buttons.

Button/Arduino 1 code with the extra bit for Arduino 1 only highlighted in RED
For each Button/Arduino the text highlighted in BLUE needs to be changed to matched the relevant reference in the Raspberry Pi list. This text is the same in all 3 locations so you can do a Find/Replace to do it in one go.

#include<SPI.h>
#include<RF24.h>

//ce. csn pins
RF24 radio(9, 10);

int buttonPin = 3;
int ledPin = 2;
int x;

void setup(void) {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
  while (!Serial);
  Serial.begin(9600);

  radio.begin();
  radio.setPALevel(RF24_PA_MAX);
  radio.setChannel(0x76);
  radio.openWritingPipe(0xF0F0F0F0E1LL);
  const uint64_t pipe = 0xE8E8F0F0E1LL;
  radio.openReadingPipe(1, pipe);

  radio.enableDynamicPayloads();
  radio.powerUp();

}

void loop() {
  radio.startListening();
  Serial.println("Starting Loop, Radio on 1P.");
  char receivedMessage[32] = {0};
  if (radio.available()) {
    radio.read(receivedMessage, sizeof(receivedMessage));
    Serial.print("Received Message: ");
    Serial.println(receivedMessage);
    Serial.println("Turning off the radio.");
    radio.stopListening();

    String stringMessage(receivedMessage);
// Actual action if asked for button press
    if (stringMessage == "1P") {
      digitalWrite(ledPin,HIGH);

      while (digitalRead(buttonPin) == HIGH){
            }
      digitalWrite(ledPin, LOW);      
      Serial.println("looks like they want a string");
      const char text[] = "Node 1P - Hello";
      radio.write(text, sizeof(text));
      Serial.println("We sent our message: " + String(text));
    }

// Test scenario    
    if (stringMessage == "TEST") {
      for(x=0; x < 5; x++){
      digitalWrite(ledPin,HIGH); 
      delay(500);
      digitalWrite(ledPin, LOW);
      delay(500);
      }
      Serial.println("Test completed");
      const char text[] = "Test done";
      radio.write(text, sizeof(text));
      Serial.println("We sent our message: " + String(text));
    
    }

  }

  delay(100);
}

On the Raspberry Pi side the code is a little more interesting as it sets up the NRF24L01 and then creates a graphical window using pygame and finally runs the game.  At this stage it displays Score and High Score.




The steps to get the Raspberry Pi ready are:
Wire up the NRF24L01 as per above
Use the Raspberry Po configuration program to enable SPI (you have to reboot after this)
Then run the following commands.


sudo apt-get update
sudo apt-get upgrade 
sudo apt-get install python-dev python3.dev -y

I'm assuming you're in hour home directory for the rest of this.

mkdir buttonFlash
git clone https://github.com/Gadgetoid/py-spidev
cd py-spidev
sudo python setup.py install
sudo python3 setup.py install

cd ..

git clone https://github.com/BLavery/lib_nrf24
cd lib_nrf24/

cp lib_nrf24.py ~/buttonFlash
cd ..

You should now have SPI working with the python SPI libraries installed for Python 2 and 3 as well as the required lib_nrf24 for working with the NRF24L01 from python.
Finally the library file is copied to the buttonFlash directory.

Copy the Raspberry Pi code into the buttonFlash directory and run it.

All the necessary files and code are available on GitHub https://github.com/winkleink/buttonFlash


sudo python3 buttonFlash.py3

Yeah. Now it all technically works
Here is a short example of it running after the initial build.



With the electronics sorted and the programs functioning the next requirement was a housing for the buttons.  I thought I found the perfect one when I got this spaghetti container from Home Bargains.   It all fit comfortable and the button was really secure.



Only problem was when I went back to get more they were out of stock with no idea when/if more would be coming in.  Then I saw the Pringles can and tried it out and it worked.  Pringles cans for the win.



Oh, and I had to eat another 4 cans of Pringles to get the 5 required.  



As this is designed to be played indoors or outdoors I needed to fina a way to make them stable when placed in a field.  I went super simple and bought 150mm bolts with nuts and passed them through the bottom of the Pringles cans.  You'll notice I numbered each can and there is also a colour listed.  I bought 5 different coloured breadboards so I could tell which Button/Arduino was in each can.  
You can see the bottoms of the tubes are deformed a bit.  Ends up Pringles cans aren't super strong.  Means I have to re-tighten the nuts as they work lose.  Wonder if an application from a glue gun will sort this out.


bottom of each Tube with bolt, number and colour 

all the bits outside the can.

If you watched the video at the top or the video at the bottom you might have noticed the Pringles cans have a bit of a base to keep them stable for indoor use.  In the rush to push the buttons the Pringles cans were falling over.  The solution was some microwave pots that tapered from the bottom to the top turned upside down and with a hole cut int he bottom.  This gives a nice wide base. If further stability is needed these pots could be filled with sand or stones to weigh down the bottom even more.
microwave pot used as base

This was an interesting build as I never used NRF24L01s before.  Finding the information on how to get them to work and wire them up was interesting as most of the guides nearly provided the full details and they all seemed to provide slightly different information. So, I enjoyed solving that riddle and end up with a playable game that scales in the number of buttons and also the space.
This could be set up as 10 buttons on a table with all the cans tied to each other or as 20 buttons around the outside of a field.  You'll hear in the video below that the Raspberry Pi can call out the button numbers. This definitely made it a bit easier as you quickly learn which button is which position.  For outdoor use if it is very sunny I have a feeling the LEDs in the buttons will not be bright enough.  So, next I will be adding more lights and indicators to the buttons so they can be identified outdoors.


Here's another video of the game being played at the Cambridge Raspberry Jam.


If you have any questions or comments let me know.





Monday, August 22, 2016

eBay USB soldering iron in use


Sometimes I've to do a little bit of soldering.  Usually only a few wires and since at present I have no place to leave an iron set up permanently this requires for me to either unpack my rework station or even just a simple mains powered soldering iron.
Even doing this has resulted in me pushing back soldering jobs as the extra time for setup
 as a ratio against actual build time doesn't feel like time well spent.

Then on eBay UK I came across a listing for USB soldering iron for £3.39


Since my electronics is usually tied to an Arduino or Raspberry Pi project I will have a computer up and running and I thought for less than £4.00 including shipped from Hong Kong it was worth a punt.
Well, it arrived this week and as per the picture it includes the soldering iron with a plastic cover for the top.  A USB to 3.5mm jack for power.  A really small stand made from a folded piece of metal with a bit taken out and just enough solder to know it's working.  Actually I soldered about 30 wires using the solder provided and have a bit left over.  Still you'll need to get some solder.

First impressions were positive.  Packed in a proper retail packaging box and not just a jiffy bag like many cheap things on eBay from Hong Kong.

The iron heated up quickly and has a red LED to let you know it's on.
It was definitely hot enough to melt the solder and do the job I required.
Since the original outing I have used it again to replace some current limiting resistors for 5 LEDs in a project I'm working on.  Again all worked great.

As I've only used it twice I can't speak for the long term reliability but from first impressions it is well worth the £3.39 it cost me.

The only things I would change are:
I would have liked the power to be microUSB and not 3.5mm jack.  I've loads of microUSB cables but this is my only USB-3.5mm cable.  If I lose it I'll have to get a new kit. Probably not a disaster at £3.39 and then I'd have a backup.

The tip on the iron is a needle tip. My personal preference is a bevel tip. The ones where it's like they cut a diagonal slice off a flat tip.
Here is a nice instructable explaining the different tips. My preference is called a C series tip in the guide.   Rarely do really fine work and even then a bevel can still be used quite well for most things.

Saying all this for less than £4.00 it feels nice to use and means I can set up, do the rework and pack away in minutes. Which is ideal when only soldering a few wires at any one time.

UPDATE: after posting this I was sent a link to a great video by bigclivedotcom where he tests, tearsdown  reverse engineers the circuit diagram.  Let's just say his review is way better than mine.
Here's the video.



Tuesday, July 19, 2016

Toy crane controlled from Raspberry Pi Zero with SenseHat using Scratch


Since the micro:bit was launched one of the demos that I kept seeing was the toy crane controlled using the motion sensing in the micro:bit.  The kids loved it and was very interactive.

Since the SenseHat on the Raspberry Pi has the motion sensors built in I thought this would a good project for a Raspberry Jam.

So, off I went to Home Bargains and bought a crane. From the picture, definitely the right age for me.  This crane is normally controlled using two levers on the hand controller. It can rotate and raise/lower the bucket.

Didn't come with the hard hat
First order of business was to figure out the wiring and cut the cable as the final build would be battery powered to work the same as the micro:bit version.


Cut the red wire

From above the wiring is:
VCC - Red wire
GND - Brown wire (not black)

Rotate motor 
Orange and Yellow

Crane lift motor
Blue and Green.

For turning and crane the direction it goes depends on how you wire it up and how your code works so some adjusting may be needed later.

To make sure I had this right I tested by touching Red to Orange and Brown to Yellow. Crane rotated one way. Swapped wires around and crane rotated the other way.
Red to Blue and Brown to Green, Bucket went down. Swapped wires around and bucket went up.

Wiring confirmed and tested.

As the Raspberry Pi isn't designed to control motors directly I needed a small motor controller.
The L9110s looked perfect for the job. Smaller than the L298N that I usually use so would be easier to accommodate in the final box.

L9110s motor controller
The 2 terminal blocks on the left in the image are for the motors.
On the right are the control pins and power.
Top 2 connections are control for Motor A
Bottom 2 connections are control for Motor B
Then in the middle are VCC and GND

NOTE: A really important thing is to make sure when using multiple boards that all the GND lines are tied together so that all the voltages have the same base reference.  Otherwise strange things can happen.

I wired up the motors. Turning uses GPIO 5 and GPIO 6 on the Raspberry Pi and Motor B on the L9110s while lifting uses GPIO 27 and GPIO 17 and Motor A.

Again did some simple code to see if it would work from Scratch. Initially manually moving with the keyboard.  It worked great and I brought it along to the Egham Jam in April 2016.  As the organiser of the Jam I was a bit delinquent in taking pictures so the only one I have is of the crane, bottom left in the booth of the car before I went to the event. I promise the kids loved it and it was a massive hit, really. Actually, I had a different project called ZeroBall that was finished so it took most of my time.

Bottom leftis the crane
There were two technical reason I didn't have it all set up with motion sensing and coded in Scratch for the Jam.

  1. The SenseHat covers all the GPIO pins meaning I couldn't get at the pins to attach the wires for the motor controller.  So, I could get the readings from the SenseHat but couldn't control the motors.
  2. The Scratch at the time had a problem whereby it didn't support AddOn board. 


The first problem was solved with Stacking Headers and great tutorial from Keith's Pi Tutorials even has a video.
Also, a great reference site for Raspberry Pi board pin usage is pinout.xyz.  They have loads of boards listed and this is where I got the details for the pins used on the SenseHat

Stackable Headers. Note the high tech blutac for holding it all in the tub


The second problem of Scratch not working at all with AddOn boards was reported and fixed in the May 2016 Raspbian update.

With the purchase of Stackable Headers from The Pi Hut and a freshly imaged SD card both of these technical problems were overcome and the way forward was sorted for the SenseHat to be used to control the crane.

Since I wanted it to be battery powered the Raspberry Pi Zero was the obvious choice as it is low power. Only thing is Scratch is a GUI program and so I needed a desktop environment to run it (If you can run Scratch code without a GUI I'd love to know, but I suspect it kind of defeats the purpose of a drag and drop interface if you run it from the command line)

To overcome this I used a USB wifi dongle to connect over the network to the PiZero and then on a laptop used RealVNC to get a desktop. Since this was going to be shown at the first Wimbledon Raspberry Jam I didn't know if I would have a wifi network to connect to so I brought my own in the shape of a VoCore. A one inch cubed wireless router running openWRT.  I backed this as a crowdfunding thing a while back and all I've used it for it to create a local wifi hotspot.  At the Jams I can even power it from a powered Raspberry Pi USB port.

Side Notes:
I think the number is the manufacturing order of the original batch and I've never seen one with a number lower than 26.
The VoCore is only the top layer. The rest is an add-on that gives you USB, Ethernet, microUSB power socket and a microSD slot.  IT also has it's own GPIO pins so can be used for embedded projects.

Vocore. Basically, the guts of a wifi router
Obviously, as this was going to be standalone it had to be battery powered. I'd been picking up these 18650 Lithium Ion batteries in Poundworld and thought 4 of these in a case would make a decent power supply for the day.  No idea why when I cracked them open one was pink.  The battery case was from eBay and it all snapped together really easily.
The case has 2 USB ports for power so could power the Raspberry Pi and the VoCore at the same time.

Batteries in their original cases

Batteries in their new case


I mentioned above that all the Grounds need to be tied together.  In this instance I have 3 circuits that need to all have the same GND. Crane, L9110s and Raspberry Pi Zero (The SenseHat is take care of through the Pi Zero)
I tied the Crane GND (Brown wire directly to Pin 39 on the Raspberry Pi, then the GND pin on the L9110s was tied to Pin 6 on the Raspberry Pi.  In this way all 3 had a common GND.

It's good to be aware that in a circuit all GND can usually be treated as the same point. Especially for such low power and low frequency signals.  If this was a high power high frequency circuit then the trace length between the different GND points could case harmonics.  I cannot think of a project using the Pi that I would do where the length of the trace between GND pins would be a problem


So, now I have power, local network, a way to run Scratch so people can see the code and all the bits wired up. Last of all was the actual Scratch code.

From the image you'll see the code isn't very complex.  The main thing I'd to figure out was which one of the sensors I needed to read. It's the Accelerometer.
I believe the range is -4095 to + 4095 on each axis.
When the program is run a base "flat' reading for Lifter and Turning is taken so any movement in the sensor doesn't carry from one person to the next.  This is what the middle block of code does.
The block of code on the right is there if it all goes wrong and I can just press [space] to turn off the motors.

Th middle block is where the magic happens.  It checks if Accelerometer X is 1000 less or 1000 more than the flat reading for Lifter and/or Turning and then activates the appropriate motor to either turn the crane or raise/lower the bucket.

Not shown below is a second costume for the crane that just says "Put Pi on a flat surface" at the start of the calibration.


If you're not up for trying to copy the code from the image you can download the Scratch code from GitHub.

To make it hand held I stuffed all the bits in to a plastic Chinese takeaway box.  You can see the L9110s on the left, wifi dongle on a short microUSD to USB cable and the SenseHat with the Stackable Headers so the wires for the motor controller can could be added.

Finally, here is a boy totally engrossed in playing with the crane at the Wimbledon Jam.  It all ended really well.

Hours of fun transporting monkey from one place to another









Monday, July 18, 2016

Minecraft Pi backup Worlds on exit

My kids love building cities on the Raspberry Pi version of Minecraft.  They're not programming them yet, but they spend hours placing blocks and designing houses, hotels, swimming pools, and other building and gardens.
All of which is great.
Except I also use the Raspberry Pi for programming and other things where due to my fumbling around I end up borking the SD card and have to start again.

That's OK. If you backup all the files in ~/.minecraft/games/com.mojang/ and then put them on the new SD card all is good.  Really simple backup.
Only problem is I keep forgetting this step and delete weeks or months or effort.

Rather than expecting somehow that I will remember in the future I thought it would be a good idea to solve the problem with a bit of code and a little modification to the menu.

The goal is to replace the command that runs minecraft-pi with a command that runs minecraft-pi and then on exit archives the worlds and sends them to an ftp server.
In this way the backup is off the Pi and even if I do reformat it I can get the backup minecraft worlds and just reinstate them.

All this is being done with Raspbian as the OS.

For the ftp server I have OSMC set up on a Raspberry Pi (1) B+ that I use mainly as a media server for a couple of Blu-Ray player and tablets in the house so it is on 24x7.

The code is quite short made up of a python script that does the archiving and ftping of the file and a bash script that runs minecraft-pi and then runs the backup script.
The code is available at https://github.com/winkleink/MinecraftPi_backup

Just copy it into pi user home folder '/home/pi'
If you copy the code somewhere else then you will need to modify the bash script and the files to take it in to account.
Once copied change the file preferences to permit execution. Since you're in the GUI the easiest way to do this is right click on the file and select [Properties].
The go to Permissions and set Execute.  I chose Anyone, but if you're only going to run as user pi then you can select 'Only owner'

Change Execute permissions so this is a program that can be run

You need to do this for the 2 files (minec.sh and ftpzipminecraft.py)

minec.sh is the bash script to run the 2 commands. With the semicolon at the end of the first command it knows to run them in sequence (one after each other) rather than potentially at the same time. No modification is needed unless you save the ftpzipminecraft.py program somewhere other than the pi home folder

minec.sh

#!/bin/bash
minecraft-pi; 
/home/pi/ftpzipminecraft.py

ftpzipminecraft.py runs after minecraft-pi closes and this does the archiving to local file in the pi home folder and then connects to the ftp server and transfers the archive to the server.
You have to change 3 items in the file for it to work.  I've highlighted them in red below.

FTP SERVER NAME/IP ADDRESS
USERNAME
PASSWORD

ftpzipminecraft.py

#!/usr/bin/python3
# Script to backup the MinecraftPi worlds and then upload them to an FTP server
# By Winkleink (July 2016)
# https://github.com/winkleink/MinecraftPi_backup
# MIT Licence
# This is a quick fix so use at your peril
import os
import zipfile
import datetime

import ftplib

now = datetime.datetime.now()
year= str(now.year)
month = str(now.month)
day = str(now.day)
hour = str(now.hour)
minute= str(now.minute)

uploadfile = "minecraft"+year+"-"+month+"-"+day+"-_-"+hour+"-"+minute+".tar.gz"

print(uploadfile)
os.system ("tar zcvf " + uploadfile + " /home/pi/.minecraft/games/com.mojang")

# Enter your FTP Server Name or IP address, Username and Password in the following line
session = ftplib.FTP("FTP SERVER NAME/IP ADDRESS","USERNAME","PASSWORD")
file = open("/home/pi/"+uploadfile, "rb")
session.storbinary("STOR " + uploadfile, file)
file.close()
session.quit()
print("Done")





Once both files are in place and are set to executable we need to modify the menu entry for Minecraft so it runs our new script minec.sh

From the main menu select [Preferences] [Main Menu Editor]


Then on the left select [Games] and pick [Minecraft] and then click [Properties] on the right.


Finally, replace the 'minecraft-pi' command with '/home/pi/minec.sh'


Its not shown here, but so I know it's the one I've changed I modified the Comment to 'Minecraft + Backup' so when I mouse over the menu entry I can see it the one with the backup.

With this little change I will hopefully never lose my kids amazing creations in Minecraft on the Raspberry Pi.