Posted by: LearningRobotics | November 8, 2017

Learning Robotics XIII

OK, we got a body.  Next we drill the holes for the eyes.  In my case I am using the 5mm RGB LED’s.  So I need a 5mm drill or a .196″ or .2″ drill to make the holes.  I used some masking tape to measure up an equal distance from each side, but the front of my bot is not too even.  I am definitely not an artist.  So the holes don’t look even.  But they are close.  Next I spread some papers on a work table in my garage, bought a small can of gray paint and coated it liberally and let it set overnight.  Its not too bad.  I put the LEDs through the holes and added a bit of hot melt glue to hold them in.  You could use a bit of paper mache, or some glue to do that.

Here is a wiring diagram of the eyes:

Screenshot from 2017-10-03 17-39-41

And a detail of the construction of the tail…

capNsocket

On the bot board I glued some blocks of balsa to hold the body on.  Here is a photo:

woodblocks

And here is a photo of the body with the eyes glued in place.

gluedEyes

As I looked at the body on the simpleBot, I realized that I could not reach the switch or plug in the USB with the body in place.  I will have to relocate my switch to make that work.  I will mount the switch on the bottom of the bot board, and rotate the UNO so that the USB connector faces forward.  Then I will be able to reach through the front of the bot to plug in the USB connector.  I will glue two socket strips on the bottom of the SimpleBot board, near the front end so that the LED’s and a future ultrasound sensor can just plug in.  We can add connectors as we modify our bot to do different things.  Even ultimately we might want to change the CPU to a Arduino Mega to get more peripherals going, like a GPS, a rotation sensor called an IMU, and other devices to do more experiments, maybe even a grabber of some kind.

One of the advantages of building in wood is the versatility so we can do different things more easily.  Metal has equivalent modification capability, but is a bit harder (literally) to change when things go oddly or you change your mind.  And metal with sufficient stiffness is heavy and hard to drill.

I have used Erector set or Meccano as it is called these days, and it is OK, but you will find that you cannot always get pieces to match the meccano hole spacing.  Worse is trying to modify a meccano piece due to the coating, and toughness of their steel.

Anyway, back to our bot.  In the preceeding lesson we learned how to program the RGB LED’s and that they were series connected.  So in our bot, we will connect data out of the left eye to the data in of the right eye.  We will connect the 5v lead of the left eye to the 5v of the right eye, and we will connect both grounds to gether as well.  These connections will go close to the base of the LED, so we can use male-female connecting wires to run down to the sockets we will mount on the front edge of the simpleBot board.  We will use female-male jumpers to wire them up to the UNO by plugging in to the correct places on the UNO.

There will be a total of 2 wires from the UNO to the socket,red for 5V and white for signal. Black ground will come from the ground at the whisker interconnect to the socket.  Coming down from the left eye will be 3 wires, black for ground, red for 5V, and white for the signal.  Here is the wiring diagram:

Screenshot from 2017-10-03 17-39-41

I have already turned the UNO board 90 degrees to get access to the USB port.  I have moved the power switch to the bottom of the board.  Notice in the picture the locations of the power switch, the socket for the LED eyes, and the socket for the next peripheral.

Here is a drawing of the connections on my bot:

botBoardConnectors

And a photo of the terminal blocks on my board:

20171026_163053

Next we put the body on and connect the eyes.  Load the demo program and watch the eyes change color.  If that works, we combine the color code into the bot run time and the new runtime is almost 400 lines of code.

mousebotCode

Here is a link to a movie of the robot running now:

 

 

 

Posted by: LearningRobotics | September 19, 2017

Learning Robotics XI

Adding a bit of personality to our basic bot.  In this lesson we will add two RGB led’s that are individually programmable to show how our bot is feeling.  As a suggestion, maybe green for all go ahead, red if blocked (angry at the blockage) and blue when turning.  Thus as the bot does its thing, we will get some idea of what it is doing.  What is neat, though is that each LED is individually programmable, so you can play with each independently, and the package of 10 means you could even add color bumps to the shell when we get that far, which could do other things.

So to test our our LED idea, we mount two of the LEDs to a bread board, Following this pin out from the BulletPixels_Datasheet.pdf which you can download:

bulletpixelpinout

So on your bread board, insert two of them with the two long leads to the right for example in locations 1,2,3,4 so that DataOut is on the left in pin 1.  skip two holes and put the next one in 7,8,9,10 with DataOut on the left in pin 7.  Put a short black jumper from pin 2 to the ground bus marked with blue on most bread boards, and anothe short black jumper from pin 8 to ground also.  Put a short red jumper from pin 3 to the red bus, and pin 9 to the red buss for 5v.    Put a long black jumper from the blue ground bus to the GND pin on the UNO, and a long red jumper from the red bus to the +5v on the UNO.  Put a short white jumper from pin 7 Data Out to pin 4 DataIN, and a long white jumper from pin 10, DataIn to the UNO pin 3 for our demo program.

Download the arduino libraries from:

http://www.samuraicircuits.com/MediaWiki/index.php?title=BulletPixels2

Plug your Arduino into your computer.  In my case the LED’s lit up with a bright blue color.  I guess it will depend on how they were last programmed, or maybe that is the default.  Open the Arduino IDE and load the Samauri Bullet Pixels 2 -> SuperBasic program.

Change line 38:

int numberOfPixels = 5; //Let’s assume you have 5 BulletPixels daisychained together

to:

int numberOfPixels = 2; //Let’s assume you have 5 BulletPixels daisychained together

Change line 47:

LED.setOutput(9); // Digital Pin 9

to

LED.setOutput(3); // Digital Pin 9

I left the comments just in case I needed to go back.

Remove the lines between, but keep these two lines:

LED.set_crgb_at(1, value); // Here all the color values are linked to the BulletPixel at address 1

remove all the lines that would be in here.

LED.sync(); // This line of code sends all the data to the pixels in one giant refresh.

Load the program and you should see the LED’s light up red and green.

To show what is possible, we will modify the program a bit more to cycle both LED’s differently.

Add a line after the variable cRGB:

byte i,j,k;

Add this line at the bottom of the setup code:

i=j=k=0;

Now change the loop by adding this nested group of “if” statements:

i++;
if (i>254){
j++;
i=0;
if (j>254){
k++;
j=0;
}
}
if(k>254) k=0;

And change the two value lines to match these:

value.r = i ; value.g = j ; value.b = k; // Define all the color values

value.r = k ; value.g = i; value.b = j; // Define all the color values

Add this delay at the end of the loop:

delay(30);

The program should now look like this:

multicolorSimple

You should see the two LEDs cycling through all kinds of colors slowly.  If you can’t get either version to work, check your wiring.  This is known to work.

UPDATE:  These LEDs are VERY heat sensitive.  I strongly recommend using sockets for connections.  I destroyed three of them making the lights on my bot.

Now lets get a body made so we know how to put the LEDs on…

 

Posted by: LearningRobotics | September 19, 2017

Learning Robotics XII

Now for a shell.  We know now how to do paper mache, so that is what we will do for our first shell.

First we need a mold.  I want mine to look something like a mouse.  That means a rounded body, a sharp nose and rounded back end.  I will use cardboard for the mold.  If you examine cardboard you will see the corrugations that run in one direction.  We will want that to go along the length of the body, so when you cut it out, make sure that you have oriented them the right way.  My robot board is 5″ wide and 6″ long, so I want the body to follow a half circle 5″ in diameter with the corregations running the 6″ dimension.  To get a 5″ semicircle, you need PI*D/2 for the dimension along the arc.  Our D dimension is the 5″.  So if you multiply 5*3.14159 you get 15.7″+.  so we will cut a piece of cardboard that is 6″ across the corregations, and 15.7″ along the corrugations.  When you have it cut out, place it along the edge of a square table, and bend it about 30 degrees every 1/2 inch or so.  This will begin the rounding process.  Next cut out a 1/2 circle with a diameter of 4.5″.  You can use a compass, or a pin and a 2.5″ piece of string.  The reason it is not the full 5″ is because it will fit inside the 1/2 tube and be taped down.  Like this:moldBody

Next we cut triangles the length we want the nose.  Each one should be about 1″ inch at the base and it will take six of them to make the nose.  Cur the first one so it has a right angle at the short side.  The 90 degree corner goes to the bottom of one side.  Tape the short side to the half tube that is the body.  Each of the next 4 should be isosceles triangles, that means the two angles at the narrow end should be equal.  It doesn’t need to be perfect, but the better they are, the smoother the nose curve will be.  Place the second one next to the one we just put on and tape its base to the shell.  Then tape it to the otherone, pulling them to the center but with the first one level with the board. then add the next 3 to match.  The final one goes as shown here:

makingNose

Once it is in place tape the long edges and add some tape on the inside to strengthen the point.

For the rounded back, we will use wider strips, 4 altogether, one on each side like a stubby right triangle,  1.5″ on the short side and about 2″ long with one side straight and  one side curved along a smooth arc.  You can trim it with scissors.  Then add a piece 1.5″ wide, with a curve that narrows to a point about 1/2″ inch from the 1.5″ side.  The curves should come smoothly together,  When you roll it a bit and pull the ends of the fork together, it should make a nice rounded curve.  You may have to trim the curves a bit to get it to fit smoothly.  Then tape the curve into it, and tape it to the body.  Finally trim the edge to match the first one you mounted, and tape it down.  Make another just like that and tape it down.  Then put another right angle piece to make the final arc like 1/2 a bowl at the back end.  It shoud look something like this:

FormingRoundCurve

Tape all the joints smoothly together, and then cover with saran wrap to make it easy to get the paper mache body off the mold:

PlasticWrap

Yea!! we have a mold.  Now mix your glue.  One cup of flour and 1.5 cups of water.  Mix till smooth.  Tear about 100 or so 1/2″ wide 5″ to 6″ stips of news paper..  Place your mold on something that will clean easily, or that you can throw out because it is about to get messy.  I put on gloves just because I’m old, and don’t clean up easily.  You might want to also.  I get gloves in boxes of 100 at a wood supply store.

Now apply some glue to the mold, and smoothly apply a strip of newspaper.  Smooth it down but be careful, once the paper is wet with the glue it can tear easily.  I started by running strips along the bottom edge of one side, from the nose to the tail.  Put the strips right next to each other, but not overlapping.  If you end up with low spots in your mold (I did) you can put smaller pieces later to build it up.  But the first two layers should be run one way, like along the body for one layer, then across the body for the next layer.

Find your low spots now and build them up with a few shorter pieces of newsprint.  Put the largest piece that will fit on the low spot bottom, then add successively larger pieces, like an upside down tower until the spot is level.  Then continue gluing, parallel layer, perpendicular layer for about 10 layers.  Like this:

applyingPaperGlue

paperStrips

When you are done it should loke something like this:

mouseshellpapermache

Now let it dry for a couple of days…

Next lesson we will paint and mount it!

 

Posted by: LearningRobotics | September 17, 2017

Learning Robotics — Paper mache

Paper mache is a simple way to produce a body for your robot. It is not light weight, but not too heavy either. Because it is fibrous, and you can make a mold for it from many kinds of materials, curves, and smooth shapes are easy. It can be drilled, or you can form holes when molding it. Braces, tabs and other features can be built in or added with flour glue, white glue or carpenters glue, making it easy to fix or modify. However it is not robust, so will be more fragile than some other forms of bodies. It can be painted with either poster paints or house paints, taking various finishes with varying degrees of success, however proper preparation can produce relatively good results. Primers are necessary to get good finishes.

Flour glue is made by adding 1.5 cups of water to 1 cup of flour. Mix until very smooth and somewhat liquid. If an adult is working on this, an alternative is to boil 1 cup of water then add 4 tablespoons of flour. Stir until smooth and all the flour is well disolved. Let it sit and thicken a bit. This will result in a clear glue, but adds no real strength or anything.

Molds can be made from childs clay, wire, balloons, and about anything strong enough to support wet paper. If the mold is fragile, putting on one or two layers then letting them dry will add to the structure of the mold and help support later layers. The paste can be library paste, homemade flour or rice paste, or you can water down white glue and brush it on. If you use a balloon, be very careful to control the temperature. The balloon will swell if it gets hot, and shrink if it gets cold. This will tear your project if it is not dry yet.

To release your shape from a fixed mold, use cooking spray oil, or brush the mold lightly with any water resistant lubricant. If you use too much lubricant it can be difficult to get the paper to hold position, so proceed sparingly. You will have to PRY your material from a fixed mold, or if the mold can be disassembled or otherwise removed, that will work better.

For our robot, we will need a mold that is 4.5” wide x 5.5” long x 5” tall, to make room for our wires and circuits, and fit on top of our base board. It should be easy to deform to remove it. The mold could be made from cardboard and taped together with duct tape or gorilla tape. If covered with clear plastic packing tape smoothly, the light oil should let the paper mache slide off when dry. If you make multiple models, you could paint the mold with exterior house paint to better protect it from the wet glue. An alternative I’m going to try is plastic wrap. That will be detailed in my design page.

Once you have your mold, tape it down to a suitable surface to hold it steady. A scrap of cardboard or plywood would work nicely. Lube it lightly either by spraying cooking spray or by using a small paintbrush and applying a light oil sparingly to the surface. It should look slick, but not dripping oil.

You can use any kind of paper, but I have found news print works well. Tissue paper and toilet paper tear too easily or disintegrate when wet. Bond paper will be quite stiff, so the strips need to be torn to make rough edges instead of cut edges, and narrow strips about ½ inch work better for managing them when they are wet with glue. Wear gloves to protect your hands from the glue, because it may be hard to wash off. Do not use any form of toxic glue or instant glue. They will not work well and have bad effects on you if used in the quantities needed for paper mache.

The glue needs to be thin, kind of like baby oil. The idea is that the paper strips will soak up the glue to better bind the fibers of the layers together.

Lay the strip of paper on a clean washable surface. I use a brush to coat one sides with the glue and let it soak in a bit so the paper gets a bit limp. Then lift it up and place is somewhere on the mold. When placing the next strip parallel to the first. Successive layers you just coat the previous layer with glue for each strip, and add the successive layers strips in parallel, but at 60 or 90 degrees to the previous layer to add strength.

Smooth the strip and make it flat. If it buckles at corners, cut a slot or two in it to get the buckle to lay flat. Put about 4-8 layers over the mold. Thicker makes a stronger shell, and easier to hold. You want the shell wall 1/8-1/4 inch (3-6 mm) thick. When you have the shell that thick, set it aside to dry. It will take 48 hours or more to dry completely.

Once it is dry, take it off the mold, and let it air dry for another day. Then you can paint it and work with it. To fasten it down make some L braces from paper mache and glue them inside the mold. Use #4 or #6 wood screws. Drill a hole slightly larger than the screw through the robot platform to pass the screws through and screw them into the L brackets you put on your shell. Or you can hot glue some nuts on the shell and drill matching holes in the wood to use some #2 or #4 bolts to hold it on.

Make holes in the shell to pass over the feelers, and if you have LEDs for decorating your bot, don’t forget to put holes to mount them in the shell or let them stick through the shell.

You can also 3d print a shell if you have a printer, or you can make one from wood or from tincans. If you use metal, make sure you clear all wiring and protect the edges with tape or some kind of barrier to protect wire passages.

Be creative, be a maker, be a robot specialist!!

Blog sheet XII will be my shell.

Posted by: LearningRobotics | September 9, 2017

Tools

There are some tools needed to build small robots, not too many, but still having this set will make life easier:

nec=necessary for normal work
MWE= makes work easier
Optional= helps when things just aren’t going right and you need more tools.

nec MWE Optional
[] small phillips #2 screwdriver
[] Small straight blade screwdriver
[] needle nose pliers for electronics
[] diagonal cutters
[] Hacksaw with extra blades
[] hand drill
[] small set of bits up to 1/4 inch
[] small set of bits up to 6mm
[] Sanding block (piece of wood will work)
[] third hand (available at most hobby shops or amazon)
[] temperature controlled soldering iron (not the 25Watt sticks, but one with a dial for temp.)
[] soldering iron stand with cleaner sponge
[] set of jewelers screwdrivers
[] nut driver set or small tool set with sockets metric and SAE
[] set of ball end hex keys
[] hand saw for wooden bots and accessories
[] digital multimeter (about $20 for a nice one with auto shutoff)
[] two large plastic breadboards for experiments
    [] dremel with saw, and metal cutting blades, sanding disk.
    [] ASTE wire stripper, crimper, bolt cutter 
    [] metric wire stripper, crimper, bolt cutter
        [] power drill
Consumables
nec MWE Optional 
[] sheets of 60,100 and 200 grit sandpaper
[] spool of solder (get the no lead kind, and avoid lead)
[] small tin of flux for cleaning wires
[] small amount of rubbing alcolol
[] spare sponges for the soldering iron cleaner (not the same as kitchen sponge!!)
[] #2, #4, #6 screws nuts and washers. You will consume 10-30 per robot section.
[] batteries AA and other sizes as required.
       [] rechargable batteries and charger cheaper in the long run NiMh has higher current, but you
          can sometimes use a cellphone recharger.
[] pack of LED's 
[] resistor selection (available from amazon and various hobby shops)
[] extra 1K and 330 ohm resistors (you will use a lot of these with LED's.)
[] USB A to B cable 
[] USB A to mini cable
[] pack of mini clip hookups (available from Amazon and others)
[] pack of 40 male to male breadboard wires
[] pack of 40 male to female breadboard wires
[] pack of 40 female to female breadboard wires

 

Large robots ( NOT battle bots. they require a machine shop or access to one.)
nec MWE Optional 
[] set of open end wrenches
[] 3/8 socket set metric and SAE
    [] access to an oscilloscope 100Mhz minimum, much wider if you go to Raspberry PI or PC controllers
[] nuts and bolts 1/8-1/4 inch
[] metal snips for cutting sheet metal
[] ball peen hammer and anvil
[] 6" or larger bench mounted vise
[] C clamps 3-6" selection as required for your bots
     [] bending brake for sheet metal
[] AC powered drill
          [] drill press
Super nice to have, but can be contracted when needed:
3D printer
laser cutter or CNC small one. 10x10x3.
Posted by: LearningRobotics | September 7, 2017

Learning Robotics X

Robot build!!

We will build a robot that is small, driven by two wheels and riding on a skid in front.  That keeps things simple and makes it quickly responsive.  The Arduino UNO will be the processor on the bot,  and our bot will be simple.  Basically two wheels, two whisker type sensors, a motor driver, 4 AA batteries and the UNO.

The method of mounting the motors depends on whether you bought a platform or if you are constructing your robot out of “found parts”, maker style.  If you bought a platform, follow its build sequence.  If you are going maker style, then follow these instructions…

First we will do some measurements to align the motors.  Mount your chosen wheel on the motor geared shaft.  We will mount the motors to the bottom of our bot board.  Place the motor on the board so that the wheel is even with the back edge (one of the 5″ edges) of the board.  Take a pen or pencil and mark the board along the body of the motor/gear assembly.  This mark shows where to place the motors relative to the board end.

Here is a photo of my wheels:

20170901_132529

And here are the motors:

20170901_132608

Now if you have a square, use it and draw a line across the board from side to side at the mark.  If you do not have a square (get one when you can.  or get a drawing right angle triangle), then here is a way to make one for temporary use.  Get an unwrinkled piece of typing or copier paper.  Carefully pull the short edges together then holding them even, press toward the closed end, until you get a good solid fold.  This will make a stronger edge.  Press it down tight until it creases sharply.  Now hold the paper or square on your board with the fold or square along the mark and across the board.  Carefully line up the one edge of the paper or the other side of the square with the edge of the board.  Lightly draw your pencil or pen along the edge across the board:

20170901_133316

20170901_133751

Voila, you have a nice mark for aligning the two motors.  Lay the motors along this mark so that the wheels are clear of the board edge on each side by about 1/10 inch.  This will make sure the wheels turn freely when driven by the motors.  Make two cross marks on the line along each motor.  See the photos to follow this process.  Very close to the motor on the opposite side of the motor make two marks.  Repeat for the other motor.  When you lift the motors away, you should have 4 marks on each side.  In a few minutes we will drill some holes there, but first lets do some more layout.

Place the battery holder on the board, clear of the marks, making sure it fits on the board without going over either edge, it can cover the area for the motors if necessary.   Holding it firmly mark each of the holes in it using a pen or pencil.   The motors will mound under the board, and the motors below the board.

Now we need to find the center of the board at the opposite end from the motors.  The easiest way is to measure it with a ruler.  If you don’t have a ruler, use your paper.  Again make a line across the board using the square or paper to make it exactly perpendicular to the edge of the board, just as you did with the motors, but this time the line will be neear the middle of the long edge of the board.  It doesn’t have to be exact, just close.  See the photo to get the idea.  Now, from one corner of the board, using your straight edge on your paper or square, draw a diagonal line to the corner formed by the middle line and the opposite edge  of the board.  Do that 4 times so you have two large X’s on the board.  Connecting these X’s with a straight line and continuing through to the edge of the board, you have now found the exact center line of your board.  About 1/2 inch from the front of the board, make a cross line on that central line.  This is where the skid will go.20170901_134332

The motor mount holes:

20170901_135830.jpg

My battery box is unlikely to match yours, but you can see how to mark it easily.

Now we’re ready to make some holes.  Drill a 1/10″ hole at each of the 8 marks for the motors.  Drill a 1/10″ hole at the marks to mount the battery box.  Check the size of the screw for your skid and make a hole just big enough for it at the center line tick 1/2 inch from the forward edge of your board.

Now measure and cut 2 each 8″ of red wire and 2 each of 8″ of black wire.  Solder one red and one black wire to each terminal on one motor.  Repeat for the other.  On the board, drill a 1/4 inch hole between the two motors and halfway toward the closest end of the board.  This is where the motor wires will go up to the motor driver.

So far we have been working on the bottom of the board.  Turn it over, and place the battery box on the board, and using 4 bolts if there are that many holes, bolt the battery box down to the top of the board.  Put the screws in through the battery box and down through the board, and put washers and nuts on them and screw them snug, but not tight yet.  Place the motor driver board on back end over where the motors will be and even with the back of the board.  Mark the through the holes of the motor driver board.  Note that it may cover the hole for the motor wires.  That’s ok.  Turn the board back over.  Cut two more 8″ pieces of wire.  Place one motor in its correct place.  Thread one piece of the wire through the holes on each side of the motor.  This is solid core wire if you bought what I mentioned.  So now it can be used to hold the motor in place.  Thread the second piece of wire through the other two holes next to the motor and twist its ends to hold the motor snugly in place.  Repeat the process for the other motor.  Your motors may need some bracing, so you can use toothpicks or other small wood to help position the motors.  If the motors do not remain square with the edge of the board, cut the wires, and glue a toothpick or larger piece of wood just next to the holes, cut to just a bit longer than the distance between the holes so it will brace the motor in place.  You can use hot melt glue or wood glue for this.  If you use wood glue, sit the board aside for one day to make sure the glue is dry.  Then reinstall the motors.  The toothpicks should now keep the motors aligned properly.  If not, you may need to add two more toothpicks to each side to make the braces a bit higher.

20170903_185423

Now use the needle nose pliers and tighten all four wires.  Tight, but not until the wire breaks.  If a wire does break, just replace it and do it again.  When all four are tight, your motors are mounted.  On each motor lightly twist the two red and black wires together to make a red/black pair, then thread both pairs through the 1/4 inch hole .

To mount the driver board, we will need some stand-offs.  I never had you buy any because we can make them.  Cut 4 strips of paper about 1/4″ wide and about 1″ long.  Coat one side of each with glue or mix a pinch of salt with 1 tablespoon of flour and add water just until it is pasty, and use that.  Roll the strips into tubes just wide enough to pass the #2 screws through.  Set them aside to dry tonight.

20170903_185411

So, how do we mount the UNO to our robot?  If the screws you have are long enough, you can just bolt it over the top of the battery box using the screws.  If you got the 1″ screws, you are all set.  If not, then you can use the wire binding trick through the holes in the UNO to bind it over the battery box.  Put two on one side, but leave it loose for now until we get the battery’s in.

Now we mount our drawer pull.  Put the pull on the bottom of the board, and use its screw to mount it through the hole near the front of our board.  If it is too short for the board to be level when sitting on the wheels, make a stand-off for it, too, just like we did for the motor driver mount.  I couldn’t find my drawer pull, so I made a skid from a furniture glide and positioned it on a block of wood.  Here is a photo;

20170904_120426

Sitting on its two wheels and skid it’s starting to look like a robot, isn’t it?

Now we need to add a few more components.  At each front corner of the board, measure 1/2″ in and 1/2″ back.  Mark the spot, and gently drill a small hole to start the screw eyes.  Put one in each, turned parallel to the front of the board.  Strip an 8″ piece of wire, and wrap the end around one screw.  Pull the wire tight and twist the other end around the opposite screw eye.  Like this:

20170904_131220

The piano wire I’m using is 0.039″.  The size is not too critical, but really fine wire will bounce too much.  Too stiff will not move easily enough to make contact without changing the robot’s course.  Starting 3″ back from the screw eyes, measure the length to about 1/2 inch in front of the farthest forward piece of your robot, including the skid.  Add 3.5″.  On my robot, this will be 4.5″+3.5″ or 10.5″.  It is better to be long than short, so I’ll make mine 11″.  Cut two pieces of the stiff piano wire to match this length.  Put a masking tape flag on each wire at the measurement point that goes through the eyes, in my case 4.5″.  Like this:

20170904_132022

Measure 2.5 inches back from the screw eyes and in line with them i.e. 1/2 inch from the edge of the board, mark an x for the hole to hold the whisker in place.  Drill a 1/10″ hole for the screws on each side.

Now carefully bend a circle in the end of the wire that will go through the screw eyes, that we will use to mount these whiskers to the board.  It should be just a little bigger inside than the #2 screws.  This will take up about 1/2 inch of your wire, give or take your bending accuracy.  Now at the middle of your tape flag, bend the wire 90 degrees such that the wire can lay on the table with both the circle and the bend laying flat on the table.  Twist the circle using your pliers until this is true.  About 1/4 inch along the wire from the circle, bend it up about 15 degrees so that if you press down on the circle, the L of the wire rises off the table far enough that 2.5″ from the circle, the wire will be high enough to pass through the screw eyes without touching.  The more accurate you get this, the easier the next steps will be. For the second whisker, lay it down so the angle is opposite the first one.  Thus one will be the right whisker and the other the left.  Repeat the bends for this wire, too.

OK, good whisker bend?  Remove the tape and clean the wire with alcohol or light sanding.  Now thread the end of the wire through the screw eye.  Cut a piece of wire, I prefer white for right and yellow for left, about 6″ long each.  We can trim them once things are working.  Strip one end for about 1/2 inch.  Bend the wire to form a closed loop around a #2 screw, cut the end of the loop so it will be flat under the screw.  Put a washer on the screw, then the wire, then a washer.  This makes sure the wire will be held well.  Now put the screw through the loop in the whisker making sure that the right whisker is on the right side so that when it is pushed flat, the wire passes cleanly through the screw eye:

20170904_132052

Now put the screw as follows:  screw, washer, signal wire, washer, whisker wire, and through the board.  Apply the nut on the bottom of the board and screw it down really snug, but not tight yet.  On top of the board, check that the whisker goes cleanly through the eye, adjust as necessary to get it right in the center.  Now tighten the screw.  The whisker will likely now touch the screw eye at the top of the eye, but we can fix that later.

20170904_132400

Your robot should now look something like this:

20170906_162154

Cut a 5″ piece of black wire and strip both ends about 1/2 inch.  Slip one end under the middle of the wire between the two screw eyes bend it over the wire tightly.  Solder it to the wire.  What we have made is a contact sensor.  The whisker is in the middle of the eye, not touching.  When the robot hits something, the wire will bend and touch the eye, grounding the pin just like our push button did earlier.  Then we program our robot to back up and turn away from that side before taking off again.

Finally we need a power switch.  You either had or purchased one.  Regardless of how you got it, you need to mount it to the board.  If it is a slide switch, it is easiest to put standoffs on screws and bolt it down after soldering the wires on it.  Connect the red battery wire to one terminal at one end of the switch, and then cut a 6″ red wire and connect it to the terminal that is shorted when the switch is turned on.  This is the same process for the toggle switch.  For the toggle switch, you can just drill a hole in the board big enough to pass the screw part of the toggle through and fasten it with the supplied nut.  You mount the switch where the battery wire can reach but in a place that doesn’t interfere with the wheels or whiskers, neither the switch, its screws, nor its wires can touch the wheels or whiskers.  Here is mine:

20170904_131133

Time to wire it all up!!

First the motor driver.  Wire both sides of the motors to the side closest to the motor.  Red to the front, black to the back and strip the wires about 1/4″ and unscrew the two screws on the sides of the motor driver.  Place the stripped ends of the wire into the block.  Look carefully the hole is near the bottom.  The wire should bottom out in the hole with almost all the stripped wire inside the hole.  Then tighten the screw.  When that is done, the wires should look something like this:

20170904_123218

Coil the wires a bit and put them under the driver board.  Connect the black battery wire ( if it is twisted to the red wire, just untwist it a bit to reach) to the center of the three-hole block by the same process.  Connect the red wire from the switch to the Left terminal of the three so it looks like the second photo.  You can tape the wires down or coil them a bit to clean up the bot.

Make sure the switch is in the off position.  Measure from the left terminal on the motor driver to the positive connection on the battery box to be sure.  You can use an ohm meter if you have one, or the wire from an LED and resistor on your bread board via 5V through the switch like we did for checking the pushbutton earlier.  Once you know for sure which is off, mark that position on the board near the switch.  Switch off.  Insert the batteries in the box.  Tape two layers of making tape on the bottom of the Arduino just to prevent any sharp points from making contact with the batteries.  Fasten the Arduino over the batteries.

We are about to add the brain to our robot!  Yay! Brain surgery!!!

You need 8 male to female jumpers to connect the Arduino to the motor driver.  One male-female jumper for the 5v. and one to one of the ground pins on the motor driver to ground on the Arduino.

Fasten the ENA and ENB to pins 9 and 10 respectively.  Then in1 to 8, in2 to 11, in3 to 12 and in4 to 13.    Left whisker to 2 and right whisker to 3.

Brain surgery done.  Double check all connections.  We don’t want to mis-connect anything or burn up one of our components.

Connection check list:

Connections:
motor driver:
[] left motor red to OUT4 screw terminal
[] left motor black to OUT3 screw terminal
[] right motor red to OUT1 screw terminal
[] right motor black to OUT2 screw terminal
[] Switch red to Vcc screw terminal
[] Battery black to GND screw terminal
[] Arduino ground to GND via male to female jumper
[] Arduino vin to 5v via male to female jumper
[] ENA to 9 via male to female jumper
[] in1 to 8 via male to female jumper
[] in2 to 11 via male to female jumper
[] in3 to 12 via male to female jumper
[] in4 to 13 via male to female jumper
[] ENB to 10 via male to female jumper

Whiskers
[] Left to arduino pin 2 via solid #22 wire
[] Right to arduino pin 3 via solid #22 wire
[] Screw eyes connected together by stripped #22 wire then a black #22 solid wire to arduino ground

Switch
[] Battery red wire to one pole of the switch. (the other already connected to Vcc on the motor driver.

Connections on the Motor driver:

Screenshot from 2017-09-06 17-47-58

From the OSEPP webpage: https://www.osepp.com/electronic-modules/breakout-boards/92-osepp-motor-driver-module

 

First we will load a simple program to run the motors, and we will put the robot on something so the wheels are not touching ground or anything. What a revolting development… My motors will not drive with 6v applied, nor will the 5v actually reach 5v.  The specification for the motor driver says it should work:

pinSpecsOSEPP_MotorDriver

From the OSEPP webpage: https://www.osepp.com/electronic-modules/breakout-boards/92-osepp-motor-driver-module

And I have 6v, but the 5v only reaches 4.65 no load.  It might be that my motor driver has been damaged somehow, but I don’t have another.  I’ll order another, but in the mean time I will just check if adding another battery will do the job.  Always check the specs and double check your connections.

Here is the code.  Note the #defines to check out the whisker operation, and the wheel test which will do a little dance without engaging the whiskers.  If neither of these is defined, the robot code will run sensing the whiskers.  When the left whisker is hit, the bot backs up and turns right.  If the right whisker is hit the bot backs up and turns left.  Note that if something is dead ahead and too small, the bot will just run into it.  If you tie a piece of thread between the whiskers, then the bot will sense something straight ahead as well.

And here are two videos.  First is the wheel test:

wheel test Dance

And a first run sort of bouncing off things in my lab:

First Run

 

Personality is next…

/*****************************************************************/

// SimpleBot

/*****************************************************************/
// 4 September 2017 by H.L.Howell
/*
Copyright 2017 H.L.Howell

Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

// to run the whisker test only uncomment the following line:
//#define WhiskerTest

// The wheel test can be run with the bot suspended so that you
// can just check that the wheels run forward and backward. If you put
// it on the floor in an open space, it will do a little dance.
// to run the wheel test only uncomment the following line:
//#define WheelTest

// test your bot to verify the 90 degree value
// for my bot at speed 200, it takes about 990ms.
#define turn90 990

#define Lwhisker 2
#define Rwhisker 3
#define Ren 9
#define Len 10
#define in1 8
#define in2 11
#define in3 12
#define in4 13

void backNleft(){
// back up for 1 second then turn left
long backtime;
backtime=millis();
digitalWrite(in1,HIGH);
digitalWrite(in2,LOW);
digitalWrite(in3,HIGH);
digitalWrite(in4,LOW);
while((millis()-backtime)<1000); // backing up for 1 second without stoppint interrupts
backtime=millis(); // get the time we start the turn
digitalWrite(in3,LOW); // this stops the left wheel
digitalWrite(in4,LOW); // but the right wheel is still going backwards turning right
while((millis()-backtime)<turn90); // turning
digitalWrite(in1,LOW); // and now going forward.
digitalWrite(in2,HIGH);
digitalWrite(in3,LOW);
digitalWrite(in4,HIGH);

}
void backNright(){
// back up for 1 second then turn left
long backtime;
backtime=millis();
digitalWrite(in1,HIGH);
digitalWrite(in2,LOW);
digitalWrite(in3,HIGH);
digitalWrite(in4,LOW);
while((millis()-backtime)<1000); // backing up for 1 second without stoppint interrupts
backtime=millis(); // get the time we start the turn
digitalWrite(in1,LOW); // this stops the left wheel
digitalWrite(in2,LOW); // but the right wheel is still going backwards turning right
while((millis()-backtime)<turn90); // turning
digitalWrite(in1,LOW); // and now going forward.
digitalWrite(in2,HIGH);
digitalWrite(in3,LOW);
digitalWrite(in4,HIGH);
}
void setup() {
// put your setup code here, to run once:
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
pinMode(Lwhisker, INPUT_PULLUP); // pulls the pin to 5v through a 10K resistor
pinMode(Rwhisker, INPUT_PULLUP); // pulls the pin to 5v through a 10K resistor
Serial.begin(115200);
}

 

void loop() {
// put your main code here, to run repeatedly:
int l,r;
l=digitalRead(Lwhisker);
r=digitalRead(Rwhisker);
Serial.print(“l=”);Serial.print(l);Serial.print(” r=”); Serial.println(r);
analogWrite(Len,200);
analogWrite(Ren,200);
#ifdef whiskertest
Serial.print(“whiskers L:”);
Serial.print(l);
Serial.print(” R:”);
Serial.println(r);
delay(300);
#endif
#ifdef WheelTest
Serial.println(“Forward both”);
digitalWrite(in1,LOW);
digitalWrite(in2,HIGH);
digitalWrite(in3,LOW);
digitalWrite(in4,HIGH);
analogWrite(Len,200);
analogWrite(Ren,200);
delay(2000);
Serial.println(“Rev right”);
digitalWrite(in1,HIGH);
digitalWrite(in2,LOW);
delay(2000);
Serial.println(“Rev LEFT”);
digitalWrite(in3,HIGH);
digitalWrite(in4,LOW);
delay(2000);

#endif
#ifdef WheelTest
#else
#ifdef WhiskerTest
#else
// normal operation
if ((l)&&(r)){ // Nothing blocking
Serial.println(“straight”);
digitalWrite(in1,LOW);
digitalWrite(in2,HIGH);
digitalWrite(in3,LOW);
digitalWrite(in4,HIGH);
}
if (l==0){// left blocked This will also be the default when both are triggered.
Serial.println(“back & left”);
backNleft(); // backup and turn left
}
if (r==0){
Serial.println(“back & right”);
backNright(); // backup and turn left.
}
#endif
#endif
}

 

 

 

 

 

 

 

 

 

Posted by: LearningRobotics | August 27, 2017

Learning Robotics IX

MOTORS… Yea!!

Well, lets start easy.  We’ll drive a servo motor first.  The servo motor is actually a small motor with a lot of gears to let it drive more slowly, but with much more power.  If you got the standard servo I recommended, it will be about 42in/oz of torque, which is quite strong.  Regardless of the company that built the servo, it will have a standard 3wire interface, typically Black, red and either yellow or white.  Red goes to the voltage, in this case the 5v terminal on your UNO.  Black goes to ground on the UNO. The yellow or white lead goes to pin 9 for our demo, but it can go to any of the pins designated as PWM pins on the UNO pinout you saw earlier.  That’s it.  The example code to drive a servo is file>example>servo>sweep.  This is what it contains:

servosweep

This uses a library which contains constants in it to limit the analog write to the correct limits.  A servo uses a potentiometer located just under the arm gear inside the case.   A potentiometer is a resistor that has a wiper on it that can pick out any voltage along the resistor or potential.  Potential is another word for voltage, although it is somewhat disfavored these days.   None the less, potentiometer it is.  So in this potentiometer, the wiper that picks up the voltage stands still and the resistor part turns with the gear in most cases.  This potential is applied to one side of a differential amplifier.  The other side is driven by the signal input through a filter.  The PWM pulse provides a voltage after filtering that is proportional to the PWM signal pulse width.  A PWM signal looks like this

PWMwaveform

The filter basically averages the voltage over the period.  If the pulse width is 50% of the period, you will end up with an average of about 1/2 the applied voltage in the pulse.  The signal used for PWM on Arduino defaults to about 490 Hz on some pins and about 980Hz on others.  The pin we selected is 480 hz.  Here is the link to the Arduino reference on AnalogWrite: https://www.arduino.cc/en/Reference/AnalogWrite

The Servo Library as used in the example slows down the frequency to about 50 hz as used in many low cost servo systems.  But we can do it more easily simply using Analog Write, and most servos will respond to it readily.  If not you can always go to the other servo example and use that code.  Here is the simple program:

servoSimplePWM

Most servos will work with this simple version, but if not you can use the servo example.  In any event, this is PWM.  Notice the delay.  This gives the servo time to respond to the change in voltage.  Some servos are fast, some are slow.  The time you chose here is dependent on how large the change you apply and the speed of the servo.  Here is a photo of the servo connection:

ServoConnection

The servo is one of the easiest motors to hook up and use.  However if you use a more robust servo, you will want to provide it power from a battery, not the 5v pin on your Arduino.  Big servos can take several amps of current so they need a separate supply.  It is simple to do that, simply hook up the servo’s red lead to a separate battery supply and hook both the arduino ground and the other battery ground together to the servo pin using a Y connection.

Servos can be used to drive the head or other animation on your robot, or several servos can be used to drive a robotic arm.  More than one requires the separate battery to drive them.  We’ll get to that later on.

A motor of any kind cannot be driven directly by the Arduino.  All of them need some kind of motor controller.  The simplest of these is the H bridge.  Here is a general schematic of an H bridgt as shown on Wikipedia: https://en.wikipedia.org/wiki/H_bridge

WikipediaHbridge

One thing to note here.  S1 and S2 cannot both be closed ever, or you will have a catastrophic failure.  The same applies to S3 and S4.  That is known in Hbridge terminology as “shoot-through” and basically is a short across the power Vin.  It works by closing either S1 and S4 or S2 and S3 to provide the motor with full voltage (almost anyway) in either direction, thus the DC motor will turn either clockwise or counter clockwise, giving you good power in both directions with a single power supply.  Here are diagrams showing the two operating conditions:

HbridgeOperation

In practice, this is usually a power circuit like the L298N By Smial – Own work, FAL, https://commons.wikimedia.org/w/index.php?curid=3898890 shown here:L298_IMGP4533_wp

Notice that the pins are staggered.  They do not simply lend themselves to .1 inch centers. although they can be carefully coerced to do so.  It is far easier to order one on a break out board from Amazon or other on-line source.  This is a robust part, but you need to protect the output pins with strong diodes.  If you get the OSEPP breakout board the diodes are in place as is a 5v output derived from the VIN applied to the breakout board.  DO NOT put 5v into the breakout board from your Arduino.  One of the two voltage regulators will probably die.

You can control the current by using PWM on the enable pin.  You can monitor the current by connecting a 0.5 ohm 5Watt power resistor to the ground pins then to ground.  Connecting that pin in turn to a comparator and setting the opposite input to the comparator to a potentiometer will let you adjust the Maximum current applied to your motor.  The OSEPP part has a good heat sink on the tab of this part.  If you do it yourself, make sure you add a good heat sink of at least 10 square inches of surface area to the tab, and use heatsink compound to be sure you get good results.

I have driven these until they got too hot to touch, and they survived.  Here is the link: https://www.osepp.com/electronic-modules/breakout-boards/92-osepp-motor-driver-module

Here is a picture of the OSEPP part:OSEPPmotorDriver

Note across the bottom right the pin connections ENA, in1, in2, in3, in4, ENB.  This is a DUAL H bridge meaning it can drive two DC motors at the same time, both forward and reverse.  The three connection block is Vin for the motors, ground for the motors, and that 5v output.  That output also appears with ground on the upper row of the pins to the right of the power block.  On the left side is the two connections for the motor driven by ENA, in1 and in2.  Just above that block you can see the diodes that protect the L298 from back current from the motor.  If you turn the motor by hand, it produces voltage these diodes prevent that current from destroying the L298.  On the other side is the output for another motor and its 4 diodes.  The other components on the board bias the L298, filter the voltages and provide the 5v output.  To use this to drive two DC motors, hook motor one to out1 and out2 on the left, and the other on out3 and out4 on the right.  Connect pins 9 and 10 of the arduino to ENA and ENB, and connect 8,11,12, 13 to in1, in2, in3 and in4.  Connect UNO ground to one of the GND pins on the top of the pin block.  Connect motor power to the left terminal of the 3 terminal block and ground or negative to the center of the 3 terminal block.  Now your have two motors ready to be driven by the motor dirver from the arduino.

I will only connect one motor as the example because it will be easier to photo graph and show.  Here is the code:updatedMotordriver

 

I’ll leave it up to you to add the other motor side to this code.

We have enough code to build a simple robot.  To do that you need:

Least expensive way from amazon:
CJRSLRB® Smart Motor Robot Car Chassis Kit with Speed Encoder wheels and Battery Box For Arduino
1 length of piano wire from a hardware shop
2 screw eyes

Diy way:
1 Small board 6″ x 5″ piece of scrap or from a hardware store or hobby shop.
2 wheel motors and wheels from Amazon or hobby shop
1 smooth dome shaped drawer pull from a hardware shop,
1 battery box for 4 AA cells
1 lenght of piano wire (feelers to be described later)
20 #2 bolts 1″ long with nuts and washers
2 screw eyes
1 small toggle or slide switch (may already be in the parts you bought earlier)

to build a two wheel robot with feelers so it can find its way.  A small manual drill and bits or electric screwdriver with bits, small screwdriver for the #2 bolts, and a  needle noise pliers to hold the nuts and bend the piano wire.

YEA!! the robot is coming…

UPDATE:  I forgot to say that you also need a pair of diagonal cutters, soldering iron, some wire 22 or 24 gauge stranded, and solder.  You can either purchase wire at an electrical shop or a set of wire spools can be purchased here:  (I recommend this because you will be using wire a lot in robotics, and this keeps it neat.)

https://www.amazon.com/Electronix-Express-Hook-Stranded-Gauge/dp/B00B4ZQ3L0/ref=sr_1_5?ie=UTF8&qid=1503940933&sr=8-5&keywords=wire

Forgot the photo of the driver hookup.  This might help:

motor driver

The red and black from the batteries go to the V+ pin and ground.  This is the motor supply.  DO NOT HOOK RED to the other pin.  It is 5v and will destroy the Motor Driver.

The Yellow, Orange, Red and brown go to 8,11,12,13 as the in1, in2, in3 and in4.  In this example only the yellow and orange are being driven.  The black and white go to ENA and ENB respectively.

The green wire is the ground.  The motor black and white go to the out1 and out2 connection.  That is the full connection.  I used the ribbon type connection to make it a bit clear to photograph.  Notice that the battery wires are twisted together a bit.  That will help make you wiring neater as well.

Note that I updated the code.  For some reason an earlier version was pasted.

 

Posted by: LearningRobotics | August 24, 2017

Learning Robotics VIII

I am sure you are wondering when we will get to the “real robots”… Well, there are only a few more things to learn about our little Arduino UNO and the Arduino IDE, and we’ll be on our way.

What good is a robot if you can’t have flashing lights, some that go dim and other effects?

To do these things we need what I promised you last time:

Now we can begin to write programs that really do stuff.  Next we will learn how to use a pushbutton to control an LED.  And we will learn how to change the brightness of an LED using PulseWidthModulation.

A pushbutton is a switch.  I like the ones that make a nice click, but any kind will do.  The big issue is that when you push on the button, its little metal contacts hit, hard, and bounce back a bit.  Our digital pins work fast enough that each bounce can be seen as another press.  So when the button is pushed with out some kind of filtering, the computer goes “button button button button button… until the contacts finally quit bouncing.  Fortunately this takes only a few milliseconds, so one quick fix, is when you see the button press, wait a few milliseconds (remember the delay(100) statement) and check again.  That is how we will do our button program.  To get a voltage out of a switch closure (the button press) we need a voltage.  The microcontroller guys thought of that, so the pinMode can be set to have a 10K ohm pull up applied inside the processor.  So our setup statement for our button pin will say:

pinMode(buttonPin,INPUT_PULLUP);

Voila, we have 5v applied to the pin through 10K ohms of resistance with no need for external components.  If there is nothing attached, and we do:

Serial.println(digitalRead(buttonPin));

in our loop procedure, we will see a long run of 1’s on the Serial Monitor.  To be able to read our button, we need to connect one side of it to the buttonPin, and the other side to ground.  When we press the button, the pin will read 0,1,0,1,0,1, until it finishes bounding.  We know that that can take several milliseconds, so we just to the following:

void loop(){
if(digitalRead(buttonPin)==0){
delay(10); // wait 10ms to for bounce to clear
if(digitalRead(buttonPin)==0){
// put the action to do here
}
}
}

So if we see a low, then we wait for 10 milliseconds, and then check that it really went low.  This prevents a brush against the button being seen as a press, and also prevents the problem of seeing the bounces repeating the action over and over in the code.

So what action?  Lets turn on or off an LED.  Put the following line in place of the comment “// put the action to do here”.

digitalWrite(LEDpin,!digitalRead(LEDpin));

The only thing we need is the pins and their pinModes in setup.  So here is the program:

 

Screenshot from 2017-08-24 11-05-27

Now you can wire up a pushbutton from pin 8 to ground, and a resistor and LED from pin 9 to ground.  You can just use one of the LED’s from the earlier 8 LED setup on the breadboard, and that will work well.  Here is that setup again for you:

20170822_101414

The white wire goes to pin 9 and the black wire to ground on your UNO.

Then you need the pushbutton.  Most pushbuttons have 4 leads, in two pairs.  If you have the spec for your button it will show you a drawing with the pairs marked or a pin diagram or list to help you.

If not just try them with the LED to find out which ones are shorted.  To do that wire UNO 5v to one pin, and connect one of the other pins to the white wire on your led and plug the Arduino into the computer.  If the LED is lit, that pair is shorted. either of the other two pins should work, and so connect the white wire to one of them and the LED should be out.  Press the button.  The LED should light up.  If not try the last pin.  you might have a two switch pushbutton.  If the last pin doesn’t work, leave the LED connected there, and try each of the remaining two pins with the 5v.  When you find a pair where 5v on ond and LED on the other works when the button is pushed, you have the pair you need.  Mark them somehow for future reference.

Unplug the Arduino from the computer.  Now take the 5v lead off the 5v and put it into UNO pin 8.  put the other lead from the pushbutton to ground (blue side of the bread board), and put the LED white lead back on UNO pin 9. Make sure the black wire from the blue side of the bread board goes to UNO ground.

Now load and run the program.  When the program starts, the LED is most likely out.  Push the button and release it. The LED should switch on.

Our program is missing something.  Hold the button down and the LED will flash about 1 second flashes.  Every pass through the loop, as long as the button is held down the led will switch.  If you reduce the 1000 delay to a few milliseconds, it may just look dim instead.  This is PWM at 50%.  PWM means only on part time, or PULSE width modulation.   A controllable PWM is the analogWrite.  This has a range from 0-255.  Here is the link to the Arduino Reference:

file:///usr/share/arduino-1.6.12/reference/www.arduino.cc/en/Reference/AnalogWrite.html

Lets modify our program to use this with the button, and to make sure it waits until the button is released.  To wait for the button release, we do a while statement looking at the buttonPin as long as it is 0.  The semicolon ends the while loop, so now basically the only statment is “while (digitalRead(buttonPin)==0)” in other words, we are just looping on reading the buttonPin.  We add an integer called brightness and we not increment that by 32 with each press.  8 presses take it back to zero.  Here is the code as modified with the serial output to check how it works:

 

LEDbutton

 

Next we work with motors.  You will need a motor driver.  You can order this one if it is not in the parts you have now.  You might want to order a standard size servo if you don’t have one yet.

https://www.sparkfun.com/products/9457

You can get a stepper motor as well, and this will drive any hobby motor.  I will provide instructions on both.

A servo can also be ordered, or you can get one at a hobby shop.  Any 6v drive servo can be used for our demo, but don’t get the continuous rotation one for this next experiment.

 

 

 

Posted by: LearningRobotics | August 24, 2017

Learning Robotics VII

So far we have gone through the Serial port and how to write stuff out, Integers and binary logic, and timing procedures.  Now we need to understand what programmers call flow control.

Our example programs for the most part have just started at the loop declaration and gone line by line to the end, except for the for loop used to show the binary count process.  In the for loop, the test statement checked if the value of the index had gone above 255.  We used the ‘>’ sign to do that.  Lets look at the other types of comparisons to see how they behave…

First we need to understand a bit more about integers…

We talked about how integers went from -32789 to +32768.  Well to make binary math work, the process goes like this…

Integer counts from 10 down to -10…
0B0000000000001010 10
0B0000000000001001 9
0B0000000000001000 8
0B0000000000000111 7
0B0000000000000110 6
0B0000000000000101 5
0B0000000000000100 4
0B0000000000000011 3
0B0000000000000010 2
0B0000000000000001 1
0B0000000000000000 0
0B1111111111111111 -1
0B1111111111111110 -2
0B1111111111111101 -3
0B1111111111111100 -4
0B1111111111111011 -5
0B1111111111111010 -6
0B1111111111111001 -7
0B1111111111111000 -8
0B1111111111110111 -9
0B1111111111110110-10

Notice that if you subtract 1 from 2:
0B0000000000000010
-0B0000000000000001 You borrow the 1 just like in decimal math
=0B0000000000000001 and so the number becomes 1.

If you subtract 1 from 0:
0B0000000000000000
-0B0000000000000001 You borrow 1, but in this case you borrow one all
=0B1111111111111111 the way across, so the result is -1 as all 1’s.

The neat thing is that if you invert all the bits of any positive number
and add 1 you get its negative value:
0B0000000000001010 10
0B1111111111110101 inverted
+ 0B0000000000000001 add 1
0B1111111111110110 -10

For most robotics programming understanding this will help when errors crop up in sensor readings or in time calculations where integers are added, subtracted or compared.

All most all the flow control operations depend on comparisons.  Generally that means the math comparisons, such as (x==y) which is the test for x being equal to y.  This can ONLY work on byte, integer or long values.  Floats are tricky because decimals numbers do not convert directly to a binary point value as pointed out earlier.  To do a check for equals with floating point values the recommended procedure is to subtract one from the other and see if the absolute result is less than a very small number.  For example:

float x=32.0002;

float y-32.00025;

if (abs(x-y)<.0001) SerialPrintln(“Equal”);

You can try this in any of the serial output programs we have done so far by just putting these three lines right after the “void loop(){”

Abs means return the difference as a positive number, so abs(-10)=10, and abs(10) also equals 10.

We just saw the “if” conditional flow statement.  The arithmetic statements are (x>y), (x<y), (x<=y), (x>=y) and (x–y) for integers.  For floats, (fx<fy) and fx>fy) will work as expected.  However any of the ones containing the equal sign may not give the expected results due to the issues of how decimal values are stored as binary point values between 1 and 2 with an exponent to indicate magnitude.  100.00 will be stored as 1.10011001000000000000000 e00000101.  Not quite the same, is it?  Different processes arriving at the 100.0000 floating point value will yeild slightly different binary equivalents.

The programming flow control statements are “if”, “for”, “while”, “switch”, and “do—while”.  We can use these with the arithmetic logic to determine when to terminate the loop for “while”, “do–while” and “for” by enclosing the comparison operator in parenthesis.  For example:

 

i=0;

while (i<100) {
Serial.println(i);
i++;
}

for (i=0;i<100;i++){
Serial.println(i);
}

i=0;
do{
i++;
Serial.println(i);
} while(i<100);

Each of these loops about 100 times.

You can copy and paste these in the loop of a simple program with setup just containing Serial.begin(9600);

More complex conditions will use the logic groupings which are “&&”, “||” and “!”.  By combining these relatively difficult decision paths can be exercised.  Try this program:

logicDemo

These are the important factors.  Now we can begin to write programs that really do stuff.  Next we will learn how to use a pushbutton to control an LED.  And we will learn how to change the brightness of an LED using PulseWidthModulation.

 

Posted by: LearningRobotics | August 23, 2017

Learning Robotics VI

Well, I promised the following:

Next time we will look at some other variable types, and some of the other logic functions, such as && and > and ||. These are logical and, arithmetic greater than and logical or. We will also talk about &, <<,>>, | and other useful logic and arithmetic operators.

Variable types for Arduino are floating point, char, byte, integer, long integer.  The integer versions, byte, integer and long integer may be unsigned as well, to double the capacity in positive numbers only or to be treated as binary values.  A floating point variable is designated as follows:

float x;

Now that may not be too exciting, but the range of a float in Arduino C and most other C versions is:

Floating-point numbers can be as large as 3.4028235E+38 and as low as -3.4028235E+38. They are stored as 32 bits (4 bytes) of information.

Floats have only 6-7 decimal digits of precision. That means the total number of digits, not the number to the right of the decimal point. Unlike other platforms, where you can get more precision by using a double (e.g. up to 15 digits), on the Arduino, double is the same size as float.

This is directly from: https://www.arduino.cc/en/Reference/Float

So you can see that while the range is quite large, the precision not so much.  Moreover, Arduino doesn’t really support double values which have more precision, as well as wider range.  Instead, to help novice users port programs, the designers of Arduino C chose to simply alais double into a float.  The program can be imported, and tun, but if it relied on the additional precision of the double, it may not run right, although in practice on the types of programs the Uno and most other Arduinos are used for, it likely won’t be a problem.  For now you won’t have to worry about that.

Recalling how different integers in binary land look compared to decimal, another related issue comes up in regards to fractional values.  That is decimal values below the decimal point do not translate easily to binary.  For example, 1/5 is 0.2, but when expressed in binary as a binary point value it becomes: 0.00110011….  In other words it is a repeating sequence of 0011 after the binary point.  The implication of this is that you cannot compare floating points directly.  in other words, 0.2 is almost never equal to a 0.2 that is arrived by calculating from floating point multiplication and/or division.  So the basic rule is do not use the comparison of floating point numbers.

We have used char, which is a variable for storing 8 bit ASCII characters, and the integer which stores 16 bit values from -32768 to +32767.  The “byte” is an 8 bit integer from -128 to +127.  The “long” or long integer is 32  bits, storing numbers from -2147483648 to +2147483647.  If each of these is preceeded in their declaration by the word unsigned they become a number twice as big as the positive value they can hold signed+1.  The declarations look like this:

byte x;
int y;
long z;
unsigned byte Ux;
unsigned int Uy;
unsigned long Uz;

Occasionally due to certain issues in object oriented code, the libararies won’t recognize one of these, and you will find that they use something like Uint_8 for an unsigned byte or Uint_16 for an unsigned integer.  Just be aware that you sometimes need to read the examples if something doesn’t work using normal variables.  The odd usage is often shown in the library’s examples.

You have already read the output of a successful compile on the UNO.  If you look carefully at it, you can see that there is 32K total program space, and about 3K for variables.  3K is pretty small, it is 3048 bytes.  If you use an integer array, you will run out of space at about 1400 values, because some of the variable space is used by the base Arduino code.  So use arrays sparringly in the UNO.

Long variables are used in several places internally.  the two places you will run into them early on is in the commands to read time.  Each time the Arduino is restarted there are two clock counters that are set to zero, that is the one used by the millis() procedure call which returns the time in milliseconds since the timer was started, and the micros() command which returns the time in microseconds since the program was restarted.  Each of these returns a long value, since time is always positive, that is not a problem, and allows a long runtime for these clocks.

Lets create a program that reads the millis() and the micros() and prints them out.

You have to disconnect the bread board from your UNO now so we can use the serial port (pins 0 and 1).

You don’t need anything wired to the Uno for this program… Open the Arduino development environment and choose new again.  Save the new program as “timeDemo”.

And enter the code shown here:

timeDemo

You can see the time a it scrolls by with a delay of 1 second between updates.

Tools>Serial Monitor.  Set to 9600 baud to see the output.

If you change the my_millis and my_micros variables to “int”, and run it again,   You will see that the numbers change in a rather unpredictable way.  This is because the move from a long as returned by the procedure calls loads only the least 16 bits into the integers, and so the numbers look really weird and not really related to what you saw from the original.  You can try byte values as well, and again the difference will be remarkable.  Note also that we didn’t specify unsigned, so the values returned change from positive to negative.  NO, we did not time travel, only that the truncation process causes the value to be interpreted as negative when the most significant bit (bit 15 of the integer or bit 7 of the byte) is set to a one.

To a programmer, it is vital to keep track of whether a number is signed or unsigned, and the correct size, long, integer or byte.  Errors of this kind can keep you up at night!

Now, what can we do with integer numbers?  Of course the usual math, add, subtract, multiply and divide.  Note that when you multiply a byte times a byte, the result is an int if the bytes are very large at all.  Integers multiplied become long’s.  So be careful when multiplying.  When dividing, you will truncate.  In other words, 5/2=2, not 3.  19/9=2, but so does 26/9=2.  Integers don’t support fractions nor do they round, they just drop the remainder.  But you can find that remainder.  The operation that does that is the % operator, called modulo.  Therefore 19%9=1, and 26%9=8.  You can also do an operation called a bit shift.  To shift a number left is the “<<” symbol pair.  to drop bits off the bottom end, you shift right “>>”.  This is how it works…

0B00001111=15.  We can multiply it by two by : 0B00001111<<1=0B00011110=30.

0B00001111=15  We can divide it by two by 0B00001111>>1=0B00000111=7.

In the second case we lost one bit off the end.  That is the truncation I was talking about.  It also applies if we shift a large number right.  For exmaple:

0B11111111=255  If we shift it left by one bit it becomes 0B11111111<<1=0B11111110 or 254.

Multiple shifts also work:

0B11111111<<3=0B11111000 or 248.

Note that shifts fill the end with 0’s. on the end shifted away from…

0B11111111>>3=0B00011111 or 31.

Another thing we can do with integers, and we do this a lot when doing PORT type loads where we want to save the port contents, is the arithmetic and “&”, the arithmetic  or “|” and the arithmetic XOR “^”.

The demo code is with bytes, but the operators work with int and long as well.

Here is the demo code for this called byteMath:

byteMath

Next we will look at the various “flow control” and logic functions to see how that all works.

Older Posts »

Categories