A web developer playing with the Intel Galileo part 4: Buttons!

Buttons are one of the main components on even some of the simplest circuits. We want our program to know when a button has been pressed and take appropriate action.

While we could use our current code and check the value of a pin for changes every X seconds this approach probably has a toll on performance, especially with languages focused on single thread execution like javascript. There, we want to find a way where a callback is executed when a button is pressed.

GPIO are capable of handling interrupts, where a system event is triggered every time a change is detected in the voltage level of a pin. To achieve this we first export the pin connected to the button and set it as input using the functions we created previously.



galileo.setUpButton = function(gpio_nr, callback){
	exportGpio(gpio_nr,function(){
		setGpioDirection(gpio_nr,"in",function(){
			// Something is missing!
		});
	});
}

In order to make the pin work with interrupts we need to write to another file in the GPIO folder, the edge file, a change the default value of none (which generates no interruption) to both (which generates interruptions on both changes from 1 to 0 and 0 to 1). Technically, GPIO edge files should accept rising and falling values as well, but it does not seem like the Galileo supports it. The complete function looks like this:


galileo.setUpButton = function(gpio_nr, callback){
	exportGpio(gpio_nr,function(){
		setGpioDirection(gpio_nr,"in",function(){
			fs.writeFile("/sys/class/gpio/gpio" + gpio_nr + "/edge", "both", fileOptions, function (err) {
				if (err) { 
					console.log("edge error");
					console.log(err); 
				}
				callback();
			});
		});
	});
}

As for making a function execute on a button press, we will use a different low level library called epoll, and guiding ourselves with the examples create a function that will bind a callback on the interrupt


galileo.setButtonCallback = function(gpio_nr, callback){
	
	var  valuefd = fs.openSync('/sys/class/gpio/gpio'+gpio_nr+'/value', 'r');
	var  buffer = new Buffer(1);

// Create a new Epoll. The callback is the interrupt handler.

	var poller = new Epoll(function (err, fd, events) {

// Read GPIO value file. Reading also clears the interrupt.
  		fs.readSync(fd, buffer, 0, 1, 0);
  		callback(buffer.toString());
	});

// Read the GPIO value file before watching to
// prevent an initial unauthentic interrupt.
	fs.readSync(valuefd, buffer, 0, 1, 0);
// Start watching for interrupts.

	poller.add(valuefd, Epoll.EPOLLPRI);

	return poller;
}

Be sure to connect your button correctly when testing, or else you will get unpredictable results:

schemeit-project(1)

 

I am putting together all this functions in a library that can be downloaded from npm and used on the Galileo. Be sure to check it out and contribute if you can.

Advertisements
Tagged with: , , ,
Posted in devices

A web developer playing with the Intel Galileo part 3: Analog Output (PWM)

So, now that we have figured out digital input/output and analog input it is time for the Analog Output… or rather, a simulation of it using the technique known as Pulse Width Modulation, or PWM. If you have some bases on electronics this term should not be anything new for you. If not, take a look at one of the very good tutorials online on how it all work. It is highly recommended you get a basic idea of how it works, since PWM is one of the most widely used techniques in electronic for controlling something like the speed of a motor or a led’s brightness. You probably use PWM on a daily basis without realizing it.

The Galileo is capable of outputting a PWM wave. Here is how we make it work from Javascript.

First, take another look at the digital pins.

galileohiresmin

If you look closely, you will realize there is sinusoidal sign next tome some pins (a squiggle). This marks which pins are capable of PMW output.

Similar to our previous cases, managing this pins is a matter of writing to a number of specific files, this time on the /sys/class/pwm/pwmchip0/ folder. The steps are simple:

  1. We write to the export file with the number of the PWM Channel we want to use
  2. Inside the folder corresponding to the channel we write 1 to the enable file
  3. We write a number (in nanoseconds) that corresponds to the period of the wave to the period file
  4. Finally, we write a length (in nanoseconds) that corresponds to the duty cycle of the wave to the duty_cycle file.

Once again the PWM channel number and the pin number are not always the same, so we must create a variable to map them out:

 


var PWMmapping = {
	"3": 3,
	"5": 5,
	"6": 6,
	"9": 1,
	"10": 7,
	"11": 4
}

With that done, let us make a pair of functions for steps 1 and 2. A function that exports the desired PWM channel and one that writes to it for enabling.


exportPWM = function(pwm_w, callback) {
	fs.writeFile('/sys/class/pwm/pwmchip0/export', pmw_w, fileOptions, function (err) {
		if (err) { 
			console.log("export error");
			console.log(err);
		}
		if(callback){
				callback();
			}
});
};

galileo.writePWM = function(pwm_wr, value, callback){
	if(value != 0 && value !=1){
		console.log("PWM write only supports binary values");
		return;
	}
	fs.writeFile("/sys/class/pwm/pwmchip0/pwm" + pwm_wr + "/enable", value, fileOptions, function(err, data) {
		if (err) { console.log("Writing " + pwm_wr + " " + value); }
		if (callback){ callback();}
	});
}

For easier future usage, we can put this into one simple prepare function:


galileo.preparePWM = function(pwm_w, callback) {
	exportPWM(pwm_w, function(){
		galileo.writePWM(pwm_w, 1, function(){
			callback();
		});
	});
}

With that done, all we need is functions that set up the period and duty cycle:


galileo.setPWMperiod = function(pwm_wr, value, callback){
	fs.writeFile("/sys/class/pwm/pwmchip0/pwm" + pwm_wr + "/period", value, fileOptions, function(err, data) {
		if (err) { console.log("Period " + pwm_wr + " " + value); }
		if (callback){ callback();}
	});
}

galileo.setPWMdutycycle = function(pwm_wr, value, callback){
	fs.writeFile("/sys/class/pwm/pwmchip0/pwm" + pwm_wr + "/duty_cycle", value, fileOptions, function(err, data) {
		if (err) { console.log("duty_cycle " + pwm_wr + " " + value); }
		if (callback){ callback();}
	});
}

Tagged with: , , ,
Posted in devices

A web developer playing with the Intel Galileo part 3: Analog Input

Next in the list is Analog Input. Once again following the arduino template, the Galileo has 5 pins that read a voltage  with a resolution of 12 bits, meaning that we will get a number from 0 to 4095 where 0 is 0 volts and 4095 is 5 volts. This is useful for reading data out of sensors and such.

You can see the analog pins labeled from A0 to A5.

Now, the sources that have guided us so far tells us that reading from the analog is not as easy as setting things on the GPIO and reading the value file. Analog pins need to be set up correctly in the inner circuity and then read trough files in /sys/bus/iio/devices/iio:device0.

Setting the inner circuity is the trickiest part, and we do it so by playing around with the multiplexers (a circuit that is able to be digitally controlled to chose what the input is connected to) and setting their values in such a way that the analog pins would be readable. Each multiplexer is connected to GPIO number and controlled from there, so we set a new variable with maps each analog pin to the multiplexer that controls it.


var analogMuxMapping = {
	"A0": 37,
	"A1": 36,
	"A2": 23,
	"A3": 22,
	"A4": 21,
	"A5": 20
}

In order to set up the multiplexer correctly we need to export the corresponding GPIO number, set it to output mode and set the value to 0 using the methods that we have already used for digital pins. We can easily create a function in the library that does this in steps:


prepareAnalogIn = function(gpio_mux, callback){
	exportGpio(gpio_mux, function(){
		galileo.setGpioOut(gpio_mux, function(){
			galileo.writeGpio(gpio_mux, 0, callback);
		});
	});
}

Once that is done, reading the pins value is simply reading from a file is /sys/bus/iio/devices/iio:device0/. There are two types of files there for every pin, a in_voltage*_raw and a in_voltage*_scale. The first one gives you the raw number between 0 and 4095, while the second gives you a scaled representation of how many volts do that mean. We will limit ourselves to using the raw value, but you can use the scaled one if needed. Also, this time the pins are not mapped out in strange ways, so 0 actually means A0 and 5 actually means A5.

The resulting javascript function looks like this:


galileo.readAnalog = function(analog_nr, callback){
	fs.readFile("/sys/bus/iio/devices/iio:device0/in_voltage" + analog_nr + "_raw", fileOptions, function(err, data) {
		if (err) { console.log("Error reading analog" + analog_nr); }
		var value = data;
		callback(value);
	});
}
Tagged with: , , ,
Posted in developer tips

A web developer playing with the Intel Galileo part 2: Digital Input-Output

Our next step is manipulating the hardware ports from a language we feel comfortable, like JavaScript, so we can do future experimentation on it. Since this seems to have some potential, we may turn this into a library so future developers can build apps on Galileo using JavaScript with ease. We will be posting our results over github and publishing at npm. Should be fun.

First we must figure out how to get the digital input working.

Physically, the Galileo uses an Arduino compatible layout of pins, which gives us 14 digital pins to play with.

galileohiresmin

Since the Galileo runs a full Linux the pins are manipulated trough the General Purpose Input Output (GPIO), which is a very fancy way of saying we control it by writing and reading to some very specific files. Every pin gets its own set of files in /sys/class/gpio.

A word of warning tough, do not start playing randomly with the gpio files. Many of the gpio files are associated with electronic components in the Galileo that have nothing to do with the digital pins and could generate catastrophic results if changed.

Now you may notice files in the gpio folder are classified by number and may think the numbers correspond to the printed pin number. Sadly, you are very wrong. The powers that be had it so the printed numbers and GPIO number had absolutely no connection whatsoever, making the warning I just gave sound much more alarming. A quick google of the GPIO mapping will easily lead to tables that describe to which GPIO each pin is connected. But since we do not want to deal with that every time we write or read from a pin we take a preventive solution and create variable that maps every printed pin to the actual GPIO number.


var digitalMapping = {
	"0": 50,
	"1": 51,
	"2": 32,
	"3": 18,
	"4": 28,
	"5": 17,
	"6": 24,
	"7": 27,
	"8": 26,
	"9": 19,
	"10": 16,
	"11": 25,
	"12": 38,
	"13": 39,
}

There! Much easier!

Now, following the guidance of Sergey Kiselev super informative blog we discover that using a pin is a 3 step process:

  1. Write to the export file on the gpio folder the number of the gpio we wish to use, which creates the necessary files
  2. Set if the pin is meant to be read or write (in or out) using the direction file in the pin’s folder
  3. Write or read a value from the value file in the pin’s folder

We are interested on making this into a Javascript function, so we can use the fs module to read and write from the files.

First, to export:


exportGpio = function(gpio_nr, callback) {
	fs.writeFile('/sys/class/gpio/export', gpio_nr, fileOptions, function (err) {
		if (err) { 
			console.log("export error");
			console.log(err);
		}
		if(callback){
				callback();
			}
});
};

Then to set the direction:


setGpioDirection = function(gpio_nr, direction, callback) {
	fs.writeFile("/sys/class/gpio/gpio" + gpio_nr + "/direction", direction, fileOptions, function (err) {
		if (err) { 
			// console.log("Could'd set gpio" + gpio_nr + " direction to " + direction + " - probably gpio not available via sysfs");
			console.log("direction error");
			console.log(err); 
		}
		callback();
	});
}

galileo.setGpioIn = function(gpio_map, callback) {
	setGpioDirection(gpio_map, 'in', callback);
}

galileo.setGpioOut = function(gpio_map, callback) {
	setGpioDirection(gpio_map, 'out', callback);
}

And finally, to write or read values:



galileo.readGpio = function(gpio_nr, callback) {
	fs.readFile("/sys/class/gpio/gpio" + gpio_nr + "/value", fileOptions, function(err, data) {
		if (err) { console.log("Error reading gpio" + gpio_nr); }
		var value = data;
		callback(value);
	});
};

galileo.writeGpio = function(gpio_nr, value, callback) {

	if(value != 0 && value !=1){
		console.log("gpio write only supports binary values");
		return;
	}

	fs.writeFile("/sys/class/gpio/gpio" + gpio_nr + "/value", value, fileOptions, function(err, data) {
		if (err) { console.log("Writing " + gpio_nr + " " + value); }
		if (callback){ callback();}
	});
};

Please remember that you can only read from pins set as input (in) an write to pins set as output (out) and that only 0 and 1 are allowed as values, with 0 being 0 volts and 1 being 5 volts. Every function is run asynchronously so you need to pass a callback in order to chain it all together. In order to simplify the process a little further we add a “preparePin” function that does the export and direction setting in succession, taking a boolean value as the direct, true for input, false for output:


galileo.preparePin = function(gpio_map, direction, callback) {
	exportGpio(gpio_map, function(){
		if(direction){
			galileo.setGpioIn(gpio_map, callback);
		}else{
			galileo.setGpioOut(gpio_map, callback);
		}
	});
}

So, for a simple example, let us load the library into a test object, connect a led to pin 0, turn it on and the off after 2 seconds:



var led_pin = test.digitalMapping[0]; 

test.galileo.preparePin(led_pin,false,function(){
     test.galileo.writeGpio(led_pin, 1, function(){

     setInterval(function(){
		 	test.galileo.writeGpio(led_pin, 0);
	},2000);

     });
});

Tagged with: , , ,
Posted in devices

When a web developer decides to play with hardware. Playing around with the Intel Galileo part 1: connecting the Galileo to a wifi

As web and occasional android developer I do not get to play a lot with hardware boards and such, but two weeks ago someone gave me and arduino uno and showed me some of the examples. I have imagined that even the basic stuff was harder and a newfound curiosity for learning how to use this kind of thing was born on me. So when I heard at MWC that Intel was showing its new Internet of things platforms, Galileo and having a workshop where I may be able to get one I jumped (quite literally) at the opportunity.

The galileo is a little marvel that runs an x86 intel quark processor and that is cable of booting full linux and running node.js, meaning that I can play with the hardware without the needed of dusting off my C skills and do some other network-related things with it.

Thankfully, the good guys at intel included an Intel Centrino Wireless-n 135 wifi card that connects to the mini PCI Express port under the board, so the first challenge was too make it connect to a wifi network, which after reading dozens of blog posts, forum threads and linux guides was harder than I expected. Here is a dumb step by step guide of how I ended making it work:

Note: I am using the galileo with full linux running from the sd card.

But first, a short guide about communicating with the Galileo

The galileo has many ports that could be used to control it from your computer, but the simplest one to start with is the serial port that looks like a headphone 3.5 mm input. Since many people do not have a serial port now a days you will need a pair of cables to connect to it which you can buy or make (as this forum thread explains).

Once you have the usb to serial and serial to 3.5 mm connected you can use minicom to connect to the galileo trough terminal and play around with it. For reference, here is the minicom configuration file I use for it. All you need to do is put this file into /etc/minicom and run minicom as root or superuser and you should connect without problem. After establishing a connection I recommend you play with the network configuration so you can ssh into the galileo. In my experience the serial connection is good for simple things but it has… complications with several programs.

In order to give the ethernet port a static ip edit the /etc/network/interface, where the configuration for all your network interfaces is. Make sure the eth0 configuration says something like:

auto eth0
iface eth0 inet
static address 10.0.0.2
netmask 255.255.255.0

This will assure us that eth0 will have the 10.0.0.2 address every time the galileo boots up. You could try restarting the networking service but the new address will not stick until we get rid of connman. More on that later. For now set it manually with:

ifconfig eth0 10.0.0.2 netmask 255.255.255.0

Make sure you configure the Ethernet interface in your computer to an address like 10.0.0.1, then you can ssh to the galileo and we do not need the minicom connection any more.

Connecting to wifi

If you use WPA encryption in your network, like I do, we are going to need to use wpa_supplicant. On the galileo, run:

root@clanton:~# wpa_passphrase WIFINAME << EOF > /etc/wpa_supplicant.conf
> YOURPASSWORD
> EOF

Substitute WIFINAME with the name of your… err, wifi, and YOURPASSWORD with the password. I am remaining you just in case.

Before we can make the connection, it turns out connman has a bug which causes the galileo to authenticate and deautenticate from the wifi in an infinite loop. The solution, according to this thread, is to kill it. So go ahead and run:

killall connman

and just to be sure, lets remove the init script

rm /etc/init.d/connman

With that out of the way, lets connect:

wpa_supplicant -B -D nl80211 -i wlan0 -c /etc/wpa_supplicant.conf

If you have configured everything properly the wifi should be autenticated by now. All you ned is to trigger the dhcp. Run

ifup wlan0

Check with ifconfig, but you should be connected at this point.

Here is a list of links that I went trough in my search for answers:

Tagged with: , ,
Posted in developer tips

FirefoxOS app Localization, the Javascript side of things

After playing around with adding several languages for my app’s HTML interface on the previous post I began researching how to use this setup to change strings on the JavaScript side depending on the settings language.

After a look at Gaia’s source code, it turns out it is actually pretty easy to access the string variables from the last post’s setup. Using the same example from that post, from JavaScript we could do

var loadVariable = navigator.mozL10n.get('loading');

var EmpPlayVariable = navigator.mozL10n.get('EmptyPlaylist');

var SaveCurVariable = navigator.mozL10n.get('SaveCurrent');

var LoadCurVariable =navigator.mozL10n.get('LoadCurrent');

var AddWhVariable =navigator.mozL10n.get('AddWhole'); 

And now we have a group of variables loaded with the correct translated value, directly from the appropriate property file. Easy

Tagged with: , ,
Posted in developer tips

Easy guide to Localize a FirefoxOS app’s html interface

Since Firefox OS was released in Spain and Latin America is targeted next I tough that translating the app I keep working on to Spanish was a natural decision.

Since my HTML interface is pretty simple, my first impulse was to take the most early-web approach every and create a secondary index.html in Spanish and have the manifest.webapp point to that file when the locale is set to “es”.

Needless to say, this did not work well. After taking a look at the gaia source code it was obvious there was some sort of mechanism the apps were using for the elements to change their text automatically depending on the phone’s set language but either I am a very bad seeker or there is no easy to find, step by step guide on how to make it work.

So, after reading some documentation here and here and trying out several things I decided to create this simple, easy to follow guide on localizing the html interface of your FirefoxOS app.

    • You are going to need a .js file used by all gaia apps. The code is here. Add this to your app and import it in your html.
    • Add a “data-l10n-id” property with an unique id to every html element whose contents you need to change depending on the language. Here is an example on my html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>TEST</title>
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/action_menu.css">
<script type='text/javascript' src="js/res/jquery.js"></script>
<script type='text/javascript' src="js/res/jquery.mobile.custom.js"></script>
<script type='text/javascript' src="js/res/modernizr.custom.js"></script>
<script type='text/javascript' src="js/res/async_storage.js"></script>
<script type='text/javascript' src="js/res/youtube.js"></script>
<script type='text/javascript' src="js/main.js"></script>

<!-- Localization stuff -->

<script type='text/javascript' src="js/res/l10n.js"></script>
</head>
<body id="body">

<div id="toast" >
<img src="img/refresh.png" /> <p data-l10n-id="loading">Loading</p>
</div>

<div id="wrapper">

<div id="scrollbar">
<!-- <img src="img/art.png"></img> -->

</div>
<div id="display">

<div id="section1">
<img src="img/test.jpg" id="CurrentlyPlaying"></img>
<p id="SongName" data-l10n-id="EmptyPlaylist"> Empty playlist. Search for youtube videos and add! </p>
<div id="SeekBar"><div id="ProgressBar"></div> </div>
</div>
<div id="section2">
<div id="Button_container">
<div id="back">
<img src="img/back.png"></img>
</div>
<div id="play">
<img id ="playImg" src="img/play.png"></img>
</div>
<div id="foward">
<img src="img/forward.png"></img>
</div>
<div id="randomB">
<img id="shuffleImg" src="img/shuffle.png"></img>
</div>
<div id="menu">
<img id="menuImg" src="img/menu.png"></img>
</div>
</div>
</div>
</div>
</div>

<div id="blocker">
<form id="secondForm" role="dialog" data-type="action">
<menu id="IniMenu">
<button id="save" data-l10n-id="SaveCurrent"> Save Current Playlist </button>
<button id="BrowsePlaylists" data-l10n-id="LoadCurrent"> Load saved playlist </button>
<button id="AddYTP" data-l10n-id="AddWhole"> Add whole YT playlist </button>
<button id="CloseUp" data-l10n-id="Close"> Close </button>
</menu>
<menu id="loadMenu">
<button id="Cancel" data-l10n-id="Close"> Close </button>
</menu>
</form>
</div>
<!-- <video controls='controls' id="player"/> -->
<audio  mozaudiochannel="content" id="player" />
</body>
</html>
    • Create a .properties file for every language you are going to be localizing to. Each file needs to contain the “data-l10n-id” of an element, an equal sign and the text you want inside of it for that lenguage… Actually, just look at my example and you will probably understand it better than my crappy explanation:

My english.properties files:

loading = Buffering. Please Wait

EmptyPlaylist = Empty playlist. Search for youtube videos and add!

SaveCurrent = Save Current Playlist

LoadCurrent = Load saved playlist

AddWhole = Add whole YT playlist

Close = Close

My spanish.properties files:

loading = Cargando. Por favor espere

EmptyPlaylist = Lista de reproducción vacía ¡Busca videos en Youtube y agrega! 
SaveCurrent = Guardar List. de Repro. actual

LoadCurrent = Cargar lista guardada

AddWhole = Importar lista de YT completa

Close = Cerrar

    • Create a locales.ini file where you import every .properties files specifying which language which one is supposed to be associated with using the structure in the example:
@import url(english.properties)

[es]
@import url(spanish.properties)
    • Be sure to import the locales.ini in your html.
<link rel="resource" type="application/l10n" href="locales/locales.ini">

And you are done. Now your HTML elements have text that reacts to the Phone’s language settings. Happy coding.

Tagged with: , , ,
Posted in developer tips