Category Archives: http://schemas.google.com/blogger/2008/kind#post

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

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 (i.e.an 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

Control_servo()

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.







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 3rdyear 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.  


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
1(Q1)
4(RS)
2
3
6 (E)
4-7
11-14
8
GND
LCD Display  Pin
Connection
1
GND
2
+5v
3
10K trimpot variable leg
5
GND
7-10
15
+5V through 220 ohms resistor
16
GND
IC pins 9-16
Arduino I/O pins
9
10
+5V
11(Sh_CP/SPI clock signal)
13
12(ST_CP/Latch Pin)
9
13
GND
14 (DS/Serial Data input)
11
15
16
+5V
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 http://42bots.com
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.

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:http://assets.tequipment.net)
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.
Harmonics
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 (3rd9th 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.
Harmoincs
In depth details about harmonics and it’s effects
Voltage abnormalities

Stability of a control system

Stability is something we all need in our lives .You may have a different perspectives about what exactly meant by being in a stable state but we all have some common aspects about it. In control systems engineering it’s essential to have a stable system otherwise the system will be impractical to setup in real world no matter how elegant is your design. When we are talking about the stability of a control system it corresponds the ability of a system to produce bounded output signals to bounded input signals. When we are talking about bounded signal I would think it as a signal with a finite energy (magnitude).When I first learn about BIBO systems (Bounded Input Bounded Output) I always had a confusion what is actually meant by bounded in real case, especially with the impulse signal .The definition tells us that it has an infinite magnitude at t=0 (when the duration is close to zero) so I wondered how could be the impulse signal is bounded signal but if we relate it to real world cases we can see this concept can model lots of forces like impulse force which acts on a body for a very short time and has a very high magnitude compared to a conventional force . Impulse signals always have a finite energy therefore I consider a bounded signal means the signal has a finite amount of energy, It can’t be infinite. So if a system is a BIBO system it will not produce an unbounded signal to a bounded signal. we only consider about BIBO systems. As well as that, all the systems we consider are LTI system (Linear Time invariant signals) which means that there is only single output to a single input(one to one relation) for all t and if a system has an output value other than zero at t=0 the system is not considered as a linear in control system. Time invariant means the system will produce the same output regardless of the time difference if the inputs and the initial conditions are identical in two instances. I mentioned those concepts here although they are not relevant here since we talk about LTI, BIBO system only.

Before I proceed to talk about the stability of a system it may be good to explain few things about a typical control system. Most of the time all the analysis of control systems are done using transfer functions of real system. Laplace transformation converts all the time varying functions to frequency varying functions in complex domain(s domain) and this transformation make the analysis very easy to carry out. The following diagram shows a typical block diagram of a control system.
Plant: Plant is the system we need to control described as a transfer function(s domain). It would be any physical system and several very different physical systems can be modelled using the same transfer function.
Sensor: The sensor component measures the value of an output specified by the design and sends it as a feedback to the controller.  
Controller:  Controller is a computing device (A computer) that compares the sensor output and reference provided as the input to the system and generates control signals to Actuator using PLCs.
Actuator: A device or a mechanism that controls the plant in a desired manner.
Now back to stability, 
having a stable system is a good and essential thing in control engineering but finding the perfect stable state for a given system will be impossible since we can’t predict how the system will be behaving in future. Any physical system change it’s qualities with time and these changes might cause the system to behave in an unpredictable manner. For example, a motor will not output it desired torque after some years due to mechanical ware and a motor control system might behave unexpectedly if this doesn’t take into account. Therefore rather than using just one stable state engineers design the system with stability margins. So system will be able to handle small parameter changes to input.  This helps to tackle any unpredictability in system and makes it more robust.
How do we determine the stability of a system? The method is easy to understand but very hard to do it without using a computer  most of the time. It’s not that difficult to determine the stability nowadays with the help of advanced computer softwares like MATLAB. But before the arrival of computers people had to find methods to determine the stability of a system by hand. Few methods are listed below. I’m hoping to discuss these topics in future. Each of this method has it’s own pros and cons and becomes handy according the problem you are dealing with.  Although using computer programs are the wildly used method in control engineering, an engineer should have an in depth knowledge about those methods in order to understand and interpret the results.
  • ·         Root locus method.
  • ·         Bode Plots.
  • ·         Nyquist plots.
  • ·         Routh-Hurwitz criterion.

Determining the stability

As I mentioned above in order to assess the stability of a system all we have to know is whether the poles of the system (closed loop) is located at the right or left side of s plane.                                          If all the poles are located in left half plane then the system will be stable.
If a single pole is located on right half s plane then the system will be unstable.
Furthermore if there is at least single multipole on the imaginary axis the system will be unstable.
If there is at least single pole on the imaginary axis then the system is said to be critically stable. It’s on the verge of being unstable.
Let’s take a simple example .Let G(s) = N(s)/P(s) = 1/(s+2)(s+3) . G(s) is the open loop transfer function . So the poles of the system are -2 and -3. And these values(poles ) are negative and therefore they are located on left half plane of s plane. Therefore the system will be stable. If we convert into time domain this result will be obvious.
By taking partial fractions of G(s),             G(s) = 1/(s+2)- 1/(s+3)
And By taking Laplace inverse of G(s) ,   g(t)= exp(-2t)-exp(-3t). 
So it is obvious when t goes to infinity g(t) will decay in an exponential manner. Therefore this system will be a stable system. But instead of the system poles were +2 and +3 then g(t) = exp(2t)-exp(3t) and when t goes to infinity t this system will produce unbounded (infinite)results, which cause malfunctions in a realistic system.
If above system (g(t)) was connected to a unity feedback system , the system’s new transfer function will be H(s)=G(s)/1+G(s) and all we have to do is to solve the denominator for roots and the roots will be new poles of the system. This 1+G(s) =0 Is called the characteristic equation of the system since it will determine the stability of the system.
In conclusion it is very important to know whether a system will be able to stabilize itself and fortunately there are many tools we can use to verify the stability and the stability margins of the systems. It is an essential aspect in Control engineering .  

Using shift registers in Arduino projects

If  you are using an Arduino board(like Uno) you get about 12 digital pins for your projects .this number is fairly enough if your  project is a simple one that won’t consume no more than few pins but as the complexity of your projects increase soon you will run out of pins. There are few solutions for this.
  • You can buy a board like mega and expand your number of digital I/O pins.
  • You can use multiplexing/ demultiplexing chips to read and write to pins.
  • You can use shift register chips to expand the I/O pins.

It’s obvious that the first solution shouldn’t be your first choice since it will cost you few bucks and it’s probably is not the best solution as well. Eventually you will run out the pins if your project needs more than 54 digital I/O pins .So keep that option ,optional!!!.
Today I’m going to discuss about the 3rd solution I mentioned. I will discuss the 2nd (mux and demux) solution in future when I get a chance. Shift registers are used to expand the I/O capabilities in an electronic circuit. In Arduino domain using only 3 pins of the board and a single chip you will be able to control up to 8 outputs. And by cascading the shift registers you will be able to control thousands of outputs only using 3 arduino pins. In order to do this I have used 74HC595N chip which has 8 outputs. For this instance I used 3 595 chips to control 24 LEDs.
Figure1 74HC595 chip

Figure2-Pin configuration
Q0-Q7   are the output pins that connected to LEDs anode.74HC595 is capable of sourcing current to               LEDs  but there are different chips that use sinking current(current is drawn into the chip)                  method to drive LED. So make sure you check the data sheet if you are not using this chip.
VCC/GND   +5v supply and ground.
DS   serial data input to the chip. This pin is connected to one of the digital output pins in Arduino              and if you cascade several of them, you have to connect the DS pin of the second chip to the                Q7’ pin of the first chip.
OE      output enable .the horizontal piece of line indicates that it’s active low. That means you                      have to make the pin low in order to make the output enabled. So connect that to the                           ground to make that pin low .
ST_CP   storage register clock input .this pin is also called latch pin since it’s the pin that is used to                  transfer the data stored in the chip to the output pins. The value loaded into the chip won’t                    get pass through unless this pin gets a LOW to HIGH transition.
SH_CP  shift register clock input. This pin is used to insert the serial data into the chip register.                         When the pin’s state gets a transition from LOW to HIGH it reads the value of the DS pin                  and sends the value to register.
MR         Master reset.(active low )this pin can reset the whole chip when activated. The values                         stored in the chip will be erased .So connect this pin to +5v supply to avoid resetting the                       chip.
Q7’         This pin is used to cascade several chips together and further expand the outputs.
               Please read the data sheet I provide carefully to understand the functionality and the                            autonomy of the chip better.   And also I have add some links to some youtube videos  that I               referred in order to learn about shift registers. I highly recommend you to watch them to get                 more understanding how this chip works.

Writing the program

There is a function called shiftOut() defined in Arduino to use in shift registers but I will present you another way of implementing the functionality and later I’ll give the code I wrote using shiftOut() function. As a first instance we’ll look how to implement a single shift register.  Use the above diagram to construct the circuit. If you want you may avoid the 1uF capacitor ,it is used to remove the flickering .
Figure3-Circuit Diagram 
Now we’ll look at the code. I have attached the source file at the end of the post. So you  may have a  look at it or you can use it in your project.
Figure4-Initializing code
Initialising is done as usual in first place. In there I have assigned pins 8,9 and 10 to the serial data pin, clock pin and latch pin of the chip. And also I created an array consists of 24 elements in order to store the status of each LED. It’s type is Boolean ,therefore I can store a HIGH or  LOW  value in each element. time_const  is used to control the speed of the LED on and off. Writereg()  is a function which defined to shift the data into the chip.
Figure5-Writereg() function
At the beginning of the function the latch pin is set to low and at the end (when the data has been transferred to the chip) it is set to high. In that way we can give a LOW to HIGH transition and data has been sent to output pins. As I mentioned  above the clock pin is used to distinguish between data bits .First the clock pin set to low then the data bit is sent to a storage register in the chip .and again clock pin is set to high and this transition stores the bit in storage register this happens in all 3 chips. The first 8 bits stored in the chip which connected directly to the Arduino. When we moved the next  byte to the first chip the previous byte get shifted to the next shift register .Like that we can shift any amount of bytes as long as we have enough chips and the first byte that shifted will be stored in the last shift register that cascaded.  

Using shiftout() function in sketches 

Arduino community has provided a built in function to handle shift functions easily.
Syntax

Shiftout(Data pin,clock pin,bitorder,value)
Data pin –  serial data input  pin of the chip is assigned to this pin.
Clock pin – SHCP pin of the chip is assigned to the this pin.
Bitorder– For this you can assign two values. They are MSBFRIST or MSBLAST .
MSBFIRST 
setup the least significant bit of the value you pass to Q0 pin. For example if you send value 6       (110 in binary) to the shift register, it will be represented as follows,
Q0 – 0
Q1 – 1
Q2 –  1 

LSBFIRST 
This is the opposite of MSBFIRST ,it will assign the LSB bit to Q7 pin and  MSB bit to Q0.
 Most of the time we are only going to use MSBFIRST since it’s much convenient .So if something is not displayed as you wish when you are executing the code try replace MSB with LSB or LSB to MSB that might solve the problem. There is a tutorial in Arduino site that explains this function in more details. Please read that as well.
Shift registers are very useful way to expand the I/O capabilities of your microcontroller. I found about this technique when I was looking for a way to control a LCD display by Arduino without compromising 6 pins. I haven’t tried it yet but I hope to write another about that in some other time. Please use the links I provide below to get to know more about shift registers.

Links

following links are few tutorials I referred in order to learn Shift registers.


Convert your car –rear view screen to a monitor for Pi

If you wanted to make your cute ,credit card sized computer to something more adorable all you need is a small display like the one in the picture above. So from today’s post ‘m going to share with you about how I did that.
Things you are going to need:
  • A Raspberry Pi computer.(I’m using a model B one)
  • Car –rear view monitor which has PAL/NTSC connection
  • A RCA coupler male to male
  • 12V power supply for the monitor.(1A output  will be all right but check the monitor specification first)
Car-view monitor
RCA male to male adapter

 You can buy the monitor in the above picture for 26 US dollars by Ali express web site.  It’s the cheapest one could find and it worth for it’s price and also shipping is free but if you want a monitor with HD facilities and if you can afford around 80 US dollars or more then check out the Adafriut official site. They got some really good monitors for the job.
You can buy the RCA male to male adapters in Ebay ,I bought that by core electronics and it cost me only around 2 US dollars excluding shipping. I could complete the project under small budget around 30 US dollars since I had a suitable power supply .If you have any electronic device which uses a power adapter you might be able use that as the power supply for the monitor. The adapter I’m using is a power supply to an unwanted router.
In this tutorial I assume you already have a working pi and you are familiar with using terminal or any other text editor to edit text files.

First connect the monitor to the yellow RCA jack using the RCA male to male coupler. Connect the power  adapter to the monitor and turn on the pi. If the display is not showing anything try to switch to NTSC /PAL mode by pressing 3 or 4 in the keyboard. if you can get a signal to the monitor then it should be very small and hard to read. We need to change the resolution for  a better view and  it can be done by editing a file called config.txt .My display is compatible with 800*480 and 480 *272 resolution and try to choose the smaller one since it will display the text more clearly. But you can use other values for these if they are agree with your screen ratio. For example if your screen ratio is 16:9 and your width is 520 pixels then you can calculate the number of pixels for  height  (520*9)/16 = 293   pixels. You can find the optimized resolution for the display by trying few values like these.

In order to change the settings type the following command in the terminal .
Sudo vi /boot/config.txt

This command will open the config.txt file to edit . In the file find the following lines. Before you edit anything I recommend to keep a backup of the file.
#framebuffer_width=1280
#framebuffer_height=720

  These settings force the display to set the resolution to the given values and to activate them remove the comments and amend the value to the values you want for example like the following,
framebuffer_width=480
framebuffer_height=272
After editing these lines save (Shift+z and wq) and reboot the pi (sudo  /sbin/shutdown –r now).You can see the display is bigger and more readable than last time.but most of the time there will be some unused space(pixels) in the display and we can stretch the window until the unused space is gone. You can optimize the display by this. To do this open the same file(config.txt) and find the following lines ;
# overscan_left=26
# overscan_right=26
# overscan_top=16
# overscan_bottom=16

Remove the comment sign and change the values to negative values in order to expand the display. You can use values up to -30 , values beyond that didn’t work for me .After that save and reboot the  pi. You might have to repeat the above steps few times in order to get the best output. It’s all about trial and error. Besides these settings you can do more configurations using this file. Read the file carefully to know what you can do with it, try to play around. If everything went well you will get a nice display like in the pictures.  





















Introduction to robotics -3(Writing the program)

In the previous post I pointed out some of the key things about the hardware components and software techniques that I used to construct the robot. I this post I hope to give more insight into the software perspective of the design.(I assume you have read the previous article and the links I provided . )
In this project my main concern was on to the software side since most of the hardware I used was either simple or they are already on a working phase (like Arduino and the chassis.)Anyway before you write your software it’s important to realise what sort of functionality you are expecting from the robot and break it down to simpler objectives. In my case the functionality of the robot can be brake down into several steps.
  1. Moving the robot to forward, backward, left and right.
  2. Detect an obstacle in the path.
  3. React to the obstacle by turning to a different direction.
  4. Continuing moving along the new direction until it encounters another obstacle.

To achieve the above tasks I used a simple program which is written using Arduino IDE. Here is a simple flowchart which summaries what the program does. The 15cm boundary is an arbitrary value, you can use any value which is in the sensor’s detection range. but I recommend  small values since the sensor is not very accurate in long distances. Initialise is the process of feeding the program and the controller about the necessary settings like the I/O pins used the constants, Interrupts etc.. I’ll explain this when I get to the actual program. The delay function which I used in the program does very important task and I would like to explain the importance of that. It’s a fact that mechanical systems are always slower than electronic systems when responding. So there will be a delay when you send an electrical signal to a mechanical system to do something and actually starting to do that thing. It won’t complete that command instantly .So a delay is needed between two commands to complete each. Otherwise your system will act in unpredictable ways. You should keep this in mind when programming since it’s not straightforward. It’s one of the most important thing s I learned in my uni. You can use any amount of delay time .with some trial and error you can easily find the most suitable delay time.
Initialise

As I mentioned above initialisations prepares the system and the program for the execution. It basically consists of declaring the I/O pins, variables  and interrupts. there is a separate function called Setup() to initialise the system. Outside this you can declare the functions you are going use and any #define statements. I have used timer interrupts to trigger the sensor every 50ms and take a distance measurement. So I strongly recommend you to read the article about the interrupts or you can just copy the code of mine. It’s a must to know how to tackle interrupts in embedded systems , otherwise your programs are not going to be function efficiently. If you want to change the trigger time all you have to do is to change the value of OCR1Ato a value you desire within it’s range. Besides this you have to include two libraries which handle interrupts in setup().

Figure1-Flow chart

 Moving the robot
Moving the robot in a particular direction is one of the primary task in any robotic project .So first of all I wrote a simple program to check the movement of the robot and to verify my hardware is working as I expected, especially the H-bridge control circuit. To achieve this I used 5 functions that each set the pins connected to the DC motors in a particular configuration. ( by setting these pins high or low you can control the direction and rotation of the motors.). I declared them as void since we don’t need that function to return anything .
Figure2-An example for control function 

 
This pin configuration can be unique or not but play with your motors to figure it out. But keep in mind not to put all the pins in HIGH since it will damage the IC. It’s always encouraged to use separate functions to carry out different tasks and not to do everything in the main()function. This practice is important when the program gets complex and branched. The functionality of the main() is like the functionality of a leader in a team. A leader is not there to do everything by himself but rather to coordinate others to do what they are capable of. Like that by separating different functions it gets easy when debugging and finding  errors.
Besides that there are two other functions to measure the distance and to trigger the sensor every 50 ms . When using interrupts there is a common practice to declare the variables used in ISR to be declared as volatile. The reason for this is to indicate to the compiler that variable can be changed a synchronically to main since it gets updated by the ISR. if you don’t declare the variable as a volatile type the variable might not get updated correctly .So it’s an important aspect to remember.
Figure3-Distance measure function
Distance value is in cm and you can change this by changing the constant 29.1 but I think cm is a reasonable range for the robot. I used a delay  of 1ms to get some time for the sound wave to spread out and reflect back into the sensor. I used unsinged int as the return type of the function since a distance can only be a positive value but recently I came to know that it’s recommended to not to use unsigned number types in practice since it might causes some troubles if you try to do arithmetic with that. Since  I don’t do any mathematical operation to  it seems legit to use it.    
Figure4-ISR function                      

This ISR function is a defined function. So all I did was to write the content of the ISR. So when the timer interrupt is triggered it will execute the Measure _distance() function and update the variable x which holds the distance value.
Figure5-Configuring Timer 1                                
I highly recommend to read this article to understand the above configuration settings .It’s really important to understand how interrupts works in order to create good designs. If you would like to use that configuration without any change it’s ok but if you want a different time (this is set to trigger every 50ms) you can change the value in 0CR1A register. For example if you double the value (780*2=1560) interrupt will trigger every 100ms.
Although this was a simple design I learned lot of things…and above all I had a chance to put the knowledge I gained in my studies to build something really works. That’s was a great experience for me.
There are some cons in the design that I would like to discuss in here.
  • Sometimes the robot’s behaviour gets unpredictable and it fails to spot an obstacle and gets hit. My primary suspicion was it was due to a fault in sensor since it only happened few times. and sometimes it stopped moving  for no apparent reason. As s solution I changed the location of the sensor to a centre position and it improved the performance of the robot.
  • According to the Figure1, when the robot detects an obstacle it only turn to right side. It’s not a very intelligent behaviour .Therefore I wrote another sketch to improve the ability to decide a direction to go when it encountered an obstacle. I’ll give you that in the next post.

You can download the complete sketch  for the project and play with that around .but I highly encourage you to write your own sketches since it will improve your programming skills .I will give a detailed information about the improvements I have done to the design in the next post.
Below are few photos of my robot Walt…

An Introduction to robotics-2

In previous post I talked about some background information about what kind of things you have to consider when planning to build a robot. In this post I’m going to extend that to another prospective. I’m going  to give you some very simple but useful information about several things you want to know about basic electronics and programming in general. and also I assume the reader has at least some basic knowledge in C programming and how to use Arduino IDE and other associated softwares.

As I told earlier it’s easy to design a robot(or any other design) if we breakdown the whole thing into several pieces and designing each one carefully. There are few advantages of this approach.
  • You will have a good understanding about each section and how they all fit together in a much larger system and the functionality of each section.

  • When something goes wrong (believe me it will) you don’t have to check each and every part, just the part associated with the fault, it will narrow down your scope and saves some time.
  • You can reuse what you have done in a project in another project if it’s suits with the requirements. It will save your effort since you don’t need to do everything from scratch .  Ex: if you wrote a function to compare two input values and send the result to main function rather than doing everything in the main, you will be able to use that function in some other instance with fewer or no changes.

  • Take your time to design and think about what you are going to do before you are actually going to do it. Thinking is one of the most important things in building something. It will help you to save your time, money and effort.

Some thoughts on embedded system programming 

There is no huge difference between writing a program to a PC and for a microcontroller .but there are few yet very important aspects that you have to remember when writing programs to a microcontroller.
  • Microcontrollers have very limited amount  of resources(memory and processing power)to work with. Therefore you have to be very careful about the size of your program and the memory it’s going to use during the execution.

  • Most of the time you will be using C or a derivation of C to program. Therefore it’s a good thing that you are comfortable with using C as a language. C is wildly use in embedded systems because it’s a well structured and easy to learn language. If you are a working most of your time in high level languages you might feel C is very low level language but that’s the thing what makes C is very suitable for system programming.

 
In this first project I didn’t use much complicated things but I think there is a concept that you have to be familiar with, Interrupts. Interrupts are one of the fundamental things in embedded   environment. An interrupt is simply an asynchronous process with respect to a main program which is used to get information to the microcontroller from outside world or within the system. There are 2 types of interrupts.
  • Hardware interrupts
  • Timer interrupts

A signal from a push button press is an example for a Hardware interrupts and sending a pulse to the system using a clock provided to indicate something to the system is an example for a time interrupt. As I said interrupt is a technique used to get inputs into a system. There is another way to do this .It’s called polling. Checking for an input within the main program constantly is called polling. Using interrupts have a significant advantage over polling in embedded system because interrupts are asynchronous .Interrupts can happen anywhere within your main and you don’t need to worry about that once you set up an ISR (Interrupt Service Routine) to handle that interrupt. I’ll provide some links where the reader can get more information about interrupts . It’s very important to understand the role of interrupts and how to use them effectively in programming.

Electronics  used in the project

Since I’m using Arduino as my control system(Brain) to the robot it made lot of things easy for me. Although I didn’t want to worry about building a system from scratch there was a big constrain . Arduino is a good platform for robotics but it cannot provide enough current to drive heavy loads like DC motors. It’s maximum output current is 40mA and voltage is +5V.So I had to think about a way to drive 2 DC motors without destroying my Uno board. In electronics it’s done by using a H-bridge circuit. A H- bridge consists of MOSFET transistors that can control both speed and direction of the motors. I used a L293D chip to control the motors.   There are motor driver shield that can drive upto 4 DC motors but the price was too high for me and also I needed only one  since an IC can control 2 DC motors and it costs me only 3.95 AUD. You can easily purchase these type of  IC in web cheaper.


L293D IC
Pin configuration of the IC
  • Voltage range : According to the datasheet L293D can output   4.5V to 36V.My motors working voltage is around 7.2V.there for it’s ok to use this chip.

  • Output current is 600mA and maximum output current is 1.2A. My motors draw 450mA(each) in normal operation and the stall current is about 1.17A.So The IC can drive these 2 motors without much trouble.

This is a great video I followed to get this thing work. I’ll explain more about the chip when required. 

 Pin description of the IC

Enable 1,2 – These pins control the motors. If they are  high motors work ,if they are low motors are   disabled. Connect these pins to +5V pin in the Uno  board for this project.
GND – Simply connect these 4 pins to ground of the Uno .
Vss  – Power supply to the chip.(+5V).  
             
Vs  –  Power input to the motors. You can connect your battery output to this pin.                                                       
Input 1,2 – These are used to control the motor1.by setting pins like High, Low or Low, High you can change the rotation direction of the motor. Never set both pins in High as it will damage the chip. Setting both pins low will turn off the motor.
Input 3,4 – These are used to control motor2.Same functionality as Input 1,2.
Output 1,2 and 3,4 – These 4 pins connects to the motor 1 and 2.

Sensors

HC-SR04 Sensor-Pins from left-VCC,Trig,Echo and GND
 I used a conventional HC-SR04 ultrasonic sensor as my sensor to detect the obstacles and send that measured value to the microcontroller. All you have to know is that this module sends out an HF wave and by detecting a reflected wave t can calculate the distance. Obviously You have to write a program to do so. In my experience these are good to detect things that are away up to 80cm after that it might give you wrong readings but since it’s very cheap  it’s very good sensor for a simple robot project.

Pin description of the sensor

VCC – power input to the pin (+5V)
GND – connects to the ground pin of the Uno.
Trig –  Setting this pin high will emit a HF wave from the sensor.
Echo – When the sensor detects an HF wave it sets this pin to high and by using a function called pulseIn() we can find out the time taken by a wave to return to the sensor. This value is in milliseconds and it has to be divided by 2 in order to get the value for the time taken by the wave to reach to the obstacle from sensor.
So these are some things that I believe you have to be familiar in order to build a simple robot. I’m not going give you every detail about how I built my robot since it’s inappropriate and you can use these guidelines to design your own robot. In the next 2 posts I hope to discuss more on the structure of the programs I wrote for the robot. 
Picture of my robot-Walt
Further Readings
Please refer to these websites and documents to improve your knowledge.

An introduction to robotics

It’s a pleasure to be here after a while. I’m having my summer vacation after a long, stressful but exciting semester and I’m hoping to spend my vacation studying robotics and microcontrollers with my knowledge I gained throughout the semester. So I thought to share some of my experiences about planning and building simple yet very exciting robotic projects I’ve done so far.

Building a robot by your self could be a challenge. It depends on how complex your robot project is. But it’s rewarding. You’ll get to know a lot about electronics and programming and it’s a great chance to use your knowledge to building something cool if you already have some academic background in electronics and programming. I’m expecting to write few blog articles about how I carried out my projects and in this article I’m hoping to present some basic ideas about robotics and design. Please use the links I’m providing throughout the article to expand your knowledge. 

First thing first

When we are  planning to build a robot we need to have an idea about what sort of robot  we need or the requirements .In my case I wanted to build an obstacle avoiding robot which is capable of detecting obstacles ,avoid them as much as possible and wander around in a given area. Next step would be searching for different examples in web and have an idea about how those types of robot functions, what sort of materials they have use to build the robot  and what is it capable of. There are lots of  very good websites in the web which were very helpful in my case. As well as these ,you need to be aware of your budget .If you are a student like me you won’t be able afford much to building a robot but it’s good to have at least few hundred dollars if you wish to buy some materials for your robot.



Modelling your robot

Every robot can be simplified into four simpler sections.
  • Sensors, Inputs and outputs
  • Control system
  • A Power Source for robot
  • mechanical parts

The combination of all these sections makes pretty much every robot we see. So when planning it’s much easier and efficient to break your model into these categories and find the most suitable parts for your application.

Power source

The main power source for  a robot will be batteries .Things like solar panel will be a good idea if your robot will spend much of it’s time out door but even in that case batteries will be there as a backup power source. So it’s good to do some research about types of batteries used in robotics before you start. The article in hereis a good article about different types of batteries and what are the pros and cons of them.  Rechargeable batteries are a good option if you can afford them since they are a bit expensive and you might need a purchase a specially designed battery charger along with them but if you are hoping to continue your robotics consider it as a good investment. In general you may be able to find good deals in E Bay or Amazon  if you search them a bit. Currently I’m using 6 conventional AA size batteries (1.5V) and a 9V battery as the power source for my robot  and I’m ok with them since I’m not extensively using my design.

Sensors ,Inputs and outputs


Sensors are another important part of any robot since they are the only way your robot can get to know it’s surroundings. There can be many types but some simple common sensors would be IR sensors, ultra sound distance sensor , photo resistors and thermal sensitive transistors etc. By  utilizing these you can give the robot an idea about it’s surroundings and to respond to them accordingly. In here I used an ultrasound distance sensor (HC-SR04) to measure the distance and navigate the robot. Your outputs would be LEDs, Speakers or even LCD displays which are capable of inform something to you about the status of your robot.

A Control system


For most of us this would be the first thing comes in to mind when we talk about robots .Controls system acts like the brain of the robot. It takes the inputs from sensors ,process them according to the instructions given  by the program and decide what do according to the results and sends the control signals to the required hardware.There are lots of microcontrollers you can choose to program your robot .Arduino is one of the most popular platform for robotic applications and I’m using that an Arduino Uno board to control my robot .It’s considered as one of the best platforms for the beginners and it’s a pretty decent and sufficient board for most of the robots applications. It is capable of many functionalities that you can use to control a robot and there are lots of support for Arduino projects out there in web and it’s very helpful when you got a problem or trying out new things and you need some support. I highly recommend official Arduino web site as a reference.

Image retrieved by http://store.arduino.cc


All other mechanical and electrical components


This categorises all other moving and non moving parts like the chassis , electrical motors connectors wheels etc. I’m not going to this section in detail about these as my primary concern is electronic and software section of the robot and I don’t have much knowledge about the mechanical parts or how they work. So my solution to this was to buy an assembled chassis from web and all I have to do was design electronics (both hardware and software)to control the motors . I used a tank type chassis (RP5-CH02) as the base of my robot because it got all the motors and gear systems that otherwise I have to build. So it’s completely up to you to make a decision but if you can build a chassis ,then you will have more freedom to customize your design.  
 

Image retrieved by http://static.rapidonline.com



So in my next post I’m hoping to talk about some of the things you may need to know about  electronics and software fields to make a robot.