Users Online

· Guests Online: 33

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

#4_01 Sensing Your IOT Environment

Sensing Your IOT Environment

 

 

Chapter Goal: Build Your First IOT Device

Topics Covered in This Chapter:

  • Building an inexpensive IOT Sensor device based on the ESP8266 and Arduino IDE

  • Setting up a simple Self-Organizing IOT Sensor Net

  • Reading I2C sensor (light and color) on the Arduino devices

  • Reading data from remote IOT sensors on the Raspberry Pi

  • Using the Raspberry Pi for Monitoring and Debugging

  • Displaying your Data on the screen and on an iPad

In this chapter, we build our first IOT device. This simple design, a light-sensor swarm, is easy to build and illustrates a number of IOT principles including the following:

  • Distributed Control

  • Self-Organization

  • Passing Information to the Internet

  • Swarm Behavior

The LightSwarm architecture is a simple and flexible scheme for understanding the idea of an IOT project using many simple small computers and sensors with shared responsibility for control and reporting. Note that in this swarm, communication with the Internet is handled by a Raspberry Pi. The swarm devices talk to each other, but not with the Internet. The Raspberry Pi is located on the same WiFi access point as the swarm, but could be located far away with some clever forwarding of packets through your WiFi router. In this case, since we have no computer security at all in this design (see Chapter 7 for information on making your IOT swarm and device more secure) and so we are sticking with the local network. The exception to this is the RasPiConnect LightSwarm control panel that can be located anywhere on the Internet and is secured by password control and could easily be sent via https, encrypting the individual XML packets.

IOT Sensor Nets

One of the major uses of the IOT will be building nets and groups of sensors. Inexpensive sensing is just as big of a driver for the IOT as the development of inexpensive computers. The ability for a computer to sense its environment is the key to gathering information for analysis, action, or transmittal to the Internet. Sensor nets have been around in academia for many years, but now the dropping prices and availability of development tools are quickly moving sensor nets out to the mainstream. Whole industrial and academic conferences are now held on sensor nets [ www.sensornets.org ]. The market is exploding for these devices, and opportunities are huge for the creative person or group that can figure out how to make the sensor net that will truly drive consumer sales.

IOT Characterization of This Project

As I discussed in Chapter 1, the first thing to do to understand an IOT project is to look at our six different aspects of IOT. LightSwarm is a pretty simple project and can be broken down into the six components listed in Table 2-1.

Table 2-1.LightSwarm Characterization (CPLPFC )

Aspect

Rating

Comments

Communications

9

WiFi connection to Internet - can do ad-hoc mesh-type communication

Processor Power

7

80MHz XTensa Harvard Architecture CPU, ∼80KB Data RAM / ∼35KB of Instruction RAM / 200K ROM

Local Storage

6

4MB Flash (or 3MB file system!)

Power Consumption

7

200mA transmitting, ∼60mA receiving, no WiFi ∼15mA, Standby ∼1mA

Functionality

7

Partial Arduino Support (limited GPIO/Analog Inputs)

Cost

9

< $10 and getting cheaper

Ratings are from 1–10, 1 being the least suitable for IOT and 10 being the most suitable for IOT applications .

This gives us a CPLPFC rating of 7.2. This is calculated by averaging all six values together with equal weighting. This way is great for learning and experimenting, and could be deployed for some applications.

The ESP8266 is an impressive device having a built-in WiFi connection, a powerful CPU, and quite a bit of RAM and access to the Arduino libraries. It is inexpensive and will get cheaper as time goes on. It is a powerful device for prototyping IOT applications requiring medium levels of functionality.

How Does This Device Hook Up to the IOT?

The ESP8266 provides a WiFi transmitter/receiver, a TCP/IP stack, and firmware to support direction connections to a local WiFi access point that then can connect to the Internet. In this project, the ESP8266 will only be talking to devices on the local wireless network. -This is an amazing amount of functionality for less than $10 retail. These chips can be found for as little as $1 on the open market, if you want to roll your own printed circuit board.

What Is an ESP8266?

The ESP8266 is made by a company in China called Espressif [espressif.com]. They are a fabless semiconductor company that just came out of nowhere with the first generation of this chip and shook up the whole industry. Now all the major players are working on inexpensive versions of an IOT chip with WiFi connectivity.

The ESP8266 chip was originally designed for connected light bulbs but soon got used in a variety of applications, and ESP8266 modules are currently now the most popular solutions to add WiFi to IOT projects. While the ESP8266 has huge functionality and a good price, the amount of current consumed by the chip makes battery-powered solutions problematic .

The ESP8266 is enabling a whole new set of applications and communities with their innovative and inexpensive design (Figure 2-1).

Figure 2-1.The ESP8266 die. (Courtesy of Hackaday.io)

We will be using a version of the ESP8266 on a breakout board designed by Adafruit (Figure 2-2). The board provides some connections, a built-in antenna, and some power regulation, all for less than $10.

Figure 2-2.The Adafruit Huzzah ESP8266 . (Courtesy of adafruit.com )

The LightSwarm Design

There are two major design aspects of the LightSwarm project . First of all, each element of the swarm is based on an ESP8266 with a light sensor attached. The software is what makes this small IOT device into a swarm. In the following block diagram you can see the major two devices. I am using the Adafruit Huzzah breakout board for the ESP8266 [ www.adafruit.com/product/2471 ]. Why use a breakout board? With a breakout board you can quickly prototype devices and then move to a less-expensive design in the future. The other electronic component (Figure 2-3) is a TCS34725 RGB light-sensor breakout board, also from Adafruit [ www.adafruit.com/products/1334 ].

Figure 2-3.TCS34725 Breakout Board . (Courtesy of adafruit.com )

The addition of a sensor to a computer is what makes this project an IOT device. I am sensing the environment and then doing something with the information (determining which of the Swarm has the brightest light). Figure 2-4 shows the block diagram of a single Swarm element.

Figure 2-4.LightSwarm Element Block Diagram

Each of the LightSwarm devices in the swarm is identical. There are no software differences and no hardware differences. As you will see when we discuss the software, they vote with each other and compare notes and then elect the device that has the brightest light as the “Master,” and then the “Master” turns the red LED on the device to show us who has been elected “Master.” The swarm is designed so devices can drop out of the swarm, be added to the swarm dynamically, and the swarm adjusts to the new configuration. The swarm behavior (who is the master, how long it takes information about changing lights to propagate through the swarm, etc.) is rather complex. More complex than expected from the simple swarm device code. There is a lesson here: simple machines in groups can lead to large complex systems with higher-level behaviors based on the simple machines and the way they interact.

The behavior of the LightSwarm surprised me a number of times and it was sometimes very difficult to figure out what was happening, even with the Raspberry Pi logger. Figure 2-5 shows the complete LightSwarm including the Raspberry Pi.

Figure 2-5.The Light Swarm

The Raspberry Pi in this diagram is not controlling the swarm. The Raspberry Pi gathers data from the swarm (the current “Master” device sends information to the Raspberry Pi), and then the Raspberry Pi can store the data and communicate it through the Internet, in this case to an iPad-based app called RasPiConnect [ www.milocreek.com ] , which displays the current and historical state of the LightSwarm.

The LightSwarm project has an amazing amount of functionality and quirky self-organizing behavior for such a simple design.

Building Your First IOT Swarm

Table 2-2 lists the parts needed to build an IOT Swarm.

Table 2-2.Swam Parts List

Part Number

Count

Description

Approximate Cost per Board

Source

ESP8266 Huzzah Board

5

CPU / WiFi board

$10

www.adafruit.com/products/2471 

TCS34725 Breakout Board

5

I2C Light Sensor

$8

www.adafruit.com/products/1334 

FTDI Cable

1

Cable for programming the ESP8266 from PC/Mac

$18

www.adafruit.com/products/70 

Installing Arduino Support on the PC or Mac

The key to making this project work is the software. While there are many ways of programming the ESP8266 (MicroPython) [micropython.org], NodeMCU Lua interpreter [nodemcu.com/index_en.html], and the Arduino IDE (Integrated Development Environment) [www.arduino.cc/en/Main/Software ]), I chose the Arduino IDE for its flexibility and the large number of sensor and device libraries available.

To install the Arduino IDE you need to do the following:

 

a.

Download the Arduino IDE package for your computer and install the software [ www.arduino.cc/en/Guide/HomePage ] .

 

b.

Download the ESP libraries so you can use the Arduino IDE with the ESP breakout board. Adafruit has an excellent tutorial for installing the ESP8266 support for the Arduino IDE [learn.adafruit.com/adafruit-huzzah-esp8266-breakout/using-arduino-ide ].

 

Your First Sketch for the ESP8266

A great way of testing your setup is to run a small sketch that will blink the red LED on the ESP8266 breakout board. The red LED is hooked up to GPIO 0 (General Purpose Input Output pin 0) on the Adafruit board.

Open a new sketch using the Arduino IDE and place the following code into the code window, replacing the stubs provided when opening a new sketch. The code given here will make the red LED blink.

void setup() {

pinMode(0, OUTPUT);

}

void loop() {

digitalWrite(0, HIGH);

delay(500);

digitalWrite(0, LOW);

delay(500);

}

If your LED is happily blinking away now, you have correctly followed all the tutorials and have the ESP8266 and the Arduino IDE running on your computer.

Next I will describe the major hardware systems and then dive into the software.

The Hardware

The main pieces of hardware in the swarm device are the following:

  • ESP8266 - CPU/WiFi Interface

  • TCS34725 - Light sensor

  • 9V Battery - Power

  • FTDI Cable - Programming and power

The ESP8266 communicates with other swarm devices by using the WiFi interface . The ESP8266 uses the I2C interface to communicate with the light sensor. The WiFi is a standard that is very common (although we use protocols to communicate that are NOT common). See the description of UDP (User Datagram Protocol) later in this chapter. The I2C bus interface is much less familiar and needs some explanation.

Reviewing the I2C Bus

An I2C bus is often used to communicate with chips or sensors that are on the same board or located physically close to the CPU. It stands for standard Inter-IC device bus. The I2C was first developed by Phillips (now NXP Semiconductors). To get around licensing issues, often the bus will be called TWI (Two Wire Interface). SMBus, developed by Intel, is a subset of I2C that defines the protocols more strictly. Modern I2C systems take policies and rules from SMBus sometimes supporting both with minimal reconfiguration needed. The Raspberry Pi and the Arduino are both these kinds of devices. Even the ESP8266 used in this project can support both.

An I2C provides good support for slow, close peripheral devices that only need be addressed occasionally. For example, a temperature measuring device will generally only change very slowly and so is a good candidate for the use of I2C, where a camera will generate lots of data quickly and potentially changes often.

An I2C bus uses only two bidirectional open-drain lines (open-drain means the device can pull a level down to ground, but cannot pull the line up to Vdd. Hence the name open-drain). Thus a requirement of an I2C bus is that both lines are pulled up to Vdd. This is an important area and not properly pulling up the lines is the first and most common mistake you make when you first use an I2C bus. More on pullup resistors later in the next section. The two lines are SDA (Serial Data Line) and the SCL (Serial Clock Line). There are two types of devices you can connect to an I2C bus. They are Master devices and Slave devices. Typically, you have one Master device (the Raspberry Pi in our case) and multiple Slave devices, each with their individual 7-bit address (like 0x68 in the case of the DS1307). There are ways to have 10-bit addresses and multiple Master devices, but that is beyond the scope of this column. Figure 2-6 shows an I2C bus with devices and the master connected.

Figure 2-6.An I2C bus with one Master (the ESP8266 in this case) and three Slave devices. Rps are the Pullup Resistors

SwitchDoc Note

Vcc and Vdd mean the same. Gnd and Vss generally also both mean ground. There are historical differences, but today Vcc usually is one power supply, and if there is a second, they will call it Vdd.

When used on the Raspberry Pi, the Raspberry Pi acts as the Master and all other devices are connected as Slaves.

SwitchDoc Note

If you connect an Arduino to a Raspberry Pi, you need to be careful about voltage levels because the Raspberry Pi is a 3.3V device and the Arduino is a 5.0V device. The ESP8266 is a 3.3V device so you also need to be careful connecting an Arduino to an ESP8266. Before you do this, read this excellent tutorial [ blog.retep.org/2014/02/15/connecting-an-arduino-to-a-raspberry-pi-using-i2c/ ].

The I2C protocol uses three types of messages:

  • Single message where a master writes data to a slave;

  • Single message where a master reads data from a slave;

  • Combined messages, where a master issues at least two reads and/or writes to one or more slaves.

Lucky for us, most of the complexity of dealing with the I2C bus is hidden by drivers and libraries.

Pullups on the I2C Bus

One important thing to consider on your I2C bus is a pullup resistor. The Raspberry Pi has 1.8K ohm (1k8) resistors already attached to the SDA and SCL lines, so you really shouldn't need any additional pullup resistors. However, you do need to look at your I2C boards to find out if they have pullup resistors. If you have too many devices on the I2C bus with their own pullups, your bus will stop working. The rule of thumb from Phillips is not to let the total pullup resistors in parallel be less than 1K (1k0) ohms. You can get a pretty good idea of what the total pullup resistance is by turning the power off on all devices and using an ohm meter to measure the resistance on the SCL line from the SCL line to Vdd .

Sensor Being Used

We are using the TCS34725 , which has RGB and Clear light-sensing elements. Figure 2-7 shows the TCS34725 die with the optical sensor showing in the center of the figure. An IR blocking filter, integrated on-chip and localized to the color-sensing photodiodes, minimizes the IR spectral component of the incoming light and allows color measurements to be made accurately. The IR filter means you'll get much truer color than most sensors, since humans don't see IR. The sensor does see IR and thus the IR filter is provided. The sensor also has a 3,800,000:1 dynamic range with adjustable integration time and gain so it is suited for use behind darkened glass or directly in the light.

Figure 2-7.The TCS34725 Chip Die

This is an excellent inexpensive sensor ($8 retail from Adafruit on a breakout board) and forms the basis of our IOT sensor array. Of course, you could add many more sensors, but having one sensor that is easy to manipulate is perfect for our first IOT project. In Chapter 3, we add many more sensors to the Raspberry Pi computer for a complete IOT WeatherStation design.

3D Printed Case

One of the big changes in the way people build prototypes is the availability of inexpensive 3D printers. It used to be difficult to build prototype cases and stands for various electronic projects. Now it is easy to design a case in one of many types of 3D software and then print it out using your 3D printer. For the swarm, I wanted a partial case to hold the 9V battery, the ESP8266, and the light sensor. I used OpenSCAD [www.openscad.org ] to do the design. OpenSCAD is a free 3D CAD system that appeals to programmers. Rather than doing the entire design in a graphical environment, you write code (consisting of various objects, joined together or subtracted from each other) that you then compile in the environment to form a design in 3D space. OpenSCAD comes with an IDE (Integrated Development Environment) and you place the code showing in Listing 2-1 in the editor, compile the code, and then see the results in the attached IDE as shown in Figure 2-8 .

Figure 2-8.OpenSCAD display

As shown in Listing 2-1, the OpenSCAD programming code to build this stand is quite simple. It consists of cubes and cylinders of various sizes and types.

//

// IOT Light Swarm Mounting Base

//

// SwitchDoc Labs

// August 2015

//

union()

{

cube([80,60,3]);

translate([-1,-1,0])

cube([82,62,2]);

// Mount for Battery

translate([40,2,0])

cube([40,1.35,20]);

translate([40,26.10+3.3,0])

cube([40,1.5,20]);

// lips for battery

translate([79,2,0])

cube([1,28,4]);

// pylons for ESP8266

translate([70-1.0,35,0])

cylinder(h=10,r1=2.2, r2=1.35/2, $fn=100);

translate([70-1.0,56,0])

cylinder(h=10,r1=2.2, r2=1.35/2, $fn=100);

translate([70-34,35,0])

cylinder(h=10,r1=2.2, r2=1.35/2, $fn=100);

translate([70-34,56,0])

cylinder(h=10,r1=2.2, r2=1.35/2, $fn=100);

// pylons for light sensor

translate([10,35,0])

cylinder(h=10,r1=2.2, r2=1.35/2, $fn=100);

translate([10,49.5,0])

cylinder(h=10,r1=2.2, r2=1.35/2, $fn=100);

translate([22,37,0])

cylinder(h=6,r1=2.2, r2=2.2, $fn=100);

translate([22,47,0])

cylinder(h=6,r1=2.2, r2=2.2, $fn=100) ;

}

Listing 2-1.Mounting Base for the IOT LightSwarm

You can see the completed stand and the FTDI cable in the upcoming Figure 2-9. Once designed, I quickly built five of them for the LightSwarm. Figure 2-10 shows a completed Swarm element.

Figure 2-9.FTDI Cable Plugged into ESP8266

Figure 2-10.Completed LightSwarm Stand

The Full Wiring List

Table 2-3 provides the complete wiring list for a LightSwarm device. As you wire it, check off each wire for accuracy.

Table 2-3.LightSwarm Wiring List

From

To

Description

ESP8266 / GND

TCS34725 /GND

Ground for I2C Light Sensor

ESP8266 / 3V

TCS34725 / 3V3

3.3V Power for I2C Light Sensor

ESP8266 / #4

TCS34725 /SDA

SDA for I2C Light Sensor

ESP8266 / #5

TCS34725 /SCL

SCL for I2C Light Sensor

ESP8266 / GND

9VBat / “-” terminal (minus terminal)

Ground for battery

ESP8266 / VBat

9VBat / “+” terminal (plus 9V)

9V from battery

TCS34725 / LED

TCS34725 / INT

Connecting these two pins together allow for software control of bright LED on TCS34725 board

The FTDI cable is plugged into the end of the Adafruit Huzzah ESP8266. Make sure you align the black wire with the GND pin on the ESP8266 breakout board as in Figure 2-9. Figure 2-11 shows the fully complete LightSwarm device.

Figure 2-11.A Complete LightSwarm Device

The Software

There are two major modules written for the LightSwarm. The first is ESP8266 code for the LightSwarm device itself (written in the Arduino IDE - written in simplified C and C++ language), and the second is the Raspberry Pi data-gathering software (written in Python on the Raspberry Pi).

The major design specifications for the LightSwarm Device software are the following:

  • Device self discovery.

  • Device becomes master when it has the brightest light; all others become slaves.

  • Distributed voting method for determining master status.

  • Self-organizing swarm. No server.

  • Swarm must survive and recover from devices coming in and out of the network.

  • Master device sends data to Raspberry Pi for analysis and distribution to Internet.

The entire code for the LightSwarm devices is provided in Listings 2-2 though 2-11 (with the exception of the TCS74725 light-sensor driver, available here [ github.​com/​adafruit/​Adafruit_​TCS34725]). The code is also available on the APress web site [ www.apress.com ] and the SwitchDoc Labs github site [ github.com/switchdoclabs/lightswarm ].

/*

Cooperative IOT Self Organizing Example

SwitchDoc Labs, August 2015

*/

#include <ESP8266WiFi.h>

#include <WiFiUdp.h>

#include <Wire.h>

#include "Adafruit_TCS34725.h"

#undef DEBUG

char ssid[] = "yyyyy";         // your wireless network SSID (name)

char pass[] = "xxxxxxx";       // your wireless network password

#define VERSIONNUMBER 28

#define SWARMSIZE 5

// 30 seconds is too old - it must be dead

#define SWARMTOOOLD 30000

int mySwarmID = 0;

Listing 2-2.LightSwarm Code

Next in Listing 2-3, we define the necessary constants. Following are the definitions of all the Swarm Commands available:

  • LIGHT_UPDATE_PACKET - Packet containing current light from a LightSwarm device. Used to determine who is master and who is slave;

  • RESET_SWARM_PACKET - All LightSwarm devices are told to reset their software;

  • CHANGE_TEST_PACKET - Designed to change the master / slave criteria (not implemented);

  • RESET_ME_PACKET - Just reset a particular LightSwarm device ID;

  • DEFINE_SERVER_LOGGER_PACKET - This is the new IP address of the Raspberry Pi so the LightSwarm device can send data packets;

  • LOG_TO_SERVER_PACKET - Packets send from LightSwarm devices to Raspberry Pi;

  • MASTER_CHANGE_PACKET - Packet sent from LightSwarm device when it becomes a master (not implemented);

  • BLINK_BRIGHT_LED - Command to a LightSwarm device to blink the bright LED on the TCS34725.

After the constants in Listing 2-3, I set up the system variables for the devices. I am using UDP across the WiFi interface. What is UDP? UDP stands for User Datagram Protocol. UDP uses a simple connectionless model. Connectionless means that there is no handshake between the transmitting device and the receiving device to let the transmitter know that the receiver is actually there. Unlike TCP (Transmission Control Protocol ), you have no idea or guarantee of data packets being delivered to any particular device. You can think of it as kind of a TV broadcast to your local network. Everyone gets it, but they don’t have to read the packets. There are also subtle other effects – such as you don’t have any guarantee that packets will arrive in the order they are sent. So why are we using UDP instead of TCP? I am using the broadcast mode of UDP so when a LightSwarm devices send out a message to the WiFi subnet, everybody gets it and if they are listening on the port 2910 (set above), then they can react to the message. This is how LightSwarm devices get discovered. Everybody starts sending packages (with random delays introduced) and all of the LightSwarm devices figure out who is present and who has the brightest light. Nothing in the LightSwarm system assigns IP numbers or names. They all figure it out themselves.

// Packet Types

#define LIGHT_UPDATE_PACKET 0

#define RESET_SWARM_PACKET 1

#define CHANGE_TEST_PACKET 2

#define RESET_ME_PACKET 3

#define DEFINE_SERVER_LOGGER_PACKET 4

#define LOG_TO_SERVER_PACKET 5

#define MASTER_CHANGE_PACKET 6

#define BLINK_BRIGHT_LED 7

unsigned int localPort = 2910;      // local port to listen for UDP packets

// master variables

boolean masterState = true;   // True if master, False if not

int swarmClear[SWARMSIZE];

int swarmVersion[SWARMSIZE];

int swarmState[SWARMSIZE];

long swarmTimeStamp[SWARMSIZE];   // for aging

IPAddress serverAddress = IPAddress(0, 0, 0, 0); // default no IP Address

int swarmAddresses[SWARMSIZE];  // Swarm addresses

// variables for light sensor

int clearColor;

int redColor;

int blueColor;

int greenColor;

const int PACKET_SIZE = 14; // Light Update Packet

const int BUFFERSIZE = 1024;

byte packetBuffer[BUFFERSIZE]; //buffer to hold incoming and outgoing packets

// A UDP instance to let us send and receive packets over UDP

WiFiUDP udp;

/* Initialize with specific int time and gain values */

Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_700MS, TCS34725_GAIN_1X);

IPAddress localIP ;

Listing 2-3.LightSwarm Constants

The setup() routine shown in Listing 2-4 is only run once after reset of the ESP8266 and is used to set up all the devices and print logging information to the Serial port on the ESP8266, where, if you have the FTDI cable connected, you can see the logging information and debugging information on your PC or Mac.

void setup()

{

Serial.begin(115200);

Serial.println();

Serial.println();

Serial.println("");

Serial.println("--------------------------");

Serial.println("LightSwarm");

Serial.print("Version ");

Serial.println(VERSIONNUMBER);

Serial.println("--------------------------");

Serial.println(F(" 09/03/2015"));

Serial.print(F("Compiled at:"));

Serial.print (F(__TIME__));

Serial.print(F(" "));

Serial.println(F(__DATE__));

Serial.println();

pinMode(0, OUTPUT);

digitalWrite(0, LOW);

delay(500);

digitalWrite(0, HIGH) ;

Listing 2-4.The Setup() Function for LightSwarm

Here we use the floating value of the analog input on the ESP8266 to set the pseudo-random number generation seed. This will vary a bit from device to device, and so it’s not a bad way of initializing the pseudo-random number generator. If you put a fixed number as the argument, it will always generate the same set of pseudo-random numbers. This can be very useful in testing. Listing 2-5 shows the setup of the random seed and the detection of the TCS34725.

What is a pseudo-random number generator? It is an algorithm for generating a sequence of numbers whose properties approximate a truly random number sequence. It is not a truly random sequence of numbers, but it is close. Good enough for our usage.

randomSeed(analogRead(A0));

Serial.print("analogRead(A0)=");

Serial.println(analogRead(A0));

if (tcs.begin()) {

Serial.println("Found sensor");

} else {

Serial.println("No TCS34725 found ... check your connections");&l

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.71 seconds
10,255,101 unique visits