CodeSnips

Friday, March 29, 2013

Arduino - Sending Serial Data

Playing with Arduino Uno board. The language for Arduino "sketches" is essentially java.

This script reads the value on analog pin 0 and write the value on the serial port every 150 milliseconds.


const int SENSOR = 0;
const int LED = 13;

int val = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(LED,OUTPUT);
  digitalWrite(LED,LOW);
}

void loop()
{
  val = analogRead(SENSOR);
  Serial.println(val);
  delay(150);
}
You then just need a client that reads the data and displays it in some clever way. The companion language for clients for Arduino is "Processing" - a java library that makes it easy to write graphical clients. There is also a companion version - Processing.js - written by John Resig that cleverly compiles Processing code into Javascript so that programs written in this language can be displayed on web pages without the need for a java applet.
The following Processing script displays an eye graphic that changes pupil size based on the relative brightness of light sensed on the analog pin 0 (via a photoresistor).

// This sketch uses serial IO to communicate with the Arduino.
// The Arduino is writing out values from
// analog input 0 - which in this case has a photoresistor
// on it.
//
// The code auto-scales based on lowest and highest readings
// and draws a "pupil" in proportion to the amount of light
// sensed.
//
import processing.serial.*;

Serial myPort;
int minval=9999;
int maxval=0;
float r=0;
int a0;
PFont f;

void setup() {
  size(200, 200);
  myPort = new Serial(this,"/dev/cu.usbmodemfd121",9600);
  myPort.clear();
  f = createFont("Krungthep",20,true);
  smooth();
}

// Reads string between two delimiters in serial stream 
String readLine(Serial p,int firstDelim, int secondDelim) {
  StringBuilder sb = new StringBuilder();
  Boolean isFirstDelim = false;
  int c;
  while (true)
  {
    while ((c = p.read()) < 0);
    if (!isFirstDelim)
    {
      if (c != firstDelim)
        continue;
      isFirstDelim = true;
    }
    else
    if (c != secondDelim)
      sb.append((char)c);
    else
      break;
  }  
  return sb.toString();
}

void getReading()
{
  String line;
  if (myPort.available()>0) {
    line = readLine(myPort,10,13);
    if (line != null && line.length()>0)
      a0 = Integer.parseInt(line);
  }
}

void draw() {
  background(255);
  textFont(f);
  textAlign(CENTER);
  getReading();
  if (a0 < minval) minval = a0;
  if (a0 > maxval) maxval = a0;
  if (maxval==minval || abs(maxval-minval) <= 20)
      r=60;
  else
  {
      r = (float) abs(a0-minval) / (float) abs(maxval-minval);
      r *= 50;
      r += 10;
  }
    
  pushMatrix();
  translate(20,40);
  drawEye(r);
  popMatrix();
  
  fill(0,127,127);
  text("A0="+a0,width/2,height-25);
  
  if (mousePressed)
  {
    minval = 9999;
    maxval = 0;
  }
  
}

void drawEye(float pupilSize)
{
    int theta=0;
    pushStyle();
    stroke(0);
    noFill();
    bezier(0,40,30,-12,130,-12,160,40);
    bezier(0,40,30,92,130,92,160,40);
    pushMatrix();
    fill(#9B9DF7);
    ellipse(80,40,80,80);
    translate(80,40);
    for (int i=0;i<360;i+=(360/12))
    {
        rotate((2*PI)/12); 
        line(-40,0,40,0);
    }
    fill(0);
    ellipse(0,0,pupilSize,pupilSize);
    fill(255);
    ellipse(15,-15,8,8);
    popMatrix();
    popStyle();
}


Thursday, March 21, 2013

Javascript from C#, JInt, Jurrasic

Just a quick code snippet. I was interested in executing javascript from C#. So far, the two clear winners for a framework to do this are JInt and Jurrasic.  Needless to say, the V8 Javascript.Net project is dead and doesn't even try to pretend otherwise...
JScript .Net has been dead a long time - let's not even go there.

Jurassic takes a bit more effort to integrate existing .Net objects into scripts as parameters, but makes perhaps is faster.

JInt is the easiest to use and integrate (takes objects directly as parameters) - and for quick DSL-like scripting using Javascript - wins my vote.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Jint;
using Jurassic;
using Newtonsoft.Json;

namespace RunJSInt
{
    public class Program
    {

        static void Main(string[] args)
        {
            JintExample();
            JurrasicExample();
            Console.ReadLine();
        }

        public class Developer
        {
            public string Name { get; set; }
            public string Title { get; set; }
        }

        public class DeveloperObjectInstance : Jurassic.Library.ObjectInstance
        {
            public DeveloperObjectInstance(ScriptEngine engine) : 
                base(engine)
            {

            }
            public void init(Developer dev)
            {
                this["Name"] = dev.Name;
                this["Title"] = dev.Title;
            }
        }

        private static void JurrasicExample()
        {
            var dev = new Developer { Name = "Mike", Title = "Developer" };
            var engine = new Jurassic.ScriptEngine();
            var obj = new DeveloperObjectInstance(engine);
            obj.init(dev);
            engine.Evaluate(@"function test(a) { 
                                  return 'Jurrasic says, hello ' + a.Name; 
                            }");
            Console.WriteLine(engine.CallGlobalFunction("test",obj));
        }


        static void JintExample()
        {
            var dev = new Developer { Name = "Mike", Title = "Developer" };
            JintEngine engine = new JintEngine();
            engine.SetParameter("message", dev);
            var result = engine.Run(@"
                return 'Jint says, hello ' + message.Name;");
            Console.WriteLine(result);
        }
    }
}