Category: i2c

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.

 

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.

Implementing the MICS-VZ-89T gas sensor on Intel Edison i2c

On my current project I have the requirement to monitor indoor air quality. What is of interest are the levels of Volatile Organic Compounds (VOCs) and CO2.  There are specific thresholds that we are looking for that when exceeded should trigger an action. For VOCs it is when the concentration is greater that 0.9 ppm. For CO2 it is when the concentration is 1000 ppm above ambient out side C02 — which is generally around 400 ppm. The links above out line the dangers of these indoor pollutants. When the threshold is reached we want to start the ventilation system and optionally message a user.

When I need a sensor my first choice is to find one that implements i2c. In this case I found a good candidate for the job in the SGX Sensortech MICS-VZ-89T. The VZ89 product is a small board with a MICS SMD device integrated with an i2c controller. The board comes in both 5 volt (VZ89) and 3.3 volt (VZ89T) versions that are are easy to implement using a logic level shifter with the Edison on a mini breakout board. (For an example of using a logic level shifter you can see my article Intel Edison and I2C sensors with XDK.)

There was no driver that I could find for implementing the board with my setup so I had to roll my own. This wasn’t too hard, but I did have to break out the logic analyzer to get it right. If we examine the MICS-VZ-89T I2C Specification page  we see that the device only has two commands. These are Set ppmC02 and Get VZ89 Status. According to the MICS-VZ-89T Data Sheet the device comes calibrated from the factory so we don’t need to implement Set ppmC02. That leaves us Get VZ89 Status. The code that follows here is available in an XDK project on git hub.

To read the status we have to perform a two step process. First we write a command byte of 0x09 to register address 0x70. We follow this by writing two data bytes to the same register. I write 0x00 twice.

We then read 6 bytes immediately after writing the command byte. The bytes are decoded as follows:

Data byte 1 = CO2-equivalent value. 
Data byte 2 = VOC_SHORT value. 
Data byte 3 = VOC_LONG value 
Data byte 4 = Raw sensor 1st byte (LSB). 
Data byte 5 = Raw sensor 2nd byte 
Data byte 6 = Raw sensor 3rd byte (MSB).

To implement the functionality I created the following class in a node module:

//Import mraa 
var mraa = require('mraa');

//Constructor -- set defaults and populate tx_buf
function VZ89(bus , address){

 this.bus = new mraa.I2c(bus || 1); 
 this.bus.address(address || 0x70); 
 
 this.tx_buf = new Buffer(3); 
 this.tx_buf[0] = 0x09;
 this.tx_buf[1] = 0x00;
 this.tx_buf[2] = 0x00; 
 
}

//Add a function to get the device readings. 
VZ89.prototype.getReadings = function() {
 this.bus.frequency(mraa.I2C_STD);
 this.bus.write(this.tx_buf); 
 return this.bus.read(6);
 
};
//Export as a node module 
module.exports = VZ89;

The MRAA library is used to access the i2c bus, so it is imported at the top or the file. There is a constructor that optionally takes a bus number and a devices address. The VZ89 is addressed at 0x70 so we don’t really need to change that. If the Edison mini-breakout is used we have a choice of busses. I have set this to bus 6 as I am using the Edison Arduino for this example.

A class function is added to implement named getReadings to perform the measurements and return data from the device. In this case the buffer is passed back to the calling program for use.

To use the class the code in the server file would look like this:

//Import our sensor file from the file system
var Sensor = require('./VZ89.js'); 
//Create an instance of the sensor object. 
var sensor = new Sensor();
//Create a var for the receive buffer.
var rx_buf; 

//Call the readBuf function every minute. 
setInterval(readBuf , 60000); 

//A function to read the sensor data, perform data conversions and display on the console every minute.
function readBuf(){

    rx_buf = sensor.getReadings();
 
    console.log("Co2_equ: " + ((rx_buf[0] - 13) * (1600/229) + 400) + " ppm"); 
    console.log("VOC_short: " + (rx_buf[1])); 
    console.log("tVOC: " + (rx_buf[2] * (1000/229)) + " ppb"); 
    console.log("Resistor Value: " + 10 * (rx_buf[3] + (256 * rx_buf[4]) + (65536 * rx_buf[5])) + " ohms"); 
}

The details of converting the rx_buf data to usable values are in the data sheet.  The ones we are most interested in are Co2 equivalent (rx_buf[0]) and total VOC (rx_buf[2]).

As you can see, the MICS-VZ89T is a pretty easy to use device once you know how. There are only a couple of gotchas to be aware of. First, the device can only be polled once a second. I find if I try to get the readings faster than that the device will return nulls. Secondly, care must be taken when handling the device. It contains organic material that is susceptible to solvents.

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.