Tuesday, August 20, 2013

Ultrasonic distance measurement using HC-SR04 ultrasonic module + Arduino Pro

Ultrasonic sensors (Ping sensors) are widely used in distance measurement as they are cheap and has a quite good accuracy. I got this cheap HC-SR04 ultrasonic module from ebay and wanted to test it.
I found the datasheet for it from here.

According to the datasheet ;
Max Range = 400cm
Min Range = 2cm

This algorithm should be used to get the echo from the module:
1. Give 10uS pulse to the TRIGGER pin.
2. Measure the pulse width at ECHO pin.
3. Calculate  distance = (echo high level time×velocity of sound) / 2

I connected the module to my Arduino Pro (Techduino) and wrote a small code for the testing. The code will send the calculated distance value to PC via its UART port.

The code :

#define echo 8
#define trigger 9
long duration,distance;

void setup() {
 Serial.begin (9600);
 pinMode(trigger, OUTPUT);
 pinMode(echo, INPUT);
 digitalWrite(trigger, LOW);

void loop() {
 digitalWrite(trigger, LOW);
 digitalWrite(trigger, HIGH);
 digitalWrite(trigger, LOW);
 duration = pulseIn(echo, HIGH);
 distance = duration/58;
 if ((distance >= 400) || (distance <= 2))
 distance = -1;
I checked the output from the Arduino to PC using a terminal program.

After that I coded a small software to get the distance data and show it in a nice way using Visual C#. This is my first C# application and I referred here and here for coding. You can download the source code and application from here.

Thursday, August 8, 2013

Computer controlled automated guided vehicles (AGV) using Parellel port interfacing

As we built a relay board to interface with "parallel port" in my earlier post. Today I'm going to talk about the control software for it. I wrote this software long time ago using Visual Basic 6 and inpout32.dll as the interface. I used this to control some modified toy cars as autonomous vehicles similar to automated guided vehicles (AGV). The path can be programmed to the software in realtime or in advance. So, the vehicle will follow the route as we need. You can download the program with source code from here.

The software interface:

This was first designed as a school science exhibition project in 2007 and recently used to control a mars rover model in a local astronomy exhibition at Sri Chandananda Buddhist College:

The mars rover model:

The control circuit:

RS-485 Communication testing with MAX485

As we know about RS-232 communication protocol, I'm going to try RS-485 communication between two nodes. RS-485 can support multiple slaves and mostly used in industrial applications with high separation distance between nodes. I recently got 10pcs of MAX485 IC from ebay for $1 which is a RS-485 transceiver. I also got  USB to RS-485 convertor based on CH430 + MAX485. I'm using another USB-UART convertor based on PL2303 for this test setup. So, I have two USB-UART chips connected using two MAX485 ICs in between,which provides the RS-485 communication.

My test setup according to MAX485 datasheet.
(Image extracted from datasheet)

As MAX485 is half duplex, I have to use one as TX with following setup. I'm using my USB-RS485 adapter as  RX and there is no need of manual setting as RX.

My TX setup on breadboard:

My RX setup, the one is right is USB-RS485 convertor:

Test results :

Tuesday, July 2, 2013

Writing and testing Linux kernel modules for Android

We compiled and installed some modules in Linux kernel in previous post. Here I'm going to write my own kernel modules and do the same. I'm stilling learning about this and I was able to write and test a hello world kernel module on my phone.

Phone kernel : Linux
PC O/S : Ubuntu 13.04 32bit
Cross compiler toolchain : Linaro GCC 4.7-2013.01


1) Check for your kernel info using "uname -a" on either terminal emulator or ADB (use "adb shell" and run it).
My result:  Linux version (Ka@Kappa) (gcc version 4.7.3 20130102 (prerelease) (Linaro GCC 4.7-2013.01) ) #94 PREEMPT Sun Apr 28 23:46:13 CEST 2013

2) Get the appropriate kernel source for your kernel. I got kernel source from a GIT host using, (If you don't have git installed, you can install it by sudo apt-get install git)
git clone https://github.com/KaSt/Kappa.git
Now my kernel source is at /home/buddika/kernel/Kappa/

3) Download the appropriate cross-compiler toolchain, I'm using Linaro GCC 4.7-2013.01 toolchain.

4) Extract toolchain to somewhere, I extracted it to, /home/buddika/linaro


I made a directory for my coding as /home/buddika/modules
Please edit these codes to suite your environment. :)

1) hello.c

 *  hello-1.c - The simplest kernel module.
#include <linux/module.h>    /* Needed by all modules */
#include <linux/kernel.h>    /* Needed for KERN_INFO */

int init_module(void)
    printk(KERN_INFO "Hello world 1.\n");

     * A non 0 return means init_module failed; module can't be loaded.
    return 0;

void cleanup_module(void)
    printk(KERN_INFO "Goodbye world 1.\n");

2) Makefile

EXTRAVERSION = .60Kappa-1.6


obj-m := hello.o
PWD := $(shell pwd)
    $(MAKE) ARCH=arm CROSS_COMPILE=/home/buddika/linaro/bin/arm-linux-gnueabihf- -C $(KERNEL_DIR) SUBDIRS=$(PWD) modules
    $(MAKE) -C $(KERNEL_DIR) SUBDIRS=$(PWD) clean


Now in console execute following commands,

cd /home/buddika/modules

Now the kernel module hello.ko will be built at /home/buddika/modules


I copied /home/buddika/modules/hello.ko my sdcard at /sdcard/mymod using (please make /sdcard/mymod directory before doing this)
adb push /home/buddika/modules/hello.ko /sdcard/mymod/

You can log into phone shell using adb shell and get root access using su at the shell.

Let's load the module using,

insmod /sdcard/mymod/hello.ko

You can check whether the module is loaded by using lsmod and check for output

root@android:/ # lsmod
Module                  Size  Used by
hello                    610  0

Run dmesg and check for line like this.If so you have written your first kernel module and loaded it successfully. :)

<6>[29913.944610] Hello world 1.

1) The Linux Kernel Module Programming Guide  
2) viulian's guide on xda-developers.com

Saturday, June 22, 2013

Using USB to UART / RS232 modules with Android phones


As we compiled the kernel modules needed for USB to UART modules in the previous post, Here I'm going to show how to use them.

You can mount /system partition on the phone with read/write permisions.
mount -o rw,remount /system

Then make a directory for kernel modules and copy them to there,
mkdir /system/modules
then copy modules (my compiled modules for to /system/modules/

I'm using init.d script to load these modules in the bootup, if not you will have to load them manually each time.
copy my script to /system/etc/init.d/
chmod 755 /system/etc/init.d/usbser

If you like to load modules manually, you can refer this to get an idea,

Now everything is done and when you plug an USB to UART module, it will be taken as /dev/ttyUSB0. You can use it with any application like on any Linux distribution.

You can do a lsmod to verify whether  the modules are loaded.


These are some dmesg outputs (when I connect the device) for some popular USB to UART devices that I have compiled the drivers for,



CH341 (from a USB to RS232 module):

A loopback test with a Serial terminal app:

Usage & Applications:

As  I mentioned earlier you can you these devices with any serial communication application for Android. I personally use "android-serialport-api" as a terminal application.

Reading from a data-logger:

Tuesday, June 18, 2013

Compiling kernel modules for an Android phone

I recently got a USB OTG cable for my mobile phone and I wanted to use my PL2303 USB to UART convertor with it. It is great for the embedded system projects I'm working on. You can follow the below procedure to do it yourself.

Phone kernel : Linux
PC O/S : Ubuntu 13.04 32bit

1) Check for your kernel info using "uname -a" on either terminal emulator or ADB (use "adb shell" and run it).
My result:  Linux version (Ka@Kappa) (gcc version 4.7.3 20130102 (prerelease) (Linaro GCC 4.7-2013.01) ) #94 PREEMPT Sun Apr 28 23:46:13 CEST 2013

2) Get the appropriate kernel source for your kernel. I got kernel source from a GIT host using, (If you don't have git installed, you can install it by sudo apt-get install git)
git clone https://github.com/KaSt/Kappa.git

3) Download the appropriate cross-compiler toolchain, I'm using Linaro GCC 4.7-2013.01 toolchain.

4) Extract toolchain to somewhere, I extracted it to, /home/buddika/linaro

5) Set path variable to the bin directory of the toolchain using,
export PATH=/home/buddika/linaro/bin/:$PATH

6) Copy the kernel configuration file to the main folder where kernel source it. I executed following command at there,
cp /home/buddika/kernel/Kappa/arch/arm/configs/ka_coconut_defconfig .config

7) Check MakeFile and config files and edit them to match the kernel magic version(in my case I had to edit following line on config file,

8) Check the toolchain's binary directory and find the prefix for the compiler, if you see file like arm-linux-gnueabihf-gcc , the prefix is "arm-linux-gnueabihf-". Note this down for steps below.

9) Go to the kernel source directory, Let's clean the old binary files which may be there.
ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- make clean

10) Let's run menuconfig to configure the kernel options. This will give you a GUI where you can enable features. Select features you need as modules (in my case usbserial...etc) and press M to build them as modules.
ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- make menuconfig

11) Finally build the selected features as kernel modules. :)
ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- make modules

Now you can find the compiled kernel modules at "drivers/usb/serial/" folder in the kernel source folder. If you enabled other functions please check the appropriate folder.

I will show you how to use these newly compiled modules on your phone to use USB to UART module in the next post :D

Sunday, June 16, 2013

Native C programs for ARM based Android phones

You can always use Android SDK to program and build Java programs for android phone which are running on Dalvik Virtual Machine. Recently I wanted to build some native C applications for my phone. As Android is based on Linux kernal, it's matter of finding an appropriate cross compiler for the PC. As I found out there are many toolchains for this and I used Linaro ARM tool chain for Windows (WIN32). This is based on GCC and  I downloaded 2013.05 version and installed it using the installer. Please make sure to tick "add to the PATH" when you installing this.

I wrote this small code to test and saved as count.c ,

#include <stdio.h>
int main()
int x=0;

Then I compiled it using following command in command prompt,

D:\>arm-linux-gnueabihf-gcc count.c -o count -static

The I copied the binary file to mobile using ADB (Android Debug Bridge), you can do it using a file manager too. Make sure to put the compile binary to /system because you can execute binaries only at there in android system.

D:\>adb push count /system
3049 KB/s (463524 bytes in 0.148s)

Then I logged into android shell using ADB, You may use a Terminal Emulator software on the phone itself.

D:\>adb shell

I got root access and changed the file attributes of "count" binary to make it executable (same as on any Linux distribution). (You can either use chmod +x or chmod 777)

~ # su
root@android:/ # cd /system
root@android:/system # chmod 777 count

I executed "count" and tested ,

root@android:/system # ./count
11|root@android:/system #

I also tested the program on phone using a terminal emulator too,

Monday, June 3, 2013

Simple LM386 based audio amplifier

I built this simple LM386-N1 based audio amplifier (Gain=200 example on datasheet) for my radio project. Here I'm testing it using a small signal generated by multimeter. You can find the schematic and more information in the datasheet. This is a quick test and I'll explain more details in the future of the project.

Sunday, June 2, 2013

Using UART & GPIO with AR7240 MIPS board

As I introduced MIPS based router board which has a AR7240 SoC, I further experimented with it to use GPIO and UART in the chip. I'm using my TPLINK WR740N router for these experiments.
I soldered some wires to the board and took the connectors to the exterior of the router so I can play with it easily. You can find the connections to the GPIO and UART pins in this page.

Then I connected my CP2102 USB to UART convertor to the UART port of the AR7240.

Then I logged into the router console using PuTTY and tried to send some data from the UART port of the AR7240 to the PC. In Linux we can use the highlighted command to send a file to the UART port.

 The test was a success and I got the data to the PC using my favorite terminal program SSCOM32.

Sunday, April 21, 2013

MSP430 In circuit programming with MSP430 Launchpad using Spy-Bi wire interface

When we use microcontrollers in our circuits we need to program and debug them in circuits after soldering. Hence, In circuit programming is much useful in such cases. Here I'm going to program my MSP430G2211 microcontroller in a circuit. The programmer I'm going to use is the MSP430 Launchpad. You can get all of them from TI including FedEX shipping.I got them for $4.30 couple of years ago and it was a great deal. This MSP430 value line microcontrollers can be programmed using Spy-Bi wire JTAG interface.

Device connections:

You have to connect SBWTCK(TEST) and SBWTDIO(RST') connections between Launchpad and microcontroller. You may also give power to the device from Launchpad too.

Here is the pinout for my MSP430G2211 from its datasheet.

You may connect the device and Launchpad like this.Use some jumper wires and connect them to the given connector headers on the launchpad.

Now you can use Code Composer Studio or any other software to write code and program/debug it to the microcontroller as they are on the Launchpad itself. I coded a simple LED blink application at P1.0 (pin2) and tested on above circuit which was a success.

Friday, April 19, 2013

Relay board for Parellel port/Microcontroller interfacing

Relays are awesome small devices which could be used to control other devices. The plus point of relays is,they can be used to drive a different voltage level device with complete isolation. In here, I'm going to show you how to build a simple relay drive board for your parallel port interfacing or microntroller interfacing. Basically we are using a simple NPN transistor as a switch to drive a relay. The diode is used to protect the transistor from back e.m.f. generated by the relay coil at transient points (relay on/off). You can use 6V or 12V or any other relay as you wish. The transistor used here is 2SD400 (Ic=1A,Pc=0.75W) which costs around Rs.10 ($0.08). You can use any other general purpose NPN transistor as you wish.

The schematic for a channel:

You can build any number of channels as you wish. Here is a 4 channel board build as above.

You can connect this board to parallel port's D0 to D7 (pin 2 to 9) which belongs to the DATA register of the port. A simple program could be coded to turn on/off the relays connected to the parallel port. Even you can connect this board to a microcontroller and do the same. (Image source:Wikipedia)

Monday, April 15, 2013

Introduction to MIPS CPU architecture with AR7240

There are many CPU architectures in current embedded devices. MIPS is also a popular architecture for embedded systems. Here I'm going to play with a MIPS based  AR7240 SoC as my development environment which has a MIPS 24Kc CPU . I'm using a TPLINK-WR740N router as my development board as I don't have any other MIPS development boards. It runs OpenWRT Linux for MIPS (this is not the stock version,I have installed it). So I won't be going to much lower level and I will play at the Linux level like using Linux on Rarspberry PI.

Router specifications:
  • Atheros AR7240@400MHz RAM:32MB Flash:4MB
  • LED * 5
  • Push buttons * 2
AR7240 has following interfaces:
  • LAN * 5
  • WiFi * 1
  • UART
  • USB
  • GPIO (LEDs & Push buttons are already connected)
For testing I just wanted to blink a LED which is connected to the GPIO0 using a shell script.
I found the GPIO mappings from the OpenWRT wiki. The LEDs are already controlled by a module by default and I had to unload it using "rmmod leds_gpio" command. If you are new to Linux, here you can find about Linux kernal modules. I found a great tutorial on controlling GPIOs in any Linux system and I coded a simple shell script to blink the LED connected to GPIO0 in 1 second intervals. Raspberry PI wiki also has a good tutorial on this.


rmmod leds_gpio
echo 0 > /sys/class/gpio/export
echo out > /sys/class/gpio/gpio0/direction
while [ 0 != 1 ]  
  echo "ON"
  echo 1 > /sys/class/gpio/gpio0/value
  sleep 1
  echo "OFF"
  echo 0 > /sys/class/gpio/gpio0/value
  sleep 1

I logged into the router with "ssh -l root" and made a shell script called blinky.sh with above code using echo command (echo "the above code" > blinky.sh). You can create the blinky.sh file on PC and upload it to router using a SFTP client too. Then I made it executable with "chmod +x blinky.sh". Finally I run the script using "./blinky.sh" and it was a success.
(In below photo, the error is because I already unloaded the leds_gpio module)

Sunday, April 14, 2013

Using TI Stellaris Launchpad as a 10Mhz,8 Channel Logic Analyzer

After Googling a bit about the TI Stellaris Launchpad, I found out that it can be used as a 10Mhz 8 Channel Logic analyzer with some small free softwares. The plugin's home page can be found here and please refer it for the further information about the functions. 

You have to download following for this,

First of all you have to unpack the both files for two folders. Then copy "ols.profile-SLLogicLogger.cfg" file from the plugin to "ols-\plugins" folder.
Then we have to flash the code into the launch pad. You can flash "sllogiclogger.bin" in the plugin to the launchpad using TI LM Flasher. If you are a linux user, you can refer to my previous post on flashing  Stellaris Launchpad on linux.

Now you can run "ols-\run.bat" to run the logic analyzer. If you are using Linux, you can run it using "ols-\run.sh" .

In Logic Sniffer, got to Capture->Begin capture and set the configuration as below. Please note that you have to select COM port (here COM47) according to your Stellaris Virtual port on device manager.

Here I'm testing 3.3V Logic '1' on PB0 pin of the launchpad which is the Channel 0 in the logic analyzer. The results was as on the picture and it was a success. So now you can have your own logic analyzer with TI Stellaris Launchpad.

Programming TI Stellaris LaunchPad on GNU/Linux

TI Stellaris LaunchPad has a quite neat ARM Cortex-M4F based microcontroller and built in ICDI debugging interface. It is a great tool for learning ARM architecture for a small price as $12.99 including FedEX shipping. Now this is upgraded to a better board called TI Tiva C launchpad which has a similar microcontroller. You can see an unboxing video of this launchpad from my friend's site.

Here I'm telling you my experience with this launchpad in GNU/Linux. I'm using Fedora based Fuduntu Linux 2013.1 64bit for this. It is a quite fast and simple linux distribution and it is worth while to try. 

First of all I checked about the device drivers availability for this. I'm using Linux kernel 3.5.8 and it got auto detected without any manual driver installation. Here you can see the output of "lsusb" command.

After some research I found out a great post on Stellaris LaunchPad linux support.
According to that I downloaded the LM4FLASH software source and compiled it. Please note that you need to have LIBUSB-DEV dependency to compile this. You can install it by " yum install libusb* " command. In a debian based distro like ubuntu,you may use apt-get instead of yum package manager. Following commands can be used for the whole process according to that post.

git clone https://github.com/utzig/lm4tools.git
cd lm4tools/lm4flash/
sudo cp lm4flash /usr/bin/
After that I programmed the "qs-rgb" example from StellarisWare (now TivaWare) to test it.
You can get the TivaWare software library for TI Tiva C series microcontrollers from here.

The flashing was a success and the colour changing of RGB led on the launchpad was working (as for qs-rgb example),

Saturday, March 30, 2013

Altera Cyclone IV EP4CE6 Testing

As I showed in my previous post,I’m going to test my CoreEP4CE6 board. It is based on Altera Cyclone IV FPGA (EP4CE6E22C8N) . I got my Altera USB Blaster (bought from here) today and tested the FPGA .

I connected the power cable to the FPGA board and connected the JTAG cable from USB Blaster. The both devices were powered by USB. I installed Altera Quartus II Web Edition which is the default IDE for Altera FPGAs. You can download the free web edition from here

I thought to check the board by powering up a LED. I just wanted to connect the LED on PIN11 to Vcc to do this. You can follow the detailed steps on this from here

The schematic diagram:


The pin assignment (according to the schematic of the board):


The hardware test (you can see the LED in bottom left is ON):


Saturday, March 23, 2013

Desoldering Surface Mount Devices (SMD)–The hard way

In my previous post, I used some scavenged parts from an old mother board. These old circuit boards are gold mines as they got many reusable components. They may also have very rare vintage chips too. But desoldering SMD is a quite complex task without proper instrument such as hot air gun,reflow oven or a soldering pot. But you can easily desolder SMD components with small pin count. I recommend upto  8 pin or so using this way, If the pins are so close you may try for higher pin count chips too.

You need a normal soldering iron,soldering wire,some tool to push chips and flux would also be helpful in some cases.

My Flux pen (Kester 951):


My tool(small flat screw driver) to remove chips:


First you have to apply some flux (if you have) and add some solder to the pins of the chip just as normal soldering.Make two solder blob in both sides like in this picture(only for one side is shown).


Then simply heat both sides switching between two sides. Don’t take too much time and it will fry your chip. Simply push the chip from the back side using the tool when the solder is melted on pins and chip becomes loose. It will be better to use tweezers to pull up the chip if you have them. I used that flat screw driver as I don’t have a good tweezer. Finally you have to do is cleaning up the board and the desoldered chip. I haven’t used any special thing for it but I think desoldering wick will be helpful.

I have desoldered  this LM431 chip using this technique. You can see the PCB pads where it was soldered in the below picture too.



Thursday, March 21, 2013

Building Real Time Clock (RTC) module based on DS1307 for Arduino

In this post I’m going to build a Real Time Clock (RTC) module based on popular DS1307 RTC chip for using with Arduino or any other micro-controller platform. DS1307 uses I2C protocol to communicate with the microcontroller.

RTC Module:

This is the circuit we have to build and it has few readily available components. The 3V coil cell battery is used to give backup power to the RTC.  Make sure to solder a 4 pin connector for Vcc,GND,SCL,SDA connections. 1kOhm pull up resistors are used for the I2C bus in the circuit.


I got the 32.768kHz Crystal and 3V CR2032 coil cell battery holder from an old computer mother board. I think they are available at any electronic component shop.


After collecting parts I built the circuit on a piece of veroboard. Total cost was around Rs:70 ($0.55). I used 4pin connector for above mentioned connections. If you don’t have a coin cell battery, make sure to short the two battery pins as on the picture,but you won’t have the backup power in case of a power failure.


Arduino Board:

I’m using my Techduino Pro board which I build on an earlier post along with the my modified CP2102 USB to UART board. Please note that my Arduino is working at 3.3V.


I connected the two boards as follows, You can get Arduino –> ATMEGA328 pinout from here.Even though DS1307 datasheet tells that the operating voltage of the chip is 5V, It worked well even at the 3.3V as I used here. Please be aware of that to avoid unnecessary outcomes.


RTC Module Arduino
Vcc +3.3V or +5V (As you need)
SDA SDA (Analog Pin 4)
SCL SCL (Analog Pin 5)



You can just write a code using Wire library. Make sure that DS1307 sends 7 BCD digits containing date & time. I was lazy to reinvent the wheel and opted to use the DS1307 RTC library for the Arduino. Get it from here and extract to the libraries folder in your Arduino IDE folder (Rename it to RTC after extracting).I modified the example file to show how to use it.

#include <Wire.h>
#include "RTClib.h"


void setup () {
    Serial.begin(57600); // UART initialize
   // RTC.adjust(DateTime("MAY 21 2013","20:40:45")); //you can use this to set initial date/time as you wish

void loop () {
    DateTime now = RTC.now();
// Sending date & time to UART every second    
    Serial.print(now.year(), DEC);
    Serial.print(now.month(), DEC);
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(now.minute(), DEC);
    Serial.print(now.second(), DEC);