2010-12-04

Controlling Arduino with iPod touch through WebSocket

In my previous entry, I made an application with DeviceMotion Event and WebSocket in iPod touch.

WebSocket server is written in Python/Tornado. So WebSocket message should be able to be relayed to other softwares or devices.

I try to control Arduino device with iPod touch through WebSocket.

Design


Flowing data among iPod touch, WebSocket server and Arduino is written in JSON.

There is a ball in a web page displayed in iPod touch/Safari. The ball moves with DeviceMotion Event by the tilt of iPod touch. The color of a ball is selected by form between red and green.

The web page sends a data including color and location of ball to a WebSocket server. The WebSocket server relays the data to Arduino through TCP socket connection.

If Arduino carrying the Ethernet Shield and Matrix LED gets a ball data from WebSocket Server, Arduino displays the information of the ball with Matrix LED. For controlling 2 colors Matrix LED, MAX7219 x 2 is used.


Implementation


WebSocket server written in Tornado is referenced with "http://192.168.254.23:8888" and "ws://192.168.254.23:8888/ball".



This WebSocket server needs to be run on PC in advance.

If this WebSocket server receives a JSON data, it sends to Arduino as TCP packet. Arduino has "192.168.254.100:9999" as IP-address:Listening-Port.

In the code for Arduino, I use Ethernet library, Matrix library and aJson library.

The data from WebSocket server includes color and location of a ball. The color of ball is used for the color of LED. The location of ball is 0 ~ 300 (X-axis) and 0 ~ 336 (Y-axis). Because Matrix LED has 8x8 LED, I use map(), that is a built-in function for Arduino, for handling location of ball and LED.





The web page is written in HTML5 because I use WebSocket and DeviceMotion Event. This web page reads the situation of iPod touch, updates the location of a ball and sends the information as JSON data to WebSocket server every 1 sec.

This page needs to be deployed in the same directory as WebSocket server.



Playing


$ ls
balls_canvas.html   balls_websocket.py
$ python balls_websocket.py
(waiting as Web/WebSocket server)

The web page is displayed in Safari of iPod touch. If I tilt iPod touch or change the color of a ball, the ball in the web page moves or changes the color. In the back, the web page sends JSON data as the information of the ball to the WebSocket server and the WebSocket server sends the data to Arduino. The situation of Matrix LED controlled by Arduino is determined by reference to the JSON data.



Thanks.

2 comments:

  1. Hi Yoshiyasu, this is excellent work! It is just what I need to get started. I want to ask you, have you probed for the minimal delay you can set in the HMTL file, so as to make the app go quicker? Thanks!

    ReplyDelete
  2. I didn't do anything special. Perhaps, ioloop of tornado (websocket server) has a positive effect.

    ReplyDelete