Robotics - Getting Started with Spark Core and Photon (2015)

Getting Started with Spark Core and Photon (2015)

Chapter 7. Robotics

The Photon’s small size and wireless connectivity makes it a great choice for robotics projects. In this chapter, you will learn how to use a Photon or Core with a Photon Bot shield to control a small roving robot.

The robot is also fitted with an ultrasonic range finder module to help prevent it from bumping into things.

Project 14. Web Controlled Robot

This project makes use of a robot controller board called the Photon Bot by MonkMakes. You may guess by the company name that I had something to do with the design of this product, which you can buy from Spark and other sources, see Appendix A.

The board is combined with a chassis kit that provides a base and gearmotors to drive the robot, as well as wheels and a battery pack.

Figure 7-2 the web page to control it and provide feedback about the state of the rover’s battery and the distance to any obstacles in front of it.

Figure 7-2. Figure 7-2. A Webpage to Control the Rover

Parts

To build this project, you are going to need the following parts in addition to your Photon/Core.

Part

Description

Appendix A code

Photon Bot

Photon Bot Robot Controller Shield

M2

Rangefinder

HC-SR04 ultrasonic rangefinder

M3

Chassis Kit

Rover robot chassis kit (6V)

H6

Hookup wire

Wire to connect the motors to the Photon Bot

H3

Table 7-1. Parts Bin

There are many low-cost robot chassis on the market and most will work with the Photon Bot. Look for a kit with 6V motors, and a 4 x AA battery holder, although lower voltage motors will also work.

You will only need the hookup wire if the gearmotors supplied with the chassis kit do not have wires attached. In which case, you will need to solder wires about 6 inches long to each motor terminal.

Software (Photon)

It’s a good idea to program your Photon/Core with the app for this project before attaching it to motors, where some inadvertent use of output pins on a previous project could have your rover marching off the end of your table.

The program for this project is the example program provided in the Photon Bot library that makes the Photon Bot easy to use.

Find the PHOTON_BOT library, by typing “PHOTON_BOT” into the search field below “Community Libraries” in the Web IDE.

When you do this, you will see the library files. Select the file WEBROVER.CPP and then click on the button “USE THIS EXAMPLE." This will create a copy of the example program that we can use to program the Photon/Core, but can also be modified if we want to change things a little.

Before the WEBROVER example can be flashed onto a Photon or Core, you will need to find a couple of libraries that are used by the PHOTON_BOT library and also the HC_SR04 library needed for the rangefinder. To import each of these libraries for use with the example WEBROVER you must find each library (HC_SR04, SPARKINTERVALTIMER and SOFTPWM) in turn in the Community Libraries area and then click on the INCLUDE IN APP button, then when the Web IDE prompts with “Which app," select WEBROVER from the list and click the ADD TO THIS APP button. Repeat this for all three libraries. You will notice that each time that you do this a new #include statement will appear at the top of the program.

The libraries take care of most of the code for the rover for us. Here is the listing for the WEBROVER.

#include "HC_SR04/HC_SR04.h"

#include "SparkIntervalTimer/SparkIntervalTimer.h"

#include "SoftPWM/SoftPWM.h"

#include "Photon_Bot/Photon_Bot.h"

double volts = 0.0;

double distance = 0.0;

PhotonBot p = PhotonBot();

HC_SR04 rangefinder = HC_SR04(p.trigPin, p.echoPin);

void setup() {

Spark.function("control", control);

Spark.variable("volts", &volts, DOUBLE);

Spark.variable("distance", &distance, DOUBLE);

}

void loop() {

volts = p.batteryVolts();

distance = rangefinder.getDistanceCM();

}

int control(String command) {

return p.control(command);

}

Note that the extra comments added next to each include that appear automatically after using a library have been removed for clarity.

This program uses two Variables: volts, which contains the battery voltage, and distance, which contains the last rangefinder measurement in cm.

After the two double variables, the PhotonBot and rangefinder are initialized and assigned to the variables p and rangefinder respectively. When the rangefinder is initialized, the pins for it to use are taken from the photon bot’s library as p.trigPin and p.echoPin (see sidebar on Ultrasonic Rangefinders).

ULTRASONIC RANGEFINDERS

Ultrasonic rangefinders work by timing how long it takes for a pulse of ultrasound to bounce off an obstacle and return to the sensor. Using the speed of sound, the distance is calculated.

The HC-SR04 module used for this has power pins and two additional pins, trigger and echo. When the trigger pin is taken high for a fraction of a second, the module emits a pulse of ultrasound. When that pulse returns, the echo pin will indicate its return.

The setup function defines a Function called control. The control function uses high level commands like “F-100”. The first letter is the direction that the bot is to travel in (F-Forwards, B-Backwards, L-turn left, R-turn right) and the parameter after the - is the speed where 100 is full speed, 50 would be half speed, etc. The command S without any speed parameter stops the bot.

The two Variables are also defined in setup: volts and distance.

The loop function just updates both variables with the current battery voltage and distance to an obstacle.

The function control is the handler for the control Function and just passes on whatever command it is given to the function of the same name within the Photon Bot library.

One tweak to mention here is that if your chassis has motors of a lower voltage than that of the battery pack (say 3V) then you can change the code slightly to compensate for this. Replace the line of code below:

PhotonBot p = PhotonBot();

with:

PhotonBot p = PhotonBot(6.0, 3.0);

The first parameter (6.0) is the battery voltage. This does not need to be exact, if you have 4 x AA cells, set this to 6.0. The second parameter is the motor voltage, so set this to 3V if you have 3V motors. If you are not sure about the voltage of the motors, start by setting them to 3V. You can always increase this if it makes the motors run too slowly.

You can flash the WEBROVER app onto your Photon/Core while it is just connected to USB before you start attaching it to the hardware and its battery pack.

Software (Webpage)

The webpage for this project uses a combination of techniques that you have already seen in earlier projects and is too long to list here, so you might want to open the file p_14_Rover.html in a text editor.

This project actually uses three URLs, for the two Variables and the control Function.

var accessToken = "cb8b348000e9d0ea9e354990bbd39ccbfb57b30e";

var deviceID = "55ff6b065075555322151487"

var volts_url = "https://api.spark.io/v1/devices/"

+ deviceID + "/volts";

var distance_url = "https://api.spark.io/v1/devices/"

+ deviceID + "/distance";

var control_url = "https://api.spark.io/v1/devices/"

+ deviceID + "/control";

Remember that you will need to change the accessToken and deviceID for your account details.

Since there are now two Variables to be displayed in gauges, there are two corresponding callback functions to update the gauges, callbackVolts and callbackDistance. Both are much the same as earlier examples. The callback for the battery voltage finishes by scheduling another reading after 10 seconds, rather than the 1 second update of the rangefinder reading, as the battery voltage shouldn’t change that quickly.

The web page (see Figure 7-2) has buttons to control direction, but also maps key-presses on the keyboard to the various direction commands. The following line is responsible for intercepting key presses while you are on this webpage and calls the function keyPress every time a key is pressed.

$(document).keypress(keyPress);

The keyPress function is listed below:

function keyPress(event){

code = event.keyCode;

if (code == 119) {

sendControl('F-100');

}

else if (code == 97) {

sendControl('L-50');

}

else if (code == 115) {

sendControl('S');

}

else if (code == 100) {

sendControl('R-50');

}

else if (code == 122) {

sendControl('B-75');

}

}

Each key has a character code, based on the ASCII code for that letter. If you search the Internet you will find information about ASCII codes for letters. In this case, w is 119, a is 97, s is 115, d is 100 and z is 122. When a particular key is pressed the relevant command is sent to the Photon/Core.

One feature of the code for the volts gauge is that the gauge should go red as the battery becomes exhausted. This is achieved using a color list associated with the gauge. The three colors being red, orange and green as # hex strings.

var volts_gauge = new JustGage({

id: "voltsGauge",

value: 0,

min: 4,

max: 7,

levelColors: ["#FF0000", "#FFFF00", "#00FF00"],

title: "Battery Voltage"

});

Hardware

Before you start attaching any electronics, you will need to assemble the robot chassis. Most kits will comprise the following items:

§ A laser-cut acrylic plastic base

§ Two gearmotors (ideally 6V)

§ Two wheels to fit the gearmotors

§ A battery box to fit from 4 to 6 AA battery cells

§ A castor or universal wheel to be fitted at one end of the chassis

Before you assemble the chassis, you may need to solder leads to the gearmotors that are long enough to reach around to the screw terminals of the Photon Bot board.

Once the chassis is assembled, work out where you want to place everything on the chassis. The heaviest part of the rover will be the battery holder (once it has batteries in it) so make sure that this is positioned inside the triangle formed by the castor and the two drive wheels otherwise the rover might tip over.

Remember that the rangefinder will need a clear view in front of it to be able to detect obstacles. If you are lucky, screw holes will be in the right place and you can screw the Photon Bot shield and battery box to the chassis base. If not, then self-adhesive Velcro (TM) pads are a great way of attaching things.

The rangefinder has been temporarily removed for a clearer view of the screw terminals.

The battery box should have one red (+) and one black (-) lead. The red lead should go to the screw terminal labelled 6V and the black lead from the battery box is connected to the screw terminal marked GND.

The Photon Bot shield can actually control up to four motors, but only the pairs of screw terminals marked M3 and M4 are capable of bi-directional operation, that is making the motor run both clockwise and counterclockwise, so we will use these rather than M1 and M2.

Thread the leads from the motors through a convenient hole in the chassis base and connect the left-hand motor leads to the pair of screw terminals marked M4 and the right-hand motor leads to the pair marked M3.

You will not really know if these leads for a particular motor are the right way around until you try and drive them. Reversing the leads on a DC motor causes it to rotate in the opposite direction.

Now you can plug the Photon/Core and Rangefinder onto the Photon Bot shield. Make sure that they are both the right way around. You can also fit the batteries into the battery holder now.

If the battery holder does not have a switch, then pull one end of one of the batteries out of the battery box as a crude switch.

Using the Project

Chances are you are going to need to swap over a few of the motor wires, so its best to get all of that sorted out while the wheels are still off the motors. That way, you can sit the rover in front of you without worrying about it wandering off.

Open p_14_rover.html in your web browser and press the F button (or key) and watch what the motor shafts do for moving forward. One of the following situations will apply.

§ They are both moving correctly - hurray you are finished!

§ One of the motors is rotating in the wrong direction. If so, swap over the wires for that motor only, or both motors if both are wrong.

Now press A or the a key on your keyboard and watch what the motors do. If you performed the step above correctly, then the motors will be moving in opposite directions. The question is, whether this is turning you to the left (counterclockwise) or right (clockwise). If the answer is counter clockwise, then all is well and you are done, otherwise, you will need to swap the motor that is connected to M3 to be connected to M4 and vice versa. When doing this, keep the leads for each motor in the same order (for example red on the left, black on the right).

The rover is fairly power hungry, so when its not in use, pull one end of one of the batteries out to turn it off.

If you are using rechargeable batteries, then these are lower voltage than single-use AA batteries (generally 1.2V rather than 1.5V) and if the battery voltage falls too low, the Photon/Core will crash and you will loose control of the motors. Using a 5 or 6 cell battery holder will give you more drive time between charges if you are using rechargeable batteries. For single-use batteries, 4 x AA batteries should give you an couple of hours of driving time.

A nice refinement to the code might be to monitor the battery voltage and automatically stop the rover when the batteries get low.

You will find a number of other examples in the Library, you might like to try some of them out on you Rover.

Summary

In Chapter 8 you will learn about Spark’s powerful publish and subscribe model and how to use it when making two or more Photons or Cores communicate with each other.