Debugging AVR, with Asynchronous UART with UNIX System

Posted in programming on October 21, 2009 by satriant

the case :

if you want to get sumthing controlled by computer or you need a data aquition for your microcontroller device….

ok!!

——–indonesia aja deh—–HIDUP INDONESIA!!!

okeh, now asumsikan bahwa smua pack untuk AVR udah kamu install smua, dan kamu telah bisa meng-compile dan men-download the hex file to modul kamu!!

register di AVR yang menangani masalah UART adalah

UCSRA  = 0×00;
UCSRB  = 0×18; pilihan mode
UBRRH = 0×00;
UBRRL  = 0×19; pilihan baud rate

silahkan liat fungsi masing2 bit di Datasheet :) jangan males ya!!

nah untuk meng-konekan antara komputer dan tuh modul, perlu di initialisasikan

standart io di linux.

stdin n stdout

ni adalah initialisinya :

static int uart_putchar(char ch, FILE* stream);
static int uart_getchar(FILE* stream);
static FILE mystdout = FDEV_SETUP_STREAM(uart_putchar,NULL,_FDEV_SETUP_WRITE);

static FILE mystdin  = FDEV_SETUP_STREAM(NULL, uart_getchar, _FDEV_SETUP_READ);

static int uart_putchar(char ch, FILE* stream) {

if (ch == ‘\n’) {
uart_putchar(‘\r’, stream);
}
loop_until_bit_is_set(UCSRA, UDRE);
UDR = ch;

return 0;
}


static int uart_getchar(FILE *stream) {

char temp;
loop_until_bit_is_set(UCSRA,RXC);
temp = UDR;
uart_putchar(temp, stream);
return(temp);
}

nah itu adalah initialisasi dan fungsi untuk file stream io.

nih main programmnya:

int main(void) {
init_uart();
stdout = &mystdout;
stdin  = &mystdin;
while(1) {
printf(“Hello World UNIX \n”);
delay_ms(1000);
}
return (0);
}

________________________________________________________

PROGRAM LENGKAPNYA

/*
*
*
* Tommy Agustianto
* Progname : Hello World…
* Asych 19200 bps.
*
*/

#define F_CPU 4000000UL
#include <avr/io.h>
#include <avr/iom16.h>
#include <util/delay.h>
#include <stdio.h>

static int uart_putchar(char ch, FILE* stream);
static int uart_getchar(FILE* stream);
static FILE mystdout = FDEV_SETUP_STREAM(uart_putchar,NULL,_FDEV_SETUP_WRITE);

static FILE mystdin  = FDEV_SETUP_STREAM(NULL, uart_getchar, _FDEV_SETUP_READ);

static int uart_putchar(char ch, FILE* stream) {

if (ch == ‘\n’) {
uart_putchar(‘\r’, stream);
}
loop_until_bit_is_set(UCSRA, UDRE);
UDR = ch;

return 0;
}

static int uart_getchar(FILE *stream) {

char temp;
loop_until_bit_is_set(UCSRA,RXC);
temp = UDR;
uart_putchar(temp, stream);
return(temp);
}

void init_uart() {

UCSRA = 0×00;
UCSRB = 0×18;
UBRRH = 0×00;
UBRRL = 0×19;

}

void delay_ms(int ms) {
unsigned int i;
for (i=0; i<=ms; i++) {
_delay_ms(1);
}
}

int main(void) {
init_uart();
stdout = &mystdout;
stdin  = &mystdin;
while(1) {
printf(“Hello World UNIX \n”);
delay_ms(1000);
}
return (0);
}

nah konekin PD0 dan PD1 di AT16, (tx,rx,+gnd) ke komputer..

configuring terminal di linux…

kamu bisa bikin sendiri terminalnya, ini bisa di buat pake lib. termios.h

atau klo ga mau pusing, pke aja minicom…

# sudo apt-get install minicom

nah klo udah, masuk ke terminal dan ketik minicom…

konfigurasi minicom dengan pencet ctrl+a+o

setting parameternya…

trs jalankan program yang tadi…(download dulu)…

dah liat apa yang terjadi di mincom…

* klo karakternya aneh, itu brati baud rate antara si mikon n si komputer blm sama, silahkan setting minicom lagi!!

BEST REGARDS

TOMMY

Tulisan ini dibuat untuk menyukseskan Lomba Blog Open Source P2I-LIPI dan
Seminar Open Source P2I-LIPI 2009.

http://www.informatika.lipi.go.id/seminar/lombablog/
http://www.informatika.lipi.go.id/seminar/

AVR di LinuX – How To…

Posted in programming on September 17, 2009 by satriant

hehe :)

just smile before you read…

banyak compiler untuk microcontroller yang biasanya di pake oleh para hobi dan mahasiswa di indonesia, pada umumnya di lingkungan windows, compiler yang dipakai adalah Codevision dan Bascom. ya tergantung tu mahasiswa maunya pake bahasa apa. Codevision untuk , Bascom untuk Basic, AVR studio untuk Assembly, AVRco untuk Pascal, dan banyak deh..

nah…hampir semua IDE(integrated development environtment) di atas itu ga gratis cuy, yang gratis palingan cuma AVR studio aja, bawaan Atmel.

ok… now… GOIN’ TO OPEN SOURCE…

opensource avr di lingkungan windows = WinAVR…, winAvr ini adalah IDE gratis buat ngompile dan ngedit2 program AVR pake bahasa C…itu cukup?! TIDAK!!

karena nanggung cuy, klo lo migrasi sistem stengah2…blm tentu juga wuh windows lo tuh asli..nah lo…

AVR-GCC & Linux

ini adalah solusinya…

pilih salah satu distro linux ksukaan lo..(penulis make ubuntu 8.1)

ok.. the steps

1. make sure klo lo pake linux..

2. download paket yang di butuhkan

$ sudo apt-get install gcc-avr

$ sudo apt-get install avr-libc

$ sudo apt-get install avrdude

3. tulis program contoh…misal testled.c

#define F_CPU 12000000UL  //setting crystal yang lo pake
#include <avr/io.h> //standart file IO header
#include <avr/iom16.h> // lib buat atmega16, lo pake apa..misal atmega8, iom8
#include <avr/delay.h>

void delayms(uint16_t millis) {
uint16_t loop;
while ( millis ) {
_delay_ms(1);
millis–;
}
}

int main(void) {
DDRC = 0xFF; /* set jadi Output..*/
while(1) {
PORTC = 0×00; /* LED on */
delayms(1000);
PORTC = 0xFF; /* LED off */
delayms(1000);
}
return 0;
}

4. Buat Makefilenya…

#
# Makefile for Tom’s AVR-Board with STK200 Parallel Programmer
# by Tommy Agustianto <satria.nt@gmail.com>
# ver 0.1
#

CC=avr-gcc
CFLAGS=-g -Os -Wall -mcall-prologues -mmcu=atmega16
OBJ2HEX=avr-objcopy
AVRDUDE=avrdude
TARGET=testled

program : $(TARGET).hex
$(AVRDUDE)  -p m16 -P /dev/parport0 -c stk200 -U flash:w:testled.hex
if=$(TARGET).hex -v=2
%.obj : %.o
$(CC) $(CFLAGS) $< -o $@

%.hex : %.obj
$(OBJ2HEX) -R .eeprom -O ihex $< $@

clean :
rm -f *.hex *.obj *.o *~

okeh…smua udah terinstal dan lo juga udah buat file yang di perlukan , jangan lupa tapo tuh testled.c dan Makefile di folder yang sama…

dan ….coba dah lo ketik

make

klo smuanya benar, nanti akan ada tulisan bgini..

tommy@xsatria:~/myprojects/AVR-Linux$ sudo make
[sudo] password for tommy:
avrdude   -p m16 -P /dev/parport0 -c stk200 -U flash:w:testled.hex

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0×1e9403
avrdude: NOTE: FLASH memory has been specified, an erase cycle will be performed
To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file “testled.hex”
avrdude: input file testled.hex auto detected as Intel Hex
avrdude: writing flash (214 bytes):

Writing | ################################################## | 100% 0.18s

avrdude: 214 bytes of flash written
avrdude: verifying flash memory against testled.hex:
avrdude: load data flash data from input file testled.hex:
avrdude: input file testled.hex auto detected as Intel Hex
avrdude: input file testled.hex contains 214 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.20s

avrdude: verifying …
avrdude: 214 bytes of flash verified

avrdude: safemode: Fuses OK

avrdude done.  Thank you.

nah, skarang lepas kabel download lu…dan hehehehe…

IT WORKS…isn’t it?

nih skematik stk200 gw…cuma modal goceng bro…

ga usah pake buffer2an…cuma resistor 4buah n lpt male connector..

toms stk200

toms stk200


Tulisan ini dibuat untuk menyukseskan Lomba Blog Open Source P2I-LIPI dan
Seminar Open Source P2I-LIPI 2009.

http://www.informatika.lipi.go.id/seminar/lombablog/
http://www.informatika.lipi.go.id/seminar/


cara pake pointer di C

Posted in programming on September 10, 2009 by satriant

misal kita punya variabel rumah tipenya integer.   —> int rumah;

nah tuh rumah ada isinya 3 orang..                         —> rumah = 3;

nah ini adalah alamanya dengan menggunakan referensi(&) —> alamat_rumah = &rumah;

next….

nah…

analisa potongan code ini :

int rumah;

int *p; //ini lo baca, nilai yang di tunjukan oleh P

p = &rumah; // nilai P itu adalah alamat Rumah misal 1771

*p = 100; //nah ini brati, nilai yang di tunjukan oleh P adalah 100,

//nilai yang di tunjukin P tiu adalah alamat rumah, nah alamat rumah kan 1771,

//nah alamat 1771 itu di isikan oleh nilai 100;
ok!!

xsatria Rock-ET ver 1.0 [Meteorology & Technology]

Posted in xsatriarobotics on August 11, 2009 by satriant

rock-ET ver 1.0 by Tommy Agustianto

rock-ET ver 1.0 by Tommy Agustianto

the rocket can measure the different of Grafity, when the rocket lauched..the Gravity will be measure by

ADXL type sensor, that can detect the diff of G’….hehe….

not only grafity but also so many things that the rocket can do…measure the temperature, Humidity and Air Pressure….

the data transmitted from the rocket to the ground base [we call it as GROUND SEGMENT] via Wireless Serial Connection.

it’s up to 2 km far…hohoho……

@ the ground segment,we can see the measurement result of the rocket!! before fly away to the sky….the rocket was Calibrated first, to minimalize the error, so the result can closely accurate….

I’ made the software for the ground segment with C, that the software can logging and make a graphic.

I use ATmega8 for controller, I think it’s enough…

@future, I’m planning to make a Inertial Rocket with Navigation System…

so I can control the rocketttt…and fly to moon…….

heheheheeeee……

best regards….

Tommy Agustianto

JIKA KAMI BERSAMA

Posted in my extraordinary life on August 10, 2009 by satriant

ika Kami bersama, nyalakan tanda bahaya
Jika kami berpesta, hening akan terpecah..
Aku, dia dan mereka memang gila memang beda,,
Tak perlu berpura-pura,, memang begini adanya..

Dan kami di sini,,, akan terus bernyanyi…

Dan jika kami bersama nyalakan tanda bahaya..
Musik akan menghentak.. anda akan tersentak!!
Dan kami tahu anda bosan dijejali rasa yang sama
Kami adalah kamu,, muda, beda dan berbahaya..–

(Ini lagunya you’re ready…)  –SDA–
Lepaskan semua belenggu yang melingkari hidupmu
berdiri tegak menantang di sana di garis depan..
aku berteriak lantang untuk jiwa yang hilang..
untuk mereka yang selalu tersingkirkan..
ketika tiada beban lagi untuk berlari,.
Ketika tiada orang yang akan peduli
Aku dan dia selalu menunggumu di sini..
angkat sekali lagi..

Dan kami di sini,,, akan terus bernyanyi.,..

Dan jika Jika Kami bersama nyalakan tanda bahaya..
musik akan menghentak.. anda akan tersentak!!
Aku, dia dan mereka memang gila memang beda,,
aku adalah kamu,, kita muda dan berbahaya..

Dan kami di sini,,, akan terus bernyanyi…

Dan jika Jika kami bersama nyalakan tanda bahaya..
musik akan menghentak.. anda akan tersentak
dan kami tahu anda bosan dijejali rasa yang sama
Kami adalah kamu,, muda beda dan berbahaya..

Dan jika Jika kami bersama nyalakan tanda bahaya..
musik akan menghentak.. anda akan tersentak!!
dan kami tahu anda bosan dijejali rasa yang sama
Kami adalah kamu,, muda beda dan berbahaya..

Write and Read Memory to a File…

Posted in programming on August 3, 2009 by satriant

huh…this my task job for this month…

how to due a memory test in embedded system….

early I dun’t know what things I’ll doin’ first, but now…

I’ve just rec a bright way…

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

	int main(void)
	{
		int counter;
		double *ptr_d;
		FILE *ptr_fp;

		/* Part A */
		ptr_d = (double *)malloc(10 * sizeof(double));
		if(!ptr_d)
		{
			printf("Memory allocation error!\n");
			exit(1);
		}else printf("Memory allocation successful.\n");

		/* Part B */
		for(counter = 0; counter < 10; counter++)
			ptr_d[counter] = (double) rand();

		/* Part C */
		if((ptr_fp = fopen("test.txt", "wb")) == NULL)
		{
			printf("Unable to open file!\n");
			exit(1);
		}else printf("Opened file successfully for writing.\n");

		/* Part D */
		if( fwrite(ptr_d, 10*sizeof(double), 1, ptr_fp) != 1)
		{
			printf("Write error!\n");
			exit(1);
		}else printf("Write was successful.\n");
		fclose(ptr_fp);
		free(ptr_d);

		/* Part E */
		ptr_d = (double *)malloc(10 * sizeof(double));
		if(!ptr_d)
		{
			printf("Memory allocation error!\n");
			exit(1);
		}else printf("Memory allocation successful.\n");

		/* Part F */
		if((ptr_fp = fopen("test.txt", "rb"))==NULL)
		{
			printf("Unable to open the file!\n");
			exit(1);
		}else printf("Opened file successfully for reading.\n");

		/* Part G */
		if(fread(ptr_d, 10 * sizeof( double ), 1, ptr_fp) != 1)
		{
			printf( "Read error!\n" );
			exit( 1 );
		}else printf( "Read was successful.\n" );
		fclose(ptr_fp);

		/* Part H */
		printf("The numbers read from file are:\n");
		for(counter = 0; counter < 10; counter++)
			printf("%f ", ptr_d[counter]);

		/* Part I */
		free(ptr_d);
		return 0;
	}


Part A: Memory Allocation

After some variable declaration we start the program with a memory allocation statement. A piece of memory is requested using malloc with a size of 10 times the size of a double. A pointer ptr_d is used to point to this piece of memory. The rest of part A does some simple error handling.

Part B: Generating Random Numbers

Part B is used to generate some random numbers (using rand function) that are placed into our allocated piece of memory. We request for 10 random numbers. The rest of part B does some simple error handling.

Part C: Open a File for Writing

Part C creates an empty file for writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file. In order to open a file as a binary file (instead of text), a "b" character has to be included in the mode string. The rest of part C does some simple error handling.

Part D: Write the Array

In part D the content of the array is written to the file that was opened in part C. After the array content has been written to the file, the file is closed (fclose function) and the allocated memory is released (free function.) The rest of part D does some simple error handling.

Part E: Memory Allocation

Once again a piece of memory is allocated. This piece of memory is used to write the memory to after we have read it from the file in the next part. The rest is some simple error handling.

Part F: Open Binary File for Reading

Almost the same as part C, but instead of opening the file for writing the file is opened for reading by using "rb" in the mode string. The rest is some simple error handling.

Part G: Reading the Binary File

Almost the same as writing the entire array to the file, but instead we use the fread function to read the content of the file. After the read the file is closed using the function fclose. The rest is some simple error handling. We now have written memory content to a file and read the content of the file back into another piece of memory. So we could have stopped here, but it's always nice to visualize things and that is where the last part is for.

Part H: Display Content

Once again we make a loop. This loop is used to print each member of the array onto the screen, nothing special.

Part I: Free Memory

As a last act we free the memory that we asked for in part E, so we don't create any memory leaks.

Basic Unix Console Commands..

Posted in programming on July 17, 2009 by satriant

The general format of Linux command line :

$ command -options target

Where target is target filename or expression

Some Commonly used Linux commands : -

Showing Currently working directory

The command prints the current working directory , for example

$ pwd
/home/tommy

It shows /home/tommy because /home/tommy is the currently working directory .

Listing files in the directory : -

ls -a :- Displays all the files in the directory , by default ls does not show hidden files( hidden files start with (.) )

ls -l :- Displays the detailed listing of the files in the directory , information like Permission , links , owner , group , size , date , name are displayed

ls -S : the -S option displays the file list in a sorted fashion with the biggest sized file displayed first

ls -sS : the -s option displays file size before the filename combined with -S option it displays a sorted list of files currently in directory with the filesize infront of the filename.
ls -Sr : the -r option combined with -S displays the sorted list of files in the current directory with the smallest sized file displayed first.

ls -sSh : the command displays the sorted list of files in the directory with the file size displayed in a more understandable fashion.

ls -F : this command displays the list of files and directory with directories ending with (/) , executable files with (*) , Symbolic links with ( @)

Removing Directories/File : -

rm directory_name/File_name : Removes directory , Files

rm – i filename/directory_name : Removes directory/file with confirmation

rm -rf filename/directory_name : Removes directory and sub-directory recursively , -f stands for Force

rm -r Directory_Name : Removes directory if it is empty

Copying completely one directory to another directory

cp -r source_directory_name destination_directory_name

-r stands for Recursively

Creating Archives :

gzip (GNU Zip)

gzip can be used for compressing a single file , it is not meant for compressing entire directories as other file formats do . The default extension used bu gzip archives is (.gz) .

gzip filename.ext would create a file name filename.gz and replace the existing filename.ext file with filename.ext.gz file which is compressed gzip archive , the gzip command retains the file’s attributes the modification,time stamp, access etc.

The compression level of the file can be varied by using options from 1 to 9 while compressing a file

gzip -1 filename.ext would compress the file quicker but with less compression.

gzip -9 filename.ext would compress the file slower but with more compression.

the default compression level is 6.

The filesize of compressed gzip archive would depend on the orignal file format it would do well with a non – archived file such as txt,doc,bmp etc but would fair poorly with JPG , PNG etc which are already compressed by some algorithm.

The gzipped file can be decompressed by using the gzip -d or gunzip command at the command line.

the default file extension used by gzip archives is .gz if you want to use a different file extension it could be done by using the -S option
example : gzip -S .x filename.ext would create a archive by the name of filename.ext.x

tar ( Tape archiver )
The tar program combines a number of files and directory in a single file which then can be compressed using a gzip or bzip2 program to reduce it’s file size.

tar -cvf file.tar file1 file2 file3 file4 : This would create a tar archive combining the file1 file2 and file3 into a single file the archive have the same name as the file1 since we have specified the -f option which makes tar use the first option as the filename of the archive , -c tells the tar program to create a archive and -v option displays all the background information on the screen.

tar -cvf file.tar file1.tar file/ : This command would create a archive named file.tar with file1.tar and file subdirectory as the content of the archive .

tar -cvzf file.tar.gz file1 file2 file3 file/ : This command would create a tar file consisiting of the files and directory specified and then the file is compressed using the gzip program, to create a final archive file.tar.gz.

tar -cvjf file.tar.bz2 file1 file2 file3 file/ : This command would create a tar file consisiting of the files and directory specified and then the file is compressed using the bzip2 program, to create a final archive file.tar.bz2

tar -xvf file.tar : This command would extract all the files contained in the tar file file.tar

tar -xvjf file.tar.bz2 : This command would extract all the files contained in the file file.tar.bz2 , it would first call the bzip2 program to extract the file.tar and the call tar to extract the file.tar and it’s conetent.

tar -xvzf file.tar.gz : This command would extract all the files contained in the file.tar.gz , it would first call the gzip program to extract the file.tar and then call tar to extract file.tar and it’s content.

If you have created the file.tar but want to add some file(s) later it can be done using the following command and using the -rf option .
tar -rf file.tar file(s)

bzip2
The bzip2 is similar to gzip program but compresses file better and more effectively as compared to gzip program . The default extension used by bzip2 program is (.bz2) , the usage of bzip2 is very similar to the gzip program but has some additional options , which are described here .

bzip2 -k filename.ext : This commmand would create a archive of the filename.ext but would also keep a copy of the orignal file unlike gzip which replaces existing file with the the new archive file.
the bzip2 program also has different compression level ranging from 1 -least to 9-maximum . which can be set by using syntax like : bzip2 -1 filename.ext

bzip2 archives can be extracted by using the bzip2 -d option or by using the program bunzip2 .

Displaying file in the console

$ cat file-name(s)

The above command displays the content of file one after the another .

cat v1 v2 v3 > v4 This statement would combine the content of textfile v1,v2,v3 and create a new file v4 having all the content of three files.

cat v4 >> v5 This statement would append v4 file at the end of file v5. To end the statement type (Ctrl + D (EOF))

cat > filename << STOP This statement would create a filenamed filename at the console and accept input from the user for the file , the file is ended(terminated ) on pressing Ctrl + D.


$ more file-name

The above command displays the content of file page-wise , asking user to press a key usually “space bar” when the entire screen is filled to move on to next screen. The command is particularly useful for long files.

$ head File-Name

The above command displays the first few lines of the file .

$ tail file-name

The above command displays the last few lines of the file .

$ wc file-name

The above command would count the lines , words and characters of the file .

Creating Soft-Link/File -Aliases

If you are right now in /home/xyz directory and you issue the following command , it would create a soft-link of the file( file-name ) in the directory /home/xyz

$ ln -s /path/file-name

Searching Commands

$ grep -r “Text” *

The above command would display all the files in the current directory and all it’s sub-directory having “Text” by searching recursively .

$ grep -n “Text” filename

The above command search for “Text” in the file-name and displays the line-number where the text was found .

$ grep “file[- ] name “ file

The above command searches for text “file-name” and “file name” in the file and displays it on the screen .

$ find file-name

the above command searches for file-name in directory hierarchy .

Some Other Miscellaneous Commands

$ cal
Commands displays calendar on the screen

$ clear
The command clears the console screen of any text

$ man command
Gives information about command

$ passwd
Above command allows changing of password of logged in user

$ df
Above command displays the free diskspace .

$ who
The command shows the user who are logged into the system .

$ env
Shows environment variables

$ ps
Shows running processes

$ top

The above command shows a dynamic real-time view of running system . It displays system summary information as well as list of task being managed by the linux kernel .

dont show me..evil side of the world

Posted in my extraordinary life on July 16, 2009 by satriant

huh….

ga percaya…tapi ini nyataaaaaa……


15-07-2009 at 16:25 @platinum margocity depok..

How To Build Kernel Module…

Posted in programming on July 10, 2009 by satriant

Alo…

I know that there are books out there that discuss building Linux kernel drivers/modules. Try searching Amazon.com..hehehe…

maybe just a little source in indonesia about the linux programming, expecially linux drivers

Linux kernel modules should work, regardless whether you use Ubuntu/Xubuntu, or any of the other flavors of Linux… at least that is my understanding.

Here’s a simple kernel module you can play with…

HelloWorld.c:

PHP Code:
#include <linux/module.h>

static int __init hello_world( void )
{
printk( "hello world!\n" );
return
0;
}

static

void __exit goodbye_world( void )
{
printk( "goodbye world!\n" );
}

module_init( hello_world );
module_exit( goodbye_world );

To compile it, save this statement into a file called Makefile:

PHP Code:
obj-m += HelloWorld.o

Then on the command line, run this command to build the kernel module:

Code:
$ make -C /lib/modules/`uname -r`/build M=`pwd`

To load the kernel module:

Code:
$ sudo insmod HelloWorld.ko

To unload the kernel module:

Code:
$ sudo rmmod HelloWorld

If you examine the tail end of the file /var/log/messages you will see the output generated by the kernel module.

Code:
$ sudo tail /var/log/messages

Driver Module

Posted in programming on July 7, 2009 by satriant

Mau buat kernel module atau linux driver ???
nih gw kasi templatenya…..
Tapi sebelumnya, apa sih definisi dari kernel module ??
Sederhananya, kernel module adalah modul yang merupakan bagian dari suatu program yang dapat di load dan di unload ke dalam kernel sesuai permintaan (definisi simplenya ;) ). Modul ini di tulis memakai bahasa C. So, kalau kalian udah pernah buat program pake C, udah pasti lu bisa buat kernel module.
Berikut ini (halah resmi amat kata-katanya hehehee) template kernel module, yang bisa dipakai untuk coba-coba ataupun untuk kebutuhan teman-teman semua heheee….
Gimana ntuk mengerti cara kerjanya ?? mending ikutin dan coba aja dulu code berikut ini :

Langkah 1: Buat satu file bernama template.c, trus masukin code berikut:

/*
* template.c – template for device driver
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
*/

#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <asm/uaccess.h>
#include “template.h”

static int dev_open = 0;

/**
* on io controller device
* this function will be execute if ioctl() function call
* (under user space)
*/
static int device_ioctl(struct inode *inode, struct file *filp, unsigned int cmd,
unsigned long arg)
{
int retval = SUCCESS;

printk(KERN_INFO “Device ioctl\n”);
switch (cmd) {
case IOCTL_XXX:
printk(KERN_INFO “IOCTL_XXX\n”);
break;
case IOCTL_YYY:
printk(KERN_INFO “IOCTL_YYY\n”);
break;
default:
printk(KERN_INFO “IOCTL default\n”);
break;
}
return retval;
}

/**
* on write device
* this function will be execute if write() function call
* (under user space)
*/
static ssize_t device_write(struct file *filp, const char *buff, size_t len,
loff_t * off)
{
printk(KERN_INFO “Device write\n”);
return SUCCESS;
}

/**
* on read device
* this function will be execute if read() function call
* (under user space)
*/
static ssize_t device_read(struct file *filp, char __user *buf, size_t count,
loff_t *f_pos)
{
printk(KERN_INFO “Device read\n”);
return SUCCESS;
}

/**
* on open device
* this function will be execute if open() function call
* (under user space)
*/
static int device_open(struct inode *inode, struct file *filp)
{
printk(KERN_INFO “Device open\n”);
/*
* We don’t want to talk to two processes at the same time
*/
if (dev_open)
return -EBUSY;

dev_open++;
try_module_get(THIS_MODULE);
return SUCCESS;
}

/**
* on close device
* this function will be execute if close() function call
* (under user space)
*/
static int device_release(struct inode *inode, struct file *filp)
{
printk(KERN_INFO “Device release\n”);

/*
* We’re now ready for our next caller
*/
dev_open–;
module_put(THIS_MODULE);
return SUCCESS;
}

/**
* file operatio for this device driver
*/
static struct file_operations device_fops = {
.owner = THIS_MODULE,
.ioctl = device_ioctl,
.write = device_write,
.read = device_read,
.open = device_open,
.release = device_release,
};

/**
* on init module
* this function will be execute at inserting module
* (using insmod)
*/
static int __init device_init(void)
{
int ret;

/*
* Register the character device
* mknod /dev/driver_template c 100 0
*/
ret = register_chrdev(MAJOR_NUM, DEVICE_NAME, &device_fops);
if (ret < SUCCESS) {
printk(KERN_ALERT “Error: register %s, : %d\n”, DEVICE_NAME, ret);
return ret;
}
printk(KERN_INFO “Device init module done\n”);
return SUCCESS;
}
module_init(device_init);

/**
* on clean up module
* this function will be execute at removing module
* (using rmmod)
*/
static void __exit device_exit(void)
{
int ret;
ret = unregister_chrdev(MAJOR_NUM, DEVICE_NAME);
if (ret < SUCCESS) {
printk(KERN_ALERT “Error: unregister %s, : %d\n”, DEVICE_NAME, ret);
}
printk(KERN_INFO “Device cleanup module done\n”);
}
module_exit(device_exit);

MODULE_AUTHOR(”Tommy Agustianto”);
MODULE_DESCRIPTION(”template driver”);
MODULE_LICENSE(”GPL”);

Langkah 2: Buat file dengan nama template.h, trus isikan dengan code berikut:
/*
* template.h – header of driver test
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
*/

#ifndef __TEMPLATE_H_
#define __TEMPLATE_H_

#include <linux/ioctl.h>

#define SUCCESS 0
#define DEVICE_NAME “driver_template”
#define MAJOR_NUM 100

#define IOCTL_XXX _IOR(MAJOR_NUM, 0, int)
#define IOCTL_YYY _IOR(MAJOR_NUM, 1, int)

#endif

Langkah 3: Buat file dengan nama Makefile, trus masukin code berikut:

obj-m += template.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
rm -f *.c~ Makefile~ *.symvers

Selesai tahap pertama dan tahap percodingan hehehehe…Langkah selanjutnya adalah mengcompile program tersebut dengan memakai command make, seperti berikut ini:

[root@tommy dev_driver_template]# make

Kompilasi seharusnya tidak mengeluarkan message error.
Langkah berikutnya adalah memasukkan module yang telah dicompile tadi kedalam kernel. Caranya adalah dengan menggunakan comman insmod, caranya:

[root@tommy dev_driver_template]# insmod template.ko

Setelah module di masukkan, seharusnya message berikut muncul:

Device init module done

Selesai deh membuat template sederhana untuk kernel module.
Bagaimana menggunakan kernel module tersebut di user space ??
Gampangnya, anggap saja kernel module (driver) tesebut sebagai file, yang bisa kita buka, tulis, baca, dan tutup.
Berikut contoh applikasi di user space yang memanfaatkan driver tersebut:
NOTE: sebelum menjalankan applikasi, terlebih dahulu membuat device node untuk drivernya,
Caranya: [root@tommy ~]# mknod /dev/driver_template c 100 0

Contoh applikasi :

#include <stdio.h>
#include <errno.h>
#include <sys/ioctl.h>
#include “template.h”
int main(int argc, char *argv[])
{
int handle;
unsigned char temp[10];
/* open device */
handle = open(”/dev/driver_template”, O_WRONLY);
if (handle < 0) {
perror(”/dev/driver_template”);
return -1;
}
/* read from device */
read(handle, &temp, sizeof(temp))
/* write to device */
write(handle, &temp, sizeof(temp))
/* close device */
close(handle);
return 0;
}

Compile contoh applikasi pake gcc: gcc sampleApp.c, trus jalanin hasilnya yaitu: a.out
maka akan keluar beberapa printout dari kernel module (prn_read, prn_write, prn_open, dan prn_release)