Tuesday, September 26, 2017

Research Links on Weight Loss, Nutrition and Fasting

I began researching weight loss approaches and fasting in particular in early 2017. Here are some links for the sources that I found most informative. I used periodic fasting (ranging from not eating until dinner time all the way up to having a meal Sunday evening and not eating again until dinner on Friday). 

I lost 40 pounds (and have kept it off for a year). I also used fasting to help improve my concentration when studying for and taking the USPTO Patent Bar Exam (I passed!)  I hope you find this information helpful.

Forks over knives article on fasting

Experiments in intermittent fasting by an athlete who is already in great shape and eating well. 

Interesting paper on metformin impact on blood sugar and weight loss

Dietary restriction with and without caloric restriction for healthy aging

Health Impacts of Calorie Reduction

Fasting Weight Loss Paper

Investigation of Starvation Mechanisms

Why fasting bolsters brain power.

Why does fasting boost learning?

Intermittent Fasting and Weight Loss

Write up about a supervised 382 day fast, patient lost 276 lbs.

A History of Modern Researchinto Fasting, Starvation, and Inanition

Interesting fasting information collected from several reference sources

Good video with links for references on Longevity and eating one meal a day.

Is Ketosis Dangerous?

Fasting versus eating less.

We should never have told people they could 'burn off' calories with exercise.

Where does the fat go when you lose weight?

Cancer cells use glucose for energy to build with amino acids

Friday, June 02, 2017

12V Cellphone and GPS Socket for 6V Positive Ground Studebaker

The Car

Sam (my Step-Father) has a 1952 Studebaker Champion that he has restored. During one of our too infrequent visits he was showing me his latest work when I noticed a small 12V battery (like you would find in a UPS or alarm system) in the trunk with a cigarette lighter socket attached via a short cable. He explained that the car had a 6V positive ground electrical system and he used the 12V battery to power his GPS when he drives to car events and for charging his cellphone while he is in the car. He said a 12V outlet for the car would be nice and asked if I thought I could build one. Challenge accepted!

Sam's 1952 Studebaker Champion
Design Steps

Initially I used electrical tape to insulate the power socket from the metal dash (which is at +6V) so the body of the socket could be connected to battery negative. This allowed the use of boost converter to generate 12V from the 6V battery.
First attempt insulated the power socket from the 6V positive ground metal dash.
While this worked and was installed in the car for over a year, insulating the outlet was an extra step and failure of the insulation between the socket and the metal dash paneled seemed to be a likely failure point. Before sharing the design I wanted a more robust solution that would be easy to install.

I considered a fully insulated power socket but could not find one that would fit the existing dash opening. I also considered using a plastic bracket to mount the power socket but that would spoil the factory look the dash. Sam was so kind as to offer to use a pigtail socket that he stows under the seat when not needed but I was determined to find a way to use the existing mounting spot in the dash.

The eureka moment came when I wrote out the the system assumptions and requirements and noticed that devices plugged into the power socket make no other connections to the vehicle electrical system. This means that the power socket does not require an absolute voltage output, but actually needs only a 12 volt difference between the power socket center terminal and the body or chassis connected terminal. So if I apply 18V to the center terminal of the power socket, any device plugged into the socket will see 18V - 6V or 12V between the socket's terminals. Sometime just writing a spec can help set the direction for a project!

A search of Pololu's DC-DC Boost Converters found no 18 V boost converters but I did find the U3V50 adjustable boost converters. These small module have a 5A input switch and adjustable output (9-30 V) for $17. Notice that these modules are offered in several fixed voltages (but not 18V) and two adjustable voltage ranges. Be sure to get the higher (30V) adjustable range, U3V50AHV. Perhaps Pololu will offer an 18V option in the future.


Once I received the module, I added some wires, powered it up and dialed the voltage to 18V. The product page at Pololu has some great information about the module's efficiency. There is even a chart showing efficiency when set for an 18V output with several input voltages.

Looking at the chart we can see that a 5V input provides an 18V output at 1 amp at better than 80% efficiency. So our 6V nominal input should give us even higher output and higher efficiency. I tested the module with a USB car charger and a PortaPow USB Power Meter. The image below shows the unit providing over 10W while charging an iPad.

The module got hot before the current started dropping off as the iPad reached full charge but the module never reached the high-temperature cut-off. The Pololu module is very robust but I would not try to draw more than 1 amp from the 12V power socket. So no high power stereos or ham radio rigs. But you should be able to charge your phone or run your GPS all day long.

The Studebaker's existing lighter socket was power via a switched negative wire with a bullet connector on the socket center terminal and an empty spade terminal on the socket body (our positive chassis 6V power source). To make the installation easier, I added a different color wire to each of our module connections and a matching connector for each terminal. I also insulated the module with clear heat-shrink tubing.

Blue wire to the power socket center terminal (module Vout)
Green wire to the power socket center terminal (module Vin)
Black wire to switched negative terminal (module GND)

Installing the new module was simple, requiring only unplugging the existing wires from the socket and connecting those wires to the module. So we unplugged the wire from the existing socket center bullet terminal and connected this to the module GND wire. Then we connected the body/chassis wire from the power module to the tab on the light socket (electrically connected to the chassis positive ground via the metal dash). Finally the output voltage wire (boosted to 18V) of the power module was connect the lighter socket center terminal.

After inserting the connectors, the wires were bundled and zip-tied to the firewall. The install only took a couple of minutes. The interior appears stock other than a plastic socket cover that indicates that it is actually a 12V outlet.

The voltage of a conventional 12V automotive system actually vary over a wide range. Wikipedia says that "Equipment intended to be powered by the receptacle needs to account for intermittent contact, and voltages outside the nominal 12V DC, such as maximum voltage 9–16V continuously. To function in this environment, 12V automotive accessories are designed to operate over a wide range of input voltages. For example, the Amazon top selling Schoche reVolt dual USB car charger specifies an input voltage range of 10 to 16 volts.

I measured the output voltage under different engine conditions to get a feel for the range produced by the boost converter on the Studebaker. At key on with the engine not running the socket put out 12.75V. The voltage varies once the engine is running though because the generator output varies with engine speed. The voltage varies because the socket output is actually 18V - generator output voltage.  The socket voltage output dipped as low as 11 volts at some engine speeds. The module could be modified to produce a stable voltage difference of 12V but this appears to be unnecessary for the vast majority of applications.


Sam upgraded the install with a matching cigarette lighter plug and socket. He removed the heating coil to keep it from being able to make electrical contact with the power socket voltage.

The new lighter plug gives the dash a factory look while retaining the ability to power modern 12V electrical accessories. 


The module worked with every device tested and has been installed and working in the Studebaker for over four years now. If you want, it is simple to build your own 6V Positive Ground to 12V power socket converter.

1 - Order the Pololu Module (U3V50AHV)
2 - Adjust module to 18V
3 - Add wires, terminals and insulate the module (tape or heat-shrink)
4 - Install and enjoy!

I was pleased with the look and performance of the project. I hope this approach can help you solve your own power system design problems!

Wednesday, February 22, 2017

Creating a Stencil from a Bitmap Image

I began searching online for a Minecraft stencil when my son (5th grade) had a school assignment to find a way to earn money to donate to the Make a Wish Foundation. He wanted to use bleach to stencil tee-shirts with MineCraft artwork to sell to his friends at school. We supported his efforts and purchased a small supply of shirts from the local variety store (Dollar Tree).

We first tried cutting stencils using Freezer Paper and ironing that onto the shirt. It worked for some shirts but the bleach had little impact on some colors. So back to the craft store for some fabric spray paint. The freezer paper stencils did not hold up well when the kids used the shirt spray paint. The stencil wanted to peel off of the shirt. We discussed coming up with a reusable stencil that would give us more detail and hold up better. 

This seemed like a great job for the laser cutter but I was not sure how to make a stencil. It took an an entire evening of working with a drawing program but I finally figured out a process that seems to work. Here are the steps I followed.

First, find a bitmap of the Minecraft item that you like. I used a Google Image search to find the image below. 

Here is how that image appears in CorelDraw. I will leave all of objects selected to make it more clear when we shift between a bitmap and objects. 

Next use your favorite drawing program to auto-trace the image. For CorelDraw you can get good results using Trace: Outline for High Quality Image. Move the Detail slider all the way to the right to ensure you get all of the squares. Smoothing did not seem to matter and I used 0 (slider all the way to the left) for Corner Smoothness. If the tracing went well you will get a group of objects that looks similar to the original image. Note the new selection handles for the newly created objects.

Next select all of the traced objects and apply a black fill.

Now change the Outline to 8.0 pt, solid line, in white.

This looks like a stencil and can be used if you want to print it and cut by hand. I read that you can get great results if you print on card-stock and laminate the card-stock before cutting the pattern out with an Xacto knife. But I want to use a laser cutter so there are still a few steps left. 

The laser cutter wants lines showing where the beam should cut. So we want lines that define the outline of the black boxes in the image above. But those black boxes are actually the fill inside the boxes defined by the 8.0 pt white rectangles. So we need to convert the fill of each square into it's own object without the white outline. 

I suspect there are easier ways to convert the black fill to objects but I did it by converting the objects to a bitmap (150 dpi, Black and White, 1-bit) and then tracing the new bitmap. Below is the bitmap produced when you convert the objects to bitmap. 

Next we Trace Outline for High Quality Art.  Set the Detail slider full right, and both Smoothing and Corner smoothness full left. You should get a group of objects like shown below. Again notice the selection handles for the new objects created by tracing.

Finally, we select all of the objects and set the Outline to Hairline, solid black line, set the fill to none and adjust the size to match the desired stencil size. You are limited only by the cutting bed size of your laser cutter. Here is the pickaxe on a letter size sheet. 

Finally save in the preferred file format for your laser cutter, I used DXF, and you should be ready to cut the stencil on your laser cutter.

The laser will cut along the lines, giving you a stencil. I ended up using thin plastic sheet that worked well. Below are some photos of the stencils and shirts the kids make using them. The green images are fabric paint. The lighter images were made applying bleach to black fabric.

We were pleased with the results. I hope this workflow can help you create your own stencils!

Sunday, February 12, 2017

Charging LEGO EV3 and NXT FLL Robots with a USB Cable

Diagnosing the performance of a robot when programming missions for a FIRST LEGO League challenge is always interesting. You think about tire slippage, did the robot move too far before a turn or should it turn a little more? Another variable that can come into play is the charge level on your robot's battery.

A robot's performance is most consistent when operated from the same battery charge level each run. Some recommend using batteries  at 80% charge for the ultimate uniformity but this seems to difficult to achieve in regular use. The lowest effort way to ensure consistent state of charge for a robot battery is to always keep them charged. But swapping batteries or getting a robot back to an AC charger between FLL rounds is not always convenient. I wanted an easy way to charge a robot between rounds and came up with this USB charging cable that I will show you how to build. Spoiler alert, there is a surprise ending.

Charging LEGO Batteries

All LEGO robot batteries have internal charge circuits that control the charging current and voltage. The external power adapter only supplies power to the charging circuit inside the battery pack. The official LEGO charger is listed on their website as a 9V charger but is actually labeled as having a 10V output with a capacity of 700 mA.  The LEGO batteries I tested appear to draw around 600 mA during charging when powered from a 10V source. I suspect the 1V higher output voltage and 100mA higher output capacity on the charger are engineering margins select by LEGO to ensure the batteries and chargers work even under worst case conditions.

So we should shoot for providing 10V and should be able to supply around 700 mA. We can also calculate that the 600 mA current observed during charging we should be able to return about 600 mAh back to the robot in the one hour between rounds. And I would like to be able to power the charger using a USB battery pack.

Designing the Charger

So I need to find a way to convert a 5V from a USB battery pack to 10V for the LEGO battery pack. My go to source for prototyping with DC-DC converts is Pololu.com and their model #799 Adjustable Boost Regulator seems like a good match and is only $12. There is another Pololu boost converter, the U3V12F9 that is cheaper, only $4 but leaves little performance margin. I will pay a little extra for some extra operating margin since this is a prototype. You should always prototype first for function and optimize later after validating your operating envelope. For comparison, the 799 has a 2 amp input switch rather than the cheaper unit's 1.4 amp input switch. 
Pololu Pololu Adjustable Boost Regulator 4-25V

The 799 needs a minimum input voltage of only 1.5V and has an output that can be adjusted from 4V to 25V. The device has a 2A input switch (which means it can only draw in 2 amps of current and your output current capacity will drop the more you boost the output voltage). The performance chart below has a line for a 5V input and 12V output that indicates a peak output of around 700 mA (the green line). We will be boosting to only 10V so we will have an even higher current limit. 

Looking at the chart, we can see the efficiency improves as the input voltage gets closer to the output voltage. For a boost from 5V to 10V we can estimate an efficiency of 85% and an estimated output current of (5V/10V) * 0.85 or 850 mA. We only need 600 mA or so giving us a nice engineering margin. 

So now I only need the small DC jack that plugs into the battery pack and a USB cable that I can use to splice everything together. I grabbed one of the micro USB cables that seems to come with everything these days and used my digital calipers to measure the LEGO battery pack power jack. It turns out the DC adapter is a 1.35 x 3.5 mm plug. Below is the link for the part at Digikey, my favorite source for parts due to their great online search engine and amazing shipping speed. 

The Build

Incoming +5V from USB on right, 10V leaving to the charge plug on the left. Note that the wires were doubled up going to the connector on the battery pack end. The wires were already there, might as well use them. 

Battery connector soldered up ready for finishing. 
After adjusting the output voltage and verify everything worked, I applied epoxy to the terminals before adding the terminal cover. The epoxy helps spread the cable stress to prevent cracking the solder joint. I learned to use epoxy via multiple repairs of laptop power cords over the years. With epoxy it is a one time job rather than every 18 months. 

The adapter draws 1.41 amps when charging the LEGO EV3 battery pack. 
I used a PortaPow USB Power Monitor to measure the current draw when charging a LEGO EV3 battery pack. Note that the current draw of 1.41 amps is under 1,500 mA which is the minimum current spec for a port meeting the USB dedicated charger port (DCP). Most tablet USB chargers can provide the current needed to power this charger.

Measurements taken when charging the same battery pack at the same state of charge compared to the power draw from a bench top power supply indicate that the Pololu 799 boost-converter was around 84% efficient when charging the battery pack at 600 mA. This number is very close to our earlier estimated 85% efficient from the performance chart.

I added black hot melt glue to insulate and provide strain relief for the module.

After adding black hot melt glue to the other side.

After trimming one side. 

I applied big globs of black hot-melt glue to the final assembly (after calibration and testing) to protect the electronics and provide strain-relief for the cables. I use a silicon mat under the device when applying the hot-glue and fold the mat over and press down on the just applied glue to get it to flatten out. I had a nice thick barrier after a few turns of applying to one side then the other. I trimmed the edge of the glue with a small hand-plane to flatten them. I did not get a photo of the module after trimming the second side. It was still not a work of art but it was well protected by the hot melt glue. 

Other options include covering with Sugru or epoxy or even some adhesive lined heat-shrink tubing. But you do need to protect the electronics and keep the cables from applying stress to the solder joints. 

How Battery Capacity is Measured

The battery capacities mentioned here are milliamp hours (mAh). Generally a mAh rating tells you how much energy that battery can deliver to a load. So a 1400 mAh battery could deliver a current of around 140 milliamps for around 10 hours. The usable amount of charge in battery drops when you discharge them a higher currents do to internal losses. For example, the same 1400 mAh battery providing 1.4 amps (1400 milliamps) to a load would be expected to last less than an hour, probably less than 30 minutes.

LEGO has two different battery chargers for use with NXT batteries. The older gray batteries (1400 mAh) use a charger with a larger tip that outputs 10V AC, while the newer white batteries (2100 mAh) use a smaller tip that outputs 10V DC. The EV3 uses a new battery (2050 mAh) that is compatible with the LEGO charger with the small tip and DC output. I am going to show you how to build a charge cable that will let you use a high-current (at least 1.4 amp capable) USB port to charge your LEGO battery that accepts a DC input.

Why would a USB charger cable be useful for a LEGO robot? A battery's output voltage dips when load draw current. The larger the load the greater the current drop (measuring the drop in terminal voltage can even be used to measure the load). The drop in voltage gets greater as the battery capacity drops during discharge and can cause undesirable robot behavior.

You can start seeing odd behavior,when the battery is at a low state of charge and motor loads are applied. One reason is that motors typically have a moment of high current (and large voltage drop) right before the start to move. Under the right conditions, high load and battery that has only 1/3 of a charge left, the voltage can drop enough to change the motor's strength and response time. In some systems the voltage drop can also cause problems with the robot's controller and sensors. So anytime you see new problems or something that was working starts not working you should ask yourself if you are seeing performance issues due to low battery.

This high current condition is described as the motor's Locked Rotor Current (because the rotating parts of the motor have not started turning). A general rule of thumb is that a motor's locked rotor current will be about 5 times its normal running current. The chart below has data for EV3 motors and shows that the Locked current for the motors is around 5 times the free run motor current.

EV3 Motor and Sensor Power consumption


The chart above helps us figure out if charging between rounds would be enough to top off the robot's battery. First we need to calculate a worst case value for the power consumed during a round. Looking at the chart, a fully charged battery would be around 8.2 volts so we will use the 8.2V column of data. We can round the 1 Motor, 100%, Locked current from 0.955 amp up to 1 amp. Since the EV3 has 4 motor ports, we multiply that current by 4 to get a maximum of 4 amps. The table lists a running EV3 with sensors as drawing 0.123 amps. Let's round that up to 0.2 amps. So we have a total worst case current draw of 4.2 amps during a match.

An FLL performance run last 2.5 minutes, which is about 0.042 of an hour (2.5/60). So the energy used during the match is (2.5/60) hrs * 4.2 amps or around 0.176 amp hours or 176 milliamp hours (mAh). So to fully charge the battery we would need to be able to return 176 mAh of charge to the battery in the roughly one hour between rounds.

The battery charges at around 600 mA and even subtracting our worst case 200 mA for power the EV3 between rounds, we should be able to charge the battery at 400mA. If you can charge the robot for 50 minutes, in theory you could return (50/60)  * 400mA or 333 mAh which is close to twice our worst case drain of 176 mAh. So we should have plenty of time to top off the battery.

Note that you will likely operate your robot at less than 100% charge because charging slows as the battery approaches full charged. But you will be operating in the upper ranges of the battery state of charge and should start each match at similar conditions.

Usage Notes

It has been handy to charge the robot from a USB port. I expect the actual impact on the robot's FLL performance is minimal. I expect you would get more benefit from cleaning the robots tires. It is also easy to toss the USB charging cable in the box with the robot and always have it. I never kept a charger in the box before. Once I did charge the robot battery from a USB battery pack while the robot was boxed up in my trunk as we drove to a scrimmage. Early the morning of the event I realized that we forgot to plug up the robot after our previous practice.

Often we use a USB battery pack with a display that shows the amount of charge on the battery (similar to below). Note you need to be sure to use only the 2 amp port with the USB charger adapter. The display let us measure how much charge the battery needed before reaching full. This raises another issue though.


The problem with amp hours as a measure of battery capacity is that it neglects the battery voltage. The battery pack above lists a capacity of 6,000 mAh so you would think it could charge an EV3 battery pack (2050 mAr) around 3 times on a single charge. But the USB battery pack probably has a single 3.7V battery where the EV3 battery pack has two 3.7V batteries.

In reality the battery pack has a 3000 mAh capacity at the same voltage as the battery pack. And the battery back is stepping the 3.7V internal battery up to 5V, our USB cable is stepping the 5V up to 10V and then the battery pack is stepping the 10V back down to the battery's charge voltage. In reality we could expect this pack to provide a little more that one full charge for a fully discharged EV3 battery pack, But using our very conservative estimate of charge used during a performance run, the pack could keep the EV3 battery pack fully charged through at least 4 performance runs (2050 mAh / 420 mAh).

This is the reason that most larger battery packs are quoted in Watt Hours (or at least list the Watt Hours). Watt hours is just the amp hour rating multiplied by the voltage. So the 3.7V battery with 6000 mAh  capacity is 22.2 Watt hours. And our 7.4V (nominal) EV3 battery pack is 15.2 Watt hours. Watt hours lets you accurately compare the energy storage capacity of battery packs with different voltages.

Here is a nifty little tool that will let you measure the amount of energy put into the charging system. This is useful information with two caveats. First, the Amp-hours reported will be larger than the actual battery capacity due to the power loss in the USB-Boost conversion and in the charging circuit inside the LEGO battery pack. Second, the only time the battery needs a full charge, allowing you to get a measure of the actual capacity, is when the battery is fully discharged before you charge it. But if you use your battery down to when you start seeing issues with your robot, you can get a feel for the usable capacity of the battery. And you have a great way to compare two batteries when  you are concerned that one might have an issue.


Or Just Order One From Amazon for $12!

I contemplated ways to make it easier to build the chargers and started searching for USB voltage boost converters and cables with the correct plug. Eventually I found the item below at Amazon. For $12 you get a USB to power jack boost converter. Mine even came with an adapter that fit the LEGO battery pack. There are 9V and 12V version of the cable and both appeared to work equally well for charging the LEGO EV3 and NXT white battery packs. You can order extra 1.35mm power jack adapters just in case your converter does not include an one (or if you want to have a spare incase you lose one).



I hope you find a USB charger a useful accessory to help keep your LEGO robot charged and ready for action!

Friday, February 10, 2017

FIRST LEGO League Jr. - Teaching Engineering to 2nd Graders

FIRST LEGO League Jr is a non-competitive LEGO based program for kids in kindergarten through 3rd grade. Each year a challenge topic is announced and each team decides on an idea to address the topic problem and they build model with at least one simple machine to illustrated their proposed solution to the challenge as well as a poster to explain their solution. FLL Jr. is a great introduction to the FIRST organization, which provides a framework a programs to promote engineering concepts for kids of all ages.


I coached my son's FIRST LEGO League Jr. as an after school program (Triangle Math and Science Academy) when he was in 1st and 2nd grade (2012-2014). My goal was to help the kids learn a little about the engineering skills used when designing and building with Legos.

FIRST LEGO League Jr. Season

My son's team's idea was a fire-fighting robot that could put out fires in areas too dangerous for human fire-fighters. They called their robot the LSV for Life Saving Vehicle and their team name was Fire Destroyers. Their model used a LEGO WeDo program running on the laptop to drive a motor attached to a geared turntable that would sweep the fire suppressant nozzle back and forth.

At the end of the season events are held where teams share their projects with other teams, exchange buttons and present their projects to judges. The FLL Jr. event may be a stand-alone event or may be paired with an FLL event where older kids compete. The judges at our event included Sam Last, FLL Head Ref for North Carolina, and Fiona Last-Powel, the FLL Head Project Judge for North Carolina. Below are some photos from our team's event.

FIRST LEGO League Jr. Poster and Model.

There always seem to be last minute program changes. 

Working out the last of the kinks in the flow programming!

Explaining their model to Sam Last, FLL Head Referee for NC.

In FLL Jr. everyone gets recognized for their effort.

And a run through the high-five line with Sam and Fiona and the other judges. 

What Can I Teach These Kids

There were the easy lessons at first, do not grab things from other people and take turns. I had them practice leading build projects following LEGO instructions and they quickly learned that they have to listen and help when someone else is in charge if they want people to listen to them when they are in charge, a huge lesson! And we did experiments to compare the strength of beams of LEGOs in tension and compression. But soon I felt like I was running out of ways to teach them skills that would useful in an engineering career. 

It was a constant struggle to keep the 12 first and second graders on task. If you spend too much time with one group, the others were quickly building cars and trying to see which was faster. There were also frequent crash from cafeteria tables when a car veered off track. 

After our regular season had finished, near the end of our 2nd year I noticed that the kids were very excited when an older FIRST LEGO League team demonstrated their competitive robot. And the team had the same excitement when we attended a local LEGO Sumobot competition that Spring. There was something about robots competing head to head that got the kids excited. But how can I do this with young kids without getting bogged down with robot controllers and programming?

A possible solution occurred to me when my son and I were playing with the Lego Power Functions Kit. (This kit includes an Infrared Remote and IR receiver along with battery pack, motor, lights, switch and accessories. It is great value for $30!)


My son and I used the kit to build remote control cars at home and it dawned on me that if I added a second IR receiver and set both to the same channel I could use the remote to start two cars at the same time. Having a no contact method to start multiple cars would allow us to have the kids race cars side-by-side to see which was faster. Drag racing! I bet the kids will love this!


So I pitched the idea of racing cars to the whole group (six 1st grader and six 2nd graders) and they wanted to started right then! 

Applied Engineering Lessons

Having the kids design and build a car each week provides the opportunity to explain and explore many facets of engineering in terms the kids can understand and observe. 

Documenting Your Ideas
Public Speaking and Presentations
Collaboration and Persuasion
Building and Deadlines
Prototype Idea, Test the Design and Update the Design
Feedback and Optimisation

We started the process by explaining that when you are working on an engineering team it is important not just to have a good idea but you must be able to communicate your idea to others in a way they can understand. So we began by passing out pencils and paper and asking every student to draw something about their idea for a car. After 20 minutes we asked each child to stand up in front of the group and tell us about their idea and answer questions from the group. 

The rules of the presentations were simple, everyone's ideas are good, no one will criticize anyone else's idea or drawing and EVERYONE gets a round of applause after their 30-90 seconds of presentation. I was surprised how many of the outgoing (loud) kids were scared at the idea of sharing an idea with the group. It took some encouragement but everyone made it through the process of their first technical design presentation! And the oldest kids were in 2nd grade! This was awesome!

Next we divided the kids into two groups and told them to discuss their car ideas, select the design features they like and build a car (we changed the mix of kids each week). The teams had 30 minutes to build a car that we would race between two tape stripes on the floor, a distance around 4 feet. Exact distance and time were not a factor since we wanted only an A vs B comparison of who reached the line first. It was fascinating watching the kids promote their ideas and debate with their teammates over the benefit of one design feature over another. Doubly so after a few weeks and they began to build a knowledge base from their previous efforts. 

As the deadline loomed (5 minute warning, 2 minute warning)  the stress of delivering an engineering prototype started to show (teams with a complex design got frustrated). The first race was often won by the only team to bring a working car to the starting line! Amazing engineering lesson! Done beats a not done every time!

After the race the teams got another 15 minutes to update their cars before racing again. The kids quickly learned that complex designs with lots of gears and multiple motors can be difficult to get working. Simple is better. Another great engineering lesson!

In the following meetings we repeated the process and changed the grouping of the kids. In those last few weeks of school the kids had fun, experienced the thrill of competition and improved their building skills. They learned to build the cars not too tight or friction would slow them down, they learned about adjusting gear ratios to match wheel sizes and they compared direct motor drive, gears and belt drives and practiced working under the pressure of a deadline. They learned the importance of working as part of a group and how to negotiate features and quickly accomplish goals. They were practicing agile prototyping!

Conclusion and Recommendations

The new drag racing program was a success. The kids embraced the challenge, improved their problem solving skills and became considerate collaborators. They quickly learned many engineering lessons that I didn't figure out until after I had an engineering degree.

A great idea does little good if you can't explain it to others. 
You need to be able to promote your idea to your team. 
You must work with your team even if your idea was not selected.
Finished beats not finished every time.
Simple is better than complex.
Loose is better than tight when it comes to speed.

I feel that changing the mix of kids each week and only competing within our group helped avoid an us versus them mentality and helped each student learn to work with their current team. This helped each team focus on the task at hand rather worrying over rivalry with another school or another team within our larger group.

We specifically disassembled the cars after each meeting. The kids wanted to get attached to the cars and save them between meetings. But the goal was not to have the kids hold on to their creations but to help the them learn and believe that they build a great car again at the next meeting. Disassembly also avoided the issue of "ownership" when the teams were mixed again the following week. The point was to teach them to come up with ideas that they can prototype, evaluate and iterate. And their designs improved as they internalized the lessons learned. Real engineering!

Teams of 3-4 may work better. We only had enough parts on hand to build two cars and limited time left in the school year so we worked with what we had and used larger groups. With enough battery packs, motors and IR kits you can support racing more cars at one time. 

There are plenty of untapped options for this framework. The cars could tow a box of books to teach the kids to design for torque rather than speed. Or use an inclined board and see which car can climb the steepest angle. Or tow a box of books up an incline. This could open up the discussion of gearing and using other Lego motors. And advanced options could include comparing motors for speed versus gearing and even motor datasheets for efficiency versus maximum power output.

I hope that some of the ideas here can help you get your kids excited about engineering!

Tuesday, February 07, 2017

LEGO EV3 Minimal Proportional Line Follower

The LEGO EV3 is a great development platform for learning about sensors, feedback and control systems. The EV3 system allows us to build a working line following program using only 4 blocks. Here we will walk through how to build and understand this minimal proportional line follower.

A Line Follower Track

You will need some kind of track. There are several options. You can purchase a cardboard tri-fold board at Dollar Tree and make your own test track using electrical tape or a black marker. Or foam core, poster board or even cardboard. The link below has a pdf file of track parts that you can print and combine to make your own track. Print the tracks you want and tape them down.

If you draw the line you need to make the lines wide. The width of the line determine how long the robot has to recover before losing the line. If the robot veers toward the line enough to reach the white on the other side the robot will not recover and will lose the line. Systems with multiple sensors can follow more narrow lines but that is an advanced topic.


The Robot

You will need a simple robot with motors on ports B & C and an EV3 Color Sensor (on port 3) with the Color Sensor mounted in front of the robot (centered) about 3/8" of an inch above the mat (6mm to 8mm). Mounting the Color Sensor on the centerline of the robot makes the programming much more simple. Having the Color Sensor mounted off-center (closer to either the right or left side of the robot) means that turning left and turning right will not move the sensor by the same amount over the line. The imbalance between the effectiveness of left and right turns can be addressed in software but requires a different gain for left and right turns. Please mount your Color Sensor along the centerline of your robot to avoid this issue. 

Shielding the bottom of the Color Sensor from external light using LEGO bricks or beams can help but be sure to use dark colors, red and yellow LEGO are very reflective and often seen as white by the sensor. 

Calibrating your Color Sensor will make the process easier but there are notes on how to use the same program with an uncalibrated sensor. The link below has a great tutorial on how to calibrate the sensor.


In particular the the EV3 development environment's Move Steering block makes it easy to separately control the power setting of the drive motors and the power distribution. That is we can set a the Power input to 25 and then use the Steering input to vary how that power is divided between the motors. With a Steering input of 0, each motor runs at 25. But with a Steering input of 100, the left motor receives full power (25) while the right motor receive no power (0), turning the robot to the right. And the opposite is true when the Steering input is set to -100.

What Does Proportional Mean?

A proportional control system measures the error (the difference between the system setpoint and the current state) in a system and then either increases or decreases the system output by enough to minimize the error. Proportional refers to the system's ability to make small changes for small errors and large changes to respond to large errors. This means the system response is proportional to the measured error.

For this example, the error will be measured using a calibrated Color Sensor in Reflected Intensity Mode and the Move Steering block allow us to use this error to steer the robot to follow the line. A calibrated color sensor in reflected intensity mode will return 0 when over a wide black line and 100 when over a white portion of the board. When centered on the edge of wide black line the sensor should return 50. The program below shows how we can use the information from the sensor to control a robot's steering to create a proportional line follower.

Minimal Proportional Line Follower

Configure the Color Sensor for Measure -> Reflected Intensity. Set the Math Block to Subtract and type 50 for the value of "a". Set the Move Steering Block to ON and the Loop Block to Motor Rotations -> Rotations and Greater than (>) and set the limit to 10.

How it Works

First, the Color Sensor returns a number indicating the average brightness of the area illuminated by the internal LED (the sensor returns 0 for all black, 100 for all white and 50 if halfway between black and white). Then the Math Block takes our set point (50 when the Color Sensor is centered on the edge of the line) and subtracts the Color Sensor reading. The result of that calculation is the system Error. Next the Error is applied to set the Steering input of the Mover Steering block. We set the Power to 25 on the Move Steering block. Finally, the Loop block runs the from the time you start the program until the B motor has turned for more than 10 rotations.

Some examples. We can see that when the Color Sensor is over the edge of the line, the measured value is 50. We calculate the Error with the Math Block, Error = Set Point (50) - Measured Value (50) = 0. So our Error is 0 and the Steering input is set to 0, telling the robot to drive straight and the robot stays on the edge of the line.

If the Color Sensor drifts to the right, away from the black line toward the white background, the Color Sensor will return a higher number, for example 60. The Math Block calculates: Error = Setpoint(50) - Measured Value (60) = -10. So the Error is -10 and the Steering input is set to -10 or run the left motor 10 percent slower than the right motor, turning the robot left toward the black line. The opposite happens if the robot drifts left and the sensor is more over the black line and returns a lower number.

Have your robot try to follow the line and see how it does. If the robot runs off of the line, turn the robot around and have it follow the line in the other direction. If your Color Sensor is mounted off-center the robot will need a different gain for turning left and turning right. That approach is called asymmetrical gain and is common in temperature control systems that may heat and cool at different rates. We will discuss using a Switch Block to apply asymmetrical at a later date. Mounting your Color Sensor at the center of the front of your robot will ensure that a left turn and a right turn each move the sensor by similar amounts.

Behind the Curtain

Note that we are using some shortcuts in this simple implementation. First we count on the Color Sensor being calibrated, allowing us to use 50 as our setpoint or target value. You can use the same program with an uncalibrated Color Sensor but you must look at the values returned from the sensor for all black and all white and select a target value halfway between those two values. We found an uncalibrated NXT sensor that returned 36 for white and 6 for black. So we would use a target value of 21 (halfway between 6 and 36).

The program also never actually multiplies our Error by a gain. We just use the Error as is, so there was an implicit multiplication by a gain of one. This works because our expected Error range from the calibrated sensor is -50 to +50 which maps well into a Steering input for the Move Steering block. If you use an uncalibrated sensor you are likely to get a smaller error. For our uncalibrated example the Error would range from -15 (21-36) to +15 (21-6). This Error range is much lower than that seen from our calibrated sensor and may not be enough change to steer the robot back on track. So you may need to a gain of 50/15 or around 3.3 to give the same steering feedback over the Error range as a calibrated sensor. This can be done by multiply the output of the uncalibrated sensor by 3.3 using a Math Block.

Moving Forward (Advanced Exercises)

A good next step after you have the line follower working with a calibrated sensor is to reset your calibration and get the program to work with the uncalibrated sensor. You will need to select the mid-point between black and white for your target value and calculate a gain to scale your maximum and minimum reflected light values to 50 and -50 respectively. When you are finished remember to calibrate your sensor for future use.

Next add a math multiply block (or select ADV on your error calculation block) to multiply your error by a gain and test the robot with lower and lower gain until the robot fails to follow the line. How did the robot behave? Now increase the gain until the robot fails to follow the line. How did the high gain failure look different from the low gain failure? Try different motor powers and adjust the gain. You may find that the robot moves more smoothly with different gains at different speeds.

Try adding new features. How about lighting up the EV3 front panel in one color for a left turn and another color for a right turn? Or add an Ultrasonic Sensor pointing straight up and program the robot so you can move your hand closer to the top of the robot to make it drive faster. How about making the robot automatically drive faster when the error value is low (which means the robot is driving straight or almost straight).

Or you could replace the Color System with a Gyro Sensor in Angle Mode and create a robot that will drive straight, even if the robot slips or gets nudged. Be sure to have the robot setting on the floor when you power up the robot to ensure the Gyro Sensor does not drift. The number for "a" in the Math Block following the sensor sets the heading. Try modifying the program to have the robot drive straight in the direction the robot is pointing when you start the program.

I hope this has helped you understand how a proportional line follower works on the LEGO EV3 platform and how this simple approach can be as a starting point for further exploration of using proportional control.