<?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>CMD-c &#38;&#38; CMD-v</title>
	<atom:link href="http://blog.datasingularity.com/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://blog.datasingularity.com</link>
	<description></description>
	<lastBuildDate>Tue, 31 Jan 2012 21:59:45 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Using an Arduino + acceleromter to monitor sleep</title>
		<link>http://blog.datasingularity.com/?p=700</link>
		<comments>http://blog.datasingularity.com/?p=700#comments</comments>
		<pubDate>Sun, 20 Jun 2010 16:50:30 +0000</pubDate>
		<dc:creator>benjamin</dc:creator>
				<category><![CDATA[Arduino]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Hardware]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[accelerometers]]></category>
		<category><![CDATA[boarduino]]></category>
		<category><![CDATA[sleep]]></category>
		<category><![CDATA[sparkfun]]></category>

		<guid isPermaLink="false">http://blog.datasingularity.com/?p=700</guid>
		<description><![CDATA[I have heard that a trip to a sleep doctor entails hooking up a bunch of sensors to you and they tell you things like how many times you woke up in the night. I don&#8217;t have a bunch of sweet EEG nodes, but I realized that I could easily create something that measures my [...]]]></description>
			<content:encoded><![CDATA[<p>I have heard that a trip to a sleep doctor entails hooking up a bunch of sensors to you and they tell you things like how many times you woke up in the night. I don&#8217;t have a bunch of sweet EEG nodes, but I realized that I could easily create something that measures my relative movement throughout the night. Looking at an over-arching chart would probably give me a good idea of how I was really sleeping. </p>
<h3>The Parts</h3>
<p>I am currently working on a system which involves control theory and I purchased one of <a href="http://www.sparkfun.com/commerce/product_info.php?products_id=9431">these IMUs from Sparkfun</a>.</p>
<div id="attachment_701" class="wp-caption aligncenter" style="width: 310px"><a href="http://blog.datasingularity.com/wp-content/uploads/2010/06/Picture-5.png"><img src="http://blog.datasingularity.com/wp-content/uploads/2010/06/Picture-5-300x212.png" alt="6DOF IMU" title="6DOF IMU" width="300" height="212" class="size-medium wp-image-701" /></a><p class="wp-caption-text">Sparkfun Razor 6DOF IMU</p></div>
<p>This is a 6 degree of freedom inertial measurement unit. It uses 2 gyroscopes and an accelerometer to give you information about your hardware&#8217;s orientation. I am waiting for some parts to come in so I just had it hooked up to one of my development boards just hanging out. I realized I could just use the accelerometer chip to relatively measure &#8220;how much&#8221; I was moving.</p>
<p>Accelerometers are really simple devices and they have become completely ubiquitous. If you are reading this on a mac or an iphone, then you are using one right now. A 3 axis accelerometer, such as the one on this board, can measure the orientation of the chip in relation to the earth&#8217;s magnetic field. Due to it&#8217;s sensitivity, it is also really good at measuring general vibration. </p>
<h3>The Build</h3>
<p>Hooking up to the accelerometer is pretty simple. You only need 5 pins: a 3.3V VCC and GND pin, then 3 analog pins for x, y, and z.<br />
<div id="attachment_704" class="wp-caption aligncenter" style="width: 310px"><a href="http://blog.datasingularity.com/wp-content/uploads/2010/06/CRW_1220.jpg"><img src="http://blog.datasingularity.com/wp-content/uploads/2010/06/CRW_1220-300x200.jpg" alt="Boarduino + IMU wired" title="Boarduino + IMU wired" width="300" height="200" class="size-medium wp-image-704" /></a><p class="wp-caption-text">Boarduino + IMU wired</p></div></p>
<p>Since most accelerometers run on 3.3V, you will likely need to account for that in some way if you are running your arduino at a higher voltage. The x, y, and z pins output a voltage b/w 0 and 3.3V for each axis. For instance, if you are holding the chip completely level, you may see something like 1.65V on the X pin, as you turn it towards 90 degrees, it will increase. You can measure this using analogRead(int pin); . </p>
<h3>The Code</h3>
<p>The code for this project was so simple it took me under 1 hour to write the firmware and the client software. First the Arduino code:</p>
<pre class="brush: cpp; title: ; notranslate">
#define DEBUG 0 //set to 1 for debug mode
#define AX 0 //accelerometer pin X
#define AY 1 //accelerometer pin Y
#define AZ 2 //accelerometer pin Z
#define DELAY 1000
#define SENSITIVITY 3 //movement required to send a movement event

//storage for x,y,z values
int x, y, z;
//storing the old values to compare relation movement
int old_x, old_y, old_z;
//our 'relative motion'
int movementFactor;

void setup() {
  Serial.begin(9600);
  readSensors();
  saveValues();//initialize
}

void loop() {

   readSensors();
   determineMovementFactor();

   if (movementFactor &gt; SENSITIVITY) { 

      if (DEBUG) {
         Serial.print(&quot;x = &quot;);
         Serial.print(x);
         Serial.print(&quot; | y = &quot;);
         Serial.print(y);
         Serial.print(&quot; | z = &quot;);
         Serial.print(z);
         Serial.print(&quot; | movement = &quot;);
         Serial.println(movementFactor);
      } else {
         Serial.println(movementFactor);
      }

      saveValues();
      delay(DELAY);
   }
}

/**
 * All we are doing here is finding the greatest derivative from
 * the 3 axises and choosing that as our relative movement factor
 */
void determineMovementFactor() {
   movementFactor = abs(old_x - x);
   int temp = abs(old_y - y); //due to impl of max(), no inline functions
   movementFactor = max(movementFactor, temp);
   temp = abs(old_z - z);
   movementFactor = max(movementFactor, temp);
}

void readSensors() {
   x = analogRead(AX);
   y = analogRead(AY);
   z = analogRead(AZ);
}

void saveValues() {
   old_x = x;
   old_y = y;
   old_z = z;
}
</pre>
<p>Assuming you don&#8217;t have it in DEBUG mode, it constantly reads the values off the accelerometer and finds the greatest change b/w all the axises. If that is greater than your SENSITIVITY, it sends it to the computer. I chose to do it this way rather than sending the movement factor every second so I could exploit the sparsity of the data and just use a scatter plot to stretch it out over the time domain. Now for the client side&#8230;</p>
<p>The client code is just a single python script. To get it working you need to install <a href="http://pyserial.sourceforge.net/">pyserial</a> of course. </p>
<pre class="brush: python; title: ; notranslate">
#!/usr/bin/env python
#
# @file: monitor.py
# @author: Benjamin Eckel
#
# To Run --&gt;
#     $python monitor.py &gt; output_file.csv
#                                                                                                              

import serial
import datetime

FTDI_USB = &quot;/dev/tty.usbserial-A3000RBH&quot;

if __name__ == &quot;__main__&quot;:
    print &quot;Time,Movement&quot;
    ser = serial.Serial(FTDI_USB, 9600)
    while 1:
        movement = ser.readline()
        print &quot;%s,%s&quot; % (datetime.datetime.now().strftime(&quot;%H:%M:%S&quot;), movement.rstrip())
</pre>
<p>This code is self explanatory, you run it and it prints out a comma-separated file with the hours, minutes, seconds, and the relative motion. You can redirect the output to whatever file or program you choose. Here is an example of some output:</p>
<blockquote><p>
Time,Movement<br />
01:31:47,4<br />
01:31:48,12<br />
01:31:49,15<br />
01:31:50,4<br />
01:31:51,4<br />
01:31:53,4<br />
01:31:54,27<br />
01:31:55,6<br />
01:31:56,12<br />
01:31:57,16<br />
01:31:58,6<br />
01:31:59,5<br />
01:32:00,5<br />
01:32:02,4<br />
01:32:03,4<br />
01:32:06,4<br />
01:32:07,4<br />
01:32:08,4<br />
01:32:09,4
</p></blockquote>
<p>All you need to change is your FTDI_USB location. If you don&#8217;t know yours, plug in your arduino and run this command:</p>
<blockquote><p>
ls /dev/usb.tty.usb*
</p></blockquote>
<p>This is assuming you are running OS X or Linux of course. Windows uses COM ports. Refer to pyserial for help.</p>
<h3>The Installation</h3>
<p>To get good readings, it is best to place the sensor somewhere on your mattress that experiences the maximum displacement of the surface (the anti-node) caused by your movements. You can program it in DEBUG mode and try different locations out. I just wrapped the sensor in a sock and stuck it in one of my pillows. </p>
<div id="attachment_726" class="wp-caption aligncenter" style="width: 310px"><a href="http://blog.datasingularity.com/wp-content/uploads/2010/06/CRW_1221.jpg"><img src="http://blog.datasingularity.com/wp-content/uploads/2010/06/CRW_1221-300x200.jpg" alt="Sock wrapped sensor" title="Sock wrapped sensor" width="300" height="200" class="size-medium wp-image-726" /></a><p class="wp-caption-text">Sock wrapped sensor</p></div>
<h3>The Results</h3>
<p>To graph the results, I imported the resulting csv file into excel and created a scatter plot. This is my sleep from June 20 1:30AM to 11:00AM [ took a while to get out of bed :) ]: </p>
<div id="attachment_734" class="wp-caption aligncenter" style="width: 310px"><a target="_blank" href="http://blog.datasingularity.com/wp-content/uploads/2010/06/sleep_june20.jpg"><img src="http://blog.datasingularity.com/wp-content/uploads/2010/06/Picture-3-300x204.png" alt="Sleep chart thumb" title="Sleep chart thumb" width="300" height="204" class="size-medium wp-image-734" /></a><p class="wp-caption-text">Click to view full chart</p></div>
<p>From what little I know about the subject, I think I should be seeing spikes separated by intervals of about 90 minutes (the time it takes to get a full cycle of sleep). There are definitely some abnormalities in there. I am going attempt to do this for about a week and maybe send the results to a doctor friend.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.datasingularity.com/?feed=rss2&#038;p=700</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Radioshack Infrared Receiver  Arduino</title>
		<link>http://blog.datasingularity.com/?p=689</link>
		<comments>http://blog.datasingularity.com/?p=689#comments</comments>
		<pubDate>Mon, 31 May 2010 18:38:03 +0000</pubDate>
		<dc:creator>benjamin</dc:creator>
				<category><![CDATA[Arduino]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Hardware]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://blog.datasingularity.com/?p=689</guid>
		<description><![CDATA[I just posted up an article on the Gumbolabs blog explaining how to use the Radioshack infrared receiver module. It contains Arduino code along with the explanations.]]></description>
			<content:encoded><![CDATA[<p>I just posted up <a href="http://www.gumbolabs.org/2010/05/29/radioshack-infrared-receiver-arduino/">an article on the Gumbolabs blog</a> explaining how to use the Radioshack infrared receiver module. It contains Arduino code along with the explanations.</p>
<p><img alt="" src="http://www.gumbolabs.org/cms/wp-content/downloads/2010/05/pRS1C-2110718w345-300x204.jpg" class="aligncenter" width="300" height="204" /></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.datasingularity.com/?feed=rss2&#038;p=689</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>p5particles for Processing released</title>
		<link>http://blog.datasingularity.com/?p=686</link>
		<comments>http://blog.datasingularity.com/?p=686#comments</comments>
		<pubDate>Thu, 27 May 2010 03:29:25 +0000</pubDate>
		<dc:creator>benjamin</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Processing]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://blog.datasingularity.com/?p=686</guid>
		<description><![CDATA[I have finally released p5particles which is my particle systems library for Processing. You can view the project here: http://code.google.com/p/p5particles/ There is currently limited documentation and support. I will start improving it if others find it useful.]]></description>
			<content:encoded><![CDATA[<p>I have finally released p5particles which is my particle systems library for Processing. You can view the project here:</p>
<p><a href="http://code.google.com/p/p5particles/">http://code.google.com/p/p5particles/</a></p>
<p>There is currently limited documentation and support. I will start improving it if others find it useful.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.datasingularity.com/?feed=rss2&#038;p=686</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Particle System in Processing: Re-examining our Integration Technique</title>
		<link>http://blog.datasingularity.com/?p=517</link>
		<comments>http://blog.datasingularity.com/?p=517#comments</comments>
		<pubDate>Fri, 19 Mar 2010 06:29:35 +0000</pubDate>
		<dc:creator>benjamin</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Processing]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[particles]]></category>
		<category><![CDATA[physics]]></category>
		<category><![CDATA[processing.org]]></category>

		<guid isPermaLink="false">http://blog.datasingularity.com/?p=517</guid>
		<description><![CDATA[This article is one in a series of articles about particle systems in Processing. To view the first of the series, click here. In the last article, we discussed forces and left off with questions about our technique for determining the particle&#8217;s position at each frame. It turns out that it was wildly inaccurate. In [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>
This article is one in a series of articles about particle systems in Processing. To view the first of the series, <a href="http://blog.datasingularity.com/?p=335">click here</a>.
</p></blockquote>
<p>In <a href="http://blog.datasingularity.com/?p=362">the last article</a>, we discussed forces and left off with questions about our technique for determining the particle&#8217;s position at each frame. It turns out that it was wildly inaccurate. In this article, I am first going to try to explain the mathematics behind what we are doing and use that knowledge to expose the source of our problem. Then I am going to try to present a solution.</p>
<h3>Where Does the Problem Come From?</h3>
<p>Recall the equation I presented in the last article which gives us distance given the state of a body and a time period:</p>
<blockquote><img src='http://s.wordpress.com/latex.php?latex=s%20%3D%20u%5Ctimes%20t%20%2B%20%280.5%5Ctimes%20a%5Ctimes%20t%5E2%29&bg=FFFFFF&fg=000000&s=0' alt='Latex formula' title='Latex formula' class='latex' /></blockquote>
<p>This equation gives us an <b>exact</b> distance for the given acceleration, initial velocity, and time period and we used it to measure the error of our technique. So the question remains, why not use this equation to determine the particle position at each frame? Well, the problem is unfortunately too complicated for me to explain easily but I am going to try. From my understanding, that equation only works when acceleration is constant over time. If you take a hard look at it, this property will become apparent. The equation gives you a distance for a given <b>step</b> of time but is not actually a continuous function with respect to time. In other words, you cannot use it to solve acceleration for any given point in time. In a particle system, there may be <b>one to many</b> forces acting on a given particle at any time. On top of that, those forces are changing the acceleration of the particle in seemingly erratic ways. In fact, it is said that the function which determines the acceleration with respect to time is <b>well-defined</b> but is actually <b>unknown</b>. Therefore, we cannot get an exact value at any given point, we can only approximate it. Given that our calculations are <b>approximations</b>, we have to assume there will always be an error. All we can do is find techniques to make the error manageable. </p>
<h3>Solving Systems Governed by Unknown Functions</h3>
<p>So, how exactly were we solving this unknown function before? Let&#8217;s step away from our particle system for a very brief moment. You may remember from high school maths that you can solve the integral of a function by integrating that function over an interval when given boundary conditions. You may also remember that in certain situations, such as when f(t, y) is unknown or cannot be solved analytically, you can solve these problems by taking an <b>initial value</b> and solving in steps. This is called an <b>initial value problem</b> and follows this form:</p>
<blockquote><img src='http://s.wordpress.com/latex.php?latex=%5Cfrac%7Bdy%7D%7Bdt%7D%20%3D%20f%28t%2C%20y%29%2C%20%5Cquad%20y%28t_0%29%20%3D%20y_0&bg=FFFFFF&fg=000000&s=0' alt='Latex formula' title='Latex formula' class='latex' /></blockquote>
<p>Some tricky manipulating of this formula results in a <b>series</b> which usually looks something like this:</p>
<blockquote><img src='http://s.wordpress.com/latex.php?latex=y_%7Bn%2B1%7D%20%3D%20y_n%20%2B%20%5Cmbox%7B%20%5Bsome%20diffEQ%20of%20y%20with%20respect%20to%20time%5D%20%7D&bg=FFFFFF&fg=000000&s=0' alt='Latex formula' title='Latex formula' class='latex' /></blockquote>
<p>So, I am pretty bad at all this maths o_0 but hopefully you are starting to see something here. In this series, we are determining the next value [y_n+1] using the current value [y_n] and adding the differential function. Just like we did with our particles, we found velocity by adding the last velocity plus the difference in velocity[acceleration]. Then we did the same for position. Acceleration is a <b>second order</b> derivative so when using this method which solves first order diffEQs, we must break it down into two first order derivatives:</p>
<blockquote><img src='http://s.wordpress.com/latex.php?latex=%20%20a%20%3D%20%5Cfrac%7Bdv%7D%7Bdt%7D%2C%20%20%5Cquad%20v%20%3D%20%5Cfrac%7Bdp%7D%7Bdt%7D%20%20&bg=FFFFFF&fg=000000&s=0' alt='Latex formula' title='Latex formula' class='latex' /></blockquote>
<p>where <b>v</b> is <b>velocity</b> and <b>p</b> is <b>position</b>. </p>
<p>Now let&#8217;s try and make sense out of this mess. </p>
<h3>Euler&#8217;s Method for Solving First Order Differential Equatons</h3>
<p>You may not have known it, but the method we were using before in our code is known as <a target="_blank" href="http://en.wikipedia.org/wiki/Euler_method">Euler&#8217;s Method</a> and is the defacto, inherent approach to this problem. The only thing I left out is the <b>time step</b>. The actual process should look something like this:</p>
<pre class="brush: java; light: true; title: ; notranslate">
velocity.add(PVector.mult(acceleration, h));
location.add(PVector.mult(velocity, h));
</pre>
<p>where <b>h</b> is the time step in the simulation. As an astute reader, you may realize that the h was actually accounted for before. It was just assumed to be &#8217;1&#8242; ;) The common way to make the Euler method more accurate is to reduce the time-step [h]. I will explain why in a second, let&#8217;s just quickly alter the code to see what happens. <a target="_blank" href="http://processing.datasingularity.com/sketches/ParticlePhysicsTutorial_7/applet/">Go check it out in action</a> then come back and examine the source:</p>
<pre class="brush: java; highlight: [5,29,79,80]; title: ; notranslate">
ArrayList particles;

Particle a;

float h = 0.2; //new time step &lt; 1

void setup() {
 size(600, 600);
 stroke(0);
 strokeWeight(3);
 fill(150);
 smooth();

 particles = new ArrayList();

 a = new Particle();
 a.location = new PVector(width/2f, height/2f);
 a.fixed = true;

 particles.add(a);
}

void draw() {
  background(255);
  for (int i = particles.size()-1; i &gt;= 0; i--) {
    Particle p = (Particle)particles.get(i);
    // experiment w/ different friction coefficients
    applyDissipativeForce(p, 0.01);
    applyAttractiveForce(a, p, 5000f, 50f);
    if(!p.exist()) {
      particles.remove(i);
    }
  }
}

void mouseDragged() {
    particles.add(new Particle());
} 

void applyDissipativeForce(Particle p, float friction) {
  PVector f = PVector.mult(p.velocity, -friction);
  p.applyForce(f);
}

void applyAttractiveForce(Particle a, Particle b, float strength, float minDistance) {
  PVector dir = PVector.sub(a.location, b.location);
  float d = dir.mag();
  if (d &lt; minDistance) d = minDistance;
  dir.normalize();
  float force = (strength * a.mass * b.mass) / (d * d);
  dir.mult(force);
  if (!b.fixed) b.applyForce(dir);
  if (!a.fixed) {
    dir.mult(-1f);
    a.applyForce(dir);
  }
}

public class Particle {
  PVector location;
  PVector velocity;
  PVector acceleration;
  float mass;
  boolean fixed;

  public Particle() {
      location = new PVector(mouseX, mouseY);
      //get velocity from direction and speed of mouse movement
      velocity = new PVector(mouseX-pmouseX, mouseY-pmouseY);
      acceleration = new PVector(0, 0, 0);
      mass = 1;
      fixed = false;
  }

  public boolean exist() {
     if (fixed) {
       fill(255,0,0);
     } else {
       velocity.add(PVector.mult(acceleration, h));
       location.add(PVector.mult(velocity, h));
       acceleration.mult(0);
       fill(150);
     }
     ellipse(location.x, location.y, 10, 10);
     return true;
  }

  void applyForce(PVector force) {
      acceleration.add(PVector.div(force, mass));
  }

}
</pre>
<p>All I did was alter the integration part, added the <b>h</b> float at 0.2, and increased the strength to <b>5000</b> to speed things up a little. What you should have noticed is that it has gotten a lot slower and it should be obvious why: Our framerate is the same but we are stepping ahead in the simulation in smaller steps of time.</p>
<p>What you probably did not notice is the huge increase in accuracy. To prove this, let&#8217;s re-implement our python script experiment from the last article and compare it with the exact results again. This time we will have a time step-size of 0.1:</p>
<pre class="brush: python; highlight: [2,13,14,15]; title: ; notranslate">
t = 0
h = 0.1

vel = 0
pos = 0
acc = 10

while (t &lt;= 10):
        print &quot;t = %s&quot; % t
        print &quot;pos = %s&quot; % pos
        print &quot;vel = %s&quot; % vel
        print &quot;-------------------&quot;
        vel += acc * h
        pos += vel * h
        t += h
</pre>
<p>When we run this script we get [middle cut out for brevity]:</p>
<blockquote><p>
t = 0<br />
pos = 0<br />
vel = 0<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
t = 0.1<br />
pos = 0.1<br />
vel = 1.0<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
t = 0.2<br />
pos = 0.3<br />
vel = 2.0<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
t = 0.3<br />
pos = 0.6<br />
vel = 3.0<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
t = 0.4<br />
pos = 1.0<br />
vel = 4.0<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
t = 0.5<br />
pos = 1.5<br />
vel = 5.0<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
.<br />
.<br />
.<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
t = 9.6<br />
pos = 465.6<br />
vel = 96.0<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
t = 9.7<br />
pos = 475.3<br />
vel = 97.0<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
t = 9.8<br />
pos = 485.1<br />
vel = 98.0<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
t = 9.9<br />
pos = 495.0<br />
vel = 99.0<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
t = 10.0<br />
pos = 505.0<br />
vel = 100.0
</p></blockquote>
<p><b>Position = 505</b>. You may remember that using these initial values with our equation:</p>
<blockquote><img src='http://s.wordpress.com/latex.php?latex=%20%20s%20%3D%20u%5Ctimes%20t%20%2B%20%280.5%5Ctimes%20a%5Ctimes%20t%5E2%29%20%20&bg=FFFFFF&fg=000000&s=0' alt='Latex formula' title='Latex formula' class='latex' /></blockquote>
<p>yielded an exact end position of <b>500</b>. Now we are only <b>off by 5</b> whereas with a <b>time-step of 1</b> we were <b>off by 50</b>! This should show you that the error for this method is close to [i think?]:</p>
<blockquote><img src='http://s.wordpress.com/latex.php?latex=%20%20%5Cmbox%7B%20error%20per%20time%20step%7D%20%3D%20%5Cfrac%7B1%7D%7B2%7D%20h%5E2%20y%5Cprime%5Cprime%20%20&bg=FFFFFF&fg=000000&s=0' alt='Latex formula' title='Latex formula' class='latex' /></blockquote>
<p>There is a mathematical way to determine the real error but we aren&#8217;t going to go into it because we will be abandoning this method soon and it is too complicated for the little value it provides us. If you really want to know, check out the <a href="http://en.wikipedia.org/wiki/Euler_method">Wikipedia article</a> on Euler&#8217;s method.</p>
<h3>Why does a Smaller h Yield More Accurate results?</h3>
<p>The question arises, why is it more accurate? The answer may help you better understand what is happening. Let&#8217;s look at a graphic representation of the Euler method in action:</p>
<div id="attachment_543" class="wp-caption aligncenter" style="width: 310px"><img src="http://blog.datasingularity.com/wp-content/uploads/2010/03/766px-Euler_method-300x234.png" alt="Graphical representation of Euler&#039;s method (Source: Wikipedia)" title="Eulers method" width="300" height="234" class="size-medium wp-image-543" /><p class="wp-caption-text">Graphical representation of Euler's method (Source: Wikipedia)</p></div>
<p>Pretend that the blue line is our unknown but well-defined function in which the acceleration is the dependent variable and that A0, A1, A2, A3, and A4 are the acceleration values we calculate. Essentially, at each step, we know the derivative [the tangent to the curve] and multiply it by the time step, then add it to the current <b>A</b> value to guess the next value. At that point, we assume we are at the correct spot and do this again and again and again. You can now see why the error accumulates. We are basically walking a dark path using a slow strobe light. Now imagine that the <b>A</b> values were taken in smaller intervals [the strobe light is blinking faster] and you can see that we would be closer to the blue line [exact solutions]. But if you took a bigger step size, you would be farther away from the exact values. The following pictures illustrate the point perfectly. The red line is the exact solution and the blue is the approximation:</p>
<div id="attachment_583" class="wp-caption aligncenter" style="width: 255px"><img src="http://blog.datasingularity.com/wp-content/uploads/2010/03/euler3.gif" alt="big step of h" title="euler3" width="245" height="233" class="size-full wp-image-583" /><p class="wp-caption-text">big step of h</p></div>
<div id="attachment_584" class="wp-caption aligncenter" style="width: 255px"><img src="http://blog.datasingularity.com/wp-content/uploads/2010/03/euler4.gif" alt="medium sized step of h" title="euler4" width="245" height="230" class="size-full wp-image-584" /><p class="wp-caption-text">medium sized step of h</p></div>
<div id="attachment_585" class="wp-caption aligncenter" style="width: 255px"><img src="http://blog.datasingularity.com/wp-content/uploads/2010/03/euler5.gif" alt="small step of h" title="euler5" width="245" height="232" class="size-full wp-image-585" /><p class="wp-caption-text">small step of h</p></div>
<div id="attachment_586" class="wp-caption aligncenter" style="width: 255px"><img src="http://blog.datasingularity.com/wp-content/uploads/2010/03/euler6.gif" alt="tiny step of h" title="euler6" width="245" height="231" class="size-full wp-image-586" /><p class="wp-caption-text">tiny step of h</p></div>
<p><a target="_blank" href="http://www.math.montana.edu/frankw/ccp/calculus/des/euler-pictures/learn.htm ">Here is the source</a> of these photos.</p>
<p>So as h gets smaller, our approximated curve inches closer to the exact curve. </p>
<h3>Picking a New Method</h3>
<p>Where do we go from here? Well, we have determined that the Euler method is just not really feasible. Sure, it may have worked out for our little examples but we can achieve more stability and accuracy with some other methods. Plus we can&#8217;t pump up the framerate enough to get a realistic speed. It just doesn&#8217;t look believable. In the next article, I am going to show you how to implement the <a target="_blank" href="http://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods">Runge-Kutta methods</a>, particularly the Fourth Order Runge-Kutta method. I am also going to try to explain the differences between implicit and explicit integration.</p>
<h3>References</h3>
<blockquote><p>
Gaffer on Games : <a href="http://gafferongames.com/game-physics/integration-basics/">Integration Basics</a>
</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://blog.datasingularity.com/?feed=rss2&#038;p=517</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Creating a Particle System in Processing: Applying Forces</title>
		<link>http://blog.datasingularity.com/?p=362</link>
		<comments>http://blog.datasingularity.com/?p=362#comments</comments>
		<pubDate>Wed, 17 Mar 2010 15:50:12 +0000</pubDate>
		<dc:creator>benjamin</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Processing]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[particle]]></category>
		<category><![CDATA[particles]]></category>
		<category><![CDATA[physics]]></category>
		<category><![CDATA[processing.org]]></category>

		<guid isPermaLink="false">http://blog.datasingularity.com/?p=362</guid>
		<description><![CDATA[This article is one in a series of articles about particle systems in Processing. To view the first of the series, click here. To recap, in my last article, I went over the basics of particles and Newtonian motion in Processing. In this article, I am going to explain using forces and Newton&#8217;s Second Law [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>
This article is one in a series of articles about particle systems in Processing. To view the first of the series, <a href="http://blog.datasingularity.com/?p=335">click here</a>.
</p></blockquote>
<p>To recap, in <a href="http://blog.datasingularity.com/?p=335">my last article</a>, I went over the basics of particles and Newtonian motion in Processing. In this article, I am going to explain using <b>forces</b> and <a target="_blank" href="http://en.wikipedia.org/wiki/Newton%27s_laws_of_motion">Newton&#8217;s Second Law of Motion</a> to describe the effects of forces on our particles. I am also going to point out that our current integration technique is flawed as segway into the next article.</p>
<h3>Forces</h3>
<p>When we last left our particle physics sandbox, it looked liked this:</p>
<pre class="brush: java; title: ; notranslate">
ArrayList particles;
int LIFESPAN = 120;
//global gravity
PVector acceleration =  new PVector(0f, 0.025);

void setup() {
 size(400, 400);
 stroke(0);
 strokeWeight(3);
 fill(150);
 smooth();
 particles = new ArrayList();
}

void draw() {
  background(255);
  //only create when mouse moves
  if (abs(mouseX-pmouseX) &gt; 0.0001) {
    particles.add(new Particle());
  }
  for (int i = particles.size()-1; i &gt;= 0; i--) {
    Particle p = (Particle)particles.get(i);
    if(!p.exist()) {
      particles.remove(i);
    }
  }
}

public class Particle {
  PVector location;
  PVector velocity;
  int age;

  public Particle() {
      location = new PVector(mouseX, mouseY);
      //get velocity from direction and speed of mouse movement
      velocity = new PVector(mouseX-pmouseX, mouseY-pmouseY);
      age = 0;
  }

  public boolean exist() {
     velocity.add(acceleration);
     location.add(velocity);
     ellipse(location.x, location.y, 10, 10);
     if (age &gt; LIFESPAN) {
       return false;
     }
     age++;
     return true;
  }

}
</pre>
<p>The PVector <b>acceleration</b> represents the acceleration resulting from a gravitational force. Gravity is a force and results in an acceleration of an object. There is an equation to determine gravity but we usually take it to result in a constant acceleration of 9.8 m/s^2 when viewing things on earth. This is because our measurements on earth usually involve relatively small and close things [relative to earth's mass and space] and the difference b/w earth&#8217;s effects on these objects is negligible.  </p>
<p>Anyways, like all other units of motion, a force can be represented as a Vector. And different forces have different equations to describe their effects. The result a force has on an object is described by Newton&#8217;s Second Law of Motion:</p>
<blockquote><img src='http://s.wordpress.com/latex.php?latex=%20%20f%20%3D%20m%20%5Ctimes%20a%20&bg=FFFFFF&fg=000000&s=0' alt='Latex formula' title='Latex formula' class='latex' /></blockquote>
<p>where <b>f</b> is the <b>force</b>, <b>m</b> is the object&#8217;s <b>mass</b>, and <b>a</b> is <b>acceleration</b>. It is usually more helpful to represent the equation in this alternate form:</p>
<blockquote><img src='http://s.wordpress.com/latex.php?latex=%20a%20%3D%20%5Cfrac%7Bf%7D%7Bm%7D%20&bg=FFFFFF&fg=000000&s=0' alt='Latex formula' title='Latex formula' class='latex' /></blockquote>
<p>Knowing this, we can now calculate the acceleration resulting from a force on an object. First we will get rid of the global PVector acceleration then we will alter the Particle class to look like this:</p>
<pre class="brush: java; title: ; notranslate">
public class Particle {
  PVector location;
  PVector velocity;
  PVector acceleration;
  float mass;

  public Particle() {
      location = new PVector(mouseX, mouseY);
      //get velocity from direction and speed of mouse movement
      velocity = new PVector(mouseX-pmouseX, mouseY-pmouseY);
      acceleration = new PVector(0, 0, 0);
      mass = 1;
  }

  public boolean exist() {
     velocity.add(acceleration);
     location.add(velocity);
     ellipse(location.x, location.y, 10, 10);
     //when it comes to a rest, get rid of it
     if (abs(velocity.x) &lt; 0.001 &amp;&amp; abs(velocity.y) &lt; 0.001) {
       return false;
     }
     acceleration.mult(0); //need to clear acceleration
     return true;
  }

  void applyForce(PVector force) {
      acceleration.add(PVector.div(force, mass));
  }

}
</pre>
<p>First, note the changes to the Particle class structure:</p>
<ol>
<li>The particle now keeps track of it&#8217;s own acceleration</li>
<li>Each particle has a mass, which we are just setting to 1 for convenience</li>
<li>We added the applyForce(PVector) method</li>
<li>We are now removing a particle from the system when it&#8217;s velocity falls below a certain level</li>
</ol>
<p>Take a look at the applyForce method. There are a few things to note about this method in particular:</p>
<ol>
<li>Notice that this is basically Newton&#8217;s equation in the second form we presented: <b>a = f/m</b></li>
<li>We are calling <b>add()</b> on acceleration b/c we may be applying other forces to this particle. It may already have an acceleration value set. But we are also clearing the acceleration after each iteration [<b>line 23</b>]. This is important b/c we don&#8217;t want the force to have an accumulative effect. See what happens when you comment out that operation.</li>
<li>Not that this is a Java lesson, but notice that I used the static <b>PVector.div(PVector, float)</b> method rather than using an instance method. The static methods return the results of the operations as new instances whereas the instance methods modify the PVector that the reference points to. Pay attention to this detail, when to use either should become obvious if not already.</li>
</ol>
<h3>Applying a Force: Friction</h3>
<p>Now we want to actually apply a force to a particle. There are many types of forces and many equations to describe their behavior. By far, one of the easiest to understand is a <b>dissipative force</b>. It most commonly manifests itself in day to day life in the form of <b>friction</b> but can also be used to simulate other phenomena. The equation is:</p>
<blockquote><img src='http://s.wordpress.com/latex.php?latex=%20f%20%3D%20-C%20%5Ctimes%20v%20&bg=FFFFFF&fg=000000&s=0' alt='Latex formula' title='Latex formula' class='latex' /></blockquote>
<p>where <b>f</b> is the <b>resulting force</b>, <b>C</b> is a mathematical <b>constant</b> known as the &#8220;<b>coefficient of friction</b>&#8220;, and <b>v</b> is the object&#8217;s <b>velocity</b>. Obviously, the larger <b>C</b> is, the more friction is applied and the quicker your object will come to a state of rest. It is usually between 0.0 and 1.0 . To implement this, I added this global function:</p>
<pre class="brush: java; light: true; title: ; notranslate">
void applyDissipativeForce(Particle p, float friction) {
  PVector f = PVector.mult(p.velocity, -friction);
  p.applyForce(f);
}
</pre>
<p>Pretty self-explanatory. We take the velocity of the particle that we are applying this force to and we multiply it by the coefficient * -1. Let&#8217;s put all this together. <a target="_blank" href="http://processing.datasingularity.com/sketches/ParticlePhysicsTutorial_5/applet/">Check out the code in action</a>, then come back and examine the whole source:</p>
<pre class="brush: java; title: ; notranslate">
ArrayList particles;

void setup() {
 size(400, 400);
 stroke(0);
 strokeWeight(3);
 fill(150);
 smooth();
 particles = new ArrayList();
}

void draw() {
  background(255);
  //only create when mouse moves
  if (abs(mouseX-pmouseX) &gt; 0.0001) {
    particles.add(new Particle());
  }
  for (int i = particles.size()-1; i &gt;= 0; i--) {
    Particle p = (Particle)particles.get(i);
    // experiment w/ different friction coefficients
    applyDissipativeForce(p, 0.08);
    if(!p.exist()) {
      particles.remove(i);
    }
  }
}

void applyDissipativeForce(Particle p, float friction) {
  PVector f = PVector.mult(p.velocity, -friction);
  p.applyForce(f);
}

public class Particle {
  PVector location;
  PVector velocity;
  PVector acceleration;
  float mass;

  public Particle() {
      location = new PVector(mouseX, mouseY);
      //get velocity from direction and speed of mouse movement
      velocity = new PVector(mouseX-pmouseX, mouseY-pmouseY);
      acceleration = new PVector(0, 0, 0);
      mass = 1;
  }

  public boolean exist() {
     //when it comes to a rest, get rid of it
     if (abs(velocity.x) &lt; 0.001 &amp;&amp; abs(velocity.y) &lt; 0.001) {
       return false;
     }
     velocity.add(acceleration);
     location.add(velocity);
     ellipse(location.x, location.y, 10, 10);
     acceleration.mult(0);
     return true;
  }

  void applyForce(PVector force) {
      acceleration.add(PVector.div(force, mass));
  }

}
</pre>
<h3>Applying Another Force: Attraction</h3>
<p>Now we are going to implement a more complicated force, attraction. This force could be used to simulate gravitational force, without all that Einstein, space-time continuum craziness of course. The equation we are going to use is:</p>
<blockquote><img src='http://s.wordpress.com/latex.php?latex=%20%20f%20%3D%20%5Cfrac%7B%28G%20%5Ctimes%20m_1%20%5Ctimes%20m_2%29%7D%7Bd%5E2%7D%20%20&bg=FFFFFF&fg=000000&s=0' alt='Latex formula' title='Latex formula' class='latex' /></blockquote>
<p>where <b>f</b> is the <b>force</b>, <b>G</b> is the <b>gravitational constant</b> [defines the apparent 'strength'], <b>m1</b> and <b>m2</b> are the <b>masses</b> of the two bodies in effect, and <b>d</b> is the <b>distance</b> between the two bodies. The problem is that this equation computes the <b>magnitude</b>, or the power, of the force; but not the direction. With the dissipative force, the direction was the opposite of the velocity. This was obvious in the equation. The force in this situation however is between the 2 bodies, so naturally, the equation will involve subtracting the positions. Here it is:</p>
<blockquote><img src='http://s.wordpress.com/latex.php?latex=%20%20d%20%3D%20%5Cfrac%7BL_2-L_1%7D%7B%5CVert%20L_2-L_1%20%5CVert%7D%20%20&bg=FFFFFF&fg=000000&s=0' alt='Latex formula' title='Latex formula' class='latex' /></blockquote>
<p>where <b>d</b> is <b>direction</b> and <b>L1</b> and <b>L2</b> are the <b>position vectors</b> of the bodies.</p>
<p>Now we will implement the global function to apply an attractive force on two particles. We will also have to modify the Particle class:</p>
<pre class="brush: java; light: true; title: ; notranslate">
void applyAttractiveForce(Particle a, Particle b, float strength, float minDistance) {
     PVector dir = PVector.sub(a.location, b.location);
     float d = dir.mag();
     if (d &lt; minDistance) d = minDistance;
     dir.normalize();
     float force = (strength * a.mass * b.mass) / (d * d);
     dir.mult(force);
     if (!b.fixed) b.applyForce(dir);
     if (!a.fixed) {
        dir.mult(-1f);
        a.applyForce(dir);
     }
}

public class Particle {
  PVector location;
  PVector velocity;
  PVector acceleration;
  float mass;
  boolean fixed;

  public Particle() {
      location = new PVector(mouseX, mouseY);
      //get velocity from direction and speed of mouse movement
      velocity = new PVector(mouseX-pmouseX, mouseY-pmouseY);
      acceleration = new PVector(0, 0, 0);
      mass = 1;
      fixed = false;
  }

  public boolean exist() {
     if (fixed) {
       fill(255,0,0);
     } else {
       velocity.add(acceleration);
       location.add(velocity);
       acceleration.mult(0);
       fill(150);
     }
     ellipse(location.x, location.y, 10, 10);
     return true;
  }

  void applyForce(PVector force) {
      acceleration.add(PVector.div(force, mass));
  }

}
</pre>
<p>I added a <b>fixed</b> property. If the Particle is fixed, it is not affected by outside forces. They also render red. </p>
<p>As for the <b>applyAttractiveForce()</b>, for the most part, it follows our two equations above.  The first thing to note is that we are constraining the distance:</p>
<pre class="brush: java; light: true; title: ; notranslate">
if (d &lt; minDistance) d = minDistance;
</pre>
<p>This is because too small a distance value will create too large a force and the particles will go flying off. Also notice that we are applying &#8220;equal but opposite&#8221; forces on each particle:</p>
<pre class="brush: java; light: true; title: ; notranslate">
     if (!b.fixed) b.applyForce(dir);
     if (!a.fixed) {
        dir.mult(-1f);
        a.applyForce(dir);
     }
</pre>
<p>Now let&#8217;s look at the whole thing. <a target="_blank" href="http://processing.datasingularity.com/sketches/ParticlePhysicsTutorial_6/applet/">Check out this code in action</a> then come back and view the source:</p>
<pre class="brush: java; title: ; notranslate">
ArrayList particles;

Particle a;

void setup() {
 size(800, 600);
 stroke(0);
 strokeWeight(3);
 fill(150);
 smooth();

 particles = new ArrayList();

 a = new Particle();
 a.location = new PVector(width/2f, height/2f);
 a.fixed = true;
 a.mass = 5.0;

 particles.add(a);
}

void draw() {
  background(255);
  for (int i = particles.size()-1; i &gt;= 0; i--) {
    Particle p = (Particle)particles.get(i);
    // experiment w/ different friction coefficients
    applyDissipativeForce(p, 0.01);
    //experiment with strength and minDistance, try a minDistance below 30
    applyAttractiveForce(a, p, 500f, 50f);
    if(!p.exist()) {
      particles.remove(i);
    }
  }
}

void mouseDragged() {
  particles.add(new Particle());
}

void applyDissipativeForce(Particle p, float friction) {
  PVector f = PVector.mult(p.velocity, -friction);
  p.applyForce(f);
}

void applyAttractiveForce(Particle a, Particle b, float strength, float minDistance) {
  PVector dir = PVector.sub(a.location, b.location);
  float d = dir.mag();
  if (d &lt; minDistance) d = minDistance;
  dir.normalize();
  float force = (strength * a.mass * b.mass) / (d * d);
  dir.mult(force);
  if (!b.fixed) b.applyForce(dir);
  if (!a.fixed) {
    dir.mult(-1f);
    a.applyForce(dir);
  }
}

public class Particle {
  PVector location;
  PVector velocity;
  PVector acceleration;
  float mass;
  boolean fixed;

  public Particle() {
      location = new PVector(mouseX, mouseY);
      //get velocity from direction and speed of mouse movement
      velocity = new PVector(mouseX-pmouseX, mouseY-pmouseY);
      acceleration = new PVector(0, 0, 0);
      mass = 1;
      fixed = false;
  }

  public boolean exist() {
     if (fixed) {
       fill(255,0,0);
     } else {
       velocity.add(acceleration);
       location.add(velocity);
       acceleration.mult(0);
       fill(150);
     }
     ellipse(location.x, location.y, 10, 10);
     return true;
  }

  void applyForce(PVector force) {
      acceleration.add(PVector.div(force, mass));
  }

}
</pre>
<p>Hopefully this code is pretty easy to understand. <b>Particle a</b> is the center red particle. We set it&#8217;s location to the center of the screen, set it as fixed, then give it a bigger mass. For every particle, we are applying both the dissipative force and the attraction to particle a:</p>
<pre class="brush: java; light: true; title: ; notranslate">
        applyDissipativeForce(p, 0.01);
        applyAttractiveForce(a, p, 500f, 50f);
</pre>
<h3>Re-examining our Integration Technique</h3>
<p>If you took the time to closely examine our technique for determining a particle&#8217;s position at each frame, you may have noticed some inaccuracies. Let&#8217;s use an analogy. Switch over your thought process from 2d down to 1d. Let&#8217;s say we are in a car travelling down a road [is commonly described as if it is one dimension].  If we know the car&#8217;s acceleration, and <b>we assume that it is constant</b>, we can theoretically calculate the position after a given time with the equation:</p>
<blockquote><img src='http://s.wordpress.com/latex.php?latex=%20%20s%20%3D%20u%5Ctimes%20t%20%2B%20%280.5%5Ctimes%20a%5Ctimes%20t%5E2%29%20%20&bg=FFFFFF&fg=000000&s=0' alt='Latex formula' title='Latex formula' class='latex' /></blockquote>
<p>where <b>s</b> is the <b>distance</b>, <b>u</b> is the <b>initial velocity</b>, <b>a</b> is the <b>acceleration</b>, and <b>t</b> is <b>time</b>. So if we have an initial velocity of <b>0</b>, an acceleration of <b>10</b> meters per second every second and we travel for <b>10</b> seconds, we end up with a distance of <b>500 meters</b>. Now let&#8217;s try this with our methodology. Here is a python script to simulate our technique:</p>
<pre class="brush: python; title: ; notranslate">
t = 0

vel = 0
pos = 0
acc = 10

while (t &lt;= 10):
        print &quot;t = %s&quot; % t
        print &quot;pos = %s&quot; % pos
        print &quot;vel = %s&quot; % vel
        print &quot;-------------------&quot;
        vel += acc
        pos += vel
        t += 1
</pre>
<p>If we run this, we get:</p>
<blockquote><p>
t = 0<br />
pos = 0<br />
vel = 0<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
t = 1<br />
pos = 10<br />
vel = 10<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
t = 2<br />
pos = 30<br />
vel = 20<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
t = 3<br />
pos = 60<br />
vel = 30<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
t = 4<br />
pos = 100<br />
vel = 40<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
t = 5<br />
pos = 150<br />
vel = 50<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
t = 6<br />
pos = 210<br />
vel = 60<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
t = 7<br />
pos = 280<br />
vel = 70<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
t = 8<br />
pos = 360<br />
vel = 80<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
t = 9<br />
pos = 450<br />
vel = 90<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
t = 10<br />
pos = 550<br />
vel = 100<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-
</p></blockquote>
<p>Position = <b>550</b>!?!? Why is it so far off? After 10 seconds in the simulation we have already drifted off 50 meters from where we should be. Another problem we see is that this error is accumulating [or compounding]. So as time goes on, our calculations of the particle&#8217;s positions will become farther and farther away from the truth. The solution to this problem requires a closer examination of the mathematics behind our process and Newton&#8217;s Second Law in general. In the next article, I am going to attempt to explain how this error occurs and how we can reduce it to a manageable level. </p>
<p><a href="http://blog.datasingularity.com/?p=517"><br />
<h4>Click here to view the next article of this series &#8212;></h4>
<p></a></p>
<h3>References</h3>
<blockquote><p>
Daniel Shiffman : <a href="http://www.shiffman.net/teaching/nature/">The Nature of Code</a>
</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://blog.datasingularity.com/?feed=rss2&#038;p=362</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Particle System in Processing: Beginning with Particle Animation</title>
		<link>http://blog.datasingularity.com/?p=335</link>
		<comments>http://blog.datasingularity.com/?p=335#comments</comments>
		<pubDate>Fri, 12 Mar 2010 08:27:05 +0000</pubDate>
		<dc:creator>benjamin</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Processing]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[integration]]></category>
		<category><![CDATA[particles]]></category>
		<category><![CDATA[processing.org]]></category>

		<guid isPermaLink="false">http://blog.datasingularity.com/?p=335</guid>
		<description><![CDATA[I have recently decided to take on the task of creating a particle system from scratch designed to work specifically with Processing. I have always been interested in the subject and I wanted to challenge myself and share something with the Processing community. I am going to write this series of articles to document my [...]]]></description>
			<content:encoded><![CDATA[<p>I have recently decided to take on the task of creating a particle system from scratch designed to work specifically with <a target="_blank" href="http://processing.org">Processing</a>. I have always been interested in the subject and I wanted to challenge myself and share something with the Processing community. I am going to write this series of articles to document my learning process as well as the evolution of this library. </p>
<p>For this first article, I am going to start with the most basic concepts of dealing with particles in Processing. No differential equations, no numerical methods, just simple linear algebra and Java. This one may be pretty boring to most Processing users, but I want to start off simple to establish a good base of knowledge because it will get pretty hairy later.  If you are a complete beginner, I suggest you <a href="http://processing.org/learning/">start here</a> and come back when you have a decent understanding of Processing.</p>
<h3>The &#8220;Hello World!&#8221; of particle physics</h3>
<p>The first thing we want to examine is how to draw and move a single particle. First <a target="_blank" href="http://processing.datasingularity.com/sketches/ParticlePhysicsTutorial_1/applet/">check out this code in action here</a> then come back and closely examine the source:</p>
<pre class="brush: java; title: ; notranslate">
//particle's screen coordinates
float x, y;
//particle's velocity
//velocity is change in postion
float vx, vy;   

void setup() {
 size(400, 400);
 stroke(0);
 strokeWeight(3);
 fill(150);
 smooth();
 //set position and velocity
 resetParticle();
}

void draw() {
  background(255);

  //draw the particle with diameter of 10
  ellipse(x, y, 10, 10); 

  /*
   * update the position by adding on the velocity
   * remember that velocity means incremental change
   * in position.
   */
  x += vx;
  y += vy;

}

// on a mouse click
void mousePressed() {
  resetParticle();
}

void resetParticle() {
  //reset the particle to the middle of the screen
  x = y = width/2f;    

  //set new random velocity
  // b/w - and + numbers
  vx = random(-0.39, 0.1);
  vy = random(-0.1, 0.21);
}
</pre>
<p>Let&#8217;s quickly dissect what is going on here. First we establish the two floats <b>x</b> and <b>y</b> to be the center point of the particle in screen coordinates. Hopefully you have messed with Processing or computer animation enough to understand <a target="_blank" href="http://leepoint.net/notes-java/GUI-lowlevel/graphics/10coord.html">screen coordinates</a>. Then we establish <b>vx</b> and <b>vy</b> as the velocity of our particle. As we remember in high school physics, velocity is defined as the change in position over time. In computer animation, our general unit of time is a &#8220;frame&#8221;. As you should know, the draw() function is called at the framerate that you run the program at [Processing default is 60 times a second I think]. So every time that function is called, we redraw a white background drawing over any previous frames:</p>
<pre class="brush: java; light: true; title: ; notranslate">
background(255);
</pre>
<p>then we draw the particle as an ellipse at it&#8217;s current x, y position:</p>
<pre class="brush: java; light: true; title: ; notranslate">
ellipse(x, y, 10, 10);
</pre>
<p>then we update the position one time step:</p>
<pre class="brush: java; light: true; title: ; notranslate">
x += vx;
y += vy;
</pre>
<p>and this is done 60 times a second creating the illusion of motion due to <a target="_blank" href="http://en.wikipedia.org/wiki/Persistence_of_vision">persistence of vision</a>. </p>
<h3>Adding Acceleration</h3>
<p>You may also remember from your childhood science classes that acceleration is the change in velocity over time. Quickly <a target="_blank" href="http://processing.datasingularity.com/sketches/ParticlePhysicsTutorial_2/applet/">view this code in action</a> and take note of the now non-uniform speed of the particle:</p>
<pre class="brush: java; title: ; notranslate">
float x, y;
float vx, vy;
//acceleration
float ax, ay;

void setup() {
 size(400, 400);
 stroke(0);
 strokeWeight(3);
 fill(150);
 smooth();
 //set position and velocity
 resetParticle();
}

void draw() {
  background(255);

  //draw the particle with diameter of 10
  ellipse(x, y, 10, 10); 

   /*
   * update the velocity by adding on the acceleration
   * remember that acceleration means incremental change
   * in velocity.
   */
  vx += ax;
  vy += ay;

  /*
   * update the position by adding on the velocity
   * remember that velocity means incremental change
   * in position.
   */
  x += vx;
  y += vy;

}

// on a mouse click
void mousePressed() {
  resetParticle();
}

void resetParticle() {
  //reset the particle to the middle of the screen
  x = y = width/2f;    

  //set velocity to 0
  vx = vy = 0f;

  ax = random(-0.01, 0.01);
  ay = random(0.003, 0.01);//downward
}
</pre>
<p>Now that we are adding on the acceleration to the velocity each frame, the velocity increases as time goes on and the particle moves faster and faster. Kind of like gravity (an acceleration of 9.8 m/s2) or a car accelerating faster and faster. Congratulations! We now have the ability to crudely describe Newtonian motion!</p>
<h3>Abstraction and Multiple Particles</h3>
<p>Now that we can create one particle with ease, let&#8217;s create many. Basically what we need to do is create an abstraction of what a particle is then turn that into a Java class. This isn&#8217;t a Java lesson and I hope you know what that means so let&#8217;s jump straight into it. <a target="_blank" href="http://processing.datasingularity.com/sketches/ParticlePhysicsTutorial_3/applet/">Check out this program</a> then come back and learn about the code.</p>
<pre class="brush: java; title: ; notranslate">
Particle[] particles;
int NUM_PARTICLES = 100;

void setup() {
 size(400, 400);
 stroke(0);
 strokeWeight(3);
 fill(150);
 smooth();
}

void draw() {
  background(255);
  if (particles != null) {
    for (int i = 0; i &lt; NUM_PARTICLES; i++) {
      particles[i].exist();
    }
  }
}

void mousePressed() {
  particles = new Particle[NUM_PARTICLES];
  for (int i = 0; i &lt; NUM_PARTICLES; i++) {
    particles[i] = new Particle();
  }
}

public class Particle {
  float x, y;
  float vx, vy;
  float ax, ay;

  public Particle() {
      x = mouseX;
      y = mouseY;
      vx = vy = 0f;
      ax = random(-0.2, 0.2);
      ay = random(-0.08, 0.05);
  }

  public void exist() {
     vx += ax;
     vy += ay;
     x += vx;
     y += vy;
     ellipse(x, y, 10, 10);
  }
}
</pre>
<p>Of course this is too crazy to resemble anything real in the our physical world, but it shows the point. Basically what we have done is created a Particle class which contains references to it&#8217;s own state information. Then we can have an array of Particles and update those in a nice loop. There is still some more improvement that can be done to this though. Let&#8217;s talk about vectors.</p>
<h3>Vectors</h3>
<p>A <b>Vector</b> is essentially a <b>1</b> row <b>N</b> column matrix. In computer graphics, we use the Vector data structure to represent multi-dimensional state information such as position, velocity, and acceleration. Because they are matrices and we set them to have the same dimensions, we can use standard matrix operations and concepts from linear algebra to help us solve some of the systems of linear equations we face. Processing contains it&#8217;s own implementation of a vector called a &#8220;PVector&#8221;. It is a 3-dimensional vector so we can represent things in 2d or 3d space. <a href="http://processing.datasingularity.com/sketches/ParticlePhysicsTutorial_4/applet/">Check out this re-write of the last program in action</a> and I will explain how it works after the code:</p>
<pre class="brush: java; title: ; notranslate">
ArrayList particles;
int LIFESPAN = 120;
//global gravity
PVector acceleration =  new PVector(0f, 0.025);

void setup() {
 size(400, 400);
 stroke(0);
 strokeWeight(3);
 fill(150);
 smooth();
 particles = new ArrayList();
}

void draw() {
  background(255);
  //only create when mouse moves
  if (abs(mouseX-pmouseX) &gt; 0.0001) {
    particles.add(new Particle());
  }
  for (int i = particles.size()-1; i &gt;= 0; i--) {
    Particle p = (Particle)particles.get(i);
    if(!p.exist()) {
      particles.remove(i);
    }
  }
}

public class Particle {
  PVector location;
  PVector velocity;
  int age;

  public Particle() {
      location = new PVector(mouseX, mouseY);
      //get velocity from direction and speed of mouse movement
      velocity = new PVector(mouseX-pmouseX, mouseY-pmouseY);
      age = 0;
  }

  public boolean exist() {
     velocity.add(acceleration);
     location.add(velocity);
     ellipse(location.x, location.y, 10, 10);
     if (age &gt; LIFESPAN) {
       return false;
     }
     age++;
     return true;
  }

}
</pre>
<p>Notice that I changed over the x and y variables to the PVectors and this gives us operations like add, subtract, multiply, magnitude, normalize, and etc. <a target="_blank" href="http://en.wikipedia.org/wiki/Matrix_%28mathematics%29">Check out this article on matrix math</a> if you don&#8217;t remember it from grade school. In this example, all you need to know is that when you add two PVectors, it does a matrix add. I do, however, highly suggest that you get real familiar with matrix math and systems of equations if you want to move on:</p>
<pre class="brush: java; light: true; title: ; notranslate">
velocity.add(acceleration);

//is equivalent to 

velocity.set( acceleration.x+velocity.x,
                    acceleration.y+velocity.y,
                    acceleration.z+velocity.z );
</pre>
<p>I also moved the <b>acceleration</b> vector out to have global static scope. And I am getting the velocity from the changing mouse positions. Remember that velocity is change in position, so we can get the velocity vector by subtracting the new cursor position from the old. </p>
<p>I don&#8217;t really want to go into Java stuff but notice that I also changed the array to an ArrayList. And if you are wondering why I didn&#8217;t use a parameterized ArrayList, it is b/c Processing uses a light-weight open source java compiler that doesn&#8217;t support it.</p>
<h3>Until next time</h3>
<p>That is it for now. I hope that wasn&#8217;t too boring. In the next article, I am going to talk more about vectors, different kinds of forces. I will also briefly point out the inaccuracies in our integration technique and open up a huge can of maths worms. </p>
<p><a href="http://blog.datasingularity.com/?p=362"><br />
<h4>Click here to view the next article of this series &#8212;></h4>
<p></a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.datasingularity.com/?feed=rss2&#038;p=335</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>DSO nano and synth circuit</title>
		<link>http://blog.datasingularity.com/?p=333</link>
		<comments>http://blog.datasingularity.com/?p=333#comments</comments>
		<pubDate>Thu, 04 Mar 2010 03:14:23 +0000</pubDate>
		<dc:creator>benjamin</dc:creator>
				<category><![CDATA[Hardware]]></category>
		<category><![CDATA[dsonano]]></category>
		<category><![CDATA[gumbolabs]]></category>
		<category><![CDATA[synth]]></category>

		<guid isPermaLink="false">http://blog.datasingularity.com/?p=333</guid>
		<description><![CDATA[I just wrote this article on the GumboLabs blog about the DSO nano pocket o-scope and I built a little synth circuit to test it out.]]></description>
			<content:encoded><![CDATA[<p>I just wrote <a href="http://www.gumbolabs.org/2010/03/03/dso-nano-and-synth-circuit/">this article on the GumboLabs blog</a> about the DSO nano pocket o-scope and I built a little synth circuit to test it out.</p>
<p><object width="480" height="393"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=9900653&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=A90000&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=9900653&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=A90000&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="480" height="393"></embed></object></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.datasingularity.com/?feed=rss2&#038;p=333</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Aruduino ethernet shield and Rails</title>
		<link>http://blog.datasingularity.com/?p=330</link>
		<comments>http://blog.datasingularity.com/?p=330#comments</comments>
		<pubDate>Sat, 06 Feb 2010 22:08:54 +0000</pubDate>
		<dc:creator>benjamin</dc:creator>
				<category><![CDATA[Arduino]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Hardware]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[ethernet shield]]></category>
		<category><![CDATA[gumbolabs]]></category>

		<guid isPermaLink="false">http://blog.datasingularity.com/?p=330</guid>
		<description><![CDATA[I just wrote an article on the GumboLabs blog about using the Arduino Ethernet shield. Be sure to check it out.]]></description>
			<content:encoded><![CDATA[<p>I just wrote <a href="http://www.gumbolabs.org/2010/02/05/rfid-ethernet-shield-client-rails/">an article on the GumboLabs blog</a> about using the Arduino Ethernet shield. Be sure to check it out.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.datasingularity.com/?feed=rss2&#038;p=330</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails app turns seedbox into mediacenter</title>
		<link>http://blog.datasingularity.com/?p=303</link>
		<comments>http://blog.datasingularity.com/?p=303#comments</comments>
		<pubDate>Sun, 10 Jan 2010 06:09:15 +0000</pubDate>
		<dc:creator>benjamin</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://blog.datasingularity.com/?p=303</guid>
		<description><![CDATA[Well, it has been a while since a post. I am glad to get something back up here. I am just coming coming up for air from a long stretch of work. I wanted to waste a little time so I decided to make an improvement on my custom seedbox / media center. If you [...]]]></description>
			<content:encoded><![CDATA[<p>Well, it has been a while since a post. I am glad to get something back up here. I am just coming coming up for air from a long stretch of work. I wanted to waste a little time so I decided to make an improvement on my custom seedbox / media center. If you want to read a little about it, <a href="http://blog.datasingularity.com/?p=193">check this post</a>. </p>
<p>Anyway, what I wanted to do is have a webpage served from my seedbox that displays all the movies on the system with a link to imdb and a link to play the movie. The link to play the movie would create a &#8216;vlcrc&#8217; subprocess and open up a new window with the controls. This way, anyone on my network, using a laptop or phone, could open up the page and choose a movie and it would play on my TV. </p>
<p>This initially seemed really complicated when I came up with the idea last year and I had started writing a pretty thorough Rails app to do it. Then I got tired of it and forgot about it. Like most code I write, I realized that unless money was involved I am too lazy to do it right and usually settle for a hack. </p>
<p>The hack resulted in this python cgi script:</p>
<pre class="brush: python; title: ; notranslate">
#!/usr/bin/env python
import cgi
import cgitb
import os, subprocess
cgitb.enable()

MOVIE_DIRECTORY = &quot;/media/MEDIA/media_backup/videos/films&quot;
MY_IP = &quot;192.168.0.100&quot;
VLC_HTTP_LINK = &quot;http://&quot; + MY_IP + &quot;:8080&quot;

form = cgi.FieldStorage()
movie_to_play = form.getvalue('movie')

print &quot;Content-type: text/html&quot;
print

movies = [mov for mov in
os.listdir(MOVIE_DIRECTORY) if (mov[-3:] == 'avi' or mov[-3:] == 'mov' or mov[-3:] == 'mpg')]

# print
print &quot;&quot;&quot;
&lt;html&gt;&lt;head&gt;&lt;title&gt;Ben's Movies&lt;/title&gt;&lt;/head&gt;&lt;body&gt;
&lt;font size=&quot;4&quot; face=&quot;Verdana&quot;&gt;&quot;&quot;&quot;

if movie_to_play:
    command = &quot;vlcrc %s&quot; % MOVIE_DIRECTORY+'/'+movie_to_play
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
    #print process.communicate()
    #retval = subprocess.call(command, 0, None, None, outptr, errptr)
    print &quot;&quot;&quot;
             &lt;script&gt;
                  window.open('%s','%s','width=400,height=200');
             &lt;/script&gt;
          &quot;&quot;&quot; % (VLC_HTTP_LINK, movie_to_play)
    print &quot;Playing: &quot;+ movie_to_play

print &quot;&quot;&quot;
&lt;/center&gt;&lt;table border=&quot;1&quot;&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;Title&lt;/th&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;&lt;/th&gt;
&lt;/tr&gt;
&quot;&quot;&quot;

base_play_link = &quot;http://&quot; + MY_IP + &quot;/cgi-bin/movies.py?movie=%s&quot;
base_imdb_link = 'http://www.imdb.com/find?s=all&amp;q=%s'

i = 1

for mov in movies:
    nice_mov = mov[:-4] #get rid of extension
    nice_mov = nice_mov.replace('_', ' ') #make it more human readble
    imdb_link = base_imdb_link % nice_mov.replace(' ', '+')
    play_link = base_play_link % mov
    print &quot;&quot;&quot;
          &lt;tr&gt;
              &lt;td&gt;%d&lt;/td&gt;
              &lt;td&gt;%s&lt;/td&gt;
              &lt;td&gt;&lt;a target=&quot;_blank&quot; href=&quot;%s&quot;&gt;IMDB Info&lt;/a&gt;&lt;/td&gt;
              &lt;td&gt;&lt;a href=&quot;%s&quot;&gt;Play&lt;/a&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &quot;&quot;&quot; % (i, nice_mov, imdb_link, play_link)
    i += 1

print &quot;&quot;&quot;
&lt;/table&gt;&lt;/center&gt;&lt;/font&gt;&lt;/body&gt;&lt;/html&gt;
&quot;&quot;&quot;
</pre>
<p>For some reason handling the vlc subprocess was not working for me. I am guessing that it has something to do with the permissions that the cgi script have when trying to execute a subprocess? I don&#8217;t know and I didn&#8217;t fight it too hard. So instead of fixing it, I just wrote a Rails app. You can <a href="http://datasingularity.com/code/misc/moviedb.tar.gz">download it here</a>.</p>
<p>It basically works exactly the same way. First let&#8217;s look at the main controller [BTW, please don't make fun of my ruby, it has been a while :) ]. Also, my source code viewer adds IO twice!!??!?! Should just be IO.popen</p>
<pre class="brush: ruby; title: ; notranslate">
class MainController &lt; ApplicationController

    MOVIE_DIRECTORY = &quot;/media/MEDIA/media_backup/videos/films&quot;
    MY_IP = &quot;192.168.0.100&quot;
    VLC_HTTP_LINK = &quot;http://&quot; + MY_IP + &quot;:8080&quot;
    BASE_IMDB_LINK  = &quot;http://www.imdb.com/find?s=all&amp;q=&quot;

    def index
        @ip = MY_IP
        @vlc_link = VLC_HTTP_LINK
    	@movies = Dir.new(MOVIE_DIRECTORY).entries.find_all{|item| item =~ /.avi$/ or item =~ /.mpg$/ or item =~ /.wmv$/ or item =~ /.mp4$/}
        @movie_to_play = params[:movie]
         if @movie_to_play
	     system(&quot;killall vlc&quot;)
	     vlcpipe = IO.popen(&quot;vlcrc &quot;+MOVIE_DIRECTORY+&quot;/&quot;+@movie_to_play)
         end
    end

end
</pre>
<p>This is the only controller. It pulls all the movies from the &#8216;films&#8217; folder on my hard-drive. I name all my movie files by the title with underscores instead of spaces, for example <em>2001_A_Space_Odyssey.avi</em>. After it gets all the movies, it checks the request for a parameter named &#8216;movie&#8217;. If there is a movie, it kills any instances of vlc, if there are any running, it then runs my little vlcrc bash script. That script ensures the DISPLAY is set to my TV and starts up vlc using <a href="http://www.videolan.org/doc/vlc-user-guide/en/ch05.html">the http interface</a>. Once again, refer to <a href="http://blog.datasingularity.com/?p=193">my last post</a>. </p>
<p>Next let&#8217;s look at the view. First the helper file:</p>
<pre class="brush: ruby; title: ; notranslate">
module MainHelper

    def nice_name(movie)
    	movie[0..movie.length-5].gsub('_', ' ')
    end

    def imdb_link(movie)
        link = &quot;http://www.imdb.com/find?s=all&amp;q=&quot;+movie.gsub('_', '+')[0..movie.length-5]
    	return &quot;&lt;a href='&quot;+link+&quot;' target='_blank'&gt;IMDB Info&lt;/a&gt;&quot;
    end

    def play_link(movie)
    	&quot;&lt;a href='/main/index?movie=&quot;+movie+&quot;'&gt;Play&lt;/a&gt;&quot;
    end

end
</pre>
<p>Then the index.html.erb template:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Ben's Movies&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;font size=&quot;4&quot; face=&quot;Verdana&quot;&gt;

   &lt;center&gt;
     &lt;h2&gt; There are currently &lt;%= @movies.length %&gt; movies on this machine &lt;/h2&gt;
    &lt;% if @movie_to_play %&gt;
	   &lt;div style=&quot;background-color:#9ACD32; color:#FFFFFF; visibility: visible&quot;&gt;&lt;p&gt;Now Playing &lt;b&gt;&lt;%= @movie_to_play %&gt;&lt;/b&gt;&lt;/p&gt;&lt;/div&gt;
           &lt;script&gt;
                 function open_vlc_window() {
                    window.open('&lt;%= @vlc_link %&gt;','&lt;%= @movie_to_play %&gt;','width=600,height=385');
                 }
                 setTimeout(&quot;open_vlc_window()&quot;,1250);//slight delay, vlc needs a second to start up
           &lt;/script&gt;
        &lt;% end %&gt;
        &lt;table border=1&gt;

          &lt;% @movies.each do |movie| %&gt;
              &lt;tr&gt;
                 &lt;td&gt;&lt;%= nice_name(movie) %&gt;&lt;/td&gt;
                 &lt;td&gt;&lt;%= imdb_link(movie) %&gt;&lt;/td&gt;
                 &lt;td&gt;&lt;%= play_link(movie) %&gt;&lt;/td&gt;
              &lt;/tr&gt;
          &lt;% end %&gt;

        &lt;/table&gt;
        &lt;/center&gt;
      &lt;/font&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Ugh, ugly code, useless declarations, poor ruby practices, oh well. Anyways, how it works should be pretty obvious. I had previously written a service to pull down the synopsis info for a movie but all that was too complicated so i just made the link a search on imdb. If the movie name is unique, it will jump straight to the page, if not, it will ask you to choose between movies with the same or similar names by just executing a standard search.</p>
<p>Here is the home page:</p>
<div id="attachment_309" class="wp-caption aligncenter" style="width: 310px"><a href="http://blog.datasingularity.com/wp-content/uploads/2010/01/moviedb1.png" target="_blank"><img src="http://blog.datasingularity.com/wp-content/uploads/2010/01/moviedb1-300x260.png" alt="Home Page" title="moviedb1" width="300" height="260" class="size-medium wp-image-309" /></a><p class="wp-caption-text">Home Page</p></div>
<p>Then we click play on Adaptation:</p>
<div id="attachment_310" class="wp-caption aligncenter" style="width: 310px"><a href="http://blog.datasingularity.com/wp-content/uploads/2010/01/noviedb2.png" target="_blank"><img src="http://blog.datasingularity.com/wp-content/uploads/2010/01/noviedb2-300x161.png" alt="Play button pushed" title="moviedb2" width="300" height="161" class="size-medium wp-image-310" /></a><p class="wp-caption-text">Play button pushed</p></div>
<p>It informs us of the movie that is playing with the green status bar and the ajax remote control box pop up. It is sized to be as small as needed:</p>
<div id="attachment_311" class="wp-caption aligncenter" style="width: 310px"><a href="http://blog.datasingularity.com/wp-content/uploads/2010/01/moviedb3.png" target="_blank"><img src="http://blog.datasingularity.com/wp-content/uploads/2010/01/moviedb3-300x217.png" alt="vlc control interface" title="moviedb3" width="300" height="217" class="size-medium wp-image-311" /></a><p class="wp-caption-text">vlc control interface</p></div>
<p>You can play, stop, pause, toggle fullscreen, change the volume, and there is even a seek bar. The best thing about it is that this is all javascript so it works pretty well on all browsers, even phone browsers. It fits nicely on my G1 :)</p>
<p>If you click on another movie, the vlc instance is killed as expected and a new one is started. All that is left to do is create an init.d bash script to start up the mongrel server on port 80 on boot up and maybe map your ip to a name if you have the means.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.datasingularity.com/?feed=rss2&#038;p=303</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Parallax RFID reader  Arduino</title>
		<link>http://blog.datasingularity.com/?p=296</link>
		<comments>http://blog.datasingularity.com/?p=296#comments</comments>
		<pubDate>Sat, 24 Oct 2009 00:36:21 +0000</pubDate>
		<dc:creator>benjamin</dc:creator>
				<category><![CDATA[Arduino]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Hardware]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://blog.datasingularity.com/?p=296</guid>
		<description><![CDATA[I just recently wrote an article at the Gumbo Labs blog on interfacing to the Parallax RFID reader. Here is the final code if you are only looking for that:]]></description>
			<content:encoded><![CDATA[<div id="attachment_297" class="wp-caption aligncenter" style="width: 240px"><a href="http://blog.datasingularity.com/wp-content/uploads/2009/10/28140-m-230x300.jpg"><img class="size-full wp-image-297" title="28140-m-230x300" src="http://blog.datasingularity.com/wp-content/uploads/2009/10/28140-m-230x300.jpg" alt="Parallax RFID reader" width="230" height="300" /></a><p class="wp-caption-text">Parallax RFID reader</p></div>
<p>I just recently wrote an article at the Gumbo Labs blog on <a href="http://www.gumbolabs.org/2009/10/17/parallax-rfid-reader-arduino/" target="_blank">interfacing to the Parallax RFID reader</a>. Here is the final code if you are only looking for that:</p>
<pre class="brush: cpp; title: ; notranslate">
/**
 * author Benjamin Eckel
 * date 10-17-2009
 *
 */
#define RFID_ENABLE 2   //to RFID ENABLE
#define CODE_LEN 10      //Max length of RFID tag
#define VALIDATE_TAG 1  //should we validate tag?
#define VALIDATE_LENGTH  200 //maximum reads b/w tag read and validate
#define ITERATION_LENGTH 2000 //time, in ms, given to the user to move hand away
#define START_BYTE 0x0A
#define STOP_BYTE 0x0D

char tag[CODE_LEN];  

void setup() {
  Serial.begin(2400);
  pinMode(RFID_ENABLE,OUTPUT);
}

void loop() {
  enableRFID();
  getRFIDTag();
  if(isCodeValid()) {
    disableRFID();
    sendCode();
    delay(ITERATION_LENGTH);
  } else {
    disableRFID();
    Serial.println(&quot;Got some noise&quot;);
  }
  Serial.flush();
  clearCode();
} 

/**
 * Clears out the memory space for the tag to 0s.
 */
void clearCode() {
  for(int i=0; i&lt;CODE_LEN; i++) {
    tag[i] = 0;
  }
}

/**
 * Sends the tag to the computer.
 */
void sendCode() {
    Serial.print(&quot;TAG:&quot;);
    //Serial.println(tag);
    for(int i=0; i&lt;CODE_LEN; i++) {
      Serial.print(tag[i]);
    }
}

/**************************************************************/
/********************   RFID Functions  ***********************/
/**************************************************************/

void enableRFID() {
   digitalWrite(RFID_ENABLE, LOW);
}

void disableRFID() {
   digitalWrite(RFID_ENABLE, HIGH);
}

/**
 * Blocking function, waits for and gets the RFID tag.
 */
void getRFIDTag() {
  byte next_byte;
  while(Serial.available() &lt;= 0) {}
  if((next_byte = Serial.read()) == START_BYTE) {
    byte bytesread = 0;
    while(bytesread &lt; CODE_LEN) {
      if(Serial.available() &gt; 0) { //wait for the next byte
          if((next_byte = Serial.read()) == STOP_BYTE) break;
          tag[bytesread++] = next_byte;
      }
    }
  }
}

/**
 * Waits for the next incoming tag to see if it matches
 * the current tag.
 */
boolean isCodeValid() {
  byte next_byte;
  int count = 0;
  while (Serial.available() &lt; 2) {  //there is already a STOP_BYTE in buffer
    delay(1); //probably not a very pure millisecond
    if(count++ &gt; VALIDATE_LENGTH) return false;
  }
  Serial.read(); //throw away extra STOP_BYTE
  if ((next_byte = Serial.read()) == START_BYTE) {
    byte bytes_read = 0;
    while (bytes_read &lt; CODE_LEN) {
      if (Serial.available() &gt; 0) { //wait for the next byte
          if ((next_byte = Serial.read()) == STOP_BYTE) break;
          if (tag[bytes_read++] != next_byte) return false;
      }
    }
  }
  return true;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.datasingularity.com/?feed=rss2&#038;p=296</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

