Arduino and BMP085

The BMP085 is a barometric and temperature sensor. I’ve got one on a breakout board from geeetech. Using this and an arduino, it is possible to build an electronic barometer.

It can be connected to an arduino uno or nano:

BMP – Arduino
VCC – 3.3V
SCL – A5
SDA – A4

The sketch is originally written by Jim Lindblom at SparkFun Electronics, I updated it slightly to be able to use a more up to date wire library. BMP085.

This will report the temperature and barometric pressure (in Pascal) on the serial port. It is also possible to combine this with a DHT11 (or DHT21 / DHT22) sensor to also get a humidity reading. See The DHT has to be connected to +5 and gnd, signal to port D2 on the arduino. The DHT library can be downloaded from

Arduino nano, DHT11 temperature and humidity sensor,BMP085 temperature and pressure sensor.

Arduino nano, DHT11 temperature and humidity sensor (blue – at top),BMP085 temperature and pressure sensor (red – at bottom).

This work has been done in Arduino 1.0.1 on a debian system.

Posted in arduino | Comments Off on Arduino and BMP085

Reading temperature data out of postgres

I have set up a system logging temperatures (and later hopefully also other parameters) to a postgres database. The data are now read out and presented as an svg-graph. (this may not work in some older browsers, i.e. msie< 9 - it is possible to use svgweb, but I have presently not implemented this)

The temperature data may be presented as a svg graph.

Temperature graph. The number in the lower left corner is number of data points in the graph.

The source code for the system is available at my github account. The version presented here, is at tag passive_plot – in the last version it is possible to read out data, clicking in the chart. Later it will also be shown how to put more charts on one web page.

Why not just use cosm? Well, in fact I am uploading my data to cosm (in fact the intermediate json format used in this project is compatible with cosm), but on one side, I like to have control and know that I know where and in which format my data are, I also do not like the ways it is possible to present data on cosm (e.g. if a long time series is presented,points are thrown away, which may be strongly misleading if a point with a (local) minimum or maxima is removed – that happens quite often)

Posted in arduino | 2 Comments

Storing temperature data in postgresql

An arduino board is running as a web server serving temperatures read out from some DS18B20 sensors. The data are stored in a postgresql database. The data table has been defined as:

create table temps(
   id serial primary key,
   termid integer,
   temp double presicion not null,
   sensoraddr character varying(20),
   datetime  timestamp with time zone default now()

A php-script is set upp to poll the arduino and fetch data. It sends data as json, described here.

$server=""; // Must be set up to match the arduino's IP.
$pgserver='localhost';   // postgres server
$username='.....'; // postgres user name
$password='.....'; // postgres password
    $dbh = new PDO($connectstring, $username, $password);
      $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  catch(PDOException $e){
    exit( "

Cannot connect - $message

$fp = fsockopen($server, 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)
} else {
    $out = "GET /json HTTP/1.1\r\n";
    $out .= "Host: $server\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    while (!feof($fp)) {
        $data .= fgets($fp, 128);
$data=split("\n",$data); // cuts of the headers
$sql="insert into temps(temp,sensoraddr)values(?,?)";

This can be trigged from some event, or it may be run periodically. To make it run once every 15 minutes, save the php script as ‘fetchtemp.php’ and make the following shell-script in the same directory:

while true; do
php fetchtemp.php
sleep 900

(or call it from cron or any other scheduler)

I have also a system for presenting the data as a svg-graph.

Posted in arduino, php, sql | 2 Comments

Arduino and infrared reflective sensor

Testing a infrared reflective sensor module.

I set it up with an arduino board, running the following sketch:

int sensorPin = 10;
int value = 0;
int prevval =0;
int count=0;
void setup() {
void loop() {
 value = digitalRead(sensorPin);
 if(value==0 && prevval==1){ // something is dected
 Serial.print("   ");
 Serial.println(value, DEC);

To run this, connect dout on the sensor to digital pin 10 on the arduino, connect + on the sensor to 5V and – to ground.
When the infrared light is reflected back to the detector, the output goes low. The sensitivity can be adjusted using the trim pot, turning it counter-clockwise lowers the sensitivity, i.e. what passes in front must come closer or be more reflective. In addition to watching the serial monitor for changes, there is a led that lights up when something is detected.

To lower the sensitivity, turn ccw, turn cw to increase the sensitivity

Adjustments of the sensor

The sensor module is marked “” and “LOGO-sensor Var1.5”.

Posted in arduino | Comments Off on Arduino and infrared reflective sensor

Store data from temperature server in couchdb

I am setting up a quick and dirty couchdb database to store data from an arduino temperature server running on (only visible on my local network)

All the code below is run under bash 4.2 on the debian system where the database resides.

The db is called arduino and is created by

curl -X PUT

Pulling out the data:


Storing it in the database:

curl -X POST http://localhost:5984/arduino -H 'Content-Type: application/json' -d <jsonstring>

This can be linked together:

GET | curl -X POST http://localhost:5984/arduino -H Content-Type: application/json' -d @-

Note the last @- that makes curl read from standard input.

What we miss now is the timestamp. We can use sed to insert a timestamp in the json string:

sed -e "s/\"mil/\"time\":\"$dte\",\"mil/"

Will insert the string “time”: and the content of the variable $dte just before the “millis” in the json.

export dte=`date +"%F %T %z"`
GET | sed -e "s/\"mil/\"time\":\"$dte\",\"mil/" | curl -X POST http://localhost:5984/arduino -H 'Content-Type: application/json' -d @-

And to make it run each 2nd minute put it all into a file:

while true; do
export dte=`date +"%F %T %z"`
GET | sed -e "s/\"mil/\"time\":\"$dte\",\"mil/" | curl -X POST http://localhost:5984/arduino -H 'Content-Type: application/json' -d @-
sleep 120

and run this with a nohup

To keep an eye on what goes in:

id=`tail -n1 nohup.out | awk -F'[,:\"]' '{ print $9 }'`;curl -X GET http://localhost:5984/arduino/$id

In the longer run, I am pretty sure these data should be stored in postgres – but for the first run testing, couchdb works fine. (Although, I could have rewritten the server to return sql-strings and run them through psql.)

Posted in arduino | 1 Comment

Arduino – temperature webserver

I am using an arduino uno, an ENC28J60 ethernet module and a few DS 18B20 temperature sensors. Presently, it seems to be possible to connect up to 7 sensors (although I have only tested with 3) by optimizing the code a bit for memory usage, it should be possible to add some more sensors. It should not be too hard to reuse much of this to use DHT11 or DHT22 sensors, but as far as I have understood, it is not possible to run more of those on one bus.

The temperatures may be read out in a browser or sent of as a json-string. The json-string also includes the sensors ids and a millisecond time stamp.

The web page is pretty simple

The web page as served from the arduino is pretty simple, Sensor 0 and 1 are measuring temperatures directly at my working desk, sensor 2 is just outside the window.

This is just a small part of what I hope will grow up to be a house monitoring system, adding on, among other things, devices for energy usage monitoring. I am planning to store the information in an sql database, but for the first stage testing, I am polling the server and storing the results in a couchdb.

The sketch can be found here:
Version 1.0 2nd feb 2013 or at github. It runs well on an arduino uno, but it is close to the limit of RAM usage. Just by adding a bit more text-output, the sketch will hang. If you want to add something, look through the sketch and see what can be removed (I have some serial debug logging and depending on the needs, it may be possible to remove either the part that serves html or the part that serves json.)

If using a newer ide than v 1.0, have a look at my description how to use the ENC 28J60.

Setup of the system

Two of the 18B20s can be seen. The gutted tp-cable runs to an outdoor one. (The Arduini Nano at the back end of the bread board is not in use in this project)

The data may also be forwarded to cosm (formerly known as Pachube). To get the data into the right format, make cosm call the cosm_uploader that further back talks to the arduino. (cosm_uploader at github).

The last five days outdoor temperatures at my place (More data can bee seen at feed 102668.)

Posted in arduino, Diverse | 2 Comments

ENC 28J60 ethernet module with arduino

I recently bought an ENC 28J60 module from geeetech. They offered a download for drivers and examples for arduino, but it turned out there were two grave snags:

My debian system had gcc-avr v 4.7.x, there are some resent changes that means that some of the arduino code does not compile. I was told that:

/usr/share/arduino/libraries/EtherCard/tcpip.cpp:459:20: error: variable 'c' must be const in order to be put into read-only section by means of '__attribute__((progmem))'

I don’t care if it is an error in the compiler or in the arduino system (as it was discussed on some lists), to get it to work, I just downgraded the compiler to version 4.3.5-1 (if you are using another system, you must download it from somewhere else). Then I installed it with sudo dpkg –install <package>. avr-libc should be dowgraded to 1.6.8 (the compiler worked without downgrading the libc, but that made further upgrades of the system impossible). To make those downgrades survive later system upgrades, pin them in /etc/apt/preferences.d/avr which should contain

Package: avr-libc
Pin: version 1.6.8*
Pin-Priority: 1001

Package: gcc-avr
Pin: version 4.3.5*
Pin-Priority: 1001

It also turned out that the code from geeetech was pre v 1.0 of the arduino SDK. Editing some code and adding in the WConstants.h and wiring.c and wiring.h from v 0.23 of the arduino SDK, i got it all to work (at least so far).

My working library can be found here : ENC28J60.tar (132k) (git repo so my changes can be seen)

This works fine with the examples where the arduino acts as a server. I have still not managed to get it to work as a client.

ENC28J60 ethernet module connected to an arduino.The markers onthe PCB may be a tad confusing. Vcc is the leftmost connection at the closest end. (red),

ENC28J60 ethernet module connected to an arduino.The markers onthe PCB may be a tad confusing. Vcc is the leftmost connection at the closest end. (red),

I am now connecting the 28J60 to the arduino using a ribbon cable (Split an old floppy disk cable to have just 10 conductors) The connections will then be:

# Arduino pin 28J60
2 3v VCC
4 D10 CS
5 D13 SCK
6 D11 SI
7 D12 SO
8 n.c WOL
9 D2 INT
10 n.c CLKOUT
Posted in arduino, Data | 1 Comment

Brød med sesamfrø

Jeg har lenge bakt med sesamfrø, men da har jeg blandet sesamfrøene i deigen. Det smaker jo ekstra godt når sesamfrøene er litt ristet, men når jeg har strødd dem oppå, har det meste drysset av etter steking. Det viste seg at jeg måtte gå litt mer drastisk til verks. Når brødene er knadd ut, fukter jeg overflaten litt (med speltbrød er det ikke nødvendig, de er klissete nok i seg selv) og ruller brødene i sesamfrø.

De utbakte brødene blir litt fuktet og så rullet i sesamfrø.

De utbakte brødene blir litt fuktet og så rullet i sesamfrø.

Dermed sitter frøene godt gjennom heving og steking.
Ferske brød med ristede sesamfrø

Ferske brød med ristede sesamfrø

Posted in Mat | Comments Off on Brød med sesamfrø

Arduino thermometer / hygrometer

I am using an arduino uno bought in a kit with a LCD/button shield and a DHT11, both parts bougth from dealextreme, although also available from a lot of other places.

The DHT11 is connected to the arduino:
* pin 1 (signal) – digital 2
* pin 2 (Vcc) – 5v
* pin 3 (gnd) – gnd


DHT22 break out board connected to arduino uno

(The cables are taken from a discarded PC cabinet)

Then the display is put on top and the sketch is downloaded:

Complete arduiono / DHT22 termometer / hygrometer

Complete arduiono / DHT22 termometer / hygrometer


#include "DHT.h"
#include <liquidcrystal.h>
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

#define DHTPIN 2 // what pin we're connected to

// Uncomment whatever type you're using!
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT22 // DHT 22 (AM2302)
//#define DHTTYPE DHT21 // DHT 21 (AM2301)


void setup() {

void loop() {
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
float t = dht.readTemperature();

// check if returns are valid, if they are NaN (not a number) then something went wrong!
if (isnan(t) || isnan(h)) {
lcd.println("Failed to read from DHT");
} else {
lcd.print(" %");
lcd.print(" *C");

The LiquidCrystal library should come with the arduino ide, the DHT library can be downloaded from

Posted in arduino, Diverse | 1 Comment

Postgresql – handling bytea data through php

postgres 9.1 / php 5.3.10 on ubuntu.

The combination of postgres and php has not made it easy and intuitive to handle blob-data. I tried first to use the large objects, as that seemed to be the easiest way, but the bytea turned out to be the best solution – having read up a few places, I have found this to work, at least for not-too-large-files where the size “too large” has to be determined for the actual application. (a few megs should hardly ever be “too large”)

I have a table defined as

create table blobstore(
   id serial primary key,
   doc varchar,
   blob bytea);

the following php-code allows storage and reading of images in this table
NOTE: This is a “proof of concept”-script. For real use, more checking must be added.

  $dsn = 'pgsql:dbname=test;host=';
  $user = 'user';
  $password = 'password'; 
   // these variables must be set to match the actual connection
  try {
    $dbh = new PDO($dsn, $user, $password);
  } catch (PDOException $e) {
    die('Connection failed: ' . $e->getMessage());

// Stores a file:
  $filename=$_GET['file']; // Normally, the file will probably be uploaded, but that's another howto  ;-)
  $data = bin2hex(file_get_contents($filename)); // This may be a problem on too large files
    $sql="insert into blobstore (doc,blob) values('test',?)";
    $sqlh= $dbh->prepare($sql);
  catch(Exception $e){

// reads a file out of the database:
  $sql="select blob from cddoc where id=?";
  $data=$data[0][0]; // print($data) here will just return "Resource id # ..."
  header('Content-Type: image/png'); // must be adjusted accordingly for other file types, maybe filetype stored as a field in the table?
  $data=fgets($data); // The data are returned as a stream handle gulp all of it in in one go, again, this may need some serious rework for too large files 
  print(pack('H*',$data)); // reverses the bin2hex, no hex2bin in my php... ????

If this code is stored as e.g. blobtest.php, it can then be called (on a debian or ubuntu system) to store the image (when looking it up in the database it should look like \x38393530346534…)


(/usr/share/pixmaps/debian-logo.png is a file that should exist on any debian or ubuntu system, if it does not exist on your system, just modify the url to point to an image file on the system)
To have the image displayed, run

http://localhost/blobtest.php?id=1 (or whatever image you want to restore)

The latter may be used directly in a web-page as

<img src="http://localhost/blobtest.php?id=1" />
Posted in php | Comments Off on Postgresql – handling bytea data through php