Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Saturday, September 3, 2011

PyQt: power of Python, beauty of Qt

Qt is very powerful tool for GUI programming. But programming using Qt C++ is not always easy because of unavailability of libraries and difficulty in coding. But Python is powerful and has abundant list of libraries related to virtually anything. Some operations in Python is very easy to use. But the problem of Python is that, it has no GUI its own as handy. PyGTK (Python and GTK) and PyQt (Python and Qt) are the remedy. Here I am explaining how to start with PyQt.
PyQt has no support from QtCreator yet, but the features of QtDesigner can also be used for the PyQt coding. This tutorial explains how to start PyQt programming if you are already aware of Qt C++ programming. This is not just a 'hello world' program, but the code will do something and make you capable of coding your own programs.
In this example, we are building a simple GUI with three LineEdit bars and a single button. When the button is clicked, the numbers entered in the LineEdit a and b are added and the sum is shown in the third LineEdit.


First of all, make GUI widget in Qt Designer and rename the objects a, b, sum and pushButton as shown in screen-shot below. Also make a custom slot named calc_sum(). Save and quit the Designer program.


Now you can see the user interface file named 'widget.ui' (the filename may vary if you changed the widget name while creating your project. Anyway, the filename with .ui as extension is the file we need). We need to create the curresponding python file for user interface. In C++, it is done using uic(User Interface Compiler). In our case, in python, we use a utility named 'pyuic4'. If 'pyuic4' will be automatically installed while you install PyQt. If not, especially in Linux, install it from the repository. Then make the user interface file 'calc_ui.py' (or any name you wish. But for the first time use this name to avoid ambiguity) file using the command:

pyuic4 widget.ui > calc_ui.py

This command will generate a new file named 'cal_ui.py'. This is the user interface file only. We are going to make another file 'calc.py' which will handle the core program. Use a text editor and copy the code below:

import sys
from PyQt4 import QtCore, QtGui

from calc_ui import Ui_Widget


class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Widget()
        self.ui.setupUi(self)
    def calc_sum(Widget):
    value1=Widget.ui.a.text();
    value2=Widget.ui.b.text();
    result=float(value1)+float(value2);
    str_result=str(result)
    Widget.ui.sum.setText(str_result);


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MyForm()
    myapp.show()
    sys.exit(app.exec_())

Save the file. Then run the file:

pyhon calc.py
I am not so good in explaining the code. I think you got the idea of how to make a custom slot and to make a standalone program. If any reader need clarification or more explanation, I will try to explain further.

Saturday, August 6, 2011

Qt Programming in Malayalam Part-2

Before reading this tutorial, read my previous post "Qt programming in Malayalam" if you have not read it yet.
    Have you ever wonder about easy switching from English to other languages such as French, Spanish etc. in software applications? Even though Malayalam switching is rare, translation is possible in Malayalam as well like any other language. Qt provides an easy way of language switching by means of Qt linguist. This tutorial describe how to build a Malayalam switchable application in Qt. An easy to start tutorial is packaged with Qt Help itself. Here is a quick tutorial of how to build a Malayalam application if you have the source code of the English version. Before we start, I assume:
1) You have Qt installed in your PC.
2) You have a very basic knowledge of Qt programming. How to compile, build and all.
    If the above is not qualified, sorry, it is better to pause here and read this and resume. Suppose you have a Qt application in English (If you have not your own, a lot of examples  are there in qtdir/qt/examples. (qtdir is the directory where you installed Qt). For better understanding, I prefer an application named 'QMusicPlayer' from examples(qtdir/qt/examples/phonon/qmusicplayer). You can take other examples as well. Open qmusicplayer.pro using Qt, then build and run it. You will get a minimal musicplayer in English. Now our aim is to make the malayalam version of the same application.


Now we need to edit two files 'main.cpp' and 'qmusicplayer.pro' as follows:

main.cpp

#include

#include "mainwindow.h"
#include

//![1]
int main(int argv, char **args)
{
    QApplication app(argv, args);
    QTranslator translator;
    translator.load("malayalam");
    app.installTranslator(&translator);

    app.setApplicationName("Music Player");
    app.setQuitOnLastWindowClosed(true);

    MainWindow window;
    window.show();

    return app.exec();
}

qmusicplayer.pro

QT        += phonon

HEADERS   += mainwindow.h
SOURCES   += main.cpp \
             mainwindow.cpp
TRANSLATIONS = malayalam.ts

# install
target.path = $$[QT_INSTALL_EXAMPLES]/phonon/qmusicplayer
sources.files = $$SOURCES $$HEADERS $$FORMS $$RESOURCES *.pro *.png images
sources.path = $$[QT_INSTALL_EXAMPLES]/phonon/qmusicplayer
INSTALLS += target sources

wince*{
DEPLOYMENT_PLUGIN += phonon_ds9 phonon_waveout
}

symbian:TARGET.UID3 = 0xA000CF6A

Changes made in the code are highlighted. The changes in code simply add a Translator feature to your application. While running, your application will seek a file named 'malayalam.qm' which contains one to one translation of all English words used in program to Malayalam. 'malayalam.qm' is a binary file and is to be generated from a file named 'malayalam.ts'. This file is automatically generated using the command in terminal:

lupdate -verbose qmusicplayer.pro

Then the newly generated file - 'malayalam.ts' can be seen in the project directory. But it is an empty file and we need to update that file with all one to one translations. To do so, open the file with Qt linguist:

linguist malayalam.ts

If you couldn't find any command like 'lupdate' or 'linguist', most probably, you have not added the qt directory to the PATH. To do this use the following command Linux,

PATH=$PATH:qtdir/qt/bin/

directory may be different and must change it as your needs. Then use 'lupdate' and 'linguist'. If you are still stucked, check whether you completely installed Qt SDK. In Windows, if you are using Qt enabled prompt, I hope there will be no any problem.

    Now I assume you opened 'malayalam.ts' successfully in Qt Linguist. It shows all english words which translation is enabled. (Refer fig). Click on each english word in 'Source Text' list and add curresponding Malayalam translation in the 'English Translation' edit box at the bottom (highlighted on figure). Repeat the process for all words and save. Then File->Release. It will generate the binary file 'malayalam.qm' in the same directory.
    Now run the qmusicplayer application with file 'malayalam.qm' is placed in the same directory of the executable. Now you can see the malayalam version of 'qmusicplayer'.

In the absense of the file 'malayalam.qm', there will be no run time error in the program, it simply shows the english version. Similarly you can build a multi-lingual swithable version.

Wednesday, July 6, 2011

How to make bitmaps for graphic LCD (glcd)?

Making bitmaps for graphic LCD is pretty easy. There is a lot of free tools available over Internet, but I think there is no need to download them if you have already installed an image editing software in your PC. Also it is interesting to know what's actually they do. In this quick tutorial,  an example using GIMP - a free image manipulation program is described. This is a general tutorial and can be applicable for almost all type of graphical LCDs.

Step1: Know the pixel size of your graphic LCD. For KS0108 (a general purpose glcd), it is 128x64.
Step2: Choose an image(any image) to be embedded on LCD.
Step3: Scale the image to 128x64. In GIMP, (menu)Image -> Scale Image. Change height to 64 and width to 128.
If your image is not an exact multiple of 128x64 and if you want to keep the aspect ratio, you need to do any of the following:
a) Crop the image to 128x64.From toolBox(dock in the left hand side most probably), choose Rectangle Select Tool and spcify the size to 128x64 in the bottom of toolbox and select a portion you want and crop it. (menu)Image -> Crop to Selection.
b) Resize the image to less than or equal to 128x64. Then start a new image by (menu)File -> New. Then from the dialog box choose size as 128x64. Copy the previous image to the new image.
c) If you want to just check and image is not matter, image search on Google specifying the size 128x64 ;-)
Step4: Before going to this step, I assume you have an image of the same size of your LCD. In this example, 128x64. Next is the conversion of your color image to monochrome image. For that, choose, (menu)Colors -> Threshold. Using the dialog box, you can change the threshold in realtime.
Step5: Change mode.(menu)Image -> Mode -> Indexed.From the dialog box, choose 'Use Black and White (1bit) palette'. Click 'Convert'
Step6: Save the image.(menu)File -> Save as. Choose extension .bmp (bitmap).

Now your image is ready for embedding to your LCD. For some programs like MikroC for PIC, there is a built in tool to convert the bitmap into array. If you don't have such advanced tools, don't worry, let's do it using open source tools.
Using Octave/Matlab for KS0108
Now you have a monochrome bitmap of only zeros and ones. Now it should be grouped and formatted to a format supported by glcd. I did the conversion using octave. The script shown below accepts the bitmap name as argument and convert it to the glcd compatible form. make appropriate changes to run the script in MATLAB. Also change yourself the program if your lcd size is different.
#This code input a monochrome bitmap of size 128x64 and convert it to a form compatible to ks0108 graphic lcd(glcd)
arg_list=argv();
x=imread(arg_list{1}); #accept argument
num=0;
printf("Controller 1 (left)\n\n");
page=0;
for offset = [1:8:64]
    printf("Page %d:\n",page);
    page+=1;
    for j=1:64
        for i=[offset:offset+7]
            num=num+x(i,j)*(2^(i-offset));
        endfor
        printf("%d ",255-num);
        num=0;
    endfor
    printf("\n\n");
endfor
printf("Controller 2 (right)\n\n");
page=0;
for offset = [1:8:64]
    printf("Page %d:\n",page);
    page+=1;
    for j=65:128
        for i=[offset:offset+7]
            num=num+x(i,j)*(2^(i-offset));
        endfor
        printf("%d ",255-num);
        num=0;
    endfor
    printf("\n\n");
endfor

Monday, July 4, 2011

ChaserDesigner - A professional approach for fancy light design

This project is published in July 2011 th issue of Electronics For You (EFY) magazine (Page no: 94 to 98) titled:"Microcontroller-Based Light Chaser". Thanks to EFY for publishing this. You can read full article from EFYmagonline or purchase one.

ChaserDesigner is a useful project for fancy light designer professionals  as well as enthusiast who want to make their own LED patterns while decorating home during festivals. It's hardware part is simple one which uses 8051(or any variants of 8051) and a handy software part based on Qt. In the GUI, you need to specify how the pattern appear on LEDs(or connected higher loads) and it will automatically generate the source code for 8051(in assembly language). Only you need to do is that, burn the program in to the micro and put it on the circuit. Then the LEDs start to glow in the designed pattern. This is very handy and there are some tools provided to easily make your own patterns. The software works in Linux, Windows, or MAC and hardware components chosen are almost ubiquitous. In case, if any component found unavailable, please comment, I will try to recommend any alternative if any. I have put source code,circuit diagram and all other associated diagrams free for download.

1. contents.zip - Article before published, circuit diagram, images etc.
http://www.4shared.com/file/MolWxWP_/content.html

2. chaserdesigner_src.zip - Software source code.
http://www.4shared.com/file/zY9fz6LF/chaserDesigner_src.html


3.chaserdesigner1.0.zip - Windows XP executable file
http://www.4shared.com/file/3WmVxoaF/ChaserDesiner10.html


4.videos.zip - videos describing, how to operate the software and hardware.
http://www.4shared.com/file/EagoltHS/videos.html


Note: Since it is published by EFY,  it is better to read this article in EFY to get more pretty article with PCB layout also.

Monday, August 30, 2010

Reveal Them! A Qt entertainment

I do some Qt exercise when I get leisure time. RevealThem is just the after effect but I hope source code will be useful for somebody. While I was over consuming my vacation in front of TV, found a nice program like RevealThem. Hiding a celebrity behind a brick wall, and player can remove bricks one at a time so that, a part of the face is visible. People get higher points if they identify the celebrity with minimum number of picks. I found it was interesting to realize in Qt.
How to use the software?
Step1: Download the program(Go to end of this post)
Step2: Download some pictures of celebrities in .jpg format and save it in images/ directory in the directory where the program is installed.
Step3: Open the executable and click 'Load Image'. then you can pick bricks by clicking on it and select correct answer from the list and click 'Check' button. For each pick you, lose your 10 points.
Step4: This program is just for fun only.

Download source code (Tested in both Linux and Windows - 3.27KB)
Download Windows binary (5.03MB)

Saturday, August 28, 2010

Qt Programming in Malayalam Part-1


Qt Programming in Malayalam is quite easy. Most of the strings used in Qt is of type QString. QString support all kind of unicode standards. So one can include mathematica and technical symbols, and non-English characters. Malayalam characters are also included in unicode. So usage of Malayalam in Qt is possible almost anywhere in Qt software designing. There are three major standards for unicode- UTF8-8bit, UTF-16-16bit, UTF-32-32bit. QString supports all standards and there's a bunch of translating functions to and fro for transforming QString to other types such as const char*.

You can transform simple programs in Qt to Malayalam with a little care. But still there may be problems while playing with non-English languages. Like other GUI's Qt is also limited in support to non-English languages, but still it is translatable.
Download this example (Windows binary - 4.76MB)
Download the source code (Tested in both Linux and Windows - 3.27KB)

Also read  Qt Programming in Malayalam Part-2

Tuesday, January 12, 2010

Here comes Octave Online


Before going to read more check whether you know about Octave.

From the inspiration of my last post about the online Python, I searched internet for the online octave. Luckily, it was a success. All scripting languages or tools are feasible to convert to its online version, even though it doesn't exist for the most. Come back to Octave online. I don't know whether it can be called as octave online, but they calls it Math calculator which supports octave. I was successful in executing simple matrix calculations in the Octave online. Anyway, it is the time to dive into Octave online. You just need to click here.
The parent website http://www.online-utility.org/ offers other free online utilities. Search and explore more.

Online Python

My friends always complaint that they don't have an environment for learning python. They have internet connectivity in the college, but not having the permission to install python interpreter on those machines. So they satisfied by just reading the tutorial only and not by doing python. But here is the solution. Online Python Interpreter is an online python terminal and you can enter python commands as like in your shell. The virtual browser shell is a little bit slower and and again slower for slower internet connections. The speed is entirely depend upon your internet connection and no way to increase because entire python engine is on the server side. But I am sure it will be a boon for the beginners and net-book users. Current limitations are:
  • Can't define functions or classes.
  • Can't run a script

Click to enter online python interpreter
Click to view the ubuntu forum discussion about online python interpreter

Friday, January 1, 2010

PYRO : Python in hand with Robotics

Python developers all over the world are searching for fields that are not involved python. I recently found a good job by them - a boon for robotics enthusiasts - that is Python Robotics or simply Pyro.

Go to pyro project page

Download Pyro live CD

Many built-in python scripts are there to define the robotic brain and paths. Of course, you can write your own scripts. Anyway, pyro is a wonderful experience.

I encountered a problem while booting from pyro live CD. It seems to be mother board and chipset specific. My problem was, no x start up. It hangs up when displays "Probing/Loading AGP Modules...". I used several knoppix cheat codes to enter into kde desktop. It was successful. Thanks to knoppix developers forum. The boot time cheat code i entered is:

knoppix noagp

If you encounter any such problem, try to search for knoppix boot problems and not for pyro boot problems.

Saturday, August 8, 2009

Try Ruby on your browser!

If you are ready to spent a 15 minutes of free time, it's enough to learn ruby. Ruby is Japanese brain and quite easy also. It is famous in its simplicity. You need not install ruby to try it, you can do it in your browser- Not joke!
Just navigate to the official website of ruby.


On the sidebar, you have a wonderful tutorial "Ruby in twenty minutes" to start with. Put a click on "Try ruby on browser" -circled in the above screenshot. Then you will get a command prompt like screen on your browser. Then now ruby is ready to what you want!
If you are beginner, type 'help' on the prompt and hit enter. Then the 'virtual' ruby navigate you through an interactive tutorial which is very useful for beginners. The tutorial takes only about 15minutes.

World's Smallest "Hello World" program

It's quite formal way to start with a "hello world!" program while introducing a new programming language. It is convinient by starting from "hello world" because the program may run properly and is helpful in gaining the confedence. Also it gives a proper output - Prints "hello world!" on the monitor. The programmer becomes happy while seeing this output. Here is a simple "hello world!" program in C.

#include
main()
{
printf("hello world!");
}
//output is
//hello world!


Quite simple?
But I think it is not at all simple. The special characters present in the program really offer some disturbances for the beginner, however a C program is not redundant and it is extreamly powerful.

In Python, I found a much more convenient way.

print "hello world!"


Simple?
It seems good but there is still void to shrink.

Take a look at Ruby,

"hello world"


That's it. I didn't found any void to shrink here. Just put the string you want to print in quotes (" ") and it is pretty easy. But this is not the standard way of printing a string on the monitor, as far as the offcial website of Ruby is concerned. They recommends,

puts ("hello world!)


Then the output will be,

Hello World
=> nil

nil stands for there is nothing to return.

Thursday, July 30, 2009

A programming language in my name!

While googling in a sleepless night, I found something intersting (interesting for me and all other Toms!). A good looking programming language named "Tom" which is my name. I just went through the official website and found it was cool. I liked some of its specialities available, and also it's license.-Yes, it's under GPL (GNU General Public License). Some of the pecularities are: (I just copied it from the official site)
  • TOM sports extensibility of objects: a class is not just defined by its main definition: classes can be adjusted, even at run time. A prime example of this is to modify in your program a class offered by a shared library, just to make it suit your program better.
  • TOM methods employ default argument values and multi-valued returns;
  • TOM has multiple inheritance - with semantics much simpler than in C++ or Eiffel and obviating the need for interfaces (Java) or protocols (Objective-C);
  • TOM offers reflectivity on objects, their classes, member variables, and methods;
  • TOM discerns classes and a few basic types - like Java and Objective-C;
  • TOM has conditions modeled after CLOS conditions;
  • TOM, as compiled by Tesla, the first TOM compiler written in TOM, adds blocks to the language;
  • The TOM standard libraries offers time-constrained garbage collection, multi-threading, distributed objects.
In their FAQ, I found a question "What does the name "Tom" mean?
The answer given was like this: "The name TOM is a name. Names don't need to have a meaning. :)"
Well, here is simple "Hello Tom" program in TOM which resembles C and Java.

int
main Array arguments
{
[[[stdio out] print "hello, Tom!"] nl];
}


Currently Tom is available for Linux,BSD platforms. An unsupported version of win32 platform also
Visit official TOM website

Saturday, June 13, 2009

Python for Symbian s60


Python is very convinient language compared to any other and constantly increasing it's popularity. It is listed in the top 10 programming languages also. It can be used in MS Windows, Linux and everywhere. It's a best hacker's choice also. Many varieties are emerging from python. Portable python- which need not be installed but paste the file in your Thumb drive or any other portable devices and you can use it everywhere. Really Nice. Now the pyhton coming to conquer the mobile phone world!. Yes, you can do what is you go for in a PC.

  • Just donwlad the pyhton instllalble file. Install it
  • Open python for s60
  • Options->Interactive Console
  • Do what you want
  • You can see some example *.py files in Options->Run Script
simplest example:

print "hello World!"

#Note: Wherever you want to press enter in PC version of linux, in mobile, you use 'scroll key', not 'enter' character in the list of special characters. You can run python scripts also bu require one text editor. One good text editor is JtextLite.

Happy Programming!

Friday, June 12, 2009

Play with "cdrom" in Linux

Linux comand shell "bash" is powerful as we know. Here is a fun with bash. You can control your cdrom using 'eject command'. Here is only a simple description. For nore details, you should look at it's man pages.

This is not a project or something serious. just for fun. You can control your cdrom by using this code. This will only work on Linux platform. I did it in fedora core 9. But it will work other disro's also.

!!!!!!!WARNING!!!!!!!!
1)Some procedure described in this article is not a recommended or the hardware devices are intended to work like it. Do it in your own risk.
2)Don't interrupt the way the hardware working (the movement of CD ROM tray by your hand).

Open your 'cdrom' tray under software control
Try this command

$eject cdrom


It will try to open your cdrom tray. if you have two or more cdrom drives, try

$eject cdrom0


If you havn't any cdrom device, bash will return an error message:

$eject cdrom2
eject: unable to find or open device for: `cdrom2'


You can find your device name ( "cdrom0', 'cdrom1' etc.) from "/media"

Close your 'cdrom' tray under software control
Try this command

$eject -t cdrom


Other useful parameters are there in 'eject'. You can read about it:

$man eject


Writing a bash script
Just entering the command at a time is not convenient. You can write some commands together and execute it when you want.
Open a new file using gedit editor (or any other you want)

$gedit cdromplay


A winow will appear and type what you want. For example, if you want to open and close your cdrom continously three times just print like this:

eject cdrom
eject -t cdrom
eject cdrom
eject -t cdrom
eject cdrom
eject -t cdrom


save it and close.
Then to resolve permission,

$chmode +x cdromplay

Then execute cdromplay

./cdromplay


You can see what I said before.

Do it in your real applications
As you know, we did some rubbish things before. There is no need to do so. But this is useful in some applications like CDburner - It will automatically eject tray after writing a CD ROM or you can control convineiently in a CD ROM player. We can use python to do a GUI application.

# File: cdromplay.py

import os
from Tkinter import *

class App:

def __init__(self, master):

frame = Frame(master)
frame.pack()
self.button = Button(frame, text="Quit", command=frame.quit)
self.button.pack(side=LEFT)

self.hi_there = Button(frame, text="Eject", command=self.say_hi)
self.hi_there.pack(side=LEFT)

def say_hi(self):
os.system("eject cdrom1 -T")
print "boss, cdrom activated"

root = Tk()

app = App(root)

root.mainloop()

As you can see, the above program is the altered version of "Hello World!" program of one famous python tutorial. Don't get upset or confused by the defnition names. The confusion in program code will not affect the real program.Copy and save it or download it from here. You require python to do this. 'cd' to the appropriate directory and run,

$python cdromplay.py


Now you will see a simple widget with a button.


Press button and observe what's happen.



Download cdromplay for python
Download cdromplay bashscript

Watch the video how cdrom is ejected:

Good Luck!