Rabu, 16 Juli 2014

Xathrya Sabertooth

Xathrya Sabertooth


Setup Slackware as Basic TFTP Server

Posted: 15 Jul 2014 10:47 PM PDT

TFTP or Trivial File Transfer Protocol is a transfer protocol notable for its simplicity. TFTP is generally used for automated transfer of configuration or boot files between machines in a local environment, such as routers and PXE (Preboot eXecution Environment) mechanism. Compared to FTP, TFTP is extremely limited, providing no authentication and is rarely used interactively by a user.

There are many TFTP implementations, such as:

  • GNU inetutils
  • tftp-hpa
  • atftp
  • tftp-serveretc…

In this article, we will discuss about how to set Slackware as a basic  TFTP server. In specific, we will use tftp-hpa which is included by default. This article is tested using Slackware64 14.0 and tftp-hpa.

Upgrade or Not?

Slackware has shipped a TFTP server by default which is tftp-hpa. The version is 0.49. However we can install the latest tftp-hpa with simple process. If you decided to install the latest version, follow this section. Otherwise you can skip to next section.

Download the latest version of tftp-hpa here: www.kernel.org/pub/software/network/tftp/tftp-hpa/. The latest version is 5.2 which can be downloaded here: www.kernel.org/pub/software/network/tftp/tftp-hpa/tftp-hpa-5.2.tar.xz

Now invoke following series of command to build TFTP (server and client):

tar -Jxf tftp-hpa-5.2.tar.xz  cd tftp-hpa-5.2  ./configure --prefix=/usr  make  cd tftp && strip --strip-unneeded tftp  cd ../tftpd && strip --strip-unneeded tftpd  cd ..

Now install it (make sure you are using root privileges):

make install

Set up

By default, the inetd use /tftpboot directory as root directory of the TFTP server. We can however change the directory to something else. Make sure the directory exists, whichever directory you use.

Suppose we want to use /usr/local/tftpboot as root directory:

mkdir -p /usr/local/tftpboot

Then we give a proper permission:

chmod +777 /usr/local/tftpboot  chown nobody /usr/local/tftpboot

Next we add the following entry to the /etc/inetd.conf file as a single line. Or you can edit it and make sure it’s uncommented.

tftp  dgram   udp     wait    root    /usr/sbin/in.tftpd  in.tftpd -s /usr/local/tftpboot -r blksize

Then, restart the inetd using root privileges.

/etc/rc.d/rc.inetd restart

Testing

Now, let’s testing our TFTP server. In our simple scenario, we will create a plain text and fill something there. Then we will download it via tftp.

echo "Xathrya was testing the TFTP server" >> /usr/local/tftpboot/test.txt

To download it, use:

tftp 127.0.0.1 -c get test.txt

And see in current directory, whether we have successfully download it:

cat test.txt

It should print out “Xathrya was testing the TFTP server”.

Senin, 14 Juli 2014

Xathrya Sabertooth

Xathrya Sabertooth


C++ Reserved Words

Posted: 14 Jul 2014 03:33 AM PDT

C++ reserves some words for its own use and for use in C++ libraries. Thus, we shouldn’t use a reserved word as an identifier in a declaration. Reserved words comes in two categories: keywords and alternative tokens.

This article will list C++ reserved words based on C++11 standard.

C++ Keywords

Keywords are identifiers that form the vocabulary or a programming language. By combining the keyword and following the grammar of C++, we do code with C++. These vocabulary may not be used for other purpose, such as serving as variable names.

The following list show C++’s keywords:

alignasexportsizeof
alignofexternstatic
asmfalsestatic_assert
autofloatstatic_cast
boolforstruct
breakfriendswitch
casegototemplate
catchifthis
charinlinethread_local
char16_tintthrow
char32_tlongtrue
classmutabletry
constnamespacetypedef
constexprnewtypeid
const_castnoexcepttypename
continuenullptrunion
decltypeoperatorunsigned
defaultprivateusing
deleteprotectedvirtual
dopublicvoid
doubleregistervolatile
dynamic_castreinterpret_castwchar_t
elsereturnwhile
enumshort
explicitsigned

Alternative Tokens

In addition to keywords, C++ has some alphabetic alternative representations of operators, termed alternative tokens. These, too, are reserved.

Token
Meaning
and&&
and_eq&=
bitand&
bitor|
compl~
not!
not_eq!=
or||
or_eq|=
xor^
xor_eq^=

Notes

The meaning of “auto” keyword has changed in C++11. In C++11 standard, the auto keyword is used to declare a variable with type inferred from the expression or value assigned to it.

In addition to keywords, there are two identifiers with special meaning, which maybe used as names of objects or functions, but have special meaning in certain contexts.

override  final

Also, each name that contains a double underscore __ or begins with an underscore followed by an uppercase letter is always reserved to the implementation and should not be used as an identifier. Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace; such names may be used as identifiers in user-defined namespaces, as names of class members, etc.

The name posix is reserved for a future top-level namespace. The behavior is undefined if a program declares or defines anything in that namespace.(since C++11)

C++11 Concurrency: Part 1 – Introduction to Threading in Standard Library

Posted: 03 Jul 2014 04:12 PM PDT

C++ is growing, as per new standard C++11 now it supports threading. C++11 introduce a new thread library. The new standard define utilities for starting and managing threads. It also contains utilities for synchronization like mutexes and other locks, atomic variables, and other utilities. We will get through this so called C++11 threading by series of articles “C++11 Concurrency”.

To compile the sample code, we need a C++11 compiler. In my case, I use GCC 4.8.1 (on Slackware Linux) or MinGW counterpart (on Windows 8.1). To activated C++11 support features, we need to pass the “-std=c++11″ option to GCC, for example:

g++ filename.cpp -o program -std=c++11

C++ Concurrency

see <atomic>, <condition_variable>, <future>, <mutex>, and <thread> for reference.

Starting from C++11, there are five more headers added to the standard library to support concurrency. They are:

  • atomic
  • condition_variable
  • future
  • mutex
  • thread

These headers are used for multithreading and concurrency. Before the language standard, we would use OS facilities such as POSIX thread or libraries like OpenMP and MPI to enable concurrency using C++.

The <atomic> header defines some definition to allow us using atomic operation. It encapsulate a value whose access is guaranteed to not cause data races and can be used to synchronize memory access among different threads.

The <condition_variable> header defines classes used as condition variable for synchronization.

The <future> header facilitates synchronization access to value.

The <mutex> header is used for allowing mutual exclusion (mutex) of concurrent execution of critical sections of code.

The <thread> header defines thread class, used for spawning threads on C++ and also manage threads as we like.

Starting Threads

see also: Multithreading Support in C++11

Starting a new thread is very easy. We need to create an instance of a std::thread and supply a function and thread will automatically be started and executing the function. The function we talk about can be a function pointer or even a lambda expression.

So first, let’s write a simple code to demonstrate the power of C++ thread.

#include <thread>  #include <iostream>    using std::cout;  using std::endl;  using std::thread;    void hello(){      cout << "Hello from thread " << endl;  }    int main(){      thread t1(hello);      t1.join();        return 0;  }

In the above snippet, we pass a function pointer to thread.

All the threads utilities can be found in the <thread> header. As we see, when constructing a thread instance, we supply a function which will be executed on the fly. The join() method is called to force current thread to wait for the other one. In other word, main thread won’t finish until t1 finish it’s task. If we omit this call, the result is undefined.

We can, however, create more than one thread. To distinguish each of thread, the std::thread class provide a get_id() method which returns an unique id for this thread. We can get a reference to the current thread by std::this_thread variable. Let’s dive in example:

#include <thread>  #include <iostream>  #include <vector>    using std::cout;  using std::endl;  using std::thread;  using std::vector;    void hello(){      cout << "Hello from thread " << this_thread::get_id() << endl;  }    int main(){      vector<thread> threads;        for (int i = 0; i < 5; ++i){          threads.push_back(thread(hello));      }        for (auto& thread : threads){          thread.join();      }        return 0;  }

Sample output:

Hello from thread 2  Hello from thread 4  Hello from thread 3  Hello from thread 5  Hello from thread 6

Our program will start thread one after one and then store them into a vector. This is common strategy to handle several threads.

The threads might interleave. We have no way to control the order of execution of threads. A thread can be preempted at any moment which might lead us to produce following result:

Hello from thread Hello from thread 6  Hello from thread 3  Hello from thread 5  2  Hello from thread 4

So, there is no certainty in which function will be executed first. All decision are taken by OS. The Operating System will decide when resource are available for our threads and execute them on whatever CPU is least occupied.

Aside from function pointer, we can also use lambda expression. Lambda execution is very useful when the executing code is very small thus we don’t necessary need to create a function just for that. We can rewrite the previous code as this one:

#include <thread>  #include <iostream>  #include <vector>    using std::cout;  using std::endl;  using std::thread;  using std::vector;    int main(){      vector<thread> threads;        for (int i = 0; i < 5; ++i){          threads.push_back(thread([]() {              cout << "Hello from thread " << this_thread::get_id() << endl;          }));      }        for (auto& thread : threads){          thread.join();      }        return 0;  }

Threading in Action

Now we will illustrate the power of parallel programming in C++11. We will do something simple yet interesting: parallel merge sort.

Kamis, 10 Juli 2014

Xathrya Sabertooth

Xathrya Sabertooth


Building GCC AVR Toolchain for Slackware64

Posted: 09 Jul 2014 05:19 AM PDT

In this article we will about how to build GCC AVR Toolchain for ARM architecture. The built GCC can be used to compile application into ARM’s machine codes. The toolchain then reside on /usr/local path.

For this article, I use:

  1. Slackware64 14.0
  2. GCC 4.9.0
  3. GDB 7.7
  4. Binutils 2.24
  5. AVR-libc 1.8
  6. GMP 6.0.0
  7. MPFR 3.1.2
  8. MPC 1.0.2

Preparation

We will need some disk space (~2GB should be enough). We also need root access to install it on “system-wide”.

Slackware64 14.0 is optional. You can use any linux distribution you like.

We will create a working directory. We will refer it as $AVRGCC, so $AVRGCC/src should really be something like ~/AVRGCC/src (the ~ means your home directory). So go ahead and create following directory structure:

# set aliases  export AVRGCC=~/AVRGCC  export TARGET=avr  export PREFIX=/usr/local    export BINUTILS_BUILD=${AVRGCC}/build/binutils-build  export GCC_BUILD=${AVRGCC}/build/gcc-build  export GDB_BUILD=${AVRGCC}/build/gdb-build    export BINUTILS_SRC=${AVRGCC}/src/binutils-2.24  export GCC_SRC=${AVRGCC}/src/gcc-4.9.0  export GDB_SRC=${AVRGCC}/src/gdb-7.7  export AVRLIBC_SRC=${AVRGCC}/src/avr-libc-1.8.0    # make base dir, original archives dir (orig), source code dir (src),   # and working / building dir (build)   mkdir ${AVRGCC}{,/{orig,src,build}}    # Make build directory for each component  mkdir ${AVRGCC}/build/{binutils,gcc,gdb}-build

Acquiring the Materials

Download latest packages of GCC, GDB, binutils, and Newlib.You can download it using wget or alternatively download via browser and move it to $ARMGCC/orig. The version we will use is GCC 4.9.0, GDB 7.7, binutils 2.24, and newlib 2.1.0.

cd ${AVRGCC}/orig  wget ftp://ftp.gnu.org/pub/gnu/gcc/gcc-4.9.0/gcc-4.9.0.tar.bz2  wget ftp://ftp.gnu.org/pub/gnu/gdb/gdb-7.7.tar.bz2  wget ftp://ftp.gnu.org/gnu/binutils/binutils-2.24.tar.bz2  wget ftp://ftp.twaren.net/Unix/NonGNU//avr-libc/avr-libc-1.8.0.tar.bz2    wget ftp://ftp.gnu.org/pub/gnu/gmp/gmp-6.0.0a.tar.xz  wget ftp://ftp.gnu.org/pub/gnu/mpc/mpc-1.0.2.tar.gz  wget ftp://ftp.gnu.org/pub/gnu/mpfr/mpfr-3.1.2.tar.gz

Then, extract them to src directory.

cd ${AVRGCC}/src    tar -jxf ${AVRGCC}/orig/gcc-4.9.0.tar.bz2  tar -jxf ${AVRGCC}/orig/gdb-7.7.tar.bz2  tar -jxf ${AVRGCC}/orig/binutils-2.24.tar.bz2  tar -jxf ${AVRGCC}/orig/avr-libc-1.8.0.tar.bz2

Next we need to download some prerequisites, especially GMP (GNU Multiple Precision), MPC (Multiple-Precision Complex), and MPFR (Multiple-Precision Floating Point Reliably) which is used for computation. The prerequisites can be downloaded by invoking following command:

The MPFR, GMP, and MPC is not the latest version, but at least we can build GCC. Supposing your working directory at /home/xathrya/AVRGCC, to obtain MPDR, GMP, and MPC invoke following command:

cd ${GCC_SRC}  ./contrib/download_prerequisites

However, the version of GMP, MPC, MPFR, PPL, CLOOG, and ISL is not the latest version. We can switch to the latest version by download the latest version and create symbolic link to it.

cd ${GCC_SRC}    rm {gmp,mpc,mpfr}    tar -Jxf ${AVRGCC}/orig/gmp-6.0.0a.tar.xz  tar -zxf ${AVRGCC}/orig/mpc-1.0.2.tar.gz  tar -zxf ${AVRGCC}/orig/mpfr-3.1.2.tar.gz    ln -s gmp-6.0.0 gmp  ln -s mpc-1.0.2 mpc  ln -s mpfr-3.1.2 mpfr

Building the Toolchains

Building stage is pretty simple. Honestly speaking, the tricky part is about how GCC and built concept and ordering them in correct order.

Binutils

First, built binutils. This will provide lots of useful tools in building ARM libraries and binaries (like objdump, ld, ranlib, etc). Invoke following commands:

cd ${BINUTILS_BUILD}  ${BINUTILS_SRC}/configure --target=${TARGET} --prefix=${PREFIX} \      --enable-interwork --enable-multilib --enable-shared   make configure-host  make -j4 all  make install

You will notice a few configure options that are really critical for getting things to work properly.

  • –target=avr Says we want a compiler to generate binaries for the avr platform.
  • –enable-interwork This allows for assembling Thumb and ARM code mixed into the same binaries (for those chips that support that)
  • –enable-multilib Multilib allows the use of libraries that are compiled multiple times for different targets/build types
  • –enable-shared – enable the creation of the shared libraries.

GCC

Next we will build the GCC. But please note that we are only intereset on C and C++ so we will ignore other language. To built GCC, do this:

cd ${GCC_BUILD}  ${GCC_SRC}/configure --target=${TARGET} --prefix=${PREFIX} --enable-interwork \     --enable-multilib --enable-languages="c,c++" --with-dwarf2 --disable-libssp \     --enable-c99 --enable-long-long --enable-__cxa_atexit --enable-shared  make -j4 all-gcc   make -j4 all-target-libgcc    make install-gcc install-target-libgcc

Now, the important points are:

  • –enable-languages=”c,c++” - means build C and C++ only.
  • –with-newlib – use Newlib instead of the standard C libraries.
  • –with-headers – this adds a header inlude path during build time and will allow the build to find the newlib header files
  • –enable-__cxa_atexit – allows use of __cxa_atexit, rather than atexit, to register C++ destructors for local statics and global objects and is essential for fully standards-compliant handling of destructors. It also affects the C++ ABI and therefore results in C++ shared libraries and C++ programs that are interoperable with other Linux distributions.
  • –enable-c99 – enable C99 support for C programs.
  • –enable-long-long – enables long long support in the compiler.

avr-libc

Now build our avr-libc

cd ${AVRLIBC_SRC}  ./configure --host=avr --build=`./config.guess` --prefix=${PREFIX}  make  make install

GDB

Optionally you can build GDB. To do so, invoke following:

cd ${GDB_BUILD}  ${GDB_SRC}/configure --target=${TARGET} --prefix=${PREFIX} \    --enable-interwork --enable-multilib  make -j4 all   make install

And that’s it. You should have them now.

Testing

The toolchain can be tested with the minimal code here:

int main()  {     return 0;  }

Jumat, 06 Juni 2014

Xathrya Sabertooth

Xathrya Sabertooth


Installing USBasp Drivers on Windows 8.1

Posted: 05 Jun 2014 04:49 AM PDT

When we are dealing with AVR programming, after create the codes in our development machine we should write the code into the device. For this purpose, we need a tool which we called Downloader or Programmer. This tool will “burn” the code into AVR CPU using spesific port.

One popular tool is USBasp (http://www.fischl.de/usbasp/). This tool is a USB in-circuit programmer which consists of an ATMega88 or an AtMega8 and a couple of passive components. In short, we need no special USB controller anymore.

usbaspver2

Sometimes, we might face a problem installing usbasp drivers on Windows 8.1. But, this article will discuss about how to install those drivers.

Precaution

The method described here will require machine to restart. Make sure you have write down the steps before proceeding.

Identify The Problem

he main problem is that Microsoft doesn’t allow us to install drivers which are not ‘digitally signed’ directly (or easily) on Windows Vista and later version (7, 8, and also 8.1). To get around this, we must temporarily disable the signature verification process.

Phase 1: Disable Driver Signature Enforcement

  1. Enter “start screen” and open “PC Settings”
  2. Choose “Update and recovery” option in the left panel.
  3. Choose “Recovery” option in the left panel
  4. Click on “Restart now” button, below the “Advanced startup” section then click “reset” button to begin resetting.
  5. Once machine is restarted, we will face several options which we can choose by pressing F1-F9. Choose F7 for “Disable driver signature enforcement”

Now, the machine will boot with no driver signature enforcement. We can then install the driver to our machine.

Phase 2: USBasp Driver Installation

Download the driver fro Windows from USBasp (http://www.fischl.de/usbasp/). The latest version is version 2011-05-28.zip which can be downloaded here. Read the readme first. Because I use WinAVR version 20100110, i will extract the libusb_0.1.12.1 folder as D:\libusb_0.1.12.1.

Plug the USBasp in to USB port. Windows will try to recognize the device. It should be recognized but it lacks of driver so the process is not finish.

Open “Device Manager” on “Control Panel”. Look for Other devices. We have USBasp device there.

usbasp-step-1

Right click on it and click on “Update Driver Software…”

usbasp-step-2

Click on “Browse my computer for driver software”.

usbasp-step-3

Type the location of folder “D:\libusb_0.1.12.1″ and then click “Next”.

usbasp-step-4

Windows will give warning as it can’t verify the publisher of the driver. Just ignore it and select “Install this driver software anyway”

usbasp-step-5

Let the installation proceed and wait until it finish.

usbasp-step-6

Done.

AVR Microcontroller Programming in Windows

Posted: 05 Jun 2014 04:01 AM PDT

AVR or Alf & Vegard RISC, is a single chip microcontroller developed by Atmel. AVR is a modified Harvard architecture 8-bit RISC (Reduced Instruction Set Computer) which is famous microcontroller.

AVR microcontrollers has many categories or we will say family. Family basically a group or category based on similiar characteristic and properties. There are six family and fortunately, AVR microcontrollers have same architecture so programming in any kind of family can be guaranteed work on other family. It is only limited to physical limitation such as different amount of flash storage, etc. This is also an advantage using AVR while variety options can be found while developing microcontroller project.

This article will be covering preparation and setting up environment in Linux to develop AVR program.

What you will need:

  1. Microsoft Windows Operating System
  2. avrdude
  3. avr-gcc
  4. avr-binutils
  5. A programmer (will be described later)
  6. AVR Microcontroller, with it’s development board if any, in this case I use AVR ATMega32

Program in Microcontroller

Before I start, let’s talk about program. What is program? A program is simply set of instructions written using machine language so it can be executed by machine. It is also called “binary” which mean to be not human-readable file (but can be understood by machine). For microcontrollers, binary files have type .hex (Intel Hex Format). You can imagine it as .exe in windows application. There are other forms, but in this article we will focus on .hex.

AVR has a small amount of memory in it. It is a storage where program is actually saved. And yes it is small compared by computer. Just some Kilobytes. When the chip starts up, microcontroller will start running whatever program written in flash.

Compiler and Cross Compiling

Compilation for microcontroller is basically similar to compiling program for PC. However, the difference between those two is in term of product of compilation. Compiler for AVR is run in our PC (developer machine), compile source code, and then produce machine language which is specific for the microcontroller (not our PC). This process is called cross compiling.

There are many cross compiler for AVR. I use AVR-GCC for this purpose (in this article and other similar articles, unless told otherwise).

Other tools we need are collectively known as avr-binutils. The binutils packages provide all the low-level utilities needed in building and manipulating object files. In this package, we have AVR assembler (avr-as), linker (avr-ld), and librarian (avr-ar and avr-ranlib). In addition, we get tools which extract data from object files (avr-objcopy), dissassemble object file information (avr-objdump), and strip information from object files (avr-strip).

The last thing to mention is the libc or standard c library. This is library designed for AVR microcontroller, or in other word it is different with our library used for PC programing.

Fortunately, avr-gcc, avr-binutils, avr-libc, and avrdude (later) are already ported into Windows. These Windows version tools are collectively called WinAVR. We can download WinAVR for free from sourceforge site (http://sourceforge.net/projects/winavr/). Download the latest version.

Download / Burn the Program to the Chip

To program microcontroller we need a downloader. It is a special chip that can connect your microcontroller with our computer and write our program into our chip. Every AVR has a set of pins that are programming pins. You have to verify you chip pins and connect the programmer to those pins in the right order.

So what programmer can be used? In this article I used USBasp. Of course you can have other programmers, but I will only talk about this programmer. For information about USBasp, you can visit this link http://www.fischl.de/usbasp/

Now we have know our programmer (USBasp I mean) but then, how to write our program to microcontroller? Relax! We will cover now.

We will use avrdude, a small application to do that. This tool is already included in WinAVR.

Let’s take a peek of avrdude by give this command on our terminal:

avrdude

Let’s see what we have got. You will get something like this:

Usage: avrdude [options]  Options:  -p <partno>                Required. Specify AVR device.  -b <baudrate>              Override RS-232 baud rate.  -B <bitclock>              Specify JTAG/STK500v2 bit clock period (us).  -C <config-file>           Specify location of configuration file.  <strong>-c <programmer>            Specify programmer type.</strong>  -D                         Disable auto erase for flash memory  -i <delay>                 ISP Clock Delay [in microseconds]  -P <port>                  Specify connection port.  -F                         Override invalid signature check.  -e                         Perform a chip erase.  -O                         Perform RC oscillator calibration (see AVR053).  -U <memtype>:r|w|v:<filename>[:format]   Memory operation specification.   Multiple -U options are allowed, each request   is performed in the order specified.  -n                         Do not write anything to the device.  -V                         Do not verify.  -u                         Disable safemode, default when running from a script.  -s                         Silent safemode operation, will not ask you if  fuses should be changed back.  -t                         Enter terminal mode.  -E <exitspec>[,<exitspec>] List programmer exit specifications.  -x <extended_param>        Pass <extended_param> to programmer.  -y                         Count # erase cycles in EEPROM.  -Y <number>                Initialize erase cycle # in EEPROM.  -v                         Verbose output. -v -v for more.  -q                         Quell progress output. -q -q for less.  -?                         Display this usage.    avrdude version 5.10, URL: <http://savannah.nongnu.org/projects/avrdude/>

Woah, that’s too much. But our interest is only in few options. I’ve bold the text which will get our attention. We only interests in -p, -U, and -c options as this is a minimum command we need to invoke along with avrdude.

  • -c : We specify the programmer we type. We are using usbasp so can be replaced with usbasp. Of course if you are using other programmer you must specify. For a complete list about supported programmer, invoke command: avrdude -c asdf. Because asdf is not a valid programmer, avrdude would complaint and print out list of supported programmer to you. Read it and verify your programmer is supported.
  • -U :r|w|v:[:format]: This is the most important command. is either flash or eeprom which is destination where our program will be stored. Next is r (read), w (write), or v (verify) option that you must choose one (only one). Next is which you have to replace with your program path and name. Next is optional format flag [:format] that specify our program format.
  • -p : Specify microcontroller series. Or simply what microcontroller we willl program. For example I will use ATMega32 so i will replace with atmega32.

With these three, we can program in minimal. In this case when I want to program ATMega32 using USBasp with filename avr_leds.hex, the command I use will be:

avrdude -c usbasp -U flash:w:avr_leds.hex -p atmega32

Wait until process is finish and then you can see you microcontroller is programmed now.

Next time I will write some actual writing program for AVR.

Jumat, 23 Mei 2014

Xathrya Sabertooth

Xathrya Sabertooth


Installing OpenMPI from Source for Slackware64

Posted: 23 May 2014 01:51 AM PDT

The Open MPI Project is an open source Message Passing Interface (MPI) implementation that is developed and maintained by a consortium of academic, research, and industry partners.

Message Passing Interface itself is a system designed by a group of researchers from academica and industry to function on a wide variety in parallel computers.The standard defines the syntax and semantics of a core routines useful to a wide range of users writing protable message-passing programs in Fortran77 or the C programming language.

This article will cover about compiling and installing latest OpenMPI for Linux Slackware64.

Obtain the Materials

The latest version (per May 23th, 2014) is 1.8.1. To build the program we need the source code. Download it from OpenMPI site or direct download from here.

Installation

Assuming we have downloaded the source code, we then extract and do compilation process:

tar -xvfj openmpi-1.8.1.tar.bz2  cd openmpi-1.8.1  ./configure CFLAGS=-m64 CXXFLAGS=-m64 --with-wrapper-cflags=-m64 --with-wrapper-cxxflags=-m64  make

The flags we passed to configure script is used to ensure the -m64 flag to gcc and g++ during the build phase and also that mpicc wrapper knows to use -m64 when it compiles our code later.

Next we install it once the compilation process is successful.

make install

To check whether you have successfully install openmpi, invoke this command on terminal:

mpicc --version

Testing

Now let’s make a simple MPI application. Copy this source code and name it as mpi.c:

#include <mpi.h>  #include <stdio.h>    int main(int argc, char** argv) {     int size, rank;     MPI_Init(&argc, &argv);     MPI_Comm_size(MPI_COMM_WORLD, &size);     MPI_Comm_rank(MPI_COMM_WORLD, &rank);       printf("Hello world from %d of %d\n", rank, size);       MPI_Finalize();  }

Compile it using:

mpicc -o my_mpi mpi.c

There is a special way to run MPI program. In general, we do like this:

mpirun <program name> <list of arguments>

Thus, to run our program we invoke:

mpirun my_mpi

Watch it and note the result ;)

Sabtu, 19 April 2014

Xathrya Sabertooth

Xathrya Sabertooth


VHDL: Hello World in GHDL

Posted: 19 Apr 2014 01:49 AM PDT

This is basic code for VHDL. In this article, we use GHDL (http://ghdl.free.fr), as DHL simulator which run on Windows 8.1 platform.

Objective

  1. Know the process to simulate VHDL using GHDL.
  2. Print some output.

Code

We will create an empty entity, named “hello_world”. We then create an architecture based on that entity.

entity hello_world is         -- test bench (top level like "main")  end entity hello_world;    library STD;   library IEEE;  use IEEE.std_logic_1164.all;  -- basic logic types  use STD.textio.all;           -- basic I/O    architecture test of hello_world is     signal counter : integer := 1;  begin     m_print : process is       -- a process is parallel        variable m_line : line; -- type 'line' comes from textio     begin        write(m_line, string'("Xath say: Hello World"));  -- formatting        writeline(output, m_line);                        -- write to "output"        write(m_line, string'("    counter = "));        write(m_line, counter);        writeline(output, m_line);        wait;     end process m_print;  end architecture test;

To simulate the code in GHDL, you should use following steps:

First, we have to analyze the file. In this step, ghdl will creates or update a .cf file which describe the library.

ghdl -a hello_world.vhdl

Second, we run the code.

ghdl -r hello_world

Result

Why it Works

Minggu, 13 April 2014

Xathrya Sabertooth

Xathrya Sabertooth


Raspberry Pi Project: Simple Blinking LED

Posted: 12 Apr 2014 10:42 PM PDT

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 Raspberry Pi.

Make sure you have wiringPi installed on Raspberry Pi already. If not, you can follow this article for guideline.

Objective

  • Make LED blinking.

Prerequisite

Requirement

Following is all materials I use for this tutorial.

  • Raspberry Pi model B
  • 5mm LED active high
  • 330 ohm resistor
  • USB A to micro USB (for powering Pi)
  • Raspbian Wheezy

This article will use Raspbian Wheezy. Although it is not a compulsion for you to update your Raspbian, it is recommended to do.

In this article, we will use pin numbering used in wiring Pi, not the one declared in Raspberry Pi reference.

Circuit

Here is the circuit image, created using Fritzing with Raspberry Pi Library update.

pi_blink_sketch

To build the circuit, attach the LED as shown in the figure. Remember that the long leg of LED is positive leg (also known as anode) and the short leg is negative leg (also known as cathode). The cable from GPIO 0 is directly connect to LED anode. The cathode is connected to resistor 330 ohm and then connected to ground on Raspberry Pi.

Code

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

#include <wiringPi.h>    const unsigned int LED_PIN = 0;  const unsigned int PAUSE = 500;    int main() {     wiringPiSetup();       //-- setup     pinMode(LED_PIN, OUTPUT);       //-- loop     for(;;) {        digitalWrite(LED_PIN, HIGH);        delay(PAUSE);        digitalWrite(LED_PIN, LOW);        delay(PAUSE);        }     return 0;  }

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 0. We use this pin as output pin. Therefore we initialize pin 0 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.

To compile, use following command:

gcc -Wall -o blink blink.c -lwiringPi

To run it, use following command:

sudo ./blink

Result

LED is blinking.

Why it Works

There are two condition of logic in circuit, HIGH and LOW. 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.

Installing Fritzing and AdaFruit Fritzing Library

Posted: 12 Apr 2014 10:23 PM PDT

What is Fritzing?

Fritzing is an open-source hardware initiative that makes electronics accessible as a creative material for anyone. It offers a software tool, a community website and services in the spirit of Processing and Arduino, fostering a creative ecosystem that allows users to document their prototypes, share them with others, teach electronics in a classroom, and layout and manufacture professional pcbs.

It can be used for sketching a prototype. In some of my articles (especially for Arduino, Beaglebone, Raspberry Pi), I used Fritzing to sketch the layout of device I want to build.

AdaFruit Fritzing Library

AdaFruit Fritzing Library is a library of parts for Fritzing, developed by AdaFruit. It is a complement library and enhance Fritzing to use some parts like Raspberry Pi, Beaglebone, and other parts which is not supported by default on Fritzing.

The library is open source project, hosted on github.

Installation

Fritzing

Installing Fritzing is very simple. However you need to download the right package for your Operating System.

  • Go to Fritzing download page. Download the latest version (version 0.8.7b now). Oh, you can make donation too if you want.
  • Extract the content of downloaded package to any folder you want.

Fritzing is now available and ready to start. To start Fritzing, just double click the application:

  • For Windows, double-click “fritzing.exe”
  • For Mac: double-click the “Fritzing” application
  • For Linux: double-click “Fritzing” or try executing “./Fritzing” in terminal

AdaFruit Fritzing Library

Installing AdaFruit Fritzing Library is not so hard. Here we want to install all the parts, not individual part.

  • Go to this link. Click the ‘View Raw’ button to download the latest AdaFruit Library.
  • Open Fritzing application and navigate to File > Open. Choose AdaFruit.fzbz to import the library
  • Once the library is imported, exit the Fritzing. You will be prompted with a box. Make sure to save the changes to your library.

Screenshot

BeagleBoard Black and Raspberry Pi on Fritzing.

beagle_pi

Jumat, 11 April 2014

Xathrya Sabertooth

Xathrya Sabertooth


WiringPi and Raspberry Pi

Posted: 11 Apr 2014 12:13 AM PDT

In this article, I use:

  • Raspberry Pi model B
  • Raspbian Wheezy

What is WiringPi?

WiringPi is a GPIO access library written in C for BCM2835 used in Raspberry Pi. It is designed to be familiar to people who have used the Arduinowiring” system.

Raspberry Pi has a 26-pin General Purpose Input/Output (GPIO) connector and this carries a set of signals and buses. There are 8 general purpose digital I/O pins – these can be programmed as either digital outputs or inputs. Besides input/output capability, one of these pins can be designated for PWM output too. Additionally there is a 2-wire I2C interface and a 4-wire SPI interface (with a 2nd select line, making it 5 pins in total) and the serial UART with a further 2 pins.

The Revision2 Raspberry Pi has an additional 4 GPIO lines on a separate connector which you have to solder on the board.

The I2C, SPI and UART interfaces can also be used as general purpose I/O pins when not being used in their bus modes, giving a grand total of 8 + 2 + 5 + 2 = 17 I/O pins on the P1 connector (plus 4 more on the P5 connector on a Revision 2 Pi).

WiringPi includes a command-line utility gpio which can be used to program and setup the GPIO pins. You can use this to read and write the pins and even use it to control them from shell scripts.

WiringPi is extendable and modules are provided to extend wiringPi to use analog interface devices on the Gertboard, and to use the popular MCP23x17/MCP23x08 (I2C 7 SPI) GPIO expansion chips, as well as module that will allow blocks of up to 4 74×595 shift registers to be daisy-chained together for an additional 32-bits worth of output as a single unit. (You can have several blocks of 4 74x595s if needed) One of the extension modules allows you to use an ATmega (e.g. Arduino, or the Gertboard) as more GPIO expansion too – via the Pi's serial port.

Additionally, you can easily write your own expansion modules to integrate your own peripheral devices with wiringPi as required.

WiringPi supports analog reading and writing, and while there is no native analog hardware on a Pi by default, modules are provided to support the Gertboards analog chips and other A/D and D/A devices can be implemented relatively easily.

WiringPi Installation

Before you can use WiringPi, of course you have to install it inside your Raspberry Pi. The installation is fairly simple. There are two way to get WiringPi installed to Pi: clone from git, download the source tar ball.

Before we go, it is recommended to check whether our distribution is up to date or not.

sudo apt-get update  sudo apt-get upgrade

Remember, this is optional.

Plan A

Installing using git, involving clone the source code tree from git repository. Make sure you have GIT installed. If you do not have one, you can install it by:

sudo apt-get install git-core

Then, clone the WiringPi source code tree by:

git clone git://git.drogon.net/wiringPi

To build WiringPi, do this command:

cd wiringPi  git pull origin  ./build

The second command will fetch an updated version of WiringPi source code (if any) and the third script will start building the library. The script will compile and install the library automatically. Remember to use root privilege to do this.

Plan B

If you can’t or don’t want to use git, use following step for manual download and installation:

Click on following URL: https://git.drogon.net/?p=wiringPi;a=summary

Look for the link marked as “snapshot”. Click on the top one which is the latest source code. You will download a tar.gz file with a name like “wiringPi-f18c8f7.tar.gz”. Note that the numbers and letter after “wiringPi” (f18c8f7 in this case) might be different. They are unique identifier for each release.

Extract and then build the package:

tar xfz wiringPi-f18c8f7.tar.gz  cd wiringPi-f18c8f7  ./build

Testing WiringPi

After success installation, we should check our WiringPi. WiringPi has a utility called “gpio” which is used for GPIO access. Here how we check:

gpio -v  gpio readall

Pin Numbering

Pin numbering of the BCM2835 GPIO port(s) on the Raspberry Pi has been a source of great confusion since the designs for the Pi were first published. In the early days (even beofre hardware was avalable) the default usable GPIO pins were simply referred to by number as GPIO0 through GPIO7. Additionally there were pins for other purposes, SPI, I2C and serial. This was highlighted on the original image on the Raspberry Pi Wiki site too.

Reference: Raspberry Pi GPIO Reference

wiringPi supports its own pin numbering scheme as well as the BCM_GPIO pin numbering scheme, and as of Version 2, it also supports the physical hardware pin numbers (for the P1 connector only). However, simplified wiringPi numbering is really recommended. In this way, our programs will be portable over different hardware revisions without needing any changes.

The following tables give the mapping of the Raspberry Pi GPIO Pins to the (P1) GPIO connector in relation to the pin numbers and the physical location on the connector. This is a representation of the GPIO connector as viewed looking at the board from above. The GPIO connector is to the top-right of the board with the Ethernet and USB sockets to the bottom.

P1 Header

gpio1

RPi_P1_header

P5 Header (Rev. 2 Pi only)

gpio21

RPi_P5_header

Further Read

Installing Adafruit’s Occidentalis on Raspberry Pi

Posted: 10 Apr 2014 07:18 AM PDT

Raspberry Pi, a small computer powered by ARM architecture is a very interesting board for learning embedded system. In this article we will discuss about how to install how to install Occidentalis v0.2 Rubus occidentalis.

For this article I use following:

  1. Slackware64 14.0
  2. Windows 8.1
  3. Raspberry Pi model B
  4. Official Occidentalis v0.2

You can use either Linux (in this article, Slackware) or Windows (in this article Windows 8.1). Just pick one and follow the rest of article for your choice.

About Occidentalis

Occidentalis is a embedded Linux distribution derived from Raspbian Wheezy. This distro is created and maintained by Adafruit Industries. The latest version is Occidentalis v0.2 which is derived from Raspbian Wheezy August 16 2012.

What differs occidentalis and other distro?

Occidentalis is tweaked in purpose to make DIY electronics more fun using Raspberry Pi. Yes, we have kernel modules for DS1307, AD525x, I2C digipots, HMC6352, BMP085, ADS1015, easy PWM/Servo control, and many more. It’s not very surprising as this distro is officially created for learning purpose in some Adafruit materials.

However, Adafruit is not full time linux distro maintainers, which means you can’t expect too much. Adafruit state that this distro is not for beginners or people who are new to linux.

Obtain the Materials

The Operating System images I used is Occidentalis v0.2 which can be downloaded from here. The size is about 900MB, per August 31, 2012.

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. On this article I use my 4GB SD card. 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-based Instruction

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. Extract the image (in this case Occidentalisv02.zip) so you will get an .img file.
  2. Insert SD card into SD card reader and check what drive letter it assigned to. For example G:\
  3. If it is not new, format it. Or at least make sure there is only one partition (FAT32 is recommended).
  4. Run the Win32DiskImager with administrator privileges.
  5. Select the image we have extracted (Occidentalis_v02.img).
  6. 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.
  7. Click Write and wait. The process should be not long.
  8. 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 3 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 Occidentalis_v02.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 Occidentalis_v02.img

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

Linux-based Instruction

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. Extract the image (in this case Occidentalisv02.zip) so you will get an .img file.
  2. Insert SD card into SD card reader .
  3. If it is not new, format it. Or at least make sure there is only one partition (FAT32 is recommended).
  4. 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.
  5. 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=Occidentalis_v02.img of=/dev/sdb
  6. Run sync as root. This will ensure the write cache is flushed and safe to unmount SD card.
  7. 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 Occidentalis_v02.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.

Running the Pi

You have write image and at this point your raspberry pi is ready. Now set up raspberry pi to boot: insert your SD card back to raspberry pi, put on power, plug video output (either HDMI or RCA).

To resize the SD card after installation, you can follow this article. Another way, you can use “raspi-config” utility to do it.

To log in on your Raspberry pi you can use the default login, which is:

Username: pi
Password: raspberry

Side Notes

I2C Support

I2C support is on SDA and SCL pins. To test, connect any I2C device to power, ground, SDA, and SCL. Run this command as root to detect which addresses are on the bus:

i2cdetect -y 0

SPI Support

SPI support is on the CLK/MOSI/MISO/CS0/CS1 pins. To test, connect your logic analyzer / scope to the pins and run following command to send some dummy data to the SPI port.

echo "xathrya test" > /dev/spidev0.0

You can simply read/write the /dev/spidev files to read/write from SPI.

One Wire Support

Most commonly used for DS18B20 temperature sensors. The Pi does not have ‘hardware’ 1-wire support but it can bit bang it with some success. Connect a DS18B20 with VCC to 2V, ground to ground, and Data to GPIO #4. Then connect a 4.7K resistor from Data to VCC.

Run following commands as root. Both command will be used to attach the temperature sub module.

modprobe w1-gpio  modprobe w1-therm

You can then run following command to read the temperature data from the bus:

cat /sys/bus/w1/devices/28-*/w1_slave

WiFi Support

The kernel has been patched with RTL8192cu-based patches.

Adafruit Kernel Source Code

You can get the kernel source code here.

Have fun :D