Gists are short code snippets that are useful for quick and simple code sharing. However, with all the functions provided by GitHub, gists are useful for much more than that: they are git repositories that have limited functions, but are versioned, can be forked, can be public/private, and can have their code embedded in web pages. It is this last feature I will use to show how the code that is stored and managed in a gist can be executed on a page.
Continue reading Dynamic execution of embedded gistsI have been programming in Lua for about 9 months and it seemed like a good time to pause and reflect on my experience with it. I have used various languages over the years -- Perl (soaplite.com, and other projects, including my current consulting work), C (DHCPLite and a ping-pong juggling robot), JavaScript (experiments with Google Maps and canvas), MATLAB (ping-pong juggling robot), and others, from Turbo Pascal to F# -- and it was interesting to see how Lua compares to the other languages I've worked with. I have done different types of projects in Lua: a remote debugger (MobDebug), extending a Lua IDE (ZeroBrane Studio), a mobile app (LuaRemote), several educational scripts (EduPack), and a demo of drawing on browser canvas with Lua.
I have come across several detailed lists that mention good and not-so-good parts of Lua (for example, Lua benefits, why Lua, why Lua is not more widely used, advantages of Lua, Lua good/bad, Lua vs. JavaScript, and Lua Gotchas), but I found that some of the features that tripped me or that I cared about were not listed, so I put together my own list. It is far from being comprehensive and some aspects of the language are not covered (for example, math and string libraries), but it captures the gist of my experience with the language.
Continue reading Lua: Good, bad, and ugly partsI have been working on getting Lua to run in a browser and was asked how much slower it is comparing to JavaScript. I put together two pages -- one for Lua and one for JavaScript -- to run the equivalent code to measure its performance and got a surprising result: Lua reliably outperformed JavaScript with the following code:
Lua
local canvas = document:getElementById("canvas")
canvas.width = canvas.width -- clear the canvas
local ctx = canvas:getContext("2d")
ctx.fillStyle = "rgb(200,0,0)"
ctx:fillRect(130, 130, 50, 50)
ctx.fillStyle = "rgba(0, 0, 200, 0.1)"
for i = 1, 100 do
ctx:fillRect(math.random(0, 300), math.random(0, 300), 50, 50)
end
JavaScript
var canvas = document.getElementById("canvas");
canvas.width = canvas.width
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect(130, 130, 50, 50);
ctx.fillStyle = "rgba(0, 0, 200, 0.1)";
for (i = 1; i<=100; i++) {
ctx.fillRect(Math.random()*300, Math.random()*300, 50, 50);
} Continue reading Can Lua be faster than JavaScript in a browser?
As I was working on my turtle library that runs on a desktop, I thought it would be useful to have a way to execute the same Lua code in a browser (as a way to demonstrate/share the result). There are several options to get Lua to run in a browser, but most of them can be placed in one of two categories: re-writing Lua VM in JavaScript (like emscripten) and translating Lua into JavaScript (like lua.js). There is also an option of writing a Lua VM in some other language, but this would require a plugin to be installed, with all associated hassles. Lua VM approach provides an option of full compatibility (as you would be running a regular Lua VM, just implemented in JavaScript), but tends to be slow. Translation to Lua gives you more speed (as the browser executes the JavaScript code of your application rather than VM) at the cost of not having Lua features that don't exist in JavaScript (like non-string keys in tables, coroutines, and some other things). As I was looking for a way to run simple scripts that work with graphics, the speed was more important than a full set of Lua features, so I decided to try lua.js.
Continue reading Drawing on browser canvas with LuaThe Arduino streaming using AJAX example provides a simple way to access analog and digital ports on Arduino over WiFi, but one of its deficiencies is the challenge of configuring WiFi. It establishes its own network, but is not able to connect to any of the existing network, which may be the configuration you prefer. It is easy to modify the code to make it connect to an access point, but the configuration would be hardcoded and any change would require a new firmware upload.
Since the example already provides a simple web interface, wouldn't it be convenient to have a way to update board's WiFi configuration from a browser and make the board to store and use that configuration? This is exactly what I am about to discuss.
Continue reading Storing WiFi configuration in EEPROM on ArduinoThis version of the library (v0.12) added support for Arduino 1.0. You can now use the same code with both Arduino 0.2x and Arduino 1.0.
The previous update (v0.10) also fixed an issue with iOS clients and have been confirmed to work with iPhone (iOS version 2) and iPad (iOS version 5). If you still having troubles for getting it to work with iOS clients, please send me an email with details.
In their last Request for Startups Y Combinator posed an interesting question: What are people going to do for fun in 20 years instead of what they do now? I asked my sixteen year old son and his idea was that in 20 years movies and TV are going to be much more interactive down to the ability to participate in the plot line and change it on the fly. According to him, there will be some sort of artificial intelligence that will be able to build a new story line, somewhat similar to the popular Choose Your Own Adventure book series. I think this is an interesting idea and may be definitely possible in 20 years, but something that doesn't really pull people away from screens.
My idea is different. I think with the current advances in miniaturization, robotics, open-source hardware, 3-d printing, connectivity, and mobile devices will lead to the ability of a large chunk of the population to mass-produce things for fun. This is in many ways similar to the role artisans or craftsmen played prior to the Industrial Revolution. The products they build will not be passive, like the vast majority of the currently produced items or tools is; they will be interactive, entertaining, and practical. In the same way as mobile devices enabled a market for mobile applications, in many cases simple and created by someone without much experience in the field, these advances will create opportunities for people to design, prototype, and niche-produce items that other people will find interesting to interact with. Niche-produce means producing 100-10,000 items, which is larger, than an individual craftsman can produce and smaller than mass production would bother with. These ideas are already being explored with Kickstarter-funded projects, using crowd-funding, which will also be leveraged by this new wave of artisans. I also believe that while connectivity and computers will play a critical role in this process, the focus of the activity will migrate back to the physical world and the items produced will take the form of physical goods more than virtual services or mobile applications.
As I have been working on the Turtle graphics library for my son, I realized that the traditional model with OnPaint event that draws everything that needs to be drawn is not very suitable for what I wanted to have. I wanted to be able to draw when I need to and avoid re-drawing everything that has been drawn so far (or at least do it in an easy way). After a bit of reading and experimenting with wxWidgets, it turned out to be not that difficult. There are four main ideas.
Continue reading Drawing outside of OnPaint with wxWidgetsI was looking for a way to combine a sequence of PNG files that were generated by the turtle library I have been working on and it turned out to be easy using ImageMagick. The command to use is:
> convert -delay 40 -loop 1 tree*.png trees.gif
This will generate an animated GIF file with 40ms delay between images that will play once (-loop 1). You can use -loop 0 value to loop indefinitely. Here is the image that was generated:
If you do not see any animation and see the grass, it means that the animation is already over (as it loops only once). You can reload the page or click on the image to see it again. It turned out that some browsers (like Firefox) do very aggressive caching of images, including animated images, and will not replay it after page reload and even if you open the same image on a different page (as long as it references the same URL). I used a simple JavaScript trick to dynamically generate a unique URL, which will allow you to see the animation when you click on the link:
<a href="/images/turtle-trees.gif"
onclick="javascript:this.href += '?' + Math.random()">
this refers to the object that the onlick event is triggered for (the a tag in this case) and its href attribute is modified with a random query parameter (which is ignored by the browser in this case).
I have been working on a simple Turtle graphics library for my seven year old son and showed him some intermediate results. One of them was a simple fractal tree that looked like this:

My son immediately got excited and wanted to come up with possible ways to change the drawing. His first idea was to color the tree and to make the trunk brown and the leaves green. Then he wanted to make the trunk wider. After that he wanted a smaller tree and grass. Then he wanted to add flowers; at this point I decided to stop, as the tree already looked good and the flowers required a different fractal. Here is the tree we generated:

I participated in the 6th Annual Science and Technology Showcase organized by UW SEBA organization. This was an opportunity to present and discuss a project or technology with potential to start a company. The event included a poster presentation to 10 judges and a one minute pitch to the group of judges and students (about 150-200 people). My presentation was about the project I have been working on for the past 9 months on developing a robot, software, and educational materials to help middle- and high-school students learn science working on projects with friends. I didn't get the main prize ($1000), but did get a cash prize for the most enthusiastic entrepreneur.
I have been working on a Lua IDE (ZeroBrane Studio) and wanted to re-format a large number of Lua files to satisfy my style preferences. I did find a nice Lua beautifier (also written in Lua), but it didn't handle many of the cases that were present in the code I was working with and I didn't want to make any manual changes. I ended up using the same approach, but completely rewrote it in Perl as its regular expressions are a tad more powerful. I'm sure that all this can be re-implemented in Lua, but I didn't have time. Lua regular expressions are simple and quite flexible, but one of the simple features I miss is the ability to add modifiers to groups. For example, I can write %d+ to indicate 1 or more digits (same as \d+ in Perl), but I can't write (local )? to indicate an optional group.
I decided to include an AJAX example that works with streaming data from Arduino in the last version my DHCPLite library. I already showed how the library allows you to point your browser to http://arduino/ and get "Hello, World!" back. Now I wanted to actually read the data from a digital or an analog input and show the result as a number and paint it as a circle (using browser canvas).
The model is simple: a request to a URL like "http://arduino/A1" returns an HTML page that includes JavaScript code that periodically retrieves data from URL "http://arduino/A1=", which returns the actual value read from analog pin 1. Similarly, requests for A# and D# retrieve and return current values read from those pins. The result looks like this:
Continue reading Streaming real-time data from Arduino using AJAX and persistent connectionsThis version of the library added options for renewal and rebinding timers and a new example with AJAX processing that streams real-time data from Arduino.
The library now works correctly with Mac OS clients, but still doesn't work with iPhone (iOS versions 2 and 4) and iPad (iOS version 5). If someone knows what needs to be fixed, please send me an email.
I have been working on my Arduino-based robot and wanted to have a way to run several devices on the same ad-hoc network and use their host names rather than their IP addresses.
It turned out that there was nothing available that worked out of the box. I tried several libraries, but some didn't have DNS server functionality, some were for the Ethernet library, which wasn't compatible with my shield (RedFly), and some simply didn't work.
First step was to get DHCP working. The sequence of DHCP messages is simple, but the format is not so much; it took me several attempts to get the format to be correct enough for the client to take the response. Wireshark was invaluable in showing the messages and giving me the ability to compare correct messages from the DHCP server in my router with the (initially) incorrect messages from my DHCP server.
Here is how the sequence of messages looks in Wireshark (this is between Windows Vista as a client and my DHCP server implementation running on Arduino + RedFly):
Continue reading DHCP and DNS servers with ArduinoThis library implements DHCP and DNS servers you can run on Arduino. This library should be used when you have your Arduino running an ad-hoc (IBSS) network and want to assign IP addresses to other devices that connect to the same network. The usage is simple:
#include <RedFly.h>
...
uint8_t buf[590];
byte serverIP[] = { 192, 168, 2, 1 };
char domainName[] = "mshome.net";
char serverName[] = "arduino\x06mshome\x03net";
...
buf_len = DHCPreply((RIP_MSG*)buf, buf_len, serverIP, domainName);
...
buf_len = DNSreply((DNS_MSG*)buf, buf_len, serverIP, serverName);
The library is available here. The package also includes a complete example (using RedFly Wifi shield) that implements DHCP, DNS, and HTTP servers.
This library implements DHCP server you can run on Arduino. While there are several libraries mentioned in Arduino forums (most notably DHCP_Web_Server_12.pde, DHCP with DNS, and Nebster's DHCP server code from this Arduino forum thread), some used UDP libraries I could not use and some I simply could not get to work. The code is based on Nebster's DHCP code, but has been re-written and tested with the RedFly shield and various clients.
This library should be used when you have your Arduino running an ad-hoc (IBSS) network and want to assign IP addresses to other devices that connect to the same network. The usage is simple (v0.01 syntax; v0.03 added one more parameter):
#include <RedFly.h>
...
uint8_t buf[590];
byte serverIP[] = { 192, 168, 2, 1 };
...
buf_len = DHCPreply((RIP_MSG*)buf, buf_len, serverIP);
The library does not fully implements the spec as it only handles DHCP Request and DHCP Discover messages and returns DHCP NAK to DHCP Inform messages. It correctly assigns IP addresses to clients running Windows Vista, Ubuntu 11.04, and iOS 4 running on iPod. However, the library does not work for clients running iOS 2 on iPhone and Snow Leopard v10.6.8 on MacBook Pro. The library responds with a DHCP Discover message, but it doesn't seem to be recognized by the client and the DHCP Request message never follows. If you know how to fix this, send me an email.
The library is available here.
So, how exactly was this done?
The system includes four main components: (1) cameras to track the movements of the ball, (2) the robot with the paddle attached, (3) the ball (or multiple balls), and (4) the software that runs the control loop and does all the calculations.
Continue reading Robot juggles two ping-pong ballsFour months ago Google released a new version of their Maps API, version 3, which promised substantial speed improvements and support for mobile browser among other benefits. It's a complete rewrite and its interface is significantly different from the current API. And yet it may still be possible to write modules that work with both APIs as this post shows.
As it turned out, the differences between the APIs are not as significant as I originally expected; although I only used a small chunk of the API, the result still provides a fully functional and potentially useful example.
I am going to use dynamic loading of the API to allow easy switching between the two versions. I am also going to set up a namespace to encapsulate the code generates the canvas class I'm using that inherits from different classes depending on the version of API being used. Namespacing your Javascript post provides a good starting point for those who may need get familiar with this approach.
Let's look at the differences between the APIs and how they can be resolved. The most impatient can scroll to the end of the post to see the result.
Continue reading GMaps: Using multiple API versionsGoogle Maps provides two ways to load its API. One is static, the simplest one that looks like this:
<script type="text/javascript"
src="http://maps.google.commaps?file=api&v=2&sensor=false&key=ABCDEF..."></script>
<script type="text/javascript">
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(33.52392, -111.90884), 12);
var myOverlay = new MyOverlay();
map.addOverlay(myOverlay);
...
</script>
<body onunload="GUnload()">
The second one, dynamic, requires a bit more work:
<script type="text/javascript"
src="http://www.google.com/jsapi?key=ABCDEF..."></script>
<script type="text/javascript">
google.load("maps", 2, {other_params:"sensor=false"});
google.setOnLoadCallback(function() {
var map = new google.maps.Map2(document.getElementById("map"));
map.setCenter(new google.maps.LatLng(33.52392, -111.90884), 12);
var myOverlay = new MyOverlay();
map.addOverlay(myOverlay);
...
});
</script>
...
<body> Continue reading GMaps: Dynamic loading of the API



Convert PNG files to an animated GIF