Go Down

Topic: Is there a way to `fork` a task? (Read 1 time) previous topic - next topic

czaralex

Jul 02, 2008, 09:03 pm Last Edit: Jul 02, 2008, 09:04 pm by czaralex Reason: 1
First, I may not have the proper term here. I'm used to MOO code (..huh?).

I'd like to take one task and have it run parallel to another so both are running at the same time. There's a few threads here about LEDs doing things simultaneously and this is along those lines, but I feel if I learn it this way, I may be able to apply it to other aspects of my future projects.

So, let's say I wanted to have one LED fade in while multiple other LEDs flicker and dance around. Can I fork the fading process and have the code move on to the dancing lights process while the code for the fading is being executed?

roypardi

Quote

So, let's say I wanted to have one LED fade in while multiple other LEDs flicker and dance around. Can I fork the fading process and have the code move on to the dancing lights process while the code for the fading is being executed?



Both the tasks you want to accomplish occur over time so if you think about breaking things down into steps you can have many tasks going on at the same time. Something like:

Code: [Select]


void loop(){
  doFade();
  doDance();
}

void doFade(){
//code to fade the LED(s) up by some step until they reach
//a certain limit you define; then start fading down (if that's what you want)

}

void doDance(){
// code to control other LEDs

}


Both those routines will be called many times per second so you probably want some timing code in there so that the results can actually be seen. You wouldn't want delay(n) since that will stop everything. You want something more like

Code: [Select]
if (millis() > updateTime){
 //do some stuff, then redefine updateTime
  updateTime = millis() + 50;
}


That would give you a 50 millisecond delay between "steps" without locking up the mc.

melka

In fact, those nice ATmega168 are not multitask chips (neither is an Intel processor or whatever ^^)
The multitasking is done by software, so you need to think in chunks of time. You can't have 2 functions running at the same exact time, but you can delay them by a millisecond, for exemple.
In case of Leds, we use the Persistence of vision of the human eye, so that even if you light only one led at a time, if you do it fast enough, every leds will "seem" to be on to our slow eye.
I don't know what you want to do, but maybe the fact that a human brain can't process something as fast as you can make it happen will help you. Maybe if you want to move two motors on opposite direction and want it to happen "at the same time" can be done by moving bit by bit, and switching continuously between each motor. See what I mean ? ^^

czaralex

Thanks folks, it makes perfect sense!

Go Up