Tag Archive : embedded

/ embedded

Arduino Project: Software Serial Communication

December 11, 2015 | Article | No Comments

In most case, our device are stand-alone application, which means we don’t involve any additional computer for operation. However, we can still make Arduino interact with our computer in such nice way. We use serial communication to achieve this.

Most possible reason for communication is debugging purpose. We analyze Arduino state for various input and condition given, by reading output shown by Arduino. The serial communication can also be used for communication of two devices.

Arduino have built-in support for serial communication on pin 0 and 1, but what if we need more serial ports? Here come SoftwareSerial Library to rescue. This library has been developed to allow serial communication to take place on the other digital pins of our Arduino board, using software to replicate the functionality of the hardwired RX and TX lines. This can be extremely helpful when the need arises to communicate with two serial enabled devices, or to talk with just one device while leaving the main serial port open for debugging purpose.

Objective

  • Use pin 10 and 11 as virtual RX and TX serial lines.
  • Echo data received from main RX serial line to virtual TX line.
  • Echo data received from virtual RX line to main TX serial line.

Prerequisite

Requirement

Following is all materials I use for this tutorial.

  • Arduino Uno R3

You can change the Arduino board to higher specification if you like.

You also need an USB A to B cable for upload our program to our Arduino and also for serial communication.

Circuit

Here is the circuit image, created using Fritzing.

SerialComm

We don’t need any extra component to do this project.

SerialComm_Diagram

Code

Let’s see what code we use for this project and discuss it later.

#include <SoftwareSerial.h>

SoftwareSerial EuSerial(10, 11);        // Bind RX and TX to pin 10 and 11

void setup() {
  // Open serial communications and wait for port to open
  Serial.begin(57600);
  // Wait for serial port to connect. Needed for Leonardo only
  while(!Serial);

  Serial.println("Arduino SoftwareSerial Demo");

  // Set the data rate for the SoftwareSerial port
  EuSerial.begin(4800);
  EuSerial.println("Hello, world?");
}

void loop() {
  // Echo data from virtual RX to main TX
  if (EuSerial.available())
    Serial.write(EuSerial.read());
  // Echo data from main RX to virtual TX
  if (Serial.available())
    EuSerial.write(Serial.read());
}

Here we have two serial line: Arduino serial and virtual serial by SoftwareSerial. Both have difference baud rate, the main lines have baud rate 57600 while the virtual lines have baud rate 4800.

The initialization of both lines are similar. We use begin() function to set the baud rate of both lines.

In loop(), we will echo every input we got. To do that, we should check the availability first. This is done by executing available(). To read data, Arduino use read() function. To send data to other end, Arduino provide print() and println() function. These functions are slight different where println() send extra new line character at the end of transmission.

Result

You need two serial lines connected to your PC. The result should be similar to Simple Serial Communication project. It is strongly recommended to use PuTTY and connect to both port recognized by your computer.

Why it Works

We have demonstrate serial communication in this project. The word serial means “one after the other”. Serial data transfer is a transmission method where data is transferred one bit at a time, one right after the other.

Information is passed back & forth between the computer and Arduino, by essentially, setting a pin high or low.

There are two condition of logic in circuit, HIGH and LOW. Some microcontrollers might define HIGH and LOW difference, but in Arduino Uno we have HIGH logic as 5V and LOW logic as 0V. If you know boolean value, yes this is boolean value with HIGH is true and LOW is false.

Objective

  • Input/Output from and to Arduino.
  • Make the LED turn on when we input certain command.
  • Make the LED turn off when we input certain command.

Prerequisite

Requirement

Following is all materials I use for this tutorial.

  • Arduino Uno R3
  • LED

You can change the Arduino board to higher specification if you like. The LED I use will emit red light as it is powered by electricity.

You also need an USB A to B cable for upload our program to our Arduino and also for serial communication.

Circuit

Here is the circuit image, created using Fritzing.

Blinking LED

To build the circuit, attach the LED as shown in the figure. Attach the long leg of an LED (positif leg or anode) to pin 13. Attach the short leg (negative leg or cathode) to the ground (GND). On Arduino Uno, there is also a built in status LED which connected to pin 13. When our Arduino running successfully, both status LED and external LED will start to blink.

We don’t need extra resistor for this project, but make sure you are using pin 13. If you do connect it to other pin, it might be destroyed. The reason is that pin 13 has an internal resistor that other pins don’t have which limit current to our LED.

ExampleCircuit_sch

Code

Let’s see what code we use for this project and discuss it later.

const unsigned int LED_PIN = 13;
const unsigned int BAUD_RATE = 9600;

char command;

void setup() {
   pinMode(LED_PIN, OUTPUT);
   Serial.begin(BAUD_RATE);
}

void loop() {
   if (Serial.available() > 0) {
      command = Serial.read();
      if (command == '1') {
         Serial.println("Led on");
         digitalWrite(LED_PIN, HIGH);
      } else if (command == '2') {
         Serial.println("Led off");
         digitalWrite(LED_PIN, LOW);
      } else {
         Serial.println("Led pattern 1");
         digitalWrite(LED_PIN, HIGH);
         delay(250);
         digitalWrite(LED_PIN, LOW);
         delay(500);
         digitalWrite(LED_PIN, HIGH);
         delay(250);
         digitalWrite(LED_PIN, LOW);
      }
      Serial.print("You enter: ");
      Serial.println(command);
   }
}

Notice that we define two constant here, LED_PIN which is pin we use, and BAUD_RATE for the baud rate. Baud rate is the rate of character transferred every second. Notice that 1 character is 1 byte, which is also 8 bit. Both party who communicate must agree on same baud rate before transmission began. If baud rate is not equal, data can’t be transferred correctly.

Here we introduce a object called Serial. This object handles input output in serial communication. To use this object we should initialize which baud rate we use. In this case we use 9600, which is common baud rate used.

To do input, we should check the availability first. This is done by executing Serial.available(). Single character can be read by read() function. To send data to other end, Arduino provide print() and println() function. These functions are slight different where println() send extra new line character at the end of transmission.

We define three commands: ‘1’, ‘2’, and ‘3’. If we enter 1, we turn the LED on. If we enter 2, we turn the LED off. If we enter 3, we make the LED on/off in certain pattern.

Result

Once the program is uploaded, open “Serial Monitor” window in Arduino IDE. It is our tool to do serial communication using Arduino IDE. You can open it by navigate to Tool > Serial Monitor. Another way to do it is press CTRL + SHIFT + M at once.

SerialMonitor

To give input to Arduino, type in to the text box and click on “Send” button. Now give input of number 1, 2, 3 and see the result. You should see the LED are turned on and off according to your command.

Why it Works

It similar to project Simple Serial Communication where we received some commands from serial communication. This command are then processed to determine which routine should we do.

Arduino Project: Simple Serial Communication

December 11, 2015 | Article | 1 Comment

In most case, our device are stand-alone application, which means we don’t involve any additional computer for operation. However, we can still make Arduino interact with our computer in such nice way. We use serial communication to achieve this.

Most possible reason for communication is debugging purpose. We analyze Arduino state for various input and condition given, by reading output shown by Arduino. The serial communication can also be used for communication of two devices.

Objective

  • Input/Output from and to Arduino.
  • Doing simple math operation and output the result.
  • Echoing the user inputs.

Prerequisite

  • none

Requirement

Following is all materials I use for this tutorial.

  • Arduino Uno R3

You can change the Arduino board to higher specification if you like.

You also need an USB A to B cable for upload our program to our Arduino and also for serial communication.

Circuit

Here is the circuit image, created using Fritzing.

SerialComm

We don’t need any extra component to do this project.

SerialComm_Diagram

Code

Let’s see what code we use for this project and discuss it later.

const unsigned int BAUD_RATE = 9600;

int a = 5;
int b = 10;
int c = 20;

void setup() {
  Serial.begin(BAUD_RATE);
  Serial.println("Arduino Serial Communication Demo");

  Serial.print("a = ");
  Serial.println(a);  
  Serial.print("b = ");
  Serial.println(b);  
  Serial.print("c = ");
  Serial.println(c);  
  Serial.print("a + b = ");      // addition
  Serial.println(a + b);  
  Serial.print("a * c = ");      // multiplication
  Serial.println(a * c);  
  Serial.print("c / b = ");      // division
  Serial.println(c / b);
  Serial.print("b - c = ");      // subtract
  Serial.println(b - c);
}

void loop() {
  if (Serial.available()) {
    Serial.write(Serial.read());
  }
}

In the first line we declare a constant, BAUD_RATE, which has value 9600. Baud rate is the rate of character transferred every second. Notice that 1 character is equal to 1 byte or 8 bit. Both party who communicate using serial communication must agree on same baud rate before transmission began. If baud rate is not equal, data can’t be transferred correctly.

Here we introduce a object called Serial. This object handles input output in serial communication. To use this object we should initialize which baud rate we use. In this case we use 9600, which is common baud rate used.

We declare three variables for our math operation: a, b, and c with their respective value. In setup() we do some basic math operation over these three variables. The result will be presented every time we initiate serial connection.

In loop(), we will echo every input we got. To do that, we should check the availability first. This is done by executing available(). To read data, Arduino use read() function. To send data to other end, Arduino provide print() and println() function. These functions are slight different where println() send extra new line character at the end of transmission.

Result

Once the program is uploaded, open “Serial Monitor” window in Arduino IDE. It is our tool to do serial communication using Arduino IDE. You can open it by navigate to Tool > Serial Monitor. Another way to do it is press CTRL + SHIFT + M at once.

SerialMonitor

Here we will be presented with the result of our math operation.

To give input to Arduino, type in to the text box and click on “Send” button. You will see nice similar message you type. Here is the result after I type “Satria Ady Pradana”:

SerialMonitor2

Alternatively, you can use puTTY in Windows or Linux terminal in Linux. However we won’t cover this subject.

Why it Works

We have demonstrate serial communication in this project. The word serial means “one after the other”. Serial data transfer is a transmission method where data is transferred one bit at a time, one right after the other.

Information is passed back & forth between the computer and Arduino, by essentially, setting a pin high or low.

There are two condition of logic in circuit, HIGH and LOW. Some microcontrollers might define HIGH and LOW difference, but in Arduino Uno we have HIGH logic as 5V and LOW logic as 0V. If you know boolean value, yes this is boolean value with HIGH is true and LOW is false.

Arduino Project: Simple Blinking LED

December 11, 2015 | Article | 2 Comments

Blink LED, like what it should be, we make certain LED blinking. We can define “blinking” as continuous condition switching between ON and OFF condition. This is the simplest project we can do for Arduino.

Objective

Prerequisite

  • Basic understanding of LED

Requirement

Following is all materials I use for this tutorial.

  • Arduino Uno R3
  • LED

You can change the Arduino board to higher specification if you like. The LED I use will emit red light as it is powered by electricity.

You also need an USB A to B cable for upload our program to our Arduino.

Circuit

Here is the circuit image, created using Fritzing.

Blinking LED

To build the circuit, attach the LED as shown in the figure. Attach the long leg of an LED (positive leg or anode) to pin 13. Attach the short leg (negative leg or cathode) to the ground (GND). On Arduino Uno, there is also a built in status LED which connected to pin 13. When our Arduino running successfully, both status LED and external LED will start to blink.

We don’t need extra resistor for this project, but make sure you are using pin 13. If you do connect it to other pin, it might be destroyed. The reason is that pin 13 has an internal resistor that other pins don’t have which limit current to our LED.

ExampleCircuit_sch

Code

Let’s see what code we use for this project and discuss it later.

const unsigned int LED_PIN = 13;
const unsigned int PAUSE = 500;

void setup() {
   pinMode(LED_PIN, OUTPUT);
}

void loop() {
   digitalWrite(LED_PIN, HIGH);
   delay(PAUSE);
   digitalWrite(LED_PIN, LOW);
   delay(PAUSE);   
}

Notice that we define two constant here, LED_PIN which is pin we use, and PAUSE for the delay interval which is 500 ms.

The heart of this project is pin 13. We use this pin as output pin. Therefore we initialize pin 13 as an output pin with the statement:

pinMode(LED_PIN,OUTPUT);

Next in the main loop, we turn the LED on by:

digitalWrite(LED_PIN, HIGH);

and turn it off by:

digitalWrite(LED_PIN, LOW);

And we now know that digitalWrite() function is used to output signal on a pin.

The delay() command is used to tell Arduino to do nothing for given time. In our case, we make Arduino wait for 500 miliseconds.

Result

LED is blinking.

Why it Works

There are two condition of logic in circuit, HIGH and LOW. Some microcontrollers might define HIGH and LOW difference, but in Arduino Uno we have HIGH logic as 5V and LOW logic as 0V. If you know boolean value, yes this is boolean value with HIGH is true and LOW is false.

The LED we use is active-high LED, which means it can turn on when it is given HIGH voltage.

Arduino and List of Arduino Boards

December 11, 2015 | Article | No Comments

Arduino is an open source electronics prototyping platform based on flexible, easy-to-use hardware and software. It is a single board microcontroller intended for artists, designers, hobbyists, and anyone interested in creating interactive objects or environment.

A microcontroller (sometimes abbreviated as µC, uC, or MCU) is an integrated circuit contain a processor core, memory, and programmable input/output peripherals. One can program microcontroller for various purpose especially for control machinery, for example: robotics, automobile engine control systems, remote controls, toys, and other embedded systems. In short, microcontroller is similar to our brain, controlling input, process, and output of electronic device. This behavior similar to computer, however microcontroller already have memory, timer, and storage for store executable program.

A microcontroller can’t be used directly. It is a IC chip and we can’t use it immediately, which means we have to supply a minimum system to run it. That is analogically same with processor and motherboard. Fortunately, Arduino has provide all we need to utilize a microcontroller. Arduino has wrapped all the complicated things and provide us with nice programmable board without us to do extra work to create a system minimum.

The Boards

When we talk about Arduino, we are actually talking about Arduino family. There are some boards released by Arduino, designed using either Atmel AVR processor and ARM-based processor. The main differences between those boards are the:

  • Type of processor
  • Number of inputs and outputs
  • Form factor

An Arduino board is basically a single board with appropriate system and components enough to power and run a microcontroller. One Arduino product (Arduino board) might differs in some aspects when compared to another Arduino product. Arduino boards use megaAVR series of chips, specifically the ATmega8, ATmega 328, ATmega 1280, and ATmega 2560; and also ARM Cortex chips.

The boards include a 5 volt linear regulator. We can power Arduino board from power connector or from USB connector when we program it.

Most of Arduino products include 16MHz crystal oscillator (or ceramic resonator in some variants). Although some designes such as the LilyPad run at 8 MHz.

As stated before, Arduino is an open-source. Arduino exposed the schematics for all of their products, open to everyone. Anyone who interested can make their own arduino board. However, Arduino restricts that no one should use Arduino brand name for third party maker. That means, any company who create the Arduino clone cannot use Arduino name.

The Shields

Shields are printed circuit expansion boards that plug into the normally supplied Arduino pin-headers. Shields can provide motor controls, GPS, ethernet, LCD display, or any function specific to that shield. These peripherals are sold separately and can also be made by ourselves.

Programming in Arduino

Microcontroller is programmable, so does Arduino board which use microcontroller to run its awesomeness.

Arduino has official Integrated Development Environment (IDE) in use of programming for Arduino. The IDE is a cross-platform application written in Java and derived from the IDE for the Processing programming language and Wiring projects. It is designed to introduce programming to artists and other newcomers unfamiliar with software development. There are also alternative to Arduino IDE which you can see from this list.

Arduino programs are written in C or C++, however the structure is simplified. Arduino use software library called Wiring from original Wiring project which makes many common input/output operations much easier. We at minimum only need to define two function to make a runnable cyclic executive program:

  • setup(): a function run once at the start of a program that can initialize settings.
  • loop(): a function called repeatedly until the board powers off.

An example for simple source code (also called as “sketch”) which will blinks a LED on and off:

const unsigned int LED_PIN = 13;

void setup() {
   pinMode (LED_PIN, OUTPUT);    // Enable pin 13 for digital output
}

void loop() {
   digitalWrite(LED_PIN, HIGH);  // Turn on the LED
   delay(1000);                  // Wait 1 second or 1000 miliseconds
   digitalWrite(LED_PIN, LOW);   // Turn off the LED
   delay(1000);                  // Wait 1 second
}

The programs compiled or created are in binary format which executable by the microcontroller. However this binary program is different with binary program in our computer. These programs use the different format, the mnemonic used by microcontroller.

The last step in programming Arduino is “upload” the program to Arduino. In common practice, uploading a program to microcontroller need external device called “programmer”. The fancy thing is, Arduino needs no external programmer. It has built component in board which allow our ordinary computer as programmer.

List of Boards

Arduino release numbers of board. This list might not be up to date. Please refer this page for more accurate Arduino product.

  1. Arduino Uno
  2. Arduino Leonardo
  3. Arduino Due
  4. Arduino Yùn
  5. Arduino Tre
  6. Arduino Micro
  7. Arduino Robot
  8. Arduino Esplora
  9. Arduino ADK
  10. Arduino Ethernet
  11. Arduino Mega 2560
  12. Arduino Mini
  13. Arduino BT (BlueTooth)
  14. LilyPad Arduino USB
  15. LilyPad Arduino Simple
  16. LilyPad Arduino SimpleSnap
  17. LilyPad Arduino
  18. Arduino Nano
  19. Arduino Pro Mini
  20. Arduino Pro
  21. Arduino Fio

For quick comparison:

[table “2” not found /]

We might cover some Arduino models. To get start, you can check following models:

  • Arduino Uno, basic one with a replaceable chipset.
  • Arduino Mega 2560, provides a bunch of inputs and output.
  • Arduino LilyPad, wearable as clothes.
  • Arduino Nano, very small device.

For my series of tutorials unless told otherwise, I will use Arduino Uno and sometime Arduino Mega.

Reference

  1. Arduino official site – http://arduino.cc/

Smart Card is a pocket-sized card with embedded integrated circuits. It provides identification, authentication, data storage and application processing on simple medium. There are two big categories of smart card: contact and contactless. To identify and authenticate a smart card properly we need a smart card reader. There are many smart card reader and the way we operate is depend on what smart card it can detect.

To detect and use smart card, there is a specification for smart card integration into computing environments. It is called PC/SC (Personal Computer / Smart Card). The standard has been implemented to various operating system: Windows (since NT/9x), Linux, Unix.

We can however create a small device which can make use of smart card reader, instead of using our PC. That’s what we will discuss on this article.

As title suggest, after we have smart card connected we will use PHP as a programming environment.

For this article, we use:

  1. Working Raspberry Pi model B (+SD card)
  2. Raspbian Wheezy release date 2013-09-25
  3. Smart Card Reader, ACR122
  4. USB power hub

Grab the Materials

Make sure the Raspberry Pi is working properly with Raspbian Wheezy installed. Also make sure all the hardware are available.

We need USB power hub as the ACR122 Smart Card Reader gives too high load for Raspberry Pi so we will feed electricity from somewhere else.

Installation

Install the drivers and related package

apt-get install build-essential libusb-dev libusb++-dev libpcsclite-dev libccid
  • build-essential is package for building a application
  • libusb-dev and libusb++-dev are package for user-space USB programming
  • libpcsclite-dev is a middleware to access a smart card using PC/SC (development files) using PC\SC-lite definition
  • libccid is a smart card driver

Install PHP and all needed development tool

apt-get install php5-dev php5-cli php-pear

Once PHP installed, we need a PHP extension for smart card:

pecl install pcsc-alpha

You can see the documentation here.

Configuration

On some case, we need to add an entry to php.ini manually for registering pcsc extension. To do this, open up php.ini and add following entry:

extension = pcsc.so

File Transfer Protocol (FTP) is a standard network protocol used for transferring files from one host to another host over a TCP-based network. The party involving two side: server and client, in other words it use client-server architecture. One famous FTP server is VSFTPD (Very Secure FTP Daemon).

In this article we will discuss about how to install VSFTPD to Arch Linux ARM, one of Linux distribution for ARM processor. Specifically, I use:

  1. Raspberry Pi model B, for machine
  2. Arch Linux ARM release 2013-07-22

Before we started, make sure you have installed Arch Linux ARM on your device.

Update the Repository

It is a good choice to update the repository as Arch Linux release new package periodically without save the old package. Arch Linux ARM use the very same package manager system like its parent uses. Therefore the command should be similar.

Make sure you have setup the Arch Linux ARM Repository.

To update the repository, do following:

pacman -Syy

Make sure your device can access the internet.

Installation

Installing vsftpd is really straightforward. We can install vsftpd from the Official Repositories by:

pacman -S vsftpd

Package manager will download the required package, depends on your connection. It will also install it automatically once the package are downloaded.

Start / Enable Server

We can enable server, which means the server started everytime we boot the device. Arch Linux use systemd, so to make it run automatically at boot time, do following:

systemctl enable vsftpd.service

While you can make it disabled / not run automatically by:

systemctl disable vsftpd.service

To start it manually, do:

systemctl start vsftpd.service

We can stop the service by:

systemctl stop vsftpd.service

Architecture of BeagleBone Board

December 9, 2015 | Article | No Comments

This article will discuss about BeagleBone architecture, for original ($89) and black version ($45).

Both are relative similar though the BeagleBone Black is improvement of the original model with half price.

General Specification

BeagleBone is a low-cost high-expansion board from BeagleBoard. It uses the TI AM3358/9 SoC (System on Chip) based on ARM-Cortex A-8 processor core (an ARMv7-A architecture).

BeagleBone ships with a 4GB micro-SD card preloaded with the Angstrom ARM Linux distribution.

Model A has one USB port and no Ethernet controller with less cost than the Model B with two USB ports and a 10/100 Ethernet controller. Eventhough the Model A doesn’t have an RJ45 Ethernet port, it can connect to a network by using a user-supplied USB Ethernet or Wi-Fi adapter. In reality there is no difference between a model A with an external Ethernet adapter and a model B with one built in, because the Ethernet port of the model B is actually a built-in USB Ethernet adapter. As is typical of modern computers, generic USB keyboards and mice are compatible with the Raspberry Pi.

The Raspberry Pi does not come with a real-time clock,so an OS must use a network time server, or ask the user for time information at boot time to get access to time and date for file time and date stamping. However, a real-time clock (such as the DS1307) with battery backup can be added via the I²C interface.

Hardware accelerated video supported default by Pi is H.264. At the same time The Raspberry Pi Foundation has release two additional codecs that can be bought separately, MPEG-2 and Microsoft’s VC-1. Also Pi will support CEC, enabling it to be controlled with the television’s remote control.

The Processing Unit

Both model A and model B has Broadcom BCM2835 (CPU, GPU, DSP, SDRAM). The CPU use ARM1176JFZ-S core (ARM11 family) and run on 700MHz clock. The SDRAM is shared between CPU and GPU but in different amount on two model. Model A has 256 MB of memory while model B has 512 MB of memory.

On the older beta model B boards, 128 MB was allocated by default to the GPU, leaving 128 MB for the CPU. On the first 256 MB release model B (and Model A), three different splits were possible. The default split was 192 MB (CPU RAM), which should be sufficient for standalone 1080p video decoding, or for simple 3D, but probably not for both together. 224 MB was for Linux only, with just a 1080p framebuffer, and was likely to fail for any video or 3D. 128 MB was for heavy 3D, possibly also with video decoding (e.g. XBMC). For the new model B with 512MB RAM initially there were new standard memory split files released( arm256_start.elf, arm384_start.elf, arm496_start.elf) for 256MB, 384MB and 496MB CPU RAM (thus leaves 256MB, 128MB and 16MB video RAM). But a week or so later the RPF released a new version of start.elf that could read a new entry in config.txt (gpu_mem=xx) and could dynamically assign an amount of RAM (from 16 to 256MB in 8MB steps) to the GPU, so the older method of memory splits became obsolete, and a single start.elf worked the same for 256 and 512 MB Pis.

The Input Output

For video output aspberry use Composite RCA (PAL and NTSC), HDMI (rev 1.3 & 1.4), and raw LCD Panels via DSI 14 HDMI from 640×350 to 1920×1200 plus various PAL and NTSC standards for both model.

For audio output both model utilize 3.5 mm jack, HDMI, and also I²S audio.

For a low-level purpose, Raspberry Pi utilize 8 x GPIO, UART, I²C bus, SPI bus with two chip selects, I²S audio +3.3 v, +5V, ground.

Power Rating and Source

To run Raspberry Pi a minimal 5 volt must be supplied to the board. While the model A need 300mA (rating 1.5 W), the model B use 700 mA (rating 3.5 W). The power can be delivered to MicroUSB or GPIO header.

A common misconception about developing for the Google Android Platform is that you have to write your code in the Java programming language. The truth is you actually have many options. OK, aside of NDK (Native Development Kit) using C/C++, you can develop application using Scripting Layer for Android.

The Scripting Layer for Android (SL4A) brings scripting language to Android by allowing you to edit and execute scripts and interactive interpreters directly on the Android device. Started out as 20% project by Google employee Damon Kohler, the project now supports Python, Ruby, Perl, Lua, JavaScript, BeanShell, and more platform.

This article is part of series of articles explores how to use Python and Scripting Layer for Android (SL4A) to build application for Android.

This article will discuss about how to setup environment for developing Android app using Python. What I use for this article are:

  1. Slackware64 14.0 as developer machine
  2. Windows 8 64-bit as developer machine
  3. Sony XPeria U as target machine
  4. Java Development Kit (JDK) 1.7.0_13
  5. Android Software Development Kit (SDK)
  6. Python 2.7.3

Note that I use Slackware (Linux) and Windows as proof of concept. You can either use one or both but I will try to make it as general as possible.

Who have Use SL4A?

Many! But notable users are:

  1. SmallSat
  2. Cellbots – http://www.cellbots.com/
  3. Oplop – http://code.google.com/p/oplop/
  4. Broadcast – http://github.com/mleone/broadcast/

Why Python?

So the first question, why python?

Python is a great tool for writing both simple scripts and complex, multi-threaded applications. The great thing about having Python on Android is the opportunity to use the untold thousands of lines of code already written and freely available. Python is an easy language to learn if you’ve never used it before, and you will find many resources available on the Internet to help get you up to speed.

Obtain Materials

SL4A has several packages. But for our goal, we need only two packages: core SL4A and Python for android. Both you can download from SL4A download site.

Here what you need (last version per September 26th, 2013):

  1. sl4a_r6.apk
  2. PythonForAndroid_r4.apk

As the popularity of Python for Android grow, the project has been forked to new project which stand side to SL4A. You can visit Python for Android project page and download their latest release.

If you don’t have Oracle JDK, Android SDK, and Python yet then grab them.

Installation and Setup

On Android Device

Install SL4A on Android device. This process is similar to any other Android application installation process.

Before installation, make sure you enable the “Unknown sources” option in your device’s “Application” settings.

screenshot_2013-09-26_1215

Open up terminal / your command prompt. Make sure you can access adb from your “$ANDROIDSDK/platform-tools” path.

Connect your phone to your machine and invoke following commands:

adb install -r sl4a_r6.apk
adb install -r PythonForAndroid_r4.apk

To make sure Python for Android installed, see your application list and search for Python for Android. It should has following user interface:

screenshot_2013-09-26_1241

Tap on Install to install the interpreter needed. Your phone then downloading some extra packages.

To verify, open application named SL4A on your launcher. See the “Interpreter” on “View” menu. You should see Python 2.6.2 there.

screenshot_2013-09-26_1305

On Development Machine

The SL4A needs Oracle Java Development Kit (JDK) and Android Software Development Kit (SDK). All of them must be provided before we install SL4A. We also need to install Python. Note that all dependencies should have correct architecture based on your machine. As I use 64-bit machine, I will need to install the 64-bit version.

At this point, I assume you have all the dependencies installed.

Reference:
  1. Installing Android SDK on Linux
  2. Installing Android SDK on Windows
  3. Installing Java Development Kit on Linux

Testing

Let’s test the environment by creating a simple hello world project.

Write this on your development machine as hello.py:

import android
droid = android.Android()
result = droid.makeToast('Hello, world!')

Then send it to your Android phone. The simplest way is using adb.

adb push hello.py /sdcard/sl4a/scripts/hello.py

Now run the script by running SL4A. You should see lot of python script in the list. Our script is hello.py, just tap it to run it and you can see the toast.

You can also create a simple script to upload your script:

Appendix A: SL4A Functionality

The SL4A has following functionality which can be used on Python:

  • ActivityResult
  • Android
  • ApplicationManager
  • BatteryManager
  • Camera
  • CommonIntents
  • Contacts
  • Event
  • EyerFree
  • Location
  • MediaPlayer
  • MediaRecorder
  • Phone
  • Preferences
  • SensorManager
  • Settings
  • Sms
  • SpeechRecognition
  • ToneGenerator
  • WakeLock
  • Wifi
  • UI

Folks at Google Creative Lab has release a project to develop a web application using Raspberry Pi platform. This project is pure open source project which turn a Raspberry Pi to a simple web server platform. This way, educators and parents can use to teach the basics of building for the web. New coders can craft small projects in HTML, CSS, and Javascript, right from the web browser. Enthusiasts can also experiments on web programming. All come from a single distribution image.

The project itself is revealed as Coder. How do we setup the Coder to run properly and operated from our machine is what we will discussed in this article.

In this article I use

  1. Raspberry Pi model B, 512MB RAM
  2. SD Card 4 GB
  3. Slackware64 14.0 as client station
  4. Windows 8 64-bit as client station
  5. Mac OS X as client station

Note that I mention three machine for experiment. You can choose any (or all) operating system and to work with.

Prologue

[embedplusvideo height=”495″ width=”880″ editlink=”http://bit.ly/18HOj1C” standard=”http://www.youtube.com/v/wH24YwdayFg?fs=1″ vars=”ytid=wH24YwdayFg&width=880&height=495&start=&stop=&rs=w&hd=0&autoplay=0&react=1&chapters=&notes=” id=”ep8669″ /]
Coder is not only designed for people who start web developing. Google also has big idea to make this platform as fun as possible to experiment and to play around.

Obtain the Material

Coder is like other Linux distribution on Raspberry Pi. It comes with SD card image which will be burned to SD card.

The latest version of Coder is 0.4 which can be downloaded here. The compressed image has size 1.04 GB.

Coder is derived from Raspbian, therefore the basic is not much different from Raspbian. The only thing differ is Coder has special codebase and platform. Though you can install the code on existing distro, we won’t cover it in this article.

The distro has several files and directory inside in hierarchical structure. There is an image with filename raspi.img which we will use later.

Preparation

You should prepare the machine well. We will use this machine (a client) to interact with our Coder. Once you choose either Windows, Mac, or Linux you should read what you need to do to prepare your machine.

Windows

A Windows user should install Apple’s Bonjour Print Service. This application will install Bonjour, a Zero-Configuration Networking system on Windows

Mac OS

You can go, Apple has installed Bonjour on their own machine.

Linux

Follow this link to install Zero-Configuration Networking on Linux.

Prepare the Disk (SD Card)

To boot the Raspberry Pi, an installation media and storage media is needed. All we need is a single SD card. The bigger space, the better. You need space for OS and additional space to hold your ROMS. On this article I use my 4GB SD card. You can use any SD card you want, but I recommend to use at least 4GB SD card (recommended by Google too). The image we download on previous section will be stored on this card and later installed. Make sure you have a way to write on SD card.

Windows

For Windows user, you can follow this section to “burn” the image. For this purpose you need additional software for writing to SD card, such as Win32DiskImager utility.

  1. Insert SD card into SD card reader and check what drive letter it assigned to. For example G:\
  2. If it is not new, format it. Or at least make sure there is only one partition (FAT32 is recommended).
  3. Run the Win32DiskImager with administrator privileges.
  4. Select the image we have extracted (raspi.img).
  5. Select the drive letter of the SD card on our machine. Make sure you have the correct drive, or you will destroy data on that drive.
  6. Click Write and wait. The process should be not long.
  7. Exit the imager and eject the SD card

Beside Win32DiskImager, you can also use other tool such as Flashnul.

  1. Follow step 1 to step 2 for Win32DiskImager’s solution
  2. Extract Flashnul from the archive
  3. Open command prompt with elevated privilege (administrator privilege).
  4. Go to your extracted directory and run flashnul with argument “-p”. For example: flashnul -p
  5. You will get list of physical drive attached on your machine, and list of drive. Make sure the drive is correct. At time of writing this article, the SD card is detected as device number 1 with and mounted to drive G:
  6. Load the image to flashnul: flashnul 1 -L raspi.img
  7. If you get an access denied error, try re-plugging the SD card and make sure to close all explorer windows or folders open for the device. If still get denial, try substitute the device number with its drive letter: flashnul G: -L raspi.img

At this point, you have successfully written image to your SD card. And I assume you are. You can proceed to next stage.

Mac OS

Run the provided installer. This should be sufficient.

You should be able to go to next stage.

Linux

Writing image on Linux is easier, in my opinion. The utility we use is “dd” which is already bundled on most distro. Make sure you know the correct device file for your SD card. In my machine I use a built in card reader and detect my SD card as /dev/sdb. It might be different on your system so better check it. For this article I use /dev/sdb to refer to SD card.

  1. Insert SD card into SD card reader .
  2. If it is not new, format it. Or at least make sure there is only one partition (FAT32 is recommended).
  3. Unmount the SD card if it is mounted. We need the whole SD card so if you see partition such as /dev/sdb1, etc its better you unmount them all.
  4. Write the image to SD card. Make sure you replace the input file after if= argument with correct path to .img file and “/dev/sdb” in the output file of= argument with your device. Also make sure to use whole SD drive and not their partition (i.e. not use /dev/sdb1, /dev/sdb1, etc). The command: dd bs=4M if=raspi.img of=/dev/sdb
  5. Run sync as root. This will ensure the write cache is flushed and safe to unmount SD card.
  6. Remove SD card from card reader.

If you hesitate to use terminal and prefer to use GUI method, here is the tutorial. Note that we

  1. Do step 1 to step 3 for previous tutorial. Make sure your directory or image file doesn’t contain any spaces.
  2. Install the ImageWriter tool from https://launchpad.net/usb-imagewriter
  3. Launch the ImageWriter tool (needs administrative privileges)
  4. Select the image file (in this case raspi.img) to be written to the SD card (note: because you started ImageWriter as administrator the starting point when selecting the image file is the administrator’s home folder so you need to change to your own home folder to select the image file)
  5. Select the target device to write the image to. In my case, it’s /dev/sdb
  6. Click the “Write to device” button
  7. Wait for the process to finish and then insert the SD card in the Raspberry Pi

At this point, you have successfully written image to your SD card. And I assume you are. You can proceed to next stage.

Accessing the Coder

Plug the SD card to Raspberry Pi.

Make sure Zero-Configuration Networking service is up (it should be).

Open up your browser and visit following url:

coder.local

Like Raspbian, when you run coder for first time you will be asked to do some configuration for example resize the SD card. Or you can resize the SD card later which you can find the guide on this article.

Social media & sharing icons powered by UltimatelySocial