Wednesday, October 12, 2011

A taste of wonder

One thing that I miss from my childhood is having a regular experience with wonder.  Being filled with awe and marvelling at something is not as common place as it once was.  It does happen from time to time however and over the weekend I experienced it again.

My dad is on the verge of retiring and so together with my siblings, we purchased an iPad for him.  Not having used an iPad, it was new for me, and the device was fascinating.  Fascinating, but not wonder inducing.

That changed a few hours later when my brother-in-law installed an astronomy app and we went outside to use it.  Placing the iPad above our heads, the app displayed and identified all the celestial objects that we could see.  Moving the iPad around caused the display to change to reflect the portion of the sky immediately behind the device.  It seemed almost magical.

To locate an object in the sky that was displayed on the iPad, all you had to do was move the iPad around the sky until the object was positioned at the center of the iPad.  Then low and behold if you then moved the iPad out of the way without moving your eyes, you were looking directly at it. 

Wow, I marvelled, how cool was that! 

I thought back to elementary school when I received a telescope one Christmas, and thought to myself that if the iPad had been available then, I might have pursued a different career.  Those frustrating few time that I actually tried to find anything in the sky back then would never have diminished my enjoyment of star gazing.

Being an engineer, it didn’t take too long for me to figure out how the app worked, and wouldn’t you know it, once I figured it out the wonder diminished.  It wasn’t magical after all.

Wednesday, August 31, 2011

Tools of the trade

Warning: this will be another one of my technical posts.

As an electrical/firmware engineer, there are a number of tools that I use on a daily basis that are indispensible to my trade.  Today I wanted to post a quick list of my favourites, with perhaps future posts going into more detail.

  1. Numero uno has to be Vim, otherwise know as “the best text editor in the world”.  Now I have only been using Vim for a little more than a year, but  it has changed my life.  Ok, perhaps that is going a little overboard, but quite honestly, if you have a year of your life to devote to learning a text editor, there is no better candidate than Vim.  If you have tried it and just don’t grok it, then read the first answer to the following question.  What is my favourite command?  “gg=G”.  Just awesome.
  2. Number two is Mercurial.  This tool is for revision control, and it absolutely beats the pants of the “official tool” I am supposed to use.  Revision control software allows you to take “snapshots” of your code so that at any time in the future you can recreate anything you have done in the past.
    For example I can type “hg update v1.1” at a command line and instantly all the files in my coding product are exactly as they were when we released version 1.1 of the software.  Type “hg update v2.0” and again all the files are updated to as they were when version 2.0 was released. 
    Mercurial is one of the new breed of revision control tools known as “distributed version control” which is in contrast to the previous breed known as “centralized version control”.  Again like with Vim, I have drunk the proverbial kool-aid.  I have been won over to this new paradigm.
  3. I will end on number 3 which is Python.  No not the animal; Python, is a programming language, named after comedy troupe Monty Python.  Python is a member of a class of languages often referred to as scripting languages. 
    On a day to day basis, I would estimate that more than 90% of my programming is done in a completely different language called C, with perhaps 10% or less done in Python.  Notwithstanding, the more I learn about Python, the more I am blown away with the simple elegance and the sheer power of the language. 
    Having a scripting language in my tool belt has made me more productive and honestly opened my eyes to what is possible.  For example after learning Python, I was able to write a utility in about 150 lines of code that analysed the output of my C compiler, calculated the execution time of each assembly instruction and then produced an annotated file which contained timing information for each line of assembly, each line of C, and each C function.  Fantastic information to know when you are trying to understand the efficiency of your compiler and optimize the code to improve performance. 
    Ignoring the fact that the equivalent utility written in C would have taken probably 2000 lines of code, my mind simply wouldn’t have known where to begin using C, while with Python a relative novice was able to produce the utility in only a couple of days.  Incredible stuff.

Monday, August 29, 2011

On Happiness

Five blog entries, in five days; so what was it all about.  As I mentioned last Monday, the experiment comes from a book that I am reading.  The book is called 59 seconds:  think a little, change a lot.  A couple of weeks ago I was reading an interesting blog entry.  The blog’s author highly recommended this book and I was convinced to purchase it.

Chapter one is called happiness, and it highlights a number of studies done on happiness and comes to a number of conclusions.   The first being that writing is far more effective than talking when it comes to working through traumatic events in a persons life.  Furthermore other studies found that the act of writing can have significant benefits to promoting everyday happiness in a person’s life.  Hence my week long homework assignment.

According to the book the results of this exercise should be a fairly quick change in mood and happiness that may last for months.  Furthermore, If the feeling wears off the author instructs the reader to repeat the exercise as needed. 

So how do I feel?

Happy is certainly a word I could use.  I am by no means unhappy, however in general I am a happy person.  I really started the exercise from a position of general happiness, so I guess a more important measure would be relative happiness compared to a week ago.  So how do I feel relative to last week?

Again it is not an easy question to answer.  I can’t say that I am tremendously more happy, but in no respects am I less happy.  Having a scientific mind I would love to say that I have achieved a 54% increase in my level of happiness, but the subjective nature of feelings prevents me from being certain.  Overall I think my happiness has increased slightly. 

As far as the exercises went, I enjoyed the process of putting my thoughts on paper and they will be an interesting record for me to look back on in the days ahead.  I think that the experiment would have been more conclusive, if I had started from a position of unhappiness, but frankly I really don’t want to find out.

The key takeaway for me is that it is good to incorporate words of gratitude and affection in my writing.  Something I will continue to try and do.

The books discussion on happiness doesn't end there however.  Based on other studies, the book concludes the following:

  1. Buying experiences and not goods promotes happiness.
  2. Giving  promotes happiness.
  3. Smiling promotes happiness.
  4. Intentional change, rather than circumstantial change will promote happiness.

Friday, August 26, 2011

Week in review

Day 5 – think back over the past week and make note of three things that went really well for you

  1. This week we handed over a software delivery to a customer, intending to fix a number of problems for them.  Immediately after deployment, out of seemingly nowhere a new bug was discovered that was critical enough that I had the unfortunate task of telling the customer that we would have to pull back the new software.  Not an enjoyable task, to admit your team screwed up.  What did go well is that after explaining the situation to the customer, they were incredibly understanding and didn’t seem to hold it against us.  I think it helped that we didn’t attempt to pass the buck, but we admitted up to our mistake and promised to make it right.  What was more amazing is that they were thanking me for how quickly I was able to provide them an analysis of the situation.
  2. A few weeks back we sold our bicycle trailer and tandem tricycle.  Both products were excellent and I couldn’t more highly recommend them, however the girls had simply outgrown them.  For a replacement we purchased the Weehoo bicycle trailer and it came in on Wednesday.  I wasn’t sure if the girls would like it, but once they saw it, their smiles of delight gave me the answer I was looking for.  We have been out twice now for rides, with one girl in the trailer and one girl in the Wee-ride front mounted child carrier.  I can see us making many lasting memories with this trailer in the years ahead.  Just today though I realized that I should have purchased a second hitch so that the trailer could be attached to either of our adult bicycles.  The trailer had been a special order so I was kicking myself for not ordering a second hitch when I placed the initial order.  Anyways when I called the bicycle store I was amazed to find that they carried extra hitches so I was able to pick it up today.
  3. On Wednesday night a wild storm rolled through the region.  There were tornado warnings issued, so I used it as a pretext to have a campout in basement with the girls.  The girls had a thoroughly good time, seemingly oblivious to the thunder and lightning.  In fact they are looking forward to the next time we can sleep in the basement.  Go figure.

Thursday, August 25, 2011

To my parents

Day 4 – write a letter to someone who has impacted your life and tell them how important they are to you

Dear Mom and Dad,

The medium of the written word, is hardly expressive enough to accurately convey the love and respect that I have for you both.  I hope that my actions and spoken words to you over the years will substantiate the words that I write today.

Dad, thank you for always loving and supporting me through every endeavour.  Thank you for demonstrating to me that the measure of a man is not in what they do, but in who they impact for eternity.  It is because of you that I know my heavenly Father is completely faithful, unconditionally loving, and abundantly good.  It is because of you that I have never second guessed my decision to follow Christ. 

You taught me how to be warm and friendly with strangers.  You taught me to have concern for the needy, the sick and the elderly.  You taught me to appreciate life, and to not fear death.  You taught me to forgive, before resentment and bitterness could set in.  You taught me that material things are not worth clinging to.  You taught me to be content.

Thank you for taking me on bicycle rides as  a child.  Thank you for taking the time to answer every deep question I posed to you.  Thank you for involving me in the work of the church.  Thank you for guiding me.

Mom, your love and support is equally appreciated.  Your listening ear and warm heart gave me the confidence to grow into the man I have become.  It is because of you that I know that God is never too busy to hear my prayers, and that no concern it too trite.  You were and continue to be my biggest advocate.

You taught me the value of a dollar and the importance of being a good steward of my resources.  You taught me to be generous with those resources and to always give to the work of the Lord first.  You taught me to become independent through the many essential life skills you taught me.  Any success that I have in life can in large part be attributed to you.

Thank you for your godly discipline.  Thank you for your advice through the years.  Thank you for giving me the nudging I needed from time to time to get things done.  Thank you for teaching me that I can do anything if I try.

Mom and Dad, in short thank you for you prayers and love.  I am blessed beyond measure to have you in my life.

Love Andrew

Wednesday, August 24, 2011

Futurama

Day 3 – write about your life in the future, imagining everything has gone well

August 24, 2046:

Hard to believe that my daughters turn 40 this year.  Where has the time gone!  Just yesterday they were pint sized bundles of joy that I could swing up onto my shoulders  without so much as a second thought.  How quickly they grow up.

To say I am proud of them would be putting it mildly.  I am overwhelmed with gratitude that God saw fit to bring them into my life, and give me the awesome privilege of raising them.  Their character, their beauty, their compassionate spirits are all proof positive that the hand of God is on their lives.  May He continue to guide their paths as they raise their children in the nurture and admonition of the Lord, and may they always walk in the favour of their God.

My wife is the glue that binds this family together.  She has faithfully been my spouse, my advocate and my best friend for over 48 years.  Nevertheless, I can honestly say the best years are still ahead.  Through every valley and over every obstacle, she has been the source of so much wise council and insight that I have never had to regret a decision we have made together.  My love for her continues to grow.

As I look back on my life thus far, I am thankful for each relationship that has enriched my life.  My circle of friends has always been wider than it has been deep, but the few that I can call close friends have been the source of much encouragement over the years.

It is fascinating to think about the journey that God has taken me on.  I would never have thought it possible that I would be where I am today.  My vocation may have been as a software engineer, but my calling turned out to be abundantly more.  I am thankful that I learned to simply trust and obey.  Fighting against the purposes of the Lord is a loosing proposition every time.

I have so much to be thankful for in this life, the Lord has been good.  Putting aside any material possessions that I may have acquired, I have been blessed beyond measure.  Blessed in my relationships, blessed in my vocation, blessed in my calling and blessed in my spirit.  The past has been good, but the future is full of hope and promise.

Tuesday, August 23, 2011

The blessing

Day 2 – write about one of the most wonderful experiences in your life

Date:  Sometime in July 1987, age 11.

Setting:  The parlour of my grandparents farmhouse, just outside the town of Coagh, Northern Ireland.

Occasion:  A blessing from my grandfather.

During the summer before grade 7, our family took a 6 week summer vacation to the UK.  The first 3 weeks were spent in Northern Ireland visiting my Dad’s family and the next 3 weeks were spent in England visiting my Mom’s family.  Shortly before leaving Ireland, my dad arranged to have each of his children blessed by my grandfather.

I remember hanging out in the family room waiting for my turn, while my older brother was in the parlour with granddad.  When it was my turn, I was called into the parlour with granddad and I remember him gently placing his hands on my head while he prayed a prayer of blessing over me.  I don’t remember the words, but still today I can remember the sound of his voice as he prayed for me. 

This experience; that of receiving a blessing from my paternal grandfather left an indelible mark on my life; the impact of which will only be fully known in eternity.

Monday, August 22, 2011

An experiment

Having somewhat of a scientific disposition, I have decided to conduct an experiment. 

What is the experiment? 

It is taken from a book that I am currently reading and for each of the next five days I have to follow a model when writing on this blog.  After the five days I hope to have some additional insights to share, based on the results of this experiment.

Day 1 – write about 3 things I am thankful for:

  1. I am grateful for my wife of 13 years.  Yesterday was my anniversary.  I have never once regretted the decision to tie the knot with the one I love.  The union of our lives proves that the whole is so much greater that the sum of our individual parts.
  2. I appreciate the time that I have been given here on earth.  The news of the day reminded me again that life is short and each day is a treasure.
  3. I am thankful for the video I just came across while reading a blog post.  It brought a smile to my face and made me realize the power a kind word has to brighten a day.

 

Tuesday, August 09, 2011

Forever Family Day #4

It was this day four years ago that I received into my arms a baby girl.  At the same moment my wife received into her arms another baby girl.  In an instant a family was born.

My daughters are the source of so much joy and happiness in my life.  They are gifts from the Lord and I cherish them.  I love them more than life itself.

In the book of Matthew, the bible says "if you love your son or daughter more than me, you are not worthy of being mine."

Difficult words.  Christ wants to be my first love; but is he?  Am I that committed?  It is hard to be sure living in Canada.  It is pretty easy to be a Christian here.  The situations that test my faith seem so insignificant in comparison to what others endure.

I am listening to a song by Keith Green as I write this.  A song called "I pledge my head to heaven".  The third verse goes like this.

    I pledge my son to heaven for the gospel.
    Though he's kicked, and beaten, ridiculed and scorned,
    I will teach him to rejoice, and lift a thankful praising voice,
    And to be like him who bore the nails and crown of thorns

What am I willing to endure for the sake of my faith in Jesus Christ?  And what is my life teaching my children about the Christian life?

Above all, I want my children to see me as faithful.  Faithful to God, faithful to their mother, and faithful to them.  I don’t think much more than that is required?  If I am an example of faithfulness to my children, it will go a long way to ensuring that they don't abandon their faith once the storms of life come their way.  And that is worth more to me than mere words can describe.

Tuesday, June 21, 2011

Thoughts on being a dad

I am forever grateful to God for the family he has given me. 

As each day passes I realise afresh how blessed I am to have a wonderful wife and and two incredible children by my side.  They bless me more than I can express.

In my opinion, I have the best family in the world, bar none.

Apparently I am not doing too bad myself in the dad department either.  This past Father’s Day I received notice that I was the best dad in the whole wide world, so my condolences go out to all runners up out there for snatching the title this year.

Now in the spirit of Father’s Day, let me recount some of the situations that make me realize just how wonderful being a dad really is.

  1. laughing, laughing, and laughing some more with my daughters
  2. bursting with pride at my daughters accomplishments
  3. hearing “I love you daddy, with all my heart” from my daughters
  4. carrying my daughters on my shoulders
  5. holding hands with my daughters
  6. cradling my daughters to comfort them
  7. getting a good night kiss from my daughters
  8. giving a nose rub to my daughters
  9. tickle fights with my daughters
  10. reading stories to my daughters
  11. playing wedding and marrying my daughters over and over again
  12. going for a bicycle ride with my daughters
  13. swimming with my daughters
  14. singing with my daughters
  15. grocery shopping with my daughters
  16. strawberry picking with my daughters
  17. camping with my daughters
  18. flying a kite with my daughters
  19. carrying my sleeping daughters off the school bus
  20. praying with my daughters

Wednesday, June 08, 2011

The human condition

Once again I have been reminded of the human condition. 

I was watching CNN a few days ago and Wolf Blitzer was interviewing a congressman about some purported indiscretion that had been made through his twitter account.  Honestly I didn’t give it much thought, I watched only a minute and the individual seemed quite genuinely shocked that someone had hacked into his account.  I had never heard of the politician before and truth be told the only thing I thought was “as a public figure you need to be more careful with your online accounts.”

You may be aware, but this past Monday the same politician admitted to being responsible for the lewd behaviour, and furthermore that it had been going on for some time with multiple recipients.

I really don’t want to dwell on the particulars of this case, but I want to make the observation that it proves once again that the human condition is inclined towards deceit, it is inclined towards lewdness and yes it is inclined towards evil. 

It is just so self-evident.

The day after these events unfolded, I heard one of my favourite songs on the radio.  Ponder the words with me.

It's a slow fade when you give yourself away
It's a slow fade when black and white have turned to gray
Thoughts invade, choices are made, a price will be paid
When you give yourself away
People never crumble in a day
Daddies never crumble in a day
Families never crumble in a day

The truth is that the the downfall of this politician didn’t begin at the keyboard of his computer last week, it began probably months or years earlier with a thought.  A thought that led to poor choices, poor choices that led to increasingly poorer choices, and finally a downward spiral into sin.

There I said it.  Sin.  For that is what it was. 

That is what it is; when we first deceive ourselves, and then deceive others.  All the while forgetting this; that we cannot deceive God.

Friday, April 22, 2011

Thoughts on Good Friday

Of all the holidays, Good Friday has to be the most significant for me.  As a Christian I take pleasure in knowing that popular culture hasn’t been able to rob the day of its meaning.  There are no images of fat men in red suits, or cute bunny rabbits to obscure the message of the day.  The day is uniquely Christian and to the believer tremendously powerful.

The only image is that of a saviour bleeding and dying on a cross so that I could be made righteous in the eyes of God.  As the bible says in 2 Corinthians 5:21 “For God made Jesus, who had never sinned, to be sin for us, that we might become the righteousness of God in Him”

The song "Amazing Love" describes it so well:

I am forgiven because He was forsaken,
I am accepted because He was condemned,
I am alive and well, His spirit is within me,
Because He died and rose again!
Amazing love, How can it be,
That You, my King, should die for me?

Yes that’s my King!

Sunday, March 06, 2011

Iron sharpening iron

Back at the end of November I mentioned that I planned to start a study group to work through the "The Truth Project" material.  Well back at the beginning of February it came to fruition. 

And so each Wednesday evening from 8:30-10:30 I am joined by 5 other young married men, who gather around my dinning room table to study the Christian worldview in detail.

So far we are about half way through the study and in that time we have looked at the following in detail:

- what is truth?
- what is our foundation for philosophy and ethics
- who is man and what is his need?
- who is God and how has he revealed himself?
- what is the evidence for God in creation

Heavy stuff, but I am so encouraged by the fact that everyone is genuinely engaged by the material.  Engaged I believe, because in their heart of hearts they understand the importance of these questions.  And specifically they know that what they believe the answers to be really does end up giving direction to their lives.

Take truth.  Do I believe that each person has to discover their personal truth?  Or do I believe in universal truths that apply regardless of time and place?

Take philosophy.  Do I believe that the universal truths (meaning, purpose, morality, destiny) can be discovered by examining the particulars of this world through scientific reasoning?  Or do I believe that the universal truths have been revealed by a benevolent creator and that they provide significance to the particulars of the created world.

Take ethics.  Do I believe there is an objective moral standard that I am to adhere to?  Or are things wrong because the majority of people have said that it is wrong?

Take man.  Do I believe that I am basically good?  Or do I recognize that I am naturally inclined towards evil?

Take God.  Do I believe that God is?  If so do I believe that God has revealed himself?  If so do I believe that God cares about my situation?  If so do I believe that God has done something about it?

Take creation.  Do I believe that I am but the end result of a purposeless evolutionary process?  Or do I believe that I am the result of an intelligent designer who has a purpose for my life?

I know what I believe, and furthermore; I believe that what I believe is really real.

Tuesday, February 22, 2011

Speaking my language

I spend the bulk of my day writing code.

I would hazard a guess that most people understand that a computer understands only one language, machine language, but I doubt that most people have ever been introduced to it or seen what it looks like.  Well let me introduce you.

Here is a small piece of code that my processor would understand

5,56,229,56,211,148,15,64,5,228,245,56

You will notice that it is simply a list of numbers where each number is between the values of 0 and 255.  Since the values are constrained to be less than 256, it means that this particular microcontroller is an 8-bit processor . 

You may know that most computers can be classified as either 8, 16, 32 or 64 bits.  What this classification means is simply how large the numbers in the list can be.  For 16 bit computers the numbers would range from 0 to 65535.  For a 32 bit computer the numbers would range from 0 to 4294967295.  Finally for a 64 bit computer the numbers would range from 0 to 18446744073709551615.

That is all well and good, but it is only a list of numbers, what does it mean?

Well this is where it can get complicated since every different type of processor interprets the numbers differently.  There are literally millions of different ways to understand what that list of numbers means.

So in order to decode the list you need to know two things.  One, what specific processor is this list of numbers encoded for and two where does the list begin.

The first requirement makes sense from what I have just told you, but why do you need to know where the beginning of the list is?

It isn’t a trick question.  Knowing where the list begins is important because each and every number in the list above can be classified as one of two different types.  The number could be an instruction to the computer, or the number could be data the computer is to use in a computation.

For example:  1+2

The numbers 1 and 2 in this case are data, the computer uses these numbers in the computation.

The + symbol is an instruction to the computer to add 1 and 2.

The problem is that the computer understands numbers, but the computer has no idea what a + symbol is.  So what are we to do?

Well the easiest thing is to encode the + symbol as a number.  For example we could give the + symbol the number 36.

Rewriting the above example so that the computer understands it we could write:

1,36,2

This would be wrong however.  The problem arise with how to know which numbers are data and which numbers are instructions.  Let’s rewrite it like this.

36,1 2

So now we know that instructions always come first and the data follows.  In this example it means ADD 1 with 2.  See how simple that was?

Going back to the purpose for this example we understand now why we need to know where the list begins, since the first number in the list will always be an instruction.  Furthermore each instruction always has a known amount of data associated with it  so we can calculate as we move down the list which numbers are instructions and which numbers are data.

Lets go back to my original example.

5,56,229,56,211,148,15,64,5,228,245,56

So the first thing we need to know is what processor these numbers are coded for.  I will give that to you.  It is for an Intel 8051 microcontroller.

Secondly based on the list as given we know that the list begins with the number 5 and that the first number is always an instruction.

So what do we do now?  Well here is where we need a little help from the processor's manual.  The manual will tell us what each instruction code means and how many numbers worth of data are used with it.  Let’s begin.

For now I will skip over the data bytes

5 = "inc direct", and it uses one byte of data, so skip the 56 in the list

229 = "mov a, direct", and it uses one byte of data, so skip the 56

211 = "setb c", and it uses no data

148 = "subb a, immediate", and it uses one byte of data, so skip the 15

64 = "jc relative", and it uses one byte of data, so skip the 5

228 = "clr a", and it uses no data

245 = "mov direct, a", and it uses one byte of data

Clear as mud I am sure.

Now we need to go one step deeper, what does “direct”, “immediate” and “relative” mean?

In order to understand these concepts we need to discuss addressing.

Let’s begin with memory.  We know that all computers have some amount of memory.  My microcontroller has 64KB of memory, but your computer at home probably has something more like 1GB of memory (refresher, 1GB = 1024 MB = 1024 KB = 1024 bytes). 

Now each byte of memory contains a number between 0 and 255.  So your computer at home with 1GB of memory contains 1,073,741,824 of these numbers.  That is a lot of numbers, so how do we find any particular number among all of those possibilities.

The answer is through its address.  Every single one of those numbers has a unique address (which is yet another number) through which we can retrieve the number.

So this is how a computer works.  You turn on the power and the processor reads from a known starting address (most likely 0), and interprets that number as an instruction.  Based on this instruction the next address may contain either data or the next instruction.  The computer continually keeps incrementing through each address, doing what the instructions ask it to do and manipulating the data it is given.

So back to the terms “direct”, “immediate” and “relative”.

Immediate is the easiest.  It simply means that the next number in the list is just a number and that the computer should do something with this number.

Direct means the next number in the list is an address.  The computer needs to read this address, then “dereference” the address to discover the number which resides at the memory location “pointed” to by the address and then do something with this number.

Finally relative means that the next number is a relative offset from the current address, and that the computer should interpret the next number as a signed number ranging from –128 through + 127.  The computer is then to compute a new address as follows:  current address = current address + relative offset.

So going back once more to our example

5,56 = inc 56 – increment the number at address 56

229,56 = mov a, 56 – move the number in memory at address 56 into the accumulator

211 = setb c – set the carry bit

148,15 = subb a, #15 – subtract 15 from the accumulator

64,5 = jc +5 – if the carry bit is set jump to address = current address + 5

228 = clr a – clear the accumulator / set to 0

245,56 = mov 56, a – move the accumulator into memory at address 56

Are we beginning to understand what is going on?

Almost, but there are just 2 more things you need to know, what is the accumulator and what is the carry bit.

The 8051 is referred to as an accumulator architecture.  In English this means that all operations on data has to occur in the accumulator (a special memory location within the processor).  That is why the code above copies data into the accumulator, does the subtraction on the accumulator and then copies the accumulator back out to memory. 

The 8051 is a fairly old processor (circa 1980) and this style of architecture was popular at that time.  More modern architectures are more efficient and reduce the amount of copying of data back and forth from memory.

The last new thing is the carry bit.  As its name implies the carry indicates if an addition caused a carry to occur.  Since each number can only range from 0-255 what happens if you add 2 numbers together and their sum is greater than 255.  Well the result would still only range from 0-255 but the carry bit would be set to indicate that a carry was done.

In our case we are doing a subtraction, so in opposite fashion we set the carry bit before the subtraction.  Then the carry bit will be cleared if the value is greater than 0.  If the result goes below 0 then the carry bit will remain set.

Different instructions can then make use of this bit and do different things.  In our case we skip the following instruction if the subtraction returned a positive result.

So now in summary this list of numbers:

5,56,229,56,211,148,15,64,5,228,245,56

can be interpreted to mean

inc 56 / mov a, 56 / setb c / subb a, #15 / jc +5 / clr a / mov 56, a

Which means – increment a value in memory, check to see if it is greater than 15, and if so reset the value back to 0.

Wasn’t that interesting!

Now for full disclosure, I didn’t write this code in machine language.  Very little code is done in machine language.  More often a language more akin to English is used and then a computer translates it into machine language.

For your pleasure here is the original source code that was translated into machine code for our example.

#define FIRST_LED_CODE   (0)

#define LAST_LED_CODE   (15)

led_code = led_code + 1;

if (led_code > LAST_LED_CODE)
{
    led_code = FIRST_LED_CODE;
}

A much nicer representation from a human perspective.  But as far as the computer is concerned it only ever knows:

5,56,229,56,211,148,15,64,5,228,245,56

Tuesday, February 15, 2011

The joys of engineering

This past month at work has been very rewarding.  We are at the initial prototype stage of development, and in many respects this is the most interesting stage.  I have some cool new toys to play with.

At the moment on my desk I have several circuit boards hooked up together communicating with my computer over a USB connection.  In addition I have 2 serial cables connected between these circuit boards and my computer. 

What I am doing is writing software for one of the circuit boards.  Actually I should use the term firmware, because at the end of the day, my code gets burned into an EEPROM (electrically erasable read only memory) chip which resides on the circuit board.

The situation is this.  On my PC I am running an application program.  This program talks to board A over a USB cable, which in turn talks to board B over a serial cable between them.  Board B is the one I am writing software for.

Currently I am writing the communications handler for board B.  This piece of software interprets the commands coming from board A, acts upon them, and then sends back a response.

Writing the software is in some respects the easy part.  Testing it can be much harder.  This is where another piece of software comes in called a debugger.  The debugger runs on my computer and allows me to examine the code that is running on one of the boards.  I can start and stop the code, view the contents of memory and generally interact with the software in such a way that I can understand what is going on.  Hence the reason for the 2 serial cables connect between my computer and the circuit boards. 

Why do I need two though since  I am only debugging the software on board B?

The reason is that board A’s software normally will send commands to board B about every 5ms, that is 200 commands a second.  That is well and good once the code for board B is working, but while testing the code, this is not desirable, I need to manually send commands back and forth between the two boards.

So even though I am not testing the software on board A, I need to use a debugger so that I can stop the code at will and only send commands to board B as I want them.

In summary I am using an application on my PC to send commands to board A via the USB cable.  I then have a debugger running the code on board A which acts upon these commands and subsequently sends commands over to board B, when I want them.  Finally I have the code under test running on board B using another debugger which acts upon the commands from board A and sends back responses, which subsequently get propagated back up to the application.

Which all together makes for a fun day at the office.

Sunday, February 06, 2011

How far we have come!

For those that remember, in October, I wrote a week long series on embedded programming.  Well I came across a video this week which I found fascinating.  It is from 1963, and in the video we learn of a new development in computer science called time-sharing which allows multiple users to use a computer simultaneously.

I found it interesting because what is described is essentially the first multitasking operating system.  That terminology isn’t used in the video, I believe the spokesperson calls the operating system a “supervisor” program which manages the memory requirements and resources for multiple users.

It’s a fascinating glimpse at history and it renews my awe with respect to how far we have come in the design of computers.

Wednesday, January 19, 2011

How would I respond?

Today my spirit was uplifted by the following newspaper article.

I encourage you to read it all, but the long and short of it is that notwithstanding being hit by a drunk driver, notwithstanding almost a year of rehab, and notwithstanding living in constant pain, Bruce Reid is a happy man.

He contains no bitterness towards the driver who hit him.  He holds no anger or malice for the events that transpired.  And he even believes that there is a greater purpose to be found in the horrific crash which almost cost him his life.

How can this be?  And if it had been me, how would I have responded?

You see, I lead a blessed life.  I have never known grief.  I have never known loss.  I have never known any real level of pain.  Furthermore I am healthy, I enjoy my work, and I love my family.  I am abundantly blessed.

But what if events transpired to change all of that.  What if tomorrow I was hit by a drunk.  How would I respond?

Well let’s take Bruce as a case study and examine why he responded the way he did. 

The following sentence says it all, “a Christian, he believes the crash wasn’t an accident.”

Ah, Bruce is a Christian.  Bruce therefore believes in God.  Bruce must even believe Romans 8:28 when it says, “and we know that to them that love God all things work together for good.”

Fundamentally this is a worldview question.  It is because Bruce views the world through the lens of a Christian worldview, that he can still be happy even after going through so much pain.  Let me explain.

Having a Christian worldview gives Bruce assurance that in comparison to eternity the events of this life are but a fleeting moment.  Having a Christian worldview also allows Bruce to understand that there is a bigger picture that only God can see, and subsequently there is a purpose in what happened to him.  And finally having a Christian worldview allows Bruce to know that no matter what he is going though God cares, and God understands, for He in the person of Jesus Christ endured much more than Bruce ever had or will have to endure.

So I hope you can see why it was that my spirit was uplifted as I read this article? 

For even though I have not experienced Bruce’s ordeal, I now have even more confidence that the faith I have chosen, and the worldview I ascribe to is the real deal.  To my mind there is no other explanation for the happiness and peace that Bruce and his wife are experiencing in the midst of their storm.

And how do I know that I am not just reading too much into that one line about Bruce being a Christian.  It is because I have had the pleasure of working with Bruce for the past 12 years.  And his life has been a testament of God’s grace and provision not just over this past year, but for the entire time that I have had the privilege of calling him a colleague and a friend.

Saturday, January 08, 2011

What would I have said?

Yesterday, my heart broke as I read the suicide note of a young man named Bill Zeller.  Twenty-seven years old, a talented programmer, and a Princeton grad student, but with an inner turmoil so great that he felt the only answer was to end his life,

He emailed this note to his friends early last Sunday morning and then he killed himself.  I can’t remember ever reading a suicide note before, but this one ended up being posted on tech blogs that I frequent so curiosity got the better of me and I decided to read it to find out why he had decided to end his life.

After reading it, I began to wonder what I would have said to him; had I known him, and had I known his intentions.  Considering he expressed resentment towards his parents because they were “fundamentalist” Christians who hated everything, I wonder if he would have given me the time of day.

Now I don’t know his parents so I am not going to comment on their faith, but the following two verses came to me as I read the Bill’s note.

From the book of Matthew Jesus says, “whoever causes one of these little ones who believe in me to sin, it would be better for him to have a great millstone fastened around his neck and to be drowned in the depth of the sea.”

Bill mentions that he was raped repeatedly as a child.  I would say to him that the guilty party will not go unpunished.  The bible repeatedly states that God is a God of justice, who hears the cries the neglected and abused.

And again from the book of Matthew Jesus says, “Judge not, that you be not judged. For with the judgment you pronounce you will be judged, and with the measure you use it will be measured to you.”

I would say to Bill that I have met a lot of judgemental Christians as well, but the words of Jesus are clear, leave it to God to judge, for he is God and we are not.  Don’t forsake Jesus because of what man has done, judge Jesus on his own merits.  He invites you to “taste and see that the Lord is good.”

Most importantly I would need to address the root of his turmoil.  The inner darkness as he calls it.

In the book of John Jesus says, “I am the light of the world. Whoever follows me will not walk in darkness, but will have the light of life.”

Now I admit that I have no way of understanding what Bill was experiencing, but I find it interesting that Bill referred to his struggle as one against darkness.  The bible also uses this terminology when it describes the epic battle between good and evil as a battle between light and darkness.

Thankfully the bible doesn’t leave us hopeless and in despair, for there is hope.  The way to combat darkness is by embracing the light.

Tuesday, December 21, 2010

Who then is God?

My previous discussions regarding my worldview were not exhaustive by any means.  In fact they really only answered one question, that being what is the nature of Man.   But there are just too many questions that are not answered by an understanding of Man for this to be enough.

The atheist is then faced then with a problem.  In a naturalistic worldview, the physical world is all that there is and the scientific method is the sole means of understanding truth.  How then can they answer the questions of origin, meaning, and destiny?  They can’t.  What a pity.

And for this reason, a worldview built around the existence of a deity, has not only always been with us, but will continue to remain the populist belief of nations everywhere.

So who then is God and what can we know about him?  I could try my hand at giving an answer, but it has been done before and with better diction that I could muster.  Here is the answer, as giving by the Westminster Catechism. 

What is God? 

Answer: God is a Spirit, in and of himself infinite in being, glory, blessedness, and perfection; all-sufficient, eternal, unchangeable, incomprehensible, everywhere present, almighty, knowing all things, most wise, most holy, most just, most merciful and gracious, long-suffering, and abundant in goodness and truth.

Are there more Gods than one?

Answer: There is but one only, the living and true God.

How many persons are there in the Godhead?

Answer: There are three persons in the Godhead, the Father, the Son, and the Holy Ghost; and these three are one true, eternal God, the same in substance, equal in power and glory; although distinguished by their personal properties.

That in essence is the Christian understanding of the nature of God.  Do I understand how God is one, yet be composed of three persons?  No I do not.  But I believe it.  

Especially at this time of year when we celebrate the birth of Jesus, this view of the Godhead is essential for the proper understanding of what took place in a stable, in Bethlehem, so long ago.

So I will rejoice this Christmas, for Christ the Saviour is born!

Tuesday, November 30, 2010

Renewing my mind

And do not be conformed to this world, but be transformed by the renewing of your mind … Romans 12:2

I mentioned a while ago that my Pastor has chosen this verse and specifically the idea of transformation to be the key theme for this ministry year (Sept. to Sept.).  

To say that this theme resonated with me would not tell the whole story for when I starting this blog at the beginning of August, I felt at the time that I needed to undertake some spiritual disciplines in order to deepen my understanding of, my appreciation for, and my devotion to my faith.

Using some of the ideas found in holy scripture, I liken this undertaking to “retuning to my first love”, to “restoring the joy of my salvation”, and to the process of “working out my salvation with fear and trembling.”

Paul the apostle writes in his letters that the Christian life can be likened to a race that is meant to be run.  Now running has never been a strength of mine, give me a bicycle and I can ride for hours, but lace up some running shoes and I am panting by the first corner.  So I have to ask myself from a spiritual perspective how well am I running? 

The honest truth is that I stopped running a long time ago.  Don’t misunderstand me, I don’t mean to imply that I have abandoned the race, only that I stopped running at the first sign of cramps and I have been content to walk most of the way.  Oh every now and then I get encouraged to sprint a short distance, but inevitably I end up walking again.

The bible says “they that wait upon the Lord, renew their strength.”  Well to be frank it is a lot easier to just stop running when I am tired than it is to wait upon the Lord for strength.

So here I am today almost 4 months into the journey and what progress have I made?  To be honest I am probably moving at a swift walk.  If you have ever watched Olympic speed walking, you can envision how I see myself.  I am moving faster than I was four months ago, but my gait doesn’t look or feel natural and I am certainly not running with intensity.

Practically speaking I have regained consistency with respect to the reading of my bible.  On the prayer front however I only average one or two mornings a week of extended prayer.  This is an area I need to address.  I started out strong, praying 3-4 days a week back in August / Sept but then it slowly  got pushed aside for the pleasure of extra sleep.

I want to mention something else that I have done specific to the idea of renewing my mind.  A couple of weeks ago I attended with my dad a training day for “The Truth Project”  I was thoroughly impressed with this series of teachings designed specifically for the purpose of re-establishing a Christian worldview “within” the church. 

Turns out that most Christians don’t actually have have a Christian worldview.  They may understand who Jesus is and what he has done for them, but they don’t have a clue how to distinguish between the truth claims of the bible and the cultural norms that society views as sacred.  This is what a worldview is; it is a filter through which a person makes sense of the world around them.

I made reference to at least the core beliefs of my world view in a previous posting when I said the following:

1.  My nature is bent towards evil.

2.  I am hopeless to change.

3.  The human race is bent towards evil.

4.  We are hopeless to change.

Well if this is a filter through which I view the world, what ramifications does this have on the way I interpret cultural messages.  Let me give you an example.

I constantly hear that whether it is through the power of positive thinking or through mind over matter or though the latest trend that Oprah has hitched her wagon to that it is within me to achieve anything I desire.  That true happiness and peace can be achieved if only I am true to myself and I don’t let others hold me back.

Well my worldview tells me that this is a lie.

The problem with this is that it turns out my true self is not very nice.  Turns out that my true self is in conflict with God and my true self is not inclined to do the morally right thing if it is not in my best interest.  It is interesting how the world actually knows this very well and that is why self-love is almost seen as the pinnacle of human achievement.  Maslow used the term self-actualization, same thing.

My worldview tells me that only God can change my heart and give true happiness and peace.  It tells me that my old nature and its desires are detestable and that through Christ I now have a new nature with new desires which are no longer bent towards evil.

See how important a worldview is with respect to making sense of life.

So back to the task at hand, renewing my mind.  Since the training day I have been working my way through the 12 lessons.  I have made it through the first four and my desire is to begin a small group study in the new year to take other Christians through the material. 

Anyway one day at a time.

Thursday, November 11, 2010

A word of thanks

What would be worth dying for? 

Would I die for my faith?  What about my family?  Perhaps the freedoms that I enjoy and most days of the year take for granted?

I ask the question because today is Remembrance day, and on this day it does my soul good to ponder it.

No one likes to think about death, certainly not me; but if I can’t answer this question today then I am not really living the other 364 days of the year.  More specifically if there is not something that I am willing to die for, then to what end am I living?

It is really as basic as that.  Life boils down to these kind of questions that have no scientific answers.  Yet an answer is still needed and until I find it I will not know lasting peace or security.

Thankfully I know the answer.  I would be willing to die for my faith.  I would be willing to die for my family.  I would be willing to die for the freedoms I enjoy.  And today, on Remembrance day I take a moment to think about the dedicated men and women of the Canadian Forces who discovered and are continuing to discover that some things are worth dying for. 

To them I simply say thank you.

But I know that words are not enough.  As the poet said:

Take up our quarrel with the foe:
To you from failing hands we throw
The torch; be yours to hold it high.
If ye break faith with us who die
We shall not sleep, though poppies grow
In Flanders fields.

So on this day I pledge to not break faith with those who have died fighting for my freedom.  I also pledge to not treat with distain those hard won freedoms.  And furthermore I pledge to not acquiesce to the demands of those who would seek to limit those freedoms in the name of political correctness. 

Vive la Canada libre!

Monday, November 08, 2010

My struggle

Like I said in my previous post actually living in obedience to God’s word is easier said than done.  If you have never read Romans chapter 7, make sure you do.  In this chapter Paul expresses the inner turmoil that each Christian faces.  He writes:

I have discovered this principle of life—that when I want to do what is right, I inevitably do what is wrong.  I love God’s law with all my heart.  But there is another power within me that is at war with my mind. This power makes me a slave to the sin that is still within me.  Oh, what a miserable person I am! Who will free me from this life that is dominated by sin and death?  Thank God! The answer is in Jesus Christ our Lord.

Boy could I agree with that sentiment.  It is amazing how strong the desires of the flesh are.  In my spirit there is a desire to follow Christ with all of my heart, all of my soul, and all of my mind, but the flesh continues to mock me.  It taunts me by producing laziness instead of self-discipline, gluttony instead of restraint and impatience instead of perseverance.

Yet when I take time to ponder it in some measure I am thankful for this battle; for it confirms to me that I have God’s spirit abiding within me.

Furthermore if I loose a battle, I have hope in the continual work of God’s grace to pick me up, dust me off  and set me back on the straight and narrow.

Furthermore still I am confident that my faith in the future grace of God will ultimately guarantee my victory in this war!

Monday, November 01, 2010

The Favour of God

As a young child if there was one person that I desperately wanted to please it was my father.  Even today knowing that I have my father's favour gives me a high level of self-confidence that I otherwise wouldn't have.

When it comes to my heavenly Father, I won't deny that the same need exists within me.  I desperately need my heavenly Father to be pleased with me.

So what must I do to earn the favour of God?

Notice I didn't say love, I said favour.  Again just like my earthly father there is absolutely nothing I can do to earn the love of my heavenly Father.  It is unconditional and freely given.  How amazing is that!  Independent of my love towards Him, God loves me with a never ending love.

Now back to the question at hand.  How do I gain the favour of God?  What do I need to do to have God take pleasure in me?

It really is quite simple in principle, though as with most things in life, easier said than done.  I have my heavenly Father's favour when I live in obedience to his Word.  Consequently I loose his favour when I live in disobedience.

Let me diagram it for you as far as I understand it.

Favour from God is a result of obedience to God's Word, which is a result of faith in God's Word, which is a result of hearing God's Word

So through hearing God’s Word I came to faith in Jesus.

Now by obeying God’s Word I can receive God's favour on my life.

Saturday, October 23, 2010

And that’s a wrap

After spending the entire day Thursday implementing the scuba computer, we found out Friday morning that the use of a real-time operating system (RTOS) to implement it was overkill.

I shouldn’t really be surprised; at my work I have worked on projects of much greater complexity without needing an RTOS.  The reality is, is that there is a continuum between hard real-time and soft real-time, along which most embedded systems fall, and using an RTOS may bring more disadvantages than advantages. 

Specifically when you have a priority scheme allowing a high priority task to snatch the processor away from a lower priority task it leads to a number of complicated problems regarding sharing the processor’s resources.  If a low priority task is using the serial port for example, and a high priority task takes over and wants to use the serial port, it could lead to corruption of the serial port data.  Tasks need to play nice and share the processors peripherals in a manor that won’t lead to corruption, while at the same time ensuring that the high priority tasks meet their time constraints. 

Now these problems have all been addressed in the design of modern RTOS’s but these solutions are not free, they require processor time, resulting in a lot of overhead that simply isn’t required if an RTOS is not used.

So Friday’s lecture was about RTOS alternatives, and it turns out that there are quite a few.  Specifically we talked about the following:

  1. Big loop + interrupt systems
  2. Cyclic executive systems
  3. Co-routine systems
  4. Proto-thread systems
  5. Function Queue systems
  6. State-machine systems

I don’t have time to touch on them here but from my perspective I have used 1, 5 and 6 to some extent.

State-machine programming is the topic that I want to discuss today, because more than all of the others it really is an entirely different programming paradigm.

What I mean by a paradigm is both the style of programming used, and subsequently the thought processes used to break down a problem.

There are many different programming paradigms, the most common being:  procedural, functional, parallel, and object-oriented.

Traditional embedded programming is entirely procedural with some parallel programming concept thrown in when using an RTOS.

State-machine programming is something a little different.  In has a correlation with the desktop world where it goes by the name of event-driven programming.  For example in Windows if you are writing an application you might draw a nice little button using the graphical tools Windows supplies and then you program the code to handle all the possible events that might happen to that button.  Specifically you would tell the computer what to do if a user clicked on the button.

In the embedded world you can design a system in a somewhat similar way.  Using our scuba computer as an example we could define some states that our system might be in.  They might be:

  • At the surface with no oxygen
  • At the surface with oxygen
  • Decending  with sufficient oxygen to reach the surface
  • Ascending with sufficient oxygen to reach the surface
  • Decending  without sufficient oxygen to reach the surface
  • Ascending without sufficient oxygen to reach the surface
  • Below the surface at a depth of greater than 40m
  • Ascending faster than 15m per minute

These are the system states.  We then also would define the possible events that could occur.  Some may be:

  • Oxygen is added.
  • Oxygen is depleted
  • Ascending
  • Descending

We then program the system to change state depending on each event that might occur.  For example if we are in the “at the surface with no oxygen” state and then oxygen is added, our new state would be at the surface with oxygen.  If instead the “descending” event occurred without adding oxygen, our state would be “descending without sufficing oxygen to reach the surface”.  Also not all events would be handled by each state.  If we are at the surface we would simply ignore the ascending event.  Also some events might just keep us in the current state.  If we are descending, a descending event wouldn’t change our state unless at the same time we ran low on oxygen or we exceeded the maximum depth.

It might not be immediately obvious to the non-programmer, but this way of thinking about a system is very different from the usual procedural way of thinking, when we instruct the computer to first do one then then do another.  Now the program literally does nothing until an event triggers it to do something.  Then with each event we might do something as we leave a state, do something as we transition between states and then maybe do something upon entering a new state.  Once this was done we then sit and spin in the new state doing nothing but waiting for the next event.  To my mind this is a fascinating way to look at a whole set of problems that I face day in and day out as an embedded programmer.

I wasn’t unfamiliar with these techniques before the course, but certainly now having had them refreshed I feed much more capable as an embedded programmer and ready to tackle the next problem that my employer sends my way.

Thursday, October 21, 2010

Coming up for air

Well that was fun.

Today we had no lecture, instead the entire day was devoted to a team project.  Specifically we designed and implemented the software for a scuba diving computer.  Something that would look like this.

dive computer

Our hardware actually looked like this, but the functionality was much the same.

board

We worked in teams of 4 to develop the software required to do the following.

1 - Show ascent-rate, depth, oxygen remaining, elapsed dive time and time to surface on the display.

2 - Sound one of three alarms.

  • High priority alarm if there is not enough oxygen in the tanks to reach the surface.
  • Medium priority alarm if the rate of ascent is greater than 15 meters per minute (prevents getting the bends).
  • Low priority alarm if your depth is greater than 40 meters.

3 – Toggle the display between showing the elapsed time, and the time to surface every 2 seconds.

This is why I love being an engineer; you get to build really cool things.  As an aside our team was the only one to finish the project.  We finished it 5 minutes before the deadline.  Whew…

To complete the project our design used 8 tasks.

  • LED driver task
  • Pushbutton driver task
  • Speaker driver task
  • Analog to digital converter driver task
  • Calculation task
  • Display task
  • Alarm task
  • Watchdog monitoring task

As a point of interest I have included below some of the code that I worked on today which did the calculations for the displayed values.  Probably not the most elegant code since we were under a time constraint, but it shows the proper use of several forms of inter-task communication.  Enjoy.

/***********************************************************
DIVE COMPUTER CALCULATION TASK
***********************************************************/
void AppTaskCalc(void * pdata)
{
   INT16S         rate_of_ascent_in_mpm = 0;
   INT16U         elapsed_time_in_s = 0;
   INT32S         depth_in_mm = 0;
   INT32S         air_supply_in_cl = 0;
   OS_FLAGS       flags;
   INT8U          err;
   INT16U         sample;
   INT16U         tick_counter = 0;
   INT16U         air_to_surface_in_cl;
   INT32U         alarm_curr = GF_ALARM_OFF;
   INT8U          at_surface = 1;

   static display_data_t display_data = {0,0,0,0,0}; 

   while(1)
   {
      flags = OSFlagPend(gh_sys_flags, GF_TIME_CALC |
              GF_BUTTON_AIR, OS_FLAG_WAIT_SET_ANY |
              OS_FLAG_CONSUME, 0, &err);
      assert(OS_NO_ERR == err);   
     
      if (flags & GF_TIME_CALC)
      {
         tick_counter++;
         // Pend on the A2D mailbox
         sample = (*(INT16U *) OSMboxPend(ghMboxAdc,
                                          10, &err));
         assert(OS_NO_ERR == err || OS_TIMEOUT == err);
        
         // Calculate the rate of ascent
         rate_of_ascent_in_mpm = sample - 511;
         rate_of_ascent_in_mpm /= 13;
         depth_in_mm -= depth_change_in_mm(
                                  rate_of_ascent_in_mpm);
         if(depth_in_mm <= 0)
         {
            depth_in_mm = 0;
            at_surface = 1;
         }

         // Calculate the elapsed time if depth is not 0
         if (depth_in_mm != 0)
         {
            if (at_surface == 1)
            {
               at_surface = 0;
               elapsed_time_in_s = 0;
            }
            if(tick_counter & 0x01)
            {
               // Every other .5s tick increment
               //   the elapsed time
               elapsed_time_in_s++;
            }
         }

         if(at_surface == 0)
         {
            air_supply_in_cl -= gas_rate_in_cl(
                                   depth_in_mm / 1000);
            if(air_supply_in_cl < 0)
            {
               air_supply_in_cl = 0;
            }
         }
         air_to_surface_in_cl = gas_to_surface_in_l(
                                   depth_in_mm / 1000);
         // Update display_data struct
         if(at_surface == 1)
         {
            display_data.rate_of_ascent_in_mpm = 0;
         }
         else
         {
            display_data.rate_of_ascent_in_mpm =
                                      rate_of_ascent_in_mpm;
         }
         display_data.depth_in_m = depth_in_mm / 1000;
         display_data.air_supply_in_cl = air_supply_in_cl;
         display_data.elapsed_time_in_s = elapsed_time_in_s;
        
         // Maximum ascent rate is 0.25m / s
         display_data.time_to_surface_in_s =
                          display_data.depth_in_m * 4;

         err = OSMboxPost(ghMboxCalc, &display_data);
         assert(OS_NO_ERR == err);
        
         OSFlagPost(gh_sys_flags, GF_MBOX_DISP,
                                        OS_FLAG_SET, &err);
         assert(OS_NO_ERR == err);
        
         // Set current alarm state.
         if(at_surface == 1)
         {
            alarm_curr = GF_ALARM_OFF;
         }
         else if (air_supply_in_cl < air_to_surface_in_cl)
         {
            alarm_curr = GF_ALARM_HI;
         }
         else if (15 < rate_of_ascent_in_mpm)
         {
            alarm_curr = GF_ALARM_MID;
         }
         else if (40 < (depth_in_mm / 1000))
         {
            alarm_curr = GF_ALARM_LOW;
         }
         else
         {
            alarm_curr = GF_ALARM_OFF;
         }

         // Signal change of speaker priority to the alarm
         OSFlagPost(gh_sys_flags, alarm_curr,
                                      OS_FLAG_SET, &err);
         assert(OS_NO_ERR == err);
      }
     
      if (flags & GF_BUTTON_AIR)
      {
         // Increment the air count at 5L per semaphore
         do
         {
            // Wait for a signal from the button driver
            OSSemPend(ghSemB1, 10, &err);
            assert(OS_NO_ERR == err || OS_TIMEOUT == err);
            if ((OS_NO_ERR == err) && (at_surface == 1))
            {
               if (air_supply_in_cl <= 199500)
               {
                  air_supply_in_cl += 500;
               }
               else if (air_supply_in_cl < 200000)
               {
                  air_supply_in_cl = 200000;
               }
            }
         }while (OS_NO_ERR == err);
      }
      // tell watchdog we are alive
      OSFlagPost(gh_sys_flags, GF_ALIVE_CALC,
                                       OS_FLAG_SET, &err);
      assert(OS_NO_ERR == err);     
   }
}