Arduino Robot-Arduino Robot kit

Arduino Robot-Arduino Robot kit

How to make Arduino Robot: Arduino Robot Kit

In this blog, we are going to make a small surveillance spy robot based on Arduino. The secret agent will be able to command the robot remotely from a web page and see what the robot is seeing in real time using a camera.

To do this, we will use everything you have learned from this blog so far:

  • How to use Wi-Fi with Arduino
  • How to create control interfaces
  • How to use a camera with the Arduino Yun
  • How to use Arduino Robot Kit

Let's dive in!

 

Hardware and software requirements

Arduino Robot

The core of the project will, of course, be the robot itself. For the robot's chassis, you have a wide range of choices available on the market. For this project, I chose a DFRobot MiniQ 2 wheels chassis, which is a small robot chassis that you can easily mount Arduino boards too.

 

Then, you will need two Arduino boards for this project. The first one will be an Arduino Yun, which we will use to connect a USB camera, Building a Cloud Spy Camera. For the camera itself, I used a C720 camera from Logitech again.

 

The other thing you will need is an Arduino Uno, which will take care of driving the motors of the robot via a motor shield. We have to use an Arduino Uno here because the Arduino Yun is incompatible with most of the motor shields of DFRobot.

 

To control the motors, I used a 1A motor shield from DFRobot. In order to control the robot remotely, we'll also use the CC3000 breakout board that we used in an earlier blog. To assemble the CC3000 board with the rest of the robot, we will also use a DFRobot prototyping shield.

 

You will also need a 7.2V battery pack to power the robot when it is not connected to your computer. I also used a DFRobot battery pack with a DC jack adapter.

 

Finally, here is a list of all the components that we will use in this project:

  • DFRobot MiniQ 2 wheels chassis 
  • DFRobot Motor shield
  • DFRobot Prototyping shield 
  • CC3000 breakout board
  • Arduino Uno
  • Arduino Yun 
  • USB camera 
  • Breadboard
  • Jumper wires
  • 7.2V battery with DC power jack

On the software side, you will need the latest version of the Arduino IDE. You will also need to install the following libraries using the Arduino library manager:

 

Hardware configuration

Arduino Robot kit 2018

Let's start with the most difficult part of this project: assembling the robot itself. Of course, the exact steps will depend on the robot chassis you are using. We start by actually mounting the Arduino Yun board on the robot chassis using the screws and headers provided with the chassis itself:

 

Once that's done, we mount the Arduino Uno board on top of the Yun using an extra row of headers. Then, we tightly screw the Arduino Uno board into the metallic headers.

 

Then, we mount the motor shield on top of the Arduino Uno board. Next, we insert the cables from the motors into the dedicated headers on the motor shield and secure them with the screws. Make sure that you are using the same polarity for both motors.

 

Here is the result at this point:

Now, we are going to assemble the CC3000 breakout board on the prototyping shield, which will then sit on top of the robot. To know how to connect the CC3000 board. This is the assembled CC3000 board with the prototyping shield:

 

Now, simply mount this shield on top of the robot:

Finally, plug the camera into the USB port of the Arduino Yun and place it in front of the robot. I secured it with screws, but this will depend on your own robot chassis.

 

This is a close-up picture showing the completely assembled robot: This is an overview of the completely assembled robot:

If you have a similar result, congratulations! You are now ready to program your surveillance robot. Don't worry about the battery for now, as we will do everything using USB cables that connect the robot directly to your computer.

 

Setting up the motor control

Arduino Robot-Arduino Robot kit

We are now going to set up the different parts of the project, starting with configuring the Arduino Uno, which will control the motors via Wi-Fi. For this, we'll use the aREST Arduino library, which makes it really easy to control Arduino projects via Wi-Fi.

 

Here is the complete code for this part:

// Robot test via aREST + WiFi #define NUMBER_VARIABLES 1 #define NUMBER_FUNCTIONS 5
// Libraries
#include <Adafruit_CC3000.h>
#include <SPI.h>
#include <aREST.h>
#include <avr/wdt.h>
// CC3000 pins
#define ADAFRUIT_CC3000_IRQ 3
#define ADAFRUIT_CC3000_VBAT 8
#define ADAFRUIT_CC3000_CS 10
// Robot speed
#define FULL_SPEED 100
#define TURN_SPEED 50
// Motor pins
int speed_motor1 = 6;
int speed_motor2 = 5;
int direction_motor1 = 7;
int direction_motor2 = 4;
// Sensor pins
int distance_sensor = A0;
// CC3000 instance
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_ CC3000_IRQ, ADAFRUIT_CC3000_VBAT);
// Create aREST instance aREST rest = aREST();
// The port to listen for incoming TCP connections
#define LISTEN_PORT 80
// Server instance
Adafruit_CC3000_Server restServer(LISTEN_PORT);
#define WLAN_SSID "KrakowskiePrzedm51m.15(flat15)"
#define WLAN_PASS "KrK51flat15_1944_15"
#define WLAN_SECURITY WLAN_SEC_WPA2
void setup(void)
{
// Start Serial Serial.begin(115200);
// Give name to robot rest.set_id("1"); rest.set_name("robot");
// Expose functions rest.function("forward",forward); rest.function("backward",backward); rest.function("left",left); rest.function("right",right); rest.function("stop",stop);
// Set up CC3000 and get connected to the wireless network Serial.print(F("Initialising CC3000..."));
if (!cc3000.begin())
{
while(1);
}
Serial.println(F("done"));
Serial.print(F("Connecting to WiFi..."));
if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) { while(1);
}
Serial.println(F("done"));
Serial.print(F("Getting DHCP..."));
while (!cc3000.checkDHCP())
{
delay(100);
}
// Start server restServer.begin();
Serial.println(F("Listening for connections...")); displayConnectionDetails(); wdt_enable(WDTO_8S);
}
void loop() {
// Handle REST calls
Adafruit_CC3000_ClientRef client = restServer.available();
rest.handle(client);
wdt_reset();
// Check connection if(!cc3000.checkConnected()){while(1){}} wdt_reset();
}
// Forward
int forward(String command) {
send_motor_command(speed_motor1,direction_motor1,100,1); send_motor_command(speed_motor2,direction_motor2,100,1); return 1;
}
// Backward
int backward(String command) {
send_motor_command(speed_motor1,direction_motor1,100,0); send_motor_command(speed_motor2,direction_motor2,100,0); return 1;
}
// Left
int left(String command) {
send_motor_command(speed_motor1,direction_motor1,75,0); send_motor_command(speed_motor2,direction_motor2,75,1); return 1;
}
// Right
int right(String command) {
send_motor_command(speed_motor1,direction_motor1,75,1); send_motor_command(speed_motor2,direction_motor2,75,0); return 1;
}
// Stop
int stop(String command) {
send_motor_command(speed_motor1,direction_motor1,0,1); send_motor_command(speed_motor2,direction_motor2,0,1); return 1;
}
// Function to command a given motor of the robot
void send_motor_command(int speed_pin, int direction_pin, int pwm, boolean dir)
{
analogWrite(speed_pin,pwm); // Set PWM control, 0 for stop, and 255 for maximum speed
digitalWrite(direction_pin,dir);
}
// Print connection details of the CC3000 chip bool displayConnectionDetails(void) {
uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;
if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
{
Serial.println(F("Unable to retrieve the IP Address!\r\n")); return false;
}
else
{
Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask)
Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
Serial.println();
return true; }
}
As this code is quite long, we are only going to look at the most important parts here.
We start by including all the required libraries:
#include <Adafruit_CC3000.h>
#include <SPI.h>
#include <aREST.h>
#include <avr/wdt.h>
Then, we define the pins that correspond to the motor shield:
int speed_motor1 = 6;
int speed_motor2 = 5;
int direction_motor1 = 7;
int direction_motor2 = 4;
After this, you need to enter your own Wi-Fi network name and password:
#define WLAN_SSID "your_wifi_ssid"
#define WLAN_PASS "your_wifi_password"
#define WLAN_SECURITY WLAN_SEC_WPA2s

 

Then, we declare the aREST instance, which we'll use later to access motor functions via Wi-Fi:

aREST rest = aREST();

In the setup() function of the sketch, we expose the different functions to control the robot so they are accessible via Wi-Fi:

rest.function("forward",forward);
rest.function("backward",backward);
rest.function("left",left);
rest.function("right",right);
rest.function("stop",stop);
After that, we start a Wi-Fi server on the board:
restServer.begin();
Serial.println(F("Listening for connections..."));

 

In the loop() function of the sketch, we continuously listen for connections and handle them with the aREST instance:

Adafruit_CC3000_ClientRef client = restServer.available(); rest.handle(client);

 

Now let's have a look at one of the functions to control the robot, for example, the one to go forward:

int forward(String command) {
send_motor_command(speed_motor1,direction_motor1,100,1); send_motor_command(speed_motor2,direction_motor2,100,1); return 1;
}
As you can see, the work is done by another function that directly acts on the motors:
void send_motor_command(int speed_pin, int direction_pin, int pwm, boolean dir)
{
analogWrite(speed_pin,pwm);
digitalWrite(direction_pin,dir);
}

 

It's now time to configure this part of the project. Connect the Arduino Uno to the computer via USB and upload this sketch to the board. Then, open the Serial monitor. After a while, you should see the IP address of the board is printed on the Serial monitor.

 

Setting up live streaming

We can now move to the next part: configuring live camera streaming on the Arduino Yun. Building a Cloud Spy Camera, so we'll only look at the most important parts here. Refer to the Hardware configuration section if you need to know how to configure your Yun again.

 

First, connect to your Yun using the following command: ssh root@arduinoyun.local

 

Then, launch camera streaming with the following command:

mjpg_streamer -i "input_uvc.so -d /dev/video0 -r 640x480 -f 25" -o "output_http.so -p 8080 -w /www/webcam" & You can check that the streaming is working at the following page http://arduinoyun.local:8080.

 

Setting up the interface

Interface

We can now move to the last part: setting up the interface that will allow a secret agent to command the robot and also to see the live stream from the camera. This interface will be composed of an HTML page and a JavaScript file. It will be based on the aREST.js module that makes it easy to control aREST devices from a web page.

 

This is the complete HTML page:

<!DOCTYPE html>

<html>
<head>
<meta charset=utf-8 />
<title>Surveillance Robot</title>
<link rel=stylesheet type=text/css href="https://maxcdn.

bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel=stylesheet type=text/css href=interface.css> <script type=text/javascript class='lazy' data-src="https://code.jquery.com/jquery-

2.1.4.min.js"></script>
<script type=text/javascript class='lazy' data-src="https://cdn.rawgit.com/Foliotek/ AjaxQ/master/ajaxq.js"></script>
<script type=text/javascript class='lazy' data-src="https://cdn.rawgit.com/ marcoschwartz/aREST.js/master/aREST.js"></script>
<script type=text/javascript class='lazy' data-src=interface.js></script> </head>
<body>
<div class=container>
<h1>Surveillance Robot</h1>
<div class=row>
<div class=col-md-2></div>
<div class=col-md-2>
<button id=fw class='btn btn-primary btn-block' type=button>Forward</button>
</div>
</div>
<div class=row>
<div class=col-md-2>
<button id=left class='btn btn-primary btn-block' type=button>Left</button>
</div>
<div class=col-md-2>
<button id=stop class='btn btn-danger btn-block' type=button>Stop</button>
</div>
<div class=col-md-2>
<button id=right class='btn btn-primary btn-block' type=button>Right</button>
</div>
</div>
<div class=row>
<div class=col-md-2></div>
<div class=col-md-2>
<button id=bw class='btn btn-primary btn-block' type=button>Backward</button>
</div>
</div>
<div class=row>
<img class='lazy' data-src="http://arduinoyun.local:8080/?action=stream" />
</div>
</div>
</body>
</html>

 

The most important parts on this page are the buttons to control the robot and the live stream of the camera. For example, this defines the button to move the robot forward:

 

<div class="col-md-2">
<button id='fw' class='btn btn-primary btn-block' type="button">Forward</button>
</div>
This <img> tag allows you to insert the live stream of the camera into the page:
<img class='lazy' data-src="http://arduinoyun.local:8080/?action=stream" />
Now let's look at the JavaScript file that will actually send the command to the robot.
This is the complete file:
$( document ).ready(function() {
// Device
var address = '192.168.1.105';
var device = new Device(address);
// Button
$('#fw').click(function() {
device.callFunction('forward', '');
});
$('#bw').click(function() {
device.callFunction('backward', '');
});
$('#left').click(function() {
device.callFunction('left', '');
});
$('#right').click(function() {
device.callFunction('right', '');
});
$('#stop').click(function() {
device.callFunction('stop', '');
});
});

 

You only have to change one thing in this script: the IP address of your board, which you obtained previously:

  • var address = '192.168.1.105';
  • var device = new Device(address);

The different lines of code on the page each control a function of the robot. For example, this piece of code creates the link between the forward button and the forward function on the robot:

  • $('#fw').click(function() {
  • device.callFunction('forward', '');
  • });

 

Testing the surveillance robot

Now that we have all the elements in place, it's time to test our little surveillance robot. Note that you can grab the complete code from https://github.com/ marcoschwartz/arduino-secret-agents.

 

Make sure that you configured the code and the hardware with the instructions from the previous sections. Now, it's time to power your robot from the battery. Insert the battery into the robot chassis, and then plug it into the Arduino Uno DC jack input.

 

Then, connect the Arduino Uno 5V pin to the Vin pin of the Yun. Also connect the GND pins of the two boards together. This will ensure that the Arduino Yun will be powered as well. Don't forget to start the live video stream again after that. Now, place your robot on the ground and open the HTML page.Now, try the different buttons, and you should see that the robot reacts nearly instantly. Congratulations, you just built your own spy robot based on Arduino!

 

Wi-Fi-controlled Mobile Robot

wifi_robot

In this last blog of the blog, we are going to use the Arduino Yún in a completely different field: robotics. You will learn how to interface DC motors, as well as how to build your own mobile robot with the Arduino Yún as the brain of the robot, a distance sensor for the robot, and wireless control using Wi-Fi and a simple web interface.

 

You will also be able to get a live display of the measurements done by the robot, for example, the distance that is measured in front of the robot by the ultrasonic sensor.

 

Building the mobile robot

mobile-robot

Arduino boards are widely used in mobile robots because they are easy to interface with the different parts of a robot, such as sensors, actuators such as DC motors, and other components such as LCD screens. Arduino even released their own robot recently so people can experiment on a common robotic platform. These robots are usually programmed once and then left alone to perform certain tasks, such as moving around without hitting obstacles or picking up objects.

 

What we want is to build a mobile robot that has the Arduino Yún as its "brain" and control it entirely via Wi-Fi from a computer or mobile devices, such as a smartphone or a tablet. To do so, we will program an Arduino sketch for the robot that will receive commands and send data back, and program a graphical interface on your computer. This way, if you want to build more complex applications in the future, you simply need to change the software running on your computer and leave the robot untouched.

 

We are first going to build the robot using some basic mechanical and electrical parts. We will not only show you how to build the robot using a specific kit but also give you a lot of advice on building your own robot using other equivalent components. 

 

At the bottom of the robot, you have most of the mechanical parts, such as the chassis, the wheels, the DC motors, and the ultrasonic sensor. You also have the battery at the center of the base of the robot. Then, you can see the different Arduino boards on top. Starting from the bottom, you have the Arduino Yún board, an Arduino Uno board, a motor shield, and a prototyping shield.

 

Assembling components in this project will be slightly different than before because we will actually have two Arduino boards in the project: the Yún, which will receive commands directly from the outside world, and an Arduino Uno board, which will be connected to the motor shield.

 

We will then perform the usual test on the individual parts of the robot, such as testing the two DC motors of the robot and the ultrasonic distance sensor that is located at the front of the robot. To test the motor, we are simply going to make them accelerate gradually to see whether or not the command circuit is working correctly. The measurements being received from the ultrasonic distance sensor will simply be displayed on the serial monitor.

 

The next step is to build the Arduino software that will receive commands from the computer and transmit them to the motors that move the robot around. At this point, we are also going to code the part that will transmit the distance information back to the computer. Because we want to standardize our code and make it usable by other projects, we will build this part with inspiration from the REST API of the Arduino Yún board that we already used in Blog, Creating a Remote Energy Monitoring and Control Device.

 

Finally, we are going to build the server-side graphical interface on your computer, so you can easily control the robot from your computer or a mobile device and receive some data about the robot, such as the readings from the ultrasonic sensor. This server-side software will again use HTML to display the interface, JavaScript to handle the users' actions, and PHP to talk directly to your Arduino Yún board via the cURL function.

 

The required hardware and software components

robot_parts

You will need several mechanical and electrical components for this project apart from the Arduino Yún. The first set of components is for the robot itself. You basically need three things: a robot base or chassis that will support all the components, two DC motors with wheels so the robot can move around, and at least one ultrasonic sensor in front of the robot. We used a mobile robot kit from DFRobot (http://www.dfrobot.com/) that you can see in the following image:

 

The kit is called the 2 Wheels miniQ Balancing Robot chassis and costs $32.20 at the time of writing this blog. Of course, you don't need this kit specifically to build this project. As long as you have a kit that includes the three kinds of components we mentioned before, you are probably good to go on this project.

 

For the motors, note that the circuit we used in the motor shield can handle up to 12V DC, so use motors that are made to work at a voltage under 12V. Also, use motors that have an integrated speed reducer. This way, you will increase the available torque of your motors (to make the robot move more easily).

 

For the ultrasonic sensor, you have many options available. We used one that can be interfaced via the pulseIn() function of Arduino, so any sensor that works this way should be compatible with the code we will see in the rest of this blog. The reference of this sensor at DFRobot is URM37. If you plan to use other kinds of distance sensors, such as sensors that work with the I2C interface, you will have to modify the code accordingly.

 

Then, you need an Arduino board that will directly interface with the DC motors via a motor shield. At this point, you might ask why we are not connecting all the components directly to the Arduino Yún without having another Arduino board in the middle. It is indeed possible to do with the sensors of the robot, but not the motors.

 

We can't connect the motors directly to an Arduino board; they usually require more current than what the Arduino pins can deliver. This is why we will use a motor shield that is specialized in that task. Usually, the Arduino Yún can't use these motor shields without being damaged, at least at the time of writing this blog.

 

This is due to the fact that motor shields are usually designed for Arduino Uno boards and the wrong pins on the shield can be connected to the wrong pins on the Yún. Of course, it would also be possible to do that with external components on a breadboard, but using a shield here really simplifies things.

 

This is why we will interface all the components with a standard Arduino board and then make the Yún board communicate with the standard Arduino board. We used a DFRduino board for this project, which is the name that DFRobot gave this clone of the Arduino Uno board. This is as shown in the following image:

 

Of course, any equivalent board will work as well, as long as it's compatible with the official Arduino Uno board. You could also use other boards, such as an Arduino Leonardo, but our code has not been tested on other boards.

 

Then, you need a motor shield to interface the two DC motors with the Arduino Uno board. We also used a motor shield from DFRobot for this project. The reference on the DFRobot website is 1A Motor Shield For Arduino, as shown in the following image:

 

Again, most motor shields will work for this project. You basically need one shield that can command at least two motors. The shield also needs to be able to handle the motors you want to control in terms of voltage and current. In our case, we needed a shield that can handle the two 6V DC motors of the robot, with a maximum current of 1A.

 

Usually, you can look for motor shields that include the L293D motor driver IC. This integrated circuit is a chip dedicated to controlling DC motors. It can handle up to two 12V DC motors with 1A of current, which will work for the mobile robot we are trying to build here. Of course, if your shield can handle more current or voltage, that would work as well.

 

The important point to look for is how to set the speed of the robot: the IC I mentioned can directly take a PWM command that comes from the Arduino board, so if you want to use the code prescribed in this blog, you will need to use a shield that uses a similar type of command to set the motor's speed.

 

Finally, we added a simple prototyping shield on top of the robot to make power connections easier and so we can add more components in the future, as shown in the following image:

 

Again, you can use any equivalent prototyping shield, for example, the official prototype shield from Arduino. It is mainly so you don't have many cables lying around, but you can also use it to extend your robot project with more components, such as an accelerometer or a gyroscope.

 

You will also need a power source for your robot. As the DC motors can use quite a lot of current, we really recommend that you don't use power coming from your computer USB port when testing the robot or you will risk damaging it. That's why we will always use a battery when working with the motors of the robot.

 

We used a 7.2V battery with a DC jack connector, so it can be easily inserted into the Arduino Uno board. This battery pack can also be found on the DFRobot website. You can also use some AA batteries instead of a battery pack. You will have to make sure that the total voltage of these batteries is greater than the nominal voltage of your DC motors.

As for the software itself, you don't need anything other than the Arduino IDE and a web server installed on your computer.

 

Robot assembly

robot_assembly

It's now time to assemble the robot. We will show you the steps you need to follow on the robot kit we used for this project, but they can be applied to any other equivalent robot kit. The first step is to put the battery at the base of the robot, as shown in the following image:

 

Note that some metal spacers were also used at the base of the robot to maintain the battery in place and to provide support for the rest of the components. These spacers can also be found on the DFRobot website. Then, you can screw on two more spacers and the Arduino Yún board to the top of the chassis.

 

Then, we added the Arduino Uno compatible board on top of the two metallic spacers. At this point, you can screw on the Arduino Uno board; all the other components will just be plugged into these boards, as shown in the following image:

 

Then, you can simply plug the motor shield on top of the Arduino Uno board. At this point, you can also connect the cables that come from the DC motors to the motor shield screw headers. Be careful with this step; it is quite easy to plug the wrong cables from the DC motors. You need to connect each motor on a different connector on the motor shield board, as shown in the following image:

 

Finally, you can plug the prototyping shield on top of the robot. At this point, we already connected the ultrasonic sensor: ground goes to Arduino ground, VCC to Arduino's 5V pin on the prototype shield, and the signal pin goes into pin A0 of the Arduino board. If your ultrasonic sensor works with a digital interface, for example, you might want to use different pins. Please read the datasheet of your ultrasonic sensor for more information. The following image shows the state of the robot at this step:

 

Connecting the Arduino Yún and Uno boards

We are not done yet! For now, there are no connections between the Arduino Yún and the Arduino Uno board, so the Yún board won't be able to access the DC motors and the sensors of the robot. To solve this issue, the first step is to connect the power from the Arduino Uno board to the Yún board. This way, when we power the project using the battery, the Yún board will be powered as well.

 

To do so, simply connect the ground pins together and plug the Vin pin on the Arduino Yún to the 5V rail of the Arduino Uno. To finish connecting the two Arduino boards, we need to connect them so they can speak together when the project is under operation. For this, we are going to use the I2C interface of the Arduino boards so they can send messages to each other.

 

I2C stands for Inter-Integrated Circuit and is a simple communication protocol that was developed for communication between circuits, and is widely used in electronics. There are two wires to connect for that purpose: SDA and SCL. To do so, simply connect pin 2 of the Yún board to pin A4 of the Uno board, and pin 3 of the Yún board to pin A5 of the Uno board, as shown in the following image:

 

Finally, you can power up the project by inserting the DC jack connector of the battery into the power connector of the Uno board as shown in the following image:

 

If everything was done correctly in this step, you should see that both boards (the Yún and the Uno) are powered up, with some of their LEDs on. To help you build the robot, we also included two pictures of the sides of the robot that show you the different connections. The following is an image of a side of the robot that shows the power connections to the Yún:

The following image shows the connections from the I2C interface to the Yún:

 

Testing the robot's hardware connections

robot_connection

Before building the remote control part of the project, we want to make sure that the hardware is wired correctly, especially between the Arduino Uno board and the different motors and sensors. This is why we are first going to build a simple sketch for the Arduino Uno board to test the different components.

 

At this point, we are going to turn the motors of the robot on; so make sure the robot is standing on a small platform, for example, to prevent it from moving around while you are testing your different Arduino sketches with the USB cable connected to your computer.

 

The sketch starts by declaring the pins for the motors, as shown in the following code. Note that these pins are specifically for the motor shield we are using; please refer to the datasheet of your shield if you are using a different one.

int speed_motor1 = 6;

int speed_motor2 = 5;
int direction_motor1 = 7;
int direction_motor2 = 4;
Declare the pin used by the ultrasonic sensor as follows:
int distance_sensor = A0;
We also want to make the speed of the motor vary during operation, so we declare the variable as follows:
int robot_speed;
In the setup() part of the sketch, we need to specify that the motor pins will behave as output pins, as shown in the following code:
for(int i=4;i<=7;i++)
{
pinMode(i, OUTPUT);
}

 

We also need to set a starting speed for the robot. Note that the speed of each motor will be set by PWM commands coming from the Arduino, so we have to specify a value between 0 (no voltage applied to the motor) and 255 (maximum voltage applied to the motor). Also, because of mechanical resistance on the motors, there is no linear relationship between the value of the PWM command and the speed of the motor.

 

We used the value 75 as a starting speed, which is a very slow speed on our DC motors. However, depending on your own setup, this value will have a completely different effect. At this point, you can also experiment to see what the maximum PWM value is that will give you exactly zero speed on your DC motors. Make sure that the robot is not on the floor just yet as it would start to move forward and possibly damage things. We put it on a small stand so the wheels don't touch anything.

 

In the loop() part, everything is done by the function send_motor_command, which will be called for both motors. For example:

send_motor_command(speed_motor1,direction_motor1,robot_speed,1);

 

Let's see the details of this function. It starts by writing the speed of the motor on the correct pin as follows:

analogWrite(speed_pin,pwm);

 

Then, we need to set the direction pin to the correct direction. This is done by a simple digitalWrite function as follows:

digitalWrite(direction_pin,dir);

Still, in the loop() function, we call a function to measure the distance in front of the robot and print the result on the Serial port:

Serial.println(measure_distance(A0));

 

Let's see the details of this function. It starts by getting the raw measurement from the sensor using the pulseIn function. Basically, the sensor returns a pulse whose length is proportional to the measured distance. The length of the pulse is measured with the following function of Arduino dedicated for that purpose:

unsigned long DistanceMeasured=pulseIn(pin,LOW);

 

Then, we check whether the reading is valid and if it is, we convert it to centimeters using the following formula:

Distance=DistanceMeasured/50;

 

This is returned with the following code:

return Distance;

 

Finally, we update the speed at every iteration of the loop by increasing it by one unit, and we reset it if it reaches 255, as shown in the following code:

robot_speed++;

if (robot_speed > 255) {robot_speed = 75;}

 

It's now time to upload the code to the robot. Before doing so, please make sure that the robot is powered by the battery. Both motors of the robot should gradually accelerate upon reaching the maximum speed and then start again at a lower speed. You can also open the serial monitor at this point to check the readings from the distance sensor. Try moving your hand or an object in front of the robot; you should see the distance changing accordingly on the serial monitor.

 

Building the Arduino sketch

It's now time to build the final sketch for our project. To be really precise, we should say sketches because we will have to develop two of them: one for the Uno board and one for the Yún board. You just have to make one simple change to the hardware at this point: connect the ultrasonic sensor directly to the Yún board by connecting the signal pin to the pin A0 of the Yún board.

 

Let's first focus on the Arduino Uno sketch. The sketch is inspired by the test sketch we wrote before, so it already includes the functions to control the two DC motors. To communicate between the two boards, we have to include the Wire library that is in charge of handling I2C communications:

#include <Wire.h>

 

Then, in the setup() part of the sketch, we need to declare that we are connecting to the I2C bus and start listening for incoming events. The Uno board will be configured as a slave, receiving commands from the Yún board, which will act as the master. This is done by the following piece of code:

Wire.begin(4);

Wire.onReceive(receiveEvent);

 

Let's see the details of this receiveEvent part, which is actually a function that is passed as an argument to the onReceive() function of the Wire library. This function will be called whenever an event is received on the I2C bus. What this function does is basically read the incoming data from the Yún, which has to follow a specific format like you can see in the following example:

speed_motor_1,direction_motor_1,speed_motor_2,direction_motor_2

 

For example, the first part of the previous message is read back with the following code:

int pwm1 = Wire.read();

Serial.print(pwm1);

char c = Wire.read();

Serial.print(c);

 

These commands that come from the Yún are then applied to the motors as follows:

send_motor_command(speed_motor1,direction_motor1,pwm1,dir1); send_ motor_command(speed_motor2,direction_motor2,pwm2,dir2);

Let's now focus on the Yún sketch. This sketch is inspired by the Bridge sketch that comes with the Arduino IDE and is based on the REST API of the Arduino Yún. To make things easier, we are going to create a new kind of REST call named the robot.

 

This way, we are going to be able to command the robot by executing calls like the following in your browser: myarduinoyun.local/arduino/robot/stop

 

First, we need to include the correct libraries for the sketch as follows:

#include <Wire.h>
#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>
Then, create a web server on the board:
YunServer server;
In the setup() function, we also join the I2C bus:
Wire.begin();
Then, we start the bridge:
Bridge.begin();
The setup() function ends by starting the web server as follows:
server.listenOnLocalhost();
server.begin();
Then, the loop() function consists of listening to incoming connections as follows:
YunClient client = server.accept();
The requests that come from these clients can be processed with the following command:
if (client) {
// Process request process(client);
// Close connection and free resources. client.stop();
}
If a client is connected, we process it to check whether or not a robot command was received, as follows:
String command = client.readStringUntil('/');
if (command == "robot") {
robotCommand(client);
}

 

This function processes the REST call to see what we need to do with the motors of the robot. For example, let's consider the case where we want to make the robot go forward at full speed. We need to send the following message to the Arduino Uno board: 255,0,255,0

This is done by the following piece of code:

if (command == "fullfw") {
Wire.beginTransmission(4);
Wire.write(255);
Wire.write(",");
Wire.write(0);
Wire.write(",");
Wire.write(255);
Wire.write(",");
Wire.write(0);
Wire.endTransmission();
}

 

We included three other commands for this simple REST API: stop (which obviously stops the robot), turn left (which makes the robot turn left at moderate speed), turn right (which makes the robot turn right), and get distance to return the distance coming from the ultrasonic sensor. We also inserted the measure_distance function in the sketch to read data that comes from the ultrasonic sensor.

 

We are now ready to upload the code to the robot. Remember that you have to upload two sketches here: one for the Uno board and one for the Yún board. The order doesn't matter that much, just upload the two Arduino sketches successfully by carefully ensuring that you are uploading the correct code to the correct board. 

 

You can then test that the Yún board is correctly relaying commands to the Uno board. At this point, you can disconnect all cables and power the robot with the battery only. Then, go to a web browser and type the following code:myarduinoyun.local/arduino/robot/turnright

 

The robot should instantly start turning to the right. To stop the robot, you can simply type the following code:myarduinoyun.local/arduino/robot/stop. You can also type the following code: myarduinoyun.local/arduino/robot/getdistance

 

This should print the value of the distance in front of the robot on your web browser. If you can see a realistic distance being printed on your web browser, it means that the command is working correctly.

 

Building the computer interface

We are now going to build an interface so you can control the robot remotely from your computer or a mobile device. This is actually quite similar to what we did for the relay control project, the main difference is that we also want to read some data back from the robot (in the present case the distance measurement from the ultrasonic sensor).

 

There will be an HTML file that will host the different elements of the interface, some PHP code to communicate with the Yún board, some JavaScript to establish the link between HTML and PHP, and finally some CSS to give some style to the interface.

 

The first step is to create the HTML file that will be our access point to the robot control. This file basically hosts four buttons that we will use to control our robot and a field to continuously display the distance measured by the ultrasonic sensor. The buttons are declared inside a form; the following is the code for one button:

<input type="button" id="stop" class="commandButton" value="Stop" onClick="stopRobot()"/>
The distance information will be displayed using the following line of code:
<div id="distanceDisplay"></div>
The following field will be updated with some JavaScript:
<script type="text/javascript">setInterval(function(){$("#distanceDisplay").load("get_distance.php")},1000);</script>

 

Let's see the content of this PHP file. It basically makes a call to the REST API of the Yún board and returns the answer to be displayed on the interface. Again, it will make use of the curl function of PHP.

 

It starts by making the cURL call to your Yún board with the getdistance parameter we defined in the sketch before:

$service_url = 'http://myarduinoyun.local/arduino/robot/getdistance';

It then prepares the call with the following code:
$curl = curl_init($service_url);
We get the answer with the following code:
$curl_response = curl_exec($curl);
We then print it back with the echo function of PHP:
echo $curl_response;

 

The PHP script that commands the motors is quite similar, so we won't detail it here.

Let's see the JavaScript file that handles the different buttons of the interface. Each button of the interface is basically linked to a JavaScript function that sends the correct parameter to the Arduino Yún, via the PHP file. For example, the stop button calls the following function:

  • function stopRobot(){
  • $.get( "update_state.php", {command: "stop"} );
  • }

 

The same is done with the function to make the robot go full speed forward. To make it turn left or right, we can implement a more complex behavior. What we usually want is not for the robot to turn continuously by itself, but for example, to turn off a quarter of a turn. This is where the approach we took in this project becomes powerful. We can do that right on the server side without having to change the sketch on the Arduino board.

 

That's why to turn right for a given amount of time, for example, we will implement a series of commands on the server side and then stop. This is done by the following code:

  • function turnRight(){
  • $.get( "update_state.php", { command: "turnright"} ); sleep(350);
  • $.get( "update_state.php", { command: "stop"} );
  • }

The sleep function itself is implemented in the same file and works by comparing the time that passed since the function was called, as shown in the following code:

function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){ break;
} }
}

 

Of course, we invite you to play with this sleep function to get the desired angle. For example, we set our sleep function such that the robot turns off about a quarter of a turn whenever we press the Turn Right button.

 

The code for the interface is available on the GitHub repository of the project:

https://github.com/openhomeautomation/geeky-projects-yun/tree/master/ blog4/remote_control

 

Now, it's time to start the project. Be sure to place all the files at the root of your web server and make sure that the web server is running. Then, go to the folder of your web server in your browser (usually by typing localhost) and open the HTML file. The project also contains a CSS sheet to make the interface look better. The following is what you should see in your browser:

 

The field that displays the distance reading from the ultrasonic sensor should be updated automatically every second, so you can see whether or not this is working right away. Try moving your hand or an object in front of the robot and the value should change accordingly.

 

Before making the robot move around, we recommend that you test the different buttons while the robot is still on a small stand so it cannot move. Indeed, if something is wrongly coded on your server or within the Arduino sketch, your robot will not respond anymore and will randomly hit objects in your home.

 

You can now also test the different buttons. You can especially focus on the buttons that make the robot turn left or right and adjust the sleep() function in the PHP code to make them do exactly what you want. Notice that while your robot is moving around, the distance detected by the ultrasonic sensor in front of the robot is updated accordingly.

Arduino Robot-Best Arduino Projects 2018

How to make Arduino Robot: Best Arduino Projects

Now that your robot is mobile and has several ways of sensing the outside world. In this blog, we explain How to make Arduino Robot and discuss the Best Arduino robot Projects. In this blog, you also learn the following topics that given below.

  • Connecting Arduino to a simple radio frequency (RF) transmitter/receiver pair
  • Connecting Arduino to an XBee transmitter/receiver pair
  • Connecting Arduino to a Bluetooth transmitter/receiver pair
  • Connecting Arduino to a Wi-Fi network using a Wi-Fi shield

 

As your Arduino will now be remote, you'll need to power it with an external source. Your Arduino will need at least 250 mA, but you might want to consider providing 500 mA to 1 A based on your project. To supply this from a battery, you can use one of several different choices. One choice is a 4 AA battery pack, like the one used to power the DC motors on the wheeled robot.

 

Connecting a simple RF interface to Arduino

Arduino Robot

Let's start by connecting to Arduino with a simple RF interface. For this exercise, it will be easiest if you connect your development machine to Arduino with an RF interface and then connect to another Arduino with a similar RF transceiver.

 

There are some very inexpensive modules available at online retailers such as ebay.com, but you will need to be a bit careful and watch what frequency your devices use, as they may violate your country's frequency usage rules.

 

Each country regulates who can use what frequencies. For more information, visit www.wired.com/2010/09/ wireless-explainer/. For example, 433 MHz is fine for Europe, but can't be used in the US unless you have the proper amateur radio license. 915 MHz is available in the US but not in Europe. 2.4 GHz is fine in either case, so you might want to go with a transceiver that operates at 2.4 GHz.

 

You will want to purchase two of these devices. Initially, to try the example, connect each of the pairs to your Arduino. You will also need to connect each device to a host computer so that you can monitor the Serial Monitor port.

 

Eventually, when you have the system up and working, disconnect one of the devices from the host computer and connect it to a battery so that it can run without a host connection. To connect the devices to Arduino, connect to the pins on the back of the device. The following is an image of the connections on the back of the device:

Arduino Robot-Best Arduino Projects

The following table shows the connections between the device and the Arduino:

  • Arduino pin Receiver pin
  • 5 V 5 V
  • GND GND
  • 12 MISO
  • 11 MOSI
  • 13 SCK
  • 8 CE
  • 7 CSN

Connect the second Arduino in the same way as the first. Now, you are ready to access two Arduino IDEs, one for each of these two Arduinos.

 

Enabling a simple RF interface in the Arduino IDE

Let's start with Arduino that will receive the RF signal. You'll need to plug it into the host computer via a USB cable in order to upload a program. In order to debug both of these devices, you will also need two computers, one to run an Arduino IDE for both the transmit and receive the device.

 

You can also do this with a single computer and two USB ports (for more information on how to do this, visit http://forum. arduino.cc/index.php?topic=407.0).

 

However, once you've created the program, you can disconnect the remote Arduino from the computer and power it from a battery. In this example, you'll use the example programs from the library to send data from the client (Arduino connected to the PC) to the server (the standalone Arduino) and then have it echo back.

 

As you did earlier, you'll first need to install the library. There are a couple of possible libraries, but the one that is the most full-featured is the RF24 library, which is available at https://github.com/maniacbug/RF24/.

 

To get the full library, select the Download ZIP button on the right side of the screen. Unzip the archive into a directory and then copy the directory to the libraries directory of your Arduino installation. You'll also need to rename this directory; I renamed mine RF24. To do this demo, you'll need two host computers, one for each RF device.

 

On both computers, open the Arduino IDE and bring up the server code by navigating to File | Examples | RF24 | GettingStarted, as shown in the following screenshot:

 

This Arduino will now have the code to configure the interface. When you bring up Serial Monitor, 

This shows the configuration of the first device. If you receive 0 for all values, you probably have your device connected incorrectly. Initially, this first device will be in receive mode, listening for a message, and when it receives one, it will send this message back to the sender.

 

Now, do the exact same thing on the second Arduino. The code you have will run and will also be waiting to send some information. On this second device, type the character T in the input field at the top of Serial Monitor and then hit Send. Now, you should begin to see the results on the send Serial Monitor. If you check the first device's Serial Monitor tab, you should see that it is now receiving the sending device's message.

 

Now, you can disconnect the receive Arduino; it will retain this program and run it each time the unit is powered on. Connect this Arduino to a battery by plugging the battery GND and VCC to the GND and VIN pins on this receive Arduino. If you are using a cell phone's USB charger, you can connect it to the USB port on Arduino.

 

The LED on the receive Arduino should be flashing, indicating that the two Arduinos are communicating.

To change the code to send a command byte, look for the following code that gets the milliseconds from the time function and sends it out to the other Arduino:

  • // Take the time, and send it. This will block until complete
  • unsigned long time = millis(); printf("Now sending %lu...",time);
  • bool ok = radio.write( &time, sizeof(unsigned long));

 

Now, change the code on the sending Arduino so that instead of sending the time, it sends a command byte that you define. Then, on the receive Arduino, look for the following code:

 

// Grab the response, compare, and send to debugging spew

  • unsigned long got_time;
  • radio.read( &got_time, sizeof(unsigned long) ); // Spew it
  • printf("Got response %lu, round-trip delay: %lu\ n\r",got_time,millis()-got_time);
  • Finally, change this code to take the command byte that you defined and then trigger some action.

 

Connecting an XBee interface to Arduino

Xbee

One of the most popular and well-documented ways of connecting to Arduino via an RF connection is to use an XBee device. This device uses a technology called ZigBee, and it is made for long-range wireless communications. These types of devices can work up to a range of 1 mile.

 

The ZigBee standard is built upon the IEEE 802.15.4 standard, a standard that was created to allow a set of devices to communicate with each other to enable low data rate coordination of multiple devices.

 

The other standard that you might hear as you try to purchase or use devices like these is XBee. This is a specific company's implementation, Digi, of several different wireless standards with standard hardware modules that can connect in many different ways to different embedded systems. They make several devices that support the ZigBee standard.

 

The advantage of using this device is that it is configured to make it very easy to create and manage a simple link between two XBee series 1 device. To make this work, you'll need the following four items:

 

Make sure you have two XBee devices that support ZigBee series #1.

You'll also need to purchase a small XBee-specific shield that provides a USB port connected to one of the two devices. This will provide communication from a host computer. You'll also need to buy a shield that plugs into your Arduino so that you can interface with the XBee devices. The following is an image of the shield plugged into Arduino with the XBee device plugged in:

 

Now, let's start to configure your two devices to talk. You'll need to configure both devices by plugging them into your host computer. Plug one of the devices into the small XBee-specific USB shield and then connect the shield to your personal computer.

 

Your computer should find the latest drivers for the device. You should see your device when you select the Devices and Printers selection from the Start menu, as shown in the following screenshot:

 

The device is now available to communicate via the IEEE 802.15.4 wireless interface. We could set up a full ZigBee-compliant network, but we're just going to communicate from one device to another directly. So, we'll just use the device as a serial port connection. Double-click on the device and then select the Hardware tab; you should see the following screenshot:

 

Note that the device is connected to the COM20 serial port. We'll use this to communicate with the device and configure it. You can use any terminal emulator program; I like to use PuTTY. 

If you don't have PuTTYyou can download it from  www.chiark.greenend.org.uk/~sgtatham/putty/download.html. This will provide an executable file that you can run to talk with and configure the devices.

 

Perform the following steps to configure the device:

1. Open up PuTTY and select the Serial selection and, in this case, the COM20 port. The following screenshot shows you how to fill in the PuTTY window:

2. Configure the terminal window and set the following parameters:

  • Speed (baud) as 9600
  • Data bits as 8
  •  Stop bit as 1
  •  Parity as None

 

3. Make sure that you also select Force on in the Local echo option and check the Implicit CR in every LF and Implicit LF in every CR checkboxes (available under the Terminal tab in the Category selection), as shown in the following screenshot:

 

4. Connect to the device by selecting Open.

 

5. Enter the following commands to the device through the terminal window:

The OK response comes back from the device as you enter each command. The first device is now configured. Remove it from the small XBee-specific shield and plug it into the Arduino XBee shield.

 

Now, plug the second device into the small XBee shield and then plug it into the PC. Note that it might choose a different COM port; go to the Devices and Printers selection, double-click on the device, and select the Hardware tab to find the COM port.

 

Follow the same steps to configure the second device, except that there are two changes. The ATMY value will be 2, and the ATDL value will be 1. The following screenshot shows the terminal window for these commands: The two devices are now ready to communicate.

 

Enabling an XBee interface in the Arduino IDE

Let's first set up the Arduino IDE for XBee that will be connected to your Arduino. Once you have connected all the shields to your Arduino, simply connect your Arduino with the USB cable to one of the computers. Bring up the Arduino IDE and then type in the following code into the sketch window:

 

This sketch is quite simple; you can turn on the onboard LED with remote commands, 1 to turn it on and 0 to turn it off. Once you have compiled and uploaded this code, disconnect the USB cable from the computer.

 

You'll need to physically change a switch setting on the wireless shield so that the device will now accept commands from your XBee controller. It is on the opposite end of the shield and looks like the following image:

 

When you are programming the device, you'll want this switch to be in the USB location. When you are ready to communicate with the device, you'll want to switch this to the MICRO setting. So, change it to the MICRO setting once your sketch has finished compiling and uploading to Arduino. Then, connect your Arduino to a battery.

 

Now, connect the other XBee device via the small Xbee-specific USB shield to the computer. Open PuTTY or any other terminal emulator window. Make sure that you set the terminal emulator data rate to 9800 baud. In PuTTY, your configuration will look like the following screenshot:

 

Now, open the terminal window. You should now be able to type 1 and the LED on the remote Arduino will turn on. Typing 0 should turn off the LED. Your PuTTY window should look like the following screenshot if you select Force on in the Local echo option and if the Implicit CR in every LF and Implicit LF in every CR options are checked:

 

Now, if your system is not working, there are a couple of ways to try and determine what is going wrong. First and foremost, make sure Arduino is turned on and is executing the correct code. Second, check to see that characters are being typed in the PuTTY window. Third, check the baud rate of the PuTTY window. If this is too high, you will see characters come through the system, but they will not be interpreted correctly on Arduino.

 

Connecting a Bluetooth shield to Arduino

bluetooth

Another way of communicating wirelessly with Arduino is through a Bluetooth link. Bluetooth is a standard communications protocol that also works at 2.4 GHz. To read more about the Bluetooth protocol, visit http://www.bluetooth.com/Pages/ Fast-Facts.aspx.

 

There are several possible ways to connect your Arduino using Bluetooth, but the most reliable one is a Bluetooth shield, which is available at www.adafruit.com. The following is an image of the shield:

 

Unfortunately, you'll need to solder header pins onto the shield to mount it on your Arduino, but then, you'll need no additional connections. You'll also need a USB module if you want to communicate with your PC. The following is an image of an adapter that is also available at www.adafruit.com:

 

The learn.adafruit.com/introducing-bluefruit-ez-link/overview website will lead you through the details of how to get the shield up and working, paired with your Bluetooth dongle, and communicating with your other Bluetooth devices.

 

Connecting a Wi-Fi shield to Arduino

wifi

The final method you might consider to connect your Arduino wirelessly is with a wireless LAN shield. I will not cover Wi-Fi in detail, but rather just show you how to connect to Wi-Fi and point you in the general direction. Wi-Fi is clearly the most complex of the different ways to communicate, but it is a very common wireless communication tool used today.

 

To know more about Wi-Fi, visit www.squidoo.com/what-is-wifi or www.radio-electronics.com/info/wireless/wi-fi/ ieee-802-11-standards-tutorial.php. In order to connect to a wireless network, you'll need a Wi-Fi shield. Place the shield onto the Arduino Uno and you are ready to connect to a wireless network.

 

Enabling the Wi-Fi shield in the Arduino IDE

Now that the shield is attached, you can access the standard library examples for Wi-Fi. Navigate to Examples | WiFi and you'll see a number of useful example programs, as shown in the following screenshot:

 

These are all very useful examples. Just to make sure that your shield works, you can select ScanNetworks. Run this program and open Serial Monitor. This program scans for available networks and should show a set of networks that are possible to connect to.

 

However, if you want to configure your Arduino as a Wi-Fi web server, you can access it via the Internet and get or send information to your Arduino via the Wi-Fi network. An excellent example to get you started is SimpleWebServerWiFi. Here, you enter your SSID and password and you can turn on an LED. I would suggest that you change the LED to pin 13, and you can then turn on and off the onboard LED via the instructions at the top of the file.

 

Connecting a GSM/GPRS shield to Arduino

There is one more way to connect remotely with Arduino, and this is via a GSM/ GPRS shield. You'll also need access to a phone plan and a SIM card. I will not cover this in this blog, so for more information, visit arduino.cc/en/Guide/ ArduinoGSMShield.

 

Using a GPS Device with Arduino

GPS

You've got quite a set of tools now to build amazing robots. One part that is not yet covered, however, is giving your robot an idea of where it is in the world. This is particularly useful for autonomous robots that might have to travel long distances. Keeping track of its location would be useful, so you can not only know where your robot is but also plan where it should go. In this blog, you'll learn the following:

 

  • How to connect a GPS device with Arduino using the I2C bus
  • How to connect GPS capability using an Arduino shield

 

Let's get started with a brief GPS tutorial.

 

GPS tutorial

The Global Positioning System (GPS) is a system of satellites that transmit signals. GPS devices use these signals to calculate a position. There are a total of 24 satellites that transmit signals all around the earth at any given moment, but your device can only see the signal from a much smaller set of satellites.

 

Each of these satellites transmits a very accurate time signal that your device can receive and interpret. It receives the time signal from each of these satellites, and then, based on the delay (the time it takes the signal to reach the device), it calculates the receiver's position using a technique called triangulation.

 

GPS device

The GPS device is able to detect the three signals and the time delays associated with receiving these signals. Time delay refers to the time difference between the travel time of each of these three signals.

 

The time delays of the signals T1, T2, and T3 can provide the GPS with an absolute position using a mathematical process called triangulation. Triangulation works like this: since the position of the satellites is known, the amount of time that the signal takes to reach the GPS device is also a measure of the distance between that satellite and the GPS device.

 

To simplify, let's show an example in two dimensions. If the GPS device knows the value of the distance to one satellite based on the amount of time delay, you can draw a circle around the satellite at that distance and know that your GPS device is on that sphere, as shown in the following diagram:

 

If you have two satellite signals and know the distance between the two:

T1 = distance to the edge of the circle

T2 = distance to the edge of the circle

 

However, since you know that you can only be at points on the circle, you must be at one of the two points that are on both circles. Adding an additional satellite would eliminate one of these two points, thus providing you with an exact location. You need more satellites if you are going to do this in all three dimensions.

 

Now that you know how a GPS device works, let's connect one to Arduino.

 

The first step is to find a suitable GPS device. There are many choices, but what you are looking for is a GPS device that can communicate via a bus that is available on Arduino. One possible device is VPN1513 GPS Receiver w/ Antenna, marketed by Parallax and available on their online store, www.parallax.com.

 

Fortunately, this unit comes with its very own antenna, and you'll connect this to the RF (gold) connector on the board. This particular device interfaces using the I2C interface, one that your Arduino supports. In order to connect the device, you connect the pins to the board. The following is an image of these pins:

 

You'll connect your Arduino using the following connections:

  • Arduino pin GPS cable pin
  • 5V 5V
  • GND GND
  • 4 TX
  • 3 RX

Now that the two devices are connected, you can access the device via the Arduino IDE.

 

Accessing the GPS device from the Arduino IDE

 

Now that your device is connected, you'll want to access the information from it programmatically. To do this, perform the following steps:

1. Copy the libraries and example programs for Arduino from www.parallax.com/downloads/vpn1513-gps-receiver-w-antenna-arduino-example-code.

2. Install the TinyGPS library into the libraries directory of Arduino.

3. Then, open the test_with_gps_device example, as shown in the following screenshot:

4. When you run that program and open the Serial Monitor tab, you should see the following display:

 

The information shows the status of the GPS receiver as well as the position, speed, time, date, and direction information. The status indication is the first column of data for each reading. This is important as it will tell you whether your device is reading enough satellites to get a valid positional calculation.

 

This particular output indicates that even with your antenna, you are not getting a valid output. This means that your device cannot sense enough satellites to accurately calculate your current position.

 

Take the unit outside or at least near a window, and your device should be able to connect to enough satellites to get a value reading. Also, your display will change to the one seen in the following screenshot:

 

For more information on the TinyGPS library, the data it gets from the GPS, and the purpose of all of the columns, visit arduiniana.org/libraries/tinygps/.

 

Connecting a GPS shield to Arduino

GPS_ardunio

Now that you have an idea of how to connect a GPS device through the I/O pins on Arduino, let's look at a different way to provide GPS information to Arduino, through a GPS shield. There are several shields available, including one from Dexter Industries that is available at many online retailers, such as www.amazon.com.

 

To connect to Arduino, simply push the shield on your Arduino device. You can use the pin labels to match the pins on Arduino. Now, it is securely on top of your Arduino device; let's look at how to access the device via the SW.

 

Accessing the GPS shield from the Arduino IDE

The GPS shield provides the hardware interface to the GPS device. Now, you can access the GPS data from inside the Arduino IDE. To do this, perform the following steps:

 

1. As with most devices, the first step is to download the appropriate libraries. For this device, you'll find the libraries at www.dexterindustries.com/ manual/arduino-shields/gps-shield/ under the Arduino GPS Shield Drivers (zip) selection.

 

2. Unzip the dGPS file and copy the dGPS file folder to your Arduino's libraries directory. You'll also need to download another three examples from this page. These aren't really set up to put in the Examples directory of dGPS and open automatically using the File | Examples process, but you can simply open them by navigating to File | Open command.

 

3. Once you have the library installed, let's write a simple program that reads the values from the GPS device. Open the Arduino IDE and type in the following code:

 

4. Now, upload the preceding code to Arduino and then open Serial Monitor. You should see something like the following screenshot:

 

These are the GPS readings from the device. As noted in the previous section, Status tells you whether or not your device is locked to enough satellites. In this case, V indicates that our device is not. You may need to go outside a building to connect with enough satellites to get a valid reading. A valid reading would look like the following screenshot:

 

The library for this device is quite extensive, and you can get back much more than your position. In fact, Example 2: Calculating GPS distance to destination, azimuth (angle of travel) to the destination. (zip) that you can download from www.dexterindustries.com/manual/arduino-shields/gps-shield/ will show you how to use the library to enter a desired latitude and longitude value and return the distance as well as the angle of travel to the desired location.

 

Creating a GPS Tracker with Arduino

We are now going to build a very common tool that any secret agent should have: a GPS tracker. We'll use the Arduino platform again to build our own DIY GPS tracker. We will actually build two applications using the same hardware:

  • The first one will be a location device that sends its position via SMS
  • The other project will be a GPS tracker that you can actually locate live on a map

Let's dive in!

Hardware and software requirements

First, let's see what the required components are for this project. As usual, we are going to use an Arduino Uno board as the central part of the project.

 

For the GPRS and GPS parts, we are going to use the Adafruit FONA 808 module again, Opening a Lock with an SMS. We'll also need a GSM antenna for GSM/GPRS communications. However, as here we want to use the onboard GPS, we'll also need an additional GPS antenna. I used a standard uFL passive GPS antenna from Adafruit:

 

Then, you will need a battery to power the FONA shield and the onboard GPS module, as the Arduino Uno board doesn't allow you to power the FONA shield (it can use up to 2A at a time!). For that, I used a 3.7V LiPo battery, along with a micro USB battery charger.

 

A very important part of the project is the SIM card, which you need to place inside the FONA shield. You will need a normal SIM card (not micro or nano), which is activated, not locked by a PIN, and able to receive text messages. You can get one at any of your local mobile network operators.

 

Also, in this blog, you also need to have a data plan active with at least 1 MB of credit on the account. Finally, here is a list of all the components that we will use in this project:

  • Arduino Uno (https://www.sparkfun.com/products/11021)
  • Adafruit Fiona 808 breakout (http://www.adafruit.com/product/2542)
  • GSM uFL antenna (http://www.adafruit.com/products/1991)
  • GSM SIM card
  • 3.7V LiPo battery (http://www.adafruit.com/products/328)
  • LiPo battery charger (http://www.adafruit.com/products/1904)
  • Passive GPS antenna (https://www.adafruit.com/product/2461)
  • Breadboard (https://www.sparkfun.com/products/12002)
  • Jumper wires (https://www.sparkfun.com/products/8431)

 

On the software side, you'll only need the latest version of the Arduino IDE, and the Adafruit FONA library. You can install this library using the Arduino IDE library manager.

 

Hardware configuration

It's now time to assemble the hardware of this project.  First, connect the power supply to the breadboard: connect the 5V pin from the Arduino board to the red power line on the breadboard, and the GND pin to the blue power line. Then, place the FONA shield on the breadboard. Connect the VIO pin to the red power line, and the GND and Key pins to the blue power line.

 

After that, connect the RST pin to Arduino pin 4, TX to Arduino pin 3, and RX to Arduino pin 2. Also connect the 3.7V LiPo battery, the GPS antenna, and the GSM antenna to the FONA shield. This is a close-up picture of the shield after the project was assembled, And this is an overview of the whole project assembled:

 

Testing the location functions

Before we dive into the two exciting projects of this blog, we'll first make a simple test using the FONA shield, and see whether it can actually locate our project on a map. The sketch will actually test whether the GPS location is working correctly.

 

This is the complete code for this part:

// Libraries

#include "Adafruit_FONA.h"
#include <SoftwareSerial.h>
// Pins
#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4
// Buffer
char replybuffer[255];
// Instances
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); SoftwareSerial *fonaSerial = &fonaSS; Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
void setup() {
// Init board
while (!Serial); Serial.begin(115200); Serial.println(F("FONA location test")); Serial.println(F("Initializing....(May take 3 seconds)"));
fonaSerial->begin(4800);
if (! fona.begin(*fonaSerial)) {
Serial.println(F("Couldn't find FONA"));
while(1);
}
Serial.println(F("FONA is OK"));
// Print SIM card IMEI number.
char imei[15] = {0}; // MUST use a 16 character buffer for IMEI!
uint8_t imeiLen = fona.getIMEI(imei);
if (imeiLen > 0) {
Serial.print("SIM card IMEI: "); Serial.println(imei);
}
// Setup GPRS APN (username/password optional) fona.setGPRSNetworkSettings(F("your_APN")); //fona.setGPRSNetworkSettings(F("your_APN"), F("your_username"),
F("your_password"));
// Turn GPS on
if (!fona.enableGPS(true)) { Serial.println(F("Failed to turn on GPS"));
}
// Turn GPRS on
fona.enableGPRS(true);
// Decide between GPS or GPRS localisation boolean GPSloc;
int8_t stat;
// Check GPS fix
stat = fona.GPSstatus();
if (stat < 0) {
GPSloc = false;
}
if (stat == 0 || stat == 1) {
GPSloc = false;
}
if (stat == 2 || stat == 3) {
GPSloc = false;
}
// Print which localisation method is used Serial.print("Localisation method: ");
if (GPSloc) {Serial.println("GPS");} else {Serial.println("GPRS");}
// Print position
if (GPSloc) {
char gpsdata[80];
fona.getGPS(0, gpsdata, 80);
Serial.println(F("Reply in format: mode, longitude, latitude, altitude, utctime(yyyymmddHHMMSS), ttff, satellites, speed, course"));
Serial.println(gpsdata);
}
else {
uint16_t returncode;
if (!fona.getGSMLoc(&returncode, replybuffer, 250))
Serial.println(F("Failed!"));
if (returncode == 0) {
Serial.println(replybuffer);
} else {
Serial.print(F("Fail code #")); Serial.println(returncode);
}
} }
void loop() {
// Nothing here
}
We are now going to look at the important parts of this sketch.
It starts by importing the required libraries:
#include "Adafruit_FONA.h"
#include <SoftwareSerial.h>
Then, we define the pins that the FONA is connected to:
#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4
We create some instances for the SoftwareSerial object and the FONA breakout:
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); SoftwareSerial *fonaSerial = &fonaSS; Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
Then, we initialize the FONA:
while (!Serial);
Serial.begin(115200);
Serial.println(F("FONA location test"));
Serial.println(F("Initializing....(May take 3 seconds)"));
fonaSerial->begin(4800);
if (! fona.begin(*fonaSerial)) {
Serial.println(F("Couldn't find FONA"));
while(1);
}
Serial.println(F("FONA is OK"));
Following this is where you need to put your GPRS data. This completely depends on your phone carrier. I simply had to put in an APN, which was internet, but you might have to put a username and password as well. Contact your carrier to get the exact information, and then comment/uncomment the required line and fill out the data:
fona.setGPRSNetworkSettings(F("your_APN")); //fona.setGPRSNetworkSettings(F("your_APN"), F("your_username"), F("your_password"));
Then, we can enable the GPS:
if (!fona.enableGPS(true)) { Serial.println(F("Failed to turn on GPS"));
}
We also enable the GPRS connection:
fona.enableGPRS(true);
When this is done, we get the state of the GPS, and check whether we can locate a GPS satellite and get a fix. If yes, we'll use the GPS for location purposes. If not, we'll switch to a GPRS location:
stat = fona.GPSstatus();
if (stat < 0) {
GPSloc = false;
}
if (stat == 0 || stat == 1) {
GPSloc = false;
}
if (stat == 2 || stat == 3) {
GPSloc = false;
}
Once we know which location method to use, we can actually get the location, depending on the chosen method:
if (GPSloc) {
location = getLocationGPS();
latitude = getLatitudeGPS(location);
longitude = getLongitudeGPS(location);
latitudeNumeric = convertDegMinToDecDeg(latitude.toFloat()); longitudeNumeric = convertDegMinToDecDeg(longitude.toFloat());
}
else {
location = getLocationGPRS();
latitude = getLatitudeGPRS(location);
longitude = getLongitudeGPRS(location);
latitudeNumeric = latitude.toFloat();
longitudeNumeric = longitude.toFloat();
}
Serial.print("Latitude, longitude: ");
Serial.print(latitudeNumeric, 6);
Serial.print(",");
Serial.println(longitudeNumeric, 6);

 

As you can see, we are calling a few helper functions here to get the latitude and longitude as float variables. We are now going to see all these functions in detail.

Here is the detail of the function to get the location using GPS:

String getLocationGPS() {

// Buffer
char gpsdata[80];
// Get data
fona.getGPS(0, gpsdata, 80);
return String(gpsdata);
}
This function is really simple, as it simply gets the data from the GPS of the FONA, and returns it as a String.
The function to get the location using GPRS is similar:
String getLocationGPRS() {
// Buffer for reply and returncode char replybuffer[255];
uint16_t returncode;
// Get and return location
if (!fona.getGSMLoc(&returncode, replybuffer, 250))
return String("Failed!");
if (returncode == 0) {
return String(replybuffer);
} else {
return String(returncode);
}
}

 

Then, we actually need to extract the data from the returned String object, and get the latitude and longitude of our GPS module. Here is the function for the longitude using the GPRS location:

String getLongitudeGPRS(String data) {

// Find commas
int commaIndex = data.indexOf(',');
int secondCommaIndex = data.indexOf(',', commaIndex+1);
return data.substring(0, commaIndex);
}
This is the function to get the latitude using the GPRS location:
String getLatitudeGPRS(String data) {
// Find commas
int commaIndex = data.indexOf(',');
int secondCommaIndex = data.indexOf(',', commaIndex+1);
return data.substring(commaIndex + 1, secondCommaIndex);
}
For the GPS location, things are similar. However, we need one extra function for the GPS module. Indeed, the latitude and longitude are given in degrees-minutes-seconds, and we need to convert this to a numeric format. This is done using the following function:
double convertDegMinToDecDeg (float degMin) { double min = 0.0;
double decDeg = 0.0;
// Get the minutes, fmod() requires double min = fmod((double)degMin, 100.0);
//rebuild coordinates in decimal degrees
degMin = (int) ( degMin / 100 );
decDeg = degMin + ( min / 60 );
return decDeg;
}

 

It's now time to test the sketch! Simply put all the code in the Arduino IDE, update your GPRS settings, and upload it to the board. Then, open the serial monitor and this is what you should see: As you can see, I was testing this while indoors so the sketch using the GPRS location.

 

I then simply copied the latitude and longitude and pasted them into Google Maps:

I immediately saw a point close to my own location, which was 100-150 meters off my real location. Not too bad if you need to track whether something is inside or outside a city for example.

 

I then tried again outside, with nothing between the GPS antenna and the sky. Then, the sketch automatically selected the GPS location option. I then also copied and pasted the GPS latitude and longitude into Google Maps:

 

Sending a GPS location by SMS

Now that we have the location part working correctly, we can start building our GPS tracking projects for secret agents. The first project will simply use the location and send it via SMS to the phone number of your choice.

 

As the sketch is quite similar to the previous one, I'll only show which parts changed compared to the location test sketch. We first need to define the phone number where you want to send the tracking data to: char * sendToNumber = "123456789";

 

After getting the location just as in the previous section, we can now build the message that we will send via SMS:

char messageToSend[140];

String message = "Current GPS location: " + latitude + "," + longitude;
message.toCharArray(messageToSend, message.length());
Using the FONA instance, it's very easy to actually send the SMS to the number we defined earlier:
if (!fona.sendSMS(sendToNumber, messageToSend)) { Serial.println(F("Failed to send SMS"));
} else {
Serial.println(F("Sent location data!"));
}

 

Finally, we wait for each message. I used 10 seconds for testing purposes, but you can enter your own delay in milliseconds: Serial.println(F("Waiting until next message...")); delay(10000);

 

It's now time to test the project. You can grab the whole code from the GitHub repository of the blog at https://github.com/marcoschwartz/arduino-secret-agents. Then, make sure you change the phone number and your GPRS settings inside the code and upload it to the board. If you can see the last line, it means that an SMS actually has been sent. This was followed by a series of messages with the current location of the project:

 

If you can see this message on your phone, congratulations, you have built your first GPS tracker using Arduino!

It's now time to build the last project of this blog: a real GPS location tracker. For this project, we'll get the location just as before, using the GPS if available, and the GPRS location otherwise.

 

However, here we are going to use the GPRS capabilities of the shield to send the latitude and longitude data to dweet.io, which is a service we have used before. Then, we'll plot this data in Google Maps, allowing you to follow your device in real time from anywhere in the world. As the sketch is very similar to the ones in the previous sections, I'll only detail the most important parts of the sketch here.

You need to define a name for the thing that will contain the GPS location data: String dweetThing = "mysecretgpstracker";

 

Then, after getting the current location, we prepare the data to be sent to dweet.io:

uint16_t statuscode;
int16_t length;
char url[80];
String request = "www.dweet.io/dweet/for/" + dweetThing + "?latitude="+ latitude + "&longitude=" + longitude; request.toCharArray(url, request.length());
After this, we actually send the data to dweet.io:
if (!fona.HTTP_GET_start(url, &statuscode, (uint16_t *)&length)) { Serial.println("Failed!");
}
while (length > 0) {
while (fona.available()) {
char c = fona.read();
// Serial.write is too slow, we'll write directly to Serial
register!
#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) loop_until_bit_is_set(UCSR0A, UDRE0); /* Wait until data
register empty. */ UDR0 = c;
#else
Serial.write(c);
#endif length--;
}
}
fona.HTTP_GET_end();

 

Now, before testing the project, we are going to prepare our dashboard that will host the Google Maps widget. Just as in the previous blog, we are going to use freeboard.io for this purpose. If you don't have an account yet, go to http://freeboard.io/.

 

Create a new dashboard, and also a new data source. Insert the name of your thing inside the THING NAME field:

Then, create a new pane with a Google Maps widget. Link this widget to the latitude and longitude of your location data source. It's now time to test the project. Make sure you grab all the code, for example from the GitHub repository of the blog. Also, don't forget to modify the thing name, as well as your GPRS settings. Then, upload the sketch to the board and open the Serial monitor. This is what you should see:

 

The most important line is the last one, which confirms that data has been sent to dweet.io and has been stored there. Now, simply go back to the dashboard you just created, and you can now see that the location on the map has been updated:

 

Note that this map is also updated in real time as new measurements arrive from the board. You can also modify the delay between two updates of the position of the tracker by changing the delay() function in the sketch. Congratulations, you just built your own GPS tracking device!

 

Cloud-Controlled ESP8266 Robot

robot

In this blog so far, we mainly used the ESP8266 Wi-Fi chip to build the Internet of Things projects that were related to the home automation or security fields, such as the remote-controlled door lock, or the complete home automation system we built in Blog 11, Cloud-Based Home Automation System.

 

However, the ESP8266 is a very versatile chip and can be used for several fields other than the two I cited above. For example, it can also be used as the "brain" of a mobile robot, and this is exactly what we are going to do on this blog.

 

We are going to build a small mobile robot that will be completely controlled by the ESP8266 Wi-Fi chip. We are going to connect the motors of the robot to the ESP8266 Wi-Fi chip, and then the chip will communicate wirelessly with a cloud platform, so the robot can be controlled from anywhere. Finally, we are going to control the robot from a cloud dashboard. Let's start!

 

Hardware and software requirements

The first thing we need for this project is the ESP8266 Wi-Fi chip. As for most of this blog, I will be using the Adafruit Huzzah ESP8266 board here.

 

Then, the other important component of this project will be the robot platform. There are many options on the market, but there are actually not so many that are made for the ESP8266, so we will need to choose a very generic platform that we can just mount the components of our choosing on.

 

We basically need a certain amount of features to have a robot platform for this project:

  • The platform needs to have at least two wheels
  • The platform needs to have two motors
  • The platforms need to be big enough to host the ESP8266, a breadboard, and batteries

Robots_parts

There are actually a large number of robot platforms that would work with those specifications. The first category is, of course, the simple two-wheeled robot kits, such as this kit from EmGreat:

 

These platforms just have two wheels with a motor on each, and then a freewheel on the front to make the robot stable. Then, you can just mount your hardware on top of it. Then, you have four-wheeled robots that are basically a little car on which you can mount your own hardware. This is the four-wheeled kit of the same brand as before:

 

If you are going for such a platform, make sure there are only two motors, as in this blog I will describe a project using two motors only. Of course, you could also easily adapt the code in this blog to a four-motor robot platform.

 

I made a similar choice for this blog, as I still had a rover-type robot I wanted to use:

This is basically the same as the robot I introduced earlier, but this time with rubber bands around the wheels, like a tank. This makes sure that the robot won't be too affected by what's behind it, such as some asperities on the ground. It also has only two motors.

 

After that, you will need additional components to control the robot. The first thing is the L293D chip, which is an integrated circuit specialized in motor control. Indeed, it would be impossible to directly control the motors from the ESP8266. You will also need a battery that is adapted to the motors of your robot platform. The motors of the rover chassis I am using were rated for 7V, so I used this 7.4V battery. You will also need the usual breadboard and jumper wires.

 

This is a list of all the components that will be used in this blog:

  • Adafruit ES8266 module (https://www.adafruit.com/products/2471)
  • FTDI USB module (https://www.adafruit.com/products/284)
  • Rover robot chassis with two motors (http://www.dfrobot.com/index. php?route=product/product&product_id=390)
  • L293D motor driver (https://www.adafruit.com/products/807)
  • 7.4V battery URL with DC jack (http://www.robotshop.com/en/dfrobot-7-4v-lipo-2200mah-battery.html)
  • Breadboard (https://www.sparkfun.com/products/12002)
  • Jumper wires (https://www.sparkfun.com/products/9194)
  • On the software side, you will need the Arduino IDE and the aREST library that we already used earlier in the blog.

 

Hardware configuration

We are now going to assemble the project. As it is quite complicated, I made a detailed diagram for you to understand the different connections:

 

The first step is to assemble all the components on the breadboard. Only then place the breadboard on the robot chassis, and then connect it to the motors. In the end, connect the battery to the project. This is the final result, only showing the breadboard, without all the connections to the motors:

 

This is the completely assembled robot platform:

Note that the platform comes with a cover to hide the components inside, but here I decided to leave it open so you can see the inside of the project. But don't do this with your own robot, or make sure to screw/glue all the components to the chassis!

 

Testing the motors

Before we actually control the robot from the cloud, we are going to perform a simple test to see whether the motors are working correctly. This will also allow you to see how to write code to control the motors.

// Define motor pins int motorOnePlus = 12; int motorOneMinus = 13; int motorOneEnable = 14;

int motorTwoPlus = 5;
int motorTwoMinus = 16;
int motorTwoEnable = 4;
void setup()
{
Serial.begin(1152000);
// Set pins pinMode(motorOnePlus, OUTPUT); pinMode(motorOneMinus, OUTPUT); pinMode(motorOneEnable, OUTPUT);
pinMode(motorTwoPlus, OUTPUT);
pinMode(motorTwoMinus, OUTPUT);
pinMode(motorTwoEnable, OUTPUT);
}
void loop()
{
// Accelerate forward setMotorOne(true, 500); setMotorTwo(true, 500);
// Delay
delay(5000);
// Stop setMotorOne(true, 0); setMotorTwo(true, 0);
// Delay delay(5000);
}
// Function to control the motor
void setMotorOne(boolean forward, int motor_speed){ digitalWrite(motorOnePlus, forward); digitalWrite(motorOneMinus, !forward); analogWrite(motorOneEnable, motor_speed);
}
// Function to control the motor
void setMotorTwo(boolean forward, int motor_speed){ digitalWrite(motorTwoPlus, forward); digitalWrite(motorTwoMinus, !forward); analogWrite(motorTwoEnable, motor_speed);
}
We are now going to see the important parts of this code. First, we define all the pins we used to connect the ESP8266 to the L293D motor driver:
int motorOnePlus = 12;
int motorOneMinus = 13;
int motorOneEnable = 14;
int motorTwoPlus = 5;
int motorTwoMinus = 16;
int motorTwoEnable = 4;
In the setup() function of the sketch, we set all those pins as outputs:
pinMode(motorOnePlus, OUTPUT);
pinMode(motorOneMinus, OUTPUT);
pinMode(motorOneEnable, OUTPUT);
pinMode(motorTwoPlus, OUTPUT);
pinMode(motorTwoMinus, OUTPUT);
pinMode(motorTwoEnable, OUTPUT);
Inside the loop() function, we first set both motors to go forward at half of their maximum speed:
setMotorOne(true, 500);
setMotorTwo(true, 500);
Later, we also stop the motors, before starting them again. Let's now have a look at the function used to set the first motor:
void setMotorOne(boolean forward, int motor_speed){ digitalWrite(motorOnePlus, forward);
digitalWrite(motorOneMinus, !forward); analogWrite(motorOneEnable, motor_speed);
}

 

As you can see, there are two parts to this function: one part for the direction, and one part for the speed. The direction is set by applying two opposite logical signals on the + and – pins of the L293D, for this particular motor. For the speed, we just apply a PWM signal on the corresponding pin with an analogWrite() function. Note that the speed can be set from 0 to 1023 using this function.

 

The function to control the other motor is really similar:

void setMotorTwo(boolean forward, int motor_speed){ digitalWrite(motorTwoPlus, forward); digitalWrite(motorTwoMinus, !forward); analogWrite(motorTwoEnable, motor_speed);

}

It's now time to test the sketch and to make the motors move! Before doing anything, make sure that the robot is standing on a little platform, so the wheels don't touch the ground. Otherwise, you may get an unpleasant surprise when the wheels start to spin! Also check that the battery is connected to the robot.

 

Then, upload the code to the robot. You should see that the wheels will quickly start turning in the same direction, before stopping and then starting the loop again.

 

If the wheels are not turning in the same direction, make sure that all the connections are correct. This is important, as we want the robot to move forward when we apply the same command to both motors.

 

Connecting the robot to the cloud

cloud

Now that we are sure that the wheels are working correctly, we are going to connect the robot to the aREST cloud platform, so it can be controlled from anywhere in the world. As the sketch is quite big and takes a lot from the motor test sketch we saw earlier, I will only go through the most important points here. You can, of course, find the complete sketch inside the GitHub repository for the blog.

 

It starts by importing the correct libraries:

#include <ESP8266WiFi.h>

#include <PubSubClient.h>
#include <aREST.h>
Then, we create the client to communicate with the aREST cloud server:
WiFiClient espClient;
PubSubClient client(espClient);
We also create an instance of the aREST client:
aREST rest = aREST(client);
Then, as we saw in earlier blogs, you need to give a unique ID to the device:
char* device_id = "40ep12";

 

You also need to set your Wi-Fi name and password here:

const char* ssid = "wifi-name";

const char* password = "wifi-password";

 

Next, we need to define a set of functions to actually control the robot remotely. Here, I will use one function per fundamental command to the robot: stop, forward, backward, right, and left.

 

We first need to declare all those functions:

int stop(String command);

int forward(String command);
int left(String command);
int right(String command);
int backward(String command);
In the setup() function, we assign the ID to the board, and also give it a name:
rest.set_id(device_id);
rest.set_name("robot");
We need to expose the functions to the aREST library, so they can be called remotely:
rest.function("forward", forward);
rest.function("stop", stop);
rest.function("right", right);
rest.function("left", left);
rest.function("backward", backward);
After that, we connect the board to the Wi-Fi network:
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
In the loop() function, we connect to the cloud with this:
rest.handle(client);
Now, let's see one of those functions that we use to make the robot move around.
This is the details of the function to make the robot move forward:
int forward(String command) {
setMotorOne(true, 1000);
setMotorTwo(true, 1000);
}

 

It's now time to test the robot! Make sure that you grabbed the whole code from the GitHub repository of the blog, assigned a unique ID to the project, and also changed the Wi-Fi credentials inside the code. Also make sure that the battery is connected to the robot.

 

Then, upload the code to the board. This time, after it's uploaded, nothing should happen. Now, to make the robot autonomous, disconnect it from the FTDI cable, and connect the Vbat pin to the battery power supply (the Adafruit ESP8266 chip can handle 7V without problems). If you have another ESP8266, you might need to power it from an external power source now.

 

Now, go to your favorite web browser and type:https://cloud.arest.io/40ep12/id

Of course, you need to replace the ID with the one you set in the code. You should get the following answer:

  • {
  • "id": "40ep12",
  • "name": "robot",
  • "connected": true
  • }

 

Then, make sure there is space around the robot and type: https://cloud.arest.io/40ep12/forward

You should get the confirmation inside your browser that the function was executed, and you should also see the robot move forward! To stop it, simply type: https://cloud.arest.io/40ep12/stop

This should immediately stop the robot. You can now also play with the other functions, to make the robot turn right or left, or go backward. Congratulations, you can now control your robot from anywhere on the planet!

 

Controlling the robot from a dashboard

What we already achieved is great, but it's not perfect yet. It's not so convenient to control the robot from a web browser, especially to perform quick actions such as making the robot turn at a specific angle.

 

To easily control the robot, we are going to again use the dashboard functions of aREST, so we can control the robot using buttons. If it's not been done yet, create an account at: http://dashboard.arest.io/

 

From there, create a new dashboard for your robot:

Now, inside the newly created dashboard, we are going to create a button for the first function: going forward. To do so, create a new element with function as the type, and forward as the function to call: Then, do the same for the stop function: After that, do the same operation with all the remaining functions. You can now immediately try the buttons; whenever you press a button, it should immediately perform the correct action on the ESP8266.

 

Building Your Own Cloud Platform to Control ESP8266 Devices

cloud_device

In all the previous blogs of this blog, we have always used external services to connect our ESP8266 projects to the cloud. For example, we used services such as IFTTT, Adafruit IO, and aREST to control and monitor our projects from the cloud.

 

However, those services are all managed by other people or companies. This can pose security issues for some projects, and also those services can be shut down at any time, or at least not be managed properly. If you really want to have complete control over your cloud-connected projects, the only way to go is to deploy your own server on the cloud.

 

We are going to first create a cloud server so we can deploy web applications that can be accessed from anywhere. We are then going to discover how to deploy your own aREST cloud server on the server you just created. Finally, as a test, we'll connect a simple ESP8266 project to your own server. Let's start!

 

Hardware and software requirements

hardware

Let's first see what we need for this project. As we just want to test the connection between an ESP8266 board and your own cloud server, we'll keep things simple here. For the ESP8266, I again chose to use an Adafruit ESP8266 module, along with an FTDI USB module.bWe'll simply connect two kinds of the component to this board: an LED and a DHT11 sensor. Of course, you'll need the usual breadboard and jumper wires.

 

This is a list of all the components that will be used in this blog:

  • Adafruit ES8266 module (https://www.adafruit.com/products/2471)
  • FTDI USB module (https://www.adafruit.com/products/284)
  • LED (https://www.sparkfun.com/products/9590)
  • 330 Ohm resistor (https://www.sparkfun.com/products/8377)
  • DHT11 sensor (https://www.adafruit.com/products/11)
  • Breadboard (https://www.sparkfun.com/products/12002)
  • Jumper wires (https://www.sparkfun.com/products/9194)

 

On the software side, you will need the Arduino IDE and the aREST library, which we have already used earlier in the blog. You will also need the PubSub library and the Adafruit DHT library.

 

Hardware configuration

We are now going to assemble the project. The hardware is really simple here, as we only want to test the connection between the project and our own cloud server we'll deploy later in this blog.

 

Simply place the ESP8266 board on your breadboard, and then connect the FTDI breakout board to it. For the LED, simply connect it in series with the resistor, with the longest pin of the LED connected to the resistor. Then, connect the remaining pin of the resistor to pin 5 of the ESP8266 board, and the remaining pin of the LED to the GND pin.

 

Once this is done, simply put the DHT11 sensor on the breadboard. Then, connect the left pin to VCC, the right pin to, and the pin next to VCC to pin 4 on your ESP8266 chip.

 

Creating a cloud server

cloud-server

We are now going to take the first step towards having the board connected to your own cloud server: creating the server itself.

 

You could run the software we'll see later on your own computer, but then you won't be able to access your ESP8266 projects remotely. This is why you need to have your own server deployed with a cloud service provider. If you already have such a server capable of running the Meteor application (the framework we are going to use), you can just skip this section.

 

There are many server providers out there, but the one I recommend is Digital Ocean. They are fast, cheap, and have a very easy-to-use interface. You can find them at https://www.digitalocean.com/

 

Once you are on their website, create a new accountThen, create a new Droplet, which is the name for a server on Digital Ocean. You will be invited to choose where you want to deploy your Droplet (choose whatever is closest to the devices you want to use):

 

Next, you need to select your monthly plan, which will also determine the computing power of your server. As we only have a lightweight software here, the cheapest plan is more than enough for our server:

Next, you need to choose an operating system for your server. Simply choose the latest stable version of the Ubuntu Linux operating system:

 

Finally, complete the creation of your server by giving it a name:

You should now see that your server has been created, and it should appear in the list: From there, what you will need is the IP address of your server, which we are going to use later on. You will also need to set root access on your server. As it's a complex process, I recommend following all the instructions here: https://www.digitalocean.com/community/tutorials/how-to-configure-ssh-key-based-authentication-on-a-linux-server

 

The aREST cloud server code

It's now time to actually deploy an application on the server that you just created. As the software for your cloud server, we are going to use the aREST cloud server that we have already used before. It is completely free and open source, and you can get the latest version of the software from here: https://github.com/marcoschwartz/meteor-aREST-mqtt

 

For now, simply copy all the files from this repository and put them inside any folder on your computer.

This application actually uses the Meteor framework, which is a complete framework based on JavaScript and Node.js and can be used to create powerful web applications. If it's not been done yet, install Meteor on your computer by going to: https://www.meteor.com/install

 

Now, let's have a quick overview of the code of the aREST cloud server. The code is quite complicated, but I just wanted to highlight some parts here so you understand how it works. Whenever a device connects to the server, the software first checks whether the server already knows the device. If that's the case, we set the device to connected, so it can be accessed from the cloud. If the device is unknown, it is added to the database on the server.

 

This is the piece of code that handles those functions:

 

Server.on('clientConnected', Meteor.bindEnvironment(function(client) {
console.log('client connected', client.id);
// Already exist?
if (Devices.find({clientId: client.id}).fetch().length == 0) {
// Insert in DB
console.log('New device detected');
device = {
clientId: client.id,
connected: true
}
Devices.insert(device);
}
else {
console.log('Existing device detected');
// Update device status
Devices.update({clientId: client.id}, {$set: {"connected":
true}}
);
}
}) );
Whenever the user wants to access a device, the user types a command inside a web browser. The cloud server will then first match this command with the commands that are available, for example:
Router.route('/:device', {
The server then checks whether the device exists:
var currentDevice = Devices.findOne({clientId: device});
If the device exists and is connected at the moment, the server prepares a message to be sent to the device, for example:
var message = {
topic: currentDevice.clientId + '_in',
payload: '',
qos: 0,
retain: false
};
Then, once the answer comes back from the device, we send it back to the user in
JSON format:
answer = sendMessage(message); this.response.setHeader('Content-Type', 'application/json'); this.response.end(answer);

 

Deploying the server

We are now going to deploy this software on your cloud server. First, you need to install Node.js if that's not been done yet. To do it, simply follow the instructions at: https://nodejs.org/en/

 

We can then install some software called Meteor Up, which will really simplify the process of deploying the application on our web server.

Go to a terminal and type:

sudo npm install -g mup

Next, navigate to the folder in which you put all the files of the application, and initialize Meteor Up with:
mup init
This will create a file called mup.json inside the folder you are currently in. This is how this file will look:
{
// Server authentication info "servers": [
{
"host": "0.0.0.0",
"username": "root",
//"password": "password"
// or pem file (ssh based authentication) "pem": "~/.ssh/id_rsa"
} ],
// Install MongoDB in the server, does not destroy local MongoDB on future setup
"setupMongo": true,
// WARNING: Node.js is required! Only skip if you already have Node. js installed on server.
"setupNode": true,
// WARNING: If nodeVersion omitted will setup 0.10.36 by default. Do not use v, only version number.
"nodeVersion": "0.10.41",
// Install PhantomJS in the server
"setupPhantom": true,
// Show a progress bar during the upload of the bundle to the server.
// Might cause an error in some rare cases if set to true, for instance in Shippable CI
"enableUploadProgressBar": true,
// Application name (No spaces)
"appName": "arest",
// Location of app (local directory) "app": ".",
// Configure environment
"env": {
"ROOT_URL": "http://localhost",
"PORT": 3000
},
// Meteor Up checks if the app comes online just after the deployment
// before mup checks that, it will wait for no. of seconds configured below
"deployCheckWaitTime": 120
}
There are two things you will need to change in this file. The first one is to set the IP address of your Digital Ocean server:
"servers":
{ "host": "0.0.0.0",
"username": "root",
//"password": "password"
// or pem file (ssh based authentication) "pem": "~/.ssh/id_rsa"
}
You can also change the port on which you want the application to run on your server. By default, it will be 3000, but you can change it in case you have several applications running on the same server:
"env": {
"ROOT_URL": "http://localhost",
"PORT": 3000 }
Once that's done, save the file and type the following command:
mup setup

 

This will initialize your server so the Meteor application can be deployed: Once you see the last SUCCESS message, you can continue and deploy the application with: mup deploy

 

This will launch the deployment process:

Once you see the final SUCCESS message in green, congratulations, you now have your own cloud server deployed, and ready to be used to control your IoT devices!