The PIC18F4550 has 4 independent hardware timers, but depending on system clock frequency they may not all be able to time a full second. Anyway you actually only need 1 timer. The problem then becomes 'how can I share 1 timer between 4 tasks?'.
The next question is 'how can the PIC perform several tasks in parallel?'. The CPU can only execute 1 instruction at a time, so to multitask it has to do the same thing a human would - a bit of one task, a bit of the next etc. in a loop so that they all get an equal share of its time.
The timer can also be shared between tasks the same way you would if you only had a single clock to read. There are several ways to do this:-
- Set up the timer to overflow at a high rate, eg. 50 times per second (20ms period). Now give each task its own counter which is incremented on every timer overflow 'tick'. When a cell is inserted, turn on the power and reset its counter to zero. When the counter reaches 50, turn off the power etc.
The timer overflow could be captured in an interrupt which then increments each task counter (and reloads the timer if necessary), or you could simply poll the timer and wait for it to overflow at the start of the multitasking loop. Using interrupts may be more accurate if you need to reload the timer to get the required 'tick' time, but you must remember that as far as each task is concerned its counter could change at any time.
- Set up the timer so it overflows much slower than 1 second. When a cell is inserted the task reads the current time and stores it. On subsequent reads it subtracts the stored time from the current time, and when the difference reaches 1 second it turns the power off etc.
But what about if the timer overflows between reads? Then the task does what you would do with a 12 hour wall clock - if the result of the subtraction is negative then add the time it takes for the timer to overflow (same as you would add 12 hours to the wall clock time).
- Set the timer to overflow once per second, and execute each task at the same rate. When a task detects that a cell has been inserted it turns the power on - unless it is already on, in which case it turns the power off etc.
Of course a cell might be inserted at any time within the 1 second period, so the initial charging time will be a random period of less than 1 second. However each subsequent charge period will be locked into the 1 second cycle. Since NiMH cells take a long time to charge this shouldn't be a problem (I have a commercial 4 cell charger that uses this technique - it works perfectly!).