Category: Interfacing

UPM library for MCP9808 in XDK.

If you have read my blog at all you may be beginning to think I have a fetish for the MCP9808. Well, maybe a little, but for a good reason. If we look it’s data sheet we see the MCP9808 is a surprisingly complex device. Some of the features the data sheet lists:

  • Accuracy:
    •  ±0.25 (typical) from -40°C to +125°C
    • ±0.5°C (maximum) from -20°C to 100°C
    • ±0.5°C (maximum) from -20°C to 100°C
  • User-Selectable Measurement Resolution:
    • +0.5°C, +0.25°C, +0.125°C, +0.0625°C
  • User-Programmable Temperature Limits:
    • Temperature Window Limit
    • Critical Temperature Limit
  • User-Programmable Temperature Alert Output
  • Operating Voltage Range: 2.7 V to 5.5V
  • Operating Current:  200 µA (typical)
  • Shutdown Current: 0.1 µA (typical)
  • I2C bus compatible

These features make the MCP9808 ideal for a variety of temperature monitoring applications when being precise would be an advantage.

The devices I have been using I got from Adafruit.  They have a driver library for the Arduino  that is useful, but I want to use the device with Linux based IoT platforms such as the Intel Edison or the Beaglebone Black. Both of these platforms support the Intel UPM library , so it made sense to add a driver for the MCP9808 to that. I implemented the driver and added a pull request to have it incorporated into the Intel UPM library. The MCP9808 was accepted in to version 4.0 of the library and should be available after upgrading the version of MRAA on your board. If not — I have a blog post that lists various ways to update MRAA/UPM on your boards. (UPM is very easy to compile).

I provided a C++ program to the UPM repo that exercises all of the implemented functions.  You can copy the code from that example into an Intel iotdk-ide project (Eclipse) and run it from there. But I didn’t include a very good example for Nodejs. That brings us to the purpose of this post — I want to go over how to use the MCP9808 in Nodejs with XDK on the Edison (or compatible) MRAA board.

In order to give a proper demo I created a Nodejs/Socket.io app that illustrates all the implemented features of the MCP9808 UPM driver. It is setup as an XDK project so you can download it and open it in the XDK ide to run it on your Edison. Before you run it open the server.js file and change the line

var temp = new mcp.MCP9808(1) 

to whatever i2c bus you are using. I generally use a handmade boardthat extends the Edison Mini breakout board so I use bus 1. It will be bus 6 on the Arduino or DFRobot breakout, 0 on the Galileo.

When you download and start the app on the board browse to it’s url :8085 (like edison.local:8085) and you should see something that looks like this:

mcp9808_default_celcus

This is a single page app that uses socket.io to communicate with the Edison. The Edison serves the app via Express and the UI is basic HTML with the  Bootstrap framework. The four sections of the app (from right to left) are:

Temperature:

The radial gauge will reflect the current temperature at the device. The MCP9808 reports temperatures as Celsius (C), but the driver provides a conversion to Fahrenheit (F). The F values are calculated, so when we switch between C and F there are sometimes rounding differences. All the other temperature values in the UI will convert to C or F except for resolution. Resolution is always reported as C. I have the temperature limited from  freezing to boiling range, but the MCP9808’s range is little wider than that — see the specsheet.

Temp limits: 

These reflect the state of the three temperature limit registers detailed in section 5.1.2 of the spec sheet. These registers are used to allow the setting of temperature limits the MCP9808 can monitor so that we don’t have to constantly check for out of limit temps in code. The limit registers will cause flags in the ambient temp register (section 5.1.3)  to set if a threshold has passed. The driver exposes these bits as flags that can be read (see lines 158 to 167 of the server code) via a simple function call.  The thing to remember with these flags is that they reflect the state of the bits as of the most recent getTemp() call, so you need to read the temp before reading the flags.

I use the state of the Temp limit bits to set the color of the subheadings in the Temp Limit section. Since at power on the temps are set at 0 C, so the bits for TCrit and TUpper are set. Using the sliders to set a value greater than the current temperature will allow the TCrit and TUpper values to go green:

MCP9808_alert_off

The temp limit registers are also used in the Alert functionality.

Alert Control: 

Described in section 5.2.3 of the spec sheet,  the MCP9808 has the ability to control an alert pin when certain conditions arise.  On power up alerts are disabled. Default sets the device to comparator mode (section 5.2.3.1). The alert will assert (in this case pull low — you need to use a pull up on the pin) whenever one of the monitor temps are crossed. When the temp comes back within limits the alert will de-assert. In interrupt mode the just the TUpper and TLower are monitored. It the temp goes over a threshold the alert is asserted and will not de-assert until the temp goes back with range and the interrupt is cleared by code. These calls are illustrated in the server code.

Other:

The Other section contains controls for  resolution and hysteresis and display for device info, id and rev.

Resolution will always be reported in Celsius. Startup default is 0.0625 and equates to 4 temp measurements per second. Temperature resolution is detailed in section 5.2.4 of the spec sheet.

Hysteresis will be reported in either C of F depending on the driver settings. Hysteresis is detailed in section 5.2.2 and Figure 5-10. If the alerts are not clearing as you expect, check the hysteresis settings.

About:

The about menu item is a list of helpful links concerning the MCP9808.

What’s not Illustrated:

I didn’t use the sleep and wake function in this application. It is illustrated in the test file in the UPM library.

What’s not implemented: 

There were a couple of things that I did not implement. First: The temp monitoring registers can be locked by setting bits in the config register. It takes a power cycle to unlock them so I didn’t implement this. The alert can be set to assert active high. I didn’t add this functionality either. If either of these capabilities are needed you can just make an MRAA call directly to the device to do so. If you need help with either of these just ask me in the comments.

 

SSD1306 i2c UPM Library with the Intel Edison

UPDATE October 6, 2015.

The current version of UPM (4.0) includes this driver. However, UPM 4.0 requires MRAA 8.0. It is pretty simple to install both of these on your Edison. I have updated this guide to use the latest library.

End Update.

The SSD1306 is a very common display driver. There are tons of SSD1306 based devices to be found on Ebay and Amazon – some very inexpensive. Adafruit has several versions for sell that can easily be added to a Edison project. The main stumbling block to using these low cost displays has been the lack of an easy to use driver. Well that problem has been solved. I have recently contributed to the intel-iot-devkit UPM library an implementation of an i2c driver for this device. As of 1-Sept-15 I have been told it will be accepted and be available in the next release.

Why the UPM library? The UPM library provides a set of commonly used drivers that can be used in multiple languages. Each driver can be made available for C/C++, nodejs, java and python. The library I implemented is configured for all supported languages but only tested on C++ and nodejs. If someone uses the driver on java or python I’d like to hear about the results.

But what if we want to use the library in node before the next release? Well that is the topic of this blog post. We will go through the steps needed to compile the driver and install it on an Edison.

For C++ utilizing the driver is simpler than nodejs, python and java. All you need to do is add the source files to your iot dev kit project. The files needed are:

  1. hd44780_bits.h
  2. lcd.h
  3. lcd.cxx
  4. ssd.h
  5. ssd1306.h
  6. ssd1306.cxx

All are available in the repo  in the src/lcd directory. There is a C++ test file in the examples directory. (Make sure you are in the ssd1306 branch). If you need help configuring the iot dev kit check out this link.

If we want to use nodejs or one of the other languages we have a little more work to do.

As always, lets unsure we have the latest version of the Yocto on our system. To check your version login to your Edison and run the following:

configure_edison --version

You will need to be on version 159 to use this driver. If you need to update I find it is really easy to use the flash tool for Edison.

Once we are up to date we need to install git on our Edison. The instructions for installing git are here.

Install MRAA

Next we need to clone the MRAA repo from git hub:

git clone https://github.com/intel-iot-devkit/mraa.git

Change to the mraa directory and  checkout the 8.0 version.

git checkout tags/v0.8.0

Then we are ready to build. We will used the same out of tree build as described in the MRAA documentation.

mkdir build
cd build
cmake .. -DCMAKE_INSTALL_PREFIX:PATH=/usr 
make
sudo make install

Install UPM:

Change back to your home directory and run the following:

git clone https://github.com/intel-iot-devkit/upm.git

Then cd to the upm directory and checkout the 4.0 version with this command:

git checkout tags/v0.4.0

We will again be using the out of tree build as described in the documentation. Enter these commands to build and install:

mkdir build
cd build
cmake .. -DCMAKE_INSTALL_PREFIX:PATH=/usr
make 
sudo make install

There is a test script for nodejs in my repo.  Simply load this up in the XDK and run it on your device. This script will run through all the functions available in the SSD1306 driver.

Installing the SSD1306 driver is a little complicated but not that difficult to accomplish. I hope these instructions make it easy for you do get this working. If you have problems feel free to let me know in the comments and I’ll see if I can help.

This should be considered the initial implementation of this driver. I have plans to add further functionality to the driver after I get a few other things done. I’d like to have the driver handle multiple display geometries (currently it only accommodates 128*64) as well and add some graphics drawing abilities. The current implementation is very functional though, and fits my requirements pretty well.

Scanning i2c bus 6 on Intel Edison

In a previous post I discussed using the LMSensors project programs to scan I2C buses on the Intel Edison. As I mentioned in that post, I only had luck scanning bus 1 on the Edison (which is only available on the mini breakout board).

Generally, when using i2ctools to scan bus 6 on the Edison the scan will run very slowly and no devices will be found. I have been a little confused by this in the past because occasionally I would find that I am able to scan the bus normally with those tools. I even went so far as to create a tool using the MRAA libraries to implement similar functionality with a Nodejs script. But I have found something interesting.

What I found was that i2c bus 6 is not configured when the system is started. If I have a node application running that uses i2c (which most of mine do) I find I am able to scan the bus with i2c tools without a problem. Also my tool — m2ctool — can serve to configure the bus so that it can be accessed by i2ctools.

To see what I am talking about try this:

  1. Start up your Edison and login. Ensure no programs are running.
  2. Enter the command i2cdetect -r 6. Press enter when prompted.
  3. The bus should scan very slowly and show no devices.
  4. Download and install m2ctool. See instructions on the read me to install.
  5. Enter the command m2ctool scan 6.
  6. The bus should scan normally and show any devices that are installed.
  7. Enter the command i2cdetect -r  6.
  8. The bus should scan normally and show any devices that are installed.

So if you need to probe i2c bus 6 on Edison but don’t have a program running that utilizes i2c, just run ‘m2ctool scan 6’ and then use i2ctools as you normally would. I have only tried this on Edison, I don’t know if this is true on other MRAA based systems.

The m2ctool has other features, I had intended it to stand in for i2ctools when dealing with MRAA based i2c buses. But given that all I need to do is initialize the bus by running a program once I could have saved myself a bit of work. For more info on m2ctool see the read me in the git hub repo.

Using a Rotary Encoder on Intel Edison, XDK

Rotary Encoders are supported by the UPM library. There is already example code that can be leveraged when we want to use one.  The code was created for the Grove Rotary Encoder but in reality we can use it for any rotary encoder we choose to implement. The Grove encoder  would be a good choice if you are using Seed Studio’s Grove Starter Kit. But that could be a problem if we wanted to use the encoder on and Edison project for the mini breakout board or wanted to access the switch in the encoder (you can not access the switch in the Grove Encoder). In my case, I intend to use the encoder to drive a menu for controlling an Edison on a mini breakout board. To accomplish that I will need to have access to the encoders built in switch so I will roll my on implementation.

Since we are going to use the Grove library for the encoder we will implement ours like theirs. If we look at the schematic for the Grove encoder we can see that it is not really that complicated.

Grove Encoder Schematic
Grove Encoder Schematic. Don’t connect  4 and 5 of the switch this way.

We can also see why the switch is not available on the Grove device – not enough pins available on the connector. (Though it does look like activating the switch will pull SIGA down, which we could look for in code. But the UPM library for this doesn’t have any provision for it.) We will wire up our encoder this way but we will wire the switch a little differently.

For the switch we will wire it so the we get a high value when it is actuated. So pin 4 goes to ground via a 10k pull down resistor and to the signal in for our Edison. Pin 5 will go to VCC.

So we need:

1     Encoder — I used these: 360 Degree Rotary Encoder w Push Button

1     Ceramic Disk 100 nf Capacitor (that is 0.1 micro farads, marked 104 on the cap).

4     3.3k Resistors. I used 2% 1/4 watt.  

And for the switch:

1     10k Resistor – also 2% 1/4 watt.

Optionally:

1     Arduino stackable header.  I plugged the encoder into this so it would fit in a breadboard better.

Wiring it up on a bread board gives us something like this:

Wired to a bead board side view
Side view
IMG_20150814_175210
Overhead view
Connected to an Edison Arduino.
Connected to an Edison Arduino board.

I used my Edison Arduino Board to prototype this, so the connections are:

SIGA —> D2

SIGB —> D3

Switch ( encoder pin 4) —> D4

VCC –> 3.3 Volts.

Don’t forget the ground connection.

The code to test this is pretty simple since we are using the UPM Libraries. We will use the Grove Rotary Encoder library for, of course, the encoder. We will use the Grove Button Library for our button functionality.

We will use socket.io to monitor our encoder with a webpage. Our server code looks like this:

//Setup express 
var express = require('express');
var app = express();
app.use(express.static(__dirname));
var server = app.listen(8085);
var io = require('socket.io').listen(server);



var mraa = require('mraa'); //require mraa
console.log('MRAA Version: ' + mraa.getVersion()); //write the mraa version to the Intel XDK console

//var myOnboardLed = new mraa.Gpio(3, false, true); //LED hooked up to digital pin (or built in pin on Galileo Gen1)
var myOnboardLed = new mraa.Gpio(13); //LED hooked up to digital pin 13 (or built in pin on Intel Galileo Gen2 as well as Intel Edison)
myOnboardLed.dir(mraa.DIR_OUT); //set the gpio direction to output

//Require the encoder and button libraries. 
var rotaryEncoder = require("jsupm_rotaryencoder");
var groveSensor = require('jsupm_grove'); 
// Instantiate a Grove Rotary Encoder, using signal pins D2 and D3
var myRotaryEncoder = new rotaryEncoder.RotaryEncoder(2, 3);
//Set up a button on D4
var button = new groveSensor.GroveButton(4); 
 
//We will send data to our client with this object. 
var data = {}; 

//When we get a socket connection we will monitor the switch. 
io.sockets.on('connection', function (socket) {
 
 //Every 100 milli seconds we will send an update to the client. 
 //You won't want to monitor encoder this way for a real project
 //but it will demonstrate the encoder and switch. 
 setInterval(function () {
 //See what the switch value is.
 readButtonValue(); 
 //Sample the current position of the encoder. 
 //Since this is an incremental encoder we will
 //get increasing or decreasing int values from 
 //the encoder library. 
 data.position = myRotaryEncoder.position();
 //For the porposes of this demo, if we go lower than -40
 //or higher than 40 we will reset the encoder init to 0. 
 if(Math.abs(data.position) > 40 ) {
 myRotaryEncoder.initPosition(0);
 data.position = 0; 
 }
 //Send the position in a json encoded string. 
 socket.emit( 'position' , JSON.stringify(data));
 }, 100);

 //Toggle the on board led on or off. 
 socket.on('toggle_led', function(data){
 if(data === 'on'){
 myOnboardLed.write(0);
 } else {
 myOnboardLed.write(1); 
 }
 });
 

});

//A fuction to read our button value
function readButtonValue() {
 //If our button is pressed set the 
 //encoder init to 0. 
 if(button.value() === 1 ) {
 myRotaryEncoder.initPosition(0); 
 } 
}
 


// When exiting: clear interval and print message

process.on('SIGINT', function()

{

 clearInterval(myInterval);

 console.log("Exiting...");

 process.exit(0); 
 
});

A Github repo with working code is located here.

When you load this on your Edison and browse to the web page it will look something like this:

Or demo page contains a gauge the reads from -40 t- 40.
Or demo page contains a gauge the reads from -40 to 40.

Rotating the knob on the encoder clockwise will increase the reading on the dial. Counter clockwise will decrease it. Activating the button on the encoder will reset the dial to 0. If we go below -40 or above 40 the dial will reset to 0. This code is based on the socket.io demo I posted about previously.

So there we have it. Using a rotary encoder in our projects will give us the ability to add controls with out the need of using potentiometers and switches. With an encoder we can implement multi-level menus to enable our end users to configure and control our devices even if they are not connected to wifi or a usb port. Implementing a menu such as this will be the subject of an up coming post.

I2C Interfacing on Intel Edison

Edit October 24, 2015.

The I2C tools  project has split from lm-sensors and has gone mia recently. Some of the links I had provided stopped working. I have not been able to track down a good reference for all the tools as yet. When I do I will update this post to let you know. In the mean time I have updated the links to the command to the best reference I can find. More information about each command can always be found on the command’s man page from *nix command line.

Marc

End update.

 

In a previous post I discussed how to read the temperature from a MCP9808 temperature sensor. In this post I want to back up a bit to demonstrate some techniques for figuring out how to interface with an i2c chip and some basic verification techniques. I will be using the Intel Edison on the mini-breakout board, but these techniques will apply to most Linux based embedded systems.

The MCP9808 is an i2c bus device. I2C is short for Inter-Integrated Circuit, a two wire bus used for connecting components to each other on electronic devices. I2C is just one option used for interconnecting devices. Other options  include. SPI, 1-wire, and Serial. When using devices for an embedded project we generally find SPI or I2C on devices. I tend to go for I2C devices when I can because they allow me to get away with using less wires to hook up.

When we do integrate a device it is handy to ensure the device is recognized by the system before we try to write code for it. There are tools that are already installed on the Edison called I2C tools. Formerly a part of the LM-Sensors project, I2C tools allow low level access to I2C busses and the devices connected to them.

Before we get started lets make sure our Edison is up to date. We can do this by logging in via ssh (or use the terminal) and executing the command:

configure-edison --upgrade

You need to have your Edison attached to a network.

Let’s get started. There are four commands we are interested in that are summarized in the table here:

Bus scanning i2cdetect
Device register dumping i2cdump
Device register reading i2cget
Device register setting i2cset

Bus scanning:  

We use the i2cdetect command to both find the busses available as well as the devices on the bus. If we execute

i2cdetect -l

we can get a list of the currently installed I2C busses. The output is as as follows:

The result of i2cdetect -l on Intel Edison.
The result of i2cdetect -l on Intel Edison.

We can see we have 8 I2C buses on the Edison. But according to the docs we are only able to use bus 1 and 6 on the mini-break out board. I have only used bus 1 in my projects so far. If we wanted to see the devices on bus 1, we would enter:

i2cdetect -r 1

and get something like the following output:

The result of i2cdetect -r 1. This gives us a dump listing the devices on i2c bus 1.
The result of i2cdetect -r 1. This gives us a dump listing the devices on i2c bus 1.

When executing this command we get the standard warning that executing this command may jack up our device. It’s true, we can cause errors if we run this command on some of the other busses, but it has always cleared up for me with a power cycle of the Edison. Usually the device just hangs.

Looking at the output we can see we have four devices on bus 1. At 0x18 we have a MCP9808 temperature sensor, 0x3C is a SSD1306 display, 0x48 is an ADS1819 ADC , and 0x77 is a BMP085 barometric pressure and temperature sensor.

Device register dumping:

Now that we know what devices are on the board (or more accurately all the devices we wired to the Edison are recognized by our system) we can start working with the devices. Each device has internal registers that control the device and provide output from the device. We use the i2cdump command to take a look at these registers. Let’s take a look at the MCP9808

i2cdump 1 0x18 w

The form of the command is 12cdump (bus | device address | option). The ‘w’ option give us word output which makes it easier (for me at least) to read the registers. Executing the command gives us output that looks like this:

i2cdump of our MCP9808 on i2c bus 1 in word format. There is a lot of register space for devices, but we see we only have 13 registers in our device.
i2cdump of our MCP9808 on i2c bus 1 in word format. There is a lot of register space for devices, but we see we only have 13 registers in our device.

To understand what we are seeing in the dump we need to study the data sheet for our MCP9808.

If we study the data sheet for the MCP9808 we can decipher the registers we dumped.
If we study the data sheet for the MCP9808 we can decipher the registers we dumped.

Keeping in mind that the MCP9808 is a little endian device, we see the 16 bit data registers storing their values with the least significant  byte (LSB) first and most significant byte (MSB) second. We just need to do a quick byte swap to look at register 0 to see the value is 0x001d. According to the spec sheet the MSB should always be 0x00 as well as the LSB bits 7-4. Bits 3-0 in the LSB are the pointer used to select which register we read and write to when communicating to the device. The MCP9808 is a surprisingly complex device, so we won’t look at all the registers. But a thorough explanation of the registers and their function begins on page 16 of the data sheet.

Read a specific register:

We could certainly read the registers from the output of  i2cdump but there is a specific command for reading a single register. If we wanted to read the the current temperature the data sheet tells us the register containing this value is 0x05. To read this register we would issue this command:

i2cget 1 0x18 0x05 w

The command is in the form i2cget (bus | device address | register | option) . This gives is the following output:

Use i2cget to read the current temperature from our MCP9808.
Use i2cget to read the current temperature from our MCP9808.

We get the requisite warning and then the little endian contents of the register. Swapping the bytes to 0xC152 and referencing page 25 of the data sheet we can get the current temperature in Celsius. Briefly —   Bits 15-13 are flags that are used when we set the device to monitor a high and low set point. They can tell us if a threshold was passed, and which one. We don’t have those set so the values are not significant to us in this case. Bit 12 of the word is the sign of the two’s compliment value, since it is 0 our value is positive. Stripping those four bits out we are left with 0x0152 which is the temperature value. The rest is a base conversion and a little math — the MSB is 1 decimal, the LSB is 82. So using the data sheet formula  –> 1 * 16 + 82 / 16  = 21 degrees Celsius. Thats a cool 69.8 F in the office today.

Set a register:

If we want to manually control the MCP9808 we can set its registers with the i2cset command. Before we use the command a little back ground.

The MCP9808 has two modes of operation — continuous conversion and shutdown mode. Shutdown mode puts the device into a low power state and , as you might have guessed, stops updating the temperature measurement. If we read the temperature register while the device is in shutdown we will retrieve the last measurement made. In a battery powered device it might be a good idea to shutdown the device and only power it up when we need to update the temperature. This is controlled by bit 8 of the config register located at 0x01.

We can use the following command to enter into shutdown mode:

 i2cset 1 0x18 0x01 0x0001 w

Remember that we need to swap the bytes in the word due to endianness. This can be tested by reading the temperature while heating up the sensor (I just put my finger on it). You can use i2cget or i2cdump to read register 0x05 of the device. To set the sensor to continuous conversion mode use this command:

i2cset 1 0x18 0x01 0x0000 w

This post covered the basics of verifying a device is detected on an I2C bus and determining if the device is functioning properly. We used the four I2C tools commands to detect the busses and devices installed, dump a device registers, read a specific register, and to write a register. With these four commands we can certainly see if our devices are working correctly as we implement an embedded system.

The i2c tools do have other modes of operation that I did not touch on here. These modes can be read about by accessing each command’s man page. Armed with these tools and the data sheet for a device we are ready to get coding.

Intel Edison and I2C sensors with XDK

The Intel Edison is becoming a popular system to use for IOT devices. Despite its small form factor it is a surprisingly capable platform. This makes the Edison a good choice for interfacing with sensors.

I like the Edison mini breakout board over the Edison kit for Arduino because of the form factor. The  mini breakout board provides USB connectivity, power input and a battery charging circuit to the Edison that covers most the of my requirements for devices.

The drawback of the mini breakout is that you need to either solder in some wires or add a header to the break out board to access i/o for the Edison. Also, the Edison I/o on this board operates at 1.8 volts while most sensors operate at 3.3 volts or higher so a level converter is needed.

The Intel Edison, on the mini breakout, supports various types of i/o but the one we are interested in today is I2C  Inter-Integrated circuit is a two wire serial protocol that is used by components to transfer data between one-another. On the mini-break out board we will be using I2C bus number 1.

Here the Edison is connected to a breadboard containing the MCP9808. There are other devices on the board.
Here the Edison is connected to a breadboard containing the MCP9808. There are other devices on the board.
Here is one way to make the i/o needed for connection available.
Here is one way to make the i/o needed for connection available.

Parts list:

  1. Intel Edison mini breakout board kit.
  2. Sparkfun bi-directional level shift converter.
  3. Adafruit MCP9808 temperature sensor board.
  4. Mini bread board.
  5. Solderless bread board jumpers. 
  6. Dupont male to female cable. 
  7. 90 degree dual row header. 

Items 6 and 7 are optional – you could just solder some wire onto the Edison if you prefer, or use some other type of pin headers.

Connection:

Edison                     Level Shifter                     MCP9808

J17  – 8                          LV1

NC                                 HV1                                  SDA

J18 – 6                           LV2

NC                                HV2                                   SCL

JP19 – 2                         LV — 1.8 volt

JP20 – 2                         HV — 3.3 volt                   VDD

JP19 – 3                        Both grounds                  Ground

The connection looks something like this. The level shifter and MCP9808 are in the center of the yellow board.
The connection looks something like this. The level shifter and MCP9808 are in the center of the yellow board.

With this connection we are ready to code.

I will be using the Intel  XDK IOT edition  to read values from our temp sensor. If you have not used the XDK you can learn how to get started here. Just create a blank project and paste the following code in. Running the code will display the temperature in the console every second.

function char(x) { return parseInt(x, 16)}; // helper for writing registers

var mraa = require('mraa'); //require mraa
console.log('MRAA Version: ' + mraa.getVersion()); //write the mraa version to the Intel XDK console

var x = new mraa.I2c(1); //We will use a device in I2C bus number 1
x.address(0x18); //Default for MCP9808 is 0x10

//x.writeWordReg(char('0x01'), char('0x0100')); // Controls sleep mode for the temp sensor.

periodicActivity();

function periodicActivity()
{

var t = x.readWordReg(char('0x05')); // 0x05 is the register for the current temp.
//The byte order of words is not the same between Edison and the MCP9808
//The edison stores the most significant byte first - big endian, where the
//MCP9808 stores the lowest byte first -- little endian.
//Here is a wikipedia article on endianness. 
var s = ((t & 0xFF) << 8) | ((t >> 8 ) & 0xFF); //swap the bytes.
var r = s & 0xFFF; // Mask of the control bits to get the temp value
r /= 16.0; // dividing by 16 will give us the temp in celcius as long as the temp is above 0.

s = r * 9 / 5 + 32; //get the farenheit value.

console.log(r + " C " + s + " F"); //log the values

setTimeout(periodicActivity,1000); //do it again in a second.
}

For a more thorough explanation of the MCP9808 control registers see it’s data sheet.

And there we have it. It is not a very complex thing to interface an I2C sensor with the Intel Edison. We just need to use a level shifter and connect the thing up. Using the XDK it is fairly easy to read the temp data and control the MCP9808. The complexity comes in when more complex devices are integrated. It can take some time studying the data sheet of a device to figure out how to get everything working correctly.

There are other options for interfacing with I2C and other devices, but MRAA is the easiest in this case as it is already installed. If our sensor had been in the UPM library we could have used a predefined class to operate it.

Beagle Bone Black, Relays and Bonescript.

One of the common things to do with an embedded system is to control a high voltage device with the low voltage signal from a microprocessor. The easiest way to do this is with a relay either of the electronic or mechanical type.

In my application I want to switch a 12 volt vacuum pump on and off and open a 12 volt bleed valve to cycle pressure on and off. When the system boots or there is no 5 volt power I want the pump to be off and the bleed valve to be closed. This means I will need to use the normally open connections of the relay to control the pump and  valve. This poses a couple problems for us, which I will get in to later.

First, lets hook the relay board (Sain Smart Relay Specification) to the BBB. I chose to use P8_11 and P8_12, with 12 controlling relay 1 and 11 controlling relay 2. So make these connections:

P8_11 –> IN2

P8_12 –> IN1

P9_01 –> Ground

P9_07 –> VCC

If we wire the relays directly to the BBB we have a problem.
If we wire the relays directly to the BBB we have a problem.

When we power up the system the first problem shows up. We hear the relays chatter and notice the indictor leds are dimly lit. The issue is that at power on the pin mode is not set and the P8_11 and P8_12 are floating at a value that is neither TTL high or low. This is a problem since we are controlling a pump we don’t want the relays to momentarily energize and send power to energize it.

With the pins on the BBB floating the relays are neither on or off[
With the pins on the BBB floating the relays are neither on or off.
We can exercise the relay with the following script. Just paste this in cloud9 and step through it.

var b = require('bonescript');

var relay1 = "P8_12";
var relay2 = "P8_11";
var c = 0;
//Set pinMode causes output to go to 0, which activates our relay!
//We really need the relay off when low.
b.pinMode(relay1 , b.OUTPUT);
b.pinMode(relay2 , b.OUTPUT);

//Just alternate the relays on/off every second.
setInterval(function(){
b.digitalWrite(relay1 , c % 2 == 0 ? b.HIGH : b.LOW);
b.digitalWrite(relay2 , c % 2 == 0 ? b.HIGH : b.LOW);
c++;
}, 1000);

When we set the pin mode we see the relay activating again. Pin mode sets the pin to TTL low initially, which in this case activates our relay. It is clear we need to add a small circuit between the BBB and the relay board to get this to work the way we want it to. We will add a 74LS04  hex inverter and  a pair of 500 ohm pull down resistors. The circuit is shown here (GND on pin 7, VCC pin 14):

We will add pull down resistors and a 74LS04
We will add pull down resistors and a 74LS04

So go ahead and shutdown the BBB and wire in the 74LS04.  Unused inputs on the 74LS04 should be grounded as per the manufacturers recommendation.

With the inverter and pull downs installed the relays behave as they should.
With the inverter and pull downs installed the relays behave as they should.

When we power up the BBB we will see the problem of the floating TTL is solved via the pull down resistors, and the inverter is translating that low to a high for the relay input. This keeps the relay off. Now we can run the test script above again. If you step through it you will see that setting the pin mode no longer causes the relay to activate. Writing a low to P8_11 and P8_12 will cause the relays to deactivate, a high to these pins will activate the relays. This meets our design goal.

So we see with minimal circuitry we can easily interface the BBB to a relays. The resistors and 74LS04 can be found in any electronics surplus store for pennies, or purchased form Mouser, Digi-Key or your favorite supplier.

Next time I will discuss how to control this relay setup via a web ui with bonescript.