All posts by sudaspace

Debouncing in Arduino

Button bouncing is another common problem that everyone faces when designing electronic circuits. This phenomenon is caused due to mechanical properties of buttons.In here I am concerned with the push button which is a type of button used often in electronic projects.

When we push (close) a switch it sends an electrical current to a microcontroller input pin. Then it is identified by that microcontroller and responds accordingly. When we push a push button it sends a sort of a pulse signal to the microcontroller as given below.

pulse
An Ideal pulse from a push button.

However, although switching on or off a switch may seem instant, real switches, buttons take some time to make the contact. so the real case is quite different from the ideal case. since a real push button is consists of a few mechanical contacts, when you press a button these metal contacts will touch several times before it settles down to a stable position (on or off). The following figure shows what happens when you push the button and releases it.

switchbounce.jpg

An oscilloscope graph of pushing a push button

As you can see there are several spikes before the switch or button settles to an “on” position. Although this whole thing occurs within few milliseconds, it is a quite a large time period with respect to a microcontroller. The result will be that the microcontroller will count these spikes as button presses (false positives). for example, if you program your Arduino to count the number of button presses, the program will output an incorrect result due to button bouncing.

There are mainly two methods which can be utilised to prevent button bouncing. They are,

  • Hardware debouncing
  • Software debouncing

This article deals with hardware debouncing methods. I highly recommend you to read it as it will give you a complete understanding. In this article, I would like to focus on software debouncing as it feels the easiest way to overcome bouncing.

As I have mentioned earlier, bouncing occurs due to button contacts making several contacts before it reaches to its desired position (state). So all we need to do is to tell the microcontroller to ignore the signals coming from the button for a certain amount of time. since we know these bounces take less than 1ms, we can program the controller to start accepting input signals after about 5ms. In this way, the microcontroller will not see those undesired spikes hence it will give us correct readings.

In this project, I am using my push button in 3 different ways.

  • Toggle a LED using a push button.
  •  Count the number of button presses to control a LED.
  • Measuring time between pushing and releasing a push button.

All these have a practical aspect since we use these functionalities in actual designs. For examples, we often use the same button to switch on/off electronic devices.Moreover, the same button reacts differently depending on the duration it was pressed. All these are possible due to the correct implementation of button debouncing techniques.

Toggle a LED using a push button

In this exercise, a push button is used to turn on and turn off a LED. although the task is simple, implementing correct functionality is difficult due to button bouncing. As a result, I used a software debounce technique to eliminate button bouncing.

The following picture shows the circuit I used to do the exercise.

17792574_10212860690934540_714035236_n

The circuit to demonstrate button debouncing

 

components.png
Circuit Schematic

I was able to perform all three exercise just using this circuit.

Initialization of the circuit was done as follows.

LED toggle1.JPG

Initialization of program and board

In this piece of code the variables, “lastbtnstate” and “currentbtnstate” are used to store the status of LED at the moment and one before. “LEDstate” is used to toggle the LED (turn it on or off).

Button debounce function

Button debounce Function

In this function, it returns a boolean value as the state of the button. Firstly, it records the current state of the button (btnstatenow). Secondly, it compares the current state of the button with the previous state (previous) to identify whether it is being pressed or released. if those states are not the same, then the function enters to a delay. This delay avoids button debouncing which would last for about 1ms.You can play with delay interval but I recommend using something like 5-10 ms will do the job. After that delay, the function once again reads the button state and returns its value.

The code I used for loop() is as follows,

 

main loop.JPG
Main function that controls the LED

In this function, it passes the previous state of the button to button debounce function and stores the current state of the button (High or Low) in the currentbtnstate variable. After that, I used if condition to detect the button press. If statement toggles the variable (LEDstate) that controls the state of LED (on or off). Finally, the button status is updated.

 

Count the number of button presses to control a LED.

Next task is to count the number of button presses that can be used to trigger something else. In this exercise, I light up a LED for 1 second and turn it off after the program detects 10 button counts.

In this, the main goal is to count the correct number of button presses. It is impossible to do this without using debouncing as the microcontroller counts unwanted button bounces as legit button presses hence turning on the LED at a random point.

Initialization is done as follows,

task2_ini.JPG
Initialization of the program

In this program, the variable count is used to store the number of button presses. You can use the same function that was used in the previous exercise to debounce button presses. So I just copy and pasted it to this program.

The Following figure shows the main function of the program.

task2_loop.JPG
Main function for task 2

Similar in task 1, at the beginning the previous button state is passed to button debouncing function and the current button state is stored. Then it is used to detect a button press using if condition. if the program detects a button press, it increases the counter variable by one and toggles the button state. then another if condition detects the button release and assign Low state to current button state. If the counter hits 10, then the program turns on LED for 1 second and turns it off and resets the counter to 0. Using debouncing guarantees only legitimate button presses are being detected.

Measuring time between pushing and releasing a push button

This functionality is another useful thing about push buttons as it allows us to execute different things depending on the duration of a push button being pressed. In order to do this, I used a built-in function in Arduino called millis(). This returns the number of milliseconds since the board started to run the program.

The concept is very simple. First I programmed the microcontroller to store a time measurement when the button is pressed. This is our starting time. Then I store another time measurement inside another variable when the button is released. Finally, I take the difference in these two measurements and divide it by 1000 to convert it into seconds.

The following picture shows the initialization code.

task3_ini.JPG
Initialization of the program

As usual, you can use the same button debouncing function in this instance as well.

The following picture shows the main function in this program.

task3_loop.JPG
Main function

You can download all three exercises using this link.Feel free to use them and change them.

I hope to see you all soon with another project.

Google Deep Mind project-Are we playing God?

Künstliche-Intelligenzen-wie-Google-DeepMind

I recently watched this small video about another amazing Google product called “Google Deep mind” .(It’s the famous  program Alpha Go Ai that became famous after beating world champion in a game called “Go”)It is amazing that we can see a general AI within this decade. The main difference between Alpha Go and it predecessors was Alpha Go used reinforcement learning and neural network to mimic learning process of a human. In other words Alpha go just didn’t calculate all possibilities selected the best moves (which is impossible as the game Go has far more number of moves than the number of atoms in universe) but rather it learned by its own mistakes and got better by practicing and by watching other human players play the game. Sounds like science fiction but according to the creator Deep mind the way Alpha Go learnt to play Go game is pretty similar to how we (humans) learn anything new to us. People are worried that this might be a warning about AI being smarter than Humans but I think it is inevitable that robots will be the next phase in evolution one day and there is no need to be worried. It has happened previously and it will happen once again.   As an engineer and a tech enthusiast I believe that machines (tools) created the man we know today. (imagine you have no phone, no PC or Laptop or any electricity, car or anything that human created using science and technology, you will be more helpless than a caveman who had at least few stone weapons.) It helped mankind to go beyond it’s physical and mental abilities and do amazing things. Therefore having machines that have similar abilities as a human might increase our chance of survival as a spices. but as we all know science and technology is like a coin. It has both positive and negative effects on humans. It’s up to future to decide what will be the relationship would looks like between humans and AI.  You can watch the video about Alpha GO and a public speech by the creator of Deep Mind using following links.

Public lecture by Demis Hassabis

Google Deep Mind explained

 

Facts about FACTS

 

 

49762

(Image of a variable Shunt reactor used in a transmission grid  http://www.bpress.cn/list/di/pic/62/49762.jpg)

In this blog post I would like to talk about Flexible AC transmission Devices (FACTS). I have being studying how these devices are being used in controlling the load flow in electrical grids, therefore I thought to share what I have come across with you.  In past few decades as the power consumption of population increased in   exponential way power industry had to expand their ability to service people by constructing new power lines, transformers and power plants. At the same industry observed that there is reduction in rate of power consumption. This was due to increase in efficiency in power equipment, economic recessions. Because of this expanding and constructing new infrastructure was not a good solution economically. And also due to control schemes used in controlling grid and handle faults were not fast enough as they consisted of mechanically controlled circuit breakers. The long switching periods and discrete operation make them difficult to handle frequently changed loads smoothly and damp out the transient oscillations quickly. In order to compensate these drawbacks, large operational margins and redundancies in equipment used were maintained. These reasons caused electrical utility companies to have higher cost of ownership and longer payback periods for their investments. In order to overcome these problems, a utilization of assets was preferred. FACTS devices were introduced as a result of this.

The development of FACTS was a by-product of development in Power Electronics. Power electronics combines the advantages of semiconductor devices and the high power rating requirements in electrical power engineering. High speed switching, reliability and accuracy were some of the qualities FACTS obtained from using power semiconductor devices such as Thyristor. Due to advancements in Power Electronic technology and advanced control technology, FACTS has become the preferred choice to control Voltage, active and reactive power flow, transient and steady state stabilization that improves the operation and functionality of existing grid assets. FACTS devices increase the efficiency of in terms of both technical and economical ways by allowing operators to distribute generated power through less congested paths to consumer hence reducing overall generation capacity. This will reduce the operation costs in electrical utility.

Before the discussion about FACTS it’s better to have some knowledge in theory behind how power flow in a line being controlled and what are the parameters to be considered.

 

1
Simplified electrical system with two buses

 

 

 

 

 

The above diagram shows the schematic of a transmission line. Although in reality there is a resistance in the line that causes real power losses it can be neglected as this value is very small one compared to the reactance of the line (typically 10 times smaller). The next figure shows the vector diagram for the power line. In most cases the two buses have the same voltage magnitude (V1=V2) but different angles. This angle difference is used to control the power flow direction. There are two main equations used to model the power flow.

 

2
Equation 1- Active Power Flow and                       Equation 2- Reactive Power flow

 

 

 

 

 

These equations model the active and reactive power flow at bus 2. In here. These two equations shows the power flow will depend on the voltage magnitudes, the phase angles and the impedance of the transmission lines. By controlling those 3 parameters electrical utilities can control the power flow in a transmission line.

There are two methods used in power flow controlling,

  • Series compensation
  • Shunt compensation

 

Series compensation

According to equation1 the active power flow will depend upon V1, V2, Sin δ and XL. In series compensation power flow control is done by controlling XL, the impedance in line. This is the overall line impedance not just the actual line impedance due to the reactance in line. A series connected capacitor or a reactor can inject a voltage causing this reactance to change hence changing the power flow in that particular line.

3
Series compensation

 

If a capacitor is added. This VC is called quadrature voltage since it’s shifted by 90 degrees. This effect will add a voltage drop which will oppose the voltage drop in line. The power flow will be increased as a result of this

If a series reactor is added  . This Vwill add a voltage drop which will cause power flow to be reduced.

Shunt compensation

Shunt compensation is used utility to regulate the voltage profiles of buses. Shunt connected reactors can reduce line over voltages by consuming reactive power and Shunt connected capacitors can inject reactive power to bus to increase the voltage. These methods help to maintain the voltage at a busbar closer to it’s rated value (1pu).

FACTS devices usually employees one or two of these methods to control the Voltage, phase angles or line reactance .

There are many FACTS techniques are being used at present but all can be categorized into 4 categories.

  • Series Controllers
  • Shunt Controllers
  • Combined series-series controllers
  • Combined series-shunt controllers

Series Control FACTS

Series connected FACTS could be a variable impedance such as a reactor or a capacitor or power electronics based variable source of main frequency. All series reactors inject a voltage in a series with the line. As long as the injected voltage is in phase quadrature with the line current, the series controller supply or consume reactive power. If the phase difference is different than this it will handle active power as well.

4

Shunt control FACTS

A shunt controller could be a variable impedance or a viable source or a combination of both. Shunt connected controllers inject current at the point of confection. Although it may seem like impedance devices are not capable of doing this they can create a variable current flow using varying impedance hence it in a way controls the current in line. The injected current is in phase quadrature with line voltage. Therefore it will only consume or deliver reactive power. Any other phase difference will cause it to handle real power as well.

5

Combined Series-Series FACTS

Combined Series-Series controllers can be used to control both active and reactive power in transmission lines. This method is often used in multiline transmission systems. These types of controllers can be operated in two methods.

  • Combination of separate series controllers which are operated in a coordinated manner in order to realise power flow control.
  • Unified controllers, several series controllers provide independent series reactive compensation for each line but also has the ability to transfer real power among transmission lines using power link. The real power transfer capability of unified series-series controller maximize the utilization of transmission systems by giving better control over both active and reactive power.

6

Combined Series-Shunt FACTS

Combined Series-Shunt can be used to control both active and reactive power in transmission lines. There are two types FACTS technologies to achieve this.

  • Combination of series and shunt which are controlled in a coordinated manner in order to realise power flow control.
  • Unified Power flow controller which contain both series and shunt components, in theory combined shunt and series controllers inject current into the system with the shunt part and voltage in series in the line with the series part. When the shunt and series parts are combined there can be a real power transfer between these two via power link.

7

Although both series and shunt FACTS have the same objective, Achieving better control over power flow in grid, these the effectiveness of these are different in different scenarios. Therefore it’s better to have a look into some of the advantages and disadvantages in both technologies.

  • Series controllers are more effective in controlling the current/power flow and damp oscillations than shunt controllers if both have same MVA ratings.
  • Shunt controllers are a good solution to control voltage at a point of connection and around that area. Therefore shunt controllers are often used to control the voltage level at substation bus as it serves the bus node independent of the individual lines connected to it.
  • One disadvantage of series controllers are that they have to be designed to handle dynamic and contingency overloading as they are connected in series with power lines.

Advantages of FACTS devices

  • Improving Power Transfer Capability.
  • Confining Power Flow to designated routes.
  • Transient and dynamic stability improvements.
  • Ability regulate voltage hence avoiding cascading power outages.
  • Damping of power system oscillations.
  • Ability use transmission lines close to their thermal limits.
  • Improving system reliability.

Drawbacks in FACTS

  • Very expensive to design and implement.
  •  Device complexity in design and implementation. These devices are often rated in MVar power range and rated voltages are the voltages equals to the system voltage they are connected to. In power transmission this could be high as 132 kV and above.
  •  Since the high power requirements, the power electronic devices used have to withstand high power and voltages causing high costs in construction.
  •  All conventional FACTS devices used are lumped in nature. Generally these are designed to withstand the load growth in next 30 years. This approach causes poor return of investment to grid owner which is a major drawback.
  •  FACTS devices are custom designed according to the requirements of the clients. This results in longer design and construction cycles. This will add additional costs to the devices.
  •  Shut down or failure of one of these FACTS have a significant impact on grid as the number of devices used in a particular electricity grid are limited.

References

  • Understanding FACTS : concepts and technology of flexible AC transmission systems By  Narain G. Hingorani and Laszlo Gyugyi.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

The Animatrix-The movie that explains why there is no spoon-Part 2

The first part of this post can be view from here. In this post I would like to talk about the rest of the  stories in  the movie Animatrix.

World Record

maxresdefault

Through out the matrix world almost all the people who freed themselves from Matrix did it by realizing the true nature of matrix, an illusion made by a software simulation to deceive minds of people who were no longer born but grown as a source of power.They use their power of mind in order to see the true nature of their reality. but this short movie tells the story of an extraordinary athlete, Dan Davis who was able to free from matrix for a short period of time by using only sheer physical power.

“Only the most exceptional people become aware of the Matrix. Those that learn it exists must possess a rare degree of intuition, sensitivity, and a questioning nature. However, very rarely, some gain this wisdom through wholly different means.”

Dan Davis is very talented athlete who is currently holds the world record for men’s 100 m (8.99 s)but unfortunately being accused of using illegal medicine to win previous races. He is planning to prove his innocence  by participating to the next world 100 m race and winning but even his coach doesn’t believe him and give up after trying to explain it to him. Dan doesn’t believe anyone except his father who advice him to believe in himself and as a father, he too believes in Dan.

How ever with all obstacles Dan qualifies to the final with hope . On the day the race starts and we can see how Dan is pushing himself beyond his physical abilities in order not to just win the race but to break his own world record. At the middle of the race Dan   get a  muscle rupture  and slows down. but because of his strong desire to win the race and prove people were wrong about him, he speeds up again and this time he is starting to go beyond his physical abilities and overcome the limitations in matrix. The agents presence in that area sense abnormal signal patterns inside the matrix that caused by Dan’s actual physical body activities in side his pod in one of the power plants. Agents try their best to stop Dan being waking up but they were unsuccessful and suddenly the wakening of Dan in a pod is shown to us. As he wakes up a machine who looks after pods reaches him and manages to connect back to the matrix. Dan looses all this memories due to this but was fortunate enough to win the race (inside matrix) with renewing his world record.(8.72 s). Dan looses his ability to walk and confined to live rest of his days under the supervision of agents.

Although the agents are pretty sure he won’t be a trouble in future the story ends putting a question mark in front of that. before the story ends we can see Dan tries once again to walk again showing his desire to be freed and disobey the machines but he falls on floor as his legs are weaken. But how can we be sure Dan won’t try and successful again in future?

The story of world record illustrates about the consequences of breaking the limitations in a system where rules are in place to govern people. Most people will obey the rules and will be okay with them even though those rules don’t make sense. Some will questions it try to overcome it. In some religions like Buddhism, the way to see the reality or the truth is to limit the physical activities and concentrating mind using methods like meditation. This is the preferred method in most cases even when matrix considered. In the first matrix movie there is a scene where Morpheus teaches Neo about martial arts. The real intention is to show the true nature of a simulation like matrix. In there after a exhausting fight with Neo, Morpheus questions him why Neo can’t defeat Morpheous. Neo says it’s because Morpheus is too fast. Morpheus answers this questions with another question to Neo.

Morpheus : How did I beat you…..?

Neo : You…you’re too fast…

Morpheus : Do you _belive_ that my being stronger or faster has anything

to do with my muscles in _this_ place?

Neo just looks at him. Morpheus stares back.

Morpheus : You think that’s _air_ you’re breathing now?

Neo : ….

Morpheus looks surprised

Morpheus : *shrugs* Hmm.

Neo stands up again

Morpheus : Again!

Morpheus shows to Neo that in simulated world being physically strong or fast is irrelevant and what important is to realize it is just an illusion.The feel of being alive or existence of myself (self-conscious) is not there anymore. So the rules that binds your physical abilities doesn’t affect you in matrix, your mind believes that it does therefore you limit yourself. although this is more into a mind game sometimes the strong desire and dedication like the one that Dan had, Winning the race to prove his innocence can lead to realize the true nature of our reality.

Beyond

animatrix

Beyond is the story that adds some sort of explainable elegance to the movie matrix. Although it doesn’t go deep into the philosophical materials, it has some of the strongest elements of any other good stories in animatrix. Story of Beyond is about a haunted house located in the middle of a city. The people in the city consider it as haunted because of some strange activities going there.In real this is a glitch in matrix therefore some physical laws (like gravity ) that govern in  rest of the matrix can be acting strangely inside this premise. At the beginning we can see a tracing program being executed to pinpoint this location and sends crew to fix the error.

Yoko is a girl who lives near to this house. One day she lost her cat and after searching in her neighborhood she meets couple of kids who suspects that her cat might be in that haunted house. She goes to the house to search her cat and the kids also follows her. In there she experience very strange things. There are rains in some parts in  house which doesn’t affect to the rest. Floating Cans and ghostly light bulbs. One of the coolest thing is that the time being slowed for those who are inside. Children jumps from heights and land safely on floor with out being injured as they can have control on  gravity in here. They enjoy these strangeness a lot as they feel they are freed from rest of the world. Yoko finally was able to find her cat inside the building. She too tries  and there she feel very calm and a feel of being freed as a bird. They don’t get to enjoy this for a long time as the  crew reaches and seals the area and evacuate the children by force.The crew was successful in fixing and re configuring the house.

After few days Yoko returns to where house was located but now it’s being replaced by a construction site. and we can see that there are no more strange things happening and every thing acts according to the way they are supposed to be. Children are pretty upset about that including Yoko. While they are worried and unhappy about what happened we can see every thing is back to normal, dull and lifeless in matrix.

I think Beyond is the most wonderful story in animatrix as even a person who has no interest in simulated reality can sit and enjoy Beyond purely because of it’s simplicity and very nice story. I always feel difficult to tell my opinion on Beyond as it’s very personal and I find it difficult to turn it into words. The feel i get whenever watching Beyond is the joy of being free just as the kids and Yoko are experiencing inside the haunted house. As kids our worlds are filled with fairy tales, happy moments,Wondering how things happen in nature, being curious and carefree life but as we grow up become adults we take responsibilities and learn about the world and it’s not a good place as we saw in our childhood and sometimes become nostalgic about what we’re missing. the adulthood might feel rather dull and lifeless compared to one’s childhood. In a way being inside the matrix represent these limitations we experience in out lives and our desire to be free once again.

A Detective Story

The-animatrix-a-detective-story

One special thing about Animatrix is that every story has a unique theme to itself. A detective story is the best example for that. It can be categorized as film-noir cyberpunk story which gives it’s uniqueness among other stories. A Detective Story is about a young detective who is on the verge of giving up on his career as detective due to lack of income and quality of work he has to do. But a single phone call from an unknown person change his mind about quitting job. The job is to find a hacker who is known as Trinity (the same Trinity we know). Detective accept the job and does his best to uncover Trinity. While working on the case he finds out there were three other detectives who tried to catch Trinity. One detective killed himself, another disappeared and the remaining one went crazy. So he goes to meet this crazy detective and he was able to get some clues.He follows those and finally is able to find Trinity (rather Trinity finds him.) in an online chat room. He was able to set up a meeting with her at a train. Eventually they meet and there Trinity finds out he has a tracking device inside him and she managed to get it out. As they are doing that the agents feels it and transported into some other passenger’s mind and converting them into agents. Then there are some action packed few minutes until both detective and Trinity finds a cover. Then an agent tries to possess the body of detective as he is still plugged into matrix. Realizing there is no option Trinity shoots detective to prevent agent possessing his body. During next couple of seconds remaining before agents arrive detective set up a trap while Trinity escapes. The story comes to an end as the agents get trapped in detective’s trap and the detective pointing a gun to them saying “A case to end all cases…..”.

A detective story has a unique charisma that attracts people even who are not fans of matrix because of it’s artistic approach. using black and white only except in last few shots where a bright flame of a cigarette is shown in colour add a strange form of elegance to the whole story. In overall it’s a great story to get your minds off from very serious philosophical aspects of matrix.

Matriculated

Matriculated20

Matriculated is the final story in Animatrix and the most interesting one in my opinion. It takes the concept of simulated reality to a whole new level.What happens if we use a simulated world to trick a robot? What will a robot would do if it is given a choice? Is there a difference between the reality we perceive and the one robots perceive? These are some of the concepts discussed in Matriculated.

Matriculated tells the story of a group of resistance fighters who lives on surface of earth and fight against machines. The main strategy of them is to convert the machines those who are captured and use them for fight against machines. Their purpose is to give robots a choice rather just capturing and reprogramming it to obey them. The story begins with  A girl name Alexa looking at an empty sea. She has a monkey like creature with her to watch the surroundings. Eventually she notice two machines are approaching and she began to trick them into a trap. Their hope was to capture those robots and convert them. However after a fight with alexa and another converted robot only one robot survives and the humans get ready to convert the remaining one.In there the most important dialogue in the story can be seen between Alexa and Nonaka, the scientist who is behind this method. I would like to copy the whole dialogue straight away as it saves me a lot of time in explaining. Dialogue was retrieved by :here

Alexa: Will it…? Do you think it will convert?
Nonaka: To convert is its choice to make.
Alexa: Do you think we ought to reprogram it?
Nonaka: No. We can’t make slaves of them.
Alexa: Because that would be simpler.
Nonaka: We won’t beat the machines by making them our slaves. Better to let them join us by choice.
Alexa: Make them believe the right choice is the one we want.
Nonaka: All right. Yes, machines are tools. They’re made to be used. It’s their nature.
Alexa: To be slaves.
Nonaka: That’s why we show them a better world, why they convert.
Alexa: But that world we show them isn’t real.
Nonaka: It doesn’t matter.
Alexa: I’m afraid they’ll figure out that we’ve made up the thing in our heads.
Nonaka: They can’t tell the difference. To an artificial mind, all reality is virtual. How do they know that the real world isn’t just another simulation? How do you?
Alexa: I know I’ m not dreaming now because I know what its like being in a dream.
Nonaka: So dreaming lets you know that reality exists?
Alexa: No. Just that my mind exists. I don’t know about the rest.                  .

The conversion process  is a complex process that designed to show robots about the humanity how good is to be a human and give them a feel of having an identity (self -awareness) to itself. In order to do that every one in the lab connects themselves into a machine which simulates the whole scene. The whole process gives a false impression to robot about it is having a choice but as Nonaka said to an artificial mind , all reality is virtual and they can’t distinguish between the real and illustrated one. Therefore Nonaka make sure the robot will eventually chose to join them not refuse it. Eventually the robot joins them as anticipated and at this time a group of another robots attacks them who were following the previous two robots. Then the usual fight between man and robots begins and this time Nonaka uses few other converted robots in fight, inevitably both parties get critically damaged leaving almost all of them dead and destroyed. The converted robot is the only thing that survives. He then see Alexa, the girl who brought him here lying unconscious on floor. He then connects Alexa and itself to the conversion machine again to enter the simulation program. Alexa was able to gain consciousness  again but get terrified to see that no other had survived and the robot has become a being with a consciousness and has grown a sort of affection towards her. She rejects this as she knows this is not real (but respect to the robot this is the simulation is his reality.) she collapses and robot remains. The story ends showing us the robot is waiting near to the sea looking at it like it is expecting someone.

The most interesting thing about Matriculated is how is adopts the concepts in Matrix and create a totally new dimension to look at the same thing. Choice is the core element in matrix. Inside the matrix it gives the person a false impression of free will. According to The Architect he created the first matrix as a Utopia but human mind easily recognized it as an illusion and rejected it finally he came up with the idea of choice (free will) with the help of Oracle. He was able to create a system where 99% of population accept the false reality, only 1% will always reject it which is something inevitable in a world where free will is practiced. Although this seems to be the case Architect make sure that every entity will eventually make the choice that is required by the system in order to keep the balance. Even the fate of The One was not something exceptional to this, When Neo met The Architect he tells Neo that there were predecessors (5 in total) and all of them inevitably chosen to enter the source and reload Matrix as they found saving human race was far more important than anything else. but to the surprise of Architect (or not) Neo chooses to Save his girlfriend Trinity and rejects to reload the matrix putting both humans and machines in danger. But we all know Neo eventually agrees to reload Matrix (in Revolution). This illustrates the true nature of choice in matrix. As in Matriculated choice is not something unbiased. Nonaka set the simulation in a way that is favorable to them while in matrix The Architect make it favorable to the existence of Matrix.

Matriculated:

Nonaka: We won’t beat the machines by making them our slaves. Better to let them join us by choice.
Alexa: Make them believe the right choice is the one we want.
Nonaka: All right. Yes, machines are tools. They’re made to be used. It’s their nature.
Alexa: To be slaves.
Nonaka: That’s why we show them a better world, why they convert.

The Matrix:Reloaded 

“Architect: Please. As I was saying, she stumbled upon a solution whereby nearly 99% of all test subjects accepted the program, as long as they were given a choice…even if they were only aware of the choice at a near unconscious level. While this answer functioned, it was obviously fundamentally flawed, thus creating the otherwise contradictory systemic anomaly, that if left unchecked might threaten the system itself. Ergo those that refused the program, while a minority, if unchecked would constitute an escalating probability of disaster.”

Next most interesting thing discussed in Matriculated is the aspect of reality.The way a human see the reality and how a robot (Artificial Intelligence ) sees the reality or is there any sense of discussing the aspect of reality with related to a robot at all.

Nonaka: They can’t tell the difference. To an artificial mind, all reality is virtual. How do they know that the real world isn’t just another simulation?How do you?

I strongly recommend you to watch this video about one of the most bizarre things you will ever hear about Matrix. What happens if the actual world where all the people in Zion and rest of the rebels live is another deeper level of Matrix made by The Architect in order to trick people those who reject the matrix all are familiar with? the idea may seem very unlikely but if you watch the video and think about the movie that idea might be the only explanation to some of the incidents happen in Matrix. This idea is clearly expressed in Matriculated as well when Nokana questions about how can we be sure if the reality we experience is the real one not another simulation. Alexa answer this by saying that since she already has experienced what is likely to be in  a simulation she knows what is real. But in my opinion this is not a sufficient answer to the question as there is no way to prove that they live in the real world or a simulated one with out experiencing them simultaneously. For example if you are having a Lucid dream (A dream where the person is aware that they are dreaming, ) you know it as you are aware that u exists in real world as well. your mind is experiencing two different realities simultaneously therefore you can compare both of them and know what is the dream and what is the reality. How ever you can’t do this just by experiencing only one. Like that there is no way that people of Zion would know that they are inside another layer of Matrix as there is no way to get information about outside of their reality. They just have to accept what they are experiencing at the moment is the actual reality. Please watch this video  to know how philosophers in the world tried to tackle this problem.

So I tried my best to explain my view about the animatrix movie and concepts that are associated with The Matrix Trilogy. These are not very easy to understand and more difficult to explain in words. Therefore I suggest that if you are really interested you should do your own study to understand these, As Neo said to the Kid “I didn’t save you, You saved yourself…”

 

 

 

 

 

 

 

 

 

 

How Electricity comes to you

Have you ever wondered how the electricity being generated and transmitted to your home? It might be easier to switch on a light bulb and at that instance the bulb light up like the energy required to light up the bulb has always being there  in some sort of a storage. But there is a good chance that the amount of energy that required to light up that bulb was generated by a power plant hundreds of kilometres away from your house and it got transmitted to you by electricity lines spans for hundreds of kilometres unless you have some sort of generating method like solar, wind or natural gas installed at your home premises. Electrical utility has become one of the most sophisticated and critical industries in the world due to the ever increasing demand for energy and the exponential growth in use of electronic devices in day to day activities. In my post today I am hoping to give you a little insight about the concepts used in electrical power engineering.

I’m pretty sure all of you have heard of things like voltage, current, Power, AC, DC, resistance and impedance. Most of us learn these at school and unless you peruse a career related to electrical engineering you might not have more complete idea about these concepts. Therefore I would like to talk about some of these in this post.

Electricity is basically the flow of charged particles. It can be positive or negative but due to the atomic structure of matter electrons are the ones that contributes to electricity most of the time. An electrical circuit is a closed loop that electrons flow from a higher voltage to a lower voltage doing work (releasing energy) on it’s way. This is not always the case but as long as there is a voltage potential difference between two points in space there is a possibility that a current will flow.

Voltage (V)

Voltage can be described as the potential difference between two points in an electric field. An electric field is similar to a gravitational field that occurs due to a presence of a mass. An electrical filed is caused by a charged particle. Voltage is just how we measure the amount of work being done when another charged particle being moved from one point in space to another point in space where there is a difference in electric filed. Although this explanation gives an insight on voltage this definition is not very useful when we are dealing with practical electrical engineering. In electrical engineering voltage is considered as an electromotive force that exists due to a voltage source like a battery or a generator.

There is one equation in electrical power engineering that is being used more often than any other equation. It is . In here P stands for the power being consumed/transmitted to an equipment. V stands for voltage at it’s terminal and I stands for current. If we want to transfer more power there are two ways to do so, by increasing voltage or current. If the power is kept at a constant value, the product of V and I is a constant. Therefore when voltage is raised current will go down and opposite is also true.

In Power transmission high voltages are preferred since using high voltages reduce the losses in occur in transmission lines. In Western Australia 132kV and 330kV voltage levels are used in transmission. But in HDVC transmission (High voltage DC) 800kV is also used. But when high voltages are being used safety becomes a major issue. But using higher voltages allows network operators to transfer more power over longer distances while minimising losses. Minimising losses in transmission is a major concern in power engineering. The power transfer happens in mega Watt scale (MW) therefore losses occur in transmission lines are also in MW scale. Engineers carefully design transmission lines, transformers and other equipment used in power transfer in order to mitigate this. The following diagram shows the different voltage levels that are being used to supply power from power plants to consumers. These voltage level could vary in different countries.

electric_grid

Image retrieved from https://anjungsainssmkss.files.wordpress.com/2011/07/electric_grid.gif

Current (I)

Current in a conductor is the amount of charged particles passing through a surface which is perpendicular to the direction of the flow measured in unit time. It can be expressed mathematically as I=Q/t  where Q is amount of charged particles and t is time interval. You might think that when you plug an electrical apparatus to a port and switched on, the electrons that are in one end of the circuit will suddenly travel to the other end but what actually happens is that electrons are being pushed towards the positive end of the circuit under the influence of voltage. It’s much more like a traffic congestion where each vehicle will move very slowly but overall the traffic keeps going. The speed of an electron in a conductor is very small. This is called drift velocity of an electron (particle) caused by an electric field (difference in voltage).

Losses in a transmission line are caused by movement of electrons. The losses in a conductor can be modelled mathematically by P(losses)= (I*I)*R  . I is the current flows through the conductor and R is the resistance of the conductor. So it obvious that if the current gets doubled in a line the losses will be increased by 4 times. This loss of electrical power will be dissipated as heat and will cause more troubles if it’s going to exceed the thermal capabilities of that line. Therefore network operators do their best to keep the amount of current being sent in a line at minimum. According to  the current required to deliver the same amount of power will get increased if the voltage gets dropped. Therefore it’s very important to maintain the voltage levels at desired level. Uncontrolled voltage drops in an electricity networks can lead to a blackout which will have very bad outcomes.

Power(W)

When electrical engineers think about power it’s a bit different than the conventional power that most of us are familiar with. Most of us are familiar with Active Power which will be converted into other forms of energy like mechanical, heat or light. In electrical power engineering we use apparent power in almost all calculations. Apparent power consists of active power and reactive power. As I mentioned active power is the type which will be converted into useful energy. Reactive power is the power consumed by the network itself in order to keep it running. The following figure shows the relationship between Apparent, active and reactive power.

SOLARPRO 7.4, JUNE & JULY 2014

 

 

Image retrieved from http://solarprofessional.com/articles/design-installation/reactive-power-primer

The ratio between Reactive Power and Real Power is called true Power Factor of a system. Power factor angle is normally defined as the ratio between Apparent Power and Active Power. Cos(θ)=P/S

The power factor of an equipment will determine how much active power it will consume. For industrial loads power factor must be close to 1 (about 0.9) and utilities penalise the customers who don’t correct their power factor according to the specifications since less power factor means utilities have to supply more reactive power to deliver the same amount of active power. This cause lines to get overloaded.

Although Reactive Power may look like a by-product of generation actually it’s very important to keep the amount of reactive power in the network at a desired level. Voltage at a busbar is dependent on amount of reactive power available and failure to keep it at constant level will cause voltage instability problems in network. If the voltage levels get too low this will has a cascading effect over the network and will cause a blackout. Reactive Power is used to change the magnetic or electric fields of electrical equipment in network. Motors need reactive power to produce magnetic fields inside their stators. Reactive power is generated due to the phase difference between voltage and current in an equipment.   S=√3*V*I Gives you the apparent power consumed or produced. All these quantities are vectors therefore they have both a magnitude and a direction. The following graphic demonstrate how apparent power being used in power transmission.

pic

Image retrieved from http://electrical-engineering-portal.com/reactive-power-and-compensation-calculation-basics

It’s obvious in order to transfer more active power using the same line utilities have to reduce the amount of reactive power being transferred. Building new infrastructures like transmission lines is a capital cost to network provider and that is not their first option. Instead of building more lines to transfer power, a technique called reactive power compensation being used nowadays. This method is a very cost-effective, practicable way to supply reactive power. Capacitor banks are used to generate reactive power closer to where it’s being consumed. This approach will reduce amount of reactive power being transferred to site and reactive losses in network overall. Therefore network operator can deliver more active power to customer. And also reactive power compensation helps to mitigate line overloading. Capacitor banks are used in in compensation. Capacitors are capable of supplying reactive power to network.

thNPK6Y0TM.jpg

Image retrieved from http//:electrical-engineering-portal.com

As shown in the diagram a portion of reactive power will be supplied by grid and the rest of the reactive power will be supplied by shunt capacitor.  Qc=P(tanφ1-tanφ2) Equation gives the capacity of the capacitor required.

2.jpg

Image retrieved from http://electrical-engineering-portal.com

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

The Animatrix-The movie that explains why there is no spoon-Part 1

If you are a true fan of The Matrix trilogy (not the people who follows the Gothic culture the movie illustrates or a person who is fascinated by the fighting scenes or slow-motion stunts) but  one who is really fascinated by the philosophy of the movie based on then you must have seen the movie already. If not the best thing to do is to stop reading this article and find the Animatrix movie and watch it first. The Animatrix is a collection of 9 animated short film collection based on the trilogy.  The Wachowski brothers were involved in making The Animatrix and 4 of the stories were written by themselves. Rest of the stories were written by the director Shinichiro Watanabe. Some of the stories are related to the Trilogy but the main purpose of the movie was to give the fans more insight into the philosophy of the movie. In my opinion these 9 stories are better than the last 2 movies since these are more focused on giving audience a different insight into the world of Matrix while the last two films of Matrix trilogy are more focused on just the battle between man and machine world. Personally I love watching matrix movies again and again to grasp more philosophical aspects I might have missed. Even the narrative techniques that are used in these short movies are different and unique to each other. For example The first short movie “Final fight of Osiris ” is produced by using CGI and very rich in graphics but not much in story itself but the short movie “Kid’s story” looks like hand drawn and a bit messy but has a strong root in philosophy of matrix.  Both these films are related to the original trilogy.

 

  1. Final fight of the Osiris

final-flight

This short film was written by Wachowski brothers and directed by Andy Jones. The story of this film is directly connected to Matrix reloaded. It uses high tech 3D animation and lot of people appreciated the hard work of crew to portrait high quality of even the smallest detail of human figures. The movie starts between a simulator fight between Thadeus, Captain of the ship Osiris and Jue, a crew member in Osiris. When they are fighting in simulator, they had to stop it due presence of machines on their way. They see an army of sentinel army with huge drilling machines. Soon Thadeus realises these sentinel army is on it’s way to enter Zion and destroy the only human city that survived from machines. There wasn’t no time to return to Zion and warn so they decide to send zion a message and Jue volunteers to enter to matrix and send it. Eventually she was able to deliver the message while crew of Osiris fight hard to buy her more time. Eventually sentinels destroy the ship and every one on ship die.  In movie reloaded we can see rebels were able to get the information sent by Osiris.

There’s not much to talk about this film in depth but the quality of animation and the effort taken by animation crew to produce such an outstanding short movie should be appreciated.

2.The Second Renaissance (Part 1 and 2)

the_second_renaissance__man_vs_machines_by_ryanonicle-d8al13n

These two short films were written by Wachowskis and directed by Mahiro Maeda. Although part 1 and 2 are considered as two short films in movie part 2 is just a continuation of part 1 .Therefore it’s easier to talk both of them combined. The second Renaissance tells the genesis of the matrix and the behind story of long lasting human machine war. The story is told by on the perspective of a 3rd person and this gives the audience an unbiased view of what happened. In my opinion watching this is essential part in order to understand Matrix movie. It will enrich your experience.

According to the narrator human race succeed in creating AI (Artificial Intelligence) during 21st century. Humans become the master of the robots as anticipated and as a result will start to be dependent more and more on robot as time pass by. According to the narrator no one knew when exactly machines became self-aware but a Robot named B1-66ER killed it’s master because he was afraid that his master will destroy him and replace him with a new model. Humans were shocked by this and immediately decides to destroy the whole robot population. After a robot holocaust robot retreated to establish their own nation named “01”. Robot leaders were able to establish trade once again with humans and this eventually make robot economy a stronger one than humans. As a result humans put economic sanctions and eventually this leads to a war between human and machine. Long story short, Machines win the war despite humans try to cut the main power source for robots, sun light by covering whole sky with dark smoke. As a result of this robots turn into a more reliable power source and unfortunately the power source happens to be humans. They start to construct huge power plants that they can use human body energy to produce electricity. In order to keep human minds under control they comes up with a simulated world called matrix.

The story looks more like a history lesson but I love the way it narrated. It uses a 3rd person’s perspective into the narration makes story unbiased. Even though second renaissance is about inception of matrix, I think it illustrates the deep connection we always had with the machines we made. I believe it’s not a completely wrong to say machines (tools) made man instead of saying man made machines. Even now we can’t think about living a single day without using a single tool.  This short film never illustrate machines or humans are the culprits but rather shows the reasoning for their actions and the consequences. Besides this the treatment of robots symbolizes the treatment of salves in past. It shows how bad people are resolving problems when they are not thinking clearly.

3.Kid’s story

anime_gallery_kids_3l

This story is my favorite due to it’s very unique art style. It’s almost like the characters are alive. Besides this the story itself is very interesting.

The story is about a boy name Karl Popper who always felt something is not ok with the world he lives. One day he saw he is falling from a building in a dream and wakes up. He sat down in front of the computer with a confused mind and start to chat with someone in a chat room. Karl questions about the feelings he is having and stranger gives strange answers and suddenly he disappears. That day at school he suddenly get phone call from Neo. Neo warns Karl that agents are coming for Karl. Karl see people wearing black suits getting off from car through a window Karl believe him and flee from them. Then he climbs up to the roof top of the building.  When Karl climbs up there he see agents are waiting for them. He realises there is no way to escape he stats to leaning back while holding onto the rails. Then he recalls the strange dream he had. His dream was that he is jumping off the building roof. He mutters “Neo I believe in you, I knew it wasn’t a dream” as he letting go of the railing. He falls to the ground below as screen gets black.

Then we see his teacher and few other people attend his funeral and talks about how Karl was couldn’t bear the reality and tried to escape. The scene comes to an end as the teacher says to himself while looking at the sky that there is no doubt Karl is in a another place now.

Then we see a room looks like some sort of room filled with wires and soon we start to hear voices that can be recognized as Neo and trinity. They are talking about self-substantiation of a person and how amazing it is. Then we start to hear the voice of Karl and it shows he is the person who was self-substantiated. Karl thank to Neo for saving him from but Neo explained that no one saved him but himself and the film comes to an end with a shot of Karl’s computer screen that shows Neo’s reply to a question.

Karl>“Who are you? Am I alone?”

Neo> “You are not alone…”

Kid’s story is my favorite not just because of how cool is it’s graphic but how deep it’s philosophical roots are. Karl represents people who are curious world around them. Their way of thinking is different than others and as a result they come to know the truth about their world and themselves. This is symbolized by self-substantiation of Karl. In matrix self-substantiation is almost impossible. According to matrix story only people are very exceptional are the people who can free themselves. Others need help from outside. Even Neo. There is no one who can help with this journey for salvation. You have to take responsibility of saving yourself. That’s what neo explained to Karl by saying “you saved yourself”. This concept is very similar to teachings in Buddhism. There are teachers who can guide you to nirvana (enlightenment, understanding the true nature of nature) but it’s you who is going to go along that path and teach yourself. It can be achieved only by struggling with yourself coming to realize the illusion of self.  (By realizing there is no spoon!!).  Kid’s story borrows lots of concepts from Buddhism (eastern culture) but it has done justice to it by presenting them in an understandable way for people who raised in western culture. For me Kid’s story is more than just a animation film. It’s a portrait of what of true nature of our world.

4.Program

the-animatrix-program

The movie starts with two people fighting in a simulation wearing body armors like Japanese warriors. We can understand the man and woman are having a relationship. After a heavy fight, Duo, the male fighter revels that he is going back to matrix and invites her to join as well. But she refuses and tries to get away from him. They keep fighting and running trying to justify their choices. Duo justifies his decision to leave real world and plugging back into matrix by saying “I’ve come to my senses” and “What real doesn’t matter .What’s important is how we live our lives. “ She refuses his invitation by saying since they know the truth, they won’t be able to live in matrix any more. Eventually the simulation program comes to an end when girl kills Duo and wakes up in their ship in real world. Duo is standing right next to her trying to calm her down by explaining that what happened is just a part of a training and a test and she has scored highest score in judgment technique and concentration areas. Then she punch to his face to release her anger and takes lift to her room. Film closes showing her exhausted face in dark.

This film questions about how faithful are we to the choices we make. This is something even matrix movies are also talk about. In Matrix movie Cypher becomes fed up with choosing the rebel life over matrix and wants to go into matrix once again even he knows everything in matrix is just an illusion. He betrays his crew to goes back to matrix but die as a traitor. Choices are a really important aspect in matrix. Choices is what at the heart of matrix and according to the architect it’s essential to keep the balance in matrix.

I will bring you the rest of the stories in my next post. Watch the following videos if you want to know about simulated universes concept and how far are we from creating a one .

Simulated universe

Rebooting the Cosmos: Is the Universe the Ultimate Computer?

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.







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 tasks.by 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.

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.