The halcompile docs are pretty good.
linuxcnc.org/docs/devel/html/hal/comp.html
But then duck over to git and have a look at the source for some of the core components (like and2) in this folder for inspiration. You learn so much just reading code.
github.com/LinuxCNC/linuxcnc/tree/master/src/hal/components
Copy one of these and use it as a template to write your own component. Thats how I do it!
Just ignore all the documentation stuff at the beginning. They are processed to make the man pages.
You just have to remember that the servo thread is a timer interrupt service loop that fires every millisecond and every hal component has to be serviced in that millisecond or following errors will occur. So a component needs to short sharp and sweet! Do not use any for or while loops. You do not need to use them as you can simply loop using the servo loop (eg increment a variable this time round and increment it again the next invocation until you get the result you want!.
You will also need to understand variable scope, eg. global variables, and static variables. Basically, global variables above the function keep their value between loops. variables in the function are created on every call so there is no memory of its value unless it is defined as a static variable.
Often you need to do something on the first pass through a component to set some values or something. I usually do it something like this:
Code:
static int first_pass = 1;
if first_pass{
// do some configuration stuff
first_pass = 0;
}
Or you want to save a value so you can use it next time (which may also require some config on the first pass.
Code:
static int last_value;
int this_value = my_hal_pin;
int delta = this_value - last_value;
// do some stuff
//At the end, save this value to be last value
last_value = this_value;
The other useful construct is a state machine. State machines have several steps that they will pass through and you can use a switch() statement to work though each step. once step 1 is satisfied, set a variable to the next step and so on and then the last state sets it back to the first state.
plasmac.comp has a lot of states defined from line 266 as an ENUM. The state machine begins on line 609 with
Code:
switch(state){
case IDLE:
and through the code you will see references to the state like
And at the end of that section, the next state is set
So the next pass through the process, execution will commence at
Mind you Plasmac is not a stellar example of the short sharp sweet components I started with but careful use of states allows this 1800 line component work perfectly! It would be possible to break it up into smaller components at the expense of greater complexity in the hal file. If you look at the core components, they are often just a couple of lines or < 10 lines.
Anyway, that should get you going.