<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>codetorment &#187; php</title>
	<atom:link href="http://www.codetorment.com/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.codetorment.com</link>
	<description>code, tech, random stuff</description>
	<lastBuildDate>Tue, 04 May 2010 21:04:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=737</generator>
		<item>
		<title>Arduino temperature data logger</title>
		<link>http://www.codetorment.com/2009/11/12/arduino-temperature-and-light-data-logging-and-chartplotting-webmonitor/</link>
		<comments>http://www.codetorment.com/2009/11/12/arduino-temperature-and-light-data-logging-and-chartplotting-webmonitor/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 16:27:09 +0000</pubDate>
		<dc:creator>tom</dc:creator>
				<category><![CDATA[Arduino]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Hardware]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[chart]]></category>
		<category><![CDATA[ethernet]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[log]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.codetorment.com/?p=672</guid>
		<description><![CDATA[An arduino, a DB18S20 one-wire temperature sensor and an LDR (Light Dependent Resistor) are hooked up with some resistors and an ethernet shield to make a datalogger and webmonitor. Notes : for this setup the connections are made on the ethernet shield instead of directly on the arduino. Since Fritzing misses a library with external [...]]]></description>
			<content:encoded><![CDATA[<p>An arduino, a DB18S20 one-wire temperature sensor and an LDR (<em>Light Dependent Resistor</em>) are hooked up with some resistors and an ethernet shield to make a datalogger and webmonitor.</p>
<p><a href="http://www.codetorment.com/wp-content/uploads/DSCN9593-1.JPG"><img class="size-full wp-image-718 alignnone" title="DSCN9593-1" src="http://www.codetorment.com/wp-content/uploads/DSCN9593-1.JPG" alt=" Arduino temperature data logger" width="448" height="335" /></a></p>
<p><span id="more-672"></span>Notes :</p>
<ul>
<li>for this setup the connections are made on the ethernet shield instead of directly on the arduino. Since <a title="Fritzing" href="http://fritzing.org/" target="_blank">Fritzing</a> misses a library with external shield I used the arduino, the pinout stays the same either way.</li>
<li>check the <a title="DS18B20 datasheet" href="http://www.google.be/url?sa=t&amp;source=web&amp;ct=res&amp;cd=1&amp;ved=0CAsQFjAA&amp;url=http%3A%2F%2Fdatasheets.maxim-ic.com%2Fen%2Fds%2FDS18B20.pdf&amp;rct=j&amp;q=ds18b20+datasheet&amp;ei=pSr8SqLvOtTX-Qaf5pSIAg&amp;usg=AFQjCNEA19aScsvJEYz5A_daB2kpye2SiA" target="_blank">DS18B20 datasheet </a>for the specifications on hooking up the sensor in parasite or powered mode</li>
</ul>
<p>Schematics :</p>
<p><a href="http://www.codetorment.com/wp-content/uploads/temp_light_monitor_tiny_bb.png"><img class="alignnone size-full wp-image-712" title="Arduino DS18B20 temperature sensor and LDR schematics" src="http://www.codetorment.com/wp-content/uploads/temp_light_monitor_tiny_bb.png" alt="Arduino DS18B20 temperature sensor and LDR schematics" width="526" height="246" /></a></p>
<p>The arduino reads the sensors every 10 seconds and passes the data to a php script on your website; which then stores the data in a text file. A second script generates a line chart of the collected data.</p>
<div id="attachment_729" class="wp-caption alignnone" style="width: 458px"><a href="http://www.codetorment.com/wp-content/uploads/tempgraph.php.png"><img class="size-full wp-image-729   " title="tempgraph.php" src="http://www.codetorment.com/wp-content/uploads/tempgraph.php.png" alt="22 hours of temperature data" width="448" height="233" /></a><p class="wp-caption-text">22 hours of temperature data</p></div>
<p>I started from <a title="Cyberspice's blog" href="http://www.cyberspice.org.uk/blog/2009/10/29/boarduino-vivarium-temperature-monitor/" target="_blank">Cyberspice&#8217;s</a> code and changed the arduino code to make use of the DB18S20 and the ethernet shield.</p>
<p>A variable was added to the upload php script in order to store the light intensity in addition to the temperature.</p>
<p>The graphing script was altered to also display the minimum temperature, the maximum temperature, the current temperature and the average temperature. A raster was added for a better interpretation of the plotted data and a green line is showing the average temperature  troughout the chart.</p>
<p>You need to alter your ip, domain and path as I explained in the post <a title="Arduino wireless motion detector" href="http://www.codetorment.com/2009/10/25/arduino-wireless-motion-detector-part-2/" target="_self">Arduino Wireless motion detector</a> so I won&#8217;t go into those details here.</p>
<p>The arduino sketch :</p>
<pre class="brush: cpp;">
#include &lt;OneWire.h&gt;
#include &lt;string.h&gt;
#include &lt;Ethernet.h&gt;

int count = 0;
OneWire ds(8);
int HighByte, LowByte, TReading, SignBit, Tc_100, Tf_100, Whole, Fract;
int Tcount = 1;
int W[6];
int F[6];
int photocellPin = 0;     // the cell and 10K pulldown are connected to a0
int light;     // the analog reading from the sensor divider

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = {
  192, 168, 1, 36};
byte server[] = { 77, 222, 78, 32};
// String buffer
char buffer[256];

Client client(server, 80);

void setup()
{
  Ethernet.begin(mac, ip);
  Serial.begin(9600);

  delay(1000);

  // Serial.println(&quot;connecting...&quot;);

}

void loop()
{
  byte i;
  byte present = 0;
  byte data[12];
  byte addr[8];

  if ( !ds.search(addr)) {
    ds.reset_search();
    return;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44,1);         // start conversion, with parasite power on at the end

  delay(1000);            

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  light = analogRead(photocellPin);
  Serial.print(&quot;light intensity = &quot;);
  Serial.print(light);
  Serial.print(&quot;\n&quot;);
  for ( i = 0; i &lt; 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
  }

  LowByte = data[0];
  HighByte = data[1];
  TReading = (HighByte &lt;&lt; 8) + LowByte;
  SignBit = TReading &amp; 0x8000;  // test most sig bit
  if (SignBit) // negative
  {
    TReading = (TReading ^ 0xffff) + 1; // 2's comp
  }
  Tc_100 = (6 * TReading) + TReading / 4;    // multiply by (100 * 0.0625) or 6.25

  Whole = Tc_100 / 100;  // separate off the whole and fractional portions
  Fract = Tc_100 % 100;

  if (SignBit) // If its negative
  {
    Serial.print(&quot;-&quot;);
  }
  Serial.print(Whole);
  Serial.print(&quot;.&quot;);
  if (Fract &lt; 10)
  {
    Serial.print(&quot;0&quot;);
  }
  Serial.print(Fract);
  Serial.print(&quot; C\n&quot;);

  if (client.connect()) {
    Serial.println(&quot;connected&quot;);
 sprintf(buffer, &quot;HEAD /path/to/script/newtemp.php?count=%d&amp;temp=%d.%d&amp;light=%d HTTP/1.1&quot;, Tcount, Whole, Fract, photocell);
 client.println(buffer);
 client.println(&quot;Host: yourdomain.com&quot;);
 client.println(&quot;Connection: close&quot;);
 client.println();
 client.stop();
 Tcount++;
 }
 else {
 Serial.println(&quot;connection failed&quot;);
 }
 delay(60000);  // wait 1 minute before sending new data
}
</pre>
<p>The upload script  &#8216;newtemp.php&#8217; :</p>
<pre class="brush: php;">
&lt;?php

if ($_SERVER['REQUEST_METHOD'] == 'HEAD') {

	$fields = explode(&quot;&amp;&quot;, $_SERVER['QUERY_STRING']);
	$values = array();

	foreach ($fields as $field) {
		$keyval = explode(&quot;=&quot;, $field);
		$values[$keyval[0]] = $keyval[1];
	}

	$file = fopen('./tempdata.txt','a+');
	if ($file) {
		fwrite($file, time() . ':' . $values['count'] . ':' . $values['temp'] . ':' . $values['light']);
		fwrite($file, &quot;\n&quot;);
		fclose($file);
	}
}

?&gt;
</pre>
<p>The graphing script &#8216;tempgraph.php&#8217; :</p>
<pre class="brush: php;">
&lt;?php

define('WIDTH', 1000);
define('HEIGHT', 520);
define('FONT', 1);
 define('FONT2',2);

// Get the temperature data
$data = array();
$file = fopen(&quot;./tempdata.txt&quot;,&quot;r&quot;);
if ($file) {
	while (!feof($file)) {
		$line = trim(fgets($file));
		if (strlen($line)) {
			$fields = explode(&quot;:&quot;, $line);
			$keyval = array();
			$keyval['time']        = $fields[0];
			$keyval['count']       = $fields[1];
			$keyval['temperature'] = $fields[2];
			$keyval['light'] 	   = $fields[3];
			$data[] = $keyval;
		}
	}

	fclose($file);
}

// Get the number of data points
$datapoints = count($data);

// Lines are chronological
$mintime = $data[0]['time'];
$maxtime = $data[$datapoints - 1]['time'];

// Temperatures need to be processed.
$mintemp = $data[0]['temperature'];
$maxtemp = $data[0]['temperature'];

foreach ($data as $datapoint) {
	$mintemp = $mintemp &lt; $datapoint['temperature'] ?
	           $mintemp : $datapoint['temperature'];
	$maxtemp = $maxtemp &gt; $datapoint['temperature'] ?
	           $maxtemp : $datapoint['temperature'];
	$avgtemp += $datapoint['temperature'];
	$curtemp = $datapoint['temperature'];
}
 $avgtemp = round(($avgtemp / $datapoints),2);

// Get the axis dimensions.  Round up and down to the nearest
// degree C and hour.
$lowtime  = intval($mintime / 3600) * 3600;
$hightime = (intval($maxtime / 3600) + 1) * 3600;
$difftime = $hightime - $lowtime;

$lowtemp  = intval($mintemp);
$hightemp = intval($maxtemp) + 1;
$difftemp = $hightemp - $lowtemp;

// Create the image
$image = imagecreate(WIDTH, HEIGHT);
if ($image) {
	$background = imagecolorallocate($image, 255, 255, 255);
	$black      = imagecolorallocate($image, 0, 0, 0);
	$red        = imagecolorallocate($image, 255, 0, 0);
	$blue       = imagecolorallocate($image, 0, 0, 255);
	$green		= imagecolorallocate($image, 0, 204, 5);
	$grey		= imagecolorallocate($image, 210,210,210);

	// Draw the axes
	imageline($image, 20, 20, 20, 485, $black);
	imageline($image, 15, 480, 980, 480, $black);
	imageline($image, 15, 20, 20, 20, $black);
	imageline($image, 980, 480, 980, 485, $black);

	// Draw top horizontal line
	imageline($image, 20, 20, 980, 20, $grey);

	// Draw right most vertical line
	imageline($image, 980, 20, 980, 479, $grey);

	for ($i = 3600; $i &lt; $difftime; $i += 3600) {
		$x = 20 + (($i * 960) / $difftime);
		// Draw ticks on horizontal axis
		imageline($image, $x, 480, $x, 483, $black);
		// Draw horizontal guides
		imageline($image, $x, 479, $x, 20, $grey);
	}
	$temp = intval($lowtemp);
	for ($i = 1; $i &lt; $difftemp; $i++) {
	    $y = 480 - (($i * 460) / $difftemp);
		// Draw ticks on vertical axis
		imageline($image, 17, $y, 20, $y, $black);

		// Draw vertical guides
		imageline($image, 21, $y, 980, $y, $grey);
		$temp = intval($temp) + 1;
		$ytemp = intval($y) - 5;
		//if($temp % 2 == 0){
			imagestring($image, FONT, 0, $ytemp, $temp . 'C', $black);
		//}
	}

	// Draw the labels
	imagestring($image, FONT, 8, 490, date(&quot;H:i&quot;, $lowtime), $black);
	imagestring($image, FONT, 970, 490, date(&quot;H:i&quot;, $hightime), $black);
	imagestring($image, FONT, 0, 475, $lowtemp . 'C', $black);
	imagestring($image, FONT, 0, 15, $hightemp . 'C', $black);

	// Draw min, max and avg
	imagestring($image, FONT2, 700, 430, &quot;Cur. temp : &quot; . $curtemp . &quot; °C&quot;,$black);
	imagestring($image, FONT2, 700, 450, &quot;Avg. temp : &quot; . $avgtemp . &quot; °C&quot;,$green);
	imagestring($image, FONT2, 850, 430, &quot;Min. temp : &quot; . $mintemp . &quot; °C&quot;,$blue);
	imagestring($image, FONT2, 850, 450, &quot;Max. temp : &quot; . $maxtemp . &quot; °C&quot;,$red);

	// Draw avg line

	$avgtemp = 480 - ((($avgtemp - $lowtemp) * 460) / $difftemp);
	imageline($image,20, $avgtemp, 980, $avgtemp, $green);

	// Draw the temperature points

	// Position of the first point
	$prevx = (($data[0]['time'] - $lowtime) * 960) / $difftime;
	$prevy = (($data[0]['temperature'] - $lowtemp) * 460) / $difftemp;

	// Draw line from previous point to current point
	for ($i = 1; $i &lt; $datapoints; $i++) {
		$x = (($data[$i]['time'] - $lowtime) * 960) / $difftime;
		$y = (($data[$i]['temperature'] - $lowtemp) * 460) / $difftemp;
		imageline($image, $prevx + 20, 480 - $prevy, $x + 20, 480 - $y, $red);
		$prevx = $x;
		$prevy = $y;
	}

	// Finally time and date stamp
	$generated = 'Generated: ' . date(&quot;r&quot;);
	imagestring($image,
	            FONT,
	            WIDTH - 15 - (imagefontwidth(FONT) * strlen($generated)),
	            HEIGHT - 15,
	            $generated,
	            $blue);

	// Output the image
	header('Content-Type: image/png');
	imagepng($image);

	// Destroy it
	imagedestroy($image);
}

?&gt;
</pre>
<p>I will soon post some improvements on the scripts :</p>
<ul>
<li>averaging 6 readings ( 1 minute ) to 1 datapoint to get rid of the noise</li>
<li>let the script fill one text file for each day, so you can look at a history over several days</li>
<li>split up data into different charts</li>
<li>last but not least, trying to add the S65 in the game : showing the current sensor readings or a graph</li>
</ul>
<p><a href="http://www.codetorment.com/wp-content/uploads/DSCN9596.JPG"><img class="alignnone size-full wp-image-786" title="DSCN9596" src="http://www.codetorment.com/wp-content/uploads/DSCN9596.JPG" alt=" Arduino temperature data logger" width="454" height="341" /></a></p>
<p>Please leave a comment or send me a link to show your arduino projects!</p>
<p><a title="Home" href="http://www.codetorment.com/" target="_self">Back to homepage</a></p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://www.codetorment.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.codetorment.com/2009/11/12/arduino-temperature-and-light-data-logging-and-chartplotting-webmonitor/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Arduino wireless motion detector : part 3</title>
		<link>http://www.codetorment.com/2009/11/07/arduino-wireless-motion-detector-part-3/</link>
		<comments>http://www.codetorment.com/2009/11/07/arduino-wireless-motion-detector-part-3/#comments</comments>
		<pubDate>Sat, 07 Nov 2009 16:43:24 +0000</pubDate>
		<dc:creator>tom</dc:creator>
				<category><![CDATA[Arduino]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[ethernet]]></category>
		<category><![CDATA[motion]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[rf-transmitter]]></category>
		<category><![CDATA[shield]]></category>
		<category><![CDATA[wireless]]></category>

		<guid isPermaLink="false">http://www.codetorment.com/?p=394</guid>
		<description><![CDATA[In this third and final part I&#8217;ll show you how to get the arduino to access a website using an ethernet shield and php. The data can then be displayed in a number of ways. Here the data is simply printed one line at a time. Each time motion is detected, the networked arduino connects [...]]]></description>
			<content:encoded><![CDATA[<p><strong>In this third and final part I&#8217;ll show you how to get the arduino to access a website using an ethernet shield and php. The data can then be displayed in a number of ways. Here the data is simply printed one line at a time.</strong></p>
<p>Each time motion is detected, the networked arduino connects to the web and executes a php script which writes the time and date of the event to a text file. When you want to check if motion was detected, acces a different php script which displays all (if any) recorded events.</p>
<p>Check my next post to see how to send sensor data from the arduino to a website using php.</p>
<p>If you followed<a title="part 1" href="http://www.codetorment.com/2009/10/25/arduino-wireless-motion-detector/" target="_blank"> part 1</a> and <a title="part 2" href="http://www.codetorment.com/2009/10/25/arduino-wireless-motion-detector-part-2/" target="_blank">part 2</a> all you need to do for part 3 is change the code of the receiving arduino since we&#8217;re only changing the output from &#8216;blink a led&#8217; to &#8216;access a website&#8217;.<span id="more-394"></span></p>
<p>Sketch :</p>
<pre class="brush: cpp;">
#include &lt;Ethernet.h&gt;

int ledPin = 13;    // pin for the LED
int RFinPin = 8;    // pin for the RF receiver
int val = 0;         // variable for reading the pin status
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };    // unique mac address
byte ip[] = { 192, 168, 1, 36};        // unique and valid ip for your network
byte server[] = { 77, 222, 78, 32};  // ip google

void setup() {
   Ethernet.begin(mac, ip);
   pinMode(ledPin, OUTPUT);    // declare LED as output
   pinMode(RFinPin, INPUT);    // declare RF receiver as input
   Serial.begin(9600);
   delay(1000);
}

Client client(server, 80);

void loop(){
   val = digitalRead(RFinPin);        // read input value
   if (val == HIGH) {
     digitalWrite(ledPin, HIGH);      // turn LED ON
     if (client.connect()) {
       Serial.println(&quot;connected&quot;);
       client.println( &quot;GET /folder/movement.php HTTP/1.1&quot;);
       client.println(&quot;Host: yourdomain.com&quot;);
       client.println(&quot;Connection: close&quot;);
       client.println();
       client.stop();
     } else {
       Serial.println(&quot;connection failed&quot;);
     }
   } else {
     digitalWrite(ledPin, LOW);       // turn LED OFF
   }
   delay(5000);
}
</pre>
<p>The script movement.php is executed when the arduino connects to <em>www.yourdomain.com/folder/movement.php</em></p>
<p>movement.php code :</p>
<pre class="brush: php;">
&lt;?php

$myFile = &quot;movement_data.txt&quot;;
$fh = fopen($myFile, 'a') or die(&quot;can't open file&quot;);
$stringData = date(&quot;D, d M Y H:i:s&quot;) . &quot;\n&quot;;
fwrite($fh, $stringData);

fclose($fh);

?&gt;</pre>
<p>The script display_movement.php takes the movement data and prints one line for every event recorded.</p>
<p>display_movement.php code:</p>
<pre class="brush: php;">
&lt;?php

 $fileName = &quot;movement_data.txt&quot;;

 if(file_exists($fileName)){
      $file = fopen($fileName,'r');

      while(!feof($file)){
                $name = fgets($file);
                if($name != NULL){
                echo('&lt;br&gt;'. &quot;Movement registered on : &quot;.$name.'&lt;/br&gt;');
			}
        }

        fclose($file);
}
?&gt;
</pre>
<p>When display_movement.php is executed you should see something like :</p>
<p><a href="http://www.codetorment.com/wp-content/uploads/movement.png"><img class="alignnone size-full wp-image-621" title="movement" src="http://www.codetorment.com/wp-content/uploads/movement.png" alt="movement Arduino wireless motion detector : part 3" width="380" height="128" /></a></p>
<p>In the next post I&#8217;ll discuss how to write sensor data (light intensity, temperature,&#8230;) to a website and plot a line chart using php.</p>
<p><a title="Home" href="http://www.codetorment.com/" target="_self">Back to homepage</a></p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://www.codetorment.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.codetorment.com/2009/11/07/arduino-wireless-motion-detector-part-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
