Wednesday, January 27, 2016

Programming the robot- part2 (giving life to little Franky)

In my last  post I have discussed several functions that I have used. From this post I would like to discuss the rest of the functions.

Functions associated with LCD Display


Write_LCD() handles displaying the current distance measurement the ultra sound sensor is taking. Since the sensor measures distance every 50ms that resolution is too fast for humans to be able grasp any information. Therefore the actual display doesn’t show the distance in real time. It has an interval about 200ms.
First challenge I faced was that variable x is an integer so I had to convert it to a string before I can send it to LCD display. By using following code I was able to convert x into a string ( array of characters).

Converting an integer into an array

Another problem I faced was since x varies from single digit to up to 3 digits the display showed meaningless characters when there are blanks. For example let’s at the beginning x was a 3 digit number. When it changes to a 3 digit number the leftmost digit will turn in to a meaningless character. My solution was to use if statements to split the case into 3 scenarios. So if x is between 0 and 9, 2 zeros will be displayed in front of x, if x is between 10 and 99, a zero will be displayed in front of x, if x is larger than 100 no zeros will be displayed in front of x. you will be able to understand my method clearly.

Writing into LCD Display

Functions associated with servo motor


Servo motor is used when robot has stopped due to detection of an obstacle and needs to find an alternative path to go. I used a polar coordination system to identify the angle and distance to an obstacle. The following diagram will help you to understand my method.

In this picture r denotes the displacement to the obstacle and theta  denotes the angle from left side horizontal axis. When the sensor facing forward direction value of  theta  must be 90 degrees. But I found that the minimum value for theta was about 20 degrees and maximum was about 150 degrees. Therefore when initializing the servo it was fed with 70 degrees not 90 degrees. Servo library takes the angle difference from it’s current position to move to a new position.

When the robot got a x value which is less than 20cm it stops and main function calls control_servo() function . Control servo() function first moves sensor from 70 degrees to 140 degrees. While doing this it records the distance when angle is 90,110 and 130 degrees. Then again sensor moves from 130 degrees to 0 degrees. Sensor records the distance when angle is 50, 30, 15 and 0 degrees. One important thing to remember is to have a delay when changing angle. Since the actual servo takes some time to move to a new position from current position a delay is required. I have used a delay of 10ms for this. By accurately measuring the angular speed of the servo this time delay can be fine-tuned. Data array is used to record relevant angle and displacement. 

Function to control Servo motor

Now I think it’s ok to explain functionality of turn_robot() function. The purpose of this function is to turn the robot in to a suitable direction based on the values in data array. When turn robot is called, first it calls control_servo() function in order to collect distance and angle measurements. Then it calls sort() function to arrange obtained data from smallest distance value to highest distance value. After this data[6] element will have the highest distance measurement and corresponding angle.70 degrees is subtracted from this angle. If this value is a negative value it means this angle (i.e. the obstacle that is situated furthest from robot) is positioned from left side of the robot. If this value is positive it means this angle (i.e. the obstacle that is situated furthest from robot) is positioned from right side of the robot. Then this angle is used to turn the robot to that direction.
equation 2

According to equation 2  there is a time period which is proportional to a given angle theta. Assuming omega is a constant which is the angular velocity of the robot turning then t can be used to turn the robot. By calculating a time period which corresponds to theta and using that time period as a delay period I was able to achieve this. We only need the magnitude of theta since we already know the direction of the turn. The angular velocity of the vehicle had to be measured experimentally and also this constant value is valid only when the surface that robot moves is uniform. So this method is not very accurate method at the moment but I am planning to implement a control system to keep the speed of the motors at a constant rate. By that we omega value will stay the same. In here I have multiplied turn_time variable by 1000 in order to convert it in to milliseconds.

Function to turn robot 

  Now I have covered all the functions I have constructed to build my program. The main program or loop() doesn’t do much except coordinating the all these functionalities and making robot move forward. Inside loop() it checks  x value .If x is larger than 20cm(or any arbitrary value) robot will move forward and if x is less than that value it will stop robot and call turn_robot() function. After that turn_robot() function will turn the robot in a suitable direction and starts main program from beginning.
Main function loop()

This is my complete program for my robot. Although this program works it still need lots of debugging. There are some unexpected behaviours that need to be fixed.It might take some time and I hope to write my progress on my blog. But I’m glad finally I was able to make a working prototype of my robot. It may sound funny but building this robot was like raising a child for me. You need to be both knowledgeable and passionate at what you are doing. Sometimes you get frustrated when things are not going well or not giving the desired output but you won’t give up until you are satisfied. You will realised even the simplest things in life like going on a straight line is not simple as it seems for somebody as simple as a robot. It takes lot of time and patience to achieve what you want but at the end of the day you can see that little creature is actually wondering in your room and this will make you feel you achieved what you deserve.

I think if you read these articles it might be helpful to you in your own projects. I have posted a link to the source code at the end of this article. Please feel free to download it and use it if you need.

Programming the robot -1(aka giving life to little Franky )

I was hoping to write about this earlier but due to many reasons I missed it and finally I got a chance to sit down continue on my post. In previous article I discussed how to connect a LCD display to Arduino board through a shift register. (74HC595N). I decided to have an LCD display in my robot for several reasons.
  •    It’s very useful to know the readings that robot is taking during testing.
  •    I can’t access serial monitor when my robot is not connected to PC. I  have to use a USB cable and it limits the robot’s movements.
  •   It’s cool to have an extra gadget on my robot. It makes it more interactive.

So with the implementation of LCD display the robot consists of 4 main sections.
  •    Motors and the IC that controls motors.
  •    LCD display and shift register.
  •    Distance sensor
  •    Servo motor

In order to control all these sections I had to write a program that controls each of this section. I have talked about the motor controls in details in a previous post and the basics of implementing the LCD display and Distance sensor were discussed in last post. Therefore I would like to talk about the rest of my program in details in upcoming posts.
In this version the robot was expected to go along a path until it detects an obstacle from a certain distance. The robot then stops and starts to scan the surrounding area using the detector attached to a servo motor. Servo motor turns the detector to left and right while the detector records 7 measurements (distance to a particular obstacle and the direction i.e. angle to it with respect to the initial position of the detector. ) then it’s chooses the most suitable direction to go (direction which the distance to an obstacle is maximum.).It may seems like an easy thing to do but implementing it was indeed a difficult task.
Since this is going to be a bit lengthy than a usual post I would like to split this into small sections where I explain the functions that I implemented in order to control my robot. Here is a list of functions that I have used in program.

Functions associated with movements of robot

  •   Go_right ()
  •    Go_left ()
  •    Go_backward()
  •    Go_forward()
  •     robot_stop()
  •     turn_robot()

Functions associated with distance sensor
  •  measure distance()
  •  sort()

Functions associated with LCD
  •  write_LCD()
d     Functions associated with servo motor
  •        control_servo()

            Then there are setup () and main () functions that are being used to initialise and run program. 
      Including required libraries and declaring variables 
Header files used in program
 In this version of robot I used timer 2 in AVR micro controller since timer 0 is allocated to delay () function and timer1 is allocated to servo motor. MsTimer2.h header file gives access to use timer 2. Servo.h is used in servo motor. SPI.h and LiquidCrystal.h are used in LCD display. SPI.h is the header file which is used in serial communication using it we can use a modified version of LiquidCrystal.h file in programs.


variables used in program

     x is the variable that is being used to store the distance measurements by distance sensor. It updates value of x every 100ms or any other given time period using timer2 interrupts. It is declared as volatile since x gets updated outside of the program. Therefore it indicates to the program that value of x can be changed anytime.

direc is variable type that is constructed exclusively for this program using structures in C. structures allows programmer to construct user-defined data types that can be used to store various types of data. In here my requirement was to have a data type which is capable of storing both angle and distance to an obstacle from robot position. In other words I wanted to use polar coordinates to detect obstacles. My initial idea was to use two different arrays to store the angle and the distance separately but it didn’t sound good because these two parameters are actually related to each other. Therefore I decided to use a user-defined data type to store these two parameters. After constructing the data type you can use it to declare variables, just as you declare an integer or any other default data types.  

Structure used in program as a user-defined data type

          In here I have declared an array called data which has 7 elements in it. Each element can store both angle and direction since their data type is direc. Rest of the variables are conventional variables that are being used to store various parameters used by program.

The next step was to initialize the setup() function. Setup() function is used to assign pins in Arduino board to various inputs or outputs that are used in program. pinMode() function is used to assign an Arduino GPIO to an input (ex: echopin which is used to measure reflected ultra sound wave) or to an output (ex: trigpin which is used to initiate an ultra sound wave) . myservo.attach () does the same.In here myservo is an object that is declared as a Servo.
      New thing in setup () is the way that timer interrupt has been set up. Previously I was able to setup a timer interrupt from scratch but this time I used a function that was built by Arduino community to setup a timer interrupt. It made my life so easy and all I had to do was to give a value to the timer interrupt period and an ISR to be called when timer overflows. Flash() is the ISR and inside flash() I have called measure_distance() function. Therefore when ISR is called by timer interrupt every 100ms, it will call measure_distance() that will measure the distance to an obstacle. MsTimer2.h header file is responsible for handling timer 2. You can use this link to learn more about this.  
Setup() function

      Lcd_home() is used to initiate the lad display by clearing up the display and positioning the cursor on left upper corner.

Myservo.write (ini_angle) is used to make sure that sensor is facing forward direction when robot is turned on. The ini_angle varible value could be any value but my case it was around 70 degrees.
Now we’ll look at the functions I have used to in my program.    

Functions associated with robot movements

These functions will depend on the type of robot you are going to build. In my case it was a robot with wheels therefore it is expected that it should be able to move forward, turn left or right and backward. There are 4 connectors that need to be energised in order to rotate the motors. So I had to play with my robot a bit to identify what combination of these will make my robot go forward, backward, turn left and right. It’s something I had to do with trial and error. The most important thing to remember is to never set all motor connectors to high state since it will destroy the H bridge circuit in L293D IC.

functions that control movements of robots

     I’m not going to explain turn_robot() function here since it requires some other functions that yet to be explained. So I will present this function later in this post.

Functions associated with distance sensor

Measure_distance() is the function that measure the distance to an obstacle and store it in variable in every 100ms. It’s one of the most critical functions. It generates an ultrasound wave and listen to it’s reflection. Then it measures time delay between sending the signal and receiving it back. This value is then used to calculate x value. 

duration is the time delay measured and diving it by 58.2 this value is converted to a distance is cm.The speed of sound is 340 m/s or 29.1 microseconds per cm. duration is the time for wave to return to the sensor after reflection. Therefore duration value is halved when calculating distance. Since x is a global variable any other function can access this x value.
Function to measure displacement

Sort() function is used to arrange collected distance and angle data from smallest value to largest value. It takes the measured values that are stored in array called data and compare an element with it’s previous value. If the previous value is higher than the chosen element it will copy the previous value to another allocated memory place temporally. Then it moves the selected element to the position of previous element .Then copies the values in temporary memory into the next element. This process is done until all the values have been compared with it’s adjacent element. The following chart will explain it better.
The technique that I used in here is called nested for loop. It means a for loop inside another for loop. These types of loops are very useful when you are trying to manipulate things like 2dimentional arrays or matrices. In this case the inner most loop is the loop responsible of carrying out the comparison and copying elements. Outer most for loop controls the iterations occurred therefore the inner most loop.

Flow chart for sorting algorithm

Function used to arrange data in ascending order

I hope to explain the rest of the function from my next post.

Thursday, December 31, 2015

Au Revoir 2015 (2015 in retrospect )

                   There are only few hours left to say good bye to 2015 and welcome 2016. The whole world is busy getting ready to welcome another new year. I’m pretty sure we all got new hopes ,wishes and challenges to complete in next year and it will be great to realise that we are very fortunate to looking in to 2016 since some of the people who celebrated 2015 with us are no longer with us to celebrate 2016. I thought writing down what I feel about how was my 2015 year went will be a good idea. Someday, may be at the end of 2016 I can look back  at this post and compare how I spent my 2016. I believe it’s always important to improve yourself at least a bit .That’s what make you feel you have achieved something in your life.
                    When I am looking back at how I spend 2015 I can honestly say I was able to improve myself over all. It’s been a great year for my studies at Curtin and I have finished 3 years in my engineering degree and looking forward to start my final year next year. I was fortunate to have great friends who were always helped me in my studies and who always got my back when things aren’t going well. 2015 was my 3rd year in Australia and it’s been great life experience so far. Living in a strange country with people who I never met before was a big challenge and overcoming the obstacles and hardships I went through made me a stronger person. Now I feel I’m ready to face my life all by myself and I’m pretty excited about upcoming years.

                     Spending 3 years as an undergraduate was a great experience. I started studying at Curtin in 2013 and I slowly became good at what I love to do. Engineering was not one of my favourite field until I actually started to learn it and now Engineering has become the love of my life. I believe it’s not just a profession but a way of life if you are serious about it. 2015 was the climax of that as I started to specialise in electrical power engineering. I was fortunate to me lot of smart, brilliant people in electrical engineering field from different cultures, social back grounds and different viewpoints. It really made my experience at university more pleasant and challenging. I recon next year will be more challenging but I’m pretty confident me and my friends are ready to face it and win it.

                       2015 year was an important year even for my personal life. After going through some painful experiences in my life I finally overcame them and started to enjoy being alive and healthy. I realised it’s not the hopes that make you a human being but working hard and constantly adopting to the situation makes you a survivor. Hopes just give you a momentarily pleasure but working towards achieving them gives you more pleasure and satisfaction. At the beginning of every year we determine to change our way of life for the betterment of our selves but only few of us are strong enough to believe in them and chase them. For me it was a mixed experience in 2015. I had couple of things determined to do but I couldn't achieve all of them but I’m happy that I was able to achieve some of the most important things in the list.
                          In 2015, I started my internship as a trainee electrical engineer at Western Power, the electrical utility company in Western Australia. It was like a dream come true and I enjoy every morning going there, doing something that actually relate to what I study ,meeting some brilliant people who excel at what they do and taking advices and guidance from them. I’m thankful to my supervisor, Mr. Chathura Karunaratna who gave me the opportunity to work there and always find time to guide me in his busy schedule. My other team mates are also a big help for me at office and especially I want to thank Mr. Charles Mnyanjagha and Mrs.Nadee Jayasekara who are always kind enough to help me. I have been working there since 1st of December and I have two more months there to complete my internship and gather some good professional experience and lots of sweet memories.

                             Sometimes I wonder that I have already spent about 1/3 of my life time and I have become an adult who have some responsibilities. It’s been nice to see my friends have changed so much and doing well. During school time we all were trained to do the same thing without giving much attention to what everyone is capable of. But now I have friends who took different paths in life and enjoying the life and what they do. I’m thankful to every friend of mine who was a part of my life during some stage in my life. We may not meet again but it’s been great to spend time with them and it’ll always be preserved as a good memory.

                                 I would like to thank to my parents, my brother and sister who were always there for me when I need them. 2015 was a year which I understood the importance of family bond to life. It gives me a great pleasure to see the next generation of my family (my 3 nephews) growing well in both physically and mentally. I’m sure our parents and relative must have had the same kind of feelings towards us when we were small kids. I t’s so amazing to see how repetitive is life. So I realised the best way to live life is to live at the moment and enjoying it to the fullest.
                                 No matter what happens life goes on. It’s the way of life. In 31st of December 2016 we’ll look back at 2016 and will have a laugh at about the silly yet lovely stuff we did. It’s good to have hopes but as I said it won’t make a human out of you. In every morning we have 2 choices, stay in bed and keep dreaming or get out of the bed and chase your dreams. It’s up to us to make the correct choice. I wish all of you a happy new year. 2016 will be a new challenge to each one of us but we are defined by how we face them. I feel 2016 going to be an amazing year for myself in both academically and personally and hope same for you.

                                    And also I would like to thank to people who come here to read my blog. I will do my best to add more useful content to my blog and hopefully everyone who spend their valuable time reading my blog will find something useful to them . I would like to thank you my brother Uchitha Ranasinghe and his friend Mr. Chaminda Serasinghe whose constant feedback give me the courage to write what I know. Hope to see you all in New Year with a good attitudes towards 2016.  

Thursday, December 17, 2015

Control LCD display using shift registers (74HC595N)

This post is pretty much a continuation of my post using shift registers in Arduino projects .Please have a look at it first if you haven’t read it since I assume you are already familiar with how shift registers work and how to use them in a project. Therefore I'm not going to explain how the shift register chip works in this post. As you might already know I was trying to build a robot during my last summer vacation. Unfortunately I had to postpone it  due to lack of technical knowledge and lack of time to learn them .but I'm having a long summer break after another successful year at university and hopefully this time I think I’ll be able to finish what I started. This project is also a side project of that project. My goal was to build an obstacle avoiding robot using Arduino platform. I wanted to use a LCD display to display the distance to an obstacle in real time since it helps a lot in debugging when your Arduino is not connected to the computer and you don’t have access to the serial input readings. But one major problem with that was the number of I/O pins the display required in order to do that. An LCD display wanted at least 6 I/O pins. I had other components like a servo motor (1 data pin) ultrasound distance (2 data pins) measuring unit and my motor controlling unit (4 data pins)  and I couldn't use 0th pin of Arduino board since it deals with the communications of the board . So I ran out of pins. Then this 74HC595N shift register IC came for the rescue. The advantage of using shift register was connecting LCD to Arduino through shift register cost me only 3 pins. That was a huge advantage when it comes to working with micro controllers. However it wasn’t straight forward since the Arduino LiquidCrystal library is not compatible with using shift registers. So I had to find a way to go through it. Fortunately I was able to find this article about how to achieve this.  This is done by using a technology called Serial Peripheral Interface (SPI) which uses a synchronous serial data protocol to communicate with 74HC595 IC. In here Arduino micro controller acts as the master device and shift register acts as the slave device. LCD display is connected to the outputs of the Shift register IC. Then SPI.h and a modified version of conventional LiquidCrystal.h header files can be used to write programs to use LCD display.

The following schematic shows the connection of the components and the connection required are listed below. You should keep in mind to use only compatible LCD displays (Such as Hitachi HD44780) with the LiquidCrystal.h header file.

                      IC Pins (1-8)
                  LCD Display pins
6 (E)

LCD Display  Pin
10K trimpot variable leg
+5V through 220 ohms resistor

IC pins 9-16
Arduino I/O pins
11(Sh_CP/SPI clock signal)
12(ST_CP/Latch Pin)
14 (DS/Serial Data input)

Remember to connect the fixed legs of the trimpot (Trimmer/variable potentiometer) to +5V and GND.
The following image is a schematic of the circuit.
Image retrieved from

After connecting all the components We can replace the old LiqudCrystal.h file with new header file which supports use of shift register. Please go through the following steps to setup the necessary files.
  1. Download this new version of the LiquidCrystal.h from here.
  2. Close Arduino IDE if you are currently using it.
  3. Find the directory where the library folder is located. It should be inside the directory where you install Arduino IDE.
  4. Replace the older version of header file with the newer one.( keep of copy of the older one as a backup )
  5. Open Arduino IDE and Go to Files à Examples à LiquidCrystal and select Hello World SPI.
. If you can see an Arduino sketch it means the new SPI supporting header file has been recognised by the IDE and you are ready to go. Just connect your Arduino board and upload the sketch to board and run it. If you can see the output “Hello world” on your LCD all good (you can replace this to anything you like in the sketch). If it’s not working please check your connections first. Most people (including me) sometimes make wrong connections that causes malfunction or not working at all. Sometimes you might see some random characters on screen . Press reset button few times to get of this and run your code. Now you can use your LCD with Arduino just using 3 pins and saving 3 more precious pins for other components.

Please go to following links since those web pages have lots of useful details about this.

If you need my sketch you can have it from here.

Saturday, December 12, 2015

Challenges to the Power quality of modern electricity grids

It's been a long time since my last post due to a busy semester in  university and my recently started internship but I am looking forward to write more posts in upcoming months since I have some free time due to summer vacation of university. Sharing the knowledge I got from my studies always help me appreciate what I learnt and I think it's my duty to share them as much as possible because in university I realised how important to share knowledge. In almost every unit we used world wide web to learn more often we use textbook. So I think by doing somebody might find it useful.
Today I am going to present you few points about power system quality. This is not a detailed post but rather an entry point to upcoming posts under this topic. I will talk about each and every topic in this post in upcoming posts.

Modern power transmission and distribution is done by using alternative current (AC).  There are several advantages using AC transmission over DC transmission like ability step down or step up voltage as required, Ability to use high voltages in long distance transmission and almost all generators (Synchronous generators) are AC machine is another reason that AC transmission is used. But in recent years HVDC (High voltage DC) technology proved it’s capability for long distance transmission and to connect grids that use different frequency levels are quite useful. We might see HVDC more in future but at the moment all our grids are used to transmit AC.  In an ideal case these currents (including voltages) would be purely sinusoidal waves which have a frequency of 50 or 60 Hz depending on the country.  But this is impossible to achieve as we all aware.  Since the advancements in electronic devices and large demand for power by numerous types of customers on daily basis the utility companies face numerous challenges to keep their power close to the ideal case mentioned above. There are several problems associated with quality of power.
  •         Voltage dips
  •          Voltage swells and spikes
  •          Over  voltages
  •          Harmonics
  •          Variations in frequency
  •          Voltage fluctuations
  •          Voltage unbalance
  •          Supply interruptions
  •      Transient behaviour 

Voltage dips
Voltage dips are decrease in magnitude of the supply voltage for short time period. Voltage dips can happen due to various reasons such as,

  •          Tripping of sensitive protection equipment.
  •          Resetting of large computer systems.
  •          Inductive loading
  •          At the starting of a large inductive motor.

When activating large industrial loads such as large motors, they draw large currents. These are called inrush currents and this happens due to the transient nature of the motor. This causes a sudden voltage drop in line until the load (motor) starts to operate in steady state. This period could be few seconds but during this period other equipment that is connected to same node might not be able to operate. In an industrial site there may be lot of other motor as well that are connected to same node. In order to prevent motors operating under low voltage they can be equipped with under voltage relay protection which isolates the motor if such things happened.

Voltage Swells/Spikes
This is the opposite phenomena of voltage dips. Equipment can be damaged due to failure of insulation, destruction of sensitive electronic devices and electromagnetic interference caused by sudden change in voltage. Voltage spikes are often caused by lightning strikes and during switching operations of circuit breakers.
Voltage abnormalities (Image retrieved from:

Over voltages
Over voltages exceed the nominal voltage of a system over a period of time. They are mainly caused by malfunctioning voltage regulators on generators.

Voltage unbalance
Voltage unbalance occurs due to unbalance loading. Unbalance voltage supply creates zero sequence currents in wires which is responsible of heating the components. This is a serious problem in motor operating. Therefore it’s a common practice to use phase unbalanced relays to detect and unbalance cases and protect the motors against them.

Frequency variations
Frequency variations often happen in isolated networks due to faults and malfunctions of governors in power plants. Frequency variations can cause problems. Motor drives will not work properly, power generation may goes out of synchronism if the frequency has changed a lot from it’s nominal value. This may require isolating generators and reconnect them again. So having the nominal frequency value at all times over the whole network is critical.

A very common problem in power systems is effect of harmonics. The main cause for having harmonics in power systems are power electronic devices such as rectifiers, inverters, uninterruptable power suppliers (UPS) ,variable frequency drives(VFDs) and computers etc... In general any non-linear loads (loads where the voltage waveform is different than current waveform) are responsible for creating harmonics. The effect of harmonics is significant when loads are motors. Harmonics consists of negative sequence voltages which cancel the positive sequence voltages which creates the required flux to operate the torque of the motor. Since a negative sequence component creates a negative flux (which is responsible for creating negative torques) this will reduce the amount of positive torque available to operate the load. Besides negative sequence components, triplet harmonics (3rd 9th 15th) which are responsible for creating zero sequence currents in neutral wire causes heating problems and eventually degrades the machine.   

I suggest the following links might be useful if you need more details.
In depth details about harmonics and it's effects
Voltage abnormalities