Category Archives: Technical

The Curious Case of Preprocessors


What would be the output of the following code snippet:

#include <stdio.h>
#define V 1
int main()
{
  int Value = 1;
  #if V == Value
      printf("Hello world\n");
  #endif // V
  return 0;
}

If you guessed that the program will print “Hello world” you are wrong.

The reason being #if is a preprocessor directive and at the stage where preprocessor directives are evaluated or expanded, ‘int Value = 1’ has still not been processed and memory has not yet been allocated. This will happen only at the compilation stage and not the preprocessing stage.

So basically there is no meaning in V==Value and this will evaluate to false. So for this piece of code to work you will have to define even ‘Value’ with the #define statement.

Thanks to two of my colleagues Rakesh and Mitul for this interesting discsussion.

Advertisements

The Garden Pi


This is a small project that will introduce you to IoT and on how to use WebIOPi and Raspberry Pi to create a small and cool project.

These are the components that you will require for this project:

  1. Raspberry Pi B+ ( Any Rpi should work)
  2. 3-6V Submersible Mini water pump
  3. Wifi Adapter  (You can skip this if you have a LAN cable long enough to reach your garden)
  4. Transistor Bs550
  5. 5V Relay
  6. Tube to supply water from the pump to the flower pots.

Setting Up the Wifi Adapter

As mentioned earlier if the LAN cable is long enough to reach your garden then you can skip this stage.

Make sure the Wifi adapter you have is compatible with the Raspberry Pi you have. I have used an Edimax Wifi usb adapter.

Insert the adapter into the Rpi USB slot and power up your Rpi.

At the command prompt type in the command lsusb

lsusbout

From the output of this command we get to know if the Wifi adapter was detected or not. In my case the last line shows my Wifi adapter.

The next task will be to edit the /etc/network/interfaces file. Type the command

sudo nano /etc/network/interfaces . This should open up the file and the contents should be edited as shown below:

# The loopback interface
 auto lo
 iface lo inet loopback
auto eth0
 iface eth0 inet static
 address 192.168.0.26   #your static IP
 network 192.168.0.0
 broadcast 192.168.0.255
 gateway 192.168.0.1     #your gateway IP
 netmask 255.255.255.0

allow-hotplug wlan0
auto wlan0
iface wlan0 inet static
 address 192.168.0.25   #your static IP
 network 192.168.0.0
 broadcast 192.168.0.255
 gateway 192.168.0.1   #your gateway IP
 netmask 255.255.255.0
 wpa-ssid "SSID of Your Wifi Network"
 wpa-psk "password of your Wifi Network"

Here I have configured the static IP of 192.168.0.26 for LAN connection on Rpi and 192.168.0.25 for Wifi on RPi.

Type ifconfig at the comamnd prompt and make sure the IP address of the Wifi (or LAN) is assigned correctly. If not reboot your Rpi.

Once this is done try pinging your Rpi from within the same network. Use the IP address of LAN or the Wifi adapter based on how your Rpi is connected to the network.

Now on your Rpi try pinging some external website like http://www.google.com

If the ping is successful all is fine. If not don’t worry there is a fix to it.

Type in route -n

Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
192.168.0.0     0.0.0.0         255.255.255.0   U         0 0          0 wlan0

If this is the output then notice that the gateway has not been set properly. All you have to do is execute the command given below.

sudo route add default gw 192.168.0.1

Now the you should be able to ping external websites. It would be a good idea to add this line to the ~/.bashrc file so that every time your Rpi starts up this get done automatically.

Once the wifi is setup you are ready to move on to the next section.

Installing WebIOPi

Since the WebIOPi has a pretty neat tutorial on how to setup WebIOPi, I will redirect you to that: http://webiopi.trouch.com/INSTALL.html

If you have both eth0(LAN)  and Wifi(wlan0) configured you may run into and issue where weaved is not able to access your WebIOPi server.

In that case type in sudo ifconfig eth0 down and that should do the trick. If it does consider adding this also to the ~/.bashrc file.

Setting Up the Garden Pi Web Page

For this project all you have to do is to write a single index.html file.

so create a project directory structure as shown below:

mkdir ~/gardenpi/html

 

edit the /etc/webiopi/config file

  • Locate [HTTP] section, add following line to tell WebIOPi where to find your HTML resources
...
[HTTP]
doc-root = /home/pi/gardenpi/html
...

More details about the config file can be found here

Now create the file ~/gardenpi/html/index.html

Add the following content into it:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>Garden Manager</title>
 /webiopi.js
 
 webiopi().ready(function() {
 webiopi().setFunction(3,"OUT");
 webiopi().setFunction(2,"IN");
 // Create a "Pump" labeled button for GPIO 3
 var button = webiopi().createGPIOButton(3,"Pump");
 // Append button to HTML element with ID="controls" using jQuery
 $("#controls").append(button);

 // Refresh GPIO buttons
 // pass true to refresh repeatedly of false to refresh once
 webiopi().refreshGPIO(true);
 });
 
 <style type="text/css">
 button {
 display: block;
 margin: 5px 5px 5px 5px;
 width: 160px;
 height: 45px;
 font-size: 24pt;
 font-weight: bold;
 color: white;
 }

 #gpio3.LOW {
 background-color: Black;
 }

 #gpio3.HIGH {
 background-color: Blue;
 }
 </style>
</head>
<body>

Turn on the pump by clicking the button below
 
</body> </html>

Once the file is created connect and LED between the GPIO3 and Ground of the RPi.

Open up a browser in your PC or mobile and go to http://192.168.0.25:8000

and ensure that the LED turns on and off at the click of the button. All you have to do now is to connect the pump instead of the LED.

Since the pump draws more current than compared to what the Rpi can supply we will be using a relay.

Wire up your components as shown in the diagram below:

cktdiagramgardenpi

This is my Rig, you may not be able to make much from the picture:

Jpeg

Hope you guys ill enjoy doing this project.

 

My Experiments with Boost Graph Library


Recently I picked up “An Introduction to Graph Theory” by Robin J. Wilson. After going through a couple of chapters I felt the sudden urge to try out a few of graph theory problems through programming. To try out the algorithms I first need to create the graphs themselves, which seemed a bit of a tedious task. But then thats what the boost graph Library is there for.

The BGL has made it very easy to create graphs and perform any operations on them.

Below is a simple program that lets you create a graph using the BGL.

#include<iostream>
 #include<boost/graph/adjacency_list.hpp>
 #include<boost/graph/graphviz.hpp>

int main(){
 boost::adjacency_list<> graph;
 int noVert = 0;
 int start=0,end=0;
 char choice = 'y';

 while(choice == 'y') {
 std::cout<<"Enter the start and end vertex of the edge: ";
 std::cin>>start>>end;
 boost::add_edge(start,end,graph);
 std::cout<<"Do you want to add another edge(y/n): ";
 std::cin>>choice;
 }

boost::write_graphviz(std::cout,graph);
 return 0;
 }

The coolest feature of BGL is that it allows you to write your graph as ‘dot’ file, which can be used to by Graphviz to visualize. Checkout my github repo for more BGL based programs.

Range Based For Loops in C++11


Here is a short post on the range based for loops in C++. I recently learned about range based for loops in C++11 standards. These are nothing but easier constructs on writing loops. You no longer have to write:

for(initialization;condition;update)

The syntax is:

for(declaration:expression)

Although this looks like a very simple feature there are a few things to keep in mind while using the range based for loops.

Lets take a look at a simple piece of code:

#include<iostream>
int count(int array[100])
{
 int total=0;
 for(auto num:array)
 total++;
 return total;
}
int main()
{
 int array={1,2,3,4,5};
 std::cout<<count(array)<<"\n";
 return 0;
}

If you compile the above code it throws compiler errors.

The same code will work if ‘array’ is a local variable in the main.
This baffled me for quite sometime and it is a friend of mine who explained to me why this happens.

This is how a range based for loop works:

It starts from the beginning of the array and travels till the end. So it needs the iterators to traverse the given array. In the code provided above ‘array’ is passed as a pointer and it does not have any iterator or boundary information. So in my original code if I pass ‘array’ as a ‘std::vector<int>array’, the code works fine.

Hope this will help someone else who is stuck. To know more in depth about how range based for loops work in C++, refer to the link provided below:
http://en.cppreference.com/w/cpp/language/range-for

Calling a function On termination of main() in C


Dear readers, A friend of mine taught me this new “trick” where you can call a function when the main() in C exits.

In the Library “stdlib.h” there exists a function

int atexit(void (*func)(void))

the “func” is any function without any arguments.

The atexit() calls the function that you register as soon as the main() terminates.

Here is a simple sample code to demonstrate this.

#include<stdio.h>
#include<stdlib.h>
void func()
{
printf(“This is after main\n”);
}
int main()
{

atexit(func);
printf(“in main\n”);
return 0;
}

The function can be registered anywhere in the main() but it will be called only after the main() terminates.

Hope this helps atleast some of you in doing some cool things. Please feel free to share your ideas.

The World of Dynamic Programming


Recently I came across the an algorithm that can find the maximum sub array in a given 1-D array. Its called the Kadane’s algorithm.It comes under the domain of dynamic programming. I would like to write about a few things I understood about Dynamic programing so that it may help someone else to get a start and at the same time to improve my own knowledge on the topic.

Dynamic programming is an optimization problem or a programming technique, where the given problem is split into sub problems and so on.
To understand more about dynamic programming we need to look at how it obtains optimization. Dynamic programming builds its optimal solution by creating optimal solutions for its sub problems.This is also called optimal substructure.
It follows the principal of Optimality which states that “A problem is said to satisfy the Principle of Optimality if the sub solutions of an optimal solution of the problem are themselves optimal solutions for their subproblems.”

Or to put it in simpler terms optimal substructures means that the optimal solution to a problem is made up of optimal solutions to its sub problems.
Another technical term used in dynamic programming is Overlapping subproblems. This means that there are a few subproblems in total and
many recurring instances of each.

Dynamic programming uses a bottom up design process. A very good example of this will be the fibonacci series generation.
Lets first look at the recursive solution to generate fibonacci series. Instances like f(1) ,f(0) repeat multiple times. If these values can be stored they don’t have to be calculated multiple times.

The left side shows the number of steps taken by a dynamic program and the right side shows the steps taken bya recursive program to calculate fibonacci series.

An example of Dp and Recursion

An example of Dynamic Programming and Recursion

It is also to be noted that dynamic programming is not the same as divide and conquer, because dynamic programming proceeds by splitting the  problem space in every possible manner.

I have tested the efficiency of the of  both kinds of Fibonacci code. And here are my findings with respect to time taken for running the code.

Test on Fibonacci

And below is the code used for testing this.

#include<stdio.h>
#include <time.h>

int fibonacci1(int n)
{
  int a=0,b=1;
  int i,c;
  for(i=0;i<n;i++)
    {
      c=a+b;
      a=b;
      b=c;
      //printf("%d\n",c);
    }
  return b;
}

int recfib(int n)
{
  if ( n == 0 )
    return 0;
  else if ( n == 1 )
    return 1;
  else
    return ( recfib(n-1) + recfib(n-2) );
}
int main()
{
  clock_t t;
  double normaltime=0,rectime=0;
  int sample;
  for(sample=0;sample<100;sample++)
    {
      t=clock();
      fibonacci1(sample);
      t = clock() - t;
      normaltime = ((double)t)/CLOCKS_PER_SEC; // in seconds
      t=clock();
      recfib(sample);
      t = clock() - t;
      rectime = ((double)t)/CLOCKS_PER_SEC; // in seconds
      printf("%f,%f\n",normaltime,rectime);
    }
  return 0;
}

Creating a Application Launcher in Ubuntu 14.04


Dear Readers,

I am back with a very small ubuntu tip after quite sometime. This is not something that is really new and there are many sources out there that explain how to create application launchers in Ubuntu. I needed this to create a launcher for Aptana Studio.

So I thought I will write down these steps here so that others in need can find it and also it will serve as a future reference to me.

Open a terminal and navigate to your home folder and then

cd  /.local/share/applications

In this particular folder create a file called yourapplicationname.desktop

And in this particular file add the following content.

[Desktop Entry]
Version=3.0
Name=Name of Application
Comment= a short description
Type=Application
Categories=Development;IDE;
Exec=absolutepath of application
Terminal=false
StartupNotify=true
Icon=path of icon image
Name[en_US]=AptanaStudio

Save this file and search for your application in unity and there you have your launcher.

A Program to calculate value of PI


Very recently I was attending an online programming course and the Instructor happened to ask a  question,
How man of you have ever written a program to calculate value of PI ?What has happened to the world ? In our days students used to attempt at least 2-3 algorithms to find value of PI.
It was only then that I realized that I have never even bothered to think about one of the most popular problems in the history of computing.
So finally I decided to learn an algorithm to calculate the value of PI, so that next time someone asks me the same question I should not run out of words. This blogpost is for all those out there lie me who have never attempted any algorithm to find the value of PI.
Here I will be introducing one of the oldest and simplest algorithm to find the value of the value of PI accurately. The accuracy of the result depends specifically on the machine and the size of the floating point numbers alloted by the programming language.
 Liu Hui was a mathematician who lived in ancient China, in his days the value of pi was approximated to be 3. But he proved that the ratio of the circumfrence to the diameter of a hexagon inscribed in a circle was 3 therefor value of Pi had to be greater than 3.
Here we start by considering a hexagon which is inscribed in a circle with radius =1. So the area of the circle is PI. Let the side length of the hexagon be 1. Then
 k2n =√(2+kn)
Sn =√(2-kn)
Area of the polygon = (1/2)(nSa)
 as the number of the sides of the polygon increases the value of a=radius.
So as the value of n increases we get a more and more accurate value of PI.
Below is the code for the algorithm
/*Author Vineeth kartha*/

#include<stdio.h>
#include<math.h>

int main()
{
  double k=1,n=6,S=0,N;
  int i;
  long double pi;
  printf("Enter the number of iterations required : ");
  scanf("%lf",&N);
  for(i=0;i<N;i++)
  {
    S=sqrt(2-k);
    n=n*2;
    k=sqrt(2+k);
  }
  n=n/2;
  pi=n*0.5*S*1;
  printf("The value of PI is %.10Lf\n",pi);
  return 0;
}

The results upto the 16th iteration seems to be correct with this algorithm.

Prepaid Manager App in Ubuntu


It was only today that I put into use my Huawei E303C modem into use. I had not used it for almost 6 months. And today I  plugged it in it with the IDEA 3G sim on Ubuntu 13.04. The Huawei linux drivers almost gave me a headache and finally to get the device working . Finally I had to uninstall it and I found out that Ubuntu 13.04 automatically detects my modem.

Now people out there who have already screwed up by trying to install the Linux drivers for Huawei modem, just uninstall and reinstall the usb-modeswitch and things should be perfect.

sudo apt-get remove usb-modeswitch usb-modeswitch-data
sudo apt-get install usb-modeswitch

Now after all these I still had one major problem in front of me. To know the balance that I have on my SIM I had to remove it from the modem insert it in to my mobile and check. It is then that I found this wonderful application in ubuntu called “prepaid manager”

sudo apt-get install prepaid-manager-applet

Once this is done you will have to change a few lines in an XML file.

go to /usr/share/mobile-provider-info

and with root permissions open the serviceproviders.xml file.

In this file go to the country and to the service provider you are using and add the following lines just before the closing gsm tag </gsm>

<balance-check>
<ussd>”USSD CODE TO GET BALANCE</ussd>
</balance-check>
<balance-top-up>
<ussd replacement=”CODE”>*USSD CODE TO RECHARGE*CODE#</ussd>
</balance-top-up>

Once this is copied make sure to change USSD CODE TO GET BALANCE to the required code for me since I was using IDEA it was *125#

Till now I have not tried the top up option, if any of my readers have done that too please eel free to comment.

Thats How We C


Two and a half years back, while I was still In college that I got this idea to write a book on Programming. By then I had spent almost 4 years learning and coding a couple of programming languages. I knew I was not an expert in the field, but I also knew that I could help a few who were struggling in programming. The very next semester had a course on C programming and I knew most of my classmates would need help, so I set out on this new venture to bring out text that will help people with no background in programming to understand what C programming is all about. It can never be considered as a replacement to any of the great books out there but still, I knew that It might help someone. So after almost six months of work I was able to have a printed copy of “Thats How We C”, I sold 25 copies of the book to my classmates at no profit, I charged them with the printing cost only.
I hope many more will find this useful and if you do please do let me know, because it will be an encouragement for me to write my next book.
Also please do give me any feedback that you might have.
You can download the book from here

%d bloggers like this: