Category Archives: Interfacing

Using Ohmite Force sensitive potentiometers.

Force sensing potentiometers offer an alternative to mechanical potentiometers and rotary encoders. These devices do away the mechanical action of the switch and instead offer a touch sensitive alternative. After looking around the web I was not able to find a suitable library for implementing these devices so I ended up creating my own for both Arduino and Circuitpython.

The libraries implement functionality for Ohmite’s FSP series of devices. The devices include one round sensor (FPS03CE), and two linear devices (FSP01CE and FSP02CE). The linear devices come in two lengths.

All devices are single touch. This means that you can only detect on touch location on the device at a time. If we tried to detect a finger on each end of a linear device it would register as being in the middle.

The libraries have a similar api, each implement the functions necessary to get the force applied to the device as well as the position of the touch.

For all devices the force is reported as voltage. Generally 3.2 volts is the highest we will see on a 3.3 volt system. The position is reported as an integer. For the FPS03CE the integer represents 0 to 360 degrees from the tail (connector) of the device. For the linear devices it is 0 to 100 mm for the FSP01CE and 0 to 55 mm for the FSP02CE. Default for the two linear devices is for zero at the tail, but the call to position call can take a parameter to return with 0 at the head end of the device.

Integration Guide:

I was only able to find one source for the integration guide — this pdf at Mouser. It is pretty comprehensive, but contains a couple of errors that an integrator should be aware of.

First: In the section for FSP0(1/2)CE on page 4:

This section from the integration guide specifies V2 as an analog input. It does not need to be.

The document specifies that V2 should be an ADC pin. In measuring the force and position I have not read an Analog value from there. Not a show stopper, but there is no need to tie up an analog input unnecessarily. I changed this to a digital input and these sensors work correctly.

Second: In the section for FSP03CE on page 7:

This table for the FSP03CE pin out is not correct.

Using Figure 10: Pin 4 is actually the the wiper pin, while pin 1 is the third drive electrode. Plus the Pin name for pin 2 is incorrect. Luckily this diagram makes it clear where the connections go.

From the integration guide.

Hook up:

Refer to this diagram when hooking up one the FSP devices.

Use this schematic when wiring up one of the FSP devices. VRef will use a digital I/O

Each device requires one analog input and multiple digital I/O lines. I used 22K for the FSP03CE voltage divider and 18K for both the liner variants. All are 1/4 watt 5%. VRef will use a digital I/O line. These resistor values worked for my application. The sensitivity of response to touch is effected by these values. This is detailed in the integration guide.

The libraries for Arduino and CircuitPython are on on git hub. I tried to make them work similarly but there are a couple differences.

Arduino:
#include "M2aglabs_Ohmite.h"

//Set this to the one the Arduino uses
#define ANALOG_RESOLUTION 12
#define LINEAR_THRESHOLD  0.3
#define ROUND_THRESHOLD  0.3


/*
	Round sensor
	WIPER, VREF, D0, D120, D240
	Linear Sensor
	WIPER, VREF, V1, V2, true/false (Short or Long)
	 
    WIPER and VREF are on two sides of a resistor. VREF floats for position measurements,
	PULLS low for force. 
*/

M2aglabs_Ohmite roundSensor(A5, 0, 2, 1, 3);
M2aglabs_Ohmite lLinear(A2, 7, 6, 10, true);  //true means short
M2aglabs_Ohmite sLinear(A4, 5, 4, 9, false);  //false is long sensor 



void setup() {

	Serial.begin(115200);
	/*
		The lib is set for a default of 10 for analog resolution and 3.3. for voltage. If the voltage is 5.0,
		set it here. 
	*/
	analogReadResolution(ANALOG_RESOLUTION);
	roundSensor.begin(ANALOG_RESOLUTION);
	sLinear.begin(ANALOG_RESOLUTION);
	lLinear.begin(ANALOG_RESOLUTION); 

	//Set options --
	/*
	Serial.println(roundSensor.readRange());
	Serial.println(roundSensor.readRange(1500)); 
	Serial.println(roundSensor.zeroOffset());
	Serial.println(roundSensor.zeroOffset(500));
	*/

}

void loop() {
	roundSensorActions();
	linearSensorActions();
}

void linearSensorActions() {

	int spos, lpos; //Position is an integer 
	float fsp, flp; //Force is a float

	fsp = sLinear.getForce(); 
	
	if (fsp > LINEAR_THRESHOLD) { 
		//False reads from tail to tip. 
		spos = sLinear.getPosition(false);
		Serial.print("s: ");
		Serial.print(fsp);
		Serial.print(" : ");
		Serial.println(spos);

	}

	flp = lLinear.getForce(); 
	if (flp > LINEAR_THRESHOLD) {
		lpos = lLinear.getPosition(false);	
		Serial.print("l: ");
		Serial.print(flp);
		Serial.print(" : ");
		Serial.println(lpos);
	}
}



void roundSensorActions() {

	//Get the force from the round sensor 
	float force = roundSensor.getForce();
	//IF it looks like we are touching it, calculate the position. 
	if (force > ROUND_THRESHOLD) {
		
		Serial.print("force: ");
		Serial.print(force);

		int angle = roundSensor.getPosition(); 
		Serial.print(" raw angle: ");
		Serial.print(angle);

		angle = constrain(angle, 0, 360);

		Serial.print(" adjusted: ");
		Serial.println(angle);
	}
	return;
} 

The function calls are documented in the header for the library.

CircuitPython
import board
from digitalio import DigitalInOut, Direction, Pull
from analogio import AnalogIn
import time
from m2aglabs_fsp import Ohmite

# Round sensor (FSP03CE) -- it needs a lot of inputs
wiper = board.A5
v_ref = board.D0
D_0 = board.D2
D_120 = board.D1
D_240 = board.D3

# Long linear sensor (FSP01CE)
l_wiper = board.A4
l_ref = board.D5
l_v1 = board.D4
l_v2 = board.D9

# Long linear sensor (FSP02CE)
s_wiper = board.A2
s_ref = board.D7
s_v1 = board.D6
s_v2 = board.D10

s_lin = Ohmite(s_wiper, s_ref, s_v1, s_v2, type=2) # FSP02
l_lin = Ohmite(l_wiper, l_ref, l_v1, l_v2, type=1) # FSP01
s_rnd = Ohmite(wiper, v_ref, D_0, D_120, D_240) #FSP03 can add type=0, but default is 0

######################### MAIN LOOP ##############################

s_rnd.begin()
l_lin.begin()
s_lin.begin()

while True:

    s_force = s_lin.get_force()
    force = s_rnd.get_force()
    l_force = l_lin.get_force()

    if s_force > 0.4:
        position = s_lin.get_position(False)
        print(s_force, position)
      
    # for long linear
    if l_force > 0.4:
        position = l_lin.get_position()
        print(l_force, position)
       
    # for round sensor
    if force > 0.09:
        angle = s_rnd.get_position()
        print(force, angle)

The circuit python code is a lot simpler. The differences from Arduino are:

  • the ‘type=’ key word argument sets the type of sensor. 0, or round, is the default
  • the analog resolution for CircuitPython is always 65536 there is no need to set it
  • I didn’t add setters for zero offset and read range. These can be adjusted by editing the library for now. This will be added shortly.
Using the library:

Usage is fairly straightforward. The general steps are:

  • Instantiate the object
  • Call begin
  • Poll for force
  • If there is force applied read the position

These libraries have only been tested on a Metro M4 and Itsybitsy M4 to date. There is nothing that is SAMD51 specific so the Arduino library should work on other devices. I’ll be using some of these sensors on a pro-micro soon, we’ll see how it goes.

Two settings to be aware of is the _ZERO_OFFSET and _READ_RANGE. These effect each sensors overall range. The _ZERO_OFFSET specifies the normal zero reading of the ADC. With a finger at the 0 position of the sensor there is still a voltage present. Depending on the sensor, the voltage will be in the 200 to 800 millivolt range. If the sensor will not go to zero try adjusting this. For round sensors the 0’s are at 0 degrees (at the tail) then clockwise to 120 degrees, then 240. This is detailed in the integration guide.

Read range sets the maximum value of the voltage at the max end of the sensor. So if the lengths come out short, or max is hit before the end reached try adjusting this setting.

Both libraries are available on git hub.

https://github.com/m2ag-labs/m2aglabs_ohmite

https://github.com/m2ag-labs/m2aglabs_ohmite_python

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.

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.