Tuesday 22 January 2013

Speed measurement with Arduino (2)


To continue my first post on speed measurement I will show how I made the arduino part more "interesting" and connected it to flash and as3.

At the end of the post I will attach the files for download.

For connecting arduino with flash I used TinkerProxy, has instructions on how to use it so I will not get into details. 
The flash file will receive the speed value and will capture a picture from the webcam. (Note, for my project I used a webcam to take pictures of the objects that passing). Also it adds to the picture the time stamp and the speed. (processing the image at the runtime). The picture is then saved to the server with a php script.

You can get creative and set a certain threshold :)

AS3 script:

//File downloaded from www.riacodes.com
// Modified by Claudiu Cristian on 28.11.2011
import flash.display.Bitmap;
import flash.display.BitmapData;
import com.adobe.images.JPGEncoder;
import flash.net.FileReference;
import com.SerialPort;
var finalSpeed:Number = 0;
var cam:Camera = Camera.getCamera();
var video:Video = new Video(320,240);
var phpPath:String;
var sendReq:URLRequest;
/*
Connecting with arduino
*/
//Character that delineates the end of a message received from the Arduino
const EOL_DELIMITER:String = "\n";
// accumulates data coming from arduino
var sensorData:String = "";
var speed:Number=0;
// connects to arduino board
var arduino:SerialPort = new SerialPort();
arduino.addEventListener(DataEvent.DATA, onArduinoData );
arduino.connect( "127.0.0.1", 5331 );
function onArduinoData( event:DataEvent ):void {
//trace( "onArduinoData", event.data );
// add to sensor data
sensorData +=  event.data;
// if it finds newline the packet of sensor data is done
if (sensorData.indexOf(EOL_DELIMITER) > 0 ) {
// process sensor data
//trace(parseFloat(event.data));
speed = parseFloat(event.data);
computeSpeed();
}
}
function computeSpeed() {
if (isNaN(speed) == false &&  speed % 1 != 0 ) {
finalSpeed = speed * 3.6;
captureImage();
saveImage();
}
else {
finalSpeed=0;
}
trace(roundDecimals(finalSpeed, 2));
sensorData="";
}
function roundDecimals(num:Number, numDecimalPlaces:int):Number {
return Math.round(num * Math.pow(10, numDecimalPlaces) ) / Math.pow(10, numDecimalPlaces);
}
video.attachCamera(cam);
video.x = 20;
video.y = 20;
addChild(video);
var bitmapData:BitmapData = new BitmapData(video.width,video.height);
var bitmap:Bitmap = new Bitmap(bitmapData);
bitmap.x = 360;
bitmap.y = 20;
addChild(bitmap);
function captureImage():void
{
bitmapData.draw(video);
//render the text
drawString(bitmapData,fileName1 + roundDecimals(finalSpeed, 2),10,200);
// display the result...
//addChild(Bitmap (bitmapData));
}
var i:Number = 1;
var fileRef:FileReference = new FileReference();

// script taken from http://www.beautifycode.com/webcam-flash-php-upload-to-server
//and modiffied
function saveImage():void
{
var encoder:JPGEncoder = new JPGEncoder(90);
var ba:ByteArray = encoder.encode(bitmapData);
    var sendHeader:URLRequestHeader = new URLRequestHeader("Content-type","application/octet-stream");
phpPath = "http://localhost/saveimg.php"

    sendReq = new URLRequest(phpPath);
    sendReq.requestHeaders.push(sendHeader);
    sendReq.method = URLRequestMethod.POST;
    sendReq.data = ba;

    var sendLoader:URLLoader;
    sendLoader = new URLLoader();
    sendLoader.load(sendReq);
}
function drawString(target:BitmapData,text:String,x:Number,y:Number):void
{
var tf:TextField = new TextField();
tf.width = 300;
tf.text = text;
var myFormat:TextFormat = new TextFormat();
//Giving the format a hex decimal color code
myFormat.color = 0xFF0000;
//Adding some bigger text size
myFormat.size = 12;
//Last text style is to make it bold.
myFormat.bold = true;
//Now the most important thing for the textformat, we need to add it to the myTextField with setTextFormat.
tf.setTextFormat(myFormat);
var bmd:BitmapData = new BitmapData(tf.width,tf.height,true,0x00000000);
bmd.draw(tf);
var mat:Matrix = new Matrix();
mat.translate(x,y);
target.draw(bmd,mat);
bmd.dispose();
}
var my_timer:Timer=new Timer(1000);
my_timer.addEventListener(TimerEvent.TIMER, onTimer);
my_timer.start();
var fileName:String;
var fileName1:String;
var txtDisplay:TextField = new TextField();

//Here we add the new textfield instance to the stage with addchild()
addChild(txtDisplay);

//Here we define some properties for our text field, starting with giving it some text to contain.
//A width, x and y coordinates.
txtDisplay.x = 20;
txtDisplay.y = 360;

//Here are some great properties to define, first one is to make sure the text is not selectable, then adding a border.
txtDisplay.selectable = false;
txtDisplay.border = true;

//This last property for our textfield is to make it autosize with the text, aligning to the left.
txtDisplay.autoSize = TextFieldAutoSize.LEFT;

function onTimer(e:TimerEvent):void {
var today_date:Date = new Date();
var thismonth:uint = today_date.getMonth();
var today_time;
var currentTime:Date = new Date();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var hours = currentTime.getHours() * 30 + currentTime.getMinutes() / 2;
var monthArr:Array = new Array('Jan','Feb','March','April','May','June','July','August','September','October','November','December');
fileName = (today_date.getDate()+ " " +monthArr[thismonth]+ " " +today_date.getFullYear()+"  "+currentTime.hours + ":" + currentTime.minutes + ":" + currentTime.seconds);
txtDisplay.text = "Date & Time "+fileName + " | " +"Object speed:" + roundDecimals(finalSpeed, 2) ;
}
PHP script:

<?php
if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] )) {
    $uniqueStamp = date(U);
    $filename = $uniqueStamp.".jpg";
    $fp = fopen( $filename,"wb");
    fwrite( $fp, $GLOBALS[ 'HTTP_RAW_POST_DATA' ] );
    fclose( $fp );

    echo "filename=".$filename."&base=".$_SERVER["HTTP_HOST"].dirname($_SERVER["PHP_SELF"]);
}
?>


Flash file  PHP file



Resources
http://code.google.com/p/tinkerit/wiki/TinkerProxy
http://www.riacodes.com/flash/captures-images-from-the-webcam-and-save-them-to-thedesktop/
http://www.beautifycode.com/webcam-flash-php-upload-to-server#php
http://www.ladyada.net/learn/sensors/cds.html




1 comment:

Unknown said...

how to connect both webcam and a laptop usb for data into an arduino uno??
can arduino due be used for this???