Skip navigation


6 Posts authored by: oneleggedredcow Top Member


In the previous articles, we set up the BeagleBone to have a MySQL database and a web server.  We also wrote a simple web site to control the LEDs on the BeagleBone.


In this article, we are going to tie all of the pieces together and create a web site that displays the temperature of the room that the BeagleBone is in.  We are going to do this by taking temperature measurements using the analog input on the BeagleBone and storing the measured values in the database.  We will then create a PHP page that will query the data out of the database and display it to the user in a google chart.


Preparing the Database

The first step is to create a new MySQL database:




Next, we should probably create a new user to log into the database with.  This isn’t strictly necessary, but it is a good idea to not log in as root every time.  Here’s how to create a new user:


CREATE USER bone@localhost IDENTIFIED BY ‘bone’;


Then we need to give the new user (bone) permissions on the newly created database:


GRANT ALL ON TempDB.* to bone@localhost;

BeagleBone - MySQL.png

I usually prefer to create my tables in code rather than through the MySQL prompt.  The reason is that if I ever want to make any changes or start over, I can just drop the table and then rerun my code and it will take care of it.  I find that this makes it faster and easier to make changes to my table.


Interfacing with the Database

So, now that the database and user are set up, we can shift over to C++ to create the table and take temperature measurements.  We’ll start by creating a program that just inserts in any old data into the table and then we’ll incorporate a temperature sensor.  Here’s the first cut at the program:


#include <mysql.h>

#include <stdlib.h>

#include <stdio.h>

#include <string.h>


/// Prints out a MySQL error message and exits


/// This function should be called after a MySQL error has been encountered.  This function will then

/// notify the user of the error that has occurred, clean up the existing MySQL connection, and then

/// exit the program.


/// @param The MySQL connection to clean up before exiting

void error_exit(MYSQL *con)


fprintf(stderr, "%s\n", mysql_error(con));


if (con != NULL)








int main(int argc, const char *argv[])


// Initialize a connection to MySQL

MYSQL *con = mysql_init(NULL);

if(con == NULL)





// Connect to MySQL

// Here we pass in:

//  host name => localhost

//  user name => bone

//  password => bone

//  database name => TempDB

if (mysql_real_connect(con, "localhost", "bone", "bone", "TempDB", 0, NULL, 0) == NULL)





// Create the TempMeas database (if it doesn't already exist)

if (mysql_query(con, "CREATE TABLE IF NOT EXISTS TempMeas(MeasTime DATETIME, Temp DOUBLE)"))





// Initialize a MySQL statement

MYSQL_STMT *stmt = mysql_stmt_init(con);

if (stmt == NULL)





// Set out insert query as the MySQL statement

const char *query = "INSERT INTO TempMeas(MeasTime, Temp) VALUES(NOW(), ?)";

if (mysql_stmt_prepare(stmt, query, strlen(query)))





// Create the MySQL bind structure to store the data that we are going to insert

double temp = 0.0;


memset(&bind, 0, sizeof(bind));

bind.buffer_type = MYSQL_TYPE_DOUBLE;

bind.buffer = (char *)&temp;

bind.buffer_length = sizeof(double);


// Bind the data structure to the MySQL statement

if (mysql_stmt_bind_param(stmt, &bind))





// Insert multiple records into the database,

// with different data each time

for (int i = 0; i < 10; i++)


temp = (float)i;




// Close the MySQL connection



return 0;



The code is surprisingly straight-forward.  We start by creating the table if it does not exist.  Then we create a parameterized query.  Note that we don’t need to recreate the query or rebind the parameters. This is because we pass a pointer to the bind structure.  So, all we need to do is execute the statement every time a new measurement is taken.


To build the code, use the following command:


g++ tempmeas_initial.cpp -o tempmeas_initial -I/usr/include/mysql –lmysqlclient


Then you can run it using:




After running the program, we can go over to MySQL and make sure that everything worked like we expected:

MySQL - initial test.png

That looks good, so let’s move on to incorporating a temperature sensor.


Temperature Sensor

Now that we know that we can put data into the database, let’s set up a circuit to gather that data:

IMG_1469 (1280x960).jpg

Here we have a MCP9701E temperature sensor connected to analog input #1.  I also did a simple voltage divider to cut the voltage in half since the input voltage is 3.3V and the analog input pins can only handle a maximum of 1.8V.  The sensor output will never be that high (unless it gets really hot), so it is probably unnecessary, but better safe than sorry.


Now we can test to make sure that the circuit is working properly by reading the value that it outputs at:


Older BeagleBone:

cat /sys/devices/platform/tsc/ain1


Newer BeagleBone:

cat /sys/devices/platform/omap/tsc/ain1


Reading the Temperature Sensor

The value that is returned is between 0 - 4096 and it is a measurement of the voltage that is connected to ain1.  We need to convert that voltage into a temperature and to do that, we use the information from the datasheet.  Here is the conversion in code:




#ifndef MCP9701E_H

#define MCP9701E_H


class MCP9701E



int _input;

char _buffer[1024];


static const float Vdd;


static const int TempSensorMin;

static const int TempSensorMax;


static const float V0;

static const float Tc;



MCP9701E(const char *pin);

float GetTemperature();

void Close();







#include "MCP9701E.h"


#include <stdlib.h>

#include <fcntl.h>

#include <stdio.h>

#include <unistd.h>


/// Input voltage

const float MCP9701E::Vdd = 3.3;


/// Maximum and minimum values that can be measured

const int MCP9701E::TempSensorMin = 0;

const int MCP9701E::TempSensorMax = 4096;


/// Temperature sensor constants

const float MCP9701E::V0 = 0.3f;

const float MCP9701E::Tc = 0.0195f;


/// Handles a MCP9701E temperature sensor


/// @param Hardware device to read the temperature measurements from

MCP9701E::MCP9701E(const char *pin)


_input = open(pin, O_RDONLY);



/// Grabs a temperature measurement

float MCP9701E::GetTemperature()


// Read the sensor

int status = read(_input, _buffer, sizeof(_buffer));

if (status == -1)


fprintf(stderr, "ERROR: Could not get temperature measurement.");

return -999.0f;



// Reset the sensor

lseek(_input, 0, 0);


// Convert the string into an integer

_buffer[status] = '\0';

int value = atoi(_buffer);


// Convert the measurement into a temperature

float voltage = ((float) value) / (TempSensorMax - TempSensorMin + 1) * Vdd;

float temp = (voltage - V0) / Tc;


return temp;



/// Closes the temperature sensor

void MCP9701E::Close()


if(_input != -1)



_input = -1;




Then we can make a small modification to our code that imports numbers into the MySQL database, so that it now imports in actual temperature measurements.  To do this, we replace the previous for loop with the code below:


// Initialize the temperature sensor

MCP9701E sensor("/sys/devices/platform/omap/tsc/ain2");


// Take a temperature measurement and insert it into the database

for (int i = 0; i < 10; i++)


temp = sensor.GetTemperature();





// Close the temperature sensor



The full version of the code is attached below.


To build the code, use the following command:


g++ tempmeas.cpp MCP9701E.cpp -o tempmeas -I/usr/include/mysql –lmysqlclient


Then you can run it using:




Next we can go over to MySQL and verify that actual temperature measurements are being populated in the database:

MySQL - temp meas.png


Creating a Web Page

The final piece of the puzzle is to create a web page to display the information in.  To do this, we will use google charts, and slightly modify their line chart example.  All we need to do is add some logic to query the data from the MySQL database:




<title>BeagleBone Temperature</title>

<script type="text/javascript" src=""></script>

<script type="text/javascript">

google.load("visualization", "1", {packages:["corechart"]});


function drawChart() {

var data = google.visualization.arrayToDataTable([

['Time', 'Temperature'],


$con = mysqli_connect("localhost", "bone", "bone", "TempDB");


$query = "SELECT * FROM TempMeas";

$result = mysqli_query($con, $query);




while ($row = mysqli_fetch_array($result))


$time = $row['MeasTime'];

$temp = $row['Temp'];

echo "['$time', $temp],";





var options = {

title: 'BeagleBone Measured Temperature',

vAxis: { title: "Degrees Celsius" }



var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

chart.draw(data, options);





<div id="chart_div" style="width: 900px; height: 500px;"></div>




The change that we made to the google chart example is the addition of the PHP code.  This code will query all of the data in the database and insert it into the web page that is returned to the user.  If the sensor has been running for a long time, this could be a lot of data.  An improvement would be to limit the measurements to the past hour or so. Even better would be to make it user configurable through the web page!  Here we are just focused on a simple example.


Finally, we can visit our web page and check out our results!

temp page.png


In these articles, we have demonstrated how to turn your BeagleBone into a very powerful web server. MySQL, PHP, and JavaScript are the building blocks of most web sites.  Using these tools, you can create some very exciting sites on your BeagleBone! And if you do, please post them to the comments, I’d love to see what projects you are working on.


MySQL is a very popular open source database.  In this project, we will use it to store the measured temperature values, which can then be retrieved by a web page.


Installing MySQL

Before we start, if you have not updated opkg in a while, you should probably do that first:


opkg update


Now on to the task at hand. Installing MySQL.  There is already an opkg package, so we’ll install that:


opkg install mysql5


This will download and install MySQL.  Unfortunately, if we try and fire up MySQL:


/etc/init.d/mysqld start


We will see an error:


/etc/init.d/mysqld: line 3: /etc/default/rcS: No such file or directory

BeagleBone - mysqld error.png

The fix to this issue is fairly easy.  We need to comment out that line 3 in the script:


vi /etc/init.d/mysqld

BeagleBone - mysqld comment out.png

Now when we try and fire up MySQL:


/etc/init.d/mysqld start


We are successful and we can log into MySQL:

BeagleBone - mysql prompt.png


At this point it might seem like time for celebration.  We have MySQL installed and are able to run it and log in.  Unfortunately, if we restart then when we log in again we will get an error stating:


Cannot make/remove an entry for the specified session.


This is really annoying since it won’t let you log in and fix the issue.  I had to resort to reimaging my SD card and trying again. (The steps are here, in case you have to do it as well.)


MySQL Configuration

To fix that issue, we need to make some more configuration changes.  First we need to remove some unnecessary links:


rm /etc/rc*/*mysqld

BeagleBone - remove mysql links.png

Now this prevents MySQL from starting at boot.  Since we want MySQL to start at boot, let’s see if we can fix that.  To do this, we need to create a new configuration file:


vi /lib/systemd/system/mysql.service


And put the following text in that file:



Description=MySQL database server




ExecStop=/bin/kill -15 $MAINPID






Now we can enable the MySQL service to start at boot and then start the MySQL service:


systemctl enable mysql.service

systemctl start mysql.service


Then we should be able to check the status of the service and make sure that it is running:


systemctl status mysql.service

BeagleBone - mysql service start.png

Now you should be able to restart without getting the log in error and MySQL should be running!


Installing MySQL Client Library

The last thing that we need to do is install the MySQL C programming client library:


opkg install libmysqlclient-dev


Now, let’s test to make sure that it installed correctly and works.  To do this, create small test script:


#include <mysql.h>

#include <stdio.h>


int main(void)


                printf(“MySQL client version: %s\n”, mysql_get_client_info());


return 0;



This will print out the version information for the MySQL client.  To build it type:


g++ test.cpp -o test -I/usr/include/mysql –lmysqlclient


And then to run it, type:



BeagleBone - test code build.png

Now MySQL should be installed on your BeagleBone and ready to use!




Next Article

In the next article, we will create a C program that will measure the temperature of the room.  It will then write the current temperature into the MySQL database.  Finally, we will create a web interface to retrieve and plot the measured temperatures of the room.


In the previous article, we set up the BeagleBone to be a webserver running Lighttpd and PHP.


In this article, we are going to build upon that foundation.  We are going to create a web site that lets the user turn on and off an LED on the BeagleBone.  This is a good example of how to create a simple web page that interacts with the BeagleBone and is a step towards our final goal of creating a website to show historical temperature information.


Turning a LED On/Off

BeagleBone LEDs can be turned on/off through command line, but in order to do this, we need to figure out what they are named.  The names can be found like this:


ls -1 /sys/class/leds

BeagleBone - led location.png

So, turning the usr2 LED on/off would look something like this:

BeagleBone - turn led on-off.png

1 will turn the LED on, and 0 will turn the LED off.


By default, some of the LEDs are used to display information to us about what is going on.  So, if you change the state of one of those LEDs, it will be quickly overwritten.  We can see this by looking at the trigger:


cat /sys/class/leds/beaglebone::usr0/trigger

BeagleBone - default trigger.png

To modify this so that the LED only changes when we tell it to, we can change the trigger to none:


echo none > /sys/class/leds/beaglebone::usr0/trigger

BeagleBone - change trigger.png


C Program

Now that we know how to turn on/off the LEDs, we can write a small C program to make it easier for us. The program will take in the number of the LED to change (0-4) and the state to change it to (off = 0, on = 1). Here’s the code:


#include <stdio.h>

#include <stdlib.h>

#include <fcntl.h>

#include <unistd.h>


int main(int argc, const char *argv[])


if (argc != 3)



printf("\tledCtl <led> <on/off>\n");


printf("<led>  : Number between 0-3\n");

printf("<on/off>: 1 = on, 0 = off\n");


return 1;



int ledNum = atoi(argv[1]);

if (ledNum < 0 || ledNum > 3)


printf("<led>  : Number between 0-3\n");


return 1;



char ledPath[1024];

sprintf(ledPath, "/sys/class/leds/beaglebone::usr%d/brightness", ledNum);

int fid = open(ledPath, O_WRONLY);


int onOff = atoi(argv[2]);

switch (onOff)


case 0:

write(fid, "0", 1);


case 1:

write(fid, "1", 1);



printf("<on/off>: 1 = on, 0 = off\n");

return 1;





return 0;



Remember to change the path of the LED to the path that we found earlier.


For a simple task like this, we could have just used the command line to turn the LEDs on/off. However, I wanted to put it into a C program so that we set ourselves up better for the future.  When we take temperature measurements and put them into a MySQL database, it will require more logic that is better suited for a small program rather than the command line.


The code should be fairly clear.  It is mostly just checking the inputs that the user gave us to make sure that they are reasonable.


Before we compile it, we need to create a directory to store the scripts that we are going to be running on our web site:


mkdir /www/cgi-bin


To compile the code, type:


g++ ledctl.cpp -o /www/cgi-bin/ledctl

BeagleBone - ledctl compile.png


Then we can run some examples and make sure that it works:



/www/cgi-bin/ledCtl 2 1

/www/cgi-bin/ledCtl 2 0

BeagleBone - ledctl test.png


Creating a Web Page

Awesome, now that we have a program to control the LEDs on the BeagleBone, let’s create a web page so that we can control the LEDs over the Internet.  Let’s call the web page ledCtl.php and place the following code in it:




<title>BeagleBone LED Changer</title>

<style type="text/css">

p { display: table-cell; }

button { width: 75px; margin: 2px auto; }



if (isset($_GET['led']) && isset($_GET['onOff']))


$led = $_GET['led'];

$onOff = $_GET['onOff'];


exec( "/www/cgi-bin/ledctl $led $onOff" );





<div style="width: 200px; margin: 0px auto;">

<div style="width: 100px; float: left;">

<p>LED #2:</p>

<button type="button" onclick="location.href='ledCtl.php?led=2&onOff=1'">ON</button>

<button type="button" onclick="location.href='ledCtl.php?led=2&onOff=0'">OFF</button>


<div sytle="width: 100px; margin-left: 100px;">

<p>LED #3:</p>

<button type="button" onclick="location.href='ledCtl.php?led=3&onOff=1'">ON</button>

<button type="button" onclick="location.href='ledCtl.php?led=3&onOff=0'">OFF</button>






Note: We used LEDs #2 and #3 because LED #0 and #1 occasionally blink and override our on/off settings.


Then we can test our web page by going to a browser and using our new web page:

BeagleBone - ledCtl.png

Pressing the buttons on the page should change the state of the LEDs on the BeagleBone!


Next Article

In the next article, we are going to get MySQL up and running on the BeagleBone.  We will use MySQL as a convenient place to store the temperature measurements that we take.  This will also make it easy to retrieve the data when the user requests historical temperature information through our web page.


In this series, we are going to turn our BeagleBone into a web server.  Then we are going to use that web server to monitor the temperature in a room.  To do this, we are going to leverage a couple of common open source programs.  We are going to use lighttpd as our web server.  Then we are going to integrate in PHP to handle the required server side logic.  We will also use a MySQL database to store the temperature measurements so that we can display historical information.  To gather the temperature measurements, we will use C to read a BeagleBone GPIO port.  Finally, we will use Javascript to give the user a nice interface to work with.


The technologies that we are going to us in this tutorial are very powerful and this is just meant as a starting point to demonstrate how the technologies can be used together on a BeagleBone.  Trust me, this is just the tip of the iceberg.


Install Lighttpd

Now before we install any new software, it is a good idea to update opkg:


opkg update


To install Lighttpd, type:


opkg install lighttpd lighttpd-module-fastcgi


Note, this will display a message about the job failing.  This is because port 80 is already in use.


Disable Preloaded Services

The BeagleBone comes with a bunch of preloaded services.  This this makes it really easy to get started, but the preloaded services use port 80, and that is exactly the one that we want to use.  So, we need to disable them, so that we can run on that port. Also, we disable a few extras in order to free up some memory on the BeagleBone.  Here’s how to disable the services (and a link to what the services that you are disabling do, in case you are interested):


For BeagleBone:

systemctl disable cloud9.service

systemctl disable gateone.service

systemctl disable bone101.service

systemctl disable avahi-daemon.service

systemctl disable gdm.service


For BeagleBone Black:

systemctl disable cloud9.service

systemctl disable gateone.service

systemctl disable bonescript.service

systemctl disable bonescript.socket

systemctl disable bonescript-autorun.service

systemctl disable avahi-daemon.service

systemctl disable gdm.service

systemctl disable mpd.service


BeagleBone - disable.png

Excellent, now that the services are disabled, we need to reboot and the services will be no longer started:


shutdown -r now



It may seem more logical to disable the services first, and then install Lighttpd.  However, this didn’t seem to work for me.  It would hang on the “configuring lighttpd…” step. Doing the installation first seemed to work much better.


Now, let’s test to make sure that Lighttpd installed correctly.  To do this we need to figure out the IP Address of the BeagleBone:


ifconfig -a

BeagleBone - IP Address.png

Now on another computer on your network (anything but the BeagleBone), point a web browser to that IP Address, and you should see a very reassuring message:

BeagleBone - lighttpd test.png


Install PHP

Next, we need to install PHP.  To do that type:


opkg install php php-cgi php-cli


Now we need to configure Lighttpd to use PHP.  To do this, we need to edit the lighttpd.conf config file.  However, before we do this, we need to gather a little bit of information. We need to find out where php-cgi was installed:


which php-cgi


Then we need to edit the Lighttpd config file:


vi /etc/lighttpd.conf


And we need to do two things.  First, we need to uncomment “mod_fastcgi”, which was at line 24 for me:

BeagleBone - server modules.png

Then we need to uncomment the fastcgi configuration.  Here we will also need to configure the “bin-path” to point to the location of php-cgi that we found earlier.

BeagleBone - fastcgi.png

To complete the configuration, we need to restart Lighttpd, so that the configuration file will be read in:


/etc/init.d/lighttpd restart

BeagleBone - lighttpd restart.png

Finally, to test that the web server is working correctly, we are going to create a simple web page:


vi /www/pages/test.php


And type in the following code:







<?php print(“PHP is working on the BeagleBone!”); ?>




To view the web page, go back to the web browser that you used earlier and type in:


<IP Address>/test.php

BeagleBone - php test.png




Next Article

In the next article, we are going to use the web server to display a web page that lets you turn the LEDs on the BeagleBone on and off.  Once we have accomplished that, then we will move on to incorporating a MySQL database and a temperature sensor.


One of my good friends and I were at the local climbing gym staring at a moon board, when we (and by we, I mean he) had a great idea.  What if the climbing holds were lit up by LEDs to indicate which ones were fair game? This would eliminate the need to memorize where the hold was and what it looked like.  This way when you were climbing, and holding onto the wall with everything that you had, you didn’t need to fumble around for where to go next. It would be very obvious because it would be lit up.


The more we started talking about this the more that we thought about making clear holds, and lighting up the entire hold.  (As opposed to putting a light above/below the hold.)  Even better, you could climb at night, so that the holds would jump out at you.  Then it would be impossible to “mistakenly” grab the wrong hold.


When I got home, I found out that someone had already patented the idea of illuminated rock climbing holds, which is good news because that means that it could one day be a reality.



So, I set about to build a way to use the BeagleBone to light up a sequence of LEDs to show the route to go up the wall.  To do this, I followed this great tutorial on how to use a 74HC595 shift register.  The tutorial was written for the arduino, but the circuit diagrams are easily transferrable – all that changes is what GPIO ports to connect to.


The code is a bit different though.  I was unable to find an analogous function for shiftOut, which seemed to be the heart of the program.  After a couple of attempts to write my own, I decided to just hard code the routes into the program and include an easy, medium and hard route.  Here are what the three routes look like:


IMG_5444 (849x1280).jpgIMG_5445 (597x1280).jpgIMG_5446 (606x1280).jpg


Here’s a quick video of the step up:


To choose between the routes, there is a switch statement:


loop = function() {

digitalWrite(latchPin, LOW);


route = 1;




case 1:



case 2:



case 3:





digitalWrite(latchPin, HIGH);



At some point I’m hoping to improve it and have an up/down selector and a small multi-segment LED to display which route you’ve selected.  The full code is attached, in case you were wondering how it was done.


Final Thoughts

I was pretty excited to use the cloud9 IDE it looked really nice and seemed like it was going to make programming a breeze.  Unfortunately, that was not the case.  I ran into two problems.


First, I could only get the program to run once through the debugger.  After that the BeagleBone seemed to be unresponsive.  In order to get it to run again, I had to restart the BeagleBone.  Not sure what the problem was, but this made it very difficult to debug.  I quickly scrapped this method and ended up just writing the code in cloud9 and running the program through PuTTY.  Not ideal, but it was certainly better than restarting every time.


Second, the cloud9’s inability to properly flag errors was annoying.  It seemed to claim that every line was in error, but it would run just fine. For someone who doesn’t know javascript very well, this made it pretty difficult to try to figure out whether there was a problem in the code or not.  I also had problems figuring out what commands were built into bonescript.


Overall, not the smoothest project, but it seemed to work in the end.

Installing Software

Connecting to the BeagleBone board is pretty easy, here’s the quick run down of how to do it:


1) Download and install the driver:


32 bit

64 bit


2) Download and install putty:





Now that you have all of the necessary software installed, you need to figure connect to the board. To do this, open device manager. I always forget where it is, so I think the easiest way to get to it is just to search for it:


Start -> Search Text Box : “Device Manager”


Once in the device manager, expand the “Ports (COM & LPT)” section.  This is where the BeagleBone will show up once it is plugged in.


Now plug in the BeagleBone. The “Ports (COM & LPT)” section should update and the BeagleBone board should show up there.  For me it was difficult figuring out which one it was, so I had to watch the list pretty closely.


The important part is what COM port it was assigned.  Once you know this open up PuTTY and:


Change the “Connection Type” to “Serial”

Set the “Serial Line” to COM<X> where <X> is the number that you found in the Device Manager.

Set the “Speed” to 115200

Click “Open”




I don’t know why, but mine comes up blank and I have to hit enter before it does anything.  Once I hit enter, it prompts me for a “beaglebone login”, which is “root”.




At this point you should be up and running with your BeagleBone.


Now that we are connected to the BeagleBone through the USB connection, we want to be able to connect to it through Ethernet.  To do this, we first need to figure out its IP Address, which can be obtained through the command:


Ifconfig -a




Then take the eth0 IP address and type that into Firefox or Chrome.  That should land you on a BeagleBoard 101 page.




Blink an LED

Create a circuit like the one shown here:




Now that we have the circuit built, we need to run a program that blinks the LED.  Fortunately, an example comes built in with the BeagleBone board.  To access it, fire up Cloud9, which is their built in Integrated Development Environment (IDE).  To do this, go to <IP_Address>:3000 in your browser:




Once you have the browser up, double click blinkled.js.  This is a simple program that blinks an LED.  To run the program, just click the green play button at the top, next to the word “debug”.


Setting up the BeagleBone is really easy.  In a couple of minutes, we went from opening up the box to running a program that blinks an LED.  Not bad at all.