Month: December 2015

Home / Month: December 2015

OpenWRT: OpenWRT Failsafe

December 3, 2015 | Article | No Comments

What if you have configure OpenWRT device and turn you device to useless? Or maybe some of configuration make you box inaccessible. But fortunately, OpenWRT has a built in feature for “resetting” your box. It’s called failsafe mode and this feature will attempt to bypass almost all configuration in favor of a few hard coded defaults. The device would boots up in with only essential service running. From this state we can telnet and fix certain problems.

But how we can do it? This article will cover the basic.

In this article I will use TP-Link MR3020

Triggering via Hardware Button (Standard method)

  1. Set our IP address to with subnet mask
  2. Turn off the device and turn it on again.
  3. Immediately after the device boot, press hardware reset
  4. Try to ping to check whether the device has entered failsafe mode.

Here is a video on to do it (for MR3020 device):

Triggering via Keyboard key Combination

  1. Unplug the router’s power cord.
  2. Connect the router’s WAN port directly to your PC.
  3. Configure your PC with a static IP address between and E. g. (gateway and DNS is not required).
  4. Plugin the power.
  5. Connect via serial
  6. Wait until the following messages is passing: Press the [f] key and hit [enter] to enter failsafe mode
  7. Press “f” and the “enter” key
  8. You should be able to telnet to the router at now (no username and password)

Now we have entered failsafe mode. You will get message similar to this:

Note: the root filesystem in failsafe mode is the only SquashFS partition. The JFFS2 is not present. To mount JFFS2 in read-write mode run this command:


Now, suppose you forgot your password you just need to set a new one. A command to do so:


Another common problem is you forgot router. To get it just give command:

uci get network.lan.ipaddr

When you fill the entire JFFS2 or install too big/ too many packages, you can clean the entire JFFS2 partition by executing one of these command:



mtd -r erase rootfs_data


rm -r /overlay/*

After you have done, you can reboot by using:

reboot -f

That’s all. Happy hacking 🙂

What is Assembly Programming Language?

December 3, 2015 | Article | No Comments

Assembly is considered as the oldest programming language. Learning assembly will improve our understanding or machine. In this first article of assembly tutorial we will discuss about what is assembly and why we should learn it.

What is Assembly Language?

Strictly speaking, assembly language is a programming language. It is corresponded to command / statement of computer instruction. The assembly programming is not so machine-independent language as processor has so much variation. In the next article we will cover only assembly language which refer to IBM-PC compatible’s instruction set or known as Intel x86 processor family.

Assembly language is a set of instruction specific to particular computer system. To write a assembly language we need an assembler or compiler which translate our source code to machine language. In term of programming language we won’t see human language as much as C\C++ does, but rather mnemonic for basic instruction like: mov, mul, div, add, sub, inc, etc.

Assembly language is considered as low level programming as it is the closest programming language to machine code. Because of the lack of abstraction in assembly language, assembly programming is also considered as difficult language (but don’t worry, we will discuss it).

Why Assembly Language?

There are many programming language out of there, but why we need to learn assembly? One of reason is to learn computer architecture and give deeper understanding about what is done inside. Another reason would be a certain programming language has difficulties to accessing some machine specific instructions. For a better performance, assembly can be used as it is simple and closest to machine.

Programming in assembly is not always using only assembly language. Once we can interfacing our code with other programming language. Often this method is used for creating program as assembly manages specific implementation of system while higher programming language manage the rest. To do this we need to know how higher language structure and translated into assembly (every language would)

The machine Language

A electronic-based computer only knows two type of value: 1 and 0 known as binary value. In machine language we actually instruct some CPU to utilize register or memory with a fix-size command in binary form. A machine language is built from set of number 1 and 0 and interpreted by CPU. A CPU usually has small program embedded on chip, known as microcode, which translate machine instruction to hardware signals.

As noted before, a machine language instruction is a fix-length instruction. Usually there are 16 bits for a single instruction. The first 8 bits is used for operation code, or opcode, which tell us what the instruction will do or achieve. The next 8 bits is operand.

Let’s see this example:


The first 8 bits is opcode for move instruction which assign a value to specific place. The next operand tell us about location of register AL and what value would fill it.

A register is a high speed memory inside of CPU chip. It is identified in assembly language by 2 or 3 character, such as: AH, AL, CX, or EBX.

Instruction set is set of machine instruction that can be executed by machine. Intel processor family has downward compatibility which means a newer processor can understand instruction for earlier processor.

In earlier of computing, every program must be written in machine language (hence in series of 1 and 0). This is more complicated and frustrating too so people invented assembly language to ease their job.

AT Commands is shortening of ATtention Commands. It is set of command understood by mobile phone and modem. Knowing AT command allow you to control your mobile phone by terminal, or even a modem you use.

In this article we will try to explore AT command using cu command. CU (Call Up) is a little tool for communicating with another system. It is a basic networking application that shipped with most linux (or maybe all) linux distribution. From linux man page we got information that cu is used to call up or connect directly or indirectly to another system and act as a dial in terminal. It can also do simple file transfers with no error checking.

To establish a connection using a modem we can invoke:

cu [ -d ] [ -h ] [ -m ] [ -T seconds ] [ -n ] [ -s speed] [ -t ] [ -e | -o ] Telephone / number

To specify the name of a device for a connection:

cu [ - d] [ -h ] [ -m ] [ -T seconds ] [ -s speed ] [ -e | -o ] -l line

To specify a system name for a connection:

cu [ - d] [ -h ] [ -m ] [ -T seconds ] [ -e | -o ] SystemName

For this article, I will using a modem (old modem which I forget the specification but it has 3.5G capability if I remember it) to perform a connection. Our goal is connecting to modem with cu application while we will discuss other use of AT commands like sending SMS in another article.

What we need:

  • mobile device, in this case modem as I said before.
  • USB cable, this for connecting our device and our computer.
  • Computer, of course! In this case I use GNU/Linux (well obviously)

Before proceeding, please switch to super user!

Device Recognition

First, we plug both of cable-end to the device and computer.

Make sure the device is recognized by computer. To see it, invoke this command:

dmesg | tail -10

That command will give last 10 message from kernel. Make sure you find entries indicated that your computer recognize the device. In my case I have this messages:

[12209.457401] usbserial: USB Serial Driver core
[12209.479009] USB Serial support registered for GSM modem (1-port)
[12209.479129] usbcore: registered new interface driver option
[12209.479131] option: v0.7.2:USB Driver for GSM modems
[12209.481986] option 3-1:1.0: GSM modem (1-port) converter detected
[12209.484529] usb 3-1: GSM modem (1-port) converter now attached to ttyUSB0
[12209.484589] option 3-1:1.1: GSM modem (1-port) converter detected
[12209.486172] usb 3-1: GSM modem (1-port) converter now attached to ttyUSB1
[12209.486229] option 3-1:1.2: GSM modem (1-port) converter detected
[12209.486653] usb 3-1: GSM modem (1-port) converter now attached to ttyUSB2

My device is registered as GSM modem and has attached to ttyUSB0, ttyUSB1, and ttyUSB2. This result might be different in your system but find out these information, especially what terminal is your device attached to. There is no exception to CDMA phone / mobile. Unless it is not detected by system, you can proceed to next stage.

Our device is registered now, then let’s see the /dev directory to make sure.

ls /dev | grep tty

Because my device is attached as ttyUSB0, ttyUSB1, and ttyUSB2, I make sure that these file is present at /dev directory. Once we have confirmed it, we can proceed to next step.

Contacting and Communicating

In this step, we will try to contacting the device with information we got from previous command. Here I use terminal ttyUSB0. Start up terminal and fire cu command. But first, let’s specify our need.

In this article I need half duplex connection so I will give -h switch. The baud rate I use is 38400 (this is standard rate). And the line I use is /dev/ttyUSB0. Now let’s type on terminal:

cu -h -s 38400 -l /dev/ttyUSB0

If you are success, you will see a “Connected.” message on your terminal. Congratulation, in this stage we have established the connection to remote device.

Now, test if AT command is recognized by device. Give this command to your terminal:


You should has OK response from device indicated that your device is supporting AT command.

Sometimes your device echoing every character you type. For example you type AT but in your terminal you see AATT. It would be difficult to see what command you have typed actually. For that case, we will disable the echo by giving command:


And gotcha, you have your terminal give clear message.

To disconnecting your connection, you can type ~. (a tilde followed by a point), and press enter (carriage return). You should see the message “Disconnected” and be returned to your prompt (terminal).

Happy hacking! 😀

Beginning C++: Operators

December 3, 2015 | Article | No Comments

When writing a program we are often demanded to define operations, either calculations, comparison, etc. To do it we need operators and C++ has a complete arsenal that can be used. In this article we will divide our focus into some subjects: assignment operator, unary operators, binary operators, ternary operators.

Assignment Operator

Assignment is a operator for storing a value into a variable or a constant. This operator is symbolized by equal sign (=). Let’s take a look of it in this snippet:

#include <iostream>
using namespace std;

int main() {
	// when declaring a constant we have to assign a value immediately.
	const float PHI = 3.14;

	// declaring variables
	char myChar;
	int myInt;
	double myDouble;

	// assign each variable
	myChar = 'A';
	myInt = 135;
	myDouble = 21.0378;

	// print out the value of each variable
	return 0;

Unary Operator

An unary operator is an operator which only has one operand for the operation. These type of operator has following operators:

Operator Operations Example
+ Make a number become positive +7
Make a number become negative -7
++ Increment C++
Decrement C–

An increment is an incremental of a value on a variable by one. For example a variable C initially has value 4 and we do incrementing it then the value of C now become 5. Similar with increment, a decrement take a variable and do decremental of a value by one. Thus, when C is initially has value 4 and we do decrementing then the value of C will become 3.

There are to type of increment and decrement: pre and post. Both will have same result in the end but they are different in operation.

The pre- (either increment or decrement) would do value-changing first before being used. While in post- (either increment or decrement) the value is changed after being used.

Let’s take a look of how the concept mean:

#include <iostream>
using namespace std;

int main() {
	int x = 5;
	int y = 5;

	cout<	cout<	cout<
	x = 5;

	cout<	cout<	cout<
	cout<	cout<	cout<
	y = 5;

	cout<	cout<	cout<
	return 0;

Binary Operator

In mathematics, a binary operator is an operator which has two operand for its operation. In C++, we divide binary operators into smaller categories: arithmetic operators, logic operators, relational operators, and bitwise operators.

Arithmetic Operator

Arithmetic operators are operators used for computing and calculating a value from another value. Like what we have learned from school, we know there are some operators in mathematics and we have it too on C++:

Operator Operations Example
+ Addition 2 + 7 = 9
Reduction 3 – 1 = 2
* Multiplication 3 * 5 = 15
/ Division 6 / 3 = 2
% Modulo 11 % 3 = 2

You must be familiar with +, -, *, and / operator. But please note for / operator, this operator will result on integer value if both of operands are integers. So if you have a = 5 and b = 2 and do a / b, instead of 2.5 you will get 2. To get a real value, you must supply one of operand (either numerator or denominator) with real-valued number.

Some of you maybe aren’t familiar with modulo operation. In simple way, a modulo operation will give an integer for remainder of division. Let’s take example from the table. We have two number, 11 and 3. When we divide 11 with 3, resulting in 3 and has remainder 2 (number that can’t be divided by 3). The modulo operation will give value 2 as a result. Another example: 6 % 4 will give 2, 19 % 5 will give 4, etc.

Logical Operators

Logical operator is an operator used for operation in which resulting only two distinct value: true or false. It is corresponded with boolean value in previous discussion. There are three operators on this category:

Operator Operations Example
&& AND true && true = true
|| OR true || false = true
! NOT NOT false = true
&& (AND) Operator

AND operation will give true only if both of operands are true. Either from that, this operator will give false. Let’s look at this truth table:

X Y X && Y
1 1 1
1 0 0
0 1 0
0 0 0

Remember that false is represented by zero and true is represented by not-zero value.

|| (OR) Operator

OR operation will give result true if one of operands has true value. Let’s see the truth table below:

X Y X || Y
1 1 1
1 0 1
0 1 1
0 0 0
! (NOT) Operator

Value of NOT operation is an inverse of the operand. Well, actually this operator is an unary operator, but for the sake of simplicity I group it with the rest of logical operators. Let’s look at the truth table:

X ! X
1 0
0 1
Relational Operators

A relational operator is an operation to determine relation between two operands. These operators are simply comparison between two operands.

Operator Operations Example
< Less than (5 < 2) = 0
> Greater than (5 > 2) = 1
<= Less than or equal (3 <= 2) = 0
>= Greater than or equal (3 >= 2) = 1
== Equal (3 == 3) = 1
!= Not equal (3 != 3) = 0

Please note that equal operator is consists of two = symbol.

Bit-wise Operators

Unlikely other programming language, C++ support bit-wise operations. A bit-wise operations used for operation of bit manipulation. Let’s take a look for the this table.

Operator Operations Example
& AND 1 & 0 = 0
| OR 1 | 0 = 1
^ Exclusive-OR (XOR) 1 ^ 1 = 0
~ NOT ~1 = 0
<< Left Shift 5 << 1 = 10
>> Right Shift 10 >> 1 = 5

At glance you might think that these operations are similar to logical operators. Well, that’s true in some way. In bit-wise operation, the operand are every bit on both side while the logical operator use whole number as operand and both operand act only as two distinct value true or false.

Let’s take example for counterparts AND: Suppose we have two number, 5 and 2. In logical operator, both 5 and 2 are treated as true this 5 && 2 will give result true. While in bit-wise operation, we treat 5 and 2 as bits which we have 5 = 00000101 and 2 = 00000010. Then, bit-wise AND would result on:

5 00000101
2 00000010
———— &
5 & 2 00000000

Now, as you can see. We do AND operation for each bit and got result 0. With similar operation we will get 2 when we operating 6 and 2 (guess why?).

An exclusive-OR operation is bit-wise operator which similar to bit-wise OR operator. But it only gives 1 if only one operand is 1 (and other is 0). Otherwise it will give 0.

The interesting part is shifting. Shift operation, like the name, is an operation to shift the bit to a direction, The number that would be shifted is the left operand and it will be shift to x place as given by right operand. Let’s look example for left and right shift.

A left shift (a << b) will shift a to b position in left. Suppose we have two number, 5 = 00000101 and 2 and did left shift like this: 5 << 2, the bits of 5 would be shift in a way that result in 00010100 = 20. Note that the result bit is actually shifted 2 position from previous one.

A right shift (a >> b) will shift a to b position in left. Suppose we have two number, 4 = 00000100 and 2 and did the right shift like this: 4 >> 2, the bits of 4 would be shift in a way that result in 00000001 = 1. Note that the result bit is actually shift 2 position form previous one.

Ternary Operator

Ternary operator is an operator which has 3 operands for operation. It seems odd but the operator consists of 2 symbols ? and :. General scheme for this operator is given below:

expression1 ? expression2 : expression3;

This operator consist of 2 stage: checking and executing. First it will check the condition on expression1. If expression1 result in true, the expression2 will be executed. If not, the operator will execute expression3. Now let’s take a look of this snippet:

#include <iostream>
using namespace std;

int main() {
	// declare 2 variables, x with random-initialized value and y with initial value 5
	int x, y = 5;

	// check if y > 0. It would be true so we have -y as a result of this operation
	x = (y > 0) ? -y : y;

	// Let's make sure the result is same as our prediction
	cout<< x <<endl;


Creating Simple AVR Program: “Running” LEDs

December 3, 2015 | Article | No Comments

In the previous article we have discussed about AVR microcontroller programming in Linux environment and Windows environment. The term program in this case is downloading / store a binary program to your microcontroller using usb programmer and avrdude. If you haven’t read the article I recommended you to read it. It’s not a long article so it would be fine to skim it.

Now, in this article we will discussed about writing a simple program for our AVR microcontroller. What we will need:

  1. Host Operating System, (you can use GNU/Linux or Microsoft Windows Operating System)
  2. AVR microcontroller, embedded as board. In this case I use atmega32
  3. avrdude, this tool is for writing our program to microcontroller
  4. avr-gcc, this tool is for compiling the code
  5. A USB programmer

Now, let’s configure the chip. I have assembly my AVR as follows:

  1. ATMega32 chip
  2. External clock with 16MHz frequency
  3. Eight active low LEDs connected to PORT A
  4. A port for ISP programming connected to PORT B

Well, actually there are more in my board but for this article we will just need those informations.

Please note that I use PORT A for LEDs. You may use other port but you must adjust your configuration with this article. The one I used are active-low LEDs which can only emitted light if we give low voltage. Also note that I use PORT B for ISP programmer and this is the only one PORT to program AVR microcontroller.

I assume we all have prepared the tools. See article for preparing tools in Windows and Linux.

Writing the Codes

When writing the codes, you can use any text editor. For simplicity, we use notepad in Windows and Geany in Linux (remember, any text editor will do).

What I want is some turn on and off some LEDs in a pattern. For every second, I will switch the condition for every LEDs and shift the series to the left. This will give impression like the LEDs are running :3

OK, let’s get to actual code. Write this codes and save it as avr-leds.c

#define F_CPU 16000000UL

#include <avr/io.h>
#include <util/delay.h>

/* our entry point */

int main() {
   /* we used PORT A for LEDs so we will give a little setup */
   DDRA 	= 0xFF;
   PORTA	= 0b11000101;
   /* used for shifting */

   int tmp;

   /* our main loop. The execution goes here */
   while(1) {
      /* setting the running speed. It's a simple delay in 800 miliseconds */

      /* get the least significant bit, in this case is the most right position
         on binary number but it is the most left position on leds */
      tmp = PORTA & 1;

      /* shift the number to the right */
      PORTA >>= 1;

      /* grab the saved bit and shift it to the most right position */
      PORTA |= tmp << 7;
   return 0;

It’s short and simple code. We only write what we need, not completely set other parts.

In this code, we only use port A as output. To do so, we set all the 8 bits to 1 (which has value of 0xFF or 255 in decimal). Port A is then connected to 8 LEDs and I give initial pattern of 0b11000101. Remember that I use active low LEDs, so it will turn on when we give low logic.

To access individual bit of a byte, we use bitwise operation.

The statement:

tmp = PORTA & 1

will give me the least significant byte of PORTA and store it to tmp variable.

Then the statement:

PORTA |= tmp << 7;

will write the most significant bit by the value of tmp variable.

Here you see some


OK, next we will compile the code. To do so open your terminal and invoke this command:

avr-gcc -g -Os -mmcu=atmega32 -c avr-leds.c

That command tell the compiler to compile a single file avr-leds.c but do not link it yet. It’s useful if you have bigger project you can compile each source code separately.

What you need to know is -mmcu switch. It tells compiler what chip we are using now. In this case we are using ATMega32.

The previous command will compile the file into an object file with filename avr-leds.o.

Now, invoke this command:

avr-gcc -g -mmcu=atmega32 -o avr-leds.elf avr-leds.o

This will produce a binary file called avr-leds.elf, which is a GNU executable file. The file format is ELF (Executable and Linkable Format) which is similiar to linux program. However, this is not what we need. We need hex file for AVR.

Now invoke this command:

avr-objcopy -j .text -j .data -O ihex avr-leds.elf avr-leds.hex

This will produce the file we want, an intel hex file. Let me explain what switches we gives

When we write -j switch we tells the avr-objcopy to only copy from that section. In this case we only copy data from section .text and .data. If you have program in assembly before, then you might know what is section.

A -O switch tells the avr-objcopy to produce file with following format. And in our case it is intel hex format (ihex).

The next arguments are the .elf file and .hex file respectively. It means that our input would be avr-leds.elf and will be processed to avr-leds.hex.

Burn the Program to the Device

We use avrdude to do so. Make sure you have connected the device with the downloader and connect it to PC. The downloader I use is USBasp.

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

And we are done!

Graphic Programming using Frame Buffer on Linux

December 3, 2015 | Article | No Comments

Graphics programming is one of interesting subject. While there are many graphic libraries developed, have you ever wonder what operations are performed at lowest level? have you ever wonder, how can your Operating System visualizing any 2D object in your monitor? There is a simple answer, they utilize a frame buffer.

A frame buffer is one of your computer’s component. A frame buffer (sometimes called as frame store) is a video output device that drives a video display from a memory buffer containing a complete frame of data. Frame buffer typically hold color values for every pixel (point that can be displayed) on screen. Color values are commonly stored in 1-bit binary (for monochrome), 4-bit palettized, 8-bit palettized, 16-bit highcolor, and 24-bit truecolor formats. The total amount of the memory required to drive the framebuffer depends on the resolution of the output signal, and on the color depth and palette size.

In this article we will discuss about how to programming, or manipulate a frame buffer. We will also cover a small example as proof of concept.

To use, switch to another tty by pressing ctrl+alt+f(n) where f(n) mean f1 to f7. We did this to see our work. This is because we can’t see the result from terminal within graphical environment. Also it happens that on some system we need to use root privilege to access frame buffer. You can do so by switching to root.

The Special Device File

Everything in Unix and Linux is treated as file, including hardware. In linux which a frame buffer is treated as special device and can be found at /dev/fb0. To access this file we will use low level function too, open().

We will open /dev/fb0 using open() function and get a file descriptor returned by open() function. Save this file descriptor in a variable (integer). Please note that this file descriptor is important as we will manipulate frame buffer later by this file descriptor.

Now, have you ever done file I/O before? Linux may treat everything as file, but we can simply manipulate frame buffer only by reading or writing something to /dev/fb0 (Actually you can, but it’s a little complicated and risky).

Mapping the Frame Buffer to Memory

Instead of doing simple file I/O operation, we will map the frame buffer to memory. To do so we need the file descriptor we got from open() function and pass it to mmap() function. Every single pixel of frame buffer would be mapped into an array on memory. This give us flexibility to traverse the frame buffer or to manipulate any pixel as we want.

But wait, before we did that we must get the actual condition / characteristic of the frame buffer. Information we need is fix screen information and variable screen information of frambuffer. With these information we can determine, how many length, what is the size of frame buffer, what is the maximum width and maximum height, etc.

To get both fix screen information and variable screen information we will use ioctl() function.

The Structure of Pixel Format

Now we have map the frame buffer to memory, what next? Our objective is accessing a single pixel. To accomplish this let me tell you the mapped frame buffer on memory.

The mapped frame buffer is simply (i would say) array of struct with single element of array is a single pixel. The problem is, what bit that frame buffer store for each pixel. You know, there’re some formats just as I said before. Normally frame buffer use either 24 bit per pixel (true color) or 16 bit per pixel (high color). Fortunately, once we have information about variable screen we can determine the bit per pixel.

Now, different format need different technique to manipulate pixel. This is because they used different structure to allocate every pixel. If you encounter 24-bit true color format, it would be easy for you. For every color of RGB you can use simple short integer / char. So in short, you will have 8-bit for Red color, 8-bit for Green color, and 8-bit for Blue color. How about 16-bit high color? For 16-bit high color you have different situation. You have 5-bit for Red color, 6-bit for Green color, and 5-bit for Blue color.

Now look at this picture for 16-bit high color format:

The Codes

Ok, I have present you the basic concept. Now let’s move to the actual code.

edit 1: modify the mapping so it can prevent segmentation fault problem. Thanks to Kamil Muszyński

#include <unistd.h>
#include <fcntl.h>		/* for fcntl */
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>		/* for mmap */
#include <sys/ioctl.h>
#include <linux/fb.h>

#include <stdio.h>
#include <stdlib.h>

int main() {
	long int screensize = 0;
	struct fb_var_screeninfo vinfo;
	struct fb_fix_screeninfo finfo;
	int fbfd;					/* frame buffer file descriptor */
	char* fbp;					/* pointer to framebuffer */
	int location;					/* iterate to location */

	int x, y;					/* x and y location */

	/* open the file for reading and writing */
	fbfd = open("/dev/fb0",O_RDWR);
	if (!fbfd) {
		printf("Error: cannot open framebuffer device.\n");
	printf ("The framebuffer device was opened successfully.\n");

	/* get the fixed screen information */
	if (ioctl (fbfd, FBIOGET_FSCREENINFO, &finfo)) {
		printf("Error reading fixed information.\n");

	/* get variable screen information */
	if (ioctl (fbfd, FBIOGET_VSCREENINFO, &vinfo)) {
		printf("Error reading variable information.\n");

	/* figure out the size of the screen in bytes */
	//screensize = vinfo.xres * vinfo.yres * vinfo.bits_per_pixel / 8;

	/* map the device to memory */
	fbp = (char*)mmap(0, finfo.smem_len, PROT_READ | PROT_WRITE, MAP_SHARED, fbfd, 0);

	if ((int)fbp == -1) {
		printf ("Error: failed to map framebuffer device to memory.\n");
	printf ("Framebuffer device was mapped to memory successfully.\n");

	// Figure out where in memory to put the pixel
	for ( y = 0; y < (vinfo.yres/2); y++ )
	    for ( x = 0; x < vinfo.xres; x++ ) { 
	        location = (x+vinfo.xoffset) * (vinfo.bits_per_pixel/8) + (y+vinfo.yoffset) * finfo.line_length;
	        if ( vinfo.bits_per_pixel == 32 ) { 
	            *(fbp + location) = 100; // Some blue 
	            *(fbp + location + 1) = 15+(x-100)/2; // A little green 
	            *(fbp + location + 2) = 200-(y-100)/5; // A lot of red
	            *(fbp + location + 3) = 0; // No transparency 
	        } else { //assume 16bpp 
	            int b = 10; int g = (x-100)/6; // A little green 
	            int r = 31-(y-100)/16; // A lot of red 
	            unsigned short int t = r<<11 | g << 5 | b; 
	            *((unsigned short int*)(fbp + location)) = t; 
	munmap(fbp, screensize);

	return 0;

That code map our frame buffer into contiguous array of bytes on RAM. That’s why we declare frame buffer pointer as char (byte). The memmap() is used to this purpose.

fbp = (char*)mmap(0,
                    PROT_READ | PROT_WRITE,
                    fbfd, 0);

Which map to the memory with read / write capability and shared.

Any questions?

Beginning C++: Primitive Types and Identifiers

December 3, 2015 | Article | No Comments

What is Identifiers?

Literally, identifiers are tokens / symbols used to identify objects declared in program. Compiler knows object through identifier. Identifier can be a variable name, constants, functions, classes, template, even namespace.

In this article we will discuss identifiers in the smaller scope: variables and constants.

Identifier act as variable (or constant) is a value-container. Both of them can save some values but they are differ in the term of how they save value. A constant can save value but it can only assigned once and the value cannot be modified at runtime. While a variable can save value and the value can be modified or changed at runtime.

Let’s save it up for later and see this little analogy:

Imagine variable and constant as a bottle. We know that a bottle is a container which can contain / save something (especially liquid). Now, the bottle has many types / kinds, such as: soysauce bottle, water bottle, kerosene bottle, gas bottle, etc. Each bottle can save specific type liquid. For example a water bottle can only save water. Imagine there is a mineral-water bottle but it contains kerosene. It’s not suitable and maybe it can bring harm later (if someone think it as a plain water and drink them, you can imagine what will come next).

From the same perspective, variables and constant do so. A variables can save a value. The values can vary but the variable can only hold one specific type of value. We can only set what kind of value the bottle can hold only at declaration. A variable can be “refilled” with another value as long as the value has same data type while a constant is cannot be refilled with another value.

Primitive Data Types

As discussed, either variables or constant can save value. But they can only save value with the same type as they are declared before. The set of values of data which variable can sabe is referred as data types. There are two types of data types: a primitive data types and user-defined data types. For this article we will focus on primitive data types.

What is primitive data type? It is a built in / native data type on C++ programming language. So far, there are four primitive data types supported on C++: integer number, real number, character, boolean. Advancing to next level, we can create a new data type using these primitive data types (let say the primitive data types are the building block to build more complex one) through enumeration process, struct, and class.

Now, how can we declare a variable?

A syntax to declare a variable is as follow:

data_type variable_name;

A data_type is a data type. It can be user-defined data type or primitive data types. While the variable_name is a variable name, an identifier.

How about a constant?

Constant declaration is similiar to variable declaration, except at the declaration the constant must be initialized with some value and preceded by keyword const.

const data_type variable_name = value;

Now let’s write the actual code with variable and constant declaration

#include <iostream>
using namespace std;

int main() {
	// declaring variables
	int i;
	float f;
	char c;
	bool b;

	// declaring constants
	const int j = 10;
	const float k = 3.14;
	const char l = 'A';
	const bool m = true;

	return 0;

From codes above, we have four variables: an integer variable named i, a real-value variable name f, a character variable name c, a boolean variable name b. We also have four constant: an integer constant namej, a real-value constant name k, a character constant name l, a bool constant name m.

We can’t write identifier arbitrary. There are some rules to naming an identifier. Here are the rules for naming identifier:

  • Identifier can’t be chosen from C++ reserved keyword. C++ has reserved keywords such as: for, do, while, int, float, return, etc and pick them for identifier name is strictly forbidden.
  • Identifier name is case sensitive. When you say aVariable and AVARIABLE, C++ distinguish them because they have different case although they are consist of same word.
  • Identifier name must be unique. You cannot declare two variable with totally same name even if the identifier has different data type.
  • Identifier name consists of alphabet, number, or underscore. Any character beside that is considered as invalid name. No symbolic character such as: #, @, ?, !, $, as identifier.
  • Identifier name cannot be preceded by number. Identifier can only preceded by underscore (_) and alphabets. Number can be used as identifier name, but it cannot be placed as first character.
  • Identifier cannot has space.

The Identifier Scope

The lifetime of an identifier, or in some terms the scope where an identifier can be resolved. There are two scope: global and local. This is applied to both variables and constants.

A global variable or constant, is a variable or constant declared outside of any blocks of code. Simply we can say a global variable is placed outside of any function. A global identifier is recognized in whole source code.

A Local variable or constant, is a variable or constant declared inside of a block of code. Simply we can say a local variable is place inside of a function, branching code, looping code, etc. This identifier is recognized only at declared blocks.

Outside from two identifier types, a variable can also be classified as static variable. A static variable is a variable which occupy computer memory permanently (until the program is unloaded). It means the last variable value will be kept. To declare a static variable we can write as:

static data_type identifier_name;

Similiar to normal variable, static variable can be categorized as local-static variable and global-static variable.

Another variable type we have are register variable. A register variable will be stored on CPU register. Register variable provide faster way to store a value. No need to access memory. To declare a register variable, one must do:

register data_type variable_name;

More into Data Types

We have discussed a little thing about data type at above. Now Let’s dive deeper into data types. As stated before, C++ has four built-in primitive data types: integer number, real number, character, boolean. We will cover each category. We will refer to x86 machine.

Integer Numbers

Integer numbers, as hinted by the name, is a set of number of integers. An integer is a whole number (not a fractional number) that can be positive, negative, or zero. Data types for this category are:

Data Type Size (bits) Range
int 16 or 32 -32,768 to -32,767 or
-2,147,483,648, to 2,147,483,647
unsigned int 16 or 32 0 to 65,535 or
0 to 4,294,967,295
signed int 16 or 32 similiar to int
short int 16 -32,768 to 32,767
unsigned short int 16 0 to 65,535
signed short int 16 similiar to short int
long int 32 -2,147,483,648, to 2,147,483,647
signed long int 32 similiar to long int
unsigned long int 32 0 to 4,294,967,295

Real Numbers

Real numbers are number for real-value number. Data types for this category are:

Data Type Size (bits) Range Precision
float 32 1.2E-38 to 3.4E+38 6 digits
double 64 2.3E-308 to 1.7E+308 15 digits
long double 80 3.4E-4932 to 1.1E+4932 19 digits

Character (and string)

Character are data type used for representing a character on computer. Character is based on ASCII. Inside a computer, a character is stored as number representation but it would be presented as a character. A series of character can form a string. A string is defined as sequence of characters and terminated by NULL character. This category has following data types:

Data Type Size (bits) Range
char 8 -128 to 127 or 0 to 255
unsigned char 8 0 to 255
signed char 8 -128 to 127

A string in other hand is formed by series of character. For example, if a single character is ‘A’, a string can be something like “Hello world” or “Learning C++ with Xathrya”.


Often said as logic data type. It has only one data type, bool which has 2 different value: false (can be represented as 0) and true (can be represented as any number except 0). This data type mainly represent condition of comparison either by operator equality, inequality, greater, less.

Advanced C++: Namespace

December 3, 2015 | Article | No Comments

Let’s imagine a computer without directory nor subdirectory. Any single file would be stored on a single repository / warehouse only. What could it be? Many problems? Absolutely. Because there is only one place to keep file, any single file must have unique filename and unique identity. Another problem occurred when we want to find a file. Searching a file in set of thousand files, isn’t it frustrating?

With directory system (hierarchically), we are helped to organize our files into smaller modules. We can group files with same objectives / functions (for example: videos, accounting report, etc) into single directory.

The same objective goes to namespace. Namespace is C++ mechanism to group a set of file into some “folder” called namespace. With namespace we can prevent conflict of reduplication variable name, constant name, function name, and class name. A different system can still shared same name but they would be separated into different namespace.

Namespace is very useful for large program with high complexity. It means a program can be broken down and reorganize into different namespace.

Our popular namespace would be std. It is a namespace used by C++ standard library to group it’s functions, modules, and classes.

Let say we have two library, A and B. Without namespace, we can’t create two functions with same name (signature). But with namespace, both can use a same name.

Defining a Namespace

To define a namespace, we can use C++ keyword namespace.

namespace namespace_name {
	// declarations

As we can see, a namespace is a simply block / scope of code where every variable, constants, functions, and classes declared can only be known by member of namespace (inside only). When we called any member of namespace scope from outside, we need to write the name of namespace with scope-resolution operator (::). Here’s the example:

#include <iostream>
using namespace std;
int x;

// Defining namespace A
namespace A {
	// declare a variable
	int x = 10;

	// declare a function prototype print() inside namespace A
	void print();

// We implement our prototype inside namespace A
void A::print() {
	// x here is know by print() because we have introduce our function
	// print() as a member of namespace A
	cout<<"The value of x "<<x<<endl;

int main() {
	x = 10;

The codes above has tell us about how to declare variables and functions under namespace A. Now write, compile, and run the code. What is the value of x?

There are two x’s. One is x inside namespace A, the one that recognized by function print(). The other one is global variable x which is known by function main(). Where a function print() is called, it only know variable x inside the namespace namespace which make it call only. While the function main() only know variable x as global variable (the one inside namespace isn’t visible to main()). So that’s why, you would encounter either 0 or random value.

Two namespace? Let’s see the example:

namespace A {
	int x;
	void printx();
void A::printx() {
	cout<<"X inside namespace is "<<;x<<endl;
namespace B {
	int x;
	class Example {
		int number;
		void setNumber(int value) {
			number = value;
		int getNumber() {
			return number;

	void printx() {
		cout<<"Now we have "<<x<<endl;
int main() {
	A::printx();		// print x value inside namespace A
	A::Example ex;		// declaration of class Example


Using namespace

After defining a namespace, we must know how to use it inside of program. In other word we must know how to access variables, constants, functions, or even classes declared inside of namespace. To do so, there are two different approach: Scope resolution (::), keyword using.

Using scope resolution

To recall variable, constant, functions, or classes defined inside a namespace we can use operator :: (scope resolution).


Here’s the example of scope resolution usage:

#include <iostream>
using namespace std;

namespace A {
	int x;
	void setX(int value) {
		x = value;
	int getX() {
		return x;
int main() {
	// assign number to variable x outside of namespace A
	A::x = 10;
	cout<<"X has value: "<<A::x<<endl;

	// Call function setx() outside of namespace A

	// call function getX() outside of namespace A
	cout<<X has value: "<<A::getX()<<endl;

	return 0;

Write, compile, and run. What’s the result?

Using keyword using.

First, let’s observe this code:

#include <iostream>

int main() {
	int number;
	std::cout<<"Input an integer: ";
	std::cout<<"You just entered number "<<number<<std::endl;

	return 0;

On codes above, we’re not giving using namespace std; like we always did. But we can still use cin, cout, and endl like we always did by giving std:: in front of them. That is, std is a namespace and to use member inside namespace std we use using namespace std clause. In general, to use whole namespace we can declare:

using namespace namespace_name;

But is there another way? Suppose we want to use std::cout only and the other is irrelevant (we do not use them). Can we just skip the others? Yes we can. In that case we are using only a single namespace member. Thus we declare something like this:

using std::cout;

In general we can use a member of namespace as:

using namespace_name::member;

Alias Namespace

If we are encounter a namespace has too long name to remember (or complicated name), we can rename it to different name. C++ help us to reduce the complexity by renaming old namespace into new space. This feature is called aliasing, or referring a new namespace to old namespace.

Here’s how you could do that:

namespace new_alias_name = old_namespace_name;

For instance, you want to rename a namespace a_very_long_namespace_to_write to be simple_namespace we can write:

namespace simple_namespace = a_very_long_namespace_to_write;

Nested Namespace

Inside namespace can be defined another namespace. This feature is called nested namespace and allow us to create namespace inside another namespace. C++ gives us capability to achieve high modularity, even for namespace.

A simple code for explaining nested namespace would be:

#include <iostream>
using namespace std;

// declaring nested namespace
namespace outer {
	int i;
	namespace inner {
		int j;

// recall the namespace
int main() {
	// assign value of i and j
	outer::i = 10;		// correct
	// outer::j = 20; 	// wrong
	outer::inner::j = 20;	// correct

	cout<<"The value of i is"<<outer::i<<endl;
	cout<<"The value of j is"<<outer::inner::j<<endl;

	// using outer namespace name
	using namespace outer;
	i = 30;			// correct
	// j = 40;		// wrong
	inner::j = 40;		// correct

	cout<<"The value of i is"<<i<<endl;
	cout<<"The value of j is"<<inner::j<<endl;

	// using inner namespace name
	using namespace inner;
	i = 50;			// correct
	j = 60;			// correct

	cout<<"The value of i is"<<i<<endl;
	cout<<"The value of j is"<<j<<endl;

	return 0;


Now, what’s your comment?

Advanced C++: Mutable Member

December 3, 2015 | Article | No Comments

In the previous article we have discussed a const member function. A const member function is a mechanism for function to prevent it to modify a data.

In practical, const functions is needed to keep purity of class. A non privileged function is restricted to modify member variable. But sometimes we are forced to change data from const function (well, it’s so rare). To do so, we have to declare data as mutable member.

This simple code will tell us about keyword mutable:

#include <iostream>
using namespace std;

class Example {
	mutable int x;
	void setX(int value) const {
		x = value;		// correct
	int getX() const {
		return x;		// correct

int main() {
	Example* p;

	p = new Example;
	cout<<"The x has value "<<p->x<<endl;

	return 0;

In this example, function setX() is allowed to modify x because x is declared as mutable.

AVR Microcontroller Programming in Windows

December 3, 2015 | Article | No Comments

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 ( 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

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:


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

Usage: avrdude [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: <>

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.

Social media & sharing icons powered by UltimatelySocial