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.
E.g.:{"temp":[23.00,23.50,-4.00],"address":["2852932640040","28A9D0264006D","2895D76E40050"],"millis":526288}

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
1 GND GND
2 3v VCC
3 RST RESET
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

Connection

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

sketch:

#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)

DHT dht(DHTPIN, DHTTYPE);

void setup() {
lcd.begin(16,2);
dht.begin();
}

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.setCursor(5,1);
lcd.println("Failed to read from DHT");
} else {
lcd.setCursor(5,1);
lcd.print(h);
lcd.print(" %");
lcd.setCursor(5,0);
lcd.print(t);
lcd.print(" *C");
}
}

The LiquidCrystal library should come with the arduino ide, the DHT library can be downloaded from http://playground.arduino.cc/Main/DHTLib.

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.

<?php
  $dsn = 'pgsql:dbname=test;host=127.0.0.1';
  $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());
  }
  $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Stores a file:
  if($_GET['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
  try{ 
    $sql="insert into blobstore (doc,blob) values('test',?)";
    $sqlh= $dbh->prepare($sql);
    $sqlh->execute(array($data));
  }
  catch(Exception $e){
    die($e->getMessage());
  }
  print("<p>Done</p>");

}
// reads a file out of the database:
if($_GET['id']){
  $sql="select blob from cddoc where id=?";
  $sqh=$dbh->prepare($sql);
  $sqh->execute(array($_GET['id']));
  $data=$sqh->fetchAll(PDO::FETCH_NUM);
  $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…)

http://localhost/blobtest.php?file=/usr/share/pixmaps/debian-logo.png

(/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

Eplekakevariant

En litt grov lite søt eplekake.

2 egg
120 gram sukker (snaut 1.5dl)
90 gram smør
1 dl melk eller fløte
180 gram fin sammalt spelt (eller hvete) (3 dl)
1.5 ts bakepulver
Saft av 1/4 sitron

6-7 epler (ca 700 gram)

kanel / kardemomme og eller koriander

pisk eggedosis av egg og sukker. Hell melken og legg smøret i en gryte og varm opp til smøret er smeltet og melken koker. Hell den kokende blandingen i eggedosisen. Bland sammen mel og bakepulver og rør det inn. Bland inn sitronsaft. Hell i en springform. Skjær eplene i tynne båter og stikk dem ned i røra. (Evt skjær eplene i biter og bland dem inn). Dryss over med litt sukker og kanel, kardemomme eller koriander.

Stekes ved 180-200 grader i ca 30 minutter, evt 160 grader på varmluft. Skjekk med pinne!

Det blir lett litt lutsmak av bakepulverbakst med grovt mel – sitronsaften hindrer dette. Dersom eplene er svært sure, kan sitronsaften kuttes ut.

Posted in Diverse, epler, Mat | 1 Comment

Eplepresselogg 2012

Eplepressingen er igang igjen.

29. september

6 liter juice – hovedsaklig james grieve

6. oktober

6 liter fra james grieve,
6 liter fra torstein

7. oktober

6 liter blanding (hovedsakelig james grieve)

14. okotober

6 liter fra james grieve

… to be continued …

Posted in Diverse, epler | Comments Off on Eplepresselogg 2012

Hvordan lage en flygel-kake

Jeg målte aldri kaken,men den var ca 30 cm bred, 40 cm lang og 6 cm tykk.

To lag langpannesukkerbrød. Lagt vaniljekrem i mellom og skåret til

To lag langpannesukkerbrød. Lagt oppå hverandre og skåret til

Skåret av litt av det øverste laget og lagt i mellom tykk vaniljekrem
Skåret av litt av det øverste laget og lagt i mellom tykk vaniljekrem
Dekket med sjokoladekrem
Dekket med sjokoladekrem
Svarte tangenter av lakris
Svarte tangenter av lakris (nb, bør legges på så kort tid som mulig før kaken skal på bordet,de misfarger kremen litt)

Og – som så ofte når det utvises godt kunstnerisk håndverk i familien, skal jeg ikke ta æren for utførelsen, selv om jeg vel var skyld i noen av de praktiske løsningene…

Posted in Mat | Comments Off on Hvordan lage en flygel-kake

Rikstv – paybacktime!

Jeg er ikke helt sikker på om vi er kunde i rikstv, men de driver nå og ringer fra tid til annen, jeg slenger på røret, andre i familien lar seg overtale, men sjelden har vel telefonsalg vært mer mislykket for selgeren. Noen synes det å betale x kr i måneden for flere kanaler med en gratis ny digitalmottaker på kjøpet og hjelp til oppkobling hørtes bra ut – vel jeg må vel innrømme at jeg i mange tilfeller regnes som en ikke-TV-fundamentalist.

Mottakeren kom i posten og noen dager etter kom montøren. Etter å ha svimet omkring i hagen med måleinstrumenter som en annen lisenskontrollør måtte han bite i det sure eplet, nei, her var mottakerforholdene for dårlige, vi kan faktisk ikke ta inn det vi skulle betalt for. Montøren måtte returnere med uforrettet sak og mottakeren ble returnert.

Hevnen er søt -får se om de klarer å få oss ut av systemet på en bedre måte enn sist.

Posted in Diverse | Comments Off on Rikstv – paybacktime!

R – barplot with error-bars

I have not found any simple way to make a barplot with error-bars in R, so I had to write a script for it:

errorbarplot< -function(data,error,ylab,xlab,main){
  palette(c('gray75','grey50','grey25','white'))
  mar=par()$mar
  par(xpd=T, mar=par()$mar+c(0,0,0,8)) # Makes a bit space to place the legend
  maxy=max(data+error)*1.05            # Space enough for the max error + some space
  bp<-barplot(data,beside=TRUE,ylab=ylab,xlab=xlab,main=main,ylim=c(0,maxy),col=c(1,2))
  segments(bp,data-error,bp,data+error) # Draws the vertical lines in the error plot   
  ew=(bp[2,1]-bp[1,1])/2                # Sets the width of the error bars as half the bare
  ew=ew/2
  segments(bp-ew,data-error,bp+ew,data-error)
  segments(bp-ew,data+error,bp+ew,data+error)
  legend(max(bp)+1,maxy,rownames(data),fill=c(1,2))
  par(mar=mar)                           # Resets the width of the plotmargins. 
}

This is called with a data set like: (It may of cource be produced other ways, just as long as you end up with one data matrix and one error-matrix)

rn=c('Aa','Bv','La','Pap','Sg','Vm','Ac','Ao','Af','Fr')
li=c(99.9,116.1,291.8,98.5,33.7,142.9,5.4,13.8,3.5,74.9)
sh=c(26.1,254.9,252,77.6,62.7,147.4,0,17.6,0.4,54.8)
seli=c(9.1,13.3,73.4,10.5,5.9,40.2,1.8,5,1.7,8.7)
sesh=c(7.7,84.6,54.2,4.4,11.3,17.4,0,13.7,0.2,3.8)


dimnames=list(c('Something','Something else'),rn)
data=matrix(c(li,sh),nrow=2,byrow=TRUE,dimnames=dimnames)
error=matrix(c(seli,sesh),nrow=2,byrow=TRUE,dimnames=dimnames)
ylab=expression(paste(alpha,'something'))
main='Main title'
xlab='X-label'
errorbarplot(data,error,ylab,xlab,main)

A bar plot with errorbars - made in R

Posted in R | Comments Off on R – barplot with error-bars