Sunday, 12 November 2017

Tropical Pallet Wood Carpentry

When the MRT project finished last July I had been almost three years continuously on-site and needed a change. A couple of new houses were being built near us and I noticed a lot of lumber were being burnt. Some of it had been used as concrete molds but most of it were used pallets.

I dragged some of the lumber home bought some cheap hand tools and dismantled the pallets.
It is quite a satisfying experience ripping apart stuff with crowbars and sledgehammers but I quickly found that extracting nails reliably required some finesse. The claw hammer and the crowbar broke the nail heads off too often, and all too often in the best pieces.

I bought an old-fashioned pair of pincers and by the third pallet could get every nail out. Even when the claw hammer broke the heads off the pincers could still save the day. This meant I could work the pallets quickly with the crowbar and hammer and revert to the pincers when I had a stuck nail.

When the wood was planed, much to my surprise some were hardwood: keruing, meranti and nyatoh. Some were almost scrap wood (and rightly so given most are burned), part-bark or knotty but a lot were usable. Meranti is endangered; it seems almost criminal to burn it.

In secondary school (high school) I did three years of Industrial Arts. It is a little like trade school- we did electrical wiring, engine maintenance, metalwork and woodwork. I loved the wood work and became really good at it. It helps if your family has a hardware store and you can get your lumber replaced when you mess your project up.

I approached my new hobby like I do my design: I searched the Internet. It was a real eye-opener. Back in the 1970s we used hand tools: jack planes, mitre gauges, set squares, handsaw, chisels. Now there are power tools for everything and you can work really fast. There are power jointers, table saws, power sanders, jigsaws, circular saws. For measurement you now have lasers which actually trace out a true line on the workpiece itself without marking it.

And youtube now has a video for nearly any aspect of woodwork, some by master carpenters. Instructables has some really good designs with complete instructions. It is good to be alive.

I bought a power jigsaw- I thought I would start small in case I lost interest in it. That enabled me to repair a long-broken shed door and seal up the shed so that rats could no longer set up there.
Power Jigsaw

Next I got a power handplane. That was less satisfying- youtube had not reckoned on tropical hardwoods. In no time the blade was blunt and fairly skipped over the hardwood like a water skier. The jigsaw suffered less - it was capable of cutting through metal.
Power plane
That dented my confidence in the new power tools. I had planned to get a circular saw next, but the circular saw looked like a very dangerous bit of kit (danger is relative - I have a chainsaw for over 20 years now) and I had visions of it jamming on tropical hardwood, kicking back and amputating some critical piece of anatomy.
Circular saw can kick back
Remembering my success with the pincers, I went old-school. I bought a tenon saw instead.
Old school: tenon saw
I practiced the youtube master carpenters' techniques on pallet wood with some success, starting on the foreign temperate soft woods. The hardwood was extremely tough going, especially an antique piece of chengal (chengal is nearly extinct in Peninsular Malaysia. Our family store used to sell it but I have not seen it for 30 years). The chengal was so hard the tenon saw was heating up like it was sawing metal. I was not going to give up on it. 

Razor sharp: Bahco Superior 2600

I got out the sharpest saw I have, a Bahco Superior 2600 which for 20 years I have been using to trim hardwood trees in the garden. That did the trick: between the youtube sawing techniques and the Bahco I could make true cuts without getting too tired.Because the Bahco saw groove was quite big, I needed to be very careful marking the wood- it is easy to end up with a piece that was too small.

I needed something to replace that power plane, and was looking for the only thing I was familiar with, a Jack Plane. But the power planes are all the rage these days and the jack plane was more expensive (over RM300) than its powered replacement! And it took two weeks to arrive.
Jack Plane

Happily I found an extremely cheap and suspect pair of hand planes from my favorite neighborhood hardware store. They were so cheap and nasty (RM40 for two) that the proprietor was reluctant to sell it, fearing I would have a bad experience with it.

Cheap and cheerful
True enough the handle was too small and skinned my right hand after a day's use. And the depth setting would not hold when in heavy use, i.e., when used on hardwood. Maybe it was because I did not expect much from the planes, but they did the trick and finished up where the power plane failed. I had to sharpen it a few times a day, but I was already good at sharpening (another youtube skill). The constant dismantling also made the wandering depth setting a little more tolerable.

I was all set. First I needed a workbench so the first batch of reclaimed wood became just that.

Palletwood workbench

Next I made a little stool to go with the bench. This time instead of building it with butt joints and holding it together with steel screws I got a little more ambitious and went for lap joints and wood glue. The glue was a revelation. It was incredibly strong, stronger than the wood and hardwood at that.

I had to relearn my jointing and sawing; the stool ended up a little squiffy but was very strong.

That was August. It is now mid-November and the rainy season means I am indoors a lot and pallet woodwork is starting to look inviting again. I thought I would try for another table, but this time better finished, even stained and polished. I put in an online order for that Jack Plane.

The tabletop is mostly 4"x0.5" pallet planks planed true by hand and glued together. It is a little rough in spots because of the odd knot and because I had failed to match the grain when I lined up the boards to be glued. But it is mostly there and I figure it can be smoothed with a sander.

Palletwood table top. Note the magic glue. You can never have too many clamps
 But I would get to try out my new sash clamps. Another revelation: the old ones were very heavy and expensive. These new clamps are a dream.

Because of the size of the top, the plane was to hold it in place with glue, then reinforce it with a few steel screws. Fastening hardwood with screws with precision was unexpectedly difficult. The holes need to be drilled in advance or the wood might split especially at the ends.
More power! The battery powered drills do not play well with hardwood.

More often the wood was so hard the screw heads simply stripped or the screw got stuck. There are very few thing more disheartening than stuck screws. Another unpleasant surprise was a stuck power drill (used as a power screwdriver) can blow the house mains fuse, but mostly you just released the magic smoke.

Going back to basics was not an option this time. Using a hand drill on hardwood is far too exhausting.
One for the museum: a hand drill

After the glue was applied, aligning the holes became difficult, after which the screw might again get stuck. Sometimes a screw does not penetrate the second piece properly and when forced in can act like a little crowbar and pry the pieces apart.

Then there is the drilling. Power drill bits for woodwork was unexpectedly difficult to buy, especially the smaller sizes. And the smaller bits are the ones that tend to break. After breaking all the bits in a single session I ended up using bits meant for metalwork. These went in readily enough, but the flutes do not excavate the waste wood well enough, resulting in a stuck bit. Even the carpenter's pincers were no good on a stuck bit- the high-speed steel is too brittle and snaps off.

Eventually, I found the waste wood can be excavated by repeatedly withdrawing the bit. The advantage of the metalwork bit is that if the wood is too hard to drill properly, I can simply set the speed to high and the resulting friction simply burns the bit through the hardwood. This should be done sparingly to minimize the burnt area. Adding small amounts of WD-40 also seems to help. This is very hard on the power drill so you need a good one.
WD-40: your magic cure for all things stuck

The glue dries in 24 hours, so wish me luck. In the meantime, in the spirit of Tim Allen's Home Improvement, "More power!" to you.

Wednesday, 8 November 2017

Controlling the Raspberry Pi Robot Platform from an Android Smartphone

It is sometimes more convenient to control the raspberry pi robot platform from the smartphone.
Raspberry Pi robot platform with smartphone HTML RC control

Perhaps it is because I am now lugging around a 17" Asus X751L laptop.

There are several options. The quickest way is to ssh into the Raspberry Pi using an app like Juicessh. I can then reuse the C programs forward, left and right.

This turned out to be quite limiting, especially at my age. The smartphone keyboard and screen are really too small for the Linux command line interface to be used for a useful length of time.

But that's what rapid prototyping is all about. We build another one as fast as possible, preferably with available resources. Time for the next iteration.

Rather typing a separate command (in this case a bash script) perhaps it is better to make a program to issue direction commands on a single key press. This takes us to the C program arrowkeys.c

The process is really quite quick and simple: I just googled for the code, starting with general terms lile 'linux', 'keypress', 'C language'. C just happened to be the language I am most familiar with. 'python' or your favoorite language should work just as well.

This search leads me to ncurses, the library that I need. We refine the search further by adding 'sample' and 'code', and this time google leads us to to the function I need, wgetch. This in turn leads us to the article 'A Simple Key Usage Example'. I copied the code wholesale, and just had to add the C library stlib.h so that the keypress code can use system() to invoke my direction programs.

            There is the program. You compile it thus:
gcc -lncurses -o arrowkeys  arrowkeys.c

 *                                                                            *
 * Simple program to issue motor commands in response to keyboard arrow keys  *
 * Copied from:                                                               *
 *                  *
 *                                                                            *
 * 2017-10-24 CM Heong                                                        *
 *                                                                            *
 *                                                                            *
 *                                                                            *
 *                                                                            *
 *                                                                            *
 *                                                                            *
 *                                                                            *
 *                                                                            *
#include <stdio.h>
#include <ncurses.h>
#include <stdlib.h>

#define WIDTH 30
#define HEIGHT 10

int startx = 0;
int starty = 0;

char *choices[] =
  "Back    ",
  "Left    ",
  "Right   ",

int n_choices = sizeof(choices) / sizeof(char *);
void print_menu(WINDOW *menu_win, int highlight);

int main()
  WINDOW *menu_win;
  int highlight = 1;
  int choice = 0;
  int c;

  cbreak();     /* Line buffering disabled. pass on everything */
  startx = (80 - WIDTH) / 2;
  starty = (24 - HEIGHT) / 2;

  menu_win = newwin(HEIGHT, WIDTH, starty, startx);
  keypad(menu_win, TRUE);
  mvprintw(0, 0, "Use arrow keys to go up and down, Any other key to exit");
  print_menu(menu_win, highlight);
    c = wgetch(menu_win);
      case KEY_UP:
         system("/home/heong/piface/piface-master/c/forward 100");/*2017-10-31*/
      case KEY_DOWN:
      case KEY_LEFT:
         system("/home/heong/piface/piface-master/c/left 100");/*2017-10-31*/
      case KEY_RIGHT:
         system("/home/heong/piface/piface-master/c/right 100");/*2017-10-31*/
        highlight=n_choices; /* exit */
    print_menu(menu_win, highlight);
    if(highlight==n_choices)  /* Exit chosen - out of the loop */
  mvprintw(23, 0, "You chose choice %d with choice string %s\n", choice, choices[choice - 1]);
  return 0;

void print_menu(WINDOW *menu_win, int highlight)
  int x, y, i; 

  x = 2;
  y = 2;
  box(menu_win, 0, 0);
  for(i = 0; i < n_choices; ++i)
  {  if(highlight == i + 1) /* High light the present choice */
    {  wattron(menu_win, A_REVERSE);
      mvwprintw(menu_win, y, x, "%s", choices[i]);
      wattroff(menu_win, A_REVERSE);
      mvwprintw(menu_win, y, x, "%s", choices[i]);

Now arrowkeys worked great on the laptop. But on the smartphone, I had to take my eyes off the robot and look at the screen, and this gets wearing very quickly as there a a lot of motion commands.

What I need is just 3 very big buttons, for forwards, left and right. The obvious way is to use an App, perhaps even write one using the MIT App Inventor.

At this point my smartphone,a Nexus 5 failed. I quickly reverted to my trusty Nexus 1, but in my haste to install the SIM card, I broke the phone's SIM connector. The second backup is a Leonovo A390, which did not have much disk space left after installing Whatsapp.

But we can work around this: if I ran a website from the Raspberry Pi, I can invoke the C motion programs from php, via the function exec(), very similar to the trusty system() function.

This means however I have to come up with the button program in html. The added advantage is it will work both in the laptop and the smartphone.

As you suspected, it is back to google. 'html', 'button' and 'system' eventually led me to the 'form', 'exec' keywords. From there the search narrows down to w3schools.

Not knowing web programming should not stop you: it didn't stop me. If you have a background in at least one computer language you should get by. The result would not be pretty code, but you will have a workable (well, sort of) prototype you can show as plausible progress.

From there on, a full day's frobbing to get the buttons screen just right, in the process discovering CSS 'style' in the process. The resulting program, robot.html and upbutton.php:

$cat robot/piface/piface-master/robot2/robot.html
   <!-- \/ starthtml -->
   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
   <META NAME="keywords" CONTENT="Heong Chee Meng electronics engineer Android Raspberry Pi Robot Platform Control">
   <META NAME="description" CONTENT="Heong Chee Meng's robot control website.">
   <META NAME="author" CONTENT="Heong Chee Meng">
   <TITLE>Heong's Robotic Control Website</TITLE>
Heong's Robot Platform Control Website
<p style="float: left; width: 33.3%; text-align: center">
<form action="upbutton.php" method="post">
  <button type="submit" name="buttonu" value="Connect"><img width="180" height="180" alt="Connect" src="./upbutton.svg" align="center"></button>
<! </form>
<p style="float: left; width: 33.3%; text-align: left">
<form action="leftbutton.php" method="post">
  <button type="submit" name="buttonl" value="Connect"><img width="180" height="180" alt="Connect" src="./leftbutton.svg" align="left"></button>
<! </form>

<p style="float: right; width: 33.3%; text-align: right">
<form action="rightbutton.php" method="post">
  <button type="submit" name="buttonr" value="Connect"><img width="180" height="180" alt="Connect" src="./rightbutton.svg" align="right"></button>
<form action="bleh.php" method="post">

<!-- /\ end html  -->

$cat robot/piface/piface-master/robot2/upbutton.php
  if (isset($_POST['buttonu'])) {
    $result = shell_exec('ls -l upbutton.svg');
    echo "Done!<pre>$result</pre>";
  if (isset($_POST['buttonl'])) {
    $result = shell_exec('ls -l leftbutton.svg');
    echo "Done!<pre>$result</pre>";
  if (isset($_POST['buttonr'])) {
    $result = shell_exec('ls -l rightbutton.svg');
    echo "Done!<pre>$result</pre>";

You can get the button images from here. Put the files into a subdirectory 'robot' in your apache directory, which in Slackware should be:


You start the webserver with

chmod +x /etc/rc.d/rc.httpd

/etc/rc.d/rc.httpd restart

The next step would be to have the phone and the Raspberry Pi log into the same wifi hotspot. This is straightforward if you are at home, just have both your Pi and smartphone log into your wifi hotspot.

If you are on the move (say you need to demo your new prototype at a client's place), just set your smartphone to be a wifi hotspot and have Raspberry Pi connect to it.

If you use static IP (say your Pi is or if you use a DHCP server, the command

dhclient -v wlan0

will display the Pi's IP.

From there it is just a matter of typing in the link into your favourite browser - I used Firefox:

By now I have a spanking new Samsung Note 5, which unhappily was slimmer than the stack of RM50 bank notes needed to buy it.

After playing RC car with the robot (I've always wanted one!) for a while it would be nice to be able to do this remotely, like, over the Internet. This would have telepresence features. Happily, you just need to configure your home wifi modem router to host the Raspberry Pi website, and the same setup should work.

Now that I have the Note 6 I just needed to complete my search for the Android App to do ssh commands with big buttons. The first hit for 'ssh', 'button', 'app' turned up HotButton SSH. Now this should be a lot less painful to get working than html and the only damage would be to my pride.

The HTML version's advantage is that it is the same whether you used a desktop, laptop or a smartphone. Best of all, it is easy to link up as an Internet of Things (IoT) device. If you were deploying an interface for, say an MRT SCADA system for both the Station Control Room as well as mobile workers this would be an advantage, especially with training costs.

The moral here is rapid prototyping simply uses the resources on hand. Time is the essence- often it is much easier to find out the faults if you (or the customer) have some form of the prototype to work on. The individual motion programs were not suitable for repeated use, and arrowkeys.c although easy to do (with my skill-set) proved OK for laptop use, but using a laptop proved inconvenient.

It sounds trendy. Indeed DevOps uses a similar approach for its 'Continuous Delivery'  portion, but this approach would sound familiar in the US during the Great Depression.

Happy trails.

Sunday, 29 October 2017

The Wild Wild East: Perils of Online Shopping

Fresh from the heady successes of the low-cost Arduino parts, all purchased online, I bought a power bank which not only puts out the standard 5V but 12V, 19V and can even jump-start the car.

Good deal? Note the 30000mAh capacity listed
MY55MART the seller at lelong promised a 30000mAh lithium power bank. The link for the product will probably not be up for that long, but at the moment it is still here.

It arrived very quickly and the first indication something is not right was that it was lighter than my 20000mAh power bank. The original China manufacturer's printing on the box does not mention 30000mAh.

The manufacturer does not mention 30000mAh
When unboxed, the product looked the same as the picture on the original link, down to every last accessory. I topped up the charge overnight.

The next morning, I tested it on my laptop, an Acer AspireF15 with a battery low on charge. Set the power bank output to 19V and it started up well, and proceeded to charge the laptop as well as a computationally-intensive kernel compile. So far so good. After about an hour the power bank was still going strong but the charge indicator on it went from 4 bars to 3. That is 25% for an hour. That seems a little fishy.

Lithium batteries capacity are usually rated at the lithium cell voltage, 3.7V. It should really be rated at nominal output voltage, 5V like a lead acid battery, but oh well.

Now capacity changes depending on the rate of output. I intend to compare it against a 20000mAh as well as a 8000mAh power bank. Useful load would be that drawn by a Raspberry Pi with a Piface cape, about 360mA.

The plan would be to power up a Raspberry Pi with its Piface cape, and print a message every 20 minutes or so until the battery runs out. I topped up the charge again, overnight.

Power bank capacity test: Raspberry Pi and Piface as load. Note the network cable connection to LAN

The voltage and current is checked (but not recorded) using a USB Charge doctor, as the load is largely the same at 360mA.

Note the Charge Doctor reading the load current at 360mA
 The program is simply a bash script. Just ssh into the Raspberry Pi via its copper LAN: 

ssh -t xx.xx.xx.xx

Set the date and time - the Pi does not have a realtime clock:
root@modem:/home/heong# date 1101094317
Wed Nov  1 09:43:00 MYT 2017

Notice here I have set the date wrong (it is actually Oct 29) but the time is correct.

The bash script is simply:

root@modem:/home/heong# while [ 1 ]; do date; sleep 1200; done
Wed Nov  1 09:45:50 MYT 2017
Wed Nov  1 10:05:50 MYT 2017
Wed Nov  1 10:25:50 MYT 2017
Wed Nov  1 10:45:50 MYT 2017
Wed Nov  1 11:05:50 MYT 2017
Wed Nov  1 11:25:50 MYT 2017
Wed Nov  1 11:45:50 MYT 2017
Wed Nov  1 12:05:50 MYT 2017
Wed Nov  1 12:25:50 MYT 2017
Wed Nov  1 12:45:50 MYT 2017
Wed Nov  1 13:05:50 MYT 2017
Wed Nov  1 13:25:50 MYT 2017
Wed Nov  1 13:45:50 MYT 2017
Wed Nov  1 14:05:50 MYT 2017
Wed Nov  1 14:25:50 MYT 2017
Wed Nov  1 14:45:50 MYT 2017
Wed Nov  1 15:05:50 MYT 2017
Wed Nov  1 15:25:50 MYT 2017
Wed Nov  1 15:45:50 MYT 2017
Wed Nov  1 16:05:50 MYT 2017
Wed Nov  1 16:25:50 MYT 2017
Wed Nov  1 16:45:50 MYT 2017
Wed Nov  1 17:05:50 MYT 2017
Wed Nov  1 17:25:50 MYT 2017
Wed Nov  1 17:45:50 MYT 2017
Wed Nov  1 18:05:50 MYT 2017
Wed Nov  1 18:25:50 MYT 2017
Wed Nov  1 18:45:50 MYT 2017
Wed Nov  1 19:05:50 MYT 2017
Wed Nov  1 19:25:50 MYT 2017
Wed Nov  1 19:45:50 MYT 2017
Wed Nov  1 20:05:50 MYT 2017
Wed Nov  1 20:25:50 MYT 2017

The difference between the last output time message and 09:39 would be taken as the duration of the load. Despite the printed start time of 09:45 the actual start time was recorded separately using my watch, as the Pi takes a little while to start up. The measurement error here is 20min.

If the power bank was indeed rated at 30Ah, 3.7V derated to 5V (neglecting the inefficiency of the power supply) means 30 x 3.7 / 5 or 22.2Ah. At consumption of 360mA this means 61.7 hours.

For a short while, maybe a couple of minutes on startup, the Pi actually drew 410mA, but this quickly settled down to 360mA. At shutdown it drew 170mA.

The Raspberry Pi stopped at 20:25 that makes 10.7 hours or 5200mAh (10.7 x 0.36 x 5 / 3.7), woefully short of the promised 30000mAh.

It does not mean the product did not work - it did power my laptop as well as charge an empty battery. It did jump start a car. The China manufacturer did not claim 30000mAh capacity, rather it seems to be the Malaysian seller doing it.

Here is another notice for roughly the same product by the same seller but without the contentious claim:

Such are the perils of online shopping in the Wild East.

Saturday, 21 October 2017

Using the long spoon: Realtek RTL8411 and Linux

I had a soft spot for Acer laptops, especially the Aspire range. They are cheap and cheerful and you can get models with CPUs that support native virtualization. They also use the same power adapter in all their models, and since I am forever forgetting to take the adapter with me, I simply leave one power adapter at likely locations where I am in danger of doing any real work.

But lately they have been failing after a year. The last three years have been almost continuous site work - two back-to-back major projects in KL (Q Sentral and MRT) each involved new designs (prototypes!). They did not like being lugged around every day in a heavy rucksack with my toolbox and spares.

When my last laptop failed, I commandeered the wife's Asus X751L gamer's laptop. A year ago, I had resized the Windows partition and installed Linux on it, Slackware 14.1. It worked fine as a dual-boot, Windows for games and Linux for everything else.

root@x751l:/home/heong# cat /proc/version
Linux version 3.10.17 (root@hive64) (gcc version 4.8.2 (GCC) ) #2 SMP Wed Oct 23
16:34:38 CDT 2013
root@x751l:/home/heong# cat /etc/slackware-version
Slackware 14.1

I upgraded it to Slackware 14.2 and without a second's thought upgraded it to the latest Linux kernel, 4.13.8.

heong@x751l:~$ cat /proc/version
Linux version 4.13.8 (root@x751l) (gcc version 5.3.0 (GCC)) #1 SMP Thu Oct 19 18:
17:53 MYT 2017
heong@x751l:~$ cat /etc/slackware-version
Slackware 14.2

The wired Ethernet LAN stopped working. It would not connect, would not ping, nothing. Yet it had been working fine with Slackware 14.1 and Linux kernel 3.10.17. The driver, r8169 reported no errors with the hardware. The Asus X751L has a Realtek RTL8411 Ethernet Controller. Come to think of it, the previous laptop, an Acer AspireF15 had problems with the Ethernet Controller just after upgrade to Slackware 14.2 and kernel 4.8.7. With the Acer, the link would be fine at first but would randomly drop. It seemed better with some network switches, but it always dropped the link after a while. And it also used the Realtek RTL8411.

When I googled the problem, the solution seemed to be to blacklist the r8169 driver (kernel module) and use the r8168. Or use the Realtek Linux driver. There are hints of lame Realtek hardware, as the r8169 had worked fine before in the older kernels. Switching to r8168 seemed a lot of work, and it needs to be redone every time I upgrade my kernel (usually when needed to run new applications like docker). Switching to the  Realtek driver seemed worse. I try to avoid anything not in the mainline kernel.

Running with the lame Realtek hardware hunch, this link suggested to boot into Windows and flip the 'LAN Auto-negotiation on Shutdown' setting in Device Manager. That seemed quicker, and while it went against grain to use Windows, I need to do it only once, and I end up with a clean mainline Linux.
When supping with the Great Satan of software, you  need a long spoon.   

So I booted into Windows, found the 'LAN Auto-negotiation on Shutdown' setting and flipped it. And it works - on booting back into Linux, the wired Ethernet works, just like that. And the link proved stable over the weekend despite a few hundred gigabytes of data transfer.

Thinking back, that turned out to be the cure for the Ethernet instability problem in the Acer Aspire F15 too. Except I had not recorded the fix in my journal, which runs on Linux, and the fix was done in Windows. I guess it is cumbersome working with Windows if you have one hand holding your nose all the time.

Well, fool me once

Saturday, 14 October 2017

Toshiba 32PU200 TV as media player that does not suck

Lame: Toshiba 32PU200
My eyesight is not getting any better, so some years ago, I started using Full HD (1920x1080 resolution) TVs as desktop monitors. This is not ideal unless you sit further away from the TV. The TV tends to be to big to fit on a desktop(especially if you mounted more than one!) so the 32-inch Toshiba 32PU200 was a reasonable compromise.

It worked well for me for a few years- I now have three screens at each workstation: a monitor, TV and the laptop screen. Two of the TVs in the study failed from lightning strikes. In both cases they damaged the TV's HDMI interface so that the laptop or desktop can no longer send images to the TV.  However, they still worked as TVs, except I no longer watched TV much.

Repair proved difficult: the designed boiled down to just one huge IC(Realtek RTD2668 LCDTV controller), and its replacement involved hand-soldering 128 pins of 0.5mm pitch. This would be a couple or hours work with the microscope. But the TV was supposed to make less work for my eyes.

Realtek LCD TV controller RTD2668
I started using the 32PU200 as a media player in the bedroom. It has a USB port which will accept a thumb drive, except it turned out to be rather lame: it used Microsoft NTFS file formatting, and worse seemed subject to the usual inexplicable random Microsoft handicaps. It would not play some movies. Some movies caused it to go into a permanent reboot loop. Not to mention the usual random hangups.

Defenestration is not an option. To get around this I used mencoder (mencoder comes with mplayer which is standard issue for Slackware 14.2) to re-encode the problem movies on my laptop before transferring them to the thumbdrive (I use a Sandisk Ultra for high speed). mencoder with pretty much default settings produced immediate results:

mencoder BabyDriver.mkv -o BabyDriver.avi -oac pcm -of avi -ovc lavc

It was so fast, mencoder can be (and often is) used to re-encode and stream movies on the fly. But now and then I get a really good quality movie and the above settings resulted in rather poor blocky colors. For cases like these the re-encoding can take as much as four hours but the results are quite satisfying.

First you need to calculate the bitrate. The formula is

optimal_bitrate = 50 * 25 * width * height / 256

For the 32PU200, width is 1920 and height is 1080, so my best bitrate is 10125000

For best quality we go for a two pass method (you run mencoder twice on the same file). This lets mencoder do really well on the action sequences, explosions, etc.

Now the mencoder command becomes:

mencoder ./BabyDriver.mkv -o ./BabyDriver.avi -oac lavc -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=10125000:v4mv:mbd=2:trell:cmp=3:subcmp=3:autoaspect:vpass=1 -vf hqdn3d=2:1:2

For the second pass the command is mostly the same except we use vpass=2

mencoder ./BabyDriver.mkv -o ./BabyDriver.avi -oac lavc -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=10125000:v4mv:mbd=2:trell:cmp=3:subcmp=3:autoaspect:vpass=2 -vf hqdn3d=2:1:2

Notice the file has ballooned to almost double the size:
-rwxr-xr-x 1 root root 2.3G Oct 15 01:41 BabyDriver.avi

The original being
-rw-r--r-- 1 heong users 1.2G Oct  1 16:14 BabyDriver.mkv

The picture for the most part is quite satisfying, and the TV gets a reprieve from the scrap heap for now.

Happy trails.

Friday, 13 October 2017

Eyes on the prize: Raspberry Pi robot gets a camera

Cheap Mobile Camera: MoboCam

As a mobile camera, the smartphone is hard to beat: it has two cameras, autofocus, front light, backup battery and best of all, virtually no additional interfacing 'glue' hardware. I used my old Samsung Nexus 1, and set it up to log into my WiFi.

To stream video back to my laptop, I used the App IP Phone Camera by Deskshare. To link to it I simply point my browser to the Nexus 1's WiFi IP address and port 8080:

Camera and platform is controlled from a laptop
 Typical front camera view:

Let sleeping dogs lie: will they be replaced by AI?
Rear-facing camera view:
MoboCam looks back ...
The nice thing about this is I get to postpone putting in encoders (and the attendant interfacing circuits), motor drives, control software and jump straight to the fun stuff.

The control commands are much the same (see previous blog post):

Command line interface: a proper GUI has yet to be done

 As usual, the smartphone is attached to the platform with a small cardboard box (the same one the Arduino parts came in), duct tape and scotch tape. The smartphone needs to be easily removed and mounted in order to start the app.

It needs to be reasonably rigid: positional accuracy is important to navigate the house. Barely one hour later, assembly was complete and MoboCam made its first remotely-controlled sortie from its birthplace: the study.

First sortie: MoboCam needs to traverse a corridor
It went down a 1m wide by 5m long corridor with no difficulty, mainly because it could center on the bright window at the end. Turn to the left and MoboCam sees its first light of day.

Light of day. Notice Mark I mobile alarm system on front guard duty.
The platform sorely needs two more wheels. It gets stuck very easily: even the thinnest doormats gets stuck on the front and back supports. And it would be nice to be able to reverse.

A dedicated program needs to be done to issue Piface commands on pressing the keyboard arrow keys. A surprising amount of turning was required to orientate myself.

The wheels needs encoders or tachometers to measure distance traversed. This makes it able to be programmed to travel to specific waypoints.

There you have it: the cheap Raspberry Pi robot platform becomes a camera carrier. Possibly applications are a telepresence robot, a mobile house alarm platform and best of all, a fun toy.

In case you are wondering, here is what a cheap Raspberry Pi robot looks like when it is not made from cardboard and duct tape: the Dexter Industries GoPiGo (USD200 or RM840):


Happy trails.

Monday, 9 October 2017

Arduino and the Robot

Arduino and the Robot Video (Youtube)

A few years ago, I bought a cheap plastic robot platform to play with. I bolted on two 12V geared motors, a Raspberry Pi with a WiPi WiFi USB dongle and a PiFace Digital,relay board and could drive the platform about. It trailed a 6m power cord. What I needed was a battery-powered system that actually lasted more than 5 minutes.

Unfortunately in 2011 I could not get lithium batteries easily, and so I used lead acid batteries instead. The batteries that were big enough were too heavy for the little platform and they cracked it. The few lithium batteries I had could not last long enough for the Raspberry Pi to power up.

The robot platform languished until I discovered recently power banks and Arduino parts are very cheap and you could buy them online. Enter the Arduino XL6009 5V to 12V converter:

The Arduino XL6009 costs a mere RM4.50
Together with a 20000mAh lithium power bank, which can cost as little as RM70 (I bought mine for RM87) I can now restart the robot platform project.

Rasberry Pi robot platform components (Raspi, Piface, WiPi, XL6009 and power bank) for assembly
Control and extra processing power for is from my Acer laptop. I expect to ssh via WiFi into the Raspi and execute the motor commands using a python script. The Piface relay board do nothing more than connecting 12V to the motors on command. Imaging, GPS and audio will be from an old onboard Android Nexus 1 smartphone, long put aside for a Nexus 5.

 The two motors are Cytron spg30-300k, rated at 12V 430mA (equivalent to 1032mA at 5V) each. Assuming the Raspberry Pi takes 160mA, that is 2224mA. The power bank should last 9 hours at full power. I expect the consumption to be a lot less mainly because it will be moving less mainly for the control program catches up. Anyway I do not expect the flimsy chassis to hold up for 9 hours.

But first, the XL6009 needs to be set correctly. Wire up a USB connector to it. You can cut a USB cable and find the 5V and 0V lines by measurement. Or you can use this:

USB connector pinouts
Or if you have recently discovered Arduino, you could buy an Arduino USB connector breakout PCB for RM2.50:
 Connect the USB connector to the XL6009 inputs and set the potentiometer until you get the right voltage output. My XL6009 was preset to 24V so I had to do a fair number of turns to get it down to 12V.

Setting the XL6009. For convenience I have connected voltmeters to the input and output

The power bank has 2 USB output ports, one at 2A and the other 1A. I connected the 2A output to a Raspberry Pi with a Piface Digital Cape as well as the WiPi WiFi dongle. The assembly took some 400mA at startup and between 100-300mA after.

I first tested the program 'dry', without the motor 12V power. You can tell if the relays are clicking on - besides the sound, there is a corresponding output LED.

Next I connected up the XP6009 to the power bank 1A output. The first time I tried it crashed the WiFi connection to my laptop. It rebooted OK after. Next to reduce the load on the motors, I raised the wheels off the floor so they spun free.

The first time I pulsed the motors on for only 20ms, and that was enough to drag the power bank output down and crash the Raspberry Pi.

Despite lifting the wheels clear, the motor gears must still present a considerable load. I needed to reduce the motor current. 1A seems a nice round number, and if I put a 5R 5W resistor at the 5V input to the XL6009 this should do it. But I only have a 2R7 resistor, and in the interests of expediency I used that, but swapped the motor power to the 2A power bank output.

Raspberry Pi Robot platform, assembled in glorious duct tape
The program is simple. You need the C library supplied with the Piface.

root@piface1:/home/heong/piface/piface-master/c# cat forward.c
#include <libpiface-1.0/pfio.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char* argv[])
  int ontime=300; /* milli-seconds */

  if ( argc != 2 )
    printf("Usage: %s ms\n", argv[0]);
  sscanf(argv[1], "%d", &ontime);
  pfio_digital_write(0, 1);
  pfio_digital_write(1, 1);
  printf("Sleeping %d milliseconds\n", ontime);
  pfio_digital_write(0, 0);
  pfio_digital_write(1, 0);

The command to compile is:
 gcc -L/usr/local/lib/ -lpiface-1.0 -o forward forward.c

To run, you ssh into the Raspberry Pi:
ssh -t 172.16.xx.yy

I find a 200ms pulse produces a reasonable step:

./forward 200
Sleeping 200 milliseconds
For the great finale the wheels were lowered to the ground and the and the command was executed as many times as necessary.

A very simple mod would allow you to make right.c and left.c when direction changes are required. And free Android apps are available to trigger the Pi commands.

The mechanical bit leaves much to be desired: the heavy power bank did not sit square over the wheels, so a left turn is much easier than a right turn. It needed two more wheels rather than those noisy screw heads, and it wobbled horribly, shaking lose its connectors after a few minutes.

And yet, it finally managed to lose its power cord tether and it moved fast enough to alarm Sidney the cat.

There you have it, a cheap robot platform prototype 6 years in the making, finished in one weekend.

Apart from the shakey construction, the power bank needs to be down-rated, and the PiFace Digital needs to be swapped out for a proper motor driver. Given that the processing is done from a host via a wireless link, a Raspberry Pi is overkill; a bluetooth PIC18F14K50 should do.

So, back to the drawing board, back to the pachinko.  In the meantime I see a bright future for the first prototype as a back porch prowler, scuttling back to the solar battery to recharge when low.