Showing posts with label Work. Show all posts
Showing posts with label Work. Show all posts

Jan 1, 2011

State Machine for embedded systems

This is a bit of a trip in the way-back machine for me. I programmed a bunch of embedded off-highway vehicle controllers using C back in the day.

Most of these systems were based on finite state machines. The goal of the programmer is to contain the machine behaviour into a finite set of behaviours based on state history and present inputs.

The hardest part was tracking down bugs which essentially turned Finite State Machines into Infinite State Machines. Global state variables and monolithic switch statements are notoriously easy to turn into spaghetti this way.

The best implementation for state machine I've seen was handed to me for maintenance when I was a junior. I remember it was wicked hard to understand at first. I gummed my first one up because I did not understand all the beauty that it brought.

Once you get over an innate fear of function pointers, it really is a great and simple state machine implementation. BTW, function pointers used this way are much safer than data pointers because the function pointers are never assigned and cannot be null.

Break this thing into several files when your state machine grows.

// I know this first include isn't very embedded. I need it for Sleeping
#include "windows.h"
#include "stdio.h"

// Declare typedefs for state conditions and actions
typedef unsigned char (*ConditionFunction)(void);
typedef void (*ActionFunction)(void);

// The structure defines an action, a condition and a transition
// If the condition is met, the action is executed and the transition occurs
typedef struct _tagState {
 ConditionFunction Condition;
 ActionFunction Action;
 struct _tagState *nextState;
} StateItem;

// Some sample conditions 
unsigned char falseCondition(void) 
{ return 0; }
unsigned char trueCondition(void)
{ return 1; }

// Some sample actions
void SomeAction(void) 
{ printf ("SomeAction\n"); }

void BootAction (void) 
{ printf ("BootAction\n"); }

void NoAction (void) 
{ printf ("NoAction\n"); }

// The state machine engine.
// Simplicity is bliss
StateItem* ProcessState(StateItem *si) {
 while(1) 
 {
  if(si->Condition() == 0)
  {
   si++;
  }
  else
  {
   si->Action();  
   return si->nextState;
  }
 }
}

// Forward declare states so jumping is unhampered
const StateItem OtherState[];
const StateItem BootState[];

/*
*  The tables represent states, each line is a state item
*  Generally, the last state item performs a state action, 
*  and jumps back to itself. Preceeding items are generally
*  transitions out to other states based on conditions
*/

// Except boot, end all the states with a trueCondition and a jump back to self
const StateItem OtherState[] = {
 {&falseCondition, &SomeAction,  OtherState},
 {&trueCondition, &NoAction,   OtherState}
};


const StateItem BootState[] = {
 {&falseCondition, &SomeAction,  BootState},
 {&trueCondition, &BootAction,  OtherState}
};

// Main just runs the state machine (no inputs or outputs are processed)
// The 'tick' time is 1 second which is slow for an embedded system
// but good for demonstrations
int main(void)
{
 StateItem *StatePtr = BootState;

 while (1) {
  StatePtr = ProcessState(StatePtr);
  Sleep(1000);
 }
  
 return 0;
}

Dec 10, 2010

Prepare to Program Series I

Doing a system upgrade.  Waiting for the previous versions to uninstall.

The first key to writing guud software is getting a proper sit going. You have to be comfortable if you're sitting at the terminal for 12-18 hours per day doing what you love. Some days I want to mount my keyboard and monitors above my bed so I can get a real guud sit going.


I don't because I think that might be crossing a line into domestic impropriety.

I love to write software especially when creating something new (fixing bugs is a regrettable but necessary exercise). But nothing gets in the way like an uncomfortable work zone. Take your home computer workstation (if you have one). Could you sit there all day?

I feel highly misunderstood when I get into a real good comfortable spot that feels just right. I'm often nearly laying down in my chair. I have my head back, looking down my nose at the monitors. Were it not for my fingers moving, you'd think I was sleeping with my eyes open.

Inevitably, not recognizing that I am in fact in the programmers zone, interrupts with - "are we keeping you awake". I like to respond - "you are now".

Dec 4, 2010

Continuous Integration

When I was a developer at a small company that sold products which happened to include software we did a lot of things different. The main reason for this is that software was a part of what we were producing, but not the main part. Elevators, electric dune buggies, CNC machines all have significant non-software development components.


The delta's show in how much attention is paid to the processes surrounding the development of each component. For example, one of our favourite ways to test software that was developed for CNC machines was to load the software onto a CNC machine and press buttons and use any new software that was implemented. The goal was to test the software for correctness and bugs. To us, this was a reasonable facsimile to a production environment.

I now work on a large team of software developers who are professionals at producing software. It's very time consuming or even impossible to test new software IRL because the production environment is not easily simulated. Continuous integration and unit testing allows me to develop software and be reasonably secure how it will perform in the field without having to 'press the buttons'.

Of course, running unit tests is not foreign to the previous shops in which I've practiced my craft. The problem with unit tests was almost always the same. The tests would be run during the development of a feature, then never used again. Instead, they might never see the inside of a version control system. They would be lost on next computer upgrade. It was hard to justify so much time writing unit tests that would only be used to aid the developer implement.

With Continuous Integration, it's different. The build and integrate process is continuous (imagine that). Each build is done on a dedicated system. All unit tests are automatically run and if everything goes ok, the build is deployed to testing fixtures which run continuously.

This process makes it more difficult for new code to break old code (as long as it's adequately tested). I wish I knew that before I wasted all those hours tracking down bugs by trying to manually set them up over and over with the user interface.

Nov 3, 2010

Solving Problems

There's nothing like the sense of accomplishment you get from solving a problem. When you're new, it's frequent that you get to solve problems. Well, maybe that's inaccurate everything you touch is a problem because you've never seen it before, you haven't learned enough yet.

Scratch, scratch, scratch your head sometimes for hours or days. Then, you get it. You've learned just enough to solve the problem and you feel accomplishment because:
  1. You solved a problem
  2. You learned something
Makes for a good day.

Nov 1, 2010

Tooting Your Horn

Software Developers are notorious introverts. There are very few who love to tell the world how good they really are at things. I'm improving, but it's not my default demeanor. It makes me uncomfortable to take credit, or to announce when I do something well. Sidebar - I'm very practiced at taking blame. I do it pretty smoothly.

People making hiring decisions, handing out assignments and deciding who's next to run the group are usually looking for great people to do those jobs. The greater the better. They are going to take the greatest one they can get (most of the time).

If they have to interrogate you to find out your level of greatness, they might take a pass. After all, the next guy in line is making it easy to find out how great he is. You don't want to bludgeon anyone over the head with self-serving arrogance, but it shouldn't be a secret either.

I try to make it part of my day to do something great, something unexpected, better than expected. The next step I have to master is making sure the right people find out about it.

Oct 29, 2010

Favorite Workplace Quote

I heard a quote from a friend of mine the other day. Not sure who originated it. Maybe his boss, maybe it's someone famous and this is a well known one.
They keep fuckin' it up, so we have to fuck it back down

Besides being hilarious maxim it's an organizational imperative that no matter who fucked it up, in the end, it has to be fucked back down.

The Hump

It's easy to go in early and home late when things are going your way. You're learning, your producing, progress is made. It's exactly the opposite that makes you a winner. Go in early and home late when things aren't the greatest. You should be there figuring out how to change it.

Oct 27, 2010

Fiefdoms And Their Leaders

Seems like there's a natural tendency in workplaces to cloister, close, confine, protect. That's the default mode for many workers, their supervisors and management. I like to think of this as a little medieval fiefdoms that are carved out of an organization. I think the idea is that you want to keep solitary that which makes you unique and at the same time control how the organization judges you and your fiefdom (sometimes fiefdoms are single person entities).

When you get good at something, it's natural to try and protect what you know and use it to your full advantage. For a worker, I think the attitude is a little forgivable. Their job is not to maximize department output, decrease inefficiency, increase output. But what about managers that have this attitude? Sometimes managers are just longer term employees that got promoted up. I guess it's possible for them to bring their attitudes with them into the more senior roles.

The leaders are also not beyond the scrutiny of their managers in turn. So if a persons natural tendency is to spin, massage, or deflect the information used to judge their performance, likewise they will protect their departments or divisions in the same way.

The problem is that in this environment, creativity is stifled, fear is at maximum warp factor, mistakes are not forgiven, so everyone is really wearing professional handcuffs. The mantra - in the fiefdom, there is safety, let's all retreat to the fiefdom.

Wouldn't it be great if there was a way to change attitudes instantly from petty fief to benevolent and potent leader? Well, there isn't one; stop dreaming. It's hard work to change your attitude. A daily grind fighting your own worst enemy. But you have to do it if you want to get off the fiefdom and do something fulfilling.

Be Generous

My favourite blog is Seth Godin. He's marvelously insightful and often when I read his blog I think he's writing a letter directly to me.

One of my favourite sethisms is that you should be generous with your ideas and knowledge. You should be giving that away for free. It does no good to pinch every piece of information you have with both hands hoping to hold on to it and through that, make yourself indispensable.

That's not how indispensable works.

The great thing about generous is that once you've done something once, you tell others, then they can do it, and you can figure out something new. That's the part of working that I love. The new and exciting, not the brainless and repetitive.

Make the Switch

I spent 8 years developing software at small startups. Mostly embedded software, sometimes Windows tools for the embedded systems. About 2 years ago I switched to a big company that makes big software for big healthcare clients.

It was a huge change in daily routine.

Firstly, I went from being one of two developers on a project to being one of more than a dozen.

Secondly,  I went from being a senior guy who pushed the development agenda, and was confident about what I was creating to being a meek churchmouse. Although, this is probably more related to the big change from embedded to Windows/Unix world.

Thirdly, I found out, when there's that many people working on a project, everyone has a different agenda. More accurately, as the number of people involved in a project goes up, the chances of everyone getting along goes down.

I found it shocking when not everyone worked at creating art in their work. Some people couldn't wait to go home at the end of the day. This was so different from the world I came from, and the world that I wanted to bring to my new big company.

The truth is, they're everywhere. But don't let them get you down (they're going to try their hardest).